From 7b2b919f41ed54efc05198b5757824cb40584449 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:34:55 -0800 Subject: [PATCH 01/42] Print: Print as Bitmap prints at advanced.bitmapResolution advanced.bitmapResolution sets the resolution Print as Bitmap renders a composite page at, in a print-ready PDF and in PostScript. 0, the default, keeps the document's raster effects resolution; 1 to 9600 ppi is VectorCraft's own range, and print.setup, print.preview and file.print refuse any other value. Given in file.print's settings it applies to that job only; print.setup saves it with the document. The Print dialog's Advanced section sets it under Resolution. When the pixel limits (64 million pixels, 32,768 a side) keep a page's image below the requested resolution, file.print and print.preview warn with the resolution it prints at. A page that prints no image gets no warning. A script's PrintJobOptions.bitmapResolution now maps to it instead of throwing. --- crates/engine/src/cmd/print.rs | 15 +- crates/engine/src/cmd/printadvanced.rs | 87 +++++++++-- crates/engine/src/script/dom/print.rs | 8 +- crates/engine/src/tests/printadvanced.rs | 173 ++++++++++++++++++++++ crates/engine/src/tests/script_print.rs | 62 ++++++++ crates/pdf/src/print.rs | 5 + crates/pdf/src/print/layout.rs | 2 +- crates/pdf/src/print/settings.rs | 19 ++- crates/ui-egui/src/dialogs/print.rs | 14 +- crates/ui-egui/src/dialogs/tests_print.rs | 33 +++++ docs/mcp.md | 25 ++-- docs/target-app-parity.md | 1 + 12 files changed, 416 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 8c507db007..68ad2acd6f 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Print Setup", [], None, - "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", + "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at bitmapResolution, or lower for a page larger than 64 Mpx or 32,768 px a side, with a warning when bitmapResolution was given), bitmapResolution: 0 (ppi Print as Bitmap renders at, 1–9600; 0: the document's raster effects resolution; other output leaves it unused), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", has_doc, setup ), @@ -138,6 +138,12 @@ fn preview(s: &mut Session, p: &Value) -> Result { let set = preset_or_saved(C, s, doc, p)?; super::printadvanced::flattener(C, &set, &s.prefs.flattener_presets)?; let mut pv = vectorcraft_pdf::preview(doc, &set).map_err(|e| pdf_error(C, e))?; + if set.advanced.print_as_bitmap && set.advanced.bitmap_resolution > 0.0 { + // Print as Bitmap renders placed documents' art and the artboards' background colors too. + let (full, _) = super::place::document::full_documents(doc); + let filled = super::fileio::with_artboard_fills(&full, p, 0..full.artboards.len()).map_err(|e| bad(C, e))?; + pv.setting_notes.extend(super::printadvanced::bitmap_notes(C, &filled, &set)?); + } pv.warnings.extend(type_warnings(doc, set.print_layers, &areas(&pv))); // What the job loses comes first, then the notes on the options. let settings = std::mem::take(&mut pv.setting_notes); @@ -245,7 +251,9 @@ fn print(s: &mut Session, p: &Value) -> Result { && super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)? .is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o)); // 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 mut bitmap_notes = vec![]; + let prepared = + super::printadvanced::prepare_noting(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich", &mut bitmap_notes)?; let path = str_param(p, "path"); // The type is read before raster effects and Print as Bitmap turn it into images. let which = set.print_layers; @@ -258,6 +266,7 @@ fn print(s: &mut Session, p: &Value) -> Result { // What the job loses comes first, then the notes on the options. r.warnings.extend(typed); r.warnings.extend(r.setting_notes); + r.warnings.extend(bitmap_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()) { @@ -268,7 +277,7 @@ fn print(s: &mut Session, p: &Value) -> Result { 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![]); + let (mut warnings, mut setting_notes) = (vec![], bitmap_notes); if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) { warnings.push("transparency is flattened into opaque art and images (PostScript has none): see flattenerPreset".to_string()); } diff --git a/crates/engine/src/cmd/printadvanced.rs b/crates/engine/src/cmd/printadvanced.rs index 8e1c3f5be8..5eaa5beb51 100644 --- a/crates/engine/src/cmd/printadvanced.rs +++ b/crates/engine/src/cmd/printadvanced.rs @@ -1,5 +1,6 @@ //! File → Print › Advanced, what needs the renderer and the flattener (the PDF writer does the -//! rest): Print as Bitmap renders each printed region as one image, and a flattener preset +//! rest): Print as Bitmap renders each printed region as one image (at `advanced.bitmapResolution`, +//! or the document's raster effects resolution), and a flattener preset //! flattens transparency, both on the document as it prints (only the layers that print, //! overprints discarded or simulated in composite output) before it is laid out on paper. @@ -31,7 +32,21 @@ pub(crate) fn flattener(cmd: &str, set: &PrintSettings, saved: &[FlattenerPreset /// `doc` as Print as Bitmap and the flattener preset of `set` print it (from `saved` presets), or /// `None` when neither applies. Print as Bitmap is for composite output. /// `rich_black`: Appearance of Black › Printing / Exporting › Output All Blacks as Rich Black. +#[cfg(test)] pub(crate) fn prepare(cmd: &str, doc: &Document, set: &PrintSettings, saved: &[FlattenerPreset], rich_black: bool) -> Result> { + prepare_noting(cmd, doc, set, saved, rich_black, &mut vec![]) +} + +/// [`prepare`], with the note on an image Print as Bitmap prints below `advanced.bitmapResolution` +/// added to `notes`. +pub(crate) fn prepare_noting( + cmd: &str, + doc: &Document, + set: &PrintSettings, + saved: &[FlattenerPreset], + rich_black: bool, + notes: &mut Vec, +) -> Result> { let composite = set.output.mode == OutputMode::Composite; let bitmap = set.advanced.print_as_bitmap && composite; let flattener = flattener(cmd, set, saved)?; @@ -40,7 +55,9 @@ pub(crate) fn prepare(cmd: &str, doc: &Document, set: &PrintSettings, saved: &[F } let printed = vectorcraft_pdf::printed_document(doc, set); if bitmap { - return bitmap_document(cmd, &printed, set, rich_black).map(Some); + let (out, lowest) = bitmap_document(cmd, &printed, set, rich_black)?; + notes.extend(capped_note(set, lowest)); + return Ok(Some(out)); } let Some(mut o) = flattener else { return Ok(None) }; // Composite overprints that were discarded or simulated aren't preserved either. @@ -62,12 +79,62 @@ fn drop_guides(nodes: &mut Vec>) { } } +/// The resolution Print as Bitmap renders `doc` at with `set` (ppi): `advanced.bitmapResolution`, +/// or the document's raster effects resolution when that is 0. +fn bitmap_ppi(doc: &Document, set: &PrintSettings) -> f64 { + let asked = set.advanced.bitmap_resolution; + if asked > 0.0 { asked } else { doc.raster_effects_ppi } +} + +/// The pixels per point Print as Bitmap renders `area` at for `ppi`: at most MAX_PIXELS, and no +/// side longer than the renderer draws (rounded up to whole pixels when it renders). +fn bitmap_scale(area: Rect, ppi: f64) -> f64 { + let side = area.width().max(area.height()).max(1.0); + let longest = f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0; + (ppi / 72.0).min((MAX_PIXELS / (area.width() * area.height()).max(1.0)).sqrt()).min(longest / side) +} + +/// The note on Print as Bitmap printing below the `advanced.bitmapResolution` of `set`, when the +/// `lowest` resolution (ppi) an image prints at is lower. None when the job leaves the resolution +/// to the document. +fn capped_note(set: &PrintSettings, lowest: Option) -> Option { + let asked = set.advanced.bitmap_resolution; + let lowest = lowest.filter(|l| asked > 0.0 && l.is_finite() && *l < asked - 1e-6)?; + Some(format!( + "Print as Bitmap prints at {} ppi, not the {asked} ppi bitmapResolution asks for: a page prints as at most 64 million pixels and 32,768 pixels a side", + lowest.floor() + )) +} + +/// What [`prepare`] notes on Print as Bitmap for `doc` printed with `set`, without rendering it, +/// for the preview: a page with art that prints whose image the pixel limits keep below +/// `advanced.bitmapResolution`. The art is judged by its bounds, so a page holding only art that +/// draws nothing (fully transparent) is counted, while the print itself leaves its image out. +pub(crate) fn bitmap_notes(cmd: &str, doc: &Document, set: &PrintSettings) -> Result> { + let asked = set.advanced.bitmap_resolution; + if !(set.advanced.print_as_bitmap && set.output.mode == OutputMode::Composite && asked > 0.0) { + return Ok(vec![]); + } + let printed = vectorcraft_pdf::printed_document(doc, set); + let regions = vectorcraft_pdf::print_regions(&printed, set).map_err(|e| pdf_error(cmd, e))?; + let bleed = set.bleed.of(&printed); + let lowest = regions + .iter() + .map(|(_, r)| outset(*r, bleed)) + .filter(|area| vectorcraft_pdf::prints_art_in(&printed, *area)) + .map(|area| bitmap_scale(area, asked) * 72.0) + .reduce(f64::min); + Ok(capped_note(set, lowest).into_iter().collect()) +} + /// `doc` (as it prints) with its art replaced by one image of each printed region (an artboard -/// with its bleed, or all the art), at the document's raster effects resolution; regions where -/// nothing is drawn get none. -fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: bool) -> Result { +/// with its bleed, or all the art), at [`bitmap_ppi`] within [`bitmap_scale`]'s limits; regions +/// where nothing is drawn get none. Also the lowest resolution an image prints at (ppi), `None` +/// without images. +fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: bool) -> Result<(Document, Option)> { let regions = vectorcraft_pdf::print_regions(doc, set).map_err(|e| pdf_error(cmd, e))?; let bleed = set.bleed.of(doc); + let ppi = bitmap_ppi(doc, set); let mut art = doc.clone(); drop_guides(&mut art.layers); let anti_alias = if doc.raster_effects.anti_alias { AntiAlias::Art } else { AntiAlias::None }; @@ -75,13 +142,10 @@ fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: b let mut out = doc.clone(); let mut renderer = vectorcraft_render::Renderer::new(); let mut images = vec![]; + let mut lowest: Option = None; for (_, r) in regions { let area = outset(r, bleed); - // At most MAX_PIXELS, and no side longer than the renderer draws (rounded up to whole - // pixels below). - let side = area.width().max(area.height()).max(1.0); - let longest = f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0; - let scale = (doc.raster_effects_ppi / 72.0).min((MAX_PIXELS / (area.width() * area.height()).max(1.0)).sqrt()).min(longest / side); + let scale = bitmap_scale(area, ppi); if !(scale.is_finite() && scale > 0.0) { continue; } @@ -101,11 +165,12 @@ fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: b let xf = Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale); let image = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None }; images.push(Arc::new(Node::new(out.alloc_id(), NodeKind::Image(Box::new(image))))); + lowest = Some(lowest.map_or(scale * 72.0, |l| l.min(scale * 72.0))); } let mut layer = Node::layer(out.alloc_id(), "Bitmap", LayerColor::Preset(0)); if let Some(children) = layer.children_mut() { *children = images; } out.layers = vec![Arc::new(layer)]; - Ok(out) + Ok((out, lowest)) } diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index c2acec376e..ada1df29a8 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -31,6 +31,9 @@ //! - With `printAllArtboards` set to false, `artboardRange` picks the artboards; without a range //! every artboard prints. //! - With one of `horizontalScale` and `verticalScale` assigned, the other keeps the saved value. +//! - `bitmapResolution` is `file.print`'s `advanced.bitmapResolution`: 0 prints at the document's +//! raster effects resolution, and 1 to 9600 ppi at that resolution; `print` throws, before +//! anything is written, for a value between 0 and 1. //! - `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 the name of a preset (any case); when `colorManagementOptions.name` is @@ -218,7 +221,7 @@ const JOB: Class = Class { name: "PrintJobOptions", fields: &[ f("artboardRange", Kind::Text, Start::Text("1-")), - kept("bitmapResolution", Kind::Number(0.0, f64::MAX), Start::Num(0.0)), + f("bitmapResolution", Kind::Number(0.0, vectorcraft_pdf::MAX_BITMAP_RESOLUTION), Start::Num(0.0)), f("collate", Kind::Bool, Start::Bool(false)), f("copies", Kind::Whole(1, 999), Start::Num(1.0)), f( @@ -622,6 +625,9 @@ fn map_job(h: &Host, slot: usize, job: &mut Job) { "printAsBitmap" => { job.group("advanced").insert("printAsBitmap".into(), json!(flag(v))); } + "bitmapResolution" => { + job.group("advanced").insert("bitmapResolution".into(), json!(number_of(v))); + } "file" => job.file = Some(v.clone()), "artboardRange" => job.range = Some(string_of(v)).filter(|r| !r.trim().is_empty()), _ => {} diff --git a/crates/engine/src/tests/printadvanced.rs b/crates/engine/src/tests/printadvanced.rs index e183e7dfb2..454dc926f3 100644 --- a/crates/engine/src/tests/printadvanced.rs +++ b/crates/engine/src/tests/printadvanced.rs @@ -152,6 +152,179 @@ fn print_as_bitmap_prints_all_of_a_long_artboard() { assert!(b.x0 <= 0.0 && b.x1 >= 9000.0, "the image covers the artboard: {b:?}"); } +/// The images `file.print` prints with `settings`: their pixel sizes and their places on the page +/// in the print-ready PDF (read back), their pixel sizes in the PostScript file (its image +/// dictionaries, each size once), and the warnings of both. +struct Printed { + pdf: Vec<(u32, u32)>, + placed: Vec, + ps: Vec<(u32, u32)>, + warnings: Vec, +} + +fn printed_images(s: &mut Session, settings: &Value) -> Printed { + let warnings = |v: &Value| -> Vec { v["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect() }; + let v = s.execute("file.print", &json!({ "settings": settings })).unwrap(); + let back = vectorcraft_pdf::import(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap(); + let (mut pdf, mut placed) = (vec![], vec![]); + back.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + pdf.push((im.width, im.height)); + placed.push(im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)))); + } + }); + let mut all = warnings(&v); + let v = s.execute("file.print", &json!({ "settings": settings, "format": "postscript" })).unwrap(); + let ps = String::from_utf8_lossy(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).into_owned(); + let mut sizes = vec![]; + for part in ps.split("<< /ImageType ").skip(1) { + let after = |key: &str| part.split_once(key).and_then(|(_, r)| r.split_whitespace().next()).and_then(|n| n.parse::().ok()); + if let (Some(w), Some(h)) = (after("/Width "), after("/Height ")) { + sizes.push((w, h)); + } + } + sizes.sort_unstable(); + sizes.dedup(); + all.extend(warnings(&v)); + Printed { pdf, placed, ps: sizes, warnings: all } +} + +const CAPPED: &str = "Print as Bitmap prints at"; + +/// `advanced.bitmapResolution` sets how many pixels Print as Bitmap prints the art with, in a +/// print-ready PDF and in PostScript, on the same place of the page; 0 or none keeps the +/// document's raster effects resolution. +#[test] +fn bitmap_resolution_sets_the_printed_image_size() { + let (mut s, _) = session(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap(); + let mut places = vec![]; + for (ppi, size) in [(Value::Null, (200, 100)), (json!(0), (200, 100)), (json!(144), (400, 200)), (json!(36), (100, 50)), (json!(1), (3, 2))] { + let mut advanced = json!({"printAsBitmap": true}); + if !ppi.is_null() { + advanced["bitmapResolution"] = ppi.clone(); + } + let p = printed_images(&mut s, &json!({ "advanced": advanced })); + assert_eq!((p.pdf.as_slice(), p.ps.as_slice()), ([size].as_slice(), [size].as_slice()), "{ppi}"); + assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{ppi}: {:?}", p.warnings); + // At 1 ppi the image is rounded up to whole pixels past the artboard. + if ppi != json!(1) { + places.extend(p.placed); + } + } + let first = places[0]; + for r in &places { + let apart = (r.x0 - first.x0).abs() + (r.y0 - first.y0).abs() + (r.width() - first.width()).abs() + (r.height() - first.height()).abs(); + assert!(apart < 1.0, "the image covers the same part of the page: {r:?} vs {first:?}"); + } + // Art that does not print as a bitmap leaves it unused. + let p = printed_images(&mut s, &json!({"advanced": {"bitmapResolution": 144}})); + assert!(p.pdf.is_empty(), "{:?}", p.pdf); +} + +/// A `bitmapResolution` given to `file.print` applies to that job alone; `print.setup` saves it. +#[test] +fn a_bitmap_resolution_given_to_file_print_applies_to_that_job() { + let (mut s, _) = session(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap(); + let undo = s.active().unwrap().history.undo.len(); + let p = printed_images(&mut s, &json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 144}})); + assert_eq!(p.pdf, [(400, 200)]); + assert!(doc(&s).print_setup.is_none(), "the saved settings stay as they are"); + assert_eq!(doc(&s).raster_effects_ppi, 72.0, "and so does the raster effects resolution"); + assert_eq!(s.active().unwrap().history.undo.len(), undo, "printing adds no undo step"); + let v = s.execute("print.setup", &json!({"settings": {"advanced": {"printAsBitmap": true, "bitmapResolution": 144}}})).unwrap(); + assert_eq!(v["settings"]["advanced"]["bitmapResolution"], 144.0); + assert_eq!(printed_images(&mut s, &json!({})).pdf, [(400, 200)], "a job without settings prints at the saved one"); + assert_eq!(printed_images(&mut s, &json!({"advanced": {"bitmapResolution": 0}})).pdf, [(200, 100)], "0 over it: the document's"); + // A saved 0 is left out of the settings, which read it back as 0. + let v = s.execute("print.setup", &json!({"settings": {"advanced": {"bitmapResolution": 0}}})).unwrap(); + assert!(v["settings"]["advanced"].get("bitmapResolution").is_none(), "{}", v["settings"]["advanced"]); +} + +/// A `bitmapResolution` outside 0 and 1–9600 ppi, or that is not a number, is refused by +/// `print.setup`, `print.preview` and `file.print` alike, and nothing is saved. +#[test] +fn a_bitmap_resolution_out_of_range_is_refused() { + let (mut s, _) = session(); + let undo = s.active().unwrap().history.undo.len(); + for bad in [json!(0.5), json!(-1), json!(-0.001), json!(9600.5), json!(1e300), json!("high"), json!(true), json!([300])] { + let p = json!({"settings": {"advanced": {"printAsBitmap": true, "bitmapResolution": bad}}}); + for cmd in ["print.setup", "print.preview", "file.print"] { + let e = s.execute(cmd, &p).map(|v| panic!("{cmd} {bad}: {v}")).unwrap_err().to_string(); + assert!(!bad.is_number() || e.contains("advanced.bitmapResolution must be 1–9600 ppi"), "{cmd} {bad}: {e}"); + } + } + assert!(doc(&s).print_setup.is_none()); + assert_eq!(s.active().unwrap().history.undo.len(), undo); + for ok in [1.0, 9600.0] { + s.execute("print.preview", &json!({"settings": {"advanced": {"printAsBitmap": true, "bitmapResolution": ok}}})).unwrap(); + } +} + +/// A page the pixel limits print below the `bitmapResolution` asked for gets a warning that names +/// the resolution it prints at, in `file.print`'s PDF and PostScript replies and in +/// `print.preview`. +#[test] +fn a_bitmap_resolution_the_pixel_limits_lower_is_named() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 9000, "height": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 9000, "height": 2})).unwrap(); + let set = json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 600}}); + let p = printed_images(&mut s, &set); + // 32,766 pixels across 9,000 pt: 262.1 ppi. + let note = "Print as Bitmap prints at 262 ppi, not the 600 ppi bitmapResolution asks for"; + assert_eq!(p.warnings.iter().filter(|w| w.starts_with(note)).count(), 2, "{:?}", p.warnings); + let [(w, _)] = p.pdf[..] else { panic!("one image: {:?}", p.pdf) }; + assert!((32_000..=vectorcraft_render::MAX_RASTER_SIDE).contains(&w), "{w} pixels"); + assert_eq!(p.ps, p.pdf); + let pv = s.execute("print.preview", &json!({ "settings": set })).unwrap(); + assert!(pv["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with(note)), "{}", pv["warnings"]); + // A resolution that fits, the document's resolution, and output that is not a bitmap: no note. + for set in [ + json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 200}}), + json!({"advanced": {"printAsBitmap": true}}), + json!({"advanced": {"bitmapResolution": 600}}), + json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 600}, "output": {"mode": "separations"}}), + ] { + let pv = s.execute("print.preview", &json!({ "settings": set })).unwrap(); + assert!(!pv["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with(CAPPED)), "{set}: {}", pv["warnings"]); + } +} + +/// An artboard with no art prints no image, so the pixel limits a bitmap of it would meet name no +/// lower resolution, also with only art that draws nothing on it in `file.print`; once a background +/// color or art that draws is on it, they do. +#[test] +fn an_empty_artboard_does_not_name_a_lower_bitmap_resolution() { + let (mut s, _) = session(); + s.execute("artboard.new", &json!({"x": 0, "y": 500, "width": 9000, "height": 2})).unwrap(); + let set = json!({"advanced": {"printAsBitmap": true, "bitmapResolution": 600}}); + let p = printed_images(&mut s, &set); + assert_eq!(p.pdf.len(), 1, "only the artboard with art prints an image: {:?}", p.pdf); + assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{:?}", p.warnings); + let pv = s.execute("print.preview", &json!({ "settings": set })).unwrap(); + assert!(!pv["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with(CAPPED)), "{}", pv["warnings"]); + // A background color prints, in file.print and in what print.preview says alike. + s.execute("artboard.setProps", &json!({"index": 1, "color": "#336699"})).unwrap(); + let p = printed_images(&mut s, &set); + assert_eq!(p.pdf.len(), 2, "{:?}", p.pdf); + assert_eq!(p.warnings.iter().filter(|w| w.starts_with(CAPPED)).count(), 2, "{:?}", p.warnings); + let pv = s.execute("print.preview", &json!({ "settings": set })).unwrap(); + assert!(pv["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with(CAPPED)), "{}", pv["warnings"]); + s.execute("artboard.setProps", &json!({"index": 1, "color": null})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 500, "width": 9000, "height": 2})).unwrap()["id"].clone(); + // Art that draws nothing prints no image either. + s.execute("object.setProps", &json!({"ids": [id], "opacity": 0})).unwrap(); + let p = printed_images(&mut s, &set); + assert_eq!(p.pdf.len(), 1, "{:?}", p.pdf); + assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{:?}", p.warnings); + s.execute("object.setProps", &json!({"ids": [id], "opacity": 100})).unwrap(); + let p = printed_images(&mut s, &set); + assert_eq!(p.pdf.len(), 2, "{:?}", p.pdf); + assert_eq!(p.warnings.iter().filter(|w| w.starts_with(CAPPED)).count(), 2, "{:?}", p.warnings); +} + /// Appearance of Black › Printing / Exporting (#394): Print as Bitmap draws pure CMYK black as RGB /// black when `rich_black` is on. #[test] diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index 104687e0e3..533a531f70 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -272,6 +272,68 @@ fn one_assigned_scale_factor_keeps_the_saved_other() { let _ = std::fs::remove_dir_all(base); } +/// The pixel sizes of the images in the PDF at `path`. +fn image_sizes(path: &Path) -> Vec<(u32, u32)> { + let back = vectorcraft_pdf::import(&std::fs::read(path).unwrap()).unwrap(); + let mut sizes = vec![]; + back.walk(|n| { + if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { + sizes.push((im.width, im.height)); + } + }); + sizes +} + +/// `PrintJobOptions.bitmapResolution` sets the resolution Print as Bitmap prints at, as +/// `advanced.bitmapResolution` does; 0 keeps the document's raster effects resolution. +#[test] +fn bitmap_resolution_sets_the_printed_image_size() { + let base = folder("bitmap"); + let mut s = session(&base); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap(); + let saved = s.execute("print.setup", &json!({})).unwrap()["settings"].clone(); + let dir = data_folder(&mut s, &base); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(), j = o.jobOptions;\n\ + vc.log(j.bitmapResolution);\n\ + j.printAsBitmap = true; j.printAllArtboards = false; j.artboardRange = '1';\n\ + j.bitmapResolution = 144; j.file = new File({}); app.activeDocument.print(o);\n\ + j.bitmapResolution = 0; j.file = new File({}); app.activeDocument.print(o);\n\ + vc.log(j.bitmapResolution);", + quoted(&dir.join("a.pdf")), + quoted(&dir.join("b.pdf")) + ), + ); + assert_eq!(out, json!([0, 0])); + assert_eq!(image_sizes(&dir.join("a.pdf")), [(600, 400)], "a 300 by 200 pt artboard at 144 ppi"); + assert_eq!(image_sizes(&dir.join("b.pdf")), [(300, 200)], "at the raster effects resolution, 72 ppi"); + let settings = json!({"artboards": "range", "range": "1", "advanced": {"printAsBitmap": true, "bitmapResolution": 144}}); + s.execute("file.print", &json!({"settings": settings, "path": dir.join("want.pdf").to_string_lossy()})).unwrap(); + assert_eq!(image_sizes(&dir.join("want.pdf")), image_sizes(&dir.join("a.pdf")), "the same image as the command prints"); + assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved, "the saved settings stay as they are"); + let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf"))); + for (case, kind, part) in [ + ("j.bitmapResolution = 9601;", "RangeError", "bitmapResolution must be from 0 to 9600"), + ("j.bitmapResolution = -1;", "RangeError", "bitmapResolution must be from 0 to 9600"), + ("j.bitmapResolution = NaN;", "TypeError", "bitmapResolution"), + ("j.bitmapResolution = Infinity;", "TypeError", "bitmapResolution"), + ("j.bitmapResolution = '300';", "TypeError", "bitmapResolution must be a finite number"), + ( + &format!("{file} j.printAsBitmap = true; j.bitmapResolution = 0.5; app.activeDocument.print(o);"), + "", + "advanced.bitmapResolution must be 1–9600 ppi", + ), + ] { + let e = failure(&mut s, &base, &format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions; {case}")); + assert!(e.contains(kind) && e.contains(part), "{case}: {e}"); + } + assert!(!dir.join("x.pdf").exists(), "nothing printed"); + 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] diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index 6c619b3165..9ac7120565 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -443,6 +443,11 @@ pub fn print_regions(doc: &Document, set: &PrintSettings) -> Result bool { + layout::has_art(printed, r) +} + impl<'a> Job<'a> { fn new(doc: &'a Document, set: &PrintSettings, postscript: bool) -> Result { set.check()?; diff --git a/crates/pdf/src/print/layout.rs b/crates/pdf/src/print/layout.rs index 5d28e9e2b1..4ab92a7f15 100644 --- a/crates/pdf/src/print/layout.rs +++ b/crates/pdf/src/print/layout.rs @@ -96,7 +96,7 @@ fn printed(n: &Node, symbols: &SymbolBoxes, f: &mut impl FnMut(Rect)) { /// Is there art that prints in `r`? The box of a symbol instance whose art holds brushed strokes /// grows by as far as their brush art can paint ([`SymbolBoxes::with_brush_art`]). -fn has_art(doc: &Document, r: Rect) -> bool { +pub(crate) fn has_art(doc: &Document, r: Rect) -> bool { let symbols = doc.symbol_boxes().with_brush_art(); let mut any = false; for l in &doc.layers { diff --git a/crates/pdf/src/print/settings.rs b/crates/pdf/src/print/settings.rs index f6f3e5c563..dc3a039526 100644 --- a/crates/pdf/src/print/settings.rs +++ b/crates/pdf/src/print/settings.rs @@ -560,9 +560,13 @@ choice! { #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct PrintAdvanced { - /// Composite pages print as one image each of the art, at the document's raster effects - /// resolution (the app renders them before printing). + /// Composite pages print as one image each of the art, at [`Self::bitmap_resolution`] (the + /// app renders them before printing). pub print_as_bitmap: bool, + /// The resolution Print as Bitmap renders at (ppi, 1–[`MAX_BITMAP_RESOLUTION`]); 0: the + /// document's raster effects resolution. Other output leaves it unused. + #[serde(skip_serializing_if = "is_zero")] + pub bitmap_resolution: f64, pub overprints: PrintOverprints, /// The transparency flattener preset transparency is flattened with (a built-in or saved /// one, by name; the app flattens before printing). Empty: transparency prints live. @@ -583,9 +587,17 @@ pub struct TileOrigin { pub y: f64, } +/// Whether `v` is 0 (a field left at its default is not written). +fn is_zero(v: &f64) -> bool { + *v == 0.0 +} + /// Most copies of a job. pub const MAX_COPIES: u32 = 999; +/// The highest [`PrintAdvanced::bitmap_resolution`] (ppi). +pub const MAX_BITMAP_RESOLUTION: f64 = 9600.0; + impl PrintSettings { /// Refuse values out of range (ranges and tile overlap are checked against the document when /// it prints). @@ -613,6 +625,9 @@ impl PrintSettings { self.marks.check()?; self.bleed.check()?; within("graphics.flatness", self.graphics.flatness, 0.2, 100.0, "")?; + if self.advanced.bitmap_resolution != 0.0 { + within("advanced.bitmapResolution", self.advanced.bitmap_resolution, 1.0, MAX_BITMAP_RESOLUTION, " ppi")?; + } let profile = self.color.profile.trim(); if !profile.is_empty() && cms::profile(profile).is_none_or(|p| p.kind == ProfileKind::Gray) { return Err(PdfError::BadSetting(format!("color.profile: no RGB or CMYK profile is called “{profile}”"))); diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index de04998800..1f91de25e1 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -937,7 +937,19 @@ fn advanced(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { note(ui, tl!("The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed.")); let composite = choice::(d, "output.mode") != Some(OutputMode::Separations); flag(ui, d, "advanced.printAsBitmap", tl!("Print as Bitmap"), composite); - note(ui, tl!("Each page prints as one image, at the document's raster effects resolution.")); + let bitmap = composite && get(d, "advanced.printAsBitmap").as_bool() == Some(true); + row(ui, tl!("Resolution:"), |ui| { + let v = get(d, "advanced.bitmapResolution").as_f64().unwrap_or(0.0); + let name = tl!("Resolution"); + let typed = ui.add_enabled_ui(bitmap, |ui| widgets::plain_field_named(ui, "advanced.bitmapResolution", Some(name), v, " ppi", 3, 64.0)); + if let Some(x) = typed.inner { + set(d, "advanced.bitmapResolution", json!(x)); + } + }); + // 0, the default, leaves the resolution to the document. + if get(d, "advanced.bitmapResolution").as_f64().unwrap_or(0.0) == 0.0 { + note(ui, tl!("Each page prints as one image, at the document's raster effects resolution.")); + } heading(ui, tl!("Overprint and Transparency Flattener Options")); row(ui, tl!("Overprints:"), |ui| { ui.add_enabled_ui(composite, |ui| pick::(ui, d, "advanced.overprints", 160.0, |_| true)); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 00b45e0db7..0d535ee63b 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -532,3 +532,36 @@ fn a_spot_inks_icon_converts_it_to_process_and_back() { screen.run(&mut app, vec![click(keep)]); assert_eq!(dialog(&mut app).fields["output"]["inks"], json!([{"name": "Gold", "print": true, "convertToProcess": false}])); } + +/// Advanced › Resolution sets the resolution Print as Bitmap prints at: a field screen readers name +/// Resolution, dimmed until Print as Bitmap is on, printed and kept with the document by Print. +#[test] +fn the_advanced_section_sets_the_print_as_bitmap_resolution() { + let (mut app, jobs) = app(); + app.run("file.print", json!({})).unwrap(); + set(&mut app, "__section", json!("Advanced")); + let mut screen = Screen::new(); + let mut field = |app: &mut VectorcraftApp| { + screen.run(app, vec![]); + let out = screen.run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let found = nodes.iter().find(|(_, n)| n.label() == Some("Resolution") && n.role() == egui::accesskit::Role::TextInput); + found.map(|(_, n)| n.is_disabled()) + }; + assert_eq!(field(&mut app), Some(true), "dimmed with Print as Bitmap off"); + set(&mut app, "advanced", json!({"printAsBitmap": true})); + assert_eq!(field(&mut app), Some(false)); + set(&mut app, "advanced", json!({"printAsBitmap": true, "bitmapResolution": 144})); + frame(&mut app); + super::confirm(&mut app).unwrap(); + let back = vectorcraft_pdf::import(&jobs.borrow()[0].2).unwrap(); + let mut sizes = vec![]; + back.walk(|n| { + if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { + sizes.push((im.width, im.height)); + } + }); + assert_eq!(sizes, [(240, 180)], "the artboard with art, 120 × 90 pt at 144 ppi"); + let saved = app.session.active().unwrap().doc.print_setup.as_ref().unwrap(); + assert_eq!(saved["advanced"]["bitmapResolution"], json!(144.0)); +} diff --git a/docs/mcp.md b/docs/mcp.md index 9d0d1a1894..1d0babd271 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2738,9 +2738,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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 + `printAsBitmap`, `bitmapResolution` (`advanced.bitmapResolution`: 0 for the document's raster effects resolution, + or 1 to 9600 ppi; `print` throws for a value between 0 and 1) 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`). @@ -11364,16 +11365,22 @@ the placement then shows as placed by the tool, with a Reset button; dragging th ## Print advanced options The Print dialog's Advanced section and the printer profile are print settings too (`print.setup`, `print.preview`, -`file.print`): `advanced: {printAsBitmap, overprints: preserve|discard|simulate, flattenerPreset}` and `color: -{profile}`. In composite output, `preserve` writes overprinting fills and strokes with an overprinting graphics state -(`/OP`, as PDF export does), `discard` makes overprinting fills and strokes knock out and `simulate` prints them +`file.print`): `advanced: {printAsBitmap, bitmapResolution, overprints: preserve|discard|simulate, flattenerPreset}` +and `color: {profile}`. In composite output, `preserve` writes overprinting fills and strokes with an overprinting +graphics state (`/OP`, as PDF export does), `discard` makes overprinting fills and strokes knock out and `simulate` prints them as Overprint Preview shows them (darkened); either way the file has no overprint left. Separations always keep overprints. `flattenerPreset` (High Resolution, Medium Resolution, Low Resolution or a saved preset, `flattener.presets.list`) flattens transparency before printing, as Object → Flatten Transparency does; empty, a PDF keeps it live (PostScript, which has none, uses `file.print`'s `flattenerPreset`, else this one, else medium). -`printAsBitmap` prints each composite page as one image of the art at the document's raster effects resolution, -or at the highest resolution that fits when the image would be larger than 64 million pixels or longer than 32,768 -pixels a side. +`printAsBitmap` prints each composite page as one image of the art at `bitmapResolution`, or at the highest +resolution that fits when the image would be larger than 64 million pixels or longer than 32,768 pixels a side. +`bitmapResolution` is VectorCraft's own range, 1 to 9600 ppi, and 0 (the default) prints at the document's raster +effects resolution; any other value is an error. When a page prints below a `bitmapResolution` that was given, the +reply's `warnings` (and `print.preview`'s) say at what resolution; a page with no art that draws prints no image +and gets no warning (`print.preview` goes by the bounds of the art, without drawing it). Separations and pages that +do not print as a bitmap leave it unused. Given in `file.print`'s `settings`, it applies to that job only; +`print.setup` saves it with the document. (https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ lists a +job's bitmap resolution with a minimum of 0 and does not say what 0 does.) `color.profile` names an RGB or CMYK profile: composite PDF colours are converted to it with `color.intent` (CMYK colours keep their numbers with `preserveNumbers`), so a CMYK profile writes device CMYK; separations separate with a CMYK one. Settings saved before these options load with their defaults. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4102f0786e..6c1c7ab647 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2399,6 +2399,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - File Info has metadata templates: its menu saves the fields as an XMP file (Save Metadata Template…, into the Metadata Templates folder in the settings folder or anywhere), imports one with a choice of clearing the fields first, replacing the ones the template has, or appending to them (VectorCraft's own names for the three ways), lists the saved templates and opens Templates Folder; the import is one undo step (`file.info.saveTemplate`, `file.info.applyTemplate`, `file.info.templates`; `crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests/file_info.rs`, `crates/ui-egui/src/dialogs/file_info.rs`). A PDF or `.ai` also opens with the rating and author title its XMP packet gives. - `file.print`, `print.preview` and `print.setup` take a print preset by name (`preset`: `[Default]` or a saved preset, in any case): its settings are used instead of the document's, with `settings` over them, `print.setup` saves them with the document, and an unknown name is refused with the list of presets. - Print's Copies per Sheet (`copiesPerSheet`, `gutter`; off by default) prints as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, as one grid placed like a single copy; the preview shows them, and an artboard that does not fit prints one copy per sheet with a warning (#1283). + - Print as Bitmap renders at `advanced.bitmapResolution` (the Print dialog's Advanced › Resolution; VectorCraft's own range, 1 to 9600 ppi; 0, the default, keeps the document's raster effects resolution), in a print-ready PDF and in PostScript, for one job through `file.print`'s `settings` or saved by `print.setup`; a page that the pixel limits print at a lower resolution gets a warning that names it. A script's `PrintJobOptions.bitmapResolution` (https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/) sets it (`crates/engine/src/tests/printadvanced.rs`, `crates/engine/src/tests/script_print.rs`). - Place and the Links panel, Package (placed `.vectorcraft` documents packaged with their own linked files and fonts, relinked to the copies: #777), File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457). - On X11, quitting while the Paste menu's background check waits on a clipboard owner that never answers waits up to 27 s for that check to drop its clipboard handle, so the app's own handle is the last one dropped when the check drops its handle within that wait, and the app quits after the wait when it has not; the window is hidden before that wait, so an X11 window closes at once (`crates/ui-egui/src/tests/sysclip_probe.rs`, `apps/vectorcraft/src/clipboard.rs`, `apps/vectorcraft/src/quit_windows.rs`). - On Linux, quitting takes every window off screen before that wait: a native Wayland main window is unmapped (its surface gets no buffer) and stays open with the connection the Wayland clipboard uses, and the X11 windows of floating panels and documents are unmapped with the hidden main window (`apps/vectorcraft/src/quit_windows.rs`). From 048d55f1f5213f5cef26c0be64b1d5808bb28638 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:16:48 -0800 Subject: [PATCH 02/42] Scripts: print on a document from documents.index counts as a file write The script checker now treats documents.index() and app.documents.index() as chains that give a document, so print on one records file.write and filesWritten like the other document chains. --- crates/scriptcheck/src/catalog.rs | 4 +++- crates/scriptcheck/src/tests.rs | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index ad3931117a..136b01d667 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -84,7 +84,7 @@ 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`). +// `addDocumentNoUI`, `getByName`, `index`). pub(crate) const DOM_DOCUMENTS: &[&str] = &[ "activeDocument", "app.activeDocument", @@ -98,6 +98,8 @@ pub(crate) const DOM_DOCUMENTS: &[&str] = &[ "app.documents.addDocumentNoUI()", "documents.getByName()", "app.documents.getByName()", + "documents.index()", + "app.documents.index()", "app.open()", ]; diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index c833ccb540..e3c617037c 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -579,8 +579,10 @@ fn print_writes_a_file() { "app.documents.addDocument('Print', s, false).print(o);\n", "documents.addDocumentNoUI('Print').print(o);\n", "app.documents.addDocumentNoUI('Print').print(o);\n", + "documents.index(0).print(o);\n", + "app.documents.index('Untitled-1').print(o);\n", )); - let lines = &[2, 3, 5, 9, 10, 11, 12, 13, 14][..]; + let lines = &[2, 3, 5, 9, 10, 11, 12, 13, 14, 15, 16][..]; 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::>(), [("filesWritten", lines)]); } From 0830cd1695de4de16de8cd49e6d54752ff967d90 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:51:37 -0800 Subject: [PATCH 03/42] Scripts: print writes level 2 PostScript when postScriptLevel is not assigned A PrintPostScriptOptions object reads postScriptLevel as PSLEVEL2, its help page's default, but a job written to a .ps file without that property assigned sent no level to file.print, which wrote level 3. Document.print now sends level 2 for every PostScript job unless PSLEVEL3 is assigned. The print test checks the %%LanguageLevel comment of an unassigned .ps job (2) and of a job with PSLEVEL3 assigned (3). docs/mcp.md and the module notes state the default. --- crates/engine/src/script/dom/print.rs | 8 +++++--- crates/engine/src/tests/script_print.rs | 6 +++++- docs/mcp.md | 4 ++-- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index 29d09da58c..2332739c85 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -20,7 +20,8 @@ //! VectorCraft's own rules, which the help pages do not state: //! - `print` writes a file: `jobOptions.file` names it, a `File` the script may write //! ([`super::super::files`]). PostScript is written when the name ends with `.ps` or -//! `postScriptOptions.postScriptLevel` is set, a print-ready PDF otherwise. Printing to a printer +//! `postScriptOptions.postScriptLevel` is set, a print-ready PDF otherwise. The PostScript is +//! level 2 when `postScriptLevel` is not assigned, the default it reads as. Printing to a printer //! from a script is not available yet, so `print` without a file throws an error. //! - Only the properties a script assigned apply; the others keep the settings `print` starts //! from: the preset's when `printPreset` is assigned, otherwise the document's print settings @@ -850,8 +851,9 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { // The format follows the name `jobOptions.file` gives, not the real path a link leads to. let postscript = job.level.is_some() || crate::cmd::fileio::extension(path) == "ps"; p.insert("format".into(), json!(if postscript { "postscript" } else { "pdf" })); - if let Some(level) = job.level { - p.insert("level".into(), json!(level)); + // PostScript prints at the level the options read as: an unassigned `postScriptLevel` is `PSLEVEL2`. + if postscript { + p.insert("level".into(), json!(job.level.unwrap_or(2))); } let settings = job.settings(); if !settings.is_empty() { diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index a9eb84b75d..e115c60aae 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -84,6 +84,8 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() { 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\ + o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL3; j.file = new File(dir + '/level3.ps');\n\ + doc.print(o);\n\ vc.log([app.printPresetsList[0], app.PPDFileList.length]);" ), ); @@ -96,9 +98,11 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() { 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)]); + assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "a .ps name alone prints at PSLEVEL2: {}", &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)]); + let ps = std::fs::read_to_string(dir.join("level3.ps")).unwrap(); + assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 3"), "an assigned PSLEVEL3: {}", &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. diff --git a/docs/mcp.md b/docs/mcp.md index f518963b46..474f7a1897 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2761,8 +2761,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `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. Without a - file it throws `Printing to a printer is not available to scripts yet`, and `app.printerList` throws an error + assigned, a print-ready PDF otherwise, also when that name is a link to a file with another extension. The + PostScript is level 2 when `postScriptLevel` is not assigned, the default it reads as. Without a file it throws `Printing to a printer is not available to scripts yet`, and `app.printerList` throws an error that says it is not available yet. `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 a666185cc67673cb300ae50589acf999d2cdaa2b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:21:19 -0800 Subject: [PATCH 04/42] Scripts: fix print, save and export gaps found after merging main - PrintJobOptions.file reads back as a File that can be assigned again. - Document.saveAs picks the format from the supplied name before following a link, trims the trailing dots and spaces Windows ignores, and keeps the .ai, .eps and .pdf rule for a name that is only a dot and an extension. - A save or export that writes several files refuses a target that is not a regular file before any file is written, with the usual path redaction. - Document.saveAs, Document.exportFile and app.open send command warnings to the Script Console. - fitToPage = false keeps a base tiling mode and clears only a base fit. - The print scale factors take 1 to 1000 at assignment. - File and Folder keep their state in native slots, so an object made from File.prototype with a path property is refused as before, and logging, localize() and toSource() still read their own properties. - bitmapResolution declares a finite maximum, so its reflection matches. - The two new script file messages are English only. --- crates/engine/src/cmd/fileio/access.rs | 8 ++ crates/engine/src/cmd/fileio/export_names.rs | 1 + crates/engine/src/cmd/fileio/save.rs | 18 ++- crates/engine/src/cmd/recovery.rs | 1 + crates/engine/src/script/dom/print.rs | 21 ++- crates/engine/src/script/dom/save_open.rs | 73 ++++++++++- crates/engine/src/tests/save.rs | 44 +++++++ crates/engine/src/tests/script_print.rs | 97 +++++++++++++- crates/engine/src/tests/script_save_open.rs | 131 +++++++++++++++++++ crates/js/src/builtins/extensions.rs | 59 ++++++++- crates/js/src/class_ops.rs | 2 +- crates/js/src/file_classes.rs | 110 ++++++++++++++-- crates/js/src/heap.rs | 5 +- crates/js/src/host.rs | 6 +- crates/ui-egui/src/i18n/ca.tsv | 2 - crates/ui-egui/src/i18n/cs.tsv | 2 - crates/ui-egui/src/i18n/da.tsv | 2 - crates/ui-egui/src/i18n/de.tsv | 2 - crates/ui-egui/src/i18n/el.tsv | 2 - crates/ui-egui/src/i18n/es.tsv | 2 - crates/ui-egui/src/i18n/fi.tsv | 2 - crates/ui-egui/src/i18n/fr.tsv | 2 - crates/ui-egui/src/i18n/hi.tsv | 2 - crates/ui-egui/src/i18n/hu.tsv | 2 - crates/ui-egui/src/i18n/id.tsv | 2 - crates/ui-egui/src/i18n/it.tsv | 2 - crates/ui-egui/src/i18n/ja.tsv | 2 - crates/ui-egui/src/i18n/ka.tsv | 2 - crates/ui-egui/src/i18n/ko.tsv | 2 - crates/ui-egui/src/i18n/nl.tsv | 2 - crates/ui-egui/src/i18n/pl.tsv | 2 - crates/ui-egui/src/i18n/pt-br.tsv | 2 - crates/ui-egui/src/i18n/ru.tsv | 2 - crates/ui-egui/src/i18n/sv.tsv | 2 - crates/ui-egui/src/i18n/tr.tsv | 2 - crates/ui-egui/src/i18n/uk.tsv | 2 - crates/ui-egui/src/i18n/vi.tsv | 2 - crates/ui-egui/src/i18n/zh-hans.tsv | 2 - crates/ui-egui/src/i18n/zh-hant.tsv | 2 - docs/mcp.md | 10 +- docs/progress/script-file-print.md | 1 + 41 files changed, 543 insertions(+), 94 deletions(-) create mode 100644 docs/progress/script-file-print.md diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 8ca1fedcd7..ae08037521 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -267,6 +267,14 @@ pub(crate) fn may_write(path: &str) -> Result<()> { crate::file_access::check_write(path).map_err(EngineError::Other) } +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn regular_write_target(path: &str) -> Result<()> { + if std::fs::metadata(path).is_ok_and(|m| !m.is_file()) { + return Err(EngineError::Other(format!("{path}: not a file"))); + } + Ok(()) +} + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_file(path: &str) -> Result> { may_read(path)?; diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 48a8c828ab..8ed2778d16 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -88,6 +88,7 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do if files.len() > 1 { for (p, _) in &files { super::may_write(p)?; + super::access::regular_write_target(p)?; } } for (p, bytes) in &files { diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f31f01a7aa..8a062c46ef 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -85,6 +85,7 @@ pub struct SavePlan { /// Where to write. `None` when no path is known (never saved, converted from an older version, /// restored by Data Recovery, or a format other than the document's own): the caller asks for one or takes the bytes. pub path: Option, + pub path_given: bool, pub format: &'static Format, /// The format's options (only those its encoder reads). pub options: Map, @@ -348,7 +349,8 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { } } let lossy_source = super::lossy_source(st, p); - Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source, kept }) + let path_given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + Ok(SavePlan { mode, path, path_given, format, options, name, folder, modified, notes, lossy_source, kept }) } /// The native save options, which a save also takes beside the path. @@ -1073,11 +1075,15 @@ impl SaveJob { // Every path is checked against the file access in force before the first file is // written. A refused file goes to `write` first, which refuses it with the error the // caller gives (naming the path as the caller does), so none of the files is written. + // A permitted target that is not a regular file then stops the save the same way. #[cfg(not(target_arch = "wasm32"))] - if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) - { - write(p, bytes)?; + if files.len() > 1 { + if let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) { + write(p, bytes)?; + } + for (p, _) in &files { + super::access::regular_write_target(p).map_err(|e| if plan.path_given { e } else { super::access::naming_in_error(e, p) })?; + } } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { @@ -1241,7 +1247,7 @@ pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result let plan = save_plan(s, mode, p)?; let job = save_job(s, plan)?; let uid = s.doc()?.uid; - let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + let given = job.plan.path_given; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 02994a9f8c..0421e3fb84 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -1185,6 +1185,7 @@ pub fn jobs(s: &mut Session, store: &Arc) -> Result<(Vec HostMember { /// What a `PrintOptions` asks `file.print` for. #[derive(Default)] struct Job { + clear_fit: bool, preset: Option, file: Option, level: Option, @@ -724,11 +726,12 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<( Some(t) } else if scaled { Some("custom") - } else if fit.is_some() || tiling.is_some() { + } else if tiling.is_some() { Some("none") } else { None }; + job.clear_fit = fit == Some(false) && scaling.is_none(); if let Some(scaling) = scaling { job.top.insert("scaling".into(), json!(scaling)); } @@ -896,21 +899,27 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { /// name (any case) and a paper by its id or label. An empty name, or one with a path separator or /// a control character, throws. fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> { - let (count, saved_ignore) = with_doc(h, doc, |_, st| { + let (count, saved_ignore, saved_fit) = with_doc(h, doc, |_, st| { let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str); - (st.doc.artboards.len(), mode == Some("ignore")) + let fit = st.doc.print_setup.as_ref().and_then(|v| v.get("scaling")).and_then(Value::as_str) == Some("fit"); + (st.doc.artboards.len(), mode == Some("ignore"), fit) }); if let Some(range) = &job.range { vectorcraft_doc::range::parse_range(range, count).map_err(|e| HostError::Range(format!("PrintJobOptions.artboardRange: {e}")))?; } let s = h.session.borrow(); let mut base_ignore = saved_ignore; + let mut base_fit = saved_fit; if let Some(name) = job.preset.take() { let n = plain_name("PrintOptions.printPreset", "print preset", &name)?; let preset = s.print_preset_settings(n).ok_or_else(|| no_such("PrintOptions.printPreset", "print preset", &name))?; base_ignore = matches!(preset.artboards, vectorcraft_pdf::PrintArtboards::Ignore); + base_fit = matches!(preset.scaling, vectorcraft_pdf::PrintScaling::Fit); job.preset = Some(n.to_string()); } + if job.clear_fit && base_fit { + job.top.insert("scaling".into(), json!("none")); + } // An assigned `printArea` prints by artboard when the base settings ignore the artboards: the // assigned `artboardRange` when there is one, otherwise every artboard. if job.print_area && base_ignore && !job.top.contains_key("artboards") { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 06c847cc3d..da29f70d61 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -31,6 +31,7 @@ //! `PDFSaveOptions` option still at a new object's default keeps the preset's value. //! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record: //! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. +//! - Each method sends command warnings to the Script Console with its name as the prefix. //! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The //! commands a script runs never show a dialog, so the level does not change what they do, and it //! never allows a file the script's grants do not. @@ -580,8 +581,8 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { let given_options = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null)); // Without options, a path ending in `.ai`, `.eps` or `.pdf` takes the defaults a new options // object of that format's class holds. - let extension = path.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase()); - let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == extension.as_deref()).map(|(c, _)| fresh(c)); + let named_format = save_format_for_name(path, cfg!(windows)).map(|f| f.id); + let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == named_format).map(|(c, _)| fresh(c)); if let Some(o) = given_options.or(by_extension.as_ref()) { let name = typename(o); let Some((class, format)) = SAVE_CLASSES.iter().find(|(c, _)| Some(c.name) == name) else { @@ -595,12 +596,30 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { p.insert("options".into(), Value::Object(q)); } } + if !p.contains_key("format") { + let format = named_format.unwrap_or_else(|| super::with_doc(h, doc, |_, st| st.format)); + p.insert("format".into(), json!(format)); + } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + let result = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + report_warnings(h, "Document.saveAs", &result); Ok(Data::Undefined) } +fn save_format_for_name(path: &str, windows: bool) -> Option<&'static crate::cmd::fileio::Format> { + let name = if windows { path.rsplit(['/', '\\']).next() } else { path.rsplit('/').next() }.unwrap_or(path); + let name = if windows { name.trim_end_matches(['.', ' ']) } else { name }; + // A name that is only a dot and an extension, such as `.pdf`, picks its format only for the + // `.ai`, `.eps` and `.pdf` options classes; any other name takes the usual extension rule. + match name.rsplit_once('.') { + Some(("", extension)) if SAVE_CLASSES.iter().any(|(_, f)| extension.eq_ignore_ascii_case(f)) => { + crate::cmd::fileio::format_for_name(&format!("x.{extension}")) + } + _ => crate::cmd::fileio::format_for_name(name), + } +} + /// `path` with the extension of `kind` added, unless its name already ends with one of them. fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String { let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions }; @@ -651,7 +670,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + let result = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + report_warnings(h, "Document.exportFile", &result); Ok(Data::Undefined) } @@ -693,6 +713,7 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; + report_warnings(h, "app.open", &r); let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { ("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()), @@ -705,6 +726,20 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { Ok(doc_ref(h, st.uid)) } +fn report_warnings(h: &Host, method: &str, result: &Data) { + let warnings = match result { + Data::Object(fields) => fields.iter().find(|(k, _)| k == "warnings").map(|(_, v)| v), + _ => None, + }; + if let Some(Data::Array(warnings)) = warnings { + for warning in warnings.iter().take(super::MAX_LISTED) { + if let Data::String(warning) = warning { + super::super::each_line(&format!("{method}: {warning}"), |line, cut| h.line(super::super::console::Entry::Output(line), cut)); + } + } + } +} + fn app_interaction(h: &Host, _: &[Data]) -> Answer { Ok(text(if h.dom.save_options.quiet.get() { QUIET } else { DISPLAY })) } @@ -745,3 +780,33 @@ pub(super) fn classes(link: &Link) -> Vec { }) .collect() } + +#[cfg(test)] +mod save_format_tests { + use super::save_format_for_name; + + #[test] + fn save_as_selects_the_format_from_windows_filename_aliases() { + for extension in ["svg", "svgz", "ai", "eps", "pdf"] { + for suffix in [".", " ", ". . ", "..."] { + for prefix in ["", "/exports/", "C:\\exports\\"] { + let name = format!("{prefix}drawing.{}{suffix}", extension.to_ascii_uppercase()); + assert_eq!(save_format_for_name(&name, true).map(|f| f.id), Some(extension), "{name}"); + assert!(save_format_for_name(&name, false).is_none(), "{name}"); + } + } + } + for name in ["drawing", "drawing. . ", "drawing.svg\t", "drawing.svg\u{a0}", "folder.svg/drawing", "folder.svg\\drawing"] { + assert!(save_format_for_name(name, true).is_none(), "{name}"); + } + assert_eq!(save_format_for_name("proof\\.svg", false).map(|f| f.id), Some("svg")); + for windows in [false, true] { + assert_eq!(save_format_for_name(".pdf", windows).map(|f| f.id), Some("pdf")); + assert!(save_format_for_name(".svg", windows).is_none()); + assert!(save_format_for_name("/exports/.png", windows).is_none()); + assert_eq!(save_format_for_name("/exports/.eps", windows).map(|f| f.id), Some("eps")); + assert_eq!(save_format_for_name("drawing.svg", windows).map(|f| f.id), Some("svg")); + assert_eq!(save_format_for_name("drawing.svgz", windows).map(|f| f.id), Some("svgz")); + } + } +} diff --git a/crates/engine/src/tests/save.rs b/crates/engine/src/tests/save.rs index 076e964212..98e6c0ca52 100644 --- a/crates/engine/src/tests/save.rs +++ b/crates/engine/src/tests/save.rs @@ -133,6 +133,50 @@ fn pathless_save_rejection_hides_document_folder() { let _ = std::fs::remove_dir_all(d); } +#[test] +fn multi_file_save_directory_errors_hide_paths_the_caller_did_not_give() { + use crate::file_access::{AutomationRoots, confine}; + + let d = dir("multi-file-directory-error"); + let (inside, outside) = (d.join("in"), d.join("kept-out")); + for folder in [&inside, &outside] { + std::fs::create_dir_all(folder).unwrap(); + } + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + let own = path(&outside, "doc.vectorcraft"); + let saved = s.execute("document.save", &json!({"path": own, "separateArtboards": true})).unwrap(); + let files: Vec = saved["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); + assert!(files.len() > 1, "{saved}"); + let primary = std::fs::read(&own).unwrap(); + rect(&mut s); + let write_only = AutomationRoots::new(&[inside.as_path()], &[outside.as_path()]).unwrap(); + let both = AutomationRoots::new(&[inside.as_path(), outside.as_path()], &[outside.as_path()]).unwrap(); + for target in [&files[0], &files[1]] { + let original = std::fs::read(target).unwrap(); + std::fs::remove_file(target).unwrap(); + std::fs::create_dir(target).unwrap(); + let name = std::path::Path::new(target).file_name().unwrap().to_string_lossy(); + for (roots, params, shown) in [ + (&write_only, json!({"separateArtboards": true}), name.as_ref()), + (&write_only, json!({"path": null, "separateArtboards": true}), name.as_ref()), + (&write_only, json!({"path": own, "separateArtboards": true}), target.as_str()), + (&both, json!({"separateArtboards": true}), target.as_str()), + ] { + let error = confine(roots.as_ref(), || s.execute("document.save", ¶ms)).unwrap_err().to_string(); + assert_eq!(error, format!("{shown}: not a file"), "{params}"); + assert!(std::path::Path::new(target).is_dir()); + if target != &own { + assert_eq!(std::fs::read(&own).unwrap(), primary); + } + assert!(s.doc().unwrap().is_dirty()); + } + std::fs::remove_dir(target).unwrap(); + std::fs::write(target, original).unwrap(); + } + let _ = std::fs::remove_dir_all(d); +} + #[test] fn an_svg_path_writes_svg_and_save_writes_it_back() { let d = dir("svg"); diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index e115c60aae..5c138066c9 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -135,6 +135,92 @@ fn print_without_a_file_does_not_print() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn a_print_job_file_can_be_read_and_assigned_to_another_job() { + let base = folder("file-getter"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let path = dir.join("proof 100%.pdf"); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var first = new PrintJobOptions(), second = new PrintJobOptions(); + first.file = new File({}); second.file = first.file; + vc.log([second.file instanceof File, second.file.fsName === first.file.fsName]); + var o = new PrintOptions(); o.jobOptions = second; app.activeDocument.print(o);", + quoted(&path) + ), + ); + assert_eq!(out[0], json!([true, true])); + assert!(!pages(&path).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn print_scale_assignment_and_reflection_share_the_supported_range() { + let base = folder("scale-range"); + let mut s = session(&base); + let out = logged( + &mut s, + &base, + "var c = new PrintCoordinateOptions(); + var names = ['horizontalScale', 'verticalScale']; + for (var i = 0; i < names.length; i++) { + var name = names[i], info = c.reflect.find(name); + c[name] = info.max; + try { c[name] = info.max + 0.01; vc.log('accepted'); } + catch (e) { vc.log([e.name, c[name] === info.max, info.max === 1000]); } + }", + ); + assert_eq!(out, json!([["RangeError", true, true], ["RangeError", true, true]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn disabling_fit_preserves_other_base_scaling_modes() { + let base = folder("fit-false"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let boxes = |path: &Path| { + let mut boxes = Vec::new(); + vectorcraft_pdf::import(&std::fs::read(path).unwrap()).unwrap().walk(|node| { + if let Some(bounds) = node.path_data().and_then(|p| p.bounds()) { + boxes.push(bounds); + } + }); + boxes + }; + for mode in ["tileFull", "tileImageable", "custom", "fit"] { + let settings = json!({"scaling": mode, "scale": {"width": 500, "height": 500}}); + s.execute("print.setup", &json!({"settings": settings})).unwrap(); + s.execute("print.presets.save", &json!({"name": "Base", "settings": settings})).unwrap(); + let override_settings = if mode == "fit" { json!({"scaling": "none"}) } else { json!({}) }; + let want = s.execute("file.print", &json!({"settings": override_settings, "path": dir.join("want.pdf").to_string_lossy()})).unwrap(); + for preset in [false, true] { + if preset { + s.execute("print.setup", &json!({"settings": {"scaling": "none"}})).unwrap(); + } + let out = dir.join(format!("{mode}-{preset}.pdf")); + let select = if preset { "o.printPreset = 'Base';" } else { "" }; + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); + {select} o.coordinateOptions.fitToPage = false; app.activeDocument.print(o);", + quoted(&out) + ), + ); + let expected = boxes(&dir.join("want.pdf")); + assert!(!expected.is_empty()); + assert_eq!(boxes(&out), expected, "{mode}, preset: {preset}"); + assert_eq!(pages(&out).len() as u64, want["pages"].as_u64().unwrap()); + } + } + let _ = std::fs::remove_dir_all(base); +} + /// Bad values throw when they are assigned, and nothing prints. #[test] fn print_options_refuse_bad_values() { @@ -149,8 +235,10 @@ fn print_options_refuse_bad_values() { ("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"), + ("c.verticalScale = 20000;", "RangeError", "verticalScale must be from 1 to 1000"), + ("c.verticalScale = 0;", "RangeError", "verticalScale must be from 1 to 1000"), + ("c.horizontalScale = 1000.01;", "RangeError", "horizontalScale must be from 1 to 1000"), + ("c.verticalScale = 1000.01;", "RangeError", "verticalScale must be from 1 to 1000"), ("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"), @@ -194,10 +282,7 @@ fn options_that_are_not_available_throw() { ("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", - ), + (&format!("{file} o.coordinateOptions.horizontalScale = 2000; app.activeDocument.print(o);"), "horizontalScale must be from 1 to 1000"), ]; let prefix = "Folder.userData; var o = new PrintOptions(), j = o.jobOptions;"; for (case, part) in cases { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8518f14365..a642aac12b 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -93,6 +93,120 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { let _ = std::fs::remove_dir_all(base); } +#[cfg(unix)] +#[test] +fn save_as_selects_the_format_before_resolving_a_link() { + let base = folder("save-link-format"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for extension in ["svg", "svgz"] { + let target = dir.join(format!("{extension}.vectorcraft")); + let link = dir.join(format!("drawing.{extension}")); + std::fs::write(&target, "original").unwrap(); + std::os::unix::fs::symlink(&target, &link).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&link))); + let bytes = std::fs::read(&target).unwrap(); + if extension == "svgz" { + assert!(bytes.starts_with(&[0x1f, 0x8b])); + } else { + assert!(String::from_utf8(bytes).unwrap().contains(" = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect(); + assert_eq!(images.len(), 1); + let image = &images[0]; + std::fs::remove_file(image).unwrap(); + std::fs::create_dir(image).unwrap(); + for save in [false, true] { + std::fs::write(&svg, "original SVG").unwrap(); + let call = if save { format!("app.activeDocument.saveAs(new File({}));", quoted(&svg)) } else { export.clone() }; + let error = failure(&mut s, &base, &format!("Folder.userData; {call}")); + assert!(error.contains("not a file"), "{call}: {error}"); + assert_eq!(std::fs::read_to_string(&svg).unwrap(), "original SVG"); + assert!(image.is_dir()); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn save_export_and_open_report_command_warnings_in_the_console() { + let base = folder("command-warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + logged( + &mut s, + &base, + "app.documents.add(DocumentColorSpace.RGB, 100, 100); + vc.run('shape.rectangle', {x: 10, y: 10, width: 50, height: 50}); + vc.run('transparency.set', {opacity: 0.5}); app.activeDocument.pageItems[0].name = 'bad\\u0001name';", + ); + for (command, format, method, call) in [ + ("file.saveAs", "eps", "Document.saveAs", "app.activeDocument.saveAs(f);"), + ("document.export", "svg", "Document.exportFile", "app.activeDocument.exportFile(f, ExportType.SVG);"), + ] { + let path = dir.join(format!("warnings.{format}")); + let want = s.execute(command, &json!({"path": path.to_string_lossy(), "format": format})).unwrap(); + let warnings: Vec = want["warnings"].as_array().unwrap().iter().map(|w| format!("{method}: {}", w.as_str().unwrap())).collect(); + assert!(!warnings.is_empty(), "{command}: {want}"); + let report = run(&mut s, &base, &format!("Folder.userData; var f = new File({}); {call}", quoted(&path))).unwrap(); + assert_eq!(report["console"]["lines"], json!(warnings)); + } + let svg = dir.join("missing-image.svg"); + std::fs::write(&svg, "") + .unwrap(); + let want = s.execute("document.open", &json!({"path": svg.to_string_lossy()})).unwrap(); + let warnings: Vec = want["warnings"].as_array().unwrap().iter().map(|w| format!("app.open: {}", w.as_str().unwrap())).collect(); + assert!(!warnings.is_empty(), "{want}"); + let report = run(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&svg))).unwrap(); + assert_eq!(report["console"]["lines"], json!(warnings)); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_multi_file_save_refuses_a_directory_before_replacing_the_primary_file() { + let base = folder("save-directory"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap(); + let path = dir.join("drawing.vectorcraft"); + let saved = s.execute("file.saveAs", &json!({"path": path.to_string_lossy(), "format": "vectorcraft", "separateArtboards": true})).unwrap(); + let files = saved["files"].as_array().unwrap(); + assert!(files.len() > 1, "{saved}"); + let primary = std::fs::read(&path).unwrap(); + let sidecar = files.iter().map(|v| PathBuf::from(v.as_str().unwrap())).find(|p| *p != path).unwrap(); + std::fs::remove_file(&sidecar).unwrap(); + std::fs::create_dir(&sidecar).unwrap(); + let error = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&path))); + assert!(error.contains("not a file"), "{error}"); + assert_eq!(std::fs::read(&path).unwrap(), primary); + assert!(sidecar.is_dir()); + let _ = std::fs::remove_dir_all(base); +} + /// Without options, a save or export writes what an untouched new options object of its class gives. #[test] fn omitted_options_are_a_new_options_objects_defaults() { @@ -496,6 +610,23 @@ fn bad_arguments_are_refused_with_an_error() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn logging_files_and_folders_reads_only_enumerable_own_properties() { + let base = folder("log-file-folder"); + let mut s = session(&base); + let text = "var f = new File('kept.svg'), d = new Folder('kept');\n\ + vc.log(f); vc.log(d); vc.log([f, {folder: d}]);\n\ + File.prototype.inherited = 'omit'; Folder.prototype.inherited = 'omit';\n\ + Object.defineProperty(f, 'hidden', {value: 'omit', enumerable: false});\n\ + Object.defineProperty(d, 'hidden', {value: 'omit', enumerable: false});\n\ + f.label = 'drawing'; d.count = 2;\n\ + vc.log(f); vc.log(d); vc.log([f, {folder: d}]);"; + let log = logged(&mut s, &base, text); + let nested = json!([{"label": "drawing"}, {"folder": {"count": 2}}]); + assert_eq!(log, json!([{}, {}, [{}, {"folder": {}}], {"label": "drawing"}, {"count": 2}, nested])); + let _ = std::fs::remove_dir_all(base); +} + /// Only a `File` the `File` class made names a file. An object made from `File.prototype` and a /// plain object throw a `TypeError`, and a `File` whose hidden path property a script set keeps its /// own path, so nothing is written or opened at the path the script put there. diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 1c63f46036..10b2e9944c 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -103,7 +103,7 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { /// The text of the localization object `id` for the current locale: the string value of the first /// of [`Localization::keys`] that the object has as its own data property. No getter runs. pub(crate) fn localized_text(interp: &mut Interp, id: ObjId) -> JsResult> { - if !matches!(interp.object(id)?.class, Class::Ordinary) { + if !matches!(interp.object(id)?.class, Class::Ordinary | Class::File(_)) { return Ok(None); } for k in interp.localization.keys() { @@ -293,11 +293,13 @@ impl Source { Some(Err(*length)) } Class::Array { .. } => return Err(interp.type_error(NOT_PLAIN_ARRAY)), - Class::Ordinary if has_symbols => return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source")), - Class::Ordinary if o.proto == Some(object_proto) && enumerable => { + Class::Ordinary | Class::File(_) if has_symbols => { + return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source")); + } + Class::Ordinary | Class::File(_) if o.proto == Some(object_proto) && enumerable => { Some(Ok(o.props.iter().map(|(k, p)| (k.clone(), p.clone())).collect::>())) } - Class::Ordinary => return Err(interp.type_error(NOT_PLAIN_OBJECT)), + Class::Ordinary | Class::File(_) => return Err(interp.type_error(NOT_PLAIN_OBJECT)), _ => None, }; let fixed = shape.as_ref().and(fixed_state(o)); @@ -451,3 +453,52 @@ fn function_name(code: &Code) -> String { None => "[anonymous]".to_string(), } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::heap::{OPEN, PropMap}; + use crate::interp::Abrupt; + + fn source_error(interp: &mut Interp, id: ObjId) -> String { + let Err(Abrupt::Throw(error)) = write_source(interp, Value::Object(id)) else { panic!("expected a source error") }; + let Value::String(message) = interp.get_value(&error, &key("message")).unwrap() else { panic!("expected an error message") }; + message.to_rust_string() + } + + #[test] + fn to_source_uses_ordinary_properties_and_guards_for_files() { + for file in [false, true] { + let mut interp = Interp::new(crate::Options { es2015: true, ..crate::Options::default() }, crate::Limits::default()); + let class = if file { + let mut slots = PropMap::default(); + slots.insert(key("__vcPath"), Value::str("native path")); + Class::File(Box::new(slots)) + } else { + Class::Ordinary + }; + let mut object = Object::new(class, Some(interp.intrinsics.object_proto)); + object.props.insert(key("label"), Prop::Data { value: Value::str("public"), flags: OPEN }); + let id = interp.heap.alloc_object(object); + let Value::String(source) = write_source(&mut interp, Value::Object(id)).unwrap() else { panic!("expected source text") }; + assert_eq!(source.to_rust_string(), r#"({"label":"public"})"#); + interp.object_mut(id).unwrap().props.insert(key("__vcPath"), Prop::Data { value: Value::str("own path"), flags: OPEN }); + let Value::String(source) = write_source(&mut interp, Value::Object(id)).unwrap() else { panic!("expected source text") }; + assert_eq!(source.to_rust_string(), r#"({"label":"public", "__vcPath":"own path"})"#); + interp.object_mut(id).unwrap().proto = None; + assert_eq!(source_error(&mut interp, id), NOT_PLAIN_OBJECT); + interp.object_mut(id).unwrap().proto = Some(interp.intrinsics.object_proto); + interp.object_mut(id).unwrap().props.insert(key("hidden"), Prop::Data { value: Value::Bool(true), flags: 0 }); + assert_eq!(source_error(&mut interp, id), NOT_PLAIN_OBJECT); + interp.object_mut(id).unwrap().props.insert(key("hidden"), Prop::Data { value: Value::Bool(true), flags: crate::heap::ENUMERABLE }); + assert_eq!(source_error(&mut interp, id), FIXED_PROPERTY); + interp.object_mut(id).unwrap().props.insert(key("hidden"), Prop::Data { value: Value::Bool(true), flags: OPEN }); + interp.object_mut(id).unwrap().extensible = false; + assert_eq!(source_error(&mut interp, id), NOT_EXTENSIBLE); + interp.object_mut(id).unwrap().extensible = true; + let symbol = interp.well_known(|w| &w.iterator).unwrap(); + interp.define_sym(id, symbol, Prop::Data { value: Value::Bool(true), flags: OPEN }).unwrap(); + assert_eq!(source_error(&mut interp, id), "toSource: an object with a Symbol property cannot be written as source"); + } + } +} diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index ed114612d4..c28c8a12a8 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -282,7 +282,7 @@ impl Interp { self.constructing = was; let v = v?; if let Value::Object(o) = &v - && matches!(self.object(*o)?.class, Class::Ordinary) + && matches!(self.object(*o)?.class, Class::Ordinary | Class::File(_)) && let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))? { self.object_mut(*o)?.proto = Some(proto); diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index df5829a41b..aba0a72162 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -8,7 +8,7 @@ //! host's `stat` says the path is a folder, and `Folder(path)` a `File` when it is a file. Two //! objects for one path are different objects. An object keeps its path in the host's platform //! form, its `error` text, the id of the file it has open (or -1), the encoding set before `open` -//! and its line feed, in properties that are not enumerable; every name the getters give comes from +//! and its line feed in native slots; every name the getters give comes from //! the host's `parse` of that path. `Folder.current` is kept in the realm and starts at the host's //! `current`. //! @@ -79,15 +79,18 @@ fn message(i: &mut Interp, name: &str) -> JsResult { /// so that a property a script put on `Object.prototype` is not read as part of it. fn field(i: &mut Interp, v: &Value, name: &str) -> JsResult { match v.as_object() { - Some(o) => slot(i, o, name), + Some(o) => Ok(match i.get_own_property(o, &key(name))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }), None => Ok(Value::Undefined), } } -/// The value of the own data property `name` of `o`, `undefined` when it has none. +/// The native slot `name` of `o`, or `undefined` when it has none. fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { - Ok(match i.get_own_property(o, &key(name))? { - Some(Prop::Data { value, .. }) => value, + Ok(match &i.object(o)?.class { + Class::File(fields) => fields.get(&key(name)).cloned().unwrap_or(Value::Undefined), _ => Value::Undefined, }) } @@ -106,10 +109,19 @@ pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult> { } fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { - if let Value::String(s) = &value { - i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?; - } - i.define(o, key(name), Prop::Data { value, flags: HIDDEN }) + let Class::File(fields) = &i.object(o)?.class else { + return Err(Abrupt::Internal("File slot on an object without native storage".into())); + }; + let name = key(name); + let added = if fields.contains(&name) { 0 } else { PROP_BYTES + string_bytes(name.len()) }; + i.rooted(&[Value::Object(o), value.clone()], |i| { + i.reserve_heap(added)?; + if let Class::File(fields) = &mut i.object_mut(o)?.class { + fields.insert(name, value); + i.heap.bytes = i.heap.bytes.saturating_add(added); + } + Ok(()) + }) } /// The object `this` and its path, or a `TypeError` naming `what` when it is not a `File` or @@ -181,8 +193,10 @@ fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult JsResult { let line_feed = host_value(i, "lineFeed")?; i.rooted(&[fs.clone(), line_feed.clone()], |i| { - i.reserve_heap(OBJECT_BYTES + 6 * PROP_BYTES)?; - let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + let storage = std::mem::size_of::>(); + i.reserve_heap(OBJECT_BYTES + storage + 6 * PROP_BYTES)?; + let o = i.heap.alloc_object(Object::new(Class::File(Box::default()), Some(proto))); + i.heap.bytes = i.heap.bytes.saturating_add(storage); i.rooted(&[Value::Object(o)], |i| { set_slot(i, o, PATH, fs.clone())?; set_slot(i, o, ERROR, Value::str(""))?; @@ -290,6 +304,11 @@ fn count(i: &mut Interp, v: &Value, what: &str) -> JsResult> { // ---- constructors ---- +pub(crate) fn from_path(i: &mut Interp, path: Value) -> JsResult { + let proto = classes(i)?.file_proto; + i.rooted(std::slice::from_ref(&path), |i| instance(i, proto, path.clone())) +} + fn file_ctor(i: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { make(i, args, construct, true) } @@ -1363,6 +1382,75 @@ mod tests { assert_eq!(v.unwrap(), JsValue::String("x,/x,2,d/b,1".into())); } + #[test] + fn files_and_folders_localize_their_own_locale_properties() { + let mut r = realm(); + r.add_script_extensions().unwrap(); + r.localization().set_locale("fr_FR"); + r.localization().set_enabled(true); + let source = "var results = []; var constructors = [File, Folder]; + for (var n = 0; n < constructors.length; n++) { + var C = constructors[n], f = new C('x'), hit = false; + C.prototype.fr = 'inherited'; + results.push(localize(f) === f); + f.en = 'English %1'; + Object.defineProperty(f, 'fr_FR', {get: function () { hit = true; return 'getter'; }, configurable: true}); + results.push(localize(f, 'text') === 'English text', !hit); + f.fr = 'French %1'; + results.push(localize(f, 'text') === 'French text'); + results.push(Object.prototype.toString.call(f) === 'French %1'); + delete C.prototype.fr; + } + results.every(function (v) { return v; })"; + assert_eq!(r.run(source).unwrap(), JsValue::Bool(true)); + } + + #[test] + fn files_and_folders_copy_only_ordinary_own_properties() { + let mut r = realm(); + let copy = HostItem::Function(Rc::new(|a: Vec| Ok(a.into_iter().next().unwrap_or(Data::Undefined)))); + r.define_host_object("host", vec![("copy".into(), copy)]).unwrap(); + let source = "var results = []; var constructors = [File, Folder]; + for (var n = 0; n < constructors.length; n++) { + var C = constructors[n], f = new C('x'); + results.push(Object.getOwnPropertyNames(f).length === 0, Object.keys(f).length === 0); + results.push(JSON.stringify(f) === '{}', typeof f === 'object', f instanceof C); + results.push(Object.prototype.toString.call(f) === '[object Object]'); + f.label = 'public'; f.child = {values: [1, true]}; f.__vcPath = 'ordinary property'; + var plain = {label: 'public', child: {values: [1, true]}, __vcPath: 'ordinary property'}; + results.push(JSON.stringify(f) === JSON.stringify(plain)); + results.push(Object.keys(f).join() === Object.keys(plain).join()); + results.push(Object.getOwnPropertyNames(f).join() === Object.getOwnPropertyNames(plain).join()); + results.push(f.fsName === '/x', f.__vcPath === 'ordinary property', f.__vcHandle === undefined); + var cloned = host.copy(f); + results.push(JSON.stringify(cloned) === JSON.stringify(plain), cloned !== f, cloned.child !== f.child); + results.push(Object.getPrototypeOf(cloned) === Object.prototype); + } + results.every(function (v) { return v; })"; + assert_eq!(r.run(source).unwrap(), JsValue::Bool(true)); + } + + #[test] + fn a_host_constructor_assigns_its_prototype_to_a_returned_file() { + let mut r = realm(); + let make = Rc::new(|_: Vec| Ok(Data::Object(vec![(crate::FILE_REF_KEY.into(), Data::String("/x".into()))]))); + let copy = Rc::new(|a: Vec| Ok(a.get(1).cloned().unwrap_or(Data::Undefined))); + let class = crate::HostClass { + name: "ReturnedFile".into(), + parent: None, + members: vec![("copy".into(), crate::HostMember::Method(copy))], + info: Vec::new(), + index: None, + construct: Some(make), + }; + r.define_host_classes(vec![class], Vec::new()).unwrap(); + let source = "var f = new ReturnedFile(); f.own = 'kept'; var d = new Folder('x'); d.own = 'folder'; + f instanceof ReturnedFile && Object.getPrototypeOf(f) === ReturnedFile.prototype && + Object.keys(f).join() === 'own' && JSON.stringify(f) === '{\"own\":\"kept\"}' && + JSON.stringify(f.copy(f)) === '{\"own\":\"kept\"}' && JSON.stringify(f.copy(d)) === '{\"own\":\"folder\"}'"; + assert_eq!(r.run(source).unwrap(), JsValue::Bool(true)); + } + #[test] fn the_constructor_picks_the_class_only_without_new() { let mut r = realm(); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index c8ae5a8c11..debfec90d8 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -272,6 +272,7 @@ pub(crate) enum Class { Xmp(Box), /// An object the `XMPFile` constructor made ([`crate::xmp_classes`]). XmpFile(Box>), + File(Box>), /// An object of a class a host defined ([`crate::host_classes`]). Host(crate::host_classes::HostObj), /// A `UnitValue` object and its measurement ([`crate::unit_value`]). @@ -578,7 +579,7 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::PromiseRecord(_) => "Object", + Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::File(_) | Class::PromiseRecord(_) => "Object", Class::Promise(_) => "Promise", Class::Math => "Math", Class::Json => "JSON", @@ -1187,7 +1188,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u extra = VIEW_BYTES; } Class::Xmp(meta) => extra = meta.heap_bytes(), - Class::XmpFile(fields) => { + Class::XmpFile(fields) | Class::File(fields) => { for (name, value) in fields.iter() { strings.add_key(name); mark_value(value, work, strings); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index ae61b15663..85e65adbc2 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -282,7 +282,7 @@ impl Interp { Class::Host(_) if r.hosted => return self.read_host_ref(id, r), Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), - Class::Ordinary => { + Class::Ordinary | Class::File(_) => { let o = self.object(id)?; if o.props.len() > r.limits.entries { return Err(self.data_error(r, ErrorType::Range, "has too many entries")); @@ -385,6 +385,10 @@ impl Interp { Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, _)] if k == crate::HOST_REF_KEY) => { self.write_host_ref(&Data::Object(items))? } + Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, Data::String(_))] if k == crate::FILE_REF_KEY) => { + let path = self.write_data(items.into_iter().next().map_or(Data::Undefined, |(_, v)| v), depth + 1, false)?; + crate::file_classes::from_path(self, path)? + } Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?, }) } diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 0c091dcc91..c451ec9811 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6647,8 +6647,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written No s’ha pogut escriure el fitxer de l’script @msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui @msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi -@msg Script file is read-only El fitxer de l’script és només de lectura -@msg Script file is open for writing El fitxer de l’script està obert per escriure-hi @msg Script file name is already in use El nom del fitxer de l’script ja està en ús @msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta @msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4309654e8d..d2a89194fa 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5429,8 +5429,6 @@ liquify-list-end {0}, {1} {0} a {1} @msg Script file could not be written Soubor skriptu nelze zapsat @msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví @msg Script file is not open for writing Soubor skriptu není otevřený pro zápis -@msg Script file is read-only Soubor skriptu je jen pro čtení -@msg Script file is open for writing Soubor skriptu je otevřený pro zápis @msg Script file name is already in use Název souboru skriptu se už používá @msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky @msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d356fd7ab2..70c167b084 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -88,8 +88,6 @@ @msg Script file could not be written Scriptfilen kunne ikke skrives @msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person @msg Script file is not open for writing Scriptfilen er ikke åben for skrivning -@msg Script file is read-only Scriptfilen er skrivebeskyttet -@msg Script file is open for writing Scriptfilen er åben for skrivning @msg Script file name is already in use Scriptfilens navn er allerede i brug @msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe @msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 3cab0128fe..e2ce6c9202 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5006,8 +5006,6 @@ liquify-list-end {0}, {1} {0} und {1} @msg Script file could not be written Skriptdatei konnte nicht geschrieben werden @msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet @msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet -@msg Script file is read-only Skriptdatei ist schreibgeschützt -@msg Script file is open for writing Skriptdatei ist zum Schreiben geöffnet @msg Script file name is already in use Name der Skriptdatei wird bereits verwendet @msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein @msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 5bc9c90d1a..51b04c5526 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2838,8 +2838,6 @@ liquify-list-end {0}, {1} {0} και {1} @msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου @msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει @msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή -@msg Script file is read-only Το αρχείο του σεναρίου είναι μόνο για ανάγνωση -@msg Script file is open for writing Το αρχείο του σεναρίου είναι ανοιχτό για εγγραφή @msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη @msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο @msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 1d177afc44..053e35e721 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5116,8 +5116,6 @@ liquify-list-end {0}, {1} {0}, {1} @msg Script file could not be written No se pudo escribir el archivo del script @msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda @msg Script file is not open for writing El archivo del script no está abierto para escritura -@msg Script file is read-only El archivo del script es de solo lectura -@msg Script file is open for writing El archivo del script está abierto para escritura @msg Script file name is already in use El nombre del archivo del script ya está en uso @msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta @msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index db1a87dbed..05c77549a0 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5359,8 +5359,6 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa @msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö @msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten -@msg Script file is read-only Komentosarjan tiedosto on vain luku -tilassa -@msg Script file is open for writing Komentosarjan tiedosto on auki kirjoittamista varten @msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä @msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota @msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 29a520a0a9..8f843cc11f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5073,8 +5073,6 @@ liquify-list-end {0}, {1} {0} et {1} @msg Script file could not be written Le fichier du script n’a pas pu être écrit @msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre @msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture -@msg Script file is read-only Le fichier du script est en lecture seule -@msg Script file is open for writing Le fichier du script est ouvert en écriture @msg Script file name is already in use Le nom du fichier du script est déjà utilisé @msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier @msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 323635ebc9..3bc5aaf219 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7850,8 +7850,6 @@ liquify-list-end {0}, {1} {0} और {1} @msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी @msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है @msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है -@msg Script file is read-only स्क्रिप्ट फ़ाइल केवल पढ़ने के लिए है -@msg Script file is open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली है @msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है @msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए @msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index eb7b957794..fedcfcf62b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5951,8 +5951,6 @@ liquify-list-end {0}, {1} {0} és {1} @msg Script file could not be written A parancsfájl fájlját nem sikerült írni @msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia @msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva -@msg Script file is read-only A parancsfájl fájlja csak olvasható -@msg Script file is open for writing A parancsfájl fájlja írásra meg van nyitva @msg Script file name is already in use A parancsfájl fájljának neve már használatban van @msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen @msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e43c36b300..3c434256fa 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8913,8 +8913,6 @@ breakText Glyphs Glif @msg Script file could not be written File skrip tidak dapat ditulis @msg Script file dialogs need a person to answer them Dialog file skrip memerlukan orang untuk menjawabnya @msg Script file is not open for writing File skrip tidak dibuka untuk ditulis -@msg Script file is read-only File skrip hanya dapat dibaca -@msg Script file is open for writing File skrip sedang dibuka untuk ditulis @msg Script file name is already in use Nama file skrip sudah digunakan @msg Script file name must be a name without a folder Nama file skrip harus berupa nama tanpa folder @msg Script file permission can be kept only for a script run from a file Izin file skrip hanya dapat disimpan untuk skrip yang dijalankan dari file diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cd54480a25..13d0656137 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5144,8 +5144,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Impossibile scrivere il file dello script @msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda @msg Script file is not open for writing Il file dello script non è aperto in scrittura -@msg Script file is read-only Il file dello script è di sola lettura -@msg Script file is open for writing Il file dello script è aperto in scrittura @msg Script file name is already in use Il nome del file dello script è già in uso @msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella @msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 32eabfa175..97606b7e76 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5980,8 +5980,6 @@ liquify-list-end {0}, {1} {0}、{1} @msg Script file could not be written スクリプトのファイルを書き込めませんでした @msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です @msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません -@msg Script file is read-only スクリプトのファイルは読み取り専用です -@msg Script file is open for writing スクリプトのファイルが書き込み用に開かれています @msg Script file name is already in use スクリプトのファイル名はすでに使用されています @msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください @msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cbfae1b8d5..a8d2240536 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8653,8 +8653,6 @@ liquify-list-end {0}, {1} {0} და {1} @msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა @msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს @msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის -@msg Script file is read-only სკრიპტის ფაილი მხოლოდ წასაკითხია -@msg Script file is open for writing სკრიპტის ფაილი ჩასაწერად გახსნილია @msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება @msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე @msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 839151841b..96e84b418e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5909,8 +5909,6 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg Script file could not be written 스크립트 파일을 쓸 수 없습니다 @msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 @msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 -@msg Script file is read-only 스크립트 파일이 읽기 전용입니다 -@msg Script file is open for writing 스크립트 파일이 쓰기용으로 열려 있습니다 @msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 @msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 @msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 90facd6389..fada1fc205 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -90,8 +90,6 @@ @msg Script file could not be written Het scriptbestand kon niet worden geschreven @msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord @msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven -@msg Script file is read-only Het scriptbestand is alleen-lezen -@msg Script file is open for writing Het scriptbestand is geopend voor schrijven @msg Script file name is already in use De naam van het scriptbestand is al in gebruik @msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn @msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 3cc4572864..01d3571047 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5246,8 +5246,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written Nie można zapisać pliku skryptu @msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie @msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu -@msg Script file is read-only Plik skryptu jest tylko do odczytu -@msg Script file is open for writing Plik skryptu jest otwarty do zapisu @msg Script file name is already in use Nazwa pliku skryptu jest już używana @msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu @msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 5e9c84ef5e..e3dd5ffeda 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6291,8 +6291,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Não foi possível gravar o arquivo do script @msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las @msg Script file is not open for writing O arquivo do script não está aberto para gravação -@msg Script file is read-only O arquivo do script é somente leitura -@msg Script file is open for writing O arquivo do script está aberto para gravação @msg Script file name is already in use O nome do arquivo do script já está em uso @msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta @msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 59d5006547..a2235998eb 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5141,8 +5141,6 @@ liquify-list-end {0}, {1} {0} и {1} @msg Script file could not be written Не удалось записать файл скрипта @msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек @msg Script file is not open for writing Файл скрипта не открыт для записи -@msg Script file is read-only Файл скрипта доступен только для чтения -@msg Script file is open for writing Файл скрипта открыт для записи @msg Script file name is already in use Имя файла скрипта уже используется @msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки @msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1a6a11ca81..41bda9072e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5014,8 +5014,6 @@ liquify-list-end {0}, {1} {0} och {1} @msg Script file could not be written Skriptets fil kunde inte skrivas @msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem @msg Script file is not open for writing Skriptets fil är inte öppen för skrivning -@msg Script file is read-only Skriptets fil är skrivskyddad -@msg Script file is open for writing Skriptets fil är öppen för skrivning @msg Script file name is already in use Namnet på skriptets fil används redan @msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp @msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7a624802e4..0ee286faa1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4842,8 +4842,6 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Script file could not be written Betiğin dosyası yazılamadı @msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir @msg Script file is not open for writing Betiğin dosyası yazmak için açık değil -@msg Script file is read-only Betiğin dosyası salt okunur -@msg Script file is open for writing Betiğin dosyası yazmak için açık @msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor @msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır @msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 39c04fe34e..e9dd432e72 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5128,8 +5128,6 @@ liquify-list-end {0}, {1} {0} і {1} @msg Script file could not be written Не вдалося записати файл скрипту @msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина @msg Script file is not open for writing Файл скрипту не відкрито для запису -@msg Script file is read-only Файл скрипту доступний лише для читання -@msg Script file is open for writing Файл скрипту відкрито для запису @msg Script file name is already in use Ім’я файлу скрипту вже використовується @msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки @msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8d10194145..8e9d5cac87 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5641,8 +5641,6 @@ liquify-list-end {0}, {1} {0} và {1} @msg Script file could not be written Không thể ghi tệp của tập lệnh @msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời @msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi -@msg Script file is read-only Tệp của tập lệnh ở chế độ chỉ đọc -@msg Script file is open for writing Tệp của tập lệnh đang được mở để ghi @msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng @msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục @msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 52440db23c..a7e94e826f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5636,8 +5636,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 无法写入脚本的文件 @msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 @msg Script file is not open for writing 脚本的文件未以写入方式打开 -@msg Script file is read-only 脚本的文件为只读 -@msg Script file is open for writing 脚本的文件已以写入方式打开 @msg Script file name is already in use 脚本的文件名已被使用 @msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 @msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a12a6a61cc..3a86a5b728 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2977,8 +2977,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 無法寫入指令碼的檔案 @msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 @msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 -@msg Script file is read-only 指令碼的檔案為唯讀 -@msg Script file is open for writing 指令碼的檔案已以寫入方式開啟 @msg Script file name is already in use 指令碼的檔案名稱已在使用中 @msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 @msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 diff --git a/docs/mcp.md b/docs/mcp.md index 19d84e1338..1cd45bb76d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3004,6 +3004,8 @@ other files through `$`: themselves, such as a path's fill, are not defined yet and read as `undefined`. - `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. + Each method sends command warnings to the Script Console with its name as the prefix: `Document.saveAs: `, + `Document.exportFile: ` or `app.open: `. Without options, `saveAs` selects the format from the supplied name before following a link. `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `file` is a `File`. `new IllustratorSaveOptions()`, `new EPSSaveOptions()` and `new PDFSaveOptions()` pick the @@ -3073,14 +3075,16 @@ other files through `$`: 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 + `horizontalScale` and `verticalScale` assigned, the other keeps its value in the settings `print` starts from. + With no scale or tiling assigned, `fitToPage = false` clears a base fit mode and preserves other base scaling modes. + `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. `printerName` and `PPDName` take 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, 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 + `PrintingBounds.ARTWORKBOUNDS`, `INRIPSEPARATION` or `PSLEVEL1`, throws an error that says it + is not available yet. Print scale factors must be from 1 to 1000 percent. 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 diff --git a/docs/progress/script-file-print.md b/docs/progress/script-file-print.md new file mode 100644 index 0000000000..b4e8ce65a9 --- /dev/null +++ b/docs/progress/script-file-print.md @@ -0,0 +1 @@ +Scripts return usable File objects from print job options, select Save As formats before resolving links, and report save, export, and open warnings in the Script Console. Saves and exports reject generated targets that already name directories before writing any output. Print options preserve base tiling when fitToPage is false and validate scale factors from 1 to 1000 percent at assignment. New message keys use English fallback text. From 15ea1ad7f14e4e24605e5d761d4cf51f61275c02 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:16:08 -0800 Subject: [PATCH 05/42] Scripts: a panic during print closes the script fence again Document.print opens the fence for file.print and closes it after the command returns. A panic in that command skipped the close, so a later run in the same session could call vc.run('file.print'). The end of each run slice now clears the marker together with script_in_run. --- crates/engine/src/script/dom/print.rs | 4 ++++ crates/engine/src/script/mod.rs | 4 ++++ crates/engine/src/tests/script_print.rs | 16 ++++++++++++++++ 3 files changed, 24 insertions(+) diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index 374b2d8248..c04499a6e0 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -984,6 +984,10 @@ const PRINT: &str = "file.print"; /// only `id` passes the fence, and only for this one command. fn unfenced(h: &Host, id: &'static str, params: &Value) -> Answer { h.session.borrow_mut().script_unfenced = Some(id); + #[cfg(test)] + if crate::script::PANIC_WHILE_UNFENCED.with(std::cell::Cell::get) { + panic!("a command past the fence failed"); + } let r = command(h, id, params); h.session.borrow_mut().script_unfenced = None; r diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index bc6ae00250..3575a34603 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2686,6 +2686,8 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result> = const { Cell::new(None) }; /// Tests: makes the next slice panic. pub(crate) static PANIC_IN_SLICE: Cell = 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 = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; /// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`]. diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index 5c138066c9..a874c5d892 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -118,6 +118,22 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() { 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}"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn print_without_a_file_does_not_print() { let base = folder("no-file"); From e916bef12542889a6bcfd972a8288505259473f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:42:47 -0800 Subject: [PATCH 06/42] Scripts: print and save options follow what the script assigned - An assigned empty artboardRange prints every artboard instead of the saved range. - Save and export refuse two destinations that resolve to the same file. - Script file paths that are not valid UTF-8 are refused. - PrintJobOptions.file keeps the assigned File, so a later name change is printed to. - app.open of a template link opens an untitled copy. - CUSTOMPROFILE with no profile assigned or saved is refused before printing. - A destination named .ps writes PostScript. - The save description limits its no-write guarantee to failures found before writing. --- crates/engine/src/cmd/fileio/export_names.rs | 13 +++ crates/engine/src/cmd/fileio/save.rs | 3 +- crates/engine/src/file_access.rs | 2 +- crates/engine/src/script/dom/print.rs | 17 +++- crates/engine/src/script/dom/save_open.rs | 14 ++- crates/engine/src/tests/script_print.rs | 90 +++++++++++++++++ crates/engine/src/tests/script_save_open.rs | 101 +++++++++++++++++++ crates/js/src/heap.rs | 8 +- crates/js/src/host.rs | 97 ++++++++++++++++-- crates/js/src/host_classes.rs | 30 +++++- crates/js/src/interp.rs | 4 + crates/js/src/realm.rs | 7 +- docs/mcp.md | 19 ++-- 13 files changed, 375 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 8ed2778d16..3c80bfb72f 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -90,6 +90,7 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do super::may_write(p)?; super::access::regular_write_target(p)?; } + distinct_write_targets(files.iter().map(|(p, _)| p.as_str()))?; } for (p, bytes) in &files { write_file(p, bytes)?; @@ -109,6 +110,18 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do Ok(merge(out, extra)) } +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn distinct_write_targets<'a>(paths: impl IntoIterator) -> Result<()> { + let mut targets = std::collections::HashSet::new(); + for path in paths { + let real = crate::file_access::resolve(path).map_err(EngineError::Other)?; + if !targets.insert(real) { + return Err(EngineError::Other("output destinations resolve to the same file".into())); + } + } + Ok(()) +} + /// `a` with the fields of `b`. pub(crate) fn merge(mut a: Value, b: Value) -> Value { if let (Some(a), Value::Object(b)) = (a.as_object_mut(), b) { diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 8a062c46ef..8a486768c9 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1084,6 +1084,7 @@ impl SaveJob { for (p, _) in &files { super::access::regular_write_target(p).map_err(|e| if plan.path_given { e } else { super::access::naming_in_error(e, p) })?; } + super::export_names::distinct_write_targets(files.iter().map(|(p, _)| p.as_str()))?; } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { @@ -1389,7 +1390,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; an access-rule, file-type or destination-collision failure found before writing leaves every file unchanged; a later write failure can leave earlier files written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 96089ae75e..277854c9ed 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -501,7 +501,7 @@ pub(crate) fn finish_recording_writes(succeeded: bool) -> Vec { /// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest /// existing folder's links followed and the rest appended. -fn resolve(path: &str) -> Result { +pub(crate) fn resolve(path: &str) -> Result { if path.is_empty() { return Err("automation path rejected: path is empty".into()); } diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index c04499a6e0..162b8a6fff 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -522,6 +522,7 @@ struct Job { paper_size: bool, /// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says. source: bool, + custom: bool, /// `printArea` is assigned: the artboards print even when the base settings ignore them. print_area: bool, /// The groups of `settings`: the top level and each nested object by its key. @@ -657,6 +658,9 @@ fn map_job(h: &Host, slot: usize, job: &mut Job) { if let Some(range) = job.range.as_ref().filter(|_| value("printAllArtboards").is_none()) { s.insert("range".into(), json!(range)); } + if job.range.is_none() && value("printAllArtboards").is_none() { + s.insert("artboards".into(), json!("all")); + } } "printArea" => job.print_area = true, _ => {} @@ -669,6 +673,7 @@ fn map_color(h: &Host, slot: usize, job: &mut Job) { let source = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "SOURCEPROFILE"); job.profile = set.iter().find(|(k, _)| *k == "name").map(|(_, v)| string_of(v)); job.source = source; + job.custom = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "CUSTOMPROFILE"); let g = job.group("color"); for (k, v) in &set { if *k == "intent" { @@ -866,7 +871,7 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { p.insert("preset".into(), json!(preset)); } // The format follows the name `jobOptions.file` gives, not the real path a link leads to. - let postscript = job.level.is_some() || crate::cmd::fileio::extension(path) == "ps"; + let postscript = job.level.is_some() || path.rsplit(['/', '\\']).next().is_some_and(|name| name.to_lowercase().ends_with(".ps")); p.insert("format".into(), json!(if postscript { "postscript" } else { "pdf" })); // PostScript prints at the level the options read as: an unassigned `postScriptLevel` is `PSLEVEL2`. if postscript { @@ -876,7 +881,7 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { if !settings.is_empty() { p.insert("settings".into(), Value::Object(settings)); } - p.insert("path".into(), json!(plain(real))); + p.insert("path".into(), json!(plain(real)?)); let printed = exactly(h, || on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, &Value::Object(p))))?; // What the job lost or how its options apply: one Script Console line each. let warnings = match &printed { @@ -899,10 +904,11 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { /// name (any case) and a paper by its id or label. An empty name, or one with a path separator or /// a control character, throws. fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> { - let (count, saved_ignore, saved_fit) = with_doc(h, doc, |_, st| { + let (count, saved_ignore, saved_fit, mut base_profile) = with_doc(h, doc, |_, st| { let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str); let fit = st.doc.print_setup.as_ref().and_then(|v| v.get("scaling")).and_then(Value::as_str) == Some("fit"); - (st.doc.artboards.len(), mode == Some("ignore"), fit) + let profile = st.doc.print_setup.as_ref().and_then(|v| v.get("color")).and_then(|v| v.get("profile")).and_then(Value::as_str); + (st.doc.artboards.len(), mode == Some("ignore"), fit, profile.unwrap_or("").to_string()) }); if let Some(range) = &job.range { vectorcraft_doc::range::parse_range(range, count).map_err(|e| HostError::Range(format!("PrintJobOptions.artboardRange: {e}")))?; @@ -915,6 +921,7 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos let preset = s.print_preset_settings(n).ok_or_else(|| no_such("PrintOptions.printPreset", "print preset", &name))?; base_ignore = matches!(preset.artboards, vectorcraft_pdf::PrintArtboards::Ignore); base_fit = matches!(preset.scaling, vectorcraft_pdf::PrintScaling::Fit); + base_profile.clone_from(&preset.color.profile); job.preset = Some(n.to_string()); } if job.clear_fit && base_fit { @@ -944,6 +951,8 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos if !job.source { job.group("color").insert("profile".into(), json!(profile.name)); } + } else if job.custom && base_profile.trim().is_empty() { + return Err(HostError::Error("PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE".into())); } if let Some(name) = job.paper.take() { let n = plain_name("PrintPaperOptions.name", "paper", &name)?; diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index da29f70d61..613a946a65 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -568,8 +568,11 @@ pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { } /// The path to give a command for the real path `real`. -pub(super) fn plain(real: std::path::PathBuf) -> String { - crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() +pub(super) fn plain(real: std::path::PathBuf) -> std::result::Result { + crate::cmd::findfiles::plain(real) + .into_os_string() + .into_string() + .map_err(|_| HostError::Error("Script file path is not valid UTF-8".into())) } /// `document.saveAs(file, options?)`: `file.saveAs` on the document, in the format the options' @@ -601,7 +604,7 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { p.insert("format".into(), json!(format)); } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; - p.insert("path".into(), json!(plain(real))); + p.insert("path".into(), json!(plain(real)?)); let result = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; report_warnings(h, "Document.saveAs", &result); Ok(Data::Undefined) @@ -669,7 +672,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { } let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; - p.insert("path".into(), json!(plain(real))); + p.insert("path".into(), json!(plain(real)?)); let result = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; report_warnings(h, "Document.exportFile", &result); Ok(Data::Undefined) @@ -711,7 +714,8 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } } let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; - p.insert("path".into(), json!(plain(real))); + plain(real)?; + p.insert("path".into(), json!(path)); let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; report_warnings(h, "app.open", &r); let index = match &r { diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index a874c5d892..8325cb6c48 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -57,6 +57,96 @@ fn pages(path: &Path) -> Vec<(f64, f64)> { info.pages.iter().map(|p| (p.width.round(), p.height.round())).collect() } +#[test] +fn print_blank_assigned_range_clears_the_saved_range() { + let base = folder("blank-range"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap(); + for (name, range) in [("empty.pdf", ""), ("spaces.pdf", " ")] { + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); + o.jobOptions.artboardRange = '{}'; app.activeDocument.print(o);", + quoted(&dir.join(name)), range + ), + ); + assert_eq!(pages(&dir.join(name)).len(), s.active().unwrap().doc.artboards.len()); + } + assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["range"], json!("1")); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn print_uses_the_assigned_file_object_after_its_path_changes() { + let base = folder("file-reference"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(), f = new File({}); o.jobOptions.file = f; + vc.log(o.jobOptions.file === f); vc.log(f.changePath({})); + app.activeDocument.print(o); vc.log(o.jobOptions.file === f); + vc.log(f.rename('renamed.pdf')); app.activeDocument.print(o); + o.jobOptions.file = null; vc.log(o.jobOptions.file == null);", + quoted(&dir.join("old.pdf")), quoted(&dir.join("new.ps")) + ), + ); + assert_eq!(out, json!([true, true, true, true, true])); + assert!(!dir.join("old.pdf").exists()); + assert!(!dir.join("new.ps").exists()); + assert!(std::fs::read(dir.join("renamed.pdf")).unwrap().starts_with(b"%PDF")); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn print_custom_profile_requires_an_assigned_or_base_profile() { + let base = folder("custom-profile-required"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let path = dir.join("custom.pdf"); + std::fs::write(&path, "original").unwrap(); + let script = format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); + o.colorManagementOptions.colorProfileMode = PrintColorProfile.CUSTOMPROFILE; app.activeDocument.print(o);", + quoted(&path) + ); + let error = failure(&mut s, &base, &script); + assert!(error.contains("must name a color profile for CUSTOMPROFILE"), "{error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + s.execute("print.setup", &json!({"settings": {"color": {"profile": "sRGB IEC61966-2.1"}}})).unwrap(); + logged(&mut s, &base, &script); + assert!(std::fs::read(&path).unwrap().starts_with(b"%PDF")); + let preset_script = script.replace("app.activeDocument.print(o);", "o.printPreset = '[Default]'; app.activeDocument.print(o);"); + let error = failure(&mut s, &base, &preset_script); + assert!(error.contains("must name a color profile for CUSTOMPROFILE"), "{error}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn print_dot_ps_file_names_write_postscript() { + let base = folder("dot-ps"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for name in [".ps", ".PS"] { + let path = dir.join(name); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", + quoted(&path) + ), + ); + assert!(std::fs::read(&path).unwrap().starts_with(b"%!PS")); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() { let base = folder("happy"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index a642aac12b..391d1de206 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -50,6 +50,107 @@ fn quoted(p: &Path) -> String { serde_json::to_string(&p.to_string_lossy()).unwrap() } +#[test] +fn save_description_limits_the_preflight_guarantee() { + let params = crate::cmd::find_command("document.save").unwrap().params; + assert!(params.contains("failure found before writing leaves every file unchanged")); + assert!(params.contains("a later write failure can leave earlier files written")); +} + +#[cfg(unix)] +#[test] +fn svg_save_and_export_refuse_resolved_destination_collisions() { + let base = folder("svg-collision"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pic = base.join("outside/pic.png"); + std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": false})).unwrap(); + let svg = dir.join("a.svg"); + let export = format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&svg)); + logged(&mut s, &base, &format!("Folder.userData; {export}")); + s.execute("file.saveAs", &json!({"path": svg.to_string_lossy(), "format": "svg", "images": "link"})).unwrap(); + let images: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect(); + assert_eq!(images.len(), 1); + std::fs::remove_file(&images[0]).unwrap(); + std::os::unix::fs::symlink(&svg, &images[0]).unwrap(); + for call in [export, format!("app.activeDocument.saveAs(new File({}));", quoted(&svg))] { + std::fs::write(&svg, "original").unwrap(); + let error = failure(&mut s, &base, &format!("Folder.userData; {call}")); + assert!(error.contains("resolve to the same file"), "{error}"); + assert_eq!(std::fs::read(&svg).unwrap(), b"original"); + assert!(std::fs::symlink_metadata(&images[0]).unwrap().file_type().is_symlink()); + } + let _ = std::fs::remove_dir_all(base); +} + +#[cfg(unix)] +#[test] +fn script_file_commands_refuse_non_utf8_resolved_paths() { + use std::os::unix::ffi::OsStringExt; + + let base = folder("non-utf8-target"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let original = dir.join("original.vectorcraft"); + s.execute("file.saveAs", &json!({"path": original.to_string_lossy()})).unwrap(); + let bytes = std::fs::read(&original).unwrap(); + let target = dir.join(std::ffi::OsString::from_vec(b"target-\xff.vectorcraft".to_vec())); + std::fs::write(&target, &bytes).unwrap(); + let link = dir.join("alias.vectorcraft"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + let lossy = PathBuf::from(target.to_string_lossy().into_owned()); + std::fs::write(&lossy, &bytes).unwrap(); + for call in [ + "app.activeDocument.saveAs(f);", + "app.activeDocument.exportFile(f, ExportType.SVG);", + "app.open(f);", + ] { + let alias = if call.contains("exportFile") { + let alias = dir.join("alias.svg"); + std::os::unix::fs::symlink(&target, &alias).unwrap(); + alias + } else { + link.clone() + }; + let count = s.documents().len(); + let error = failure(&mut s, &base, &format!("Folder.userData; var f = new File({}); {call}", quoted(&alias))); + assert!(error.contains("Script file path is not valid UTF-8"), "{call}: {error}"); + assert_eq!(s.documents().len(), count); + assert_eq!(std::fs::read(&target).unwrap(), bytes); + assert_eq!(std::fs::read(&lossy).unwrap(), bytes); + } + let _ = std::fs::remove_dir_all(base); +} + +#[cfg(unix)] +#[test] +fn open_template_link_creates_an_untitled_copy() { + let base = folder("template-link"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let target = dir.join("drawing.vectorcraft"); + s.execute("file.saveAs", &json!({"path": target.to_string_lossy()})).unwrap(); + let link = dir.join("drawing.vctemplate"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + let count = s.documents().len(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&link))); + assert_eq!(s.documents().len(), count + 1); + assert!(s.active().unwrap().path.is_none()); + assert_ne!(s.active().unwrap().title(), "drawing.vectorcraft"); + assert!(!s.active().unwrap().doc.template); + let template = dir.join("source.vctemplate"); + std::fs::write(&template, std::fs::read(&target).unwrap()).unwrap(); + let document = dir.join("alias.vectorcraft"); + std::os::unix::fs::symlink(&template, &document).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&document))); + assert!(s.active().unwrap().path.is_some()); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn save_as_export_file_and_open_write_and_read_where_the_script_may() { let base = folder("happy"); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 8f6190a63d..64a362d609 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -1243,7 +1243,13 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u extra = std::mem::size_of::>() + PROP_BYTES * fields.len(); } Class::UnitValue(_) => extra = UNIT_VALUE_BYTES, - Class::Host(h) => extra = crate::host_classes::handle_bytes(h.handle.len()), + Class::Host(h) => { + for (_, file, _) in &h.files { + mark_value(file, work, strings); + } + extra = crate::host_classes::handle_bytes(h.handle.len()) + + h.files.iter().map(|(name, _, path)| PROP_BYTES + name.len() + path.len()).sum::(); + } Class::Promise(p) => { for v in p.values() { mark_value(&v, work, strings); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index dc5201f856..b8a5c4fe83 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -119,6 +119,16 @@ pub(crate) enum ArgRead { /// [`Data`], objects of host classes in them as [`crate::host_ref`] gives them; the objects of /// host classes in the result are made from theirs. Hosted, + /// A read of a host property whose reflected type is `File`. + HostedFileGet, + /// An assignment to a host property whose reflected type is `File`. + HostedFileSet, +} + +impl ArgRead { + fn hosted(&self) -> bool { + matches!(self, Self::Hosted | Self::HostedFileGet | Self::HostedFileSet) + } } /// A member of an object the host adds to the global environment. @@ -434,9 +444,12 @@ impl Interp { /// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to /// the script. pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { + if how.hosted() { + self.sync_host_files()?; + } let data = match how { ArgRead::Site => site_data(self.call_site()), - ArgRead::Hosted => self.read_args(name, Some(this), args, how)?, + how if how.hosted() => self.read_args(name, Some(this), args, how)?, _ => self.read_args(name, None, args, how)?, }; // Only the script's own code, in a run that can pause, can wait for a result, and a host @@ -445,12 +458,25 @@ impl Interp { self.can_wait.set(can_wait); let result = f(data); self.can_wait.set(false); + if result.is_ok() + && let Some(id) = this.as_object() + { + if matches!(how, ArgRead::HostedFileSet) { + let file = args.first().cloned().unwrap_or(Value::Undefined); + self.keep_host_file(id, name.clone(), file)?; + } else if matches!(how, ArgRead::HostedFileGet) + && let Class::Host(h) = &self.object(id)?.class + && let Some((_, file, _)) = h.files.iter().find(|(n, _, _)| n == name) + { + return Ok(file.clone()); + } + } match result { - Ok(d) if matches!(how, ArgRead::Hosted) => self.write_hosted(d), + Ok(d) if how.hosted() => self.write_hosted(d), Ok(d) => self.write_data(d, 0, matches!(how, ArgRead::Frozen)), Err(HostError::Wait) if can_wait => { self.waiting = true; - self.waiting_hosted = matches!(how, ArgRead::Hosted); + self.waiting_hosted = how.hosted(); self.pause.set(true); Ok(Value::Undefined) } @@ -459,6 +485,59 @@ impl Interp { } } + fn keep_host_file(&mut self, id: ObjId, name: Rc, file: Value) -> JsResult<()> { + let path = match file.as_object() { + Some(file) => crate::file_classes::file_path(self, file)?, + None => None, + }; + let Class::Host(h) = &self.object(id)?.class else { return Ok(()) }; + let before = h.files.iter().find(|(n, _, _)| n == &name).map_or(0, |(n, _, p)| PROP_BYTES + n.len() + p.len()); + let after = path.as_ref().map_or(0, |p| PROP_BYTES + name.len() + p.len()); + if after > before { + self.reserve_heap(after - before)?; + } + self.heap.bytes = self.heap.bytes.saturating_sub(before).saturating_add(after); + if let Class::Host(h) = &mut self.object_mut(id)?.class { + h.files.retain(|(n, _, _)| n != &name); + if let Some(path) = path { + h.files.push((name, file, path)); + } + } + if after > 0 && !self.host_file_objects.contains(&id) { + self.host_file_objects.push(id); + } else if after == 0 && matches!(&self.object(id)?.class, Class::Host(h) if h.files.is_empty()) { + self.host_file_objects.retain(|&kept| kept != id); + } + Ok(()) + } + + fn sync_host_files(&mut self) -> JsResult<()> { + let mut updates = Vec::new(); + for id in self.host_file_objects.clone() { + self.use_fuel()?; + let Some(object) = self.heap.object(id) else { continue }; + let Class::Host(h) = &object.class else { continue }; + let Some(class) = self.host_classes.get(h.class as usize) else { continue }; + for (name, file, previous) in &h.files { + let Some(file_id) = file.as_object() else { continue }; + if crate::file_classes::file_path(self, file_id)?.as_ref() != Some(previous) + && let Some((_, set)) = class.file_setters.iter().find(|(n, _)| n == name) + { + updates.push((id, name.clone(), file.clone(), set.clone())); + } + } + } + for (id, name, file, set) in updates { + self.use_fuel()?; + let data = self.read_args(&name, Some(&Value::Object(id)), std::slice::from_ref(&file), &ArgRead::Hosted)?; + if let Err(error) = set(data) { + return Err(self.host_error(error)?); + } + self.keep_host_file(id, name, file)?; + } + Ok(()) + } + /// Where the innermost frame of the script's code is: its source's tag and the line and column /// of the instruction it is running. fn call_site(&self) -> CallSite { @@ -546,7 +625,7 @@ impl Interp { ancestors: Vec::new(), path: Vec::new(), function: name.clone(), - hosted: matches!(how, ArgRead::Hosted), + hosted: how.hosted(), }; let args = match how { ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), @@ -562,14 +641,20 @@ impl Interp { } // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); - if !matches!(how, ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Hosted) { + if !matches!(how, ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen) && !how.hosted() { self.temp_roots.extend(args.iter().cloned()); } let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); let d = match how { - ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading), + ArgRead::Data + | ArgRead::DataWithin(_) + | ArgRead::Frozen + | ArgRead::Site + | ArgRead::Hosted + | ArgRead::HostedFileGet + | ArgRead::HostedFileSet => self.read_data(a, &mut reading), ArgRead::Text => self.read_text(a, &mut reading), ArgRead::Each(list) => match list.get(i) { Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 7f20a30adf..d6e7d728ac 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -117,6 +117,8 @@ pub struct HostClass { pub(crate) struct HostObj { pub(crate) class: u32, pub(crate) handle: Rc<[f64]>, + /// The assigned File objects and the paths last sent to their setters. + pub(crate) files: Vec<(Rc, Value, String)>, } /// The estimated bytes an object of a host class holds beyond [`crate::heap::OBJECT_BYTES`] for a @@ -146,6 +148,7 @@ pub(crate) struct Entry { unavailable: Rc>, /// The class's own members as `reflect` lists them. members: Rc<[Reflected]>, + pub(crate) file_setters: Vec<(Rc, HostFunction)>, } /// How a script may use a member of a host class. @@ -304,7 +307,7 @@ impl Interp { } let extra = handle_bytes(handle.len()); self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(extra))?; - let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); + let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into(), files: Vec::new() }), Some(proto)); o.extensible = false; let id = self.heap.alloc_object(o); self.heap.bytes = self.heap.bytes.saturating_add(extra); @@ -478,6 +481,17 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { own: Rc::new(names(own_members)), unavailable: Rc::new(names(unavailable)), members, + file_setters: class + .members + .iter() + .filter_map(|(name, member)| { + let HostMember::Property { set, .. } = member else { return None }; + if !class.info.iter().any(|(n, info)| n == name && info.data_type == "File") { + return None; + } + Some((format!("{}.{name}", class.name).into(), set.clone())) + }) + .collect(), }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) @@ -526,9 +540,11 @@ fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult Prop::Accessor { get: Some(hosted_function(i, f.clone(), &full)), set: None, flags: ENUMERABLE }, HostMember::Property { get, set } => { - let get = hosted_function(i, get.clone(), &full); + let file = class.info.iter().any(|(n, info)| n == name && info.data_type == "File"); + let get = hosted_function_read(i, get.clone(), &full, if file { ArgRead::HostedFileGet } else { ArgRead::Hosted }); i.temp_roots.push(Value::Object(get)); - Prop::Accessor { get: Some(get), set: Some(hosted_function(i, set.clone(), &full)), flags: ENUMERABLE } + let set = hosted_function_read(i, set.clone(), &full, if file { ArgRead::HostedFileSet } else { ArgRead::Hosted }); + Prop::Accessor { get: Some(get), set: Some(set), flags: ENUMERABLE } } HostMember::Method(f) => Prop::Data { value: Value::Object(hosted_function(i, f.clone(), &full)), flags: 0 }, HostMember::Unavailable(f) => { @@ -551,6 +567,10 @@ fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult ObjId { - let proto = i.intrinsics.function_proto; - i.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read: ArgRead::Hosted }), Some(proto))) + hosted_function_read(i, f, name, ArgRead::Hosted) +} + +fn hosted_function_read(i: &mut Interp, f: HostFunction, name: &str, read: ArgRead) -> ObjId { + let proto = i.intrinsics.function_proto; + i.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read }), Some(proto))) } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index fa4b649e74..a2f705eff2 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -352,6 +352,8 @@ pub(crate) struct Interp { /// the same one give the same object. It is not a root: an entry whose object was collected is /// dropped after each collection. pub(crate) host_objects: crate::host_classes::Made, + /// Host objects with assigned Files stay reachable until the next script run. + pub(crate) host_file_objects: Vec, /// `UnitValue`, once a host has added it ([`crate::Realm::add_unit_values`]). Until then the /// operators take no object as a measurement. pub(crate) unit_values: Option, @@ -679,6 +681,7 @@ impl Interp { host_classes: Vec::new(), write_hosted: false, host_objects: crate::host_classes::Made::default(), + host_file_objects: Vec::new(), unit_values: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), @@ -964,6 +967,7 @@ impl Interp { roots.objects.extend(self.script_ui.iter().flat_map(crate::scriptui::Classes::objects)); roots.objects.extend(self.xmp.iter().flat_map(crate::xmp_classes::Classes::objects)); roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects)); + roots.objects.extend(self.host_file_objects.iter().copied()); roots.values.extend(self.symbols.root_values()); roots.objects.extend(self.symbols.root_objects()); roots.objects.extend(self.unit_values.iter().map(crate::unit_value::Classes::object)); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 439b231d16..571c9e47c1 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use crate::bytecode::CodeKind; -use crate::heap::{Func, HIDDEN, Object, Prop, key}; +use crate::heap::{Class, Func, HIDDEN, Object, Prop, key}; use crate::interp::{Abrupt, CompileError, Interp}; use crate::module::{LinkFail, ModuleLimits, ModuleLoader}; use crate::value::Value; @@ -745,6 +745,11 @@ impl Realm { pub fn reset_folder_current(&mut self) -> Result<(), RunError> { self.interp.last_thrown = Value::Undefined; self.interp.last_error = Value::Null; + for id in std::mem::take(&mut self.interp.host_file_objects) { + if let Class::Host(host) = &mut self.interp.object_mut(id).map_err(|_| internal_error("missing host file object"))?.class { + host.files.clear(); + } + } match crate::file_classes::reset_current(&mut self.interp) { Ok(()) => Ok(()), Err(e) => self.outcome(Err(e)).map(drop), diff --git a/docs/mcp.md b/docs/mcp.md index f00f901bf0..d1d4f37965 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3124,7 +3124,9 @@ through `$`: each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, `EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`. VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the - command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open + command runs. A resolved path that is not valid UTF-8 throws before the command runs. `app.open` keeps the + supplied name for format detection, so a `.vctemplate` link to a native document opens an untitled copy. + A path outside the script's folders throws `Script file access denied`, also when it is an open document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is read-only`; a file a `File` object holds open for writing throws `Script file is open for writing` on `saveAs` and `exportFile`, and `Script file access denied` when a command would write it besides the file named; and the @@ -3134,7 +3136,9 @@ through `$`: format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and - when one of those files may not be written, none of them is. A listed option that is not mapped is accepted at its help page's default, and any other value throws + an access-rule, file-type or destination-collision failure found before writing leaves every file unchanged. + Destinations that resolve to the same file are refused. A later write failure can leave earlier files written. + A listed option that is not mapped is accepted at its help page's default, and any other value throws an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`; properties the help pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default keeps the preset's value. A bad value throws an error before anything is written. @@ -3162,14 +3166,16 @@ through `$`: `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 + names. `jobOptions.file` keeps the assigned File object and uses its current path when printing. + The file is checked as `saveAs` checks its file: PostScript when the name ends with `.ps` (any case, including `.ps` alone) or `postScriptLevel` is assigned, a print-ready PDF otherwise, also when that name is a link to a file with another extension. The PostScript is level 2 when `postScriptLevel` is not assigned, the default it reads as. Without a file it throws `Printing to a printer is not available to scripts yet`, and `app.printerList` throws an error that says it is not available yet. `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 + from, which prints when those settings print a range. An assigned empty or whitespace-only range prints every + artboard. `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. With no scale or tiling assigned, `fitToPage = false` clears a base fit mode and preserves other base scaling modes. @@ -3177,7 +3183,8 @@ through `$`: 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 + and `width` or `height` is assigned above 0. `CUSTOMPROFILE` requires an assigned profile name or a profile in + the base settings; otherwise `print` throws before writing. 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. `printerName` and `PPDName` take only `""`. A listed option that is not mapped, or a value that is not mapped such as `PrintingBounds.ARTWORKBOUNDS`, `INRIPSEPARATION` or `PSLEVEL1`, throws an error that says it is not available yet. Print scale factors must be from 1 to 1000 percent. Each value is checked when it is assigned: a wrong type, a number that is not finite or is From 9fb897457509ad28c6d5dfd160df314ec72bc4e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:28:06 -0800 Subject: [PATCH 07/42] fmt: format the print and save script changes --- crates/engine/src/script/dom/save_open.rs | 5 +---- crates/engine/src/tests/script_print.rs | 11 +++++------ crates/engine/src/tests/script_save_open.rs | 6 +----- 3 files changed, 7 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 613a946a65..85074812f2 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -569,10 +569,7 @@ pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { /// The path to give a command for the real path `real`. pub(super) fn plain(real: std::path::PathBuf) -> std::result::Result { - crate::cmd::findfiles::plain(real) - .into_os_string() - .into_string() - .map_err(|_| HostError::Error("Script file path is not valid UTF-8".into())) + crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| HostError::Error("Script file path is not valid UTF-8".into())) } /// `document.saveAs(file, options?)`: `file.saveAs` on the document, in the format the options' diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index 8325cb6c48..3e1a68dc89 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -70,7 +70,8 @@ fn print_blank_assigned_range_clears_the_saved_range() { &format!( "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); o.jobOptions.artboardRange = '{}'; app.activeDocument.print(o);", - quoted(&dir.join(name)), range + quoted(&dir.join(name)), + range ), ); assert_eq!(pages(&dir.join(name)).len(), s.active().unwrap().doc.artboards.len()); @@ -93,7 +94,8 @@ fn print_uses_the_assigned_file_object_after_its_path_changes() { app.activeDocument.print(o); vc.log(o.jobOptions.file === f); vc.log(f.rename('renamed.pdf')); app.activeDocument.print(o); o.jobOptions.file = null; vc.log(o.jobOptions.file == null);", - quoted(&dir.join("old.pdf")), quoted(&dir.join("new.ps")) + quoted(&dir.join("old.pdf")), + quoted(&dir.join("new.ps")) ), ); assert_eq!(out, json!([true, true, true, true, true])); @@ -137,10 +139,7 @@ fn print_dot_ps_file_names_write_postscript() { logged( &mut s, &base, - &format!( - "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", - quoted(&path) - ), + &format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", quoted(&path)), ); assert!(std::fs::read(&path).unwrap().starts_with(b"%!PS")); } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 391d1de206..1006f9698a 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -103,11 +103,7 @@ fn script_file_commands_refuse_non_utf8_resolved_paths() { std::os::unix::fs::symlink(&target, &link).unwrap(); let lossy = PathBuf::from(target.to_string_lossy().into_owned()); std::fs::write(&lossy, &bytes).unwrap(); - for call in [ - "app.activeDocument.saveAs(f);", - "app.activeDocument.exportFile(f, ExportType.SVG);", - "app.open(f);", - ] { + for call in ["app.activeDocument.saveAs(f);", "app.activeDocument.exportFile(f, ExportType.SVG);", "app.open(f);"] { let alias = if call.contains("exportFile") { let alias = dir.join("alias.svg"); std::os::unix::fs::symlink(&target, &alias).unwrap(); From 7da1dc0750f11166a390863de47296e019837839 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:01:40 -0800 Subject: [PATCH 08/42] Scripts: save, print, export and app.open check names and sizes first A multi-file save whose destination fails the access check now returns that error without calling the writer. app.open refuses a document larger than 256 MiB, checked from the file's size and again while the file is read. On Windows, print and exportFile read the format from the file name with trailing dots and spaces removed, as saveAs does. The script checker reports app.open and app['open'] as file reads. --- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/access.rs | 46 +++++++++++++++++++++ crates/engine/src/cmd/fileio/save.rs | 9 ++-- crates/engine/src/script/dom.rs | 4 ++ crates/engine/src/script/dom/print.rs | 8 +++- crates/engine/src/script/dom/save_open.rs | 24 +++++++---- crates/engine/src/script/files.rs | 9 +++- crates/engine/src/tests/save.rs | 40 ++++++++++++++++++ crates/engine/src/tests/script_print.rs | 17 ++++++++ crates/engine/src/tests/script_save_open.rs | 36 ++++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 19 +++++++-- crates/scriptcheck/src/tests.rs | 7 ++++ docs/mcp.md | 3 +- 13 files changed, 201 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 5f66067142..e8feaf17e6 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -141,7 +141,7 @@ mod formats; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; -pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder}; +pub(crate) use access::{READ_TOO_LARGE, check_images_in, check_scripts_of, with_read_limit, with_readable_settings_folder}; pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with}; #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index ae08037521..1523a2e80e 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -275,8 +275,32 @@ pub(super) fn regular_write_target(path: &str) -> Result<()> { Ok(()) } +thread_local! { + static READ_LIMIT: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +pub(crate) const READ_TOO_LARGE: &str = "File exceeds scoped read limit"; + +pub(crate) fn with_read_limit(max: usize, f: impl FnOnce() -> T) -> T { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + READ_LIMIT.with(|limit| limit.set(self.0)); + } + } + let _restore = Restore(READ_LIMIT.with(|limit| limit.replace(Some(limit.get().map_or(max, |outer| outer.min(max)))))); + f() +} + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_file(path: &str) -> Result> { + if let Some(max) = READ_LIMIT.with(std::cell::Cell::get) { + let bytes = read_file_head(path, max.saturating_add(1))?; + if bytes.len() > max { + return Err(EngineError::Other(READ_TOO_LARGE.into())); + } + return Ok(bytes); + } may_read(path)?; // A device or pipe may never end: only a regular file is read to its end. if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() { @@ -688,6 +712,28 @@ mod tests { use super::*; use crate::file_access::{AutomationRoots, confine}; + #[test] + fn scoped_read_limit_bounds_reads_and_restores_the_previous_limit() { + let path = std::env::temp_dir().join(format!("vc-access-read-limit-{}", std::process::id())); + std::fs::write(&path, b"12345").unwrap(); + let path_text = path.to_str().unwrap(); + assert_eq!(read_file(path_text).unwrap(), b"12345"); + with_read_limit(5, || { + assert_eq!(read_file(path_text).unwrap(), b"12345"); + with_read_limit(4, || { + assert_eq!(read_file(path_text).unwrap_err().to_string(), READ_TOO_LARGE); + with_read_limit(6, || assert!(read_file(path_text).is_err())); + }); + assert_eq!(read_file(path_text).unwrap(), b"12345"); + std::fs::write(&path, b"123456").unwrap(); + assert_eq!(read_file(path_text).unwrap_err().to_string(), READ_TOO_LARGE); + }); + assert_eq!(read_file(path_text).unwrap(), b"123456"); + let _ = std::panic::catch_unwind(|| with_read_limit(0, || panic!("test unwind"))); + assert_eq!(read_file(path_text).unwrap(), b"123456"); + std::fs::remove_file(path).unwrap(); + } + /// An error about a path the client did not give, under roots that don't let it be read: the /// path is named by its file name (after a `/` or a `\`), or as [`UNNAMED`] when it ends in no /// name or its name is not valid text, and every root and the reason stay whole. A path inside the diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 8a486768c9..ae46b5eef8 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1072,14 +1072,11 @@ impl SaveJob { if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::>()) { return Ok(stopped); } - // Every path is checked against the file access in force before the first file is - // written. A refused file goes to `write` first, which refuses it with the error the - // caller gives (naming the path as the caller does), so none of the files is written. - // A permitted target that is not a regular file then stops the save the same way. + // Every path is checked before the first file is written. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 { - if let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) { - write(p, bytes)?; + for (p, _) in &files { + super::may_write(p).map_err(|e| if plan.path_given { e } else { super::access::naming_in_error(e, p) })?; } for (p, _) in &files { super::access::regular_write_target(p).map_err(|e| if plan.path_given { e } else { super::access::naming_in_error(e, p) })?; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 6961088fab..2131df3540 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -100,6 +100,10 @@ mod tags; mod text; mod variables; +#[cfg(test)] +pub(crate) use print::postscript_name; +#[cfg(test)] +pub(crate) use save_open::with_extension; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; /// What [`after_command`] compares with, taken before each command a script runs diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index 162b8a6fff..f68e128392 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -850,6 +850,10 @@ fn map_postscript(h: &Host, slot: usize, job: &mut Job) { } } +pub(crate) fn postscript_name(path: &str, windows: bool) -> bool { + super::save_open::filename_for_suffix(path, windows).to_lowercase().ends_with(".ps") +} + /// `document.print(options?)`: `file.print` of the document to the file `jobOptions.file` names, /// with the assigned options over the document's print settings. fn doc_print(h: &Host, a: &[Data]) -> Answer { @@ -865,13 +869,13 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { let Some(file) = job.file.take() else { return Err(HostError::Error(NO_PRINTER.into())) }; check_names(h, doc, &mut job)?; let path = file_path(&file, "print")?; + // The format follows the name `jobOptions.file` gives, not the real path a link leads to. + let postscript = job.level.is_some() || postscript_name(path, cfg!(windows)); let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; let mut p = Map::new(); if let Some(preset) = job.preset.take() { p.insert("preset".into(), json!(preset)); } - // The format follows the name `jobOptions.file` gives, not the real path a link leads to. - let postscript = job.level.is_some() || path.rsplit(['/', '\\']).next().is_some_and(|name| name.to_lowercase().ends_with(".ps")); p.insert("format".into(), json!(if postscript { "postscript" } else { "pdf" })); // PostScript prints at the level the options read as: an unassigned `postScriptLevel` is `PSLEVEL2`. if postscript { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 85074812f2..f80b62be2d 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -608,8 +608,7 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } fn save_format_for_name(path: &str, windows: bool) -> Option<&'static crate::cmd::fileio::Format> { - let name = if windows { path.rsplit(['/', '\\']).next() } else { path.rsplit('/').next() }.unwrap_or(path); - let name = if windows { name.trim_end_matches(['.', ' ']) } else { name }; + let name = filename_for_suffix(path, windows); // A name that is only a dot and an extension, such as `.pdf`, picks its format only for the // `.ai`, `.eps` and `.pdf` options classes; any other name takes the usual extension rule. match name.rsplit_once('.') { @@ -620,10 +619,13 @@ fn save_format_for_name(path: &str, windows: bool) -> Option<&'static crate::cmd } } -/// `path` with the extension of `kind` added, unless its name already ends with one of them. -fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String { - let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions }; - let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase(); +pub(crate) fn filename_for_suffix(path: &str, windows: bool) -> &str { + let name = if windows { path.rsplit(['/', '\\']).next() } else { path.rsplit('/').next() }.unwrap_or(path); + if windows { name.trim_end_matches(['.', ' ']) } else { name } +} + +pub(crate) fn with_extension(path: &str, extensions: &[&str], windows: bool) -> String { + let name = filename_for_suffix(path, windows).to_lowercase(); match extensions.first() { Some(first) if !extensions.iter().any(|e| name.ends_with(&format!(".{e}"))) => format!("{path}.{first}"), _ => path.to_string(), @@ -667,7 +669,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { } else { p.insert("useArtboards".into(), json!(false)); } - let named = with_extension(path, &kind, svgz); + let named = with_extension(path, if svgz { &["svgz"] } else { kind.extensions }, cfg!(windows)); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; p.insert("path".into(), json!(plain(real)?)); let result = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; @@ -713,7 +715,13 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; plain(real)?; p.insert("path".into(), json!(path)); - let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; + let r = crate::cmd::fileio::with_read_limit(super::super::files::MAX_OPEN_BYTES as usize, || { + exactly(h, || command(h, "document.open", &Value::Object(p))) + }) + .map_err(|e| match e { + HostError::Error(message) if message == crate::cmd::fileio::READ_TOO_LARGE => refused(super::super::files::OPEN_TOO_LARGE, path), + e => e, + })?; report_warnings(h, "app.open", &r); let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 1cded460ab..3adac22d94 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -108,6 +108,9 @@ pub const MAX_MASK_STEPS: usize = 1 << 24; pub(crate) const ACCESS_DENIED: &str = "Script file access denied"; pub(crate) const TOO_LARGE: &str = "Script file exceeds 8 MiB"; +/// The largest document `app.open` reads, checked before the file is read. +pub(crate) const MAX_OPEN_BYTES: u64 = 256 << 20; +pub(crate) const OPEN_TOO_LARGE: &str = "Script document exceeds 256 MiB"; pub(crate) const NOT_OPEN: &str = "Script file is not open"; pub(crate) const UNDECODABLE: &str = "Script file cannot be decoded"; pub(crate) const NOT_REGULAR: &str = "Script file is not a regular file"; @@ -723,9 +726,13 @@ impl Disk { Err(ScriptRead::Refused | ScriptRead::TooLarge) => return Err(ACCESS_DENIED), Err(ScriptRead::Failed(_)) => return Err(READ_FAILED), }; - if !real.is_file() { + let meta = std::fs::metadata(&real).map_err(|_| READ_FAILED)?; + if !meta.is_file() { return Err(NOT_REGULAR); } + if meta.len() > MAX_OPEN_BYTES { + return Err(OPEN_TOO_LARGE); + } Ok(real) } diff --git a/crates/engine/src/tests/save.rs b/crates/engine/src/tests/save.rs index 98e6c0ca52..f6a2f5158c 100644 --- a/crates/engine/src/tests/save.rs +++ b/crates/engine/src/tests/save.rs @@ -177,6 +177,46 @@ fn multi_file_save_directory_errors_hide_paths_the_caller_did_not_give() { let _ = std::fs::remove_dir_all(d); } +#[test] +fn refused_multi_file_save_never_calls_the_writer() { + use crate::cmd::fileio::save_job; + use crate::file_access::{AutomationRoots, confine}; + + let d = dir("refused-writer"); + let inside = d.join("in"); + let outside = d.join("out"); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + let own = path(&outside, "doc.vectorcraft"); + s.execute("document.save", &json!({"path": own})).unwrap(); + let original = std::fs::read(&own).unwrap(); + let roots = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + for explicit in [false, true] { + let p = if explicit { json!({"path": own, "separateArtboards": true}) } else { json!({"separateArtboards": true}) }; + let plan = save_plan(&s, SaveMode::Save, &p).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let mut calls = 0; + let error = confine(roots.as_ref(), || { + job.write_unless( + |_| None, + |_, _| { + calls += 1; + Ok(()) + }, + ) + }) + .unwrap_err() + .to_string(); + assert_eq!(calls, 0); + assert!(error.contains("outside the write root"), "{error}"); + assert_eq!(error.contains(&outside.to_string_lossy().to_string()), explicit, "{error}"); + assert_eq!(std::fs::read(&own).unwrap(), original); + } + let _ = std::fs::remove_dir_all(d); +} + #[test] fn an_svg_path_writes_svg_and_save_writes_it_back() { let d = dir("svg"); diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index 3e1a68dc89..dd3f6dca75 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -9,6 +9,23 @@ use crate::*; const DENIED: &str = "Script file access denied"; +#[test] +fn postscript_suffix_recognizes_windows_filename_aliases() { + use crate::script::dom::postscript_name; + + for suffix in [".", " ", ". . ", "..."] { + for prefix in ["", "/exports/", "C:\\exports\\"] { + let name = format!("{prefix}proof.PS{suffix}"); + assert!(postscript_name(&name, true), "{name}"); + assert!(!postscript_name(&name, false), "{name}"); + } + } + for name in ["proof.pdf", "proof.ps\t", "proof.ps\u{a0}", "folder.ps/proof", "folder.ps\\proof"] { + assert!(!postscript_name(name, true), "{name}"); + } + assert!(postscript_name("proof.ps", false)); +} + /// A fresh folder for test `name`, by its real path, with `main` for the script. fn folder(name: &str) -> PathBuf { let base = std::env::temp_dir().join(format!("vc-script-print-{name}-{}", std::process::id())); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 1006f9698a..0ae5625aff 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -10,6 +10,42 @@ use crate::*; const DENIED: &str = "Script file access denied"; +#[test] +fn export_extension_recognizes_windows_filename_aliases() { + use crate::script::dom::with_extension; + + for extension in ["svg", "svgz", "jpg", "jpeg", "png"] { + for suffix in [".", " ", ". . ", "..."] { + for prefix in ["", "/exports/", "C:\\exports\\"] { + let name = format!("{prefix}drawing.{}{suffix}", extension.to_ascii_uppercase()); + assert_eq!(with_extension(&name, &[extension], true), name); + assert_eq!(with_extension(&name, &[extension], false), format!("{name}.{extension}")); + } + } + } + assert_eq!(with_extension("drawing.JPEG ", &["jpg", "jpeg"], true), "drawing.JPEG "); + assert_eq!(with_extension("drawing.svg ", &["svgz"], true), "drawing.svg .svgz"); + for name in ["drawing", "drawing.png\t", "drawing.png\u{a0}", "folder.png/drawing", "folder.png\\drawing"] { + assert_eq!(with_extension(name, &["png"], true), format!("{name}.png")); + } +} + +#[test] +fn app_open_refuses_an_oversized_document() { + let base = folder("oversized-open"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let input = dir.join("huge.svg"); + std::fs::File::create(&input).unwrap().set_len(crate::script::files::MAX_OPEN_BYTES + 1).unwrap(); + let before = s.documents().len(); + let error = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&input))); + assert!(error.contains(crate::script::files::OPEN_TOO_LARGE), "{error}"); + assert_eq!(s.documents().len(), before); + let out = logged(&mut s, &base, &format!("Folder.userData; var f = new File({}); vc.log([f.open('r'), f.error]);", quoted(&input))); + assert_eq!(out, json!([[false, crate::script::files::TOO_LARGE]])); + let _ = std::fs::remove_dir_all(base); +} + /// A fresh folder for test `name`, by its real path, with `main` for the script. fn folder(name: &str) -> PathBuf { let base = std::env::temp_dir().join(format!("vc-script-save-{name}-{}", std::process::id())); diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 3a7aab4e63..2705482e7a 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -302,11 +302,20 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if is(h0, "]") && is(h2, "[") && let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32)) - && (catalog::DOM_FILE_WRITES.contains(&name.as_str()) || (name == catalog::DOM_PRINT && self.document_print("[]()"))) { - self.acc.feature(FeatureId::FileWrite, line); - self.acc.outside(OutsideId::FilesWritten, line, None); - return; + if catalog::DOM_FILE_WRITES.contains(&name.as_str()) || (name == catalog::DOM_PRINT && self.document_print("[]()")) { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + return; + } + if name == catalog::OPEN + && word(h3, "app") + && !self.shadowed[0] + && self.suspended.last().is_some_and(|c| c.wait.saturating_add(1) == self.depth() && c.path == "app[]()") + { + self.acc.feature(FeatureId::FileRead, line); + return; + } } let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; let n = callee.text; @@ -320,6 +329,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let file = held.is_some(); if n == catalog::MENU_COMMAND { self.pending = Pending::Menu(line); + } else if n == catalog::OPEN && word(h2, "app") && !member_mark(h3) && !self.shadowed[0] { + self.acc.feature(FeatureId::FileRead, line); } else if n == catalog::OPEN && file { self.pending = Pending::Open(line); } else if catalog::DRAWING.contains(&n) { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index ba446167a9..40a4f61993 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -53,6 +53,12 @@ const FEATURE_CASES: &[(&str, &str, &str)] = &[ ("file.objects", "var f = new File(path);", "var f = new Filer(path);"), ("file.places", "var t = Folder.temp;", "var t = cache.temp;"), ("file.read", "var f = new File(p); f.open('r');", "var f = new File(p);"), + ("file.read", "app.open(f);", "var f = app.open;"), + ("file.read", "app.open(f);", "cache.app.open(f);"), + ("file.read", "app.open(f);", "var app = cache; app.open(f);"), + ("file.read", "app['open'](f);", "var f = app['open'];"), + ("file.read", "app['open'](f);", "cache.app['open'](f);"), + ("file.read", "app['open'](f);", "var app = cache; app['open'](f);"), ("file.read", "var f = new File(p); var s = f.read();", "var s = cache.read();"), ("file.read", "var all = folder.getFiles();", "var all = folder.files;"), ("file.read", "var s = File(p).read();", "var s = Cache(p).read();"), @@ -546,6 +552,7 @@ fn save_as_and_export_file_write_a_file() { "d.saveAs(f);\n", "app.activeDocument.exportFile(f, ExportType.PNG24);\n", )); + assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[2][..])); assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..])); assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } diff --git a/docs/mcp.md b/docs/mcp.md index 42432a7bf3..23b031c0e4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3102,7 +3102,8 @@ through `$`: `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. Each method sends command warnings to the Script Console with its name as the prefix: `Document.saveAs: `, `Document.exportFile: ` or `app.open: `. Without options, `saveAs` selects the format from the supplied name before following a link. - `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` + `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document`; a file + larger than 256 MiB throws `Script document exceeds 256 MiB` before it is read (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `file` is a `File`. `new IllustratorSaveOptions()`, `new EPSSaveOptions()` and `new PDFSaveOptions()` pick the format (https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, From 42cd387802d5e894a77f3016a819400c52a2ef99 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 00:22:37 -0800 Subject: [PATCH 09/42] Print: Print as Bitmap keeps its resolution at a print scale Print as Bitmap rendered at bitmapResolution in document points, so a job printed at 200%, or enlarged by Fit to Page, printed the image at a lower resolution than asked and the pixel-limit warning did not name it. The render now takes the page's horizontal and vertical print scale into account, and the warning and the preview note compare the resolution on paper. --- crates/engine/src/cmd/print.rs | 2 +- crates/engine/src/cmd/printadvanced.rs | 56 +++++++++++------ crates/engine/src/tests/printadvanced.rs | 32 ++++++++++ crates/pdf/src/print.rs | 7 +++ crates/pdf/src/print/layout.rs | 79 ++++++++++++++++-------- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 7 files changed, 134 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 612f9da868..ac40f4a187 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Print Setup", [], None, - "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete (PostScript output: subset (default) sends each page the glyphs it shows, complete sends every glyph of each font once before the first page, none sends no font and names the printer's own; PDF output embeds subsets of the fonts whose licenses allow it, and draws the others as outlines, with any of them, and none or complete adds a note)}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at bitmapResolution, or lower for a page larger than 64 Mpx or 32,768 px a side, with a warning when bitmapResolution was given), bitmapResolution: 0 (ppi Print as Bitmap renders at, 1–9600; 0: the document's raster effects resolution; other output leaves it unused), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", + "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete (PostScript output: subset (default) sends each page the glyphs it shows, complete sends every glyph of each font once before the first page, none sends no font and names the printer's own; PDF output embeds subsets of the fonts whose licenses allow it, and draws the others as outlines, with any of them, and none or complete adds a note)}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at bitmapResolution, or lower for a page larger than 64 Mpx or 32,768 px a side, with a warning when bitmapResolution was given), bitmapResolution: 0 (ppi Print as Bitmap prints at on paper, so a print scale above 100% renders more pixels, 1–9600; 0: the document's raster effects resolution; other output leaves it unused), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", has_doc, setup ), diff --git a/crates/engine/src/cmd/printadvanced.rs b/crates/engine/src/cmd/printadvanced.rs index 6b8e067e8f..c5927f3bfd 100644 --- a/crates/engine/src/cmd/printadvanced.rs +++ b/crates/engine/src/cmd/printadvanced.rs @@ -86,12 +86,28 @@ fn bitmap_ppi(doc: &Document, set: &PrintSettings) -> f64 { if asked > 0.0 { asked } else { doc.raster_effects_ppi } } -/// The pixels per point Print as Bitmap renders `area` at for `ppi`: at most MAX_PIXELS, and no -/// side longer than the renderer draws (rounded up to whole pixels when it renders). -fn bitmap_scale(area: Rect, ppi: f64) -> f64 { - let side = area.width().max(area.height()).max(1.0); +/// The pixels per document point Print as Bitmap renders `area` at so that it prints at `ppi` on +/// paper when the page scales it by `placed` on each axis (1 = 100%): at most MAX_PIXELS, and +/// no side longer than the renderer draws (rounded up to whole pixels when it renders). +fn bitmap_scale(area: Rect, ppi: f64, placed: (f64, f64)) -> (f64, f64) { + let (w, h) = (area.width() * ppi / 72.0 * placed.0, area.height() * ppi / 72.0 * placed.1); let longest = f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0; - (ppi / 72.0).min((MAX_PIXELS / (area.width() * area.height()).max(1.0)).sqrt()).min(longest / side) + let limit = 1.0_f64.min((MAX_PIXELS / (w * h).max(1.0)).sqrt()).min(longest / w.max(1.0)).min(longest / h.max(1.0)); + let (w, h) = (w * limit, h * limit); + let rounding = if whole_pixels(w) * whole_pixels(h) > MAX_PIXELS { ((MAX_PIXELS - w - h - 1.0) / (w * h)).sqrt() } else { 1.0 }; + (w * rounding / area.width(), h * rounding / area.height()) +} + +/// The whole pixels Print as Bitmap renders `len` pixels of art as: rounded up, at least 1, with +/// the rounding error of `len` scaled down and up again left out. +fn whole_pixels(len: f64) -> f64 { + (len - 1e-6).ceil().max(1.0) +} + +/// The horizontal and vertical scales (1 = 100%) the page prints the region `r` of `printed` +/// at with `set`, both 1 when it prints on no page. +fn placed_scale(printed: &Document, set: &PrintSettings, r: Rect) -> (f64, f64) { + vectorcraft_pdf::print_region_scale(printed, set, r).filter(|(x, y)| x.is_finite() && *x > 0.0 && y.is_finite() && *y > 0.0).unwrap_or((1.0, 1.0)) } /// The note on Print as Bitmap printing below the `advanced.bitmapResolution` of `set`, when the @@ -120,9 +136,12 @@ pub(crate) fn bitmap_notes(cmd: &str, doc: &Document, set: &PrintSettings) -> Re let bleed = vectorcraft_pdf::page_bleed(&set.bleed, &printed); let lowest = regions .iter() - .map(|(_, r)| outset(*r, bleed)) - .filter(|area| vectorcraft_pdf::prints_art_in(&printed, *area)) - .map(|area| bitmap_scale(area, asked) * 72.0) + .map(|(_, r)| (outset(*r, bleed), placed_scale(&printed, set, *r))) + .filter(|(area, _)| vectorcraft_pdf::prints_art_in(&printed, *area)) + .map(|(area, placed)| { + let (x, y) = bitmap_scale(area, asked, placed); + (x / placed.0).min(y / placed.1) * 72.0 + }) .reduce(f64::min); Ok(capped_note(set, lowest).into_iter().collect()) } @@ -145,27 +164,26 @@ fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: b let mut lowest: Option = None; for (_, r) in regions { let area = outset(r, bleed); - let scale = bitmap_scale(area, ppi); - if !(scale.is_finite() && scale > 0.0) { + let placed = placed_scale(doc, set, r); + let scale = bitmap_scale(area, ppi, placed); + if !(scale.0.is_finite() && scale.0 > 0.0 && scale.1.is_finite() && scale.1 > 0.0) { continue; } // Whole pixels. - let region = Rect::new( - area.x0, - area.y0, - area.x0 + (area.width() * scale).ceil().max(1.0) / scale, - area.y0 + (area.height() * scale).ceil().max(1.0) / scale, - ); - let img = renderer.render_region_with(&art, region, scale, &opts); + let width = whole_pixels(area.width() * scale.0) as u32; + let height = whole_pixels(area.height() * scale.1) as u32; + let view = Affine::scale_non_uniform(scale.0, scale.1) * Affine::translate((-area.x0, -area.y0)); + let img = renderer.render(&art, width, height, view, &opts); if img.pixels.as_chunks::<4>().0.iter().all(|px| px[3] == 0) { continue; } let key = unique_key(&out, "print-bitmap"); out.images.insert(key.clone(), ImageBlob::new("image/png", img.to_png().map_err(EngineError::Other)?)); - let xf = Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale); + let xf = Affine::translate(area.origin().to_vec2()) * Affine::scale_non_uniform(1.0 / scale.0, 1.0 / scale.1); let image = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None }; images.push(Arc::new(Node::new(out.alloc_id(), NodeKind::Image(Box::new(image))))); - lowest = Some(lowest.map_or(scale * 72.0, |l| l.min(scale * 72.0))); + let printed_ppi = (scale.0 / placed.0).min(scale.1 / placed.1) * 72.0; + lowest = Some(lowest.map_or(printed_ppi, |l| l.min(printed_ppi))); } let mut layer = Node::layer(out.alloc_id(), "Bitmap", LayerColor::Preset(0)); if let Some(children) = layer.children_mut() { diff --git a/crates/engine/src/tests/printadvanced.rs b/crates/engine/src/tests/printadvanced.rs index 454dc926f3..7d1a0e6e2e 100644 --- a/crates/engine/src/tests/printadvanced.rs +++ b/crates/engine/src/tests/printadvanced.rs @@ -222,6 +222,38 @@ fn bitmap_resolution_sets_the_printed_image_size() { assert!(p.pdf.is_empty(), "{:?}", p.pdf); } +#[test] +fn print_as_bitmap_keeps_its_resolution_at_unlinked_print_scales() { + let (mut s, _) = session(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap(); + let set = json!({ + "advanced": {"printAsBitmap": true, "bitmapResolution": 144}, + "scaling": "custom", "scale": {"width": 200, "height": 100, "linked": false} + }); + let p = printed_images(&mut s, &set); + assert_eq!((p.pdf.as_slice(), p.ps.as_slice()), ([(800, 200)].as_slice(), [(800, 200)].as_slice())); + assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{:?}", p.warnings); + let [placed] = p.placed[..] else { panic!("one image: {:?}", p.placed) }; + assert!((placed.width() - 400.0).abs() < 0.01 && (placed.height() - 100.0).abs() < 0.01, "{placed:?}"); +} + +/// Print as Bitmap prints at `bitmapResolution` on paper: a job printed at 200% renders twice the +/// pixels, and so does one that Fit to Page enlarges, so the image keeps its resolution. +#[test] +fn print_as_bitmap_keeps_its_resolution_at_a_print_scale() { + let (mut s, _) = session(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 72})).unwrap(); + let advanced = json!({"printAsBitmap": true, "bitmapResolution": 144}); + let p = printed_images(&mut s, &json!({"advanced": advanced, "scaling": "custom", "scale": {"width": 200}})); + assert_eq!((p.pdf.as_slice(), p.ps.as_slice()), ([(800, 400)].as_slice(), [(800, 400)].as_slice())); + assert!(!p.warnings.iter().any(|w| w.starts_with(CAPPED)), "{:?}", p.warnings); + let fit = printed_images(&mut s, &json!({"advanced": advanced, "scaling": "fit"})); + let [(w, _)] = fit.pdf[..] else { panic!("one image: {:?}", fit.pdf) }; + let [placed] = fit.placed[..] else { panic!("one image: {:?}", fit.placed) }; + let ppi = f64::from(w) / placed.width() * 72.0; + assert!((ppi - 144.0).abs() < 2.0, "{w} pixels across {} pt: {ppi} ppi", placed.width()); +} + /// A `bitmapResolution` given to `file.print` applies to that job alone; `print.setup` saves it. #[test] fn a_bitmap_resolution_given_to_file_print_applies_to_that_job() { diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index 52308ae89b..65c36f1c22 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -443,6 +443,13 @@ pub fn print_regions(doc: &Document, set: &PrintSettings) -> Result Option<(f64, f64)> { + layout::region_scale(printed, set, r) +} + /// Is there art that prints in `r` of `printed`, a document as [`printed_document`] gives it? pub fn prints_art_in(printed: &Document, r: kurbo::Rect) -> bool { layout::has_art(printed, r) diff --git a/crates/pdf/src/print/layout.rs b/crates/pdf/src/print/layout.rs index fcfaef6400..71ad42defb 100644 --- a/crates/pdf/src/print/layout.rs +++ b/crates/pdf/src/print/layout.rs @@ -9,7 +9,7 @@ use kurbo::{Affine, Rect, Vec2}; use serde::Serialize; -use vectorcraft_doc::marks::outset; +use vectorcraft_doc::marks::{PrinterMarks, outset}; use vectorcraft_doc::range::parse_range; use vectorcraft_doc::{Document, Node, NodeKind, SymbolBoxes}; @@ -183,6 +183,56 @@ fn turns(set: &PrintSettings, (w, h): (f64, f64), flipped: bool) -> (Affine, (f6 (v, (w, h)) } +/// The bleed at scale `s` and how far it and the marks reach around the artboard, +/// `[top, bottom, left, right]` each. +fn reach_around(marks: &PrinterMarks, bleed: [f64; 4], s: (f64, f64)) -> ([f64; 4], [f64; 4]) { + let b = scaled(bleed, s); + let reach = marks.reach(b); + (b, std::array::from_fn::(|i| b[i].max(reach[i]))) +} + +/// The horizontal and vertical scale `set` prints the artboard `r` at on `imageable` (1 = 100%); +/// `None` when Fit to Page finds no scale at which it fits with its bleed and marks. +fn print_scale(set: &PrintSettings, marks: &PrinterMarks, bleed: [f64; 4], imageable: Rect, r: Rect) -> Option<(f64, f64)> { + match set.scaling { + PrintScaling::None => Some((1.0, 1.0)), + PrintScaling::Fit => { + // The largest scale whose artboard with its bleed and marks fits: the marks reach + // further when a larger scale grows the bleed. + let fit = |s: f64| { + let (_, most) = reach_around(marks, bleed, (s, s)); + ((imageable.width() - most[2] - most[3]) / r.width()).min((imageable.height() - most[0] - most[1]) / r.height()) + }; + let first = fit(1.0); + let s = if first <= 1.0 { first } else { fit(first) }; + (s.is_finite() && s > 0.0).then_some((s, s)) + } + _ => Some((set.scale.width / 100.0, set.scale.height / 100.0)), + } +} + +/// The scale `set` prints the region `r` of `doc` at (1 = 100%), as [`layout`] works it out, +/// without laying out its pages: the horizontal and vertical scales. `None` for a +/// region with no area, a margin that leaves no imageable area, or art that doesn't fit. +pub(crate) fn region_scale(doc: &Document, set: &PrintSettings, r: Rect) -> Option<(f64, f64)> { + if !(r.width() > 0.0 && r.height() > 0.0) { + return None; + } + let (pw, ph) = set.paper(); + let landscape = match set.auto_rotate { + true => (r.width() > r.height()) != (pw > ph), + false => set.orientation.landscape(), + }; + let paper = if landscape { (ph, pw) } else { (pw, ph) }; + let m = set.margin; + let imageable = Rect::new(m, m, paper.0 - m, paper.1 - m); + if imageable.width() < 1.0 || imageable.height() < 1.0 { + return None; + } + let marks = crate::printer_marks(&set.marks); + print_scale(set, &marks, crate::page_bleed(&set.bleed, doc), imageable, r) +} + fn too_many_pages() -> PdfError { PdfError::BadSetting(format!("the job would print more than {} pages", super::MAX_PAGES)) } @@ -222,31 +272,10 @@ pub(crate) fn layout( if imageable.width() < 1.0 || imageable.height() < 1.0 { return Err(PdfError::BadSetting(format!("margin: a {m} pt margin leaves no imageable area on the paper"))); } - // How far the bleed and marks reach around the artboard at scale `s`, `[top, bottom, left, right]`. - let around = |s: (f64, f64)| { - let b = scaled(bleed, s); - let reach = marks.reach(b); - (b, std::array::from_fn::(|i| b[i].max(reach[i]))) + let Some(scale) = print_scale(set, &marks, bleed, imageable, r) else { + return Err(PdfError::BadSetting(format!("{what} doesn't fit the paper with its bleed and marks"))); }; - let scale = match set.scaling { - PrintScaling::None => (1.0, 1.0), - PrintScaling::Fit => { - // The largest scale whose artboard with its bleed and marks fits: the marks reach - // further when a larger scale grows the bleed. - let fit = |s: f64| { - let (_, most) = around((s, s)); - ((imageable.width() - most[2] - most[3]) / r.width()).min((imageable.height() - most[0] - most[1]) / r.height()) - }; - let first = fit(1.0); - let s = if first <= 1.0 { first } else { fit(first) }; - if !(s.is_finite() && s > 0.0) { - return Err(PdfError::BadSetting(format!("{what} doesn't fit the paper with its bleed and marks"))); - } - (s, s) - } - _ => (set.scale.width / 100.0, set.scale.height / 100.0), - }; - let (bleed_s, most) = around(scale); + let (bleed_s, most) = reach_around(&marks, bleed, scale); let size = (r.width() * scale.0, r.height() * scale.1); let extent = (most[2] + size.0 + most[3], most[0] + size.1 + most[1]); let flipped = !set.auto_rotate && orientation.flipped(); diff --git a/docs/mcp.md b/docs/mcp.md index e25e103277..7a5bdbd11a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13125,7 +13125,8 @@ overprints. `flattenerPreset` (High Resolution, Medium Resolution, Low Resolutio PDF keeps it live (PostScript, which has none, uses `file.print`'s `flattenerPreset`, else this one, else medium). `printAsBitmap` prints each composite page as one image of the art at `bitmapResolution`, or at the highest resolution that fits when the image would be larger than 64 million pixels or longer than 32,768 pixels a side. -`bitmapResolution` is VectorCraft's own range, 1 to 9600 ppi, and 0 (the default) prints at the document's raster +The resolution is measured on paper: a page printed at 200%, or enlarged by Fit to Page, renders that many more +pixels. `bitmapResolution` is VectorCraft's own range, 1 to 9600 ppi, and 0 (the default) prints at the document's raster effects resolution; any other value is an error. When a page prints below a `bitmapResolution` that was given, the reply's `warnings` (and `print.preview`'s) say at what resolution; a page with no art that draws prints no image and gets no warning (`print.preview` goes by the bounds of the art, without drawing it). Separations and pages that diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2be0ab3b53..4511757699 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2574,7 +2574,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - File Info has metadata templates: its menu saves the fields as an XMP file (Save Metadata Template…, into the Metadata Templates folder in the settings folder or anywhere), imports one with a choice of clearing the fields first, replacing the ones the template has, or appending to them (VectorCraft's own names for the three ways), lists the saved templates and opens Templates Folder; the import is one undo step (`file.info.saveTemplate`, `file.info.applyTemplate`, `file.info.templates`; `crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests/file_info.rs`, `crates/ui-egui/src/dialogs/file_info.rs`). A PDF or `.ai` also opens with the rating and author title its XMP packet gives. - `file.print`, `print.preview` and `print.setup` take a print preset by name (`preset`: `[Default]` or a saved preset, in any case): its settings are used instead of the document's, with `settings` over them, `print.setup` saves them with the document, and an unknown name is refused with the list of presets. - Print's Copies per Sheet (`copiesPerSheet`, `gutter`; off by default) prints as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, as one grid placed like a single copy; the preview shows them, and an artboard that does not fit prints one copy per sheet with a warning (#1283). - - Print as Bitmap renders at `advanced.bitmapResolution` (the Print dialog's Advanced › Resolution; VectorCraft's own range, 1 to 9600 ppi; 0, the default, keeps the document's raster effects resolution), in a print-ready PDF and in PostScript, for one job through `file.print`'s `settings` or saved by `print.setup`; a page that the pixel limits print at a lower resolution gets a warning that names it. A script's `PrintJobOptions.bitmapResolution` (https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/) sets it (`crates/engine/src/tests/printadvanced.rs`, `crates/engine/src/tests/script_print.rs`). + - Print as Bitmap renders at `advanced.bitmapResolution` (the Print dialog's Advanced › Resolution; VectorCraft's own range, 1 to 9600 ppi; 0, the default, keeps the document's raster effects resolution) measured on paper, so a print scale or Fit to Page that enlarges the page renders more pixels, in a print-ready PDF and in PostScript, for one job through `file.print`'s `settings` or saved by `print.setup`; a page that the pixel limits print at a lower resolution gets a warning that names it. A script's `PrintJobOptions.bitmapResolution` (https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/) sets it (`crates/engine/src/tests/printadvanced.rs`, `crates/engine/src/tests/script_print.rs`). - Place and the Links panel, Package (placed `.vectorcraft` documents packaged with their own linked files and fonts, relinked to the copies: #777), File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457). - On X11, quitting while the Paste menu's background check waits on a clipboard owner that never answers waits up to 27 s for that check to drop its clipboard handle, so the app's own handle is the last one dropped when the check drops its handle within that wait, and the app quits after the wait when it has not; the window is hidden before that wait, so an X11 window closes at once (`crates/ui-egui/src/tests/sysclip_probe.rs`, `apps/vectorcraft/src/clipboard.rs`, `apps/vectorcraft/src/quit_windows.rs`). - On Linux, quitting takes every window off screen before that wait: a native Wayland main window is unmapped (its surface gets no buffer) and stays open with the connection the Wayland clipboard uses, and the X11 windows of floating panels and documents are unmapped with the hidden main window (`apps/vectorcraft/src/quit_windows.rs`). From f4aa208239142114339768aae99f74e7d5ee0ac1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 09:28:31 -0800 Subject: [PATCH 10/42] Scripts: Check Script reads document member names given in brackets Check Script now counts print on a document as a file write when the document is reached with member names as string literals in brackets (app['activeDocument'].print(o), app["documents"][0].print(o), app.documents['getByName']('Draft').print(o)), also through a variable, parentheses, a closed function or catch scope, and included files. A string key on a collection stays an item lookup by name (app.documents['Draft']) unless it names one of the collection's documented members or an Object.prototype member. The report still shows each chain as written. --- crates/scriptcheck/src/analyze.rs | 118 ++++++++++++++++++--- crates/scriptcheck/src/analyze/features.rs | 18 ++-- crates/scriptcheck/src/catalog.rs | 28 +++++ crates/scriptcheck/src/tests.rs | 52 +++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 6 files changed, 200 insertions(+), 21 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index a88d7fd04e..7c3d858017 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -51,6 +51,7 @@ pub(crate) struct IncludeRef { #[derive(Clone, Debug, Default)] pub(crate) struct Known { pub bound: HashMap, + pub bound_dom: HashMap, pub files: HashSet, pub folders: HashSet, /// A file gives names values the analysis doesn't read ([`Declared::unsure`]): no object counts @@ -59,10 +60,11 @@ pub(crate) struct Known { } impl Known { - /// The names known, a name that may hold a File object counting twice: a Folder that becomes a - /// possible File object ([`Known::add`]) changes it too. + /// The names known, a chain's document-model form counting as one more and a name that may hold + /// a File object counting twice: a Folder that becomes a possible File object ([`Known::add`]) + /// changes it too. pub fn len(&self) -> usize { - self.bound.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) + usize::from(self.unsure) + self.bound.len() + self.bound_dom.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) + usize::from(self.unsure) } /// No variable holds a member chain or a File or Folder object. [`Known::unsure`] may be set. @@ -76,8 +78,13 @@ impl Known { pub fn add(&mut self, other: Known, entries: usize) { self.unsure |= other.unsure; for (name, chain) in other.bound { - if self.bound.len() < entries || self.bound.contains_key(&name) { - self.bound.entry(name).or_insert(chain); + if self.bound.len() < entries + && let std::collections::hash_map::Entry::Vacant(entry) = self.bound.entry(name.clone()) + { + if let Some(dom) = other.bound_dom.get(&name) { + self.bound_dom.insert(name, dom.clone()); + } + entry.insert(chain); } } for name in other.files { @@ -339,7 +346,7 @@ impl ObjectValue { /// What a value the check follows holds: a member chain, or a File or Folder object (`folder` when it /// is a Folder object whatever the path names: [`Operand::file_step`]). enum Held { - Chain(String), + Chain { path: String, dom: Option }, File { folder: bool }, } @@ -473,12 +480,22 @@ struct Chain { assign: Option, /// The grouped value ([`Group::id`]) whose operand starts with the chain. group: Option, + /// The chain as the document model reads it, for telling which method is called on what: as + /// `path`, without the echo limit, but with a string literal in brackets that names a member + /// written as that member (`app['activeDocument']` is `app.activeDocument`). `None` once it + /// passes [`DOM_KEY_MAX`] characters. + dom: Option, } +/// The most characters [`Chain::dom`] holds. +const DOM_KEY_MAX: usize = 256; + impl Chain { fn new(root: String, bare: bool, line: usize) -> Self { let (chars, cut) = (root.chars().count(), root.ends_with('…')); + let dom = (!cut && chars <= DOM_KEY_MAX).then(|| root.clone()); Chain { + dom, path: root, chars, cut, @@ -510,10 +527,23 @@ impl Chain { } } + /// Adds `s` to [`Chain::dom`], which ends when it would pass [`DOM_KEY_MAX`] characters. + fn append_dom(&mut self, s: &str) { + if let Some(dom) = &mut self.dom { + if dom.chars().count() + s.chars().count() > DOM_KEY_MAX { + self.dom = None; + } else { + dom.push_str(s); + } + } + } + fn member(&mut self, name: &str, cap: usize) { self.segments += 1; self.append(".", cap); self.append(name, cap); + self.append_dom("."); + self.append_dom(name); self.last_change = name.starts_with("set") || name.starts_with("remove"); } @@ -522,6 +552,28 @@ impl Chain { self.change_call |= call && self.last_change; self.last_change = false; self.append(if call { "()" } else { "[]" }, cap); + self.append_dom(if call { "()" } else { "[]" }); + } + + /// The index `[]` just closed held only the string literal `name`, read whole. When `name` is + /// an identifier and the index is not one of a collection (`documents['Draft']` looks a + /// document up by its name), [`Chain::dom`] reads `.name` there, as a member reached with a + /// dot does. The shown `path` keeps `[]`. + fn named_index(&mut self, name: &str) { + let mut chars = name.chars(); + let identifier = chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$'); + let Some(dom) = &mut self.dom else { return }; + let Some(before) = dom.strip_suffix("[]") else { return }; + let collection = before.rsplit('.').next().unwrap_or(before); + let lookup = !catalog::OBJECT_PROTOTYPE_MEMBERS.contains(&name) + && catalog::DOM_COLLECTIONS.iter().any(|(c, members)| collection == *c && !members.contains(&name)); + if !identifier || lookup { + return; + } + dom.truncate(before.len()); + self.append_dom("."); + self.append_dom(name); } } @@ -554,6 +606,8 @@ struct Catch { struct Saved { /// The member chain assigned to it. chain: Option, + /// The document-model form of the saved chain when it differs from the shown path. + dom: Option, /// It held a File or Folder object. file: bool, /// It held a Folder object. @@ -633,6 +687,9 @@ struct Analyzer<'s, 'a, 'l> { shadowed: [bool; 4], /// Variables assigned from a member chain, and the chain. bound: HashMap, + /// For a variable in `bound`, the chain as the document model reads it ([`Chain::dom`]) when it + /// differs from the chain shown. + bound_dom: HashMap, /// Variables holding a File or Folder object. files: HashSet, /// The variables in `files` holding a Folder object whatever the path names ([`Held::File`]). @@ -733,6 +790,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { suspend: false, shadowed: [false; 4], bound: known.bound.clone(), + bound_dom: known.bound_dom.clone(), files: known.files.clone(), folders: known.folders.clone(), // A variable of the same name as a property a member assignment writes may be that @@ -900,7 +958,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else { return false; }; - self.active = Some(Chain::new(root, bare, t.line)); + let mut c = Chain::new(root, bare, t.line); + if let Some(dom) = self.bound_dom.get(t.text).filter(|_| self.bound.contains_key(t.text)) { + c.dom = Some(dom.clone()); + } + self.active = Some(c); true } @@ -938,23 +1000,28 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { && g.id == id && matches!(g.operand, Operand::Chain) { - g.operand = Operand::Done(Held::Chain(c.path.clone())); + g.operand = Operand::Done(Held::Chain { path: c.path.clone(), dom: c.dom.clone() }); } if let Some(name) = c.assign { let ends = ending.is_none_or(ends_value); if ends && !key { - self.bind(name, c.path); + self.bind(name, c.path, c.dom); } else { self.unbind(&name); } } } - fn bind(&mut self, name: String, path: String) { + /// `name` holds the chain `path`, which the document model reads as `dom` when that differs. + fn bind(&mut self, name: String, path: String, dom: Option) { self.files.remove(&name); self.folders.remove(&name); self.writers.remove(&name); + self.bound_dom.remove(&name); if self.bound.contains_key(&name) || self.acc.room(self.bound.len()) { + if let Some(dom) = dom.filter(|d| *d != path) { + self.bound_dom.insert(name.clone(), dom); + } self.bound.insert(name, path); } } @@ -962,6 +1029,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `name` holds a File or Folder object (`folder` for a Folder object whatever the path names). fn hold_file(&mut self, name: String, folder: bool) { self.bound.remove(&name); + self.bound_dom.remove(&name); self.folders.remove(&name); self.writers.remove(&name); if !folder && !self.maybe_files.contains(&name) { @@ -1081,6 +1149,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let shadowed = catalog::DOM_ROOTS.iter().position(|r| *r == name).and_then(|i| self.shadowed.get(i).copied()); Saved { chain: self.bound.get(name).cloned(), + dom: self.bound_dom.get(name).cloned(), file: self.files.contains(name), folder: self.folders.contains(name), maybe_file: self.maybe_files.contains(name), @@ -1094,8 +1163,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `name` holds `saved` again. fn restore(&mut self, name: String, saved: Saved) { self.acc.steps = self.acc.steps.saturating_add(1); + self.bound_dom.remove(&name); match saved.chain { Some(chain) => { + if let Some(dom) = saved.dom { + self.bound_dom.insert(name.clone(), dom); + } self.bound.insert(name.clone(), chain); } None => { @@ -1177,6 +1250,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn empty(&mut self, name: &str) { self.make_own(name); self.bound.remove(name); + self.bound_dom.remove(name); self.files.remove(name); self.folders.remove(name); self.writers.remove(name); @@ -1262,6 +1336,19 @@ 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']` reads as `app.activeDocument` in the chain's + // `dom`. A key longer than `DOM_KEY_MAX` characters is not read whole. + if t.text == "]" + && is(self.h[1], "[") + && let Some(s) = self.h[0].filter(|s| s.kind == T::Str) + { + let name = unquote(s.text, DOM_KEY_MAX + 1); + if name.chars().count() <= DOM_KEY_MAX + && let Some(c) = self.active.as_mut() + { + c.named_index(&name); + } + } } self.close_scopes(); let grouped = self.close_parens(t); @@ -1367,6 +1454,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let Some(c) = self.catches.get_mut(i) else { return }; let empty = Saved { chain: None, + dom: None, file: false, folder: false, maybe_file: false, @@ -1711,7 +1799,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn settle(&mut self, g: Group, ends: bool) { let complete = (g.closed || g.bare) && ends; match g.operand { - Operand::Done(Held::Chain(path)) if complete => self.bind(g.name, path), + Operand::Done(Held::Chain { path, dom }) if complete => self.bind(g.name, path, dom), Operand::Done(Held::File { folder }) | Operand::FileName { new: true, folder } if complete => self.hold_file(g.name, folder), _ => self.unbind(&g.name), } @@ -1799,7 +1887,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } // A variable that any assignment gave a value that may be a File object leaves as one. let folders = self.folders.iter().filter(|name| self.folder(name)).cloned().collect(); - let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders, unsure: self.unsure }; + let known = Known { + bound: std::mem::take(&mut self.bound), + bound_dom: std::mem::take(&mut self.bound_dom), + files: std::mem::take(&mut self.files), + folders, + unsure: self.unsure, + }; (std::mem::take(&mut self.includes), module, known) } } diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index cd7ae0dfbd..40e7a3c80f 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -308,11 +308,15 @@ 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 { + /// set aside until its `)` is one of [`catalog::DOM_DOCUMENTS`] followed by `.print()`, read as + /// the document model reads the chain ([`super::Chain::dom`]), so a member name in brackets + /// counts as one after a dot. + fn document_print(&self) -> bool { let chain = self.suspended.last().filter(|c| c.wait.saturating_add(1) == self.depth()); - chain.and_then(|c| c.path.strip_suffix(called)).is_some_and(|receiver| catalog::DOM_DOCUMENTS.contains(&receiver)) + chain + .and_then(|c| c.dom.as_deref()) + .and_then(|dom| dom.strip_suffix(".print()")) + .is_some_and(|receiver| catalog::DOM_DOCUMENTS.contains(&receiver)) } /// `(` after a name: a call. @@ -324,7 +328,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { && let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32)) { if (catalog::DOM_FILE_WRITES.contains(&name.as_str()) && !Self::defines(self.index_receiver, &name)) - || (name == catalog::DOM_PRINT && self.document_print("[]()")) + || (name == catalog::DOM_PRINT && self.document_print()) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -333,7 +337,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if name == catalog::OPEN && word(h3, "app") && !self.shadowed[0] - && self.suspended.last().is_some_and(|c| c.wait.saturating_add(1) == self.depth() && c.path == "app[]()") + && self.suspended.last().is_some_and(|c| c.wait.saturating_add(1) == self.depth() && c.dom.as_deref() == Some("app.open()")) { self.acc.feature(FeatureId::FileRead, line); return; @@ -363,7 +367,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { 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()")) + || (n == catalog::DOM_PRINT && self.document_print()) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index fbbca9502c..7567613c2e 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -105,6 +105,34 @@ pub(crate) const DOM_DOCUMENTS: &[&str] = &[ "app.open()", ]; +// Every collection inherits these Object.prototype members (ECMA-262 3rd edition, section 15.2.4). +pub(crate) const OBJECT_PROTOTYPE_MEMBERS: &[&str] = + &["constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable"]; + +// Each collection lists the members a string key names instead of looking up an item. +// https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ and the corresponding collection +// pages list these properties and methods. +pub(crate) const DOM_COLLECTIONS: &[(&str, &[&str])] = &[ + ("artboards", &["add", "getActiveArtboardIndex", "getByName", "insert", "length", "parent", "remove", "setActiveArtboardIndex", "typename"]), + ("characterStyles", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]), + ("documents", &["add", "addDocument", "addDocumentNoUI", "getByName", "index", "length", "parent", "typename"]), + ("groupItems", &["add", "createFromFile", "getByName", "index", "length", "parent", "removeAll", "typename"]), + ("layers", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]), + ("pageItems", &["getByName", "index", "length", "parent", "removeAll", "typename"]), + ("paragraphStyles", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]), + ( + "pathItems", + &["add", "ellipse", "getByName", "index", "length", "parent", "polygon", "rectangle", "removeAll", "roundedRectangle", "star", "typename"], + ), + ("pathPoints", &["add", "index", "length", "parent", "removeAll", "typename"]), + ("stories", &["index", "length", "parent", "typename"]), + ("swatches", &["add", "getByName", "getSelected", "index", "length", "parent", "removeAll", "typename"]), + ("symbols", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]), + ("tags", &["add", "getByName", "index", "length", "parent", "removeAll", "typename"]), + ("textFrames", &["add", "areaText", "getByName", "index", "length", "parent", "pathText", "pointText", "removeAll", "typename"]), + ("views", &["index", "length", "parent", "typename"]), +]; + // The save option of `Document.close` that saves the document to its own file: // https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and // https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ (SaveOptions). diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 18f7d5f065..013305abb0 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -674,6 +674,58 @@ fn print_writes_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", lines)]); } +/// A document reached with its member names in brackets prints to a file as one reached with dots +/// does, and so does one a collection looks up by its name; a bracketed name that is not a +/// document's member, and a computed one, do not. The report still shows the chains as written. +#[test] +fn print_on_bracketed_document_chains_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", + "app[\"documents\"][0].print(o);\n", + "app.documents['Draft'].print(o);\n", + "app['preferences'].print(o);\n", + "app[key].print(o);\n", + "app['open'](new File(p));\n", + "var d = app['activeDocument']; d.print(o);\n", + "app.documents['getByName']('Draft').print(o);\n", + "app['documents']['length'].print(o);\n", + "var grouped = (app['activeDocument']); grouped.print(o);\n", + "var scoped = app['activeDocument']; function f(scoped) {} scoped.print(o);\n", + "var caught = app['activeDocument']; try {} catch (caught) {} caught.print(o);\n", + "function later() { future.print(o); } var future = app['activeDocument'];\n", + "app.documents['removeAll'].print(o);\n", + "app['documents']['remove'].print(o);\n", + "app.documents['addDocumentNoUI']('Print').print(o);\n", + "app.documents['index'](0).print(o);\n", + "app.documents['parent'].print(o); app.documents['typename'].print(o);\n", + "app['documents']['toString'].print(o);\n", + )); + let lines = &[2, 3, 4, 5, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19][..]; + 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::>(), [("filesWritten", lines)]); + assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[8][..])); + assert!(r.members.iter().any(|m| m.name == "app[].print()")); + assert!(r.members.iter().all(|m| m.name != "app.activeDocument.print()")); +} + +/// A bracketed document chain keeps its document-model form across scans and included files. +#[test] +fn print_on_bracketed_document_chains_in_included_files_writes_a_file() { + for order in [["doc.jsxinc", "alias.jsxinc"], ["alias.jsxinc", "doc.jsxinc"]] { + let mut m = mem(&[("doc.jsxinc", "var doc = app['activeDocument'];\n"), ("alias.jsxinc", "var alias = doc;\n")]); + let main = format!("#include '{}'\n#include '{}'\ndoc.print(o);\nalias.print(o);\n", order[0], order[1]); + let r = check("main.jsx", main.as_bytes(), Some(&mut m), &Limits::default()); + let lines = &[3, 4][..]; + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines), "{order:?}"); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", lines)], "{order:?}"); + let mut members: Vec<&str> = r.members.iter().map(|m| m.name.as_str()).collect(); + members.sort_unstable(); + assert_eq!(members, ["app[]", "app[].print()"], "{order:?}"); + } +} + /// `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. diff --git a/docs/mcp.md b/docs/mcp.md index 064c8a9f81..df87abf69b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2750,7 +2750,8 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, 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, and `print` called on `app.activeDocument`, `app.documents[i]`, `documents.add()`, `documents.getByName()` or `app.open()`, or on a - variable that holds one of them), `filesOpened` (files opened in other apps), `network`, + variable that holds one of them, with each member name after a dot or as a string in brackets + (`app['activeDocument']['print'](o)`)), `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, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b27feeba4b..e775ce3d67 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1120,7 +1120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets. Printing to a printer from a script and `app.printerList` are not available yet (`docs/mcp.md`). `crates/engine/src/tests/script_print.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. Printing to a printer from a script and `app.printerList` are not available yet (`docs/mcp.md`). Check Script counts `print` on a document as a file write, with the document's member names after dots or as strings in brackets (`app['activeDocument'].print(o)`, `app.documents['Draft'].print(o)`). `crates/engine/src/tests/script_print.rs`, `crates/scriptcheck/src/tests.rs` (`print_writes_a_file`, `print_on_bracketed_document_chains_writes_a_file`). - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From f44ecb3741fd5bf916fe759303011d2310d1902b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 14:48:45 -0800 Subject: [PATCH 11/42] Scripts: refusals name files as the save was given them; locked folders give READ_ONLY_LOCATION A save job now takes its path naming from whether the plan was given a path, so a refused multi-file save without a path names its files by their file names for every caller of `save_job`, as `document.save` already did. Merging the save, export and open branch had left the job naming full paths unless `save` set the field, which failed `refused_multi_file_save_never_calls_the_writer`. A multi-file save or export into a folder that may not be read no longer fails with "automation path rejected: cannot resolve": a path whose real path cannot be found is compared as written, and its write reports READ_ONLY_LOCATION as other saves there do. The print tests remove their folders when an assertion fails, and Check Script has a test for printing the document `app['open']` returns. --- crates/engine/src/cmd/fileio/export_names.rs | 5 ++- crates/engine/src/cmd/fileio/save.rs | 8 ++-- crates/engine/src/tests/save.rs | 28 ++++++++++++++ crates/engine/src/tests/script_print.rs | 40 +++++++++++++++++++- crates/scriptcheck/src/tests.rs | 16 ++++++++ 5 files changed, 91 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 3c80bfb72f..c9e34a5ca8 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -110,11 +110,14 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do Ok(merge(out, extra)) } +/// An error when two of `paths` are the same file. A path whose real path cannot be found (a folder +/// that may not be read, a link that leads nowhere) is compared as written, and its write then +/// reports its own error. #[cfg(not(target_arch = "wasm32"))] pub(super) fn distinct_write_targets<'a>(paths: impl IntoIterator) -> Result<()> { let mut targets = std::collections::HashSet::new(); for path in paths { - let real = crate::file_access::resolve(path).map_err(EngineError::Other)?; + let real = crate::file_access::resolve(path).or_else(|_| std::path::absolute(path)).unwrap_or_else(|_| std::path::PathBuf::from(path)); if !targets.insert(real) { return Err(EngineError::Other("output destinations resolve to the same file".into())); } diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 8a7987496d..f53c00332b 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -604,6 +604,8 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + /// Whether a refusal names a file by its file name: the plan was given no path + /// ([`SavePlan::path_given`]). redact_paths: bool, } @@ -966,7 +968,8 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option Result { let plan = save_plan(s, mode, p)?; - let mut job = save_job(s, plan)?; + let job = save_job(s, plan)?; let uid = s.doc()?.uid; let given = job.plan.path_given; - job.redact_paths = !given; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) diff --git a/crates/engine/src/tests/save.rs b/crates/engine/src/tests/save.rs index f6a2f5158c..2beeb53fd6 100644 --- a/crates/engine/src/tests/save.rs +++ b/crates/engine/src/tests/save.rs @@ -217,6 +217,34 @@ fn refused_multi_file_save_never_calls_the_writer() { let _ = std::fs::remove_dir_all(d); } +/// A save of several files into a folder that may not be read fails as a write there fails, with +/// READ_ONLY_LOCATION, and not because the files' real paths could not be compared. +#[cfg(unix)] +#[test] +fn a_multi_file_save_into_a_locked_folder_is_read_only() { + use std::os::unix::fs::PermissionsExt; + + let d = dir("locked-multi"); + let locked = d.join("locked"); + std::fs::create_dir_all(&locked).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + let own = path(&locked, "doc.vectorcraft"); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap(); + // Where permissions don't hold (root), the folder reads as any other. + let enforced = std::fs::read_dir(&locked).is_err(); + let r = s.execute("document.save", &json!({"path": own, "separateArtboards": true})); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); + if enforced { + let e = r.unwrap_err(); + assert!(matches!(e, EngineError::ReadOnlyLocation(_)), "{e}"); + assert!(std::fs::read_dir(&locked).unwrap().next().is_none()); + } else { + assert!(r.is_ok(), "{r:?}"); + } + let _ = std::fs::remove_dir_all(d); +} + #[test] fn an_svg_path_writes_svg_and_save_writes_it_back() { let d = dir("svg"); diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index dd3f6dca75..9bf3b72bd8 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -26,13 +26,49 @@ fn postscript_suffix_recognizes_windows_filename_aliases() { assert!(postscript_name("proof.ps", false)); } +/// A test's folder, removed when the test ends, also when an assertion fails. +struct Workspace(PathBuf); + +impl std::ops::Deref for Workspace { + type Target = PathBuf; + fn deref(&self) -> &PathBuf { + &self.0 + } +} + +impl AsRef 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) -> PathBuf { +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(); - std::fs::canonicalize(&base).unwrap() + Workspace(std::fs::canonicalize(&base).unwrap()) +} + +#[test] +fn a_workspace_is_removed_when_its_test_panics() { + let base = folder("removed-on-panic"); + let path = base.to_path_buf(); + assert!( + std::panic::catch_unwind(move || { + let _held = base; + panic!("a failed assertion"); + }) + .is_err() + ); + assert!(!path.exists()); } /// A session whose scripts keep their data folders in `base/settings/Script Data`, with a diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index c6d6efaf7c..708fcaabca 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -710,6 +710,22 @@ fn print_on_bracketed_document_chains_writes_a_file() { assert!(r.members.iter().all(|m| m.name != "app.activeDocument.print()")); } +/// The document `app.open` returns prints to a file when `open` is named in brackets too, and the +/// call reads the opened file. +#[test] +fn print_on_a_document_app_open_returns_writes_a_file() { + let r = report(concat!( + "var o = new PrintOptions(); o.jobOptions.file = new File(p);\n", + "app['open'](new File(p)).print(o);\n", + "app.open(new File(p))['print'](o);\n", + "app[\"open\"](new File(p))[\"print\"](o);\n", + )); + let lines = &[2, 3, 4][..]; + 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::>(), [("filesWritten", lines)]); + assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(lines)); +} + /// A bracketed document chain keeps its document-model form across scans and included files. #[test] fn print_on_bracketed_document_chains_in_included_files_writes_a_file() { From ed531e430edc93db17010f5c897a1ac9c4c24c75 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 15:04:47 -0800 Subject: [PATCH 12/42] Scripts: saveAs without options takes the format the file name gives on Windows `Document.saveAs` without options read the format from the path as written, so on Windows `drawing.svg.` or `drawing.svg ` saved in the document's own format under an SVG name. It now uses the format the file name gives without its trailing dots and spaces, as `save_format_for_name` reads it. --- crates/engine/src/script/dom/save_open.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index f1198924a7..2fa9aac1c8 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -804,10 +804,9 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } else if !q.is_empty() { p.insert("options".into(), Value::Object(q)); } - } else { - let format = crate::cmd::fileio::format_for_name(path).map_or_else(|| super::with_doc(h, doc, |_, st| st.format), |f| f.id); - p.insert("format".into(), json!(format)); } + // Without options, the format of the file name as the platform reads it (on Windows, without + // trailing dots and spaces), else the document's own. if !p.contains_key("format") { let format = named_format.unwrap_or_else(|| super::with_doc(h, doc, |_, st| st.format)); p.insert("format".into(), json!(format)); From b4505b2558bf131e44788946f0cae45ff91b7c30 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:31:35 -0800 Subject: [PATCH 13/42] Scripts: assigned File properties follow the host's value A File assigned to a host property is kept for the property's getter and its path changes are sent to the setter. Four cases were wrong: - A property inherited from a parent class never received path changes, since only the class's own setters were looked up. - The getter gave the kept File after the host had cleared or replaced the property. It now gives the kept File only while the host still names its file, and drops it otherwise. - A path change the host refused, or a getter that failed, threw on every later hosted call, an assignment of a new File included. The File stops being tracked once the error is thrown. - A path change sent the setter even after the host had cleared the property, which restored it. The getter is read first. The receiver and arguments of a host call stay rooted while files sync, the host runs and the assigned File is kept, so a File passed through apply cannot be collected first. --- crates/js/src/host.rs | 71 +++++++++++++++++++++++++--- crates/js/src/host_classes.rs | 21 +++++++-- crates/js/src/host_tests.rs | 89 +++++++++++++++++++++++++++++++++++ 3 files changed, 172 insertions(+), 9 deletions(-) diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 1f6119c8ea..7598f803d9 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -449,6 +449,17 @@ impl Interp { /// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to /// the script. pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { + // The receiver and the arguments may be held only here (an `apply` of an array-like): they + // stay rooted while the files sync, the host runs and the assigned File is kept. + let mark = self.temp_roots.len(); + self.temp_roots.push(this.clone()); + self.temp_roots.extend(args.iter().cloned()); + let r = self.call_data_rooted(f, name, this, args, how); + self.temp_roots.truncate(mark); + r + } + + fn call_data_rooted(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { if how.hosted() { self.sync_host_files()?; } @@ -471,9 +482,21 @@ impl Interp { self.keep_host_file(id, name.clone(), file)?; } else if matches!(how, ArgRead::HostedFileGet) && let Class::Host(h) = &self.object(id)?.class - && let Some((_, file, _)) = h.files.iter().find(|(n, _, _)| n == name) + && let Some((_, file, kept)) = h.files.iter().find(|(n, _, _)| n == name) + && let Ok(d) = &result { - return Ok(file.clone()); + // The assigned File keeps its identity while the getter still names its file; + // otherwise the host changed the property, and the getter's value is given. + let (file, kept, d) = (file.clone(), kept.clone(), d.clone()); + let (same, got) = self.names_file(d, &kept)?; + if same { + return Ok(file); + } + self.keep_host_file(id, name.clone(), Value::Undefined)?; + return match got { + Some(got) => Ok(got), + None => Ok(Value::Undefined), + }; } } match result { @@ -516,26 +539,62 @@ impl Interp { Ok(()) } + /// Whether the host's value `d` is a File for `path`, compared as the File the script receives + /// for it; with the File made to compare it, when one was made. + fn names_file(&mut self, d: Data, path: &str) -> JsResult<(bool, Option)> { + if crate::file_ref_path(&d) == Some(path) { + return Ok((true, None)); + } + let got = self.write_hosted(d)?; + let same = match got.as_object() { + Some(g) => crate::file_classes::file_path(self, g)?.as_deref() == Some(path), + None => false, + }; + Ok((same, Some(got))) + } + fn sync_host_files(&mut self) -> JsResult<()> { let mut updates = Vec::new(); for id in self.host_file_objects.clone() { self.use_fuel()?; let Some(object) = self.heap.object(id) else { continue }; let Class::Host(h) = &object.class else { continue }; - let Some(class) = self.host_classes.get(h.class as usize) else { continue }; + let class = h.class; for (name, file, previous) in &h.files { let Some(file_id) = file.as_object() else { continue }; if crate::file_classes::file_path(self, file_id)?.as_ref() != Some(previous) - && let Some((_, set)) = class.file_setters.iter().find(|(n, _)| n == name) + && let Some((get, set)) = self.file_accessors(class, name) { - updates.push((id, name.clone(), file.clone(), set.clone())); + updates.push((id, name.clone(), file.clone(), previous.clone(), get, set)); } } } - for (id, name, file, set) in updates { + for (id, name, file, previous, get, set) in updates { self.use_fuel()?; + // A property the host changed since the assignment no longer holds this File: it is + // not tracked any more, and the host's value stays. + let this = self.read_args(&name, Some(&Value::Object(id)), &[], &ArgRead::Hosted)?; + let same = match get(this) { + Ok(d) => self.names_file(d, &previous).map(|(same, _)| same), + Err(error) => Err(self.host_error(error).unwrap_or_else(|e| e)), + }; + match same { + Ok(true) => {} + Ok(false) => { + self.keep_host_file(id, name, Value::Undefined)?; + continue; + } + Err(e) => { + // A getter that fails stops tracking too, so the error is thrown once. + self.keep_host_file(id, name, Value::Undefined)?; + return Err(e); + } + } let data = self.read_args(&name, Some(&Value::Object(id)), std::slice::from_ref(&file), &ArgRead::Hosted)?; if let Err(error) = set(data) { + // The host refused the new path: the File is no longer tracked, so the error is + // thrown once and a later assignment can replace it. + self.keep_host_file(id, name, Value::Undefined)?; return Err(self.host_error(error)?); } self.keep_host_file(id, name, file)?; diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index d6e7d728ac..1d857052f4 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -148,7 +148,8 @@ pub(crate) struct Entry { unavailable: Rc>, /// The class's own members as `reflect` lists them. members: Rc<[Reflected]>, - pub(crate) file_setters: Vec<(Rc, HostFunction)>, + /// The getter and setter of each File property the class declares, by `Class.member`. + pub(crate) file_setters: Vec<(Rc, HostFunction, HostFunction)>, } /// How a script may use a member of a host class. @@ -229,6 +230,20 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { } impl Interp { + /// The getter and setter of File property `name` (`Class.member`) of `class` or of a class it + /// descends from. + pub(crate) fn file_accessors(&self, class: u32, name: &str) -> Option<(HostFunction, HostFunction)> { + let mut at = Some(class); + for _ in 0..=self.host_classes.len() { + let entry = self.host_classes.get(at? as usize)?; + if let Some((_, get, set)) = entry.file_setters.iter().find(|(n, _, _)| &**n == name) { + return Some((get.clone(), set.clone())); + } + at = entry.parent; + } + None + } + /// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host /// class, and `k` names an available member of that class or of a class it descends from. The /// nearest class that declares `k` decides, so a member a class declares unavailable is not @@ -485,11 +500,11 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { .members .iter() .filter_map(|(name, member)| { - let HostMember::Property { set, .. } = member else { return None }; + let HostMember::Property { get, set } = member else { return None }; if !class.info.iter().any(|(n, info)| n == name && info.data_type == "File") { return None; } - Some((format!("{}.{name}", class.name).into(), set.clone())) + Some((format!("{}.{name}", class.name).into(), get.clone(), set.clone())) }) .collect(), }); diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index cd7518eb4b..328a6bcb39 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -1245,3 +1245,92 @@ proptest::proptest! { proptest::prop_assert!(matches!(out.as_str(), "ok" | "RangeError" | "TypeError"), "{}", out); } } + +/// A realm whose global `it` is a `Child` that inherits the File property `file` from `Base`. The +/// setter records each path it is given and refuses one containing `bad`; `clear()` sets the +/// property to null and `touch()` does nothing. +fn file_property_realm() -> (Realm, Rc>>) { + let mut r = realm(10_000_000); + let parse: HostFunction = Rc::new(|a| { + let fs = match a.first() { + Some(Data::String(s)) => s.clone(), + _ => String::new(), + }; + let name = fs.trim_start_matches('/').to_string(); + let fields = [("fs", fs.clone()), ("uri", fs), ("name", name.clone()), ("display", name), ("path", "/".into()), ("parent", "/".into())]; + Ok(Data::Object(fields.into_iter().map(|(k, v)| (k.to_string(), Data::String(v))).collect())) + }); + let messages = ["notOpen", "badMode"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into())))); + r.define_file_classes(vec![ + ("text".into(), HostItem::Object(messages.to_vec())), + ("current".into(), HostItem::Function(Rc::new(|_| Ok(Data::String("/".into()))))), + ("parse".into(), HostItem::Function(parse)), + ]) + .unwrap(); + let stored = Rc::new(RefCell::new(Data::Null)); + let seen = Rc::new(RefCell::new(Vec::new())); + let (get_stored, set_stored, clear_stored) = (stored.clone(), stored.clone(), stored); + let log = seen.clone(); + let get: HostFunction = Rc::new(move |_| Ok(get_stored.borrow().clone())); + let set: HostFunction = Rc::new(move |args| { + let path = args.last().and_then(file_ref_path).unwrap_or("?").to_string(); + if path.contains("bad") { + return Err(HostError::Error(format!("{path} is refused"))); + } + log.borrow_mut().push(path.clone()); + *set_stored.borrow_mut() = file_ref(&path); + Ok(Data::Undefined) + }); + let clear: HostFunction = Rc::new(move |_| { + *clear_stored.borrow_mut() = Data::Null; + Ok(Data::Undefined) + }); + let info = MemberInfo { data_type: "File".into(), ..MemberInfo::default() }; + let base = HostClass { + name: "Base".into(), + parent: None, + members: vec![ + ("file".into(), HostMember::Property { get, set }), + ("clear".into(), HostMember::Method(clear)), + ("touch".into(), HostMember::Method(Rc::new(|_| Ok(Data::Undefined)))), + ], + info: vec![("file".into(), info)], + index: None, + construct: None, + }; + let child = HostClass { name: "Child".into(), parent: Some("Base".into()), members: vec![], info: Vec::new(), index: None, construct: None }; + r.define_host_classes(vec![base, child], vec![("it".into(), host_ref("Child", &[1.0]))]).unwrap(); + (r, seen) +} + +#[test] +fn an_inherited_file_property_follows_its_files_new_path() { + let (mut r, seen) = file_property_realm(); + r.run("var f = new File('/a'); it.file = f; f.changePath('/b'); it.touch();").unwrap(); + assert_eq!(*seen.borrow(), ["/a", "/b"]); +} + +#[test] +fn the_getter_gives_its_own_value_once_the_host_changes_a_file_property() { + let (mut r, _) = file_property_realm(); + let source = "var f = new File('/a'); it.file = f; var same = it.file === f; it.clear(); [same, it.file === null].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("true|true".into())); +} + +#[test] +fn a_path_change_does_not_restore_a_property_the_host_cleared() { + let (mut r, seen) = file_property_realm(); + let source = "var f = new File('/a'); it.file = f; it.clear(); f.changePath('/b'); it.touch(); it.file === null"; + assert_eq!(r.run(source).unwrap(), JsValue::Bool(true)); + assert_eq!(*seen.borrow(), ["/a"]); +} + +#[test] +fn a_refused_path_change_is_thrown_once() { + let (mut r, seen) = file_property_realm(); + let source = "var f = new File('/a'); it.file = f; f.changePath('/bad'); var first = 'none'; try { it.touch(); } catch (e) { first = e.message; }\n\ + it.touch(); it.file = new File('/good'); first"; + let JsValue::String(first) = r.run(source).unwrap() else { panic!("not a string") }; + assert!(first.contains("refused"), "{first}"); + assert_eq!(*seen.borrow(), ["/a", "/good"]); +} From 56dd6d07e5d81eb329bc92689cc9368b1bf5329e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:31:35 -0800 Subject: [PATCH 14/42] Script checker: open on a File held in a variable named app writes `var app = new File(p); app.open('w');` was reported as an application open (file.read). A receiver that holds a File now takes the File open mode rules, so the check reports file.write and filesWritten. --- crates/scriptcheck/src/analyze/features.rs | 2 +- crates/scriptcheck/src/tests.rs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 40e7a3c80f..e09a5d94f0 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -355,7 +355,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let file = held.is_some(); if n == catalog::MENU_COMMAND { self.pending = Pending::Menu(line); - } else if n == catalog::OPEN && word(h2, "app") && !member_mark(h3) && !self.shadowed[0] { + } else if n == catalog::OPEN && word(h2, "app") && !member_mark(h3) && !self.shadowed[0] && !file { self.acc.feature(FeatureId::FileRead, line); } else if n == catalog::OPEN && file { self.pending = Pending::Open(line); diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 708fcaabca..48bdddb0d5 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -63,6 +63,7 @@ const FEATURE_CASES: &[(&str, &str, &str)] = &[ ("file.read", "var all = folder.getFiles();", "var all = folder.files;"), ("file.read", "var s = File(p).read();", "var s = Cache(p).read();"), ("file.write", "var f = new File(p); f.open('w');", "var f = new File(p); f.open('r');"), + ("file.write", "var app = new File(p); app.open('w');", "var app = new File(p); app.open('r');"), ("file.write", "var f = File.saveDialog(); f.write(s);", "var f = picker(); f.write(s);"), ("file.write", "new File(p).remove();", "new Thing(p).remove();"), ("file.write", "var a = new File(p); var b = a; b.remove();", "var a = new File(p); var b = a.parent; b.remove();"), From c0411d4e4b5202d8e4a33202960c1ce9548404eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:31:36 -0800 Subject: [PATCH 15/42] Export: a dangling link to the primary file counts as a collision When an export's linked image path was a link to the primary file that did not exist yet, the destination check compared the link as written. The primary was written first, the link then led to it, and the image replaced it. The check now compares such a link by the file it leads to. --- crates/engine/src/cmd/fileio/export_names.rs | 44 ++++++++++++++++++-- crates/engine/src/tests/script_save_open.rs | 11 ++++- 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index c9e34a5ca8..ec749cd737 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -110,14 +110,18 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do Ok(merge(out, extra)) } -/// An error when two of `paths` are the same file. A path whose real path cannot be found (a folder -/// that may not be read, a link that leads nowhere) is compared as written, and its write then -/// reports its own error. +/// An error when two of `paths` are the same file. A link that leads nowhere is compared by the file +/// its write creates; another path whose real path cannot be found (a folder that may not be read) +/// is compared as written, and its write then reports its own error. #[cfg(not(target_arch = "wasm32"))] pub(super) fn distinct_write_targets<'a>(paths: impl IntoIterator) -> Result<()> { let mut targets = std::collections::HashSet::new(); for path in paths { - let real = crate::file_access::resolve(path).or_else(|_| std::path::absolute(path)).unwrap_or_else(|_| std::path::PathBuf::from(path)); + let real = crate::file_access::resolve(path) + .ok() + .or_else(|| dangling_target(path)) + .or_else(|| std::path::absolute(path).ok()) + .unwrap_or_else(|| std::path::PathBuf::from(path)); if !targets.insert(real) { return Err(EngineError::Other("output destinations resolve to the same file".into())); } @@ -125,6 +129,38 @@ pub(super) fn distinct_write_targets<'a>(paths: impl IntoIterator Option { + let mut at = std::path::PathBuf::from(path); + let mut followed = false; + for _ in 0..40 { + if !std::fs::symlink_metadata(&at).is_ok_and(|m| m.file_type().is_symlink()) { + break; + } + let next = std::fs::read_link(&at).ok()?; + at = match at.parent() { + Some(parent) if next.is_relative() => parent.join(next), + _ => next, + }; + followed = true; + } + if !followed { + return None; + } + // Resolved as the primary destination is; a name that is not UTF-8 keeps its bytes, with its + // folder's links followed. + match at.to_str() { + Some(text) => crate::file_access::resolve(text).ok(), + None => { + let folder = std::fs::canonicalize(at.parent()?).ok()?; + Some(folder.join(at.file_name()?)) + } + } + .or_else(|| std::path::absolute(&at).ok()) +} + /// `a` with the fields of `b`. pub(crate) fn merge(mut a: Value, b: Value) -> Value { if let (Some(a), Value::Object(b)) = (a.as_object_mut(), b) { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 5345d58562..1efa9e255f 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -111,13 +111,22 @@ fn svg_save_and_export_refuse_resolved_destination_collisions() { assert_eq!(images.len(), 1); std::fs::remove_file(&images[0]).unwrap(); std::os::unix::fs::symlink(&svg, &images[0]).unwrap(); - for call in [export, format!("app.activeDocument.saveAs(new File({}));", quoted(&svg))] { + for call in [export.clone(), format!("app.activeDocument.saveAs(new File({}));", quoted(&svg))] { std::fs::write(&svg, "original").unwrap(); let error = failure(&mut s, &base, &format!("Folder.userData; {call}")); assert!(error.contains("resolve to the same file"), "{error}"); assert_eq!(std::fs::read(&svg).unwrap(), b"original"); assert!(std::fs::symlink_metadata(&images[0]).unwrap().file_type().is_symlink()); } + // With no primary file yet, the image's link leads nowhere but still names the primary. + std::fs::remove_file(&svg).unwrap(); + let error = s.execute("file.saveAs", &json!({"path": svg.to_string_lossy(), "format": "svg", "images": "link"})).unwrap_err().to_string(); + assert!(error.contains("resolve to the same file"), "{error}"); + assert!(!svg.exists()); + // A script may not write through a link that leads nowhere at all. + let error = failure(&mut s, &base, &format!("Folder.userData; {export}")); + assert!(error.contains("resolve to the same file") || error.contains("access denied"), "{error}"); + assert!(!svg.exists()); let _ = std::fs::remove_dir_all(base); } From e08f8dddf3541b2b856b75b09182a340b5a575f1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:31:36 -0800 Subject: [PATCH 16/42] Scripts: print options check values as file.print takes them - An option that is not mapped accepts only its exact default, so `bitmapResolution = 0.0000000005` throws that it is not available. - Paper `width` and `height` take 0 or 72 to 14,400 pt, checked when they are assigned, as `file.print` requires for a custom size. - An assigned `position` places an untiled job when the base settings hold a placed Print Tiling origin. The saved settings keep the origin. - The `app.open` size limit in docs/mcp.md is the 128 MiB a script command reads, with the 256 MiB error above that. - The backslash file name test asserts the result of each platform, and the printArea test checks that the page is artboard 2. --- crates/engine/src/script/dom/print.rs | 46 +++++++++++++++++++---- crates/engine/src/script/dom/save_open.rs | 4 ++ crates/engine/src/tests/script_print.rs | 36 ++++++++++++++++++ docs/mcp.md | 8 +++- 4 files changed, 85 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index 5ebfe77c27..bc3f3cefd5 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -49,7 +49,7 @@ //! `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, //! or that holds `/`, `\` or a control character (also at either end), throws too. Each checked //! name goes to `file.print` without the spaces around it. `printerName` and `PPDName` take only the empty -//! string. +//! string. Paper `width` and `height` take 0 (not assigned) or 72 to 14,400 pt. //! - A run makes at most [`MAX_OPTION_OBJECTS`] option objects. //! - `app.printerList` is not available yet, and `app.PPDFileList` is empty: VectorCraft prints //! without PPD files. @@ -139,6 +139,8 @@ enum Kind { Number(f64, f64), /// A whole number from the first to the second. Whole(u64, u64), + /// A paper side in points: 0 (not assigned) or a custom size from 72 to 14,400. + PaperSize, Text, /// A value of the enumeration (its name and members); only the members in the last list are /// available. @@ -155,6 +157,12 @@ impl Kind { Kind::Bool => typed("boolean"), Kind::Number(min, max) => MemberInfo { min: Some(min), max: Some(max), ..typed("number") }, Kind::Whole(min, max) => MemberInfo { min: Some(min as f64), max: Some(max as f64), ..typed("number") }, + Kind::PaperSize => MemberInfo { + min: Some(0.0), + max: Some(MAX_PAPER), + description: Some(format!("0 (not assigned) or a custom size from {MIN_PAPER} to {MAX_PAPER} pt")), + ..typed("number") + }, Kind::Text => typed("string"), Kind::Choice(name, ..) | Kind::Child(name) => typed(name), Kind::File => typed("File"), @@ -186,7 +194,7 @@ impl Start { fn matches(self, kind: Kind, d: &Data) -> bool { match (self, d) { - (Start::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9, + (Start::Num(a), Data::Number(b)) => a == *b, (Start::None, _) => false, _ => self.value(kind) == *d, } @@ -332,14 +340,18 @@ const MARKS: Class = Class { const PAPER: Class = Class { name: "PrintPaperOptions", fields: &[ - f("height", Kind::Number(0.0, 14_400.0), Start::Num(0.0)), + f("height", Kind::PaperSize, Start::Num(0.0)), f("name", Kind::Text, Start::None), kept("offset", Kind::Number(0.0, 14_400.0), Start::Num(0.0)), f("transverse", Kind::Bool, Start::Bool(false)), - f("width", Kind::Number(0.0, 14_400.0), Start::Num(0.0)), + f("width", Kind::PaperSize, Start::Num(0.0)), ], }; +/// The custom paper sizes `file.print` takes, in points. +const MIN_PAPER: f64 = 72.0; +const MAX_PAPER: f64 = 14_400.0; + const POSTSCRIPT: Class = Class { name: "PrintPostScriptOptions", fields: &[ @@ -417,6 +429,14 @@ fn checked(h: &Host, class: &Class, field: &Field, d: &Data) -> std::result::Res } _ => return Err(HostError::Type(format!("{what} must be a finite number"))), }, + Kind::PaperSize => match d { + Data::Number(n) if n.is_finite() => { + if *n != 0.0 && !(MIN_PAPER..=MAX_PAPER).contains(n) { + return Err(HostError::Range(format!("{what} must be 0 or from {MIN_PAPER} to {MAX_PAPER}"))); + } + } + _ => return Err(HostError::Type(format!("{what} must be a finite number"))), + }, Kind::Whole(lo, hi) => match d { Data::Number(n) => { if !whole(*n).is_some_and(|n| (lo..=hi).contains(&n)) { @@ -524,6 +544,8 @@ struct Job { custom: bool, /// `printArea` is assigned: the artboards print even when the base settings ignore them. print_area: bool, + /// `position` is assigned: an untiled job does not use the saved Print Tiling origin. + position: bool, /// The groups of `settings`: the top level and each nested object by its key. top: Map, groups: Vec<(&'static str, Map)>, @@ -784,6 +806,7 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<( _ => "center", }; job.group("placement").insert("origin".into(), json!(origin)); + job.position = true; } _ => {} } @@ -907,11 +930,12 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { /// name (any case) and a paper by its id or label. An empty name, or one with a path separator or /// a control character, throws. fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> { - let (count, saved_ignore, saved_fit, mut base_profile) = with_doc(h, doc, |_, st| { + let (count, saved_ignore, saved_fit, saved_tiled, mut base_profile) = with_doc(h, doc, |_, st| { let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str); - let fit = st.doc.print_setup.as_ref().and_then(|v| v.get("scaling")).and_then(Value::as_str) == Some("fit"); + let scaling = st.doc.print_setup.as_ref().and_then(|v| v.get("scaling")).and_then(Value::as_str); let profile = st.doc.print_setup.as_ref().and_then(|v| v.get("color")).and_then(|v| v.get("profile")).and_then(Value::as_str); - (st.doc.artboards.len(), mode == Some("ignore"), fit, profile.unwrap_or("").to_string()) + let tiled = matches!(scaling, Some("tileFull" | "tileImageable")); + (st.doc.artboards.len(), mode == Some("ignore"), scaling == Some("fit"), tiled, profile.unwrap_or("").to_string()) }); if let Some(range) = &job.range { vectorcraft_doc::range::parse_range(range, count).map_err(|e| HostError::Range(format!("PrintJobOptions.artboardRange: {e}")))?; @@ -919,17 +943,25 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos let s = h.session.borrow(); let mut base_ignore = saved_ignore; let mut base_fit = saved_fit; + let mut base_tiled = saved_tiled; if let Some(name) = job.preset.take() { let n = plain_name("PrintOptions.printPreset", "print preset", &name)?; let preset = s.print_preset_settings(n).ok_or_else(|| no_such("PrintOptions.printPreset", "print preset", &name))?; base_ignore = matches!(preset.artboards, vectorcraft_pdf::PrintArtboards::Ignore); base_fit = matches!(preset.scaling, vectorcraft_pdf::PrintScaling::Fit); + base_tiled = preset.scaling.tiles(); base_profile.clone_from(&preset.color.profile); job.preset = Some(n.to_string()); } if job.clear_fit && base_fit { job.top.insert("scaling".into(), json!("none")); } + // A placed Print Tiling origin replaces the placement, so an assigned `position` clears it + // for this job when the job does not tile; the saved settings keep it. + let tiled = job.top.get("scaling").and_then(Value::as_str).map_or(base_tiled, |s| matches!(s, "tileFull" | "tileImageable")); + if job.position && !tiled { + job.group("tileOrigin").insert("placed".into(), json!(false)); + } // An assigned `printArea` prints by artboard when the base settings ignore the artboards: the // assigned `artboardRange` when there is one, otherwise every artboard. if job.print_area && base_ignore && !job.top.contains_key("artboards") { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 2fa9aac1c8..4f2c5288ac 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -1182,7 +1182,11 @@ mod save_format_tests { for name in ["drawing", "drawing. . ", "drawing.svg\t", "drawing.svg\u{a0}", "folder.svg/drawing", "folder.svg\\drawing"] { assert!(save_format_for_name(name, true).is_none(), "{name}"); } + // Production passes `cfg!(windows)`; a Windows host still splits this name at the backslash. + #[cfg(unix)] assert_eq!(save_format_for_name("proof\\.svg", false).map(|f| f.id), Some("svg")); + #[cfg(windows)] + assert!(save_format_for_name("proof\\.svg", false).is_none()); for windows in [false, true] { assert_eq!(save_format_for_name(".pdf", windows).map(|f| f.id), Some("pdf")); assert!(save_format_for_name(".svg", windows).is_none()); diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index 9bf3b72bd8..b3e14608f6 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -398,6 +398,9 @@ fn print_options_refuse_bad_values() { ("c.horizontalScale = 1000.01;", "RangeError", "horizontalScale must be from 1 to 1000"), ("c.verticalScale = 1000.01;", "RangeError", "verticalScale must be from 1 to 1000"), ("m.trimMarksWeight = -1;", "RangeError", "trimMarksWeight must be from 0"), + ("o.paperOptions.width = 36;", "RangeError", "width must be 0 or from 72 to 14400"), + ("o.paperOptions.height = 71.9;", "RangeError", "height must be 0 or from 72 to 14400"), + ("o.paperOptions.width = 72; o.paperOptions.width = 0; o.paperOptions.width = 1;", "RangeError", "width must be 0 or from 72"), ("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"), @@ -438,6 +441,7 @@ fn options_that_are_not_available_throw() { ("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"), + ("j.bitmapResolution = 0.0000000005;", "PrintJobOptions.bitmapResolution 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 must be from 1 to 1000"), @@ -546,14 +550,46 @@ fn assigned_job_and_scale_options_apply_over_the_saved_settings() { 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"); + s.execute("artboard.setProps", &json!({"index": 1, "width": 150})).unwrap(); 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 info = vectorcraft_pdf::info(&std::fs::read(dir.join("area-range.pdf")).unwrap(), None).unwrap(); + let trim = info.pages[0].boxes.iter().find(|(k, _)| *k == vectorcraft_pdf::CropTo::Trim).map(|(_, r)| *r).unwrap(); + assert_eq!((trim.width().round(), trim.height().round()), (150.0, 200.0), "the page is artboard 2"); 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); } +/// An assigned `position` places an untiled print even when the saved Print Tiling origin is +/// placed; the saved origin stays. +#[test] +fn an_assigned_position_replaces_a_placed_tile_origin() { + let base = folder("position"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let trim = |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);"), + ); + let info = vectorcraft_pdf::info(&std::fs::read(dir.join(name)).unwrap(), None).unwrap(); + let b = info.pages[0].boxes.iter().find(|(k, _)| *k == vectorcraft_pdf::CropTo::Trim).map(|(_, r)| *r).unwrap(); + [b.x0, b.y0, b.x1, b.y1].map(f64::round) + }; + let top_left = "o.coordinateOptions.position = PrintPosition.TRANSLATETOPLEFT;"; + s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap(); + let plain = trim(&mut s, "plain.pdf", top_left); + s.execute("print.setup", &json!({"settings": {"tileOrigin": {"placed": true, "x": 100, "y": 0}}})).unwrap(); + assert_ne!(trim(&mut s, "placed.pdf", ""), plain, "the placed origin moves the art"); + assert_eq!(trim(&mut s, "assigned.pdf", top_left), plain, "the assigned position wins"); + assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["tileOrigin"]["placed"], json!(true), "the saved origin stays"); + 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)] diff --git a/docs/mcp.md b/docs/mcp.md index 25cd5c26a5..73ec9a9895 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3117,7 +3117,8 @@ through `$`: Each method sends command warnings to the Script Console with its name as the prefix: `Document.saveAs: `, `Document.exportFile: ` or `app.open: `. Without options, `saveAs` selects the format from the supplied name before following a link. `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document`; a file - larger than 256 MiB throws `Script document exceeds 256 MiB` before it is read + larger than 128 MiB, the most a script command reads, throws before it is read: above 256 MiB the error is + `Script document exceeds 256 MiB`, and otherwise it ends `file exceeds 128 MiB` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `file` is a `File`. `new IllustratorSaveOptions()`, `new EPSSaveOptions()` and `new PDFSaveOptions()` pick the format (https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, @@ -3239,6 +3240,8 @@ through `$`: `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. With no scale or tiling assigned, `fitToPage = false` clears a base fit mode and preserves other base scaling modes. + An assigned `position` places an untiled job even when the base settings hold a placed Print Tiling origin; the + saved settings keep that origin. `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 @@ -3247,7 +3250,8 @@ through `$`: the base settings; otherwise `print` throws before writing. 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. `printerName` and `PPDName` take only `""`. A listed option that is not mapped, or a value that is not mapped such as `PrintingBounds.ARTWORKBOUNDS`, `INRIPSEPARATION` or `PSLEVEL1`, throws an error that says it - is not available yet. Print scale factors must be from 1 to 1000 percent. Each value is checked when it is assigned: a wrong type, a number that is not finite or is + is not available yet. Print scale factors must be from 1 to 1000 percent. Paper `width` and `height` take 0 (not + assigned) or 72 to 14,400 pt. 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 From 80a3f65798ccefd6346cb2c1d9ead3a4be878f72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 20:24:12 -0800 Subject: [PATCH 17/42] Print: keep the branch to Print as Bitmap's resolution - The print option classes list their members in reflect as #9060 lists them; the rule that left out unmapped options came from an earlier merge of main and is not part of this change. - Document.tags keeps its place after print in the Document members, as on main. --- crates/engine/src/script/dom.rs | 2 +- crates/engine/src/script/dom/print.rs | 6 +----- crates/engine/src/tests/script_print.rs | 12 ------------ 3 files changed, 2 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 6af22a5733..601664d77b 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -3106,9 +3106,9 @@ fn classes(link: &Link) -> Vec { 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(variables::document_members(l)); - document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") })); 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( "Views", diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index 060122066a..dcce58f2a0 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -1238,11 +1238,7 @@ pub(super) fn classes(link: &Link) -> Vec { create(&h, index) }); let mut members = vec![("typename".to_string(), super::typename_of(c.name), typed("string"))]; - // `reflect` leaves out a property that is not mapped: it takes only its default. - members.extend(c.fields.iter().enumerate().map(|(i, field)| { - let info = MemberInfo { unavailable: !field.mapped, ..field_info(field) }; - (field.name.to_string(), property(link, index, i), info) - })); + members.extend(c.fields.iter().enumerate().map(|(i, field)| (field.name.to_string(), property(link, index, i), field_info(field)))); HostClass { construct: Some(construct), ..class(c.name, None, members, None) } }) .collect(); diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index a99e56cd12..a59cbf0e3f 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -684,18 +684,6 @@ fn options_that_are_not_available_throw() { let _ = std::fs::remove_dir_all(base); } -/// `reflect` lists the options a script can set and leaves out the ones that take only their default. -#[test] -fn reflect_leaves_out_options_that_are_not_available() { - let base = folder("reflect"); - let mut s = session(&base); - let script = "var o = new PrintOptions(), j = new PrintJobOptions(); \ - vc.log(String(o.reflect.find('printerName'))); vc.log(String(j.reflect.find('name'))); \ - vc.log(String(o.reflect.find('printPreset') != null)); vc.log(String(j.reflect.find('copies') != null));"; - assert_eq!(logged(&mut s, &base, script), json!(["null", "null", "true", "true"])); - 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() { From 755f2216fbd7e14672cce20b2fd0c7c1387f9b06 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:15:10 -0800 Subject: [PATCH 18/42] Print: export destinations differing only in case, and indexed reads, follow File paths - distinct_write_targets compares each destination's folder and its name folded as a case-insensitive file system folds it (screens.rs fold), so a.svg beside a dangling link to A.svg is refused before either write. distinct_names uses the same fold, so generated artboard names that fold to one name get a -2 suffix instead of failing the export. - A host class's indexer now syncs File properties first, as method calls do, so it[0] after f.changePath('/b') hands the host /b. The receiver stays rooted while the files sync. - docs/mcp.md states the case rule. --- crates/engine/src/cmd/fileio/export_names.rs | 48 ++++++++++++++++++-- crates/engine/src/cmd/fileio/screens.rs | 2 +- crates/js/src/host.rs | 2 +- crates/js/src/host_classes.rs | 7 +++ crates/js/src/host_tests.rs | 18 +++++++- docs/mcp.md | 3 +- 6 files changed, 72 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index ec749cd737..77837d266f 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -45,9 +45,10 @@ pub(crate) fn unique_file_names_keeping_dots<'a>(names: impl IntoIterator) -> Vec { - distinct_names_by(names, str::to_lowercase) + distinct_names_by(names, super::screens::fold) } /// `names` with `-2`, `-3`… after a name already used, two names matching when `key` gives the same @@ -112,7 +113,8 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do /// An error when two of `paths` are the same file. A link that leads nowhere is compared by the file /// its write creates; another path whose real path cannot be found (a folder that may not be read) -/// is compared as written, and its write then reports its own error. +/// is compared as written, and its write then reports its own error. Two names in one folder that +/// differ only in letter case are treated as the same file on every volume. #[cfg(not(target_arch = "wasm32"))] pub(super) fn distinct_write_targets<'a>(paths: impl IntoIterator) -> Result<()> { let mut targets = std::collections::HashSet::new(); @@ -122,7 +124,11 @@ pub(super) fn distinct_write_targets<'a>(paths: impl IntoIterator dir.join(super::screens::fold(name)), + _ => real, + }; + if !targets.insert(key) { return Err(EngineError::Other("output destinations resolve to the same file".into())); } } @@ -192,3 +198,37 @@ pub(crate) fn write_or_return(path: Option<&str>, bytes: &[u8], extra: Value) -> }; Ok(merge(out, extra)) } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + fn folder(tag: &str) -> std::io::Result { + let d = std::env::temp_dir().join(format!("vc-export-names-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d)?; + Ok(d) + } + + #[test] + fn names_differing_only_in_case_are_one_file() { + let d = folder("case").unwrap(); + let s = |n: &str| d.join(n).to_str().unwrap().to_string(); + assert!(distinct_write_targets([s("a.svg").as_str(), s("A.svg").as_str()]).is_err()); + assert!(distinct_write_targets([s("ας.svg").as_str(), s("ΑΣ.svg").as_str()]).is_err(), "a final sigma"); + assert!(distinct_write_targets([s("S.svg").as_str(), s("ſ.svg").as_str()]).is_err(), "a long s"); + assert_eq!(distinct_names(["ας".to_string(), "ασ".to_string()]), ["ας", "ασ-2"]); + assert!(distinct_write_targets([s("a.svg").as_str(), s("b.svg").as_str()]).is_ok()); + let _ = std::fs::remove_dir_all(&d); + } + + #[cfg(unix)] + #[test] + fn a_dangling_link_to_a_case_variant_of_another_destination_is_the_same_file() { + let d = folder("link").unwrap(); + std::os::unix::fs::symlink("A.svg", d.join("side.svg")).unwrap(); + let (a, side) = (d.join("a.svg"), d.join("side.svg")); + assert!(distinct_write_targets([a.to_str().unwrap(), side.to_str().unwrap()]).is_err()); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 4cc3cad433..3e803bc937 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -622,7 +622,7 @@ pub(crate) fn check_settings(s: &Session, p: &Value) -> Result<()> { /// same key, and so do `ΟΣ`, `ος` and `οσ` (`ΟΣ`); `ᾈ` and `ᾀ` give `ᾀ`, and `ß` stays `ß`. /// Dotless `ı` stays `ı`, as NTFS and Unicode case folding outside Turkic languages keep it apart /// from `i` and `I`. -fn fold(name: &str) -> String { +pub(super) fn fold(name: &str) -> String { name.to_lowercase() .chars() .map(|c| { diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 69474c6b39..808adf952f 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -556,7 +556,7 @@ impl Interp { Ok((same, Some(got))) } - fn sync_host_files(&mut self) -> JsResult<()> { + pub(crate) fn sync_host_files(&mut self) -> JsResult<()> { let mut updates = Vec::new(); for id in self.host_file_objects.clone() { self.use_fuel()?; diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 880cc8b076..735c637311 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -396,6 +396,13 @@ impl Interp { if self.host_ref_size(id)?.is_none() { return Ok(Value::Undefined); } + // The host reads File properties as the script left them, as it does for a method call. The + // receiver may be held only here, so it stays rooted while the files sync. + let mark = self.temp_roots.len(); + self.temp_roots.push(Value::Object(id)); + let synced = self.sync_host_files(); + self.temp_roots.truncate(mark); + synced?; let args = self.read_index_args(id, k, probe)?; match f(args) { Ok(d) => self.write_hosted(d), diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 4e0485ed4f..3ca2704676 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -1382,6 +1382,12 @@ proptest::proptest! { /// setter records each path it is given and refuses one containing `bad`; `clear()` sets the /// property to null and `touch()` does nothing. fn file_property_realm() -> (Realm, Rc>>) { + file_property_realm_indexed(false) +} + +/// [`file_property_realm`], with an indexer on `Child` when `indexed` that gives the last path the +/// setter was given when it is called. +fn file_property_realm_indexed(indexed: bool) -> (Realm, Rc>>) { let mut r = realm(10_000_000); let parse: HostFunction = Rc::new(|a| { let fs = match a.first() { @@ -1430,7 +1436,10 @@ fn file_property_realm() -> (Realm, Rc>>) { index: None, construct: None, }; - let child = HostClass { name: "Child".into(), parent: Some("Base".into()), members: vec![], info: Vec::new(), index: None, construct: None }; + let last = seen.clone(); + let index: Option = + indexed.then(|| -> HostFunction { Rc::new(move |_| Ok(last.borrow().last().map_or(Data::Null, |p| Data::String(p.clone())))) }); + let child = HostClass { name: "Child".into(), parent: Some("Base".into()), members: vec![], info: Vec::new(), index, construct: None }; r.define_host_classes(vec![base, child], vec![("it".into(), host_ref("Child", &[1.0]))]).unwrap(); (r, seen) } @@ -1442,6 +1451,13 @@ fn an_inherited_file_property_follows_its_files_new_path() { assert_eq!(*seen.borrow(), ["/a", "/b"]); } +#[test] +fn an_indexed_read_follows_a_file_propertys_new_path() { + let (mut r, seen) = file_property_realm_indexed(true); + assert_eq!(r.run("var f = new File('/a'); it.file = f; f.changePath('/b'); it[0]").unwrap(), JsValue::String("/b".into())); + assert_eq!(*seen.borrow(), ["/a", "/b"]); +} + #[test] fn the_getter_gives_its_own_value_once_the_host_changes_a_file_property() { let (mut r, _) = file_property_realm(); diff --git a/docs/mcp.md b/docs/mcp.md index 9ef09de9ec..e98de1f512 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3264,7 +3264,8 @@ through `$`: `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and when the script's folders refuse one of those files, or a file-type or destination-collision check fails, none of - them is written. Destinations that resolve to the same file are refused. A write that fails once the + them is written. Destinations that resolve to the same file are refused, including two names in one folder that + differ only in letter case. A write that fails once the first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and From 36ba9c50df9f5af7a5dc202b4a89e90d92ec1870 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:34:51 -0800 Subject: [PATCH 19/42] Scripting: keep the placed image size message after app.open's limit The 256 MiB document limit sat in Disk::open_target, which placedItems' file assignment also calls, so an oversized image was refused as "Script document exceeds 256 MiB" before its own check ("is larger than 256 MiB") ran, and placed_file_refuses_bad_values_without_changing_the_document failed. app.open now checks the document size itself after open_target, and open_target still reports a failed metadata read as a read failure. --- crates/engine/src/script/dom/save_open.rs | 4 ++++ crates/engine/src/script/files.rs | 6 +----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 8dbac791bc..8cfe20efef 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -944,6 +944,10 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } // The command opens the given path; a real path that is not valid UTF-8 is still refused. let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; + // The document's size is read before any of it is; a placed image keeps its own limit and message. + if std::fs::metadata(&real).is_ok_and(|m| m.len() > super::super::files::MAX_OPEN_BYTES) { + return Err(refused(super::super::files::OPEN_TOO_LARGE, path)); + } plain(real)?; p.insert("path".into(), json!(plain(std::path::PathBuf::from(path))?)); let r = crate::cmd::fileio::with_read_limit(super::super::files::MAX_OPEN_BYTES as usize, || { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index b33e1c0c68..31ddbdacd2 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -726,13 +726,9 @@ impl Disk { Err(ScriptRead::Refused | ScriptRead::TooLarge) => return Err(ACCESS_DENIED), Err(ScriptRead::Failed(_)) => return Err(READ_FAILED), }; - let meta = std::fs::metadata(&real).map_err(|_| READ_FAILED)?; - if !meta.is_file() { + if !std::fs::metadata(&real).map_err(|_| READ_FAILED)?.is_file() { return Err(NOT_REGULAR); } - if meta.len() > MAX_OPEN_BYTES { - return Err(OPEN_TOO_LARGE); - } Ok(real) } From 844c1658ca3178b7d43dc699dfef8e8ef9b158ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 02:54:00 -0800 Subject: [PATCH 20/42] Canvas, Gradient, Home: drop the stop-popover and Space Hand workarounds, test Home's scrolling The craft-libs pin now carries storytold/craft-libs#5131, #5056 and #5193, which fix these in the framework: - Gradient panel: the slider no longer drags a stop on the press of the double click that opens the stop's popover (#5131). The panel's color_press and color_drag fields and the early return that dropped that press's edits are removed. The test gradient_stop_popover_stays_open_when_the_double_click_drifts still passes without them. - Canvas: the tool host ends a momentary Hand whose key went up while the canvas was away (#5056). end_missed_momentary, note_momentary_keys, their calls and CanvasCache::momentary_keys are removed. Both Space Hand tests still pass without them. - Home: a Column start page whose column fits the view no longer scrolls for the margin under it (#5193). A new test shows the whole window with no recent files: at 1440 by 900 a wheel over the title leaves it in place, and at 1280 by 800, where the column is taller than the view, the page scrolls. --- crates/ui-egui/src/app.rs | 1 - crates/ui-egui/src/caches.rs | 3 -- crates/ui-egui/src/canvas/tool_adapter.rs | 44 ++--------------------- crates/ui-egui/src/panels/gradient.rs | 22 ------------ crates/ui-egui/src/tests/home.rs | 44 +++++++++++++++++++++++ 5 files changed, 47 insertions(+), 67 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 25170c9f12..13b36e3d3d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -149,7 +149,6 @@ impl VectorcraftApp { spelling: Default::default(), text_nodes: Default::default(), momentary: None, - momentary_keys: vec![], hand: None, zoom_tool: None, selection_box: None, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index d2809d5846..6dcec22bff 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -81,9 +81,6 @@ pub struct CanvasCache { /// The Hand, Zoom and Rotate View tools the Space key and its chords lend the canvas, between /// passes; the tool adapter takes it out for its call and puts it back. pub momentary: Option, - /// The keys down when the held momentary command started; empty while none is held or when none started it. - /// Temporary, with `tool_adapter::end_missed_momentary` (craft-libs#5056). - pub momentary_keys: Vec, pub hand: Option, /// The selected Zoom tool keeps its press and drag rectangle between canvas passes. pub zoom_tool: Option, diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 58e735257e..1136fda54d 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -7,8 +7,8 @@ use craft::behavior::{CancelReason, CanvasView, Cursor, PointerKind as Device, P use craft::keymap::{Chord, Key}; use craft::ui::canvas::ToolPath; use craft::ui::canvas::{ - Autoscroll, CanvasTool, Momentary, MomentaryCommands, MomentaryShift, ToolAction, ToolClaims, ToolContext, ToolHost, ToolHostResponse, ToolKey, - ToolPass, ToolPointer, + Autoscroll, CanvasTool, Momentary, MomentaryShift, ToolAction, ToolClaims, ToolContext, ToolHost, ToolHostResponse, ToolKey, ToolPass, + ToolPointer, }; use serde_json::json; use vectorcraft_engine::ViewInfo; @@ -610,37 +610,6 @@ impl CanvasTool for SessionTool<'_> { } } -/// Ends the held momentary command (Space's Hand, Cmd+Space's Zoom...) once none of the keys that were down when it -/// started is down, and returns the command still held. The shortcut board drops a queued release when the canvas -/// does not run on the frame the key goes up (a dialog or another tab in front). A hold that started with no key down -/// (automation) lasts until its release. -/// -/// Temporary: craft-libs#5056 ends the hold inside the tool host. Remove this function, [`note_momentary_keys`], -/// their calls and `CanvasCache::momentary_keys` once the craft-libs pin includes that change. -fn end_missed_momentary(ctx: &egui::Context, momentary: &mut Momentary, keys: &mut Vec) -> Option { - let held = momentary.held()?; - if keys.is_empty() { - return Some(held); - } - let down = craft::ui::runtime::keys::held(ctx); - if keys.iter().any(|key| down.contains(key)) { - return Some(held); - } - momentary.fired(held, craft::ui::runtime::commands::FirePhase::Release); - keys.clear(); - None -} - -/// Notes the keys down when a momentary command starts (or changes), for [`end_missed_momentary`]; `before` is the -/// command held before the tool host's pass. -fn note_momentary_keys(ctx: &egui::Context, before: Option, momentary: &Momentary, keys: &mut Vec) { - match momentary.held() { - None => keys.clear(), - Some(held) if before != Some(held) => *keys = craft::ui::runtime::keys::held(ctx), - Some(_) => {} - } -} - /// Runs the tool host on `tool` with the app's momentary set, which the app keeps across passes. A finger, once a pen /// has been seen, only navigates (palm rejection). fn host_run(app: &mut VectorcraftApp, ui: &Ui, pass: &ToolPass, tool: &mut dyn CanvasTool) -> ToolHostResponse { @@ -648,9 +617,7 @@ fn host_run(app: &mut VectorcraftApp, ui: &Ui, pass: &ToolPass, tool: &mut dyn C let mut momentary = app.canvas.momentary.take().unwrap_or_else(|| Momentary::new(options).shift(MomentaryShift::RotateView)); momentary.set_options(options); momentary.hand_selected(app.session.tool_id() == "hand"); - let before = end_missed_momentary(ui.ctx(), &mut momentary, &mut app.canvas.momentary_keys); let response = ToolHost::new().momentary(&mut momentary).navigates(crate::touch::finger_navigates_only()).run(ui, pass, tool); - note_momentary_keys(ui.ctx(), before, &momentary, &mut app.canvas.momentary_keys); app.canvas.momentary = Some(momentary); response } @@ -783,14 +750,9 @@ fn host_run_session(tool: &mut SessionTool<'_>, ui: &Ui, pass: &ToolPass) -> Too let mut momentary = app.canvas.momentary.take().unwrap_or_else(|| Momentary::new(options).shift(MomentaryShift::RotateView)); momentary.set_options(options); momentary.hand_selected(app.session.tool_id() == "hand"); - let mut keys = std::mem::take(&mut app.canvas.momentary_keys); drop(app); - let before = end_missed_momentary(ui.ctx(), &mut momentary, &mut keys); let response = ToolHost::new().momentary(&mut momentary).navigates(crate::touch::finger_navigates_only()).run(ui, pass, tool); - note_momentary_keys(ui.ctx(), before, &momentary, &mut keys); - let mut app = tool.app(); - app.canvas.momentary = Some(momentary); - app.canvas.momentary_keys = keys; + tool.app().canvas.momentary = Some(momentary); response } diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 9d6088cbd3..4c8122fa77 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -102,13 +102,6 @@ pub struct GradientUi { /// `paint.editGradient` sorts the stops, so the gradient shown mid-gesture is the last preview /// re-sorted: the editor's tags name stops of this one. pub(crate) begun: Option>, - /// The press of a double click that asked for a stop's color is still held. Until craft-libs#5131 reaches the - /// pin, the slider also drags the stop when the pointer drifts during that press, and the moved stop closes the - /// popover the double click opened: the panel drops that press's slider edits. - pub(crate) color_press: bool, - /// The slider's gesture that the press above began, dropped until its `Commit` or `Cancel`, which can arrive in a - /// pass after the button is up. - pub(crate) color_drag: bool, } /// Select stop `i` (the session's selected stop, shared with the Gradient tool's annotator, the @@ -836,21 +829,6 @@ fn stops_editor(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gra .shared_selection(Bind::bound(&mut shared)) .drop_target::() .show(ui); - let panel = &mut app.ui.gradient_panel; - let color_press = panel.color_press || out.color_requested.is_some(); - let held = craft::ui::runtime::pointer::press_state(ui.ctx()).buttons.contains(craft::behavior::Buttons::PRIMARY); - let dropping = panel.color_drag || (color_press && out.edit.events.began()); - let ended = matches!(out.edit.events.last(), Some(EditEvent::Commit { .. } | EditEvent::Cancel { .. } | EditEvent::Set { .. })); - panel.color_press = color_press && held; - panel.color_drag = dropping && !ended; - if color_press || dropping { - // The drift of the press that asked for the color moves no stop (craft-libs#5131). - if is_grad && let Some(request) = &out.color_requested { - let at = request.rect.map_or(out.edit.response.rect.left_bottom(), |r| r.left_bottom()); - open_popover(app, request.index, at); - } - return; - } let events = &out.edit.events; if !is_grad { // The slider shows the default gradient: an edit of it applies a gradient first. diff --git a/crates/ui-egui/src/tests/home.rs b/crates/ui-egui/src/tests/home.rs index 50991b8d8c..77748f68f5 100644 --- a/crates/ui-egui/src/tests/home.rs +++ b/crates/ui-egui/src/tests/home.rs @@ -125,6 +125,50 @@ fn home_screen(app: VectorcraftApp) -> Panel { home } +/// Where one frame of the whole window `size` big painted Home's title, after `events`. +fn home_title_after(app: &mut VectorcraftApp, ctx: &egui::Context, size: egui::Vec2, events: Vec) -> egui::Rect { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }; + let out = crate::testing::app_frame(app, ctx, raw); + let titles: Vec = crate::tests_labels::painted_shapes(&out.shapes) + .into_iter() + .filter_map(|(shape, transform, _)| match shape { + egui::Shape::Text(t) if t.galley.text() == "Welcome to VectorCraft" => Some(transform * t.visual_bounding_rect()), + _ => None, + }) + .collect(); + assert_eq!(titles.len(), 1, "Home paints its title once: {titles:?}"); + titles[0] +} + +/// How far a wheel turned to the end over Home's title moves the title, with no recent files in a window `size` big. +fn home_title_moved_by_a_wheel(size: egui::Vec2) -> f32 { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + home_title_after(&mut app, &ctx, size, vec![]); + } + assert!(crate::menus::home_showing(&app), "Home with no document open"); + let before = home_title_after(&mut app, &ctx, size, vec![]); + home_title_after(&mut app, &ctx, size, vec![egui::Event::PointerMoved(before.center())]); + home_title_after(&mut app, &ctx, size, vec![craft::ui::testing::pointer::wheel(-2000.0)]); + let mut after = before; + for _ in 0..3 { + after = home_title_after(&mut app, &ctx, size, vec![]); + } + after.top() - before.top() +} + +/// At the app's default window size, Home's column fits the canvas view, so the page has no room to scroll and shows no +/// scroll bar beside the docks: a wheel leaves the title where it is. In a smaller window, where the Learn cards stand +/// two by two and the column is taller than the view, the page scrolls. +#[test] +fn home_scrolls_only_when_its_column_is_taller_than_the_window() { + let moved = home_title_moved_by_a_wheel(egui::vec2(1440.0, 900.0)); + assert!(moved.abs() < 0.5, "at 1440 by 900 the column fits, so the page does not scroll: moved {moved}"); + let moved = home_title_moved_by_a_wheel(egui::vec2(1280.0, 800.0)); + assert!(moved < -1.0, "at 1280 by 800 the column is taller than the view, so the page scrolls: moved {moved}"); +} + /// Home's Open while a file dialog is still open (a window the system may have placed out of sight) /// says so in the status bar and asks for no second picker; once the first answers, Open asks again /// (#6160). From d70ab835f34e49eb7b304a316df6e6a9b4e712f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 15:30:10 -0800 Subject: [PATCH 21/42] Automation: a dropped file stays confined until its drop is delivered A drop of files the OS made in a pass that carried injected input was confined to the automation roots only through the next root frame. The drag session holds a drop that comes without a pointer position until a later pass resolves its target, so a drop delivered after that frame could open a file outside the roots. The app now keeps the dropped files the drag session holds and confines every pass until the session lets them go, the pass that delivers them included. A new test drops a file after a hover with a pointer position, in a pass without one, and checks that the drop is refused when it is delivered two passes later. --- crates/ui-egui/src/app.rs | 23 ++++++++++++++------- crates/ui-egui/src/lib.rs | 7 ++++--- crates/ui-egui/src/tests/automation.rs | 28 ++++++++++++++++++++++---- 3 files changed, 44 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 7adfcccd1f..cf6e35b4ae 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -11,6 +11,7 @@ use craft::ui::docking::IconGroupSeparator; use craft::ui::list::{CommandHighlight, ThumbRows}; use craft::ui::menu::{MenuTitleLook, MenuTitlePad}; use craft::ui::patterns::form_dialogs::PresetCardLook; +use craft::ui::runtime::drag::{self, OsFiles}; use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey, WordsOverride, with_env}; use craft::ui::runtime::frame::{FrameInput, FrameOutput}; use craft::ui::runtime::toast::{self, Toast}; @@ -361,18 +362,26 @@ impl VectorcraftApp { } /// The folders this pass may read and write: the automation roots while the pass carries - /// input the control channel injected, or delivers files the OS dropped in such a pass; - /// anywhere otherwise. + /// input the control channel injected, or while the drag session still holds files the OS + /// dropped in such a pass; anywhere otherwise. fn automation_scope(&self, ctx: &egui::Context) -> Option> { - let delivers = self.confined_drop.is_some_and(|last| ctx.cumulative_frame_nr_for(egui::ViewportId::ROOT) <= last); - (WindowHost::of(ctx).injected_pass() || delivers).then(|| self.automation_roots.clone()).flatten() + (WindowHost::of(ctx).injected_pass() || self.confined_drop.is_some()).then(|| self.automation_roots.clone()).flatten() } - /// Notes files the OS dropped in a pass that carries injected input: the drag session delivers - /// them in the next root frame, which [`Self::automation_scope`] confines too. + /// Keeps the files the OS dropped in a pass that carries injected input until the drag session + /// lets them go: it delivers them in a later pass, after their target is resolved, and + /// [`Self::automation_scope`] confines every pass until then. fn note_confined_drop(&mut self, ctx: &egui::Context) { + if self.automation_roots.is_none() { + return; + } + let held = || drag::active::(ctx); if WindowHost::of(ctx).injected_pass() && ctx.input(|i| !i.raw.dropped_files.is_empty()) { - self.confined_drop = Some(ctx.cumulative_frame_nr_for(egui::ViewportId::ROOT) + 1); + self.confined_drop = held(); + } else if let Some(dropped) = &self.confined_drop + && !held().is_some_and(|now| Arc::ptr_eq(&now, dropped)) + { + self.confined_drop = None; } } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 115af4ac32..c3412f24db 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -346,9 +346,10 @@ pub struct VectorcraftApp { /// (`--automation-read-root`, `--automation-write-root`); `None`: anywhere. See /// [`Self::with_automation_roots`]. automation_roots: Option>, - /// The last root frame of a drop of files the OS made in a pass that carried injected input: the drag session - /// delivers that drop in the next frame, which [`Self::ui`] confines to the automation roots as well. - confined_drop: Option, + /// The files the OS dropped in a pass that carried injected input, while the drag session holds them: every pass + /// until the session lets them go, the one that delivers them included, is confined to the automation roots as well + /// ([`Self::ui`]). + confined_drop: Option>, /// The agents link while the ArtCraft Launcher's switch may let agents in ([`Self::with_agents`]). #[cfg(not(target_arch = "wasm32"))] pub(crate) agents: Option>, diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index b8798e6cfa..7bdc89069f 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -580,10 +580,24 @@ fn a_drop_in_a_pass_with_one_step_of_injected_input_is_confined_when_delivered() drop_in_an_injected_pass_is_confined("ui.text", json!({"text": "a"})); } +/// The OS held the file under the pointer and drops it in a pass with no pointer position: the drag +/// session holds the drop until a later pass resolves its target, and the drop is still refused when +/// it is delivered there. +#[test] +fn a_drop_that_waits_for_its_target_is_confined_when_delivered() { + drop_is_confined("ui.text", json!({"text": "a"}), true); +} + /// Injects `method` with `params`, has the person drop a file outside the automation roots in the /// same pass, and checks that the drop opens nothing, then that a later drop of the person's opens /// the file. fn drop_in_an_injected_pass_is_confined(method: &str, params: Value) { + drop_is_confined(method, params, false); +} + +/// [`drop_in_an_injected_pass_is_confined`]; `pointer`: the pass that hovers the file carries a +/// pointer position and the drop's pass none, so the drag session delivers the drop a pass later. +fn drop_is_confined(method: &str, params: Value, pointer: bool) { #[derive(Debug)] struct Dropped(PathBuf); impl egui::DroppedFile for Dropped { @@ -602,6 +616,12 @@ fn drop_in_an_injected_pass_is_confined(method: &str, params: Value) { let mut raw = egui::RawInput::default(); if hovered { raw.hovered_files.push(egui::HoveredFile { path: Some(outside.clone()), mime: String::new() }); + if pointer { + raw.events.push(egui::Event::PointerMoved(egui::pos2(300.0, 300.0))); + } + } + if dropped && pointer { + raw.events.push(egui::Event::PointerGone); } if dropped { raw.dropped_files.push(std::sync::Arc::new(Dropped(outside.clone()))); @@ -614,13 +634,13 @@ fn drop_in_an_injected_pass_is_confined(method: &str, params: Value) { tx.send(req).unwrap(); app.run_control(&ctx); pass(&mut app, false, true); - // The drag session delivers a drop of files in the pass after the one the OS dropped them in. - assert_eq!(pass(&mut app, false, false), 0, "{method}: the drop of the pass carrying the input is confined"); - for _ in 0..4 { - pass(&mut app, false, false); + // The drag session delivers a drop of files in a pass after the one the OS dropped them in. + for _ in 0..5 { + assert_eq!(pass(&mut app, false, false), 0, "{method}: the drop of the pass carrying the input is confined"); } pass(&mut app, true, false); pass(&mut app, false, true); + pass(&mut app, false, false); assert_eq!(pass(&mut app, false, false), 1, "{method}: the person's pass is not"); let _ = std::fs::remove_dir_all(base); } From 7c2994d78e8db75405eedae30037372479b11f81 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 16:42:16 -0800 Subject: [PATCH 22/42] Tests: give each confined drop scenario its own fixture directory The two drop tests that inject `ui.text` both used the directory vc-ui-roots-synthetic-ui.text-. Tests run in parallel, and each one removes that directory during setup and cleanup, so one test could delete outside/b.svg before the other's final drop. The tag now also names whether the scenario moves the pointer. --- crates/ui-egui/src/tests/automation.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index 7bdc89069f..9bc6810b71 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -608,7 +608,8 @@ fn drop_is_confined(method: &str, params: Value, pointer: bool) { std::fs::read(&self.0).map_err(|e| e.to_string()) } } - let (mut app, tx, base) = confined(&format!("synthetic-{method}")); + // Each scenario has its own directory, so tests running in parallel do not remove each other's files. + let (mut app, tx, base) = confined(&format!("synthetic-{method}-{}", if pointer { "pointer" } else { "nopointer" })); let ctx = crate::testing::ui_context(); let outside = base.join("outside/b.svg"); // The OS holds the file over the window in the pass before it drops it (`hovered`), as a desktop drag does. From aabe8f210793f1133b3f54ae89530427d5cef583 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 18:58:53 -0800 Subject: [PATCH 23/42] Type: new type takes new art's fills, strokes and effects text.create gave new type an empty appearance whatever new art's template held, so type made with the Type tools ignored New Art Has Basic Appearance off and a graphic style picked with nothing selected. New type now takes the template's fills, strokes and effects when the template is more than one plain fill and stroke or comes from a graphic style. With Override Character Color on, its characters lose the fill and stroke the template paints, as when a style is applied to type; a color given to text.create keeps the characters' fill. With the option on and no style picked, new type is unchanged. Type keeps its own opacity and blend mode, as before. Docs: docs/mcp.md (New art), docs/target-app-parity.md. --- crates/engine/src/cmd/create.rs | 19 ++++--- crates/engine/src/cmd/newart.rs | 14 ++++++ crates/engine/src/cmd/style.rs | 7 ++- crates/engine/src/tests/newart.rs | 84 +++++++++++++++++++++++++++++++ docs/mcp.md | 5 ++ docs/target-app-parity.md | 1 + 6 files changed, 122 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 934151589b..e41d9bbe06 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -174,7 +174,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on. When new art's template is more than one plain fill and stroke (New Art Has Basic Appearance off) or comes from a graphic style picked with nothing selected, the type takes its fills, strokes and effects, and with Override Character Color on its characters lose the fill and stroke those paint (a `color` given keeps the fill)", has_doc, text_create ), @@ -988,11 +988,11 @@ fn text_parent(s: &Session, p: &Value) -> Result> { } /// New type `kind` on top of the contents of `parent`, whatever the drawing mode; selected. -fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, bbox_angle: f64) -> Result { +fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, look: NewArt, bbox_angle: f64) -> Result { let id = s.edit("Type", |d, sel| { let id = d.alloc_id(); let mut n = Node::new(id, kind); - NewArt::plain(Appearance::default()).apply(d, &mut n); + look.apply(d, &mut n); super::object::align_new_object(d, &mut n); n.bbox_angle = bbox_angle; d.insert(Some(parent), usize::MAX, n)?; @@ -1040,11 +1040,16 @@ fn text_create(s: &mut Session, p: &Value) -> Result { // Lays the text out (and sizes an Auto Size frame). super::typecmd::refresh_bounds(&mut t); } + // New art's fills, strokes and effects (New Art Has Basic Appearance off, or a graphic style + // picked with nothing selected), with the characters' paint under Override Character Color as + // graphicStyle.apply gives type; a `color` given keeps the characters' fill. + let look = s.new_type_look(); + if s.prefs.override_char_color { + super::style::override_text_chars(&mut t, &look.appearance, p.get("color").and_then(color_value).is_none()); + } let made = match parent { - Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), bbox_turn(rotation))?, - None => { - insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)? - } + Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), look, bbox_turn(rotation))?, + None => insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), look, None, true, bbox_turn(rotation), true)?, }; let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index d719434f28..1b787420d2 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -335,6 +335,20 @@ impl Session { NewArt { appearance, opacity, blend, style: style.map(str::to_string), unit_box: true } } + /// The look of new type (`text.create`): the template's fills, strokes and effects when it is + /// more than one plain fill and stroke or comes from a graphic style, else none of its own, so + /// the characters' fill and stroke show. The template is not repainted with the fill and + /// stroke proxies. + pub(crate) fn new_type_look(&self) -> NewArt { + let plain = || NewArt::plain(Appearance::default()); + let Some(t) = self.template() else { return plain() }; + let (opacity, blend, style) = self.new_art_transparency(); + if t.is_basic() && style.is_none() { + return plain(); + } + NewArt { appearance: t.into_owned(), opacity, blend, style: style.map(str::to_string), unit_box: true } + } + /// The appearance of the next object drawn (the Appearance panel shows it with nothing /// selected). Placed gradients are relative to the unit box. pub fn new_art(&self) -> Appearance { diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 05fa6ce85f..699f3cdec7 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -257,7 +257,12 @@ pub(crate) fn captured(n: &Node) -> Appearance { /// fills, and their stroke when it has strokes. fn override_chars(n: &mut Node, ap: &Appearance) { let NodeKind::Text(t) = &mut n.kind else { return }; - let (fills, strokes) = (ap.items.iter().any(|i| i.is_fill()), ap.items.iter().any(|i| !i.is_fill())); + override_text_chars(t, ap, true); +} + +/// [`override_chars`] for type `t`; with `fill` false its characters keep their fill. +pub(crate) fn override_text_chars(t: &mut vectorcraft_doc::TextObject, ap: &Appearance, fill: bool) { + let (fills, strokes) = (fill && ap.items.iter().any(|i| i.is_fill()), ap.items.iter().any(|i| !i.is_fill())); for r in &mut t.runs { if fills { r.style.fill = Paint::None; diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index 6737666046..6bebbb236a 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -474,3 +474,87 @@ fn set_new_art_refuses_while_new_art_takes_the_selected_look() { assert_eq!(run(&mut s, "appearance.setNewArt", json!({"weight": 7})), json!({"changed": true})); assert_eq!(s.new_art().stroke().unwrap().width, 7.0); } + +fn new_type(s: &mut Session, p: Value) -> Node { + let id = NodeId(run(s, "text.create", p)["id"].as_u64().unwrap()); + node(s, id) +} + +/// The fill of `n`'s first run of characters. +fn char_fill(n: &Node) -> Paint { + match &n.kind { + vectorcraft_doc::NodeKind::Text(t) => t.runs[0].style.fill.clone(), + _ => panic!("{} is not type", n.id.0), + } +} + +/// Type with a second fill and a drop shadow on the object, selected. +fn styled_type(s: &mut Session) -> NodeId { + let id = NodeId(run(s, "text.create", json!({"x": 20, "y": 60, "text": "RIP", "size": 30}))["id"].as_u64().unwrap()); + run(s, "appearance.addFill", json!({})); + run(s, "paint.setFill", json!({"color": "#ff0000"})); + run(s, "effect.apply", json!({"effect": "stylize.dropShadow"})); + id +} + +#[test] +fn with_basic_appearance_off_new_type_takes_the_last_selections_fills_and_effects() { + let mut s = session(); + let group = run(&mut s, "object.newGroup", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "select.none", json!({})); + let src = styled_type(&mut s); + let from = node(&s, src).appearance; + assert_eq!(from.effects.len(), 1); + run(&mut s, "appearance.setNewArtBasic", json!({"on": false})); + run(&mut s, "select.set", json!({"ids": [src.0]})); + run(&mut s, "select.none", json!({})); + let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "new"})); + assert_eq!(n.appearance.effects.len(), 1, "the drop shadow"); + assert_eq!(n.appearance.items.iter().filter(|i| i.is_fill()).count(), from.items.iter().filter(|i| i.is_fill()).count()); + assert_eq!(n.appearance.fill_paint(), from.fill_paint(), "the template keeps its own fill"); + // Override Character Color: the object's fill shows instead of the characters' own. + assert_eq!(char_fill(&n), Paint::None); + // Type placed in a group takes it too, and a color given keeps the characters' fill. + run(&mut s, "select.set", json!({"ids": [src.0]})); + run(&mut s, "select.none", json!({})); + let g = new_type(&mut s, json!({"x": 200, "y": 250, "text": "in", "parent": group, "color": "#00ff00"})); + assert_eq!(g.appearance.effects.len(), 1); + assert_ne!(char_fill(&g), Paint::None); +} + +#[test] +fn new_type_keeps_plain_characters_without_a_template_beyond_a_basic_fill_and_stroke() { + let mut s = session(); + let plain = new_type(&mut s, json!({"x": 20, "y": 60, "text": "a"})); + assert!(plain.appearance.items.is_empty() && plain.appearance.effects.is_empty()); + // Option on: a styled selection gives new type only its basic paints, so it stays plain. + let src = styled_type(&mut s); + run(&mut s, "select.none", json!({})); + let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "b"})); + assert_eq!((n.appearance.items.len(), n.appearance.effects.len(), char_fill(&n)), (0, 0, char_fill(&plain))); + // Option off with plain type last selected: its characters' basic look, no fills of the object. + run(&mut s, "appearance.setNewArtBasic", json!({"on": false})); + run(&mut s, "select.set", json!({"ids": [n.id.0]})); + run(&mut s, "select.none", json!({})); + let m = new_type(&mut s, json!({"x": 200, "y": 250, "text": "c"})); + assert_eq!((m.appearance.items.len(), char_fill(&m)), (0, char_fill(&plain))); + assert!(node(&s, src).appearance.effects.len() == 1, "the source keeps its look"); +} + +#[test] +fn a_graphic_style_clicked_with_nothing_selected_styles_the_next_type() { + let mut s = session(); + fancy(&mut s); + let name = run(&mut s, "graphicStyle.new", json!({"name": "Fancy"}))["name"].as_str().unwrap().to_string(); + run(&mut s, "select.none", json!({})); + run(&mut s, "graphicStyle.apply", json!({"name": name})); + let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "styled"})); + assert_eq!((n.appearance.items.iter().filter(|i| i.is_fill()).count(), n.appearance.effects.len()), (2, 1)); + assert_eq!(char_fill(&n), Paint::None); + // With Override Character Color off the characters keep their fill under the style's. + run(&mut s, "graphicStyle.setOptions", json!({"overrideCharColor": false})); + run(&mut s, "select.none", json!({})); + let kept = new_type(&mut s, json!({"x": 200, "y": 250, "text": "kept"})); + assert_eq!(kept.appearance.effects.len(), 1); + assert_ne!(char_fill(&kept), Paint::None); +} diff --git a/docs/mcp.md b/docs/mcp.md index 6d416ac78e..2ef4e77266 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11442,6 +11442,11 @@ the weight from it: only a paint or weight the selected objects share, and art w colorized) changes nothing. With the option off (`appearance.setNewArtBasic {on: false}`, the preference `newArtBasic`) new art takes the whole appearance of the last selected object. `appearance.newArt` reports what the next object gets; `paint.default` resets it. +New type (`text.create`) takes the template's fills, strokes and effects when the template is more than one plain fill +and stroke or comes from a graphic style; otherwise it has no fills or strokes of its own and its characters keep their +color. With Override Character Color on, its characters lose the fill and stroke the template paints, as when a +graphic style is applied to type; a `color` given to `text.create` keeps the characters' fill. The type keeps its own +opacity and blend mode. `appearance.setNewArtBasic` rejects an `on` value that is not a boolean. Omitting `on` toggles the current preference. `appearance.setNewArt {fill?, stroke?, weight?, cap?, join?, miterLimit?, dash?, dashOffset?, fillOverprint?, strokeOverprint?}` sets new art's fill, stroke and stroke options whatever is selected, and leaves the selection, its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bfccfd4a5a..2115ac0695 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -782,6 +782,7 @@ since 2026-10-01. - **PDF editable import:** Place from bytes or a path with `link: false`, and `clipboard.importPdf` followed by Paste, preserve live type on the selected page. Place still honors `textAs: "outlines"`. Synthetic two-page regressions: `crates/engine/src/cmd/fileio/tests_pdffidelity.rs`. No change to the PDF reader's existing fallback rules. - **Tab stops in `.ai`/EPS type and right-aligned lines with tabs (#6147):** type from the text document keeps its paragraphs' tab stops (key 30: positions and left, center, right and decimal alignments; leaders aren't read), at most 1,024 a paragraph and 2^20 a story, past which the default stops apply with a warning. In right-aligned area type, the text before a line's last tab sits at its stops, measured from the left edge, and the text after it (none when the tab ends the line, with its hyphen when the line is hyphenated) against the right edge; centred and justified lines, point type and right-to-left paragraphs are aligned as a whole as before. Evidence: `ate::tests::a_paragraph_keeps_its_tab_stops`, `ate::tests::a_story_s_tab_stops_are_bounded`, `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`, `import_fuzz::text_frames_with_hostile_paragraph_attributes_never_panic`. Scores unchanged. - **`.ai`/EPS graphic styles that paint with a named gradient:** a graphic style library's style (or a file's listed style) whose fill, or the fill or stroke of a style of one paint, paints with one of the file's gradients by name loads with that gradient at the style's angle, fitted to the bounds of each object it is applied to (VectorCraft's own placement; the style stores only the gradient's name and angle). A style naming a gradient the file doesn't define, or painting with a pattern, is still left out. Evidence: `fileio::tests_aiimport::graphic_styles_in_a_ai_library_that_paint_with_a_named_gradient_load_with_it`, `style::tests::a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on`. Scores unchanged. +- **New type takes new art's appearance:** with New Art Has Basic Appearance off, new objects take every appearance attribute of the current appearance ([Edit appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/edit-appearance-attributes.html)). Type made with the Type tools (`text.create`) now takes the template's fills, strokes and effects when the template is more than one plain fill and stroke or comes from a graphic style picked with nothing selected, and with Override Character Color on its characters lose the fill and stroke those paint. With the option on and no style picked, new type is unchanged. Evidence: `tests::newart::with_basic_appearance_off_new_type_takes_the_last_selections_fills_and_effects`, `tests::newart::new_type_keeps_plain_characters_without_a_template_beyond_a_basic_fill_and_stroke`, `tests::newart::a_graphic_style_clicked_with_nothing_selected_styles_the_next_type`. Scores unchanged. - **`.ai`/EPS type laid out closer to the file's page (#6137):** type from the text document keeps auto leading as auto, each line taking the paragraph's Auto Leading share (key 7) of the largest type on it ([Line and character spacing](https://helpx.adobe.com/illustrator/using/line-character-spacing.html)); the paragraph's hyphenation options (keys 10 to 15) are read; area type of one frame whose last lines the file sets, but which don't fit here, may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines and no more than the file has (`vectorcraft_text::fit_source_lines`), with a warning when it does: the frame can stay as it is, or show only some of them; and a line a soft return ends is justified as a wrapped line is, a paragraph's last line keeping its alignment. Evidence: `ate::tests::auto_leading_follows_the_size_of_each_line`, `ate::tests::a_paragraph_keeps_its_auto_leading`, `ate::tests::a_paragraph_keeps_its_hyphenation_options`, `ate::tests::the_last_lines_the_file_sets_in_its_frame_show`, `tests::fit_source_lines_keeps_the_last_lines_the_source_sets`, `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores unchanged. - **Graphs saved to `.ai` keep their data and settings:** a grouped column, stacked column, line or area graph is written to a `.ai` file, in either form, with the records the `.ai` reader reads (`crates/eps/src/import/ai/read/graph.rs`, #7311): `%_Gs`, its plot, type, settings, axes and table, its series' groups each tagged `Go`, and `%_GS` ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), §17 and appendix A). The file opens again with the same live graph. A graph with settings the reader doesn't keep, graph designs, label formatting, more than 10,000 categories or 256 series, or art the reader doesn't attach a graph to is written as its art, with a warning. `crates/eps/src/legacy_ai/tests.rs` and `crates/eps/src/ai_editing/tests.rs` write and read back each kind of graph; `a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns` checks every graph type the graph tools draw. Scores unchanged. - **Graph legend swatches have their series' stroke:** a default legend swatch of a stacked column, stacked bar, area or pie series has the thin white stroke of the series' marks (VectorCraft's own rule), beside the plot or across the top, and a stroke kept on the series is on the swatch too. Each series' group then paints with one stroke, so a stacked column or area graph the graph tools draw is saved to `.ai` with its data and settings and opens again as a live graph; a stacked bar graph is still written as its art, as the reader has no type for it. Evidence: `cmd::graph::tests::a_legend_swatch_has_the_stroke_of_its_series_marks`, `cmd::graph::tests::a_drawn_stacked_column_graph_saved_as_ai_opens_as_a_graph_that_takes_new_data`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`. Scores unchanged. From 88a997db16dda8b42c3f056b10846ed9a2642ec6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 21:17:22 -0800 Subject: [PATCH 24/42] Canvas: pans move the view by whole pixels of the art's frame A pan by part of a device pixel (a trackpad, an eased wheel line, a middle-button drag at a fractional display scale) moved the view so that the art's frame no longer differed from the last one by whole pixels. The render worker then rendered the whole canvas again for every step instead of moving the frame it kept. The canvas now moves each pan by the whole number of frame pixels nearest to it and keeps the part of a pixel left over for the next pan, so steps under half a pixel still add up. A Hand, scroll bar or compass drag sets the view from where the drag started, and is rounded without the earlier remainder. A zoom, a turn, a resize or a view the app sets is not rounded. This is a temporary change in VectorCraft's canvas code until storytold/craft-libs#5411, which makes the framework's pans move by whole device pixels, reaches VectorCraft's craft-libs pin. The pin bump that brings it in removes this code. --- crates/ui-egui/src/canvas.rs | 114 ++++++++++++++- crates/ui-egui/src/canvas/tests.rs | 221 +++++++++++++++++++++++++++++ crates/ui-egui/src/state.rs | 5 + 3 files changed, 334 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 73b97bce0f..584137c1c4 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -146,6 +146,8 @@ struct Body { edited: Option, /// The Quick Pen tool took this pass's wheel for its arc size ([`quick_pen_wheel::arc_size`]). arc_view: Option, + /// What this pass's pan by whole device pixels left ([`pan_on_device_pixels`]). + pan: Option, } /// Window `win`'s document in the framework canvas, filling the rest of `ui`. True when the canvas @@ -265,8 +267,14 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin pass.view = Some(arc_view); } } + // The canvas's own pans (the wheel, a middle-button drag, keys) move the view by a step from where it was. + let pan = (!measuring).then(|| { + let rest = doc_windows::view(app, win).and_then(|v| v.pan_rest.filter(|rest| rest.kept == Some((v.center, v.zoom, v.rotation)))); + pan_on_device_pixels(rest, ui.ctx().input(|i| i.max_texture_side), &mut space, pass.as_mut()) + }); body = with_canvas_space(ui, space, |ui| show_body(app, ui, &space, pass.as_ref(), win, kind, bar_shapes)); body.arc_view = arc_turn.then_some(arc_view); + body.pan = pan; } }); let output = shown.output; @@ -279,7 +287,7 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin rulers::apply(app, ui, out); } let pressed = matches!(output.press.phase, PressPhase::Down { .. }); - let Body { reply, context_at, context_key, edited, arc_view } = body; + let Body { reply, context_at, context_key, edited, arc_view, pan } = body; let request = reply .as_ref() .and_then(|r| r.context.as_ref()) @@ -288,13 +296,17 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin let jumped = edited.is_some(); // Presentation Mode keeps its view through a drag of the middle button, which the canvas pans on its own, and a // wheel turn the Quick Pen tool takes for its arc size leaves other view requests in place. - let view_now = if presenting && ui.input(|i| i.pointer.middle_down()) { - given - } else { - edited.or(reply.and_then(|r| r.view)).or(arc_view).or(output.view).unwrap_or(cv) - }; + let keeps_given = presenting && ui.input(|i| i.pointer.middle_down()); + let pan = pan.filter(|_| !keeps_given); + let view_now = + if keeps_given { given } else { edited.or(reply.and_then(|r| r.view)).or(arc_view).or(pan.map(|p| p.view)).or(output.view).unwrap_or(cv) }; + // Pointer drags of the Hand, compass and scroll bars request absolute views without carrying a rounding remainder. + let absolute_drag = (edited.is_some() || app.session.tool_id() == "hand" || tool_adapter::view_tool_held(app)) + && ui.input(|i| i.pointer.any_down() || i.pointer.any_released()); + let (view_now, pan) = settled_on_device_pixels(pan, view_now, !absolute_drag); if let Some(view) = doc_windows::view_mut(app, win) { view.set_canvas(&view_now, scaling); + view.pan_rest = pan.map(|rest| PanRest { kept: Some((view.center, view.zoom, view.rotation)), ..rest }); // Fitted once, the view stays where it is moved. view.fitted |= refit; // An edit of the compass or a scroll bar reaches the next pass, which stops a running ease. @@ -318,6 +330,96 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin pressed } +/// What a canvas pan by whole device pixels ([`pan_step`]) left: the view the canvas settled on, the device pixels a +/// point it was shown at, and the part of a device pixel along each screen axis the pan has not moved yet (at most half +/// a pixel each way). +/// +/// Temporary: storytold/craft-libs#5411 moves the canvas's pans and wheel steps by whole device pixels. Remove this, +/// [`crate::state::View::pan_rest`] and their callers with the craft-libs pin bump that brings it in. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct PanRest { + view: CanvasView, + pixels_per_point: f32, + owed: (f64, f64), + /// The app's center, zoom and rotation after keeping the settled view. + kept: Option<(vectorcraft_geom::Point, f64, f64)>, +} + +impl PanRest { + /// A rest of nothing after `view`, shown at `pixels_per_point`. + fn none(view: CanvasView, pixels_per_point: f32) -> Self { + Self { view, pixels_per_point, owed: (0.0, 0.0), kept: None } + } +} + +/// `view`, when it differs from `from` only in its center: the view that moves the document from where `from` draws it +/// by a whole number of device pixels at `pixels_per_point` along each screen axis, the number nearest to how far +/// `view` moves it plus `owed` device pixels, with what is left of a pixel. Exactly half a pixel left stays owed. None +/// when `view` differs from `from` in more than its center, or `pixels_per_point` or the views are not usable. +pub(crate) fn pan_step(from: CanvasView, view: CanvasView, owed: (f64, f64), pixels_per_point: f32) -> Option<(CanvasView, (f64, f64))> { + let ppp = f64::from(pixels_per_point); + let mut moved = from; + moved.center = view.center; + if moved != view || !(ppp.is_finite() && ppp > 0.0 && view.zoom.is_finite() && view.zoom > 0.0) { + return None; + } + let (a, b) = (from.affine() * vectorcraft_geom::Point::ZERO, view.affine() * vectorcraft_geom::Point::ZERO); + let total = ((b.x - a.x) * ppp + owed.0, (b.y - a.y) * ppp + owed.1); + let nearest = |t: f64| t.signum() * (t.abs() - 0.5).ceil().max(0.0); + let whole = (nearest(total.0), nearest(total.1)); + let shift = egui::vec2((a.x + whole.0 / ppp - b.x) as f32, (a.y + whole.1 / ppp - b.y) as f32); + if !(shift.x.is_finite() && shift.y.is_finite()) { + return None; + } + let mut shown = view; + if shift != egui::Vec2::ZERO { + shown.center = view.center - view.unmap_vec(shift); + } + (shown.center.x.is_finite() && shown.center.y.is_finite()).then_some((shown, (total.0 - whole.0, total.1 - whole.1))) +} + +/// Moves the view the canvas settled on in this pass (`space`'s target) from `rest.view` by whole pixels of the art's +/// frame ([`pan_step`], [`raster::frame_ppp`] with the display's largest texture side `max_side`), adding the part of a +/// pixel `rest` owes, and gives the tool host the same view in `pass`. The render worker then moves the frame it kept +/// ([`raster::render_job`]) instead of rendering the whole canvas for a pan by part of a pixel. Nothing is rounded while +/// a zoom eases, or when the app changed the view since `rest`. Returns the rest to keep. +fn pan_on_device_pixels(rest: Option, max_side: usize, space: &mut CanvasSpace, pass: Option<&mut ToolPass>) -> PanRest { + let target = space.target(); + // The pixels of the art's frame, which are fewer than the device's when the frame would be wider than `max_side`. + let ppp = raster::frame_ppp(target.rect.size(), space.pixels_per_point, max_side); + let step = rest.filter(|rest| !space.easing() && rest.pixels_per_point == ppp).and_then(|rest| { + let mut from = rest.view; + // Match zooms separated only by the UI scaling round trip. + if (from.zoom - target.zoom).abs() <= 1e-12 * from.zoom.abs().max(target.zoom.abs()) { + from.zoom = target.zoom; + } + pan_step(from, target, rest.owed, ppp) + }); + let Some((view, owed)) = step else { + return PanRest::none(target, ppp); + }; + if view != target { + space.set_view(view); + if let Some(pass) = pass { + pass.space = Some(*space); + pass.view = Some(view); + } + } + PanRest { view, pixels_per_point: ppp, owed, kept: None } +} + +/// `view`, the view the app keeps after this pass, moved from the view of `rest` by whole device pixels when it differs +/// from it in its center alone (a tool, a scroll bar or the compass panned it after [`pan_on_device_pixels`]), and the +/// rest to keep. +fn settled_on_device_pixels(rest: Option, view: CanvasView, carry: bool) -> (CanvasView, Option) { + let Some(rest) = rest.filter(|rest| rest.view != view) else { return (view, rest) }; + let ppp = rest.pixels_per_point; + match pan_step(rest.view, view, if carry { rest.owed } else { (0.0, 0.0) }, ppp) { + Some((view, owed)) => (view, Some(PanRest { view, owed, ..rest })), + None => (view, Some(PanRest::none(view, ppp))), + } +} + /// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks and the /// display-only widgets over it, the picture last. fn show_body( diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index af2755f7ea..8660fcc476 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6247,6 +6247,227 @@ fn a_whole_pixel_pan() { } } +/// Wheel steps of part of a device pixel, at a zoom and center that put the document's origin between device pixels, +/// move the frame the render worker kept: every frame that may copy from the last one does. +#[test] +fn wheel_steps_of_part_of_a_pixel_move_the_kept_frame() { + keeping_color_settings(|| { + for rulers in [false, true] { + for scaling in [1.0, 1.75] { + wheel_steps_of_part_of_a_pixel(rulers, scaling); + } + } + }); +} + +fn wheel_steps_of_part_of_a_pixel(rulers: bool, scaling: f64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.ui_scaling = scaling; + app.ui.view.rulers = rulers; + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for x in [20, 160, 300] { + app.session.execute("shape.rectangle", &json!({"x": x, "y": 40, "width": 80, "height": 200})).unwrap(); + } + app.canvas.worker_started = true; + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } + { + let v = app.view_mut().unwrap(); + let zoom = 1.37; + let scale = f64::from(scaling as f32); + if scaling != 1.0 { + assert_ne!((zoom * scale) / scale, zoom, "the UI scaling round trip changes the canvas zoom"); + } + v.zoom = zoom * scale; + v.center = Point::new(200.3, 150.7); + } + app_step(&mut app, &ctx, vec![]); + let (worker, jobs, done) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(worker); + app.canvas.last_ms = 50.0; + let at = app.canvas_view().unwrap().rect.center(); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.3, -0.4), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::default(), + source: egui::MouseWheelSource::Unknown, + }; + let start = app.canvas_view().unwrap().center; + let mut r = vectorcraft_render::Renderer::new(); + let (mut kept, mut copying) = (None, 0); + for _ in 0..10 { + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(at), wheel.clone()]); + while let Ok(job) = jobs.try_recv() { + let may = job.may_copy && kept.is_some(); + let frame = render_job(&mut r, &mut kept, &job); + copying += usize::from(may); + if may { + assert!(frame.reused, "each new frame of the pan copies the kept frame's pixels, rulers: {rulers}, UI scaling: {scaling}"); + } + let (img, reused) = (frame.img, frame.reused); + done.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused, view_sized: false }) + .unwrap(); + } + } + assert_ne!(app.canvas_view().unwrap().center, start, "the wheel pans the view"); + assert!(copying >= 3, "the pan asks for new frames: {copying}"); +} + +/// Pans by part of a device pixel, each from the view the last one settled on, move the document by whole device pixels +/// at the view's zoom and rotation, and the parts left over add up: after each step the document is within half a device +/// pixel of where the pans together put it. A change of more than the center is not a pan. +#[test] +fn pans_by_part_of_a_pixel_move_by_whole_device_pixels_and_add_up() { + let rect = egui::Rect::from_min_size(pos2(10.5, 7.25), vec2(640.0, 480.0)); + for (zoom, rotation, ppp) in [(1.37, 0.0, 1.0), (0.613, 30.0, 2.0), (7.9, -75.0, 1.25)] { + let start = CanvasView::new(rect, Point::new(203.17, -48.6), zoom).rotation(rotation); + let origin = |v: &CanvasView| v.affine() * Point::ZERO; + let (mut view, mut owed) = (start, (0.0, 0.0)); + // Each step moves the document 0.3 points right and 0.45 points up on screen. + let step = vec2(0.3, -0.45); + for n in 1..=12 { + let mut next = view; + next.center = view.center - view.unmap_vec(step); + let (shown, left) = super::pan_step(view, next, owed, ppp).expect("a pan"); + let ppp = f64::from(ppp); + let (a, b) = (origin(&view), origin(&shown)); + let wanted = origin(&start) + vectorcraft_geom::Vec2::new(f64::from(step.x), f64::from(step.y)) * f64::from(n); + for (from, to, want) in [(a.x, b.x, wanted.x), (a.y, b.y, wanted.y)] { + let moved = (to - from) * ppp; + assert!((moved - moved.round()).abs() < 1e-6, "{zoom} {rotation}° step {n}: moved {moved} device pixels"); + assert!(((to - want) * ppp).abs() <= 0.5 + 1e-6, "{zoom} {rotation}° step {n}: {} device pixels short", (want - to) * ppp); + } + assert_eq!((shown.zoom, shown.rotation, shown.rect), (start.zoom, start.rotation, start.rect)); + (view, owed) = (shown, left); + } + let mut zoomed = view; + zoomed.zoom = zoom * 1.1; + assert_eq!(super::pan_step(view, zoomed, owed, ppp), None, "a zoom is not a pan"); + } +} + +/// A drag (a button held) sets where the view goes: each pass's view stays within half a device pixel of the view the +/// drag asked for, however many passes it lasts, and moves by whole device pixels from the last one. +#[test] +fn a_drag_s_views_stay_within_half_a_pixel_of_the_pointer() { + let rect = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(640.0, 480.0)); + let start = CanvasView::new(rect, Point::new(100.0, 80.0), 1.37); + let mut rest = Some(super::PanRest::none(start, 1.0)); + for n in 1..=20 { + // The drag asks for the view at its press moved 0.35 points a pass. + let mut asked = start; + asked.center = start.center - start.unmap_vec(vec2(0.35, 0.35) * n as f32); + let last = rest.unwrap().view; + let (view, next) = super::settled_on_device_pixels(rest, asked, false); + let [a, b, c] = [last, view, asked].map(|v| v.affine() * Point::ZERO); + for (from, to, want) in [(a.x, b.x, c.x), (a.y, b.y, c.y)] { + assert!(((to - from) - (to - from).round()).abs() < 1e-6, "pass {n}: whole pixels from the last view"); + assert!((to - want).abs() <= 0.5 + 1e-6, "pass {n}: {} device pixels from the drag", want - to); + } + rest = next; + } +} + +/// Steps a tool takes from where the view was (a drag's autoscroll, the Hand's glide) keep the parts of a pixel they +/// leave: after each pass the view is within half a device pixel of all the steps together. +#[test] +fn a_tool_s_steps_keep_the_parts_of_a_pixel_they_leave() { + let rect = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(640.0, 480.0)); + let start = CanvasView::new(rect, Point::new(100.0, 80.0), 1.37); + let mut rest = Some(super::PanRest::none(start, 1.25)); + for n in 1..=12 { + let last = rest.unwrap().view; + // Each pass the tool moves the view it was given 2.4 device pixels left. + let mut asked = last; + asked.center = last.center - last.unmap_vec(vec2(-2.4 / 1.25, 0.0)); + let (view, next) = super::settled_on_device_pixels(rest, asked, true); + let moved = (view.affine() * Point::ZERO).x - (start.affine() * Point::ZERO).x; + assert!((moved * 1.25 + 2.4 * f64::from(n)).abs() <= 0.5 + 1e-5, "pass {n}: moved {} device pixels", moved * 1.25); + rest = next; + } +} + +/// A Hand drag by parts of a device pixel, at a zoom and center that put the document's origin between device pixels, +/// ends where the pointer let go: the document is within half a device pixel of where the drag puts it, after the +/// release too. +#[test] +fn a_hand_drag_by_parts_of_a_pixel_ends_where_the_pointer_lets_go() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("hand"); + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } + { + let v = app.view_mut().unwrap(); + v.zoom = 1.37; + v.center = Point::new(200.3, 150.7); + } + app_step(&mut app, &ctx, vec![]); + let start = app.canvas_view().unwrap(); + let at = start.rect.center(); + let end = at + vec2(17.7, 12.35); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(at), press(at, true)]); + for to in [at + vec2(13.7, 9.35), end] { + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + } + let origin = |v: &CanvasView| v.affine() * Point::ZERO; + let wanted = origin(&start) + vectorcraft_geom::Vec2::new(f64::from(end.x - at.x), f64::from(end.y - at.y)); + let near = |app: &VectorcraftApp, when: &str| { + let got = origin(&app.canvas_view().unwrap()); + assert!((got.x - wanted.x).abs() <= 0.5 + 1e-6 && (got.y - wanted.y).abs() <= 0.5 + 1e-6, "{when}: {got:?}, the drag puts it at {wanted:?}"); + }; + near(&app, "dragging"); + app_step(&mut app, &ctx, vec![press(end, false)]); + app_step(&mut app, &ctx, vec![]); + near(&app, "released"); +} + +/// A middle-button drag at 1.25 device pixels a point moves the view by whole device pixels and keeps the parts of a +/// pixel each move leaves: after moves of one point each the document is within half a device pixel of the pointer. +#[test] +fn a_middle_button_drag_keeps_the_parts_of_a_pixel_it_moves() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ctx = crate::testing::ui_context(); + let step = |app: &mut VectorcraftApp, events: Vec| { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0)); + let mut raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + raw.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(1.25); + crate::testing::app_frame(app, &ctx, raw); + }; + for _ in 0..3 { + step(&mut app, vec![]); + } + { + let v = app.view_mut().unwrap(); + v.zoom = 1.37; + v.center = Point::new(200.3, 150.7); + } + step(&mut app, vec![]); + assert_eq!(ctx.pixels_per_point(), 1.25); + let start = app.canvas_view().unwrap(); + let at = start.rect.center(); + let middle = + |at: Pos2, pressed: bool| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Middle, pressed, modifiers: Default::default() }; + step(&mut app, vec![egui::Event::PointerMoved(at), middle(at, true)]); + let mut to = at; + for _ in 0..8 { + to += vec2(1.0, 0.0); + step(&mut app, vec![egui::Event::PointerMoved(to)]); + } + let origin = |v: &CanvasView| v.affine() * Point::ZERO; + let (got, from) = (origin(&app.canvas_view().unwrap()), origin(&start)); + let moved = (got.x - from.x) * 1.25; + assert!((moved - f64::from(to.x - at.x) * 1.25).abs() <= 0.5 + 1e-6, "moved {moved} device pixels for {} points", to.x - at.x); + assert!(((got.y - from.y) * 1.25).abs() <= 0.5 + 1e-6, "no move down"); + step(&mut app, vec![middle(to, false)]); +} + /// Installing, replacing or removing a plug-in draws a document with a plug-in effect again, and a /// pan from the frame drawn before the change renders whole instead of copying its pixels. The key /// of a document without a plug-in effect does not follow the plug-ins. The other tests share the diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index fda6c31677..fbf40de0de 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -104,6 +104,10 @@ pub struct View { /// How the canvas reaches the view the app last set ([`Self::set_canvas`] callers). #[serde(skip)] pub moved: Option, + /// What the canvas's last pan left to move ([`crate::canvas::PanRest`]). Temporary, removed with the craft-libs pin + /// bump that brings in storytold/craft-libs#5411. + #[serde(skip)] + pub(crate) pan_rest: Option, } impl Default for View { @@ -122,6 +126,7 @@ impl Default for View { rect: egui::Rect::NOTHING, request: None, moved: None, + pan_rest: None, } } } From 2ce31c6d5d025d16ed790c781b7bd021bc8a3012 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 21:42:28 -0800 Subject: [PATCH 25/42] Type: new type made with a graphic style stays linked to it With New Art Has Basic Appearance off and a basic graphic style picked with nothing selected, only the first new type took the style. New type was never linked to the style, so the next one inherited an unlinked basic look and came out plain. New type made with a graphic style's look now takes the style's opacity and blend mode and is linked to it, as graphicStyle.apply does for type. Other new type keeps its own opacity and blend mode. --- crates/engine/src/cmd/create.rs | 2 +- crates/engine/src/cmd/newart.rs | 4 ++-- crates/engine/src/tests/newart.rs | 18 ++++++++++++++++++ docs/mcp.md | 5 +++-- docs/target-app-parity.md | 2 +- 5 files changed, 25 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index e41d9bbe06..24ab6c3cb3 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -174,7 +174,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on. When new art's template is more than one plain fill and stroke (New Art Has Basic Appearance off) or comes from a graphic style picked with nothing selected, the type takes its fills, strokes and effects, and with Override Character Color on its characters lose the fill and stroke those paint (a `color` given keeps the fill)", + "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on. When new art's template is more than one plain fill and stroke (New Art Has Basic Appearance off) or comes from a graphic style picked with nothing selected, the type takes its fills, strokes and effects, and with Override Character Color on its characters lose the fill and stroke those paint (a `color` given keeps the fill); type with a style's look also takes the style's opacity and blend mode and is linked to it", has_doc, text_create ), diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index 1b787420d2..addb2866c9 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -291,7 +291,7 @@ impl NewArt { } /// Give new object `n` (in `d`) this look: its placed gradients land relative to its bounds, and - /// it links to the style (type keeps its own transparency). + /// it links to the style (type keeps its own transparency unless the look is a graphic style's). pub(crate) fn apply(&self, d: &mut vectorcraft_doc::Document, n: &mut Node) { n.appearance = self.appearance.clone().into(); if self.unit_box @@ -300,7 +300,7 @@ impl NewArt { { n.appearance.rebase_gradients(GraphicStyle::UNIT_BOX, b); } - if matches!(n.kind, NodeKind::Text(_)) { + if matches!(n.kind, NodeKind::Text(_)) && self.style.is_none() { return; } (n.opacity, n.blend) = (self.opacity, self.blend); diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index 6bebbb236a..15607d9187 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -558,3 +558,21 @@ fn a_graphic_style_clicked_with_nothing_selected_styles_the_next_type() { assert_eq!(kept.appearance.effects.len(), 1); assert_ne!(char_fill(&kept), Paint::None); } + +#[test] +fn a_basic_graphic_style_picked_with_basic_appearance_off_styles_each_new_type() { + let mut s = session(); + let src = painted(&mut s, 20.0, "#ff0000", "#0000ff", 2.0); + let red = node(&s, src).appearance.fill_paint(); + let name = run(&mut s, "graphicStyle.new", json!({"name": "Plain"}))["name"].as_str().unwrap().to_string(); + run(&mut s, "appearance.setNewArtBasic", json!({"on": false})); + run(&mut s, "select.none", json!({})); + run(&mut s, "graphicStyle.apply", json!({"name": name})); + // The first type is linked to the style, so the next one, taking its look, gets it too. + for (y, text) in [(200, "one"), (250, "two")] { + let n = new_type(&mut s, json!({"x": 200, "y": y, "text": text})); + assert_eq!(n.appearance.fill_paint(), red, "{text}"); + assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some((name.clone(), true)), "{text}"); + run(&mut s, "select.none", json!({})); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 873499f9dc..3ccc47fb78 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11562,8 +11562,9 @@ resets it. New type (`text.create`) takes the template's fills, strokes and effects when the template is more than one plain fill and stroke or comes from a graphic style; otherwise it has no fills or strokes of its own and its characters keep their color. With Override Character Color on, its characters lose the fill and stroke the template paints, as when a -graphic style is applied to type; a `color` given to `text.create` keeps the characters' fill. The type keeps its own -opacity and blend mode. +graphic style is applied to type; a `color` given to `text.create` keeps the characters' fill. Type made with a graphic +style's look takes the style's opacity and blend mode and is linked to it; otherwise the type keeps its own opacity and +blend mode. `appearance.setNewArtBasic` rejects an `on` value that is not a boolean. Omitting `on` toggles the current preference. `appearance.setNewArt {fill?, stroke?, weight?, cap?, join?, miterLimit?, dash?, dashOffset?, fillOverprint?, strokeOverprint?}` sets new art's fill, stroke and stroke options whatever is selected, and leaves the selection, its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7d647ec718..6e7f092863 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -783,7 +783,7 @@ since 2026-10-01. - **PDF editable import:** Place from bytes or a path with `link: false`, and `clipboard.importPdf` followed by Paste, preserve live type on the selected page. Place still honors `textAs: "outlines"`. Synthetic two-page regressions: `crates/engine/src/cmd/fileio/tests_pdffidelity.rs`. No change to the PDF reader's existing fallback rules. - **Tab stops in `.ai`/EPS type and right-aligned lines with tabs (#6147):** type from the text document keeps its paragraphs' tab stops (key 30: positions and left, center, right and decimal alignments; leaders aren't read), at most 1,024 a paragraph and 2^20 a story, past which the default stops apply with a warning. In right-aligned area type, the text before a line's last tab sits at its stops, measured from the left edge, and the text after it (none when the tab ends the line, with its hyphen when the line is hyphenated) against the right edge; centred and justified lines, point type and right-to-left paragraphs are aligned as a whole as before. Evidence: `ate::tests::a_paragraph_keeps_its_tab_stops`, `ate::tests::a_story_s_tab_stops_are_bounded`, `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`, `import_fuzz::text_frames_with_hostile_paragraph_attributes_never_panic`. Scores unchanged. - **`.ai`/EPS graphic styles that paint with a named gradient:** a graphic style library's style (or a file's listed style) whose fill, or the fill or stroke of a style of one paint, paints with one of the file's gradients by name loads with that gradient at the style's angle, fitted to the bounds of each object it is applied to (VectorCraft's own placement; the style stores only the gradient's name and angle). A style naming a gradient the file doesn't define, or painting with a pattern, is still left out. Evidence: `fileio::tests_aiimport::graphic_styles_in_a_ai_library_that_paint_with_a_named_gradient_load_with_it`, `style::tests::a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on`. Scores unchanged. -- **New type takes new art's appearance:** with New Art Has Basic Appearance off, new objects take every appearance attribute of the current appearance ([Edit appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/edit-appearance-attributes.html)). Type made with the Type tools (`text.create`) now takes the template's fills, strokes and effects when the template is more than one plain fill and stroke or comes from a graphic style picked with nothing selected, and with Override Character Color on its characters lose the fill and stroke those paint. With the option on and no style picked, new type is unchanged. Evidence: `tests::newart::with_basic_appearance_off_new_type_takes_the_last_selections_fills_and_effects`, `tests::newart::new_type_keeps_plain_characters_without_a_template_beyond_a_basic_fill_and_stroke`, `tests::newart::a_graphic_style_clicked_with_nothing_selected_styles_the_next_type`. Scores unchanged. +- **New type takes new art's appearance:** with New Art Has Basic Appearance off, new objects take every appearance attribute of the current appearance ([Edit appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/edit-appearance-attributes.html)). Type made with the Type tools (`text.create`) now takes the template's fills, strokes and effects when the template is more than one plain fill and stroke or comes from a graphic style picked with nothing selected, and with Override Character Color on its characters lose the fill and stroke those paint. Type made with a style's look is linked to the style. With the option on and no style picked, new type is unchanged. Evidence: `tests::newart::with_basic_appearance_off_new_type_takes_the_last_selections_fills_and_effects`, `tests::newart::new_type_keeps_plain_characters_without_a_template_beyond_a_basic_fill_and_stroke`, `tests::newart::a_graphic_style_clicked_with_nothing_selected_styles_the_next_type`, `tests::newart::a_basic_graphic_style_picked_with_basic_appearance_off_styles_each_new_type`. Scores unchanged. - **`.ai`/EPS type laid out closer to the file's page (#6137):** type from the text document keeps auto leading as auto, each line taking the paragraph's Auto Leading share (key 7) of the largest type on it ([Line and character spacing](https://helpx.adobe.com/illustrator/using/line-character-spacing.html)); the paragraph's hyphenation options (keys 10 to 15) are read; area type of one frame whose last lines the file sets, but which don't fit here, may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines and no more than the file has (`vectorcraft_text::fit_source_lines`), with a warning when it does: the frame can stay as it is, or show only some of them; and a line a soft return ends is justified as a wrapped line is, a paragraph's last line keeping its alignment. Evidence: `ate::tests::auto_leading_follows_the_size_of_each_line`, `ate::tests::a_paragraph_keeps_its_auto_leading`, `ate::tests::a_paragraph_keeps_its_hyphenation_options`, `ate::tests::the_last_lines_the_file_sets_in_its_frame_show`, `tests::fit_source_lines_keeps_the_last_lines_the_source_sets`, `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores unchanged. - **Graphs saved to `.ai` keep their data and settings:** a grouped column, stacked column, line or area graph is written to a `.ai` file, in either form, with the records the `.ai` reader reads (`crates/eps/src/import/ai/read/graph.rs`, #7311): `%_Gs`, its plot, type, settings, axes and table, its series' groups each tagged `Go`, and `%_GS` ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), §17 and appendix A). The file opens again with the same live graph. A graph with settings the reader doesn't keep, graph designs, label formatting, more than 10,000 categories or 256 series, or art the reader doesn't attach a graph to is written as its art, with a warning. `crates/eps/src/legacy_ai/tests.rs` and `crates/eps/src/ai_editing/tests.rs` write and read back each kind of graph; `a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns` checks every graph type the graph tools draw. Scores unchanged. - **Graph legend swatches have their series' stroke:** a default legend swatch of a stacked column, stacked bar, area or pie series has the thin white stroke of the series' marks (VectorCraft's own rule), beside the plot or across the top, and a stroke kept on the series is on the swatch too. Each series' group then paints with one stroke, so a stacked column or area graph the graph tools draw is saved to `.ai` with its data and settings and opens again as a live graph; a stacked bar graph is still written as its art, as the reader has no type for it. Evidence: `cmd::graph::tests::a_legend_swatch_has_the_stroke_of_its_series_marks`, `cmd::graph::tests::a_drawn_stacked_column_graph_saved_as_ai_opens_as_a_graph_that_takes_new_data`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`. Scores unchanged. From 0dbe076365a126da337a31af2cb5e913e03ed787 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 22:23:14 -0800 Subject: [PATCH 26/42] Graphic styles: new art from a style takes its isolate and knockout New art made with a graphic style picked with nothing selected took the style's opacity and blend mode but kept the default isolate and knockout. A style with Isolate Blending or Knockout Group set therefore left the new object unlinked at once, and Redefine Graphic Style skipped it. New objects and new type linked to a style now take its isolate and knockout too. --- crates/engine/src/cmd/newart.rs | 9 +++++++-- crates/engine/src/tests/newart.rs | 16 ++++++++++++++++ docs/mcp.md | 4 ++-- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index addb2866c9..f7001d63dd 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -291,7 +291,8 @@ impl NewArt { } /// Give new object `n` (in `d`) this look: its placed gradients land relative to its bounds, and - /// it links to the style (type keeps its own transparency unless the look is a graphic style's). + /// it links to the style, taking its isolate and knockout too (type keeps its own transparency + /// unless the look is a graphic style's). pub(crate) fn apply(&self, d: &mut vectorcraft_doc::Document, n: &mut Node) { n.appearance = self.appearance.clone().into(); if self.unit_box @@ -304,7 +305,11 @@ impl NewArt { return; } (n.opacity, n.blend) = (self.opacity, self.blend); - n.extras_mut().graphic_style = self.style.as_deref().and_then(|name| d.graphic_style_index(name)).map(|i| d.graphic_style_id(i)); + let style = self.style.as_deref().and_then(|name| d.graphic_style_index(name)); + if let Some(g) = style.and_then(|i| d.graphic_styles.get(i)) { + (n.isolate, n.knockout) = (g.isolate, g.knockout); + } + n.extras_mut().graphic_style = style.map(|i| d.graphic_style_id(i)); } } diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index 15607d9187..58cf6ab295 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -559,6 +559,22 @@ fn a_graphic_style_clicked_with_nothing_selected_styles_the_next_type() { assert_ne!(char_fill(&kept), Paint::None); } +#[test] +fn new_art_and_type_from_a_knockout_style_stay_linked_to_it() { + let mut s = session(); + rect(&mut s, 20.0); + run(&mut s, "transparency.set", json!({"knockout": "on", "isolate": true})); + let name = run(&mut s, "graphicStyle.new", json!({"name": "Knockout"}))["name"].as_str().unwrap().to_string(); + for (make, p) in + [("shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 30})), ("text.create", json!({"x": 200, "y": 200, "text": "k"}))] + { + run(&mut s, "select.none", json!({})); + run(&mut s, "graphicStyle.apply", json!({"name": name})); + run(&mut s, make, p); + assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some((name.clone(), true)), "{make}"); + } +} + #[test] fn a_basic_graphic_style_picked_with_basic_appearance_off_styles_each_new_type() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 3ccc47fb78..d57063581c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11552,8 +11552,8 @@ a pin back restores the original; every pin must be on the art's mesh, and empty Initially (and after `paint.default`) new art has a white fill and a 1 pt black stroke. New objects take the fill and stroke proxies (`paint.setFill` / `paint.setStroke` and the weight, whatever is selected) on top of a template. With nothing selected, `stroke.set` / `stroke.setAdvanced` (cap, join, dashes, -arrowheads, profile…) and `graphicStyle.apply` (every fill, stroke and effect, opacity, blend mode and the link to the -style; `add: true` stacks it) set that template instead of editing art. With the Appearance panel's New Art Has Basic +arrowheads, profile…) and `graphicStyle.apply` (every fill, stroke and effect, opacity, blend mode, isolate, knockout and +the link to the style; `add: true` stacks it) set that template instead of editing art. With the Appearance panel's New Art Has Basic Appearance on (the default), a `select.*` command or `layer.target` that changes the selection loads the proxies and the weight from it: only a paint or weight the selected objects share, and art without paint (a placed image that isn't colorized) changes nothing. With the option off (`appearance.setNewArtBasic {on: false}`, the preference `newArtBasic`) new art takes the From a8a8cf8e1101012a331adc2677f7d471cdc58e90 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 22:59:43 -0800 Subject: [PATCH 27/42] Canvas: a view the app asks for is not rounded to whole device pixels A fit or another view request that keeps the zoom and rotation changes only the center, so the pan's rounding still matched its kept view and moved the fitted view by up to half a device pixel. The canvas now applies the pan remainder only on passes without a view request. --- crates/ui-egui/src/canvas.rs | 9 ++++-- crates/ui-egui/src/canvas/tests.rs | 46 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 584137c1c4..66b055c874 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -186,6 +186,8 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin if refit && queued.is_empty() { queued.push(ViewRequest::Place(ViewCommands::FitArtboard)); } + // A view the app asks for this pass (a fit, a zoom command) keeps its exact center. + let requested = !queued.is_empty(); let mut cv = view.canvas(scaling, area); let given = cv; // A zoom percentage (Actual Size) counts from the density of the display that shows this @@ -269,7 +271,9 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin } // The canvas's own pans (the wheel, a middle-button drag, keys) move the view by a step from where it was. let pan = (!measuring).then(|| { - let rest = doc_windows::view(app, win).and_then(|v| v.pan_rest.filter(|rest| rest.kept == Some((v.center, v.zoom, v.rotation)))); + let rest = doc_windows::view(app, win) + .filter(|_| !requested) + .and_then(|v| v.pan_rest.filter(|rest| rest.kept == Some((v.center, v.zoom, v.rotation)))); pan_on_device_pixels(rest, ui.ctx().input(|i| i.max_texture_side), &mut space, pass.as_mut()) }); body = with_canvas_space(ui, space, |ui| show_body(app, ui, &space, pass.as_ref(), win, kind, bar_shapes)); @@ -382,7 +386,8 @@ pub(crate) fn pan_step(from: CanvasView, view: CanvasView, owed: (f64, f64), pix /// frame ([`pan_step`], [`raster::frame_ppp`] with the display's largest texture side `max_side`), adding the part of a /// pixel `rest` owes, and gives the tool host the same view in `pass`. The render worker then moves the frame it kept /// ([`raster::render_job`]) instead of rendering the whole canvas for a pan by part of a pixel. Nothing is rounded while -/// a zoom eases, or when the app changed the view since `rest`. Returns the rest to keep. +/// a zoom eases, when the app changed the view since `rest`, or when the app asks for a view this pass (`rest` is None). +/// Returns the rest to keep. fn pan_on_device_pixels(rest: Option, max_side: usize, space: &mut CanvasSpace, pass: Option<&mut ToolPass>) -> PanRest { let target = space.target(); // The pixels of the art's frame, which are fewer than the device's when the frame would be wider than `max_side`. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 8660fcc476..c44a3934dc 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6468,6 +6468,52 @@ fn a_middle_button_drag_keeps_the_parts_of_a_pixel_it_moves() { step(&mut app, vec![middle(to, false)]); } +/// A fit the app asks for after a pan by parts of a device pixel, at the zoom the pan kept, puts the view at the fitted +/// center exactly: the pan's leftover part of a pixel does not round it. +#[test] +fn a_fit_after_a_pan_by_part_of_a_pixel_keeps_its_exact_center() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ctx = crate::testing::ui_context(); + let step = |app: &mut VectorcraftApp, events: Vec| { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0)); + let mut raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + raw.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(1.25); + crate::testing::app_frame(app, &ctx, raw); + }; + for _ in 0..3 { + step(&mut app, vec![]); + } + let fitted = app.canvas_view().unwrap(); + let at = fitted.rect.center(); + // The pans start from a view whose document origin is between device pixels of the fitted one. + { + let v = app.view_mut().unwrap(); + v.center = Point::new(v.center.x + 0.37, v.center.y + 0.21); + } + step(&mut app, vec![]); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.3, -0.45), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::default(), + source: egui::MouseWheelSource::Unknown, + }; + for _ in 0..3 { + step(&mut app, vec![egui::Event::PointerMoved(at), wheel.clone()]); + } + let panned = app.canvas_view().unwrap(); + assert_ne!(panned.center, fitted.center, "the wheel pans the view"); + assert_eq!(panned.zoom, fitted.zoom, "the pan keeps the zoom"); + assert!(app.view().unwrap().pan_rest.is_some(), "the pan keeps a rest"); + app.view_mut().unwrap().fitted = false; + step(&mut app, vec![]); + let refit = app.canvas_view().unwrap(); + assert_eq!(refit.zoom, fitted.zoom, "the fit gives the same zoom"); + let (got, want) = (refit.affine() * Point::ZERO, fitted.affine() * Point::ZERO); + assert!((got.x - want.x).abs() < 1e-6 && (got.y - want.y).abs() < 1e-6, "the fit is not rounded: {got:?}, fitted at {want:?}"); +} + /// Installing, replacing or removing a plug-in draws a document with a plug-in effect again, and a /// pan from the frame drawn before the change renders whole instead of copying its pixels. The key /// of a document without a plug-in effect does not follow the plug-ins. The other tests share the From 755d28c33345358e35a2e7a7caafd663cf516764 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 22:30:06 -0800 Subject: [PATCH 28/42] 3D: Revolve renders on groups and on fills and strokes In Render Settings > Rendered, Revolve on a group or layer drew its shaded faces and reported "Revolve renders on a single object only". Revolve on a fill or stroke did the same. Extrude & Bevel, Inflate and Rotate already draw an image in both cases. - On a group, every member's surface is swept about the shared axis into one mesh list and drawn as one image, with the shadow plane placed from every member that casts. A member that is not an opaque solid color in Normal blending, or that sits in a group with an opacity mask or a blending mode, keeps the shaded faces and reports why, as the other effects do. The painted bounds of the group are the image's rectangle. - On a fill or stroke, that paint's surface is drawn as its own image under the effects after its Revolve, as Extrude & Bevel, Inflate and Rotate draw a rendered fill or stroke. - When a group's members, or the clipping groups, blends and symbol instances in it, can't be revolved, a rendered Revolve on the group reports the reason in the status bar and the command's warning. - The object, fill and stroke paths share one helper for the image, so the eligibility checks and the shadow plane are the same in each. Docs: docs/mcp.md, docs/three-d.md, docs/target-app-parity.md. --- crates/effects/src/revolve.rs | 238 ++++++++++++++++---- crates/effects/src/solids.rs | 9 +- crates/effects/src/solids/rendered.rs | 3 - crates/effects/src/solids/rendered/tests.rs | 171 +++++++++++++- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- docs/three-d.md | 5 +- 7 files changed, 367 insertions(+), 67 deletions(-) diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 601706a0ca..8d4e448162 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -1072,8 +1072,23 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result Result, String> { // The graphics go on the side of the member with the longest profile, as the canvas draws them. - let longest = if options.map_surface { graphics_member(&shapes, b, options) } else { None }; + let longest = if options.map_surface { graphics_member(shapes, b, options) } else { None }; let mut out = vec![]; for (k, s) in shapes.iter().enumerate() { let Some(item) = surface_item(&s.items) else { continue }; @@ -1099,9 +1114,18 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, buil if !has_revolve(n) { return None; } - let n = &*resolve_for(doc, n, "Revolve", false).ok()?; + let n = &*match resolve_for(doc, n, "Revolve", false) { + Ok(n) => n, + Err(error) => { + // Art that has to be resolved draws only the Revolve on the object itself. + if n.appearance.effects.iter().find(|e| e.visible && is_revolve(&e.id)).is_some_and(crate::renders_image) { + warning.get_or_insert(error); + } + return None; + } + }; if is_container(n) { - return group_art(doc, n, expand, check_only, warning); + return group_art(doc, n, expand, build, warning); } let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); @@ -1115,37 +1139,8 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, buil let paints = solid_paints(n); let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let p = merged_params(&fx.id, &fx.params); - // Rendered, the surface's image, with the shadows of every light on the surface and on the - // shadow plane; the shaded faces when it can't be made, and for vector measurements. - let image = crate::render_settings(&fx.id, &p).filter(|_| build != Build::Vector).and_then(|settings| { - let result = if crate::solids::rendered::reshapes_paths_only(&n.appearance.effects[index + 1..]) { - Err(crate::solids::rendered::PATHS_ONLY.into()) - } else if crate::mapped_graphics(&p).is_empty() && crate::solids::rendered::takes([item], false) { - let b = path.bounds()?; - let (paint, opacity, _) = paint_of(item); - let options = rule_options(fx, rule); - surface_meshes(&path, rule, b, fx, options, (&paint, opacity, 1.0), true).and_then(|meshes| { - let lighting = crate::solids::rendered::lighting(&fx.id, &p); - let lighting = match crate::solids::rendered::plane_settings(&p, &lighting).filter(|_| crate::solids::shadow::casts(opacity)) { - Some(shadow) => { - let mut caster = vectorcraft_three_d::ShadowCaster::new(); - let faces = cast_surface(&mut caster, &path, b, options, None)?; - crate::solids::rendered::with_receiver(lighting, &caster, shadow, &[faces]) - } - None => lighting, - }; - if build == Build::Bounds { - crate::solids::rendered::bounds_art(doc, n.id, &lighting, &meshes, settings) - } else { - crate::solids::rendered::art(doc, n.id, &lighting, &meshes, settings, check_only) - } - }) - } else { - Err(crate::solids::rendered::OPAQUE_ONLY.into()) - }; - crate::solids::rendered::reported(result, warning) - }); + let later = n.appearance.effects.get(index + 1..).unwrap_or_default(); + let image = surface_image(ImageFor { doc, id: n.id, build }, fx, later, &path, rule, item, warning); if check_only { return None; } @@ -1180,13 +1175,22 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, buil for (original, item) in originals.into_iter().zip(&items) { if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) { let fx = item.effects().get(index)?; - if crate::renders_image(fx) { - warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into()); - } - if check_only { + if check_only && !crate::renders_image(fx) { continue; } let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original)); + // Rendered, this fill's or stroke's surface as an image, under the effects after its + // Revolve, with the shadows in the image. + let later = item.effects().get(index + 1..).unwrap_or_default(); + let image = surface_image(ImageFor { doc, id: n.id, build }, fx, later, &p, rule, item, warning); + if check_only { + continue; + } + if let Some(mut image) = image { + Arc::make_mut(&mut image).appearance.effects = later.iter().filter(|e| !is_revolve(&e.id)).cloned().collect(); + children.push(image); + continue; + } let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); if crate::solids::renders_wireframe(fx) { let mut art = wire_art(n.id, [(&p, rule)], p.bounds()?, fx, fx_options(fx))?; @@ -1218,6 +1222,126 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, buil Some(art) } +/// What a rendered image is made for: the object `id` it is art of, the document `doc` whose raster +/// effects resolution it takes, and the art `build` it goes in. +#[derive(Clone, Copy)] +struct ImageFor<'a> { + doc: Option<&'a Document>, + id: NodeId, + build: Build, +} + +/// The rendered image of Revolve `fx` for `to`, swept from `path` (filled under `rule`) about its +/// own bounds and painted with `item`; `later` are the effects after `fx`. `None` when `fx` draws no +/// image or `to.build` takes none, and when the image can't be made, with the reason in `warning`: +/// the caller then draws the shaded faces. +fn surface_image( + to: ImageFor, + fx: &Effect, + later: &[Effect], + path: &PathData, + rule: FillRule, + item: &AppearanceItem, + warning: &mut Option, +) -> Option> { + let p = merged_params(&fx.id, &fx.params); + let settings = crate::render_settings(&fx.id, &p).filter(|_| to.build != Build::Vector)?; + let paint = item.paint(); + let opacity = item.opacity(); + let result = if crate::solids::rendered::reshapes_paths_only(later) { + Err(crate::solids::rendered::PATHS_ONLY.into()) + } else if !crate::mapped_graphics(&p).is_empty() + || !crate::solids::rendered::takes([item], false) + || crate::solids::mesh_color(paint, opacity)[3] != 1.0 + { + Err(crate::solids::rendered::OPAQUE_ONLY.into()) + } else if let Some(b) = path.bounds() { + let options = rule_options(fx, rule); + surface_meshes(path, rule, b, fx, options, (paint, opacity, 1.0), true).and_then(|meshes| { + let lighting = crate::solids::rendered::lighting(&fx.id, &p); + let lighting = match crate::solids::rendered::plane_settings(&p, &lighting).filter(|_| crate::solids::shadow::casts(opacity)) { + Some(shadow) => { + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + let faces = cast_surface(&mut caster, path, b, options, None)?; + crate::solids::rendered::with_receiver(lighting, &caster, shadow, &[faces]) + } + None => lighting, + }; + image_for(to, &lighting, &meshes, settings) + }) + } else { + Err("Revolve requires a shape with at least two anchors".into()) + }; + crate::solids::rendered::reported(result, warning) +} + +/// [`surface_image`] of the members `shapes` of a group, every member swept about the axis of `b` +/// with `options` into one image, as the shaded faces draw them in one order. The shaded faces are +/// drawn instead when a member's surface is not an opaque solid color in Normal blending, or when a +/// member, or a group it is in, has an opacity below 100%, a blending mode or an opacity mask. +fn members_image( + to: ImageFor, + fx: &Effect, + later: &[Effect], + shapes: &[Profile], + b: Rect, + options: Revolve, + warning: &mut Option, +) -> Option> { + let p = merged_params(&fx.id, &fx.params); + let settings = crate::render_settings(&fx.id, &p).filter(|_| to.build != Build::Vector)?; + let profiles = shapes.iter().filter(|s| surface_item(&s.items).is_some()); + let surfaces = profiles.clone().filter_map(|s| surface_item(&s.items)); + let result = if profiles.clone().next().is_none() { + Err("Revolve requires a group holding a shape with a fill or stroke".into()) + } else if crate::solids::rendered::reshapes_paths_only(later) { + Err(crate::solids::rendered::PATHS_ONLY.into()) + } else if crate::mapped_graphics(&p).is_empty() + && crate::solids::rendered::takes(surfaces, crate::solids::profiles_have_masks(profiles)) + && shapes.iter().all(|s| { + let Some(item) = surface_item(&s.items) else { return true }; + crate::solids::mesh_color(item.paint(), item.opacity() * s.opacity)[3] == 1.0 + }) + { + members_meshes(fx, shapes, b, options, &mut 0, crate::solids::MAX_MESH_TRIANGLES).and_then(|meshes| { + let lighting = crate::solids::rendered::lighting(&fx.id, &p); + let lighting = match crate::solids::rendered::plane_settings(&p, &lighting) { + Some(shadow) => { + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + let mut faces = vec![]; + for s in shapes { + let Some((_, opacity, _)) = surface_item(&s.items).map(paint_of) else { continue }; + if crate::solids::shadow::casts(opacity * s.opacity) { + faces.push(cast_surface(&mut caster, &s.path, b, Revolve { fill_rule: s.rule, ..options }, None)?); + } + } + crate::solids::rendered::with_receiver(lighting, &caster, shadow, &faces) + } + None => lighting, + }; + image_for(to, &lighting, &meshes, settings) + }) + } else { + Err(crate::solids::rendered::OPAQUE_ONLY.into()) + }; + crate::solids::rendered::reported(result, warning) +} + +/// The rendered image of `meshes` lit by `lighting` for `to`: for [`Build::Bounds`] its rectangle +/// without pixels, for [`Build::Check`] only the check of its limits. +fn image_for( + to: ImageFor, + lighting: &crate::solids::rendered::Lighting, + meshes: &[crate::SolidMesh], + settings: crate::solids::wireframe::RenderSettings, +) -> Result>, String> { + if to.build == Build::Bounds { + crate::solids::rendered::bounds_art(to.doc, to.id, lighting, meshes, settings) + } else { + crate::solids::rendered::art(to.doc, to.id, lighting, meshes, settings, to.build == Build::Check) + } +} + /// The members' `surfaces`, or runs of their faces, in order, from the [`Scope`] at `level` of each /// one's `Profile::scopes` inward: consecutive surfaces that share a scope go in one group with its /// opacity, blending mode and opacity mask, so each applies once, to the faces it holds together. @@ -1338,19 +1462,43 @@ pub(crate) fn overlaps(a: Rect, b: Rect) -> bool { /// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them, /// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when /// the effect is only on the group's own fills or strokes or when its members can't be revolved. -fn group_art(doc: Option<&Document>, n: &Node, expand: bool, check_only: bool, warning: &mut Option) -> Option { +fn group_art(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warning: &mut Option) -> Option { + let check_only = build == Build::Check; let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?; let fx = n.appearance.effects.get(index)?; - if crate::renders_image(fx) { - warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into()); + if check_only && !crate::renders_image(fx) { + return None; } + let prepared = members(n, "Revolve").and_then(|mut shapes| { + reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); + let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?; + let options = shared_options(&shapes, fx_options(fx))?; + Ok((shapes, b, options)) + }); + let (shapes, b, options) = match prepared { + Ok(prepared) => prepared, + Err(e) => { + // In rendered mode the reason the members can't be revolved is reported, as the reason + // an image can't be made is; the canvas then draws the source art. + if crate::renders_image(fx) { + warning.get_or_insert(e); + } + return None; + } + }; + // Rendered, one image of every member's surface, with the shadows of every light on the + // surfaces and on the shadow plane; the shaded faces when it can't be made. + let later = n.appearance.effects.get(index + 1..).unwrap_or_default(); + let image = members_image(ImageFor { doc, id: n.id, build }, fx, later, &shapes, b, options, warning); if check_only { return None; } - let mut shapes = members(n, "").ok()?; - reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); - let b = union_bounds(&shapes)?; - let options = shared_options(&shapes, fx_options(fx)).ok()?; + if let Some(image) = image { + let mut art = n.clone(); + art.kind = NodeKind::Group { children: vec![image], clip: false }; + art.appearance = Appearance { effects: past_effect(&n.appearance.effects, index), ..Default::default() }.into(); + return Some(art); + } if crate::solids::renders_wireframe(fx) { // In wireframe mode the edges of every member's faces, with no shadow. let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| (&s.path, s.rule)); diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 6a9ddfbbff..5fca519b94 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -689,7 +689,12 @@ fn masked(id: NodeId, surfaces: Vec<(&[Scope], Arc)>) -> Vec> { /// Does any of `shapes` sit in a scope with an opacity mask or a blending mode other than Normal? pub(crate) fn has_masks(shapes: &[Profile]) -> bool { - shapes.iter().any(|s| s.scopes.iter().any(composites)) + profiles_have_masks(shapes.iter()) +} + +/// Does any profile sit in a scope with an opacity mask or a blending mode other than Normal? +pub(crate) fn profiles_have_masks<'a>(mut shapes: impl Iterator) -> bool { + shapes.any(|s| s.scopes.iter().any(composites)) } /// One shape a solid is built from: its outline and fill rule, the fills and strokes that paint @@ -721,7 +726,7 @@ const MAX_MEMBERS: usize = 4096; /// The most triangles the meshes of one 3D effect hold together (about 290 MB of corners and /// normals): past it the object is too complex to export. -const MAX_MESH_TRIANGLES: usize = 2_000_000; +pub(crate) const MAX_MESH_TRIANGLES: usize = 2_000_000; /// The most facets of solid colors under colored lights that one 3D effect draws as faces of their /// own, to go in one order with other solids' faces. Each such face is about 16 nodes, a composite diff --git a/crates/effects/src/solids/rendered.rs b/crates/effects/src/solids/rendered.rs index 59b425da48..a21ccbbba2 100644 --- a/crates/effects/src/solids/rendered.rs +++ b/crates/effects/src/solids/rendered.rs @@ -35,9 +35,6 @@ pub(crate) fn reshapes_paths_only(effects: &[vectorcraft_doc::Effect]) -> bool { }) } -/// The message for Revolve on a group or on a fill or stroke, which draws its shaded faces. -pub const OBJECTS_ONLY: &str = "Revolve renders on a single object only; showing the shaded faces instead"; - /// Why a visible 3D effect in rendered mode on `n` draws shaded faces instead of an image. /// Messages are English, to be translated when displayed. `None` when no rendered effect falls back. pub fn rendered_warning(doc: &vectorcraft_doc::Document, n: &Node) -> Option { diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs index 403991b6ca..59633f835f 100644 --- a/crates/effects/src/solids/rendered/tests.rs +++ b/crates/effects/src/solids/rendered/tests.rs @@ -796,7 +796,7 @@ fn rendered_images_are_reused_until_an_input_changes() { /// faces, which apply them; without either, the group draws the image. #[test] fn masked_or_blended_members_draw_the_shaded_faces() { - for id in [super::super::EXTRUDE, super::super::INFLATE, super::super::ROTATE] { + for id in FOUR { let group = |member: Node| { let mut g = Node::group(NodeId(10), vec![std::sync::Arc::new(member)]); g.appearance.effects.push(crate::new_effect(id, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); @@ -817,23 +817,170 @@ fn masked_or_blended_members_draw_the_shaded_faces() { } } -/// Revolve on a group, or on a fill or stroke, draws the shaded faces and reports why. +/// The page rectangle image `i` covers. +fn image_rect(i: &vectorcraft_doc::ImageObject) -> Rect { + let [a, _, _, d, e, f] = i.xf.as_coeffs(); + Rect::new(e, f, e + a * f64::from(i.width), f + d * f64::from(i.height)) +} + +/// Revolve on a group draws one image of every member's surface, over the area of the shaded faces +/// of all of them, and its painted bounds are that image's rectangle; nothing is reported. #[test] -fn revolve_on_a_group_or_a_paint_reports_objects_only() { +fn revolve_on_a_group_draws_one_image_of_every_member() { + let doc = vectorcraft_doc::Document::new(600.0, 400.0); + let member = + |id: u64, x: f64, color: Color| Node::path(NodeId(id), square(x, 100.0, 100.0), Appearance::basic(Paint::solid(color), Paint::None, 0.0)); + let members = + vec![std::sync::Arc::new(member(11, 100.0, Color::rgb(0.2, 0.5, 0.8))), std::sync::Arc::new(member(12, 300.0, Color::rgb(0.8, 0.3, 0.2)))]; + let mut group = Node::group(NodeId(10), members); + group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &group), None, "a group's rendered Revolve reports a fallback"); + let art = crate::revolve_art_drawn_in(Some(&doc), &group).unwrap(); + let found = images(&art); + assert_eq!(found.len(), 1, "a group's Revolve draws one image of every member, not the shaded faces"); + assert!(faces_bounds(&art).is_none(), "a group's rendered Revolve draws no shaded faces"); + let shaded = faces_bounds(&crate::revolve_art_in(Some(&doc), &group).unwrap()).unwrap(); + let rect = image_rect(&found[0]); + let grown = rect.inflate(1.0, 1.0); + assert!(grown.contains(shaded.origin()) && grown.contains(Point::new(shaded.x1, shaded.y1)), "the image {rect:?} misses the faces {shaded:?}"); + let bounds = crate::three_d_bounds_art_in(Some(&doc), &group).unwrap(); + let measured = images(&bounds); + assert_eq!(measured.len(), 1, "the painted bounds of a group's rendered Revolve are its image's rectangle"); + assert_eq!(image_rect(&measured[0]), rect); +} + +/// A group's rendered Revolve draws the shaded faces, and reports why, when a member is not opaque. +#[test] +fn revolve_on_a_group_with_a_see_through_member_draws_the_shaded_faces() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let mut member = + Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + member.opacity = 0.5; + let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(member)]); + group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some(OPAQUE_ONLY), "member at 50%"); + let art = drawn(&group); + assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "member at 50%"); +} + +/// A member with no surface paint does not prevent the group's Revolve from rendering. +#[test] +fn revolve_on_a_group_ignores_blending_on_an_unpainted_member() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let painted = Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + let mut unpainted = Node::path(NodeId(12), square(250.0, 100.0, 100.0), Appearance::basic(Paint::None, Paint::None, 0.0)); + unpainted.blend = vectorcraft_doc::color::BlendMode::Multiply; + let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(painted), std::sync::Arc::new(unpainted)]); + group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &group), None); + assert_eq!(images(&drawn(&group)).len(), 1); +} + +/// A group whose members can't be revolved reports why in rendered mode. +#[test] +fn revolve_on_a_group_that_cant_be_revolved_reports_why() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let mut group = Node::group(NodeId(10), vec![]); + group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + let warning = crate::rendered_warning(&doc, &group); + assert!(warning.as_deref().is_some_and(|w| w.starts_with("Revolve requires")), "an empty group's rendered Revolve reports {warning:?}"); + // An image with a fill of its own inside a clipping group is refused while the clipping group + // is resolved, before the members are listed. + let mut clip = Node::path(NodeId(21), square(100.0, 100.0, 100.0), Appearance::default()); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let mut image = Node::new( + NodeId(22), + NodeKind::Image(Box::new(vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::translate((150.0, 150.0)), + link: None, + placement: Default::default(), + pixels: None, + })), + ); + image.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into(); + let clipped = Node::new(NodeId(20), NodeKind::Group { children: vec![std::sync::Arc::new(clip), std::sync::Arc::new(image)], clip: true }); + let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(clipped.clone())]); + group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + let warning = crate::rendered_warning(&doc, &group); + assert!(warning.as_deref().is_some_and(|w| w.contains("trace it first")), "a clipped image's rendered Revolve reports {warning:?}"); + // A clipping group draws no Revolve on its own fill, so that one reports nothing. + let mut on_fill = clipped; + on_fill.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into(); + on_fill.appearance.items[0].effects_mut().push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered"}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &on_fill), None, "a clipping group's fill Revolve"); +} + +/// A group's rendered Revolve reports when no member has a fill or stroke. +#[test] +fn revolve_on_a_group_without_surface_paint_reports_why() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let member = Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::None, Paint::None, 0.0)); + let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(member)]); + group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some("Revolve requires a group holding a shape with a fill or stroke")); +} + +/// Revolve on a fill, or on a stroke, draws an image of that paint's surface under the effects +/// after it, with nothing reported; with both, each draws its own image. A fill at 50% draws the +/// shaded faces and reports why. +#[test] +fn revolve_on_a_fill_or_a_stroke_draws_its_image() { + use vectorcraft_doc::AppearanceItem; let doc = vectorcraft_doc::Document::new(400.0, 400.0); let rendered = || crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap(); - let member = || Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); - let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(member())]); - group.appearance.effects.push(rendered()); - assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some(OBJECTS_ONLY), "group"); - assert!(images(&drawn(&group)).is_empty(), "group"); - let mut fill = member(); - fill.appearance.items[0].effects_mut().push(rendered()); - assert_eq!(crate::rendered_warning(&doc, &fill).as_deref(), Some(OBJECTS_ONLY), "fill"); - assert!(images(&drawn(&fill)).is_empty(), "fill"); + let painted = || { + Node::path( + NodeId(11), + square(100.0, 100.0, 100.0), + Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::solid(Color::BLACK), 4.0), + ) + }; + let at = |n: &Node, stroke: bool| n.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(_)) == stroke).unwrap(); + for stroke in [false, true] { + let mut n = painted(); + let i = at(&n, stroke); + n.appearance.items[i].effects_mut().push(rendered()); + n.appearance.items[i].effects_mut().push(crate::new_effect("stylize.dropShadow", &json!({})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &n), None, "stroke {stroke}: a paint's rendered Revolve reports a fallback"); + let art = crate::revolve_art_drawn_in(Some(&doc), &n).unwrap(); + let mut later = vec![]; + art.walk(&mut |c| { + if matches!(c.kind, NodeKind::Image(_)) { + later.push(c.appearance.effects.iter().map(|e| e.id.clone()).collect::>()); + } + }); + assert_eq!(later, [["stylize.dropShadow"]], "stroke {stroke}: Revolve on one paint draws one image under the effects after it"); + } + let mut both = painted(); + for item in &mut both.appearance.items { + item.effects_mut().push(rendered()); + } + assert_eq!(images(&crate::revolve_art_drawn_in(Some(&doc), &both).unwrap()).len(), 2, "each paint draws its own image"); + let mut faint = painted(); + let i = at(&faint, false); + faint.appearance.items[i].effects_mut().push(rendered()); + if let AppearanceItem::Fill(f) = &mut faint.appearance.items[i] { + f.opacity = 0.5; + } + assert_eq!(crate::rendered_warning(&doc, &faint).as_deref(), Some(OPAQUE_ONLY), "fill at 50%"); + assert!(images(&drawn(&faint)).is_empty(), "fill at 50%"); assert_eq!(crate::rendered_warning(&doc, &solid_square(crate::REVOLVE, Color::BLACK, json!({"render": {"mode": "rendered"}}))), None); } +/// A rendered Revolve on an empty fill profile reports why it cannot render. +#[test] +fn revolve_on_an_empty_fill_profile_reports_why() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let mut n = Node::path(NodeId(1), PathData::new(vec![]), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + n.appearance.items[0].effects_mut().push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some("Revolve requires a shape with at least two anchors")); +} + /// Baking a rendered object's appearance, as an envelope with Distort Appearance does, keeps its /// image, for Revolve and the other 3D effects. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 762958f91f..16818b21de 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7527,10 +7527,12 @@ values), `resolution` (`null` for Document Raster Effects Settings › Resolutio `background` (`"transparent"`, the default, or `"white"`). A quality whose samples would pass 16,777,216 pixels takes fewer, and an image past that limit at one sample a pixel draws the shaded faces. The shaded faces are also drawn for a scene past the renderer's limits on triangles, vertices, lights or work, for a mesh point at or behind -the eye, for Revolve on a group or on a fill or stroke, for solids painted with a gradient, a pattern, graphics, an +the eye, for solids painted with a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal, and for a later geometry effect that reshapes paths but leaves images unchanged. Extrude & Bevel and Inflate check the top fill and the strokes they build solids from; Rotate -checks every fill and stroke, since it draws a plane for each. The status bar and +checks every fill and stroke, since it draws a plane for each. Revolve on a group draws every member's surface in one +image and checks each member's surface fill or stroke; Revolve on a fill or stroke draws that fill's or stroke's +surface as an image under the effects after it. The status bar and the command result's `warning` field report when the shaded faces are drawn instead. A `render` that is not an object, another key, another value, and `render` on Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic) are refused before the document changes. In wireframe mode the graphics' art is not checked against the graphics diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 10e96a36c1..c8ea8a917b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -741,7 +741,7 @@ since 2026-10-01. - 3D and Materials › Object › Bevel › Reset: the button next to Extrude & Bevel's Bevel heading, in the options dialog and the panel, sets Bevel Shape, Width, Height, Repeat, Space, Bevel Inside and Bevel both sides back to their defaults and leaves the other settings as they are, as one undo step in the panel; it is unavailable while every bevel setting is at its default ([three-d.md](three-d.md#extrude--bevel)); `crates/ui-egui/src/dialogs/revolve/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Quick Actions › Expand as Wireframes (#6354): `effect.expandAsWireframes` replaces each selected 3D object with a group of 0.5 pt black stroked paths, the edges of the faces its effect draws, each edge once and joined end to end, curves kept, in one undo step ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs`, `crates/engine/src/cmd/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Render Settings › Wireframe: `render: {mode: "wireframe"}` on Extrude & Bevel, Revolve, Inflate and Rotate draws the live effect as the edges of its faces, 0.5 pt black strokes with no shadow, in every output and in Expand Appearance ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. -- 3D and Materials › Render Settings › Rendered: `render: {mode: "rendered"}` with `quality`, `resolution` and `background` draws the solid of Extrude & Bevel, Revolve, Inflate and Rotate as one depth-buffered image lit by every light, with shadow maps while Shading and Shadows are both on; solids painted with a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal, a later geometry effect that reshapes paths only, Revolve on a group, fill or stroke, and an image past the renderer's limits draw the shaded faces instead, with a warning ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/rendered/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. +- 3D and Materials › Render Settings › Rendered: `render: {mode: "rendered"}` with `quality`, `resolution` and `background` draws the solid of Extrude & Bevel, Revolve, Inflate and Rotate as one depth-buffered image lit by every light (Revolve on a group draws every member's surface in one image, and Revolve on a fill or stroke draws that surface's own image), with shadow maps while Shading and Shadows are both on; solids painted with a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal, a later geometry effect that reshapes paths only, and an image past the renderer's limits draw the shaded faces instead, with a warning ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/rendered/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Materials › Properties: Roughness and Metallic sliders set `material: {roughness, metallic}` on Extrude & Bevel, Revolve, Inflate and Rotate; with Shading on and outside Wireframe mode, any material other than the default (1 and 0) is shaded with craft-pbr's glTF 2.0 metallic-roughness BRDF, its highlight screened over each face; in every mode glTF exports write both factors, and USD exports write roughness and write metallic only when it is not the default 0 ([three-d.md](three-d.md#material-properties)); `crates/three-d/src/material.rs`, `crates/effects/src/solids/tests_material.rs`, `crates/engine/src/cmd/fileio/mesh3d/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Export 3D Object: the panel's button adds the selected objects that have a 3D effect to Asset Export as 3D assets (`assets.add3D`), one undo step and none when each is an asset already, selects their assets and shows the Asset Export panel ([three-d.md](three-d.md#3d-and-materials-panel)); `panels::three_d::tests::{export_3d_object_adds_the_selected_3d_objects_to_asset_export, export_3d_object_leaves_out_a_3d_object_inside_another}` cover it. Scores and hours unchanged. - 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. diff --git a/docs/three-d.md b/docs/three-d.md index d45a826edc..2fddfee31e 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -77,8 +77,9 @@ pages describe it. image, the effect draws its shaded faces. The image keeps transparency where no surface is, or is white with `background: white`. The image shows opaque solid colors only: a solid painted with a gradient or a pattern, one with graphics, a paint with an opacity below 100% or in a blending mode other than Normal, and a group member whose opacity mask or blending mode - applies to its solid draw the shaded faces, as do Revolve on a group, Revolve on a fill or stroke, and a later - geometry effect that reshapes paths but leaves images unchanged. The mode + applies to its solid draw the shaded faces, as does a later geometry effect that reshapes paths but leaves images + unchanged. Revolve on a group draws every member's surface in one image, and Revolve on a fill or stroke draws an + image of that fill's or stroke's surface under the effects after it. The mode is saved with the effect. The status bar and the command result's `warning` field report when the shaded faces are drawn instead. The lighting follows the same lights as the shaded faces but in linear light, so lit areas differ from the shaded faces' colors. Ambient Light keeps its full range from 0 to 200%; From cdfcef172f73feebdb8fa88fd46ba5741233082c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 23:35:05 -0800 Subject: [PATCH 29/42] Type: new type's style link stays in its document, gradients fit the wrapped frame New art and type took the graphic style picked with nothing selected by its name, so in another document they were linked to a style of the same name there, and took its isolate and knockout. The template now records the document the style came from, and new art elsewhere takes the look without the link. New area type that text wrap moves as it is made (an Auto Size frame below a wrap object grows) had the template's placed gradients fitted to the frame before the reflow. Both ways of making type now let text wrap reflow it first and fit the gradients to the frame it ends with; type whose bounds do not change keeps its placement. The docs name text.create as the command whose type takes the template, state that Type on a Path and Area Type keep the default appearance, and note that a color given to text.create keeps the characters' fill under Override Character Color. --- crates/engine/src/cmd/create.rs | 26 +++++++++++++- crates/engine/src/cmd/newart.rs | 40 ++++++++++++++++------ crates/engine/src/session/edit.rs | 10 +++--- crates/engine/src/tests/newart.rs | 57 +++++++++++++++++++++++++++++++ crates/tools/src/context.rs | 3 ++ docs/mcp.md | 5 ++- docs/target-app-parity.md | 4 +-- 7 files changed, 126 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 24ab6c3cb3..be8155274e 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -174,7 +174,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on. When new art's template is more than one plain fill and stroke (New Art Has Basic Appearance off) or comes from a graphic style picked with nothing selected, the type takes its fills, strokes and effects, and with Override Character Color on its characters lose the fill and stroke those paint (a `color` given keeps the fill); type with a style's look also takes the style's opacity and blend mode and is linked to it", + "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on. When new art's template is more than one plain fill and stroke (New Art Has Basic Appearance off) or comes from a graphic style picked with nothing selected, the type takes its fills, strokes and effects, and with Override Character Color on its characters lose the fill and stroke those paint (a `color` given keeps the fill); type with a style's look also takes the style's opacity and blend mode and is linked to it (in the document the style was picked in; elsewhere it is not linked), and its placed gradients fit the frame text wrap gives it", has_doc, text_create ), @@ -255,6 +255,7 @@ fn insert_look_turned( } n.name = name; n.bbox_angle = bbox_angle; + let pre = wrap_snapshot(d, &n, &look); let mut into = None; match (mode, inside) { (crate::DrawMode::Inside, Some(target)) if d.node(target).is_some() => { @@ -274,6 +275,7 @@ fn insert_look_turned( d.insert(parent, usize::MAX, n)?; } } + place_after_wrap(d, pre, id, &look); if select { sel.set([id]); } @@ -995,13 +997,35 @@ fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, look: NewAr look.apply(d, &mut n); super::object::align_new_object(d, &mut n); n.bbox_angle = bbox_angle; + let pre = wrap_snapshot(d, &n, &look); d.insert(Some(parent), usize::MAX, n)?; + place_after_wrap(d, pre, id, &look); sel.set([id]); Ok(id) })?; Ok(json!({ "id": id.0 })) } +/// The document before new type `n` goes in, when `look` places gradients on it: text wrap can +/// reflow the type once it is in ([`place_after_wrap`]). +fn wrap_snapshot(d: &vectorcraft_doc::Document, n: &Node, look: &NewArt) -> Option { + (matches!(n.kind, NodeKind::Text(_)) && look.places_gradients()).then(|| d.clone()) +} + +/// New type `id` just inserted into `d` (`pre`: `d` before, from [`wrap_snapshot`]): text wrap +/// reflows it now, and when that changes its bounds (an Auto Size frame below a wrap object grows), +/// `look`'s gradients are placed on the bounds it ends with. +fn place_after_wrap(d: &mut vectorcraft_doc::Document, pre: Option, id: NodeId, look: &NewArt) { + let Some(pre) = pre else { return }; + let placed_on = d.node(id).and_then(Node::geometric_bounds); + super::textwrap::refresh(&pre, d); + if let Some(n) = d.node_mut(id) + && n.geometric_bounds() != placed_on + { + look.place(n); + } +} + fn text_create(s: &mut Session, p: &Value) -> Result { let parent = text_parent(s, p)?; let x = f64_req(p, "x", "text.create")?; diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index f7001d63dd..01044f7c21 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -294,13 +294,7 @@ impl NewArt { /// it links to the style, taking its isolate and knockout too (type keeps its own transparency /// unless the look is a graphic style's). pub(crate) fn apply(&self, d: &mut vectorcraft_doc::Document, n: &mut Node) { - n.appearance = self.appearance.clone().into(); - if self.unit_box - && n.appearance.has_placed_gradient() - && let Some(b) = n.geometric_bounds() - { - n.appearance.rebase_gradients(GraphicStyle::UNIT_BOX, b); - } + self.place(n); if matches!(n.kind, NodeKind::Text(_)) && self.style.is_none() { return; } @@ -311,6 +305,21 @@ impl NewArt { } n.extras_mut().graphic_style = style.map(|i| d.graphic_style_id(i)); } + + /// Give `n` this look's appearance, its placed gradients relative to `n`'s bounds now. + pub(crate) fn place(&self, n: &mut Node) { + n.appearance = self.appearance.clone().into(); + if self.places_gradients() + && let Some(b) = n.geometric_bounds() + { + n.appearance.rebase_gradients(GraphicStyle::UNIT_BOX, b); + } + } + + /// Does this look place gradients on the bounds of the object it is given to? + pub(crate) fn places_gradients(&self) -> bool { + self.unit_box && self.appearance.has_placed_gradient() + } } impl Session { @@ -360,9 +369,16 @@ impl Session { self.new_art_look(self.paint.fill.clone(), self.paint.stroke.clone(), self.paint.stroke_width).appearance } - /// The opacity, blend mode and graphic style (name) of the next object drawn. + /// The opacity, blend mode and graphic style (name) of the next object drawn. The style is + /// left out in a document other than the one it was taken from, so new art there is not + /// linked to a style of the same name. pub fn new_art_transparency(&self) -> (f32, BlendMode, Option<&str>) { - if self.basic_only() { (1.0, BlendMode::Normal, None) } else { (self.paint.opacity, self.paint.blend, self.paint.style.as_deref()) } + if self.basic_only() { + return (1.0, BlendMode::Normal, None); + } + let here = self.active().map(|st| st.uid); + let style = self.paint.style.as_deref().filter(|_| self.paint.style_doc.is_some() && self.paint.style_doc == here); + (self.paint.opacity, self.paint.blend, style) } /// The stroke of the next object drawn (the Stroke panel shows it with nothing selected). @@ -409,14 +425,16 @@ impl Session { } /// Make `ap` (placed gradients relative to the unit box) and this transparency the template, - /// and its top fill, stroke and weight the proxies. + /// and its top fill, stroke and weight the proxies. `style` is a graphic style of the + /// document in front. fn take_new_art(&mut self, ap: Appearance, opacity: f32, blend: BlendMode, style: Option, inherited: bool) { + let style_doc = style.as_ref().and_then(|_| self.active().map(|st| st.uid)); let p = &mut self.paint; (p.fill, p.stroke) = (unplaced(&ap.fill_paint()), unplaced(&ap.stroke_paint())); if let Some(st) = ap.stroke() { p.stroke_width = st.width; } - (p.appearance, p.opacity, p.blend, p.style, p.inherited) = (Some(ap), opacity, blend, style, inherited); + (p.appearance, p.opacity, p.blend, p.style, p.style_doc, p.inherited) = (Some(ap), opacity, blend, style, style_doc, inherited); } /// After each command: with New Art Has Basic Appearance off, new art takes the appearance of diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 604ca822df..a3cab90ac4 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -414,7 +414,7 @@ impl Session { // parts it left alone keep the interaction's. The pattern lists every field, so a field // added to `PaintDefaults` does not compile until it is handled here. The paints a preview // took its new-art paints over from take the change as well. - let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = &self.paint; + let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, style_doc, inherited } = &self.paint; for start in std::iter::once(&mut it.paint).chain(it.inherited_preview_paint.as_mut()) { if *fill != paint.fill { start.fill.clone_from(fill); @@ -434,8 +434,9 @@ impl Session { if *blend != paint.blend { start.blend = *blend; } - if *style != paint.style { + if *style != paint.style || *style_doc != paint.style_doc { start.style.clone_from(style); + start.style_doc = *style_doc; } if *inherited != paint.inherited { start.inherited = *inherited; @@ -917,7 +918,7 @@ fn take_changed_paints( left: &vectorcraft_tools::PaintDefaults, now: &vectorcraft_tools::PaintDefaults, ) { - let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = now; + let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, style_doc, inherited } = now; if left.fill != *fill { target.fill.clone_from(fill); } @@ -936,8 +937,9 @@ fn take_changed_paints( if left.blend != *blend { target.blend = *blend; } - if left.style != *style { + if left.style != *style || left.style_doc != *style_doc { target.style.clone_from(style); + target.style_doc = *style_doc; } if left.inherited != *inherited { target.inherited = *inherited; diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index 58cf6ab295..a649399f9c 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -592,3 +592,60 @@ fn a_basic_graphic_style_picked_with_basic_appearance_off_styles_each_new_type() run(&mut s, "select.none", json!({})); } } + +#[test] +fn new_type_that_text_wrap_moves_takes_the_styles_gradient_on_the_frame_it_ends_with() { + let mut s = session(); + let group = run(&mut s, "object.newGroup", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 80})); + // A placed vertical gradient, top to bottom of the rectangle. + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]); + run(&mut s, "paint.setFill", json!({"gradient": {"stops": stops, "start": [50, 0], "end": [50, 80]}})); + let name = run(&mut s, "graphicStyle.new", json!({"name": "Vertical"}))["name"].as_str().unwrap().to_string(); + run(&mut s, "object.textWrap.make", json!({"offset": 0})); + let style = s.doc().unwrap().doc.graphic_styles.iter().find(|g| g.name == name).unwrap().clone(); + assert!(style.unit_box && style.appearance.has_placed_gradient()); + let area = json!({"width": 100, "height": 20, "fit": "autoHeight"}); + // Drawn behind the wrap object, and placed into a group below it. + for p in [ + json!({"x": 0, "y": 0, "text": "a", "size": 12, "area": area}), + json!({"x": 0, "y": 0, "text": "a", "size": 12, "area": area, "parent": group}), + ] { + run(&mut s, "select.none", json!({})); + run(&mut s, "view.drawMode", json!({"mode": if p.get("parent").is_some() { "normal" } else { "behind" }})); + run(&mut s, "graphicStyle.apply", json!({"name": name})); + let n = new_type(&mut s, p.clone()); + let b = n.geometric_bounds().unwrap(); + assert!(b.height() > 80.0, "the frame grows below the wrap object: {b:?} ({p})"); + let mut placed = style.appearance.clone(); + placed.rebase_gradients(vectorcraft_doc::GraphicStyle::UNIT_BOX, b); + assert_eq!(*n.appearance, placed, "{p}"); + } +} + +#[test] +fn new_art_in_another_document_is_not_linked_to_a_style_of_the_same_name() { + let mut s = session(); + fancy(&mut s); + run(&mut s, "transparency.set", json!({"knockout": "on", "isolate": true})); + run(&mut s, "graphicStyle.new", json!({"name": "Shared"})); + run(&mut s, "select.none", json!({})); + run(&mut s, "graphicStyle.apply", json!({"name": "Shared"})); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + rect(&mut s, 20.0); + run(&mut s, "graphicStyle.new", json!({"name": "Shared"})); + for (make, p) in + [("shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 30})), ("text.create", json!({"x": 200, "y": 200, "text": "k"}))] + { + run(&mut s, "select.none", json!({})); + let id = NodeId(run(&mut s, make, p)["id"].as_u64().unwrap()); + let n = node(&s, id); + assert_eq!((n.extras().graphic_style, n.isolate), (None, false), "{make}"); + assert_eq!(n.appearance.effects.len(), 1, "{make} keeps the template's look"); + } + // Back in the document the style came from, new art is linked to it again. + s.set_active(0); + run(&mut s, "select.none", json!({})); + run(&mut s, "text.create", json!({"x": 200, "y": 200, "text": "k"})); + assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Shared".to_string(), true))); +} diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 2ac3c90086..acc45b4338 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -25,6 +25,8 @@ pub struct PaintDefaults { pub blend: vectorcraft_color::BlendMode, /// The graphic style the template came from (by name): new art is linked to it. pub style: Option, + /// The document `style` is in (its session id): new art in another document is not linked. + pub style_doc: Option, /// The template is the last selection's appearance (New Art Has Basic Appearance off): with /// the option on again, new art takes only its basic fill and stroke. pub inherited: bool, @@ -41,6 +43,7 @@ impl Default for PaintDefaults { opacity: 1.0, blend: Default::default(), style: None, + style_doc: None, inherited: false, } } diff --git a/docs/mcp.md b/docs/mcp.md index 28cf93df21..b16ffb028d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11564,7 +11564,10 @@ and stroke or comes from a graphic style; otherwise it has no fills or strokes o color. With Override Character Color on, its characters lose the fill and stroke the template paints, as when a graphic style is applied to type; a `color` given to `text.create` keeps the characters' fill. Type made with a graphic style's look takes the style's opacity and blend mode and is linked to it; otherwise the type keeps its own opacity and -blend mode. +blend mode. New art and type are linked to the style only in the document the style was picked in, or the selection +it was taken from was in; in another document they take the look without the link. When text wrap moves new area +type as it is made (an Auto Size frame below a wrap object grows), the template's placed gradients fit the frame the +type ends with. Type on a Path and Area Type (`text.createInPath`) keep the default appearance. `appearance.setNewArtBasic` rejects an `on` value that is not a boolean. Omitting `on` toggles the current preference. `appearance.setNewArt {fill?, stroke?, weight?, cap?, join?, miterLimit?, dash?, dashOffset?, fillOverprint?, strokeOverprint?}` sets new art's fill, stroke and stroke options whatever is selected, and leaves the selection, its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 32a74f9a04..b37eee173f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -783,7 +783,7 @@ since 2026-10-01. - **PDF editable import:** Place from bytes or a path with `link: false`, and `clipboard.importPdf` followed by Paste, preserve live type on the selected page. Place still honors `textAs: "outlines"`. Synthetic two-page regressions: `crates/engine/src/cmd/fileio/tests_pdffidelity.rs`. No change to the PDF reader's existing fallback rules. - **Tab stops in `.ai`/EPS type and right-aligned lines with tabs (#6147):** type from the text document keeps its paragraphs' tab stops (key 30: positions and left, center, right and decimal alignments; leaders aren't read), at most 1,024 a paragraph and 2^20 a story, past which the default stops apply with a warning. In right-aligned area type, the text before a line's last tab sits at its stops, measured from the left edge, and the text after it (none when the tab ends the line, with its hyphen when the line is hyphenated) against the right edge; centred and justified lines, point type and right-to-left paragraphs are aligned as a whole as before. Evidence: `ate::tests::a_paragraph_keeps_its_tab_stops`, `ate::tests::a_story_s_tab_stops_are_bounded`, `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`, `import_fuzz::text_frames_with_hostile_paragraph_attributes_never_panic`. Scores unchanged. - **`.ai`/EPS graphic styles that paint with a named gradient:** a graphic style library's style (or a file's listed style) whose fill, or the fill or stroke of a style of one paint, paints with one of the file's gradients by name loads with that gradient at the style's angle, fitted to the bounds of each object it is applied to (VectorCraft's own placement; the style stores only the gradient's name and angle). A style naming a gradient the file doesn't define, or painting with a pattern, is still left out. Evidence: `fileio::tests_aiimport::graphic_styles_in_a_ai_library_that_paint_with_a_named_gradient_load_with_it`, `style::tests::a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on`. Scores unchanged. -- **New type takes new art's appearance:** with New Art Has Basic Appearance off, new objects take every appearance attribute of the current appearance ([Edit appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/edit-appearance-attributes.html)). Type made with the Type tools (`text.create`) now takes the template's fills, strokes and effects when the template is more than one plain fill and stroke or comes from a graphic style picked with nothing selected, and with Override Character Color on its characters lose the fill and stroke those paint. Type made with a style's look is linked to the style. With the option on and no style picked, new type is unchanged. Evidence: `tests::newart::with_basic_appearance_off_new_type_takes_the_last_selections_fills_and_effects`, `tests::newart::new_type_keeps_plain_characters_without_a_template_beyond_a_basic_fill_and_stroke`, `tests::newart::a_graphic_style_clicked_with_nothing_selected_styles_the_next_type`, `tests::newart::a_basic_graphic_style_picked_with_basic_appearance_off_styles_each_new_type`. Scores unchanged. +- **New type takes new art's appearance:** with New Art Has Basic Appearance off, new objects take every appearance attribute of the current appearance ([Edit appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/edit-appearance-attributes.html)). Type made with `text.create` (the Type and Vertical Type tools) now takes the template's fills, strokes and effects when the template is more than one plain fill and stroke or comes from a graphic style picked with nothing selected, and with Override Character Color on its characters lose the fill and stroke those paint, except that a `color` given to `text.create` keeps the characters' fill. Its placed gradients fit the frame the type has once text wrap has moved it. Type made with a style's look is linked to the style, in the document the style was picked in; in another document it takes the look without the link. Type on a Path and Area Type (`text.createInPath`) keep the default appearance. With the option on and no style picked, new type is unchanged. Evidence: `tests::newart::with_basic_appearance_off_new_type_takes_the_last_selections_fills_and_effects`, `tests::newart::new_type_keeps_plain_characters_without_a_template_beyond_a_basic_fill_and_stroke`, `tests::newart::a_graphic_style_clicked_with_nothing_selected_styles_the_next_type`, `tests::newart::a_basic_graphic_style_picked_with_basic_appearance_off_styles_each_new_type`, `tests::newart::new_type_that_text_wrap_moves_takes_the_styles_gradient_on_the_frame_it_ends_with`, `tests::newart::new_art_in_another_document_is_not_linked_to_a_style_of_the_same_name`. Scores unchanged. - **`.ai`/EPS type laid out closer to the file's page (#6137):** type from the text document keeps auto leading as auto, each line taking the paragraph's Auto Leading share (key 7) of the largest type on it ([Line and character spacing](https://helpx.adobe.com/illustrator/using/line-character-spacing.html)); the paragraph's hyphenation options (keys 10 to 15) are read; area type of one frame whose last lines the file sets, but which don't fit here, may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines and no more than the file has (`vectorcraft_text::fit_source_lines`), with a warning when it does: the frame can stay as it is, or show only some of them; and a line a soft return ends is justified as a wrapped line is, a paragraph's last line keeping its alignment. Evidence: `ate::tests::auto_leading_follows_the_size_of_each_line`, `ate::tests::a_paragraph_keeps_its_auto_leading`, `ate::tests::a_paragraph_keeps_its_hyphenation_options`, `ate::tests::the_last_lines_the_file_sets_in_its_frame_show`, `tests::fit_source_lines_keeps_the_last_lines_the_source_sets`, `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores unchanged. - **Graphs saved to `.ai` keep their data and settings:** a grouped column, stacked column, line or area graph is written to a `.ai` file, in either form, with the records the `.ai` reader reads (`crates/eps/src/import/ai/read/graph.rs`, #7311): `%_Gs`, its plot, type, settings, axes and table, its series' groups each tagged `Go`, and `%_GS` ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), §17 and appendix A). The file opens again with the same live graph. A graph with settings the reader doesn't keep, graph designs, label formatting, more than 10,000 categories or 256 series, or art the reader doesn't attach a graph to is written as its art, with a warning. `crates/eps/src/legacy_ai/tests.rs` and `crates/eps/src/ai_editing/tests.rs` write and read back each kind of graph; `a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns` checks every graph type the graph tools draw. Scores unchanged. - **Graph legend swatches have their series' stroke:** a default legend swatch of a stacked column, stacked bar, area or pie series has the thin white stroke of the series' marks (VectorCraft's own rule), beside the plot or across the top, and a stroke kept on the series is on the swatch too. Each series' group then paints with one stroke, so a stacked column or area graph the graph tools draw is saved to `.ai` with its data and settings and opens again as a live graph; a stacked bar graph is still written as its art, as the reader has no type for it. Evidence: `cmd::graph::tests::a_legend_swatch_has_the_stroke_of_its_series_marks`, `cmd::graph::tests::a_drawn_stacked_column_graph_saved_as_ai_opens_as_a_graph_that_takes_new_data`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`. Scores unchanged. @@ -1933,7 +1933,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Find Font: type in opacity masks and pattern swatches:** Type › Find Font…'s Document list (`text.fonts`), Find (`select.font`), Change and Change All (`text.replaceFont`), Replace Missing Fonts (`addon.cleanup.replaceFonts`), the Missing Fonts dialog (`text.missingFonts`), Document Info's Fonts and Font Details for the whole document (`document.info`), File › Package and the export warning about fonts that aren't available include the type in opacity masks (on objects and layers, disabled masks and masks inside mask, symbol or pattern art included) and in the art of pattern swatches, also a swatch that nothing paints with. A pattern's type is listed and changed once, however many objects the pattern paints. Find selects the objects whose mask holds the font, the text whose inline graphics draw a symbol whose art uses it, and the objects painted with a pattern whose art uses it by a visible fill or stroke above 0% opacity (VectorCraft's own rule; a layer's mask and a swatch that nothing paints with select nothing); Change and Change All leave the type in the mask of a hidden or locked object in its font and count it in `skipped`, and Change does the same with the type of a pattern that only hidden or locked selected objects paint with. The help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) says the Document list holds all the fonts the document uses. Tests: `crates/engine/src/cmd/fonts.rs`, `crates/engine/src/cmd/addons/cleanup/text/tests.rs`, `crates/engine/src/cmd/docinfo.rs`. - **Find Font works out the document's fonts once per version:** while Type › Find Font… is open, its Document list (`text.fonts`) and whether it shows Find in Folder… (the document misses a font) are worked out once for each version of the document's content and of the available fonts, and later frames reuse them. The list and the button are the same as before; an edit, an undo, another document in front, entering or leaving pattern editing, a composite font defined or taken out, and fonts added or scanned again give them anew. With 2,000 point-type objects of 50 characters each, set in five installed faces and a missing family, working them out took a median 1.53 ms of thread CPU time per frame in a release build on Linux; the first frame after a change still takes about as long, and later frames take about 10 ns. With 20 such objects it took 58 µs per frame. Tests: `find_font::tests::the_font_list_is_worked_out_once_per_document_version`, `an_edit_works_the_font_list_out_again`, `other_available_fonts_work_the_font_list_out_again`, `the_font_list_follows_the_document_in_front`; the timing probe is `find_font::tests::find_font_list_timing`. - **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the font filters every font menu shares (one chosen in the Glyphs panel's menu or a dialog's applies too) but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`. -- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). New type, made with the Type tools, `text.create`, `text.createInPath` or by pasting plain text, starts in [Normal Character Style] as every character does by default ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)), so it is filled black, or with the fill a redefined [Normal Character Style] has (editing that style is how new type's defaults change: [FAQs on fonts in Illustrator](https://helpx.adobe.com/illustrator/using/fonts-faq.html), "How to change the default font"), not with the current fill left from the last shape; a `color` given to the command still wins (#7975). It also takes the font, style, size and other character attributes of a redefined [Normal Character Style], so redefining that style in a New Document profile sets the default font of the profile's documents ([Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html)); a `font`, `style` or `size` given to the command still wins. Tests: `new_type_takes_the_normal_character_style_fill_not_the_current_fill`, `pasted_plain_text_takes_the_normal_character_style_fill`, `tests::newdoc::a_profiles_normal_character_style_is_the_default_font`. +- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). New type, made with the Type tools, `text.create`, `text.createInPath` or by pasting plain text, starts in [Normal Character Style] as every character does by default ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)), so it is filled black, or with the fill a redefined [Normal Character Style] has (editing that style is how new type's defaults change: [FAQs on fonts in Illustrator](https://helpx.adobe.com/illustrator/using/fonts-faq.html), "How to change the default font"), not with the current fill left from the last shape; a `color` given to the command still wins (#7975). When `text.create` type takes the new-art template's fills and strokes (New type takes new art's appearance), Override Character Color takes the characters' fill and stroke away, and only a `color` given to the command keeps their fill. It also takes the font, style, size and other character attributes of a redefined [Normal Character Style], so redefining that style in a New Document profile sets the default font of the profile's documents ([Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html)); a `font`, `style` or `size` given to the command still wins. Tests: `new_type_takes_the_normal_character_style_fill_not_the_current_fill`, `pasted_plain_text_takes_the_normal_character_style_fill`, `tests::newdoc::a_profiles_normal_character_style_is_the_default_font`. The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). Each reference shows an icon of the height it measures before its name, in the open list and in the closed field (#6304): a frame around a letter for Em Box, a bar from the baseline to the top of a capital for Cap Height and of a lowercase x for x-Height, and a frame inset in the em square for ICF Box. With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in area type of any shape, rows, columns and text wrap included. In a frame that is not a rectangle, or with text wrap, each line it tries is measured where the lines above it put it, across the line's own height, so a taller line gets the room of the narrower part of the frame, or of the span beside a wrap object, that it reaches. When the frame cannot hold all of such a paragraph, the lines it holds are still composed with the whole paragraph, the lines past the frame's end measured as wide as the last line the frame holds (VectorCraft's own rule); they overflow or go on in the next threaded frame, which composes them again. Such a paragraph is broken with the Single-line Composer when the frame has no room for its first line or when the search passes VectorCraft's own limits. The Single-line Composer measures a line's room across the height of its tallest character too: a line that takes in a taller character is placed again and broken again in the room there. Behavior reference: [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/set-hyphenation-and-line-breaks.html), and for text that flows on between threaded objects, [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html). A text wrap object's Offset may be negative as well as positive ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=307)). A negative Offset (to -1000 pt) shrinks the wrap object by that distance, measured from each edge itself and from the edges of its holes, so lines beside it, above it and below it run that far into it, and an object narrower than twice the distance no longer moves text aside. With Invert Wrap, a negative Offset keeps the text that far inside the object. These are VectorCraft's own rules for the shape of the shrunk object. Text Wrap Options, `object.textWrap.make` and `object.textWrap.options` and the MCP `text_wrap` tool take the negative value, and layout uses it (`crates/text/src/layout/region.rs` tests, `cmd::textwrap::tests::text_wrap_options_negative_offset_reflows_and_round_trips`). From ecec18e70ce3abf656eacbfcab5a9bd7ff9d4f0f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 23:47:31 -0800 Subject: [PATCH 30/42] Fix #10804: E with the Extend Path tool cycles its shape without a drag The Extend Path tool claims E at all times, but outside a gesture the canvas takes only the fixed key sets its claims match (brackets, digits, Tab, Home and End). A plain E with no drag running went to the shortcuts and chose the Free Transform tool. The canvas now takes E while the active tool claims it, so E cycles the tool's shape (straight, bezier, arc) whether or not a drag is running, as docs/mcp.md describes. Other tools do not claim E outside a marquee, so E still chooses Free Transform with them. Reported by MichelRickhaus. --- crates/ui-egui/src/canvas/tool_adapter.rs | 3 +++ crates/ui-egui/src/shortcuts/tests.rs | 25 +++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index c7d13cc96c..1e144c0f87 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -47,6 +47,7 @@ const PLANES: &[Chord] = &[Chord::plain(Key::Num1), Chord::plain(Key::Num2), Chord::plain(Key::Num3), Chord::plain(Key::Num4), Chord::plain(Key::Num5)]; const TAB: &[Chord] = &[Chord::plain(Key::Tab)]; const HOME_END: &[Chord] = &[Chord::plain(Key::Home), Chord::plain(Key::End)]; +const LETTER_E: &[Chord] = &[Chord::plain(Key::E)]; /// The modifiers of an egui key event, as the engine's tools read them. pub fn mods(m: egui::Modifiers, space: bool) -> Mods { @@ -489,6 +490,8 @@ impl CanvasTool for SessionTool<'_> { _ if claim(&mut app, EngineKey::Digit(1)) => PLANES, _ if claim(&mut app, EngineKey::Tab) => TAB, _ if claim(&mut app, EngineKey::Home) => HOME_END, + // The Extend Path tool's E cycles its shape with no drag running too. + _ if claim(&mut app, EngineKey::Letter('e')) => LETTER_E, _ => &[], }; let mut claims = ToolClaims::NONE.keys(keys); diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 5ed8517c01..d2e2c1182c 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -406,6 +406,31 @@ fn tool_keys_choose_their_tools() { } } +/// E with the Extend Path tool and no drag cycles the tool's shape; with another tool E still chooses Free Transform. +#[test] +fn e_with_the_extend_path_tool_cycles_its_shape_without_a_drag() { + let press_e = |tool: &str| { + let mut app = new_app(); + let ctx = ready(&mut app); + app.select_tool(tool); + focus_canvas(&mut app, &ctx); + assert!(!app.session.tool_busy()); + key_frame(&mut app, &ctx, typed(Key::E, Modifiers::NONE, "e")); + app + }; + let app = press_e("selection"); + assert_eq!(app.session.tool_id(), "freeTransform", "E's shortcut with a tool that does not use E"); + + let extend = vectorcraft_tools::addons::extend_path::ID; + let mut app = press_e(extend); + assert_eq!(app.session.tool_id(), extend, "E is the tool's key"); + assert_eq!(app.session.tool_options()["mode"], "bezier", "E cycles straight to bezier"); + let ctx = ready(&mut app); + focus_canvas(&mut app, &ctx); + key_frame(&mut app, &ctx, typed(Key::E, Modifiers::NONE, "e")); + assert_eq!(app.session.tool_options()["mode"], "arc", "a second E cycles on"); +} + /// A tool bound to a key that types nothing, a panel and a command, and a held Cmd+= zooms on. #[test] fn shortcuts_run_tools_panels_and_commands() { From 3a00fd8f4e0b6653a1f1f82782e468824adaef5d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 23:56:29 -0800 Subject: [PATCH 31/42] Canvas: absolute drags leave no part of a pixel for later pans An absolute drag (Hand, compass, scroll bars) rounds each pass's view from the last one without adding the remainder kept from earlier, but it still stored the remainder pan_step returned. A drag by 0.4 device pixels then made a later wheel step of 0.2 device pixels move the view by a whole pixel. settled_on_device_pixels now keeps nothing owed after an absolute drag. --- crates/ui-egui/src/canvas.rs | 4 ++-- crates/ui-egui/src/canvas/tests.rs | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 66b055c874..1490c35a89 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -415,12 +415,12 @@ fn pan_on_device_pixels(rest: Option, max_side: usize, space: &mut Canv /// `view`, the view the app keeps after this pass, moved from the view of `rest` by whole device pixels when it differs /// from it in its center alone (a tool, a scroll bar or the compass panned it after [`pan_on_device_pixels`]), and the -/// rest to keep. +/// rest to keep. Without `carry` (an absolute drag) the rest neither adds nor keeps a part of a pixel. fn settled_on_device_pixels(rest: Option, view: CanvasView, carry: bool) -> (CanvasView, Option) { let Some(rest) = rest.filter(|rest| rest.view != view) else { return (view, rest) }; let ppp = rest.pixels_per_point; match pan_step(rest.view, view, if carry { rest.owed } else { (0.0, 0.0) }, ppp) { - Some((view, owed)) => (view, Some(PanRest { view, owed, ..rest })), + Some((view, owed)) => (view, Some(PanRest { view, owed: if carry { owed } else { (0.0, 0.0) }, ..rest })), None => (view, Some(PanRest::none(view, ppp))), } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index c266b780c2..cb3083be8e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6371,6 +6371,23 @@ fn a_drag_s_views_stay_within_half_a_pixel_of_the_pointer() { } } +/// A drag's rounding is not owed to the pans after it: a drag by 0.4 device pixels leaves the view where it was and +/// nothing owed, so a later step of 0.2 device pixels does not move the view either. +#[test] +fn a_drag_leaves_nothing_owed_to_later_pans() { + let rect = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(640.0, 480.0)); + let start = CanvasView::new(rect, Point::new(100.0, 80.0), 1.0); + let mut asked = start; + asked.center = start.center - start.unmap_vec(vec2(0.4, 0.0)); + let (view, rest) = super::settled_on_device_pixels(Some(super::PanRest::none(start, 1.0)), asked, false); + assert_eq!(view.center, start.center, "a drag by 0.4 device pixels rounds to no move"); + assert_eq!(rest.map(|rest| rest.owed), Some((0.0, 0.0)), "the drag leaves nothing owed"); + let mut stepped = view; + stepped.center = view.center - view.unmap_vec(vec2(0.2, 0.0)); + let (after, _) = super::settled_on_device_pixels(rest, stepped, true); + assert_eq!(after.center, view.center, "a step of 0.2 device pixels alone does not move the view"); +} + /// Steps a tool takes from where the view was (a drag's autoscroll, the Hand's glide) keep the parts of a pixel they /// leave: after each pass the view is within half a device pixel of all the steps together. #[test] From 5f49ebf6e59e162cbee2433d526df29c86bb6471 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 00:52:29 -0800 Subject: [PATCH 32/42] Type: new type keeps a style's look and transparency in another document A graphic style picked in one document and used for new type in another lost its look when the style was one plain fill and stroke, and lost its opacity and blend mode in every case, because both checks read the style name that is dropped outside the style's document. New type now checks whether its look came from a graphic style separately from the link: the link is still left out in another document, the look and transparency are not. The docs say that area type made with `text.create` and `area` takes the template, and only Type on a Path and `text.createInPath` area type keep the default appearance. --- crates/engine/src/cmd/newart.rs | 27 ++++++++++++++++++--------- crates/engine/src/tests/newart.rs | 16 ++++++++++++++++ docs/mcp.md | 7 ++++--- docs/target-app-parity.md | 2 +- 4 files changed, 39 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index 01044f7c21..2dfaf626f6 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -280,6 +280,8 @@ pub(crate) struct NewArt { opacity: f32, blend: BlendMode, style: Option, + /// Taken from a graphic style, linked to it or not (a style from another document is not). + styled: bool, /// From the template: placed gradients are relative to the unit box. unit_box: bool, } @@ -287,7 +289,7 @@ pub(crate) struct NewArt { impl NewArt { /// A plain look: `appearance`, full opacity, no link. pub(crate) fn plain(appearance: Appearance) -> Self { - Self { appearance, opacity: 1.0, blend: BlendMode::Normal, style: None, unit_box: false } + Self { appearance, opacity: 1.0, blend: BlendMode::Normal, style: None, styled: false, unit_box: false } } /// Give new object `n` (in `d`) this look: its placed gradients land relative to its bounds, and @@ -295,7 +297,7 @@ impl NewArt { /// unless the look is a graphic style's). pub(crate) fn apply(&self, d: &mut vectorcraft_doc::Document, n: &mut Node) { self.place(n); - if matches!(n.kind, NodeKind::Text(_)) && self.style.is_none() { + if matches!(n.kind, NodeKind::Text(_)) && !self.styled { return; } (n.opacity, n.blend) = (self.opacity, self.blend); @@ -346,21 +348,28 @@ impl Session { st.width = width; } let (opacity, blend, style) = self.new_art_transparency(); - NewArt { appearance, opacity, blend, style: style.map(str::to_string), unit_box: true } + NewArt { appearance, opacity, blend, style: style.map(str::to_string), styled: self.new_art_styled(), unit_box: true } } /// The look of new type (`text.create`): the template's fills, strokes and effects when it is - /// more than one plain fill and stroke or comes from a graphic style, else none of its own, so - /// the characters' fill and stroke show. The template is not repainted with the fill and - /// stroke proxies. + /// more than one plain fill and stroke or comes from a graphic style (of this document or + /// another), else none of its own, so the characters' fill and stroke show. The template is + /// not repainted with the fill and stroke proxies. pub(crate) fn new_type_look(&self) -> NewArt { let plain = || NewArt::plain(Appearance::default()); let Some(t) = self.template() else { return plain() }; - let (opacity, blend, style) = self.new_art_transparency(); - if t.is_basic() && style.is_none() { + let styled = self.new_art_styled(); + if t.is_basic() && !styled { return plain(); } - NewArt { appearance: t.into_owned(), opacity, blend, style: style.map(str::to_string), unit_box: true } + let (opacity, blend, style) = self.new_art_transparency(); + NewArt { appearance: t.into_owned(), opacity, blend, style: style.map(str::to_string), styled, unit_box: true } + } + + /// Does the next object drawn take its look from a graphic style, in this document or the one + /// the style was taken from? + fn new_art_styled(&self) -> bool { + !self.basic_only() && self.paint.style.is_some() } /// The appearance of the next object drawn (the Appearance panel shows it with nothing diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index a649399f9c..f7ef210fd0 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -649,3 +649,19 @@ fn new_art_in_another_document_is_not_linked_to_a_style_of_the_same_name() { run(&mut s, "text.create", json!({"x": 200, "y": 200, "text": "k"})); assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Shared".to_string(), true))); } + +#[test] +fn new_type_in_another_document_takes_a_basic_styles_look_and_transparency() { + let mut s = session(); + let src = painted(&mut s, 20.0, "#ff0000", "#0000ff", 2.0); + let red = node(&s, src).appearance.fill_paint(); + run(&mut s, "transparency.set", json!({"opacity": 50, "blend": "multiply"})); + run(&mut s, "graphicStyle.new", json!({"name": "Red"})); + run(&mut s, "select.none", json!({})); + run(&mut s, "graphicStyle.apply", json!({"name": "Red"})); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "k"})); + assert_eq!(n.appearance.fill_paint(), red, "the style's fill"); + assert_eq!((n.opacity, n.blend), (0.5, BlendMode::Multiply), "the style's transparency"); + assert_eq!(n.extras().graphic_style, None, "no link to a style of another document"); +} diff --git a/docs/mcp.md b/docs/mcp.md index 390919c0d0..2bc1631657 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11574,9 +11574,10 @@ color. With Override Character Color on, its characters lose the fill and stroke graphic style is applied to type; a `color` given to `text.create` keeps the characters' fill. Type made with a graphic style's look takes the style's opacity and blend mode and is linked to it; otherwise the type keeps its own opacity and blend mode. New art and type are linked to the style only in the document the style was picked in, or the selection -it was taken from was in; in another document they take the look without the link. When text wrap moves new area -type as it is made (an Auto Size frame below a wrap object grows), the template's placed gradients fit the frame the -type ends with. Type on a Path and Area Type (`text.createInPath`) keep the default appearance. +it was taken from was in; in another document they take the look, with the style's opacity and blend mode, without +the link. When text wrap moves new area type as it is made (an Auto Size frame below a wrap object grows), the +template's placed gradients fit the frame the type ends with. Area type made with `text.create` and `area` takes the +template too; Type on a Path and area type made with `text.createInPath` keep the default appearance. `appearance.setNewArtBasic` rejects an `on` value that is not a boolean. Omitting `on` toggles the current preference. `appearance.setNewArt {fill?, stroke?, weight?, cap?, join?, miterLimit?, dash?, dashOffset?, fillOverprint?, strokeOverprint?}` sets new art's fill, stroke and stroke options whatever is selected, and leaves the selection, its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 75df3f748a..86de5c7ade 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -783,7 +783,7 @@ since 2026-10-01. - **PDF editable import:** Place from bytes or a path with `link: false`, and `clipboard.importPdf` followed by Paste, preserve live type on the selected page. Place still honors `textAs: "outlines"`. Synthetic two-page regressions: `crates/engine/src/cmd/fileio/tests_pdffidelity.rs`. No change to the PDF reader's existing fallback rules. - **Tab stops in `.ai`/EPS type and right-aligned lines with tabs (#6147):** type from the text document keeps its paragraphs' tab stops (key 30: positions and left, center, right and decimal alignments; leaders aren't read), at most 1,024 a paragraph and 2^20 a story, past which the default stops apply with a warning. In right-aligned area type, the text before a line's last tab sits at its stops, measured from the left edge, and the text after it (none when the tab ends the line, with its hyphen when the line is hyphenated) against the right edge; centred and justified lines, point type and right-to-left paragraphs are aligned as a whole as before. Evidence: `ate::tests::a_paragraph_keeps_its_tab_stops`, `ate::tests::a_story_s_tab_stops_are_bounded`, `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`, `import_fuzz::text_frames_with_hostile_paragraph_attributes_never_panic`. Scores unchanged. - **`.ai`/EPS graphic styles that paint with a named gradient:** a graphic style library's style (or a file's listed style) whose fill, or the fill or stroke of a style of one paint, paints with one of the file's gradients by name loads with that gradient at the style's angle, fitted to the bounds of each object it is applied to (VectorCraft's own placement; the style stores only the gradient's name and angle). A style naming a gradient the file doesn't define, or painting with a pattern, is still left out. Evidence: `fileio::tests_aiimport::graphic_styles_in_a_ai_library_that_paint_with_a_named_gradient_load_with_it`, `style::tests::a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on`. Scores unchanged. -- **New type takes new art's appearance:** with New Art Has Basic Appearance off, new objects take every appearance attribute of the current appearance ([Edit appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/edit-appearance-attributes.html)). Type made with `text.create` (the Type and Vertical Type tools) now takes the template's fills, strokes and effects when the template is more than one plain fill and stroke or comes from a graphic style picked with nothing selected, and with Override Character Color on its characters lose the fill and stroke those paint, except that a `color` given to `text.create` keeps the characters' fill. Its placed gradients fit the frame the type has once text wrap has moved it. Type made with a style's look is linked to the style, in the document the style was picked in; in another document it takes the look without the link. Type on a Path and Area Type (`text.createInPath`) keep the default appearance. With the option on and no style picked, new type is unchanged. Evidence: `tests::newart::with_basic_appearance_off_new_type_takes_the_last_selections_fills_and_effects`, `tests::newart::new_type_keeps_plain_characters_without_a_template_beyond_a_basic_fill_and_stroke`, `tests::newart::a_graphic_style_clicked_with_nothing_selected_styles_the_next_type`, `tests::newart::a_basic_graphic_style_picked_with_basic_appearance_off_styles_each_new_type`, `tests::newart::new_type_that_text_wrap_moves_takes_the_styles_gradient_on_the_frame_it_ends_with`, `tests::newart::new_art_in_another_document_is_not_linked_to_a_style_of_the_same_name`. Scores unchanged. +- **New type takes new art's appearance:** with New Art Has Basic Appearance off, new objects take every appearance attribute of the current appearance ([Edit appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/edit-appearance-attributes.html)). Type made with `text.create` (the Type and Vertical Type tools) now takes the template's fills, strokes and effects when the template is more than one plain fill and stroke or comes from a graphic style picked with nothing selected, and with Override Character Color on its characters lose the fill and stroke those paint, except that a `color` given to `text.create` keeps the characters' fill. Its placed gradients fit the frame the type has once text wrap has moved it. Type made with a style's look is linked to the style, in the document the style was picked in; in another document it takes the look, with the style's opacity and blend mode, without the link. Area type dragged with the Type tool (`text.create` with `area`) takes the template too; Type on a Path and area type made with `text.createInPath` keep the default appearance. With the option on and no style picked, new type is unchanged. Evidence: `tests::newart::with_basic_appearance_off_new_type_takes_the_last_selections_fills_and_effects`, `tests::newart::new_type_keeps_plain_characters_without_a_template_beyond_a_basic_fill_and_stroke`, `tests::newart::a_graphic_style_clicked_with_nothing_selected_styles_the_next_type`, `tests::newart::a_basic_graphic_style_picked_with_basic_appearance_off_styles_each_new_type`, `tests::newart::new_type_that_text_wrap_moves_takes_the_styles_gradient_on_the_frame_it_ends_with`, `tests::newart::new_art_in_another_document_is_not_linked_to_a_style_of_the_same_name`, `tests::newart::new_type_in_another_document_takes_a_basic_styles_look_and_transparency`. Scores unchanged. - **`.ai`/EPS type laid out closer to the file's page (#6137):** type from the text document keeps auto leading as auto, each line taking the paragraph's Auto Leading share (key 7) of the largest type on it ([Line and character spacing](https://helpx.adobe.com/illustrator/using/line-character-spacing.html)); the paragraph's hyphenation options (keys 10 to 15) are read; area type of one frame whose last lines the file sets, but which don't fit here, may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines and no more than the file has (`vectorcraft_text::fit_source_lines`), with a warning when it does: the frame can stay as it is, or show only some of them; and a line a soft return ends is justified as a wrapped line is, a paragraph's last line keeping its alignment. Evidence: `ate::tests::auto_leading_follows_the_size_of_each_line`, `ate::tests::a_paragraph_keeps_its_auto_leading`, `ate::tests::a_paragraph_keeps_its_hyphenation_options`, `ate::tests::the_last_lines_the_file_sets_in_its_frame_show`, `tests::fit_source_lines_keeps_the_last_lines_the_source_sets`, `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores unchanged. - **Graphs saved to `.ai` keep their data and settings:** a grouped column, stacked column, line or area graph is written to a `.ai` file, in either form, with the records the `.ai` reader reads (`crates/eps/src/import/ai/read/graph.rs`, #7311): `%_Gs`, its plot, type, settings, axes and table, its series' groups each tagged `Go`, and `%_GS` ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), §17 and appendix A). The file opens again with the same live graph. A graph with settings the reader doesn't keep, graph designs, label formatting, more than 10,000 categories or 256 series, or art the reader doesn't attach a graph to is written as its art, with a warning. `crates/eps/src/legacy_ai/tests.rs` and `crates/eps/src/ai_editing/tests.rs` write and read back each kind of graph; `a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns` checks every graph type the graph tools draw. Scores unchanged. - **Graph legend swatches have their series' stroke:** a default legend swatch of a stacked column, stacked bar, area or pie series has the thin white stroke of the series' marks (VectorCraft's own rule), beside the plot or across the top, and a stroke kept on the series is on the swatch too. Each series' group then paints with one stroke, so a stacked column or area graph the graph tools draw is saved to `.ai` with its data and settings and opens again as a live graph; a stacked bar graph is still written as its art, as the reader has no type for it. Evidence: `cmd::graph::tests::a_legend_swatch_has_the_stroke_of_its_series_marks`, `cmd::graph::tests::a_drawn_stacked_column_graph_saved_as_ai_opens_as_a_graph_that_takes_new_data`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`. Scores unchanged. From 8ed783706be7714615756cc75f9d20a3f126870a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 00:54:44 -0800 Subject: [PATCH 33/42] Canvas: an absolute drag that keeps the view clears what is owed settled_on_device_pixels returned the rest unchanged when the view after the pass matched the rest's view, so an absolute drag pass that left the view in place kept the part of a pixel earlier pans owed. A later wheel step could then move the view by a whole pixel the drag had left out. That branch now clears the owed part when the pass does not carry it, and keeps it when it does. --- crates/ui-egui/src/canvas.rs | 5 ++++- crates/ui-egui/src/canvas/tests.rs | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 1490c35a89..facbde7d15 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -417,7 +417,10 @@ fn pan_on_device_pixels(rest: Option, max_side: usize, space: &mut Canv /// from it in its center alone (a tool, a scroll bar or the compass panned it after [`pan_on_device_pixels`]), and the /// rest to keep. Without `carry` (an absolute drag) the rest neither adds nor keeps a part of a pixel. fn settled_on_device_pixels(rest: Option, view: CanvasView, carry: bool) -> (CanvasView, Option) { - let Some(rest) = rest.filter(|rest| rest.view != view) else { return (view, rest) }; + let Some(rest) = rest else { return (view, None) }; + if rest.view == view { + return (view, Some(PanRest { owed: if carry { rest.owed } else { (0.0, 0.0) }, ..rest })); + } let ppp = rest.pixels_per_point; match pan_step(rest.view, view, if carry { rest.owed } else { (0.0, 0.0) }, ppp) { Some((view, owed)) => (view, Some(PanRest { view, owed: if carry { owed } else { (0.0, 0.0) }, ..rest })), diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index cb3083be8e..8e2281effb 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6388,6 +6388,25 @@ fn a_drag_leaves_nothing_owed_to_later_pans() { assert_eq!(after.center, view.center, "a step of 0.2 device pixels alone does not move the view"); } +/// A drag pass that leaves the view where it was clears what earlier pans left owed, so a later step of 0.2 device +/// pixels after 0.4 owed does not move the view by a whole pixel. +#[test] +fn a_drag_that_leaves_the_view_in_place_clears_what_is_owed() { + let rect = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(640.0, 480.0)); + let start = CanvasView::new(rect, Point::new(100.0, 80.0), 1.0); + let owing = super::PanRest { owed: (0.4, 0.0), ..super::PanRest::none(start, 1.0) }; + let (view, rest) = super::settled_on_device_pixels(Some(owing), start, false); + assert_eq!(view, start, "the drag keeps the view"); + assert_eq!(rest.map(|rest| rest.owed), Some((0.0, 0.0)), "the drag leaves nothing owed"); + let mut stepped = view; + stepped.center = view.center - view.unmap_vec(vec2(0.2, 0.0)); + let (after, _) = super::settled_on_device_pixels(rest, stepped, true); + assert_eq!(after.center, view.center, "a step of 0.2 device pixels alone does not move the view"); + // A pass that carries the rest keeps what is owed when the view stays where it was. + let (_, kept) = super::settled_on_device_pixels(Some(owing), start, true); + assert_eq!(kept.map(|rest| rest.owed), Some((0.4, 0.0)), "a carrying pass keeps what is owed"); +} + /// Steps a tool takes from where the view was (a drag's autoscroll, the Hand's glide) keep the parts of a pixel they /// leave: after each pass the view is within half a device pixel of all the steps together. #[test] From 98121b6621a4a2e1c05474795573aee20aae6dd6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 01:40:24 -0800 Subject: [PATCH 34/42] Fix #10817: Tab while editing type types a tab without hiding the panels While the Type tool edited text, one Tab press typed a tab character and also hid the panels, and Shift+Tab hid the panels except the tools. The framework sends a bare Tab that the text editor keeps to the panels toggle as well (craft-libs#4783). The command gate now refuses both panels toggles while the Type tool edits text, so Tab and Shift+Tab reach only the editor and typing order is unchanged. Outside an edit Tab hides the panels as before. The rule is a workaround: the craft-libs pin bump that includes #4783 removes it. Reported by anselher. --- crates/ui-egui/src/menus/model.rs | 19 ++++++----- crates/ui-egui/src/tests/selectall.rs | 48 ++++++++++++++++++++++++++- 2 files changed, 58 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 84125b1a43..56b6d2ce80 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -277,16 +277,19 @@ pub(crate) fn command_input(app: &VectorcraftApp) -> CommandInput { input.gate(CommandGate::new(gate_state(app), gate_open)) } -/// What the commands' gate reads: whether a file dialog is open or a shortcut is being recorded, and whether the app -/// presents. -fn gate_state(app: &VectorcraftApp) -> (bool, bool) { - (app.file_dialog_open() || recording_shortcut(app), app.ui.screen_mode == 3) +/// What the commands' gate reads: whether a file dialog is open or a shortcut is being recorded, whether the app +/// presents, and whether the Type tool edits text. +fn gate_state(app: &VectorcraftApp) -> (bool, bool, bool) { + (app.file_dialog_open() || recording_shortcut(app), app.ui.screen_mode == 3, app.session.tool_wants_text()) } -/// Whether `command` may run now: nothing while a file dialog is open or a shortcut is being recorded, and only -/// Presentation Mode's own toggle while presenting. -fn gate_open(&(blocked, presenting): &(bool, bool), command: &CommandRef) -> bool { - !blocked && (!presenting || command.id == "view.presentation") +/// Whether `command` may run now: nothing while a file dialog is open or a shortcut is being recorded, only +/// Presentation Mode's own toggle while presenting, and neither panels toggle while the Type tool edits text, where +/// Tab types a tab. Workaround for craft-libs#4783: the framework also sends the Tab the Type tool keeps to the panels +/// toggle. The craft-libs pin bump that includes #4783 removes the third rule. +fn gate_open(&(blocked, presenting, typing): &(bool, bool, bool), command: &CommandRef) -> bool { + let panels_toggle = matches!(ChromeCommand::from_ref(command), Some(ChromeCommand::TogglePanels | ChromeCommand::TogglePanelsKeepTools)); + !blocked && (!presenting || command.id == "view.presentation") && !(typing && panels_toggle) } /// [`gate_open`] for `command` in the app's state now. diff --git a/crates/ui-egui/src/tests/selectall.rs b/crates/ui-egui/src/tests/selectall.rs index d7ae5f9b04..1f68db8f0b 100644 --- a/crates/ui-egui/src/tests/selectall.rs +++ b/crates/ui-egui/src/tests/selectall.rs @@ -2,7 +2,8 @@ //! a focused text field selects its own text, the Type tool editing selects the text being edited, //! the Artboards panel selects every artboard after a click on one of its rows with the Artboard //! tool, and only otherwise are all the objects selected. The clipboard keys follow it too: Copy -//! and Cut copy the text selected in a field or in a panel's label before the art. +//! and Cut copy the text selected in a field or in a panel's label before the art. Tab while the +//! Type tool edits types a tab and leaves the panels. use egui::accesskit::{Node, NodeId}; use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, pos2, vec2}; @@ -206,6 +207,51 @@ fn cmd_a_while_editing_type_selects_all_of_its_text() { assert!(names.contains(&json!("Z")), "{names:?}"); } +/// #10817: while the Type tool edits, Tab types a tab character and Shift+Tab does nothing; neither +/// hides the panels. Once the edit ends, Tab hides them again. +#[test] +fn tab_while_editing_type_types_a_tab_and_keeps_the_panels() { + let mut a = App::new(); + a.app.select_tool("type"); + let view = a.app.view_info(); + for kind in [PointerKind::Down, PointerKind::Up] { + a.app.session.pointer(&PointerEvent::new(kind, 100.0, 200.0), view).unwrap(); + } + a.frame(vec![]); + a.frame(vec![Event::Text("abc".into())]); + let text = |a: &App| { + let (id, _, _) = crate::panels::character::text_editing(&a.app).expect("the Type tool edits"); + match &a.app.session.active().unwrap().doc.node(id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(text(&a), "abc"); + assert!(crate::panel_docking::panels_shown(&a.app)); + // A press and its release, as a keyboard sends them. + let tap = |key, modifiers| [press(key, modifiers), Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }]; + a.frame(tap(Key::Tab, Modifiers::NONE).to_vec()); + a.frame(vec![]); + assert_eq!(text(&a), "abc\t", "Tab types a tab"); + assert!(crate::panel_docking::panels_shown(&a.app), "Tab leaves the panels"); + a.frame(tap(Key::Tab, Modifiers::SHIFT).to_vec()); + a.frame(vec![]); + assert_eq!(text(&a), "abc\t", "Shift+Tab types nothing"); + assert!(crate::panel_docking::panels_shown(&a.app), "Shift+Tab leaves the panels"); + // Two taps in one frame type two tabs. + a.frame([tap(Key::Tab, Modifiers::NONE), tap(Key::Tab, Modifiers::NONE)].concat()); + a.frame(vec![]); + assert_eq!(text(&a), "abc\t\t\t"); + assert!(crate::panel_docking::panels_shown(&a.app)); + // Escape ends the edit: Tab hides the panels again. + a.frame(tap(Key::Escape, Modifiers::NONE).to_vec()); + a.frame(vec![]); + assert!(crate::panels::character::text_editing(&a.app).is_none(), "the edit ended"); + a.frame(tap(Key::Tab, Modifiers::NONE).to_vec()); + a.frame(vec![]); + assert!(!crate::panel_docking::panels_shown(&a.app), "Tab hides the panels outside an edit"); +} + /// With the Artboard tool, Cmd+A after a click on an Artboards panel row selects every artboard /// and leaves the active artboard and the art as they are; so does the macOS menu bar's Select All. /// After a press on the canvas, with the panel closed, or with the Selection tool, Cmd+A selects From 084d211cc9783d325a72ef409b63129aaa1c490a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 01:35:50 -0800 Subject: [PATCH 35/42] Fix #10547: tools draw their move, resize, grab and not-allowed cursors Most tool cursors are drawn by the app at its own cursor size, but Cursor::Move, the four resize cursors, HandGrab, NotAllowed, Text and the vertical type cursors were handed to the system. On Wayland the compositor draws those from the desktop's cursor theme at the theme's size, so one tool switched between a small drawn cursor and a large themed one, for example the Curvature tool over an anchor, the bounding box handles, or the Hand while panning. These cursors are now drawn too: new move, resize, not-allowed and vertical I-beam glyphs in assets/cursors, the framework's I-beam for Text, and the framework's hand, which closes while the primary button is down, for HandGrab. The busy pointer of a long operation stays the system's. --- ASSETS.md | 7 +++++ assets/cursors/cursor-move.svg | 1 + assets/cursors/cursor-not-allowed.svg | 1 + assets/cursors/cursor-resize-h.svg | 1 + assets/cursors/cursor-resize-nesw.svg | 1 + assets/cursors/cursor-resize-nwse.svg | 1 + assets/cursors/cursor-resize-v.svg | 1 + assets/cursors/cursor-type-vertical.svg | 1 + crates/tools/src/cursors.toml | 2 +- crates/ui-egui/src/cursors.rs | 29 +++++++++++++------- crates/ui-egui/src/cursors/tests.rs | 36 +++++++++++++++++++++++++ 11 files changed, 71 insertions(+), 10 deletions(-) create mode 100644 assets/cursors/cursor-move.svg create mode 100644 assets/cursors/cursor-not-allowed.svg create mode 100644 assets/cursors/cursor-resize-h.svg create mode 100644 assets/cursors/cursor-resize-nesw.svg create mode 100644 assets/cursors/cursor-resize-nwse.svg create mode 100644 assets/cursors/cursor-resize-v.svg create mode 100644 assets/cursors/cursor-type-vertical.svg diff --git a/ASSETS.md b/ASSETS.md index 03f33d9a6e..a74a9a29a4 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -83,11 +83,18 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/cursors/cursor-mark-ring.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-mark-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-mark-star.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-move.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-not-allowed.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-pen-convert.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-pen-curvature.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-pen-join.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-pen-new.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/cursors/cursor-reshape-segment.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-resize-h.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-resize-nesw.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-resize-nwse.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-resize-v.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/cursors/cursor-type-vertical.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork | | `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork | | `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork | diff --git a/assets/cursors/cursor-move.svg b/assets/cursors/cursor-move.svg new file mode 100644 index 0000000000..ee3c16ed90 --- /dev/null +++ b/assets/cursors/cursor-move.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-not-allowed.svg b/assets/cursors/cursor-not-allowed.svg new file mode 100644 index 0000000000..83a8556cd0 --- /dev/null +++ b/assets/cursors/cursor-not-allowed.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-resize-h.svg b/assets/cursors/cursor-resize-h.svg new file mode 100644 index 0000000000..361da7e098 --- /dev/null +++ b/assets/cursors/cursor-resize-h.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-resize-nesw.svg b/assets/cursors/cursor-resize-nesw.svg new file mode 100644 index 0000000000..0f37741f94 --- /dev/null +++ b/assets/cursors/cursor-resize-nesw.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-resize-nwse.svg b/assets/cursors/cursor-resize-nwse.svg new file mode 100644 index 0000000000..d143d581da --- /dev/null +++ b/assets/cursors/cursor-resize-nwse.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-resize-v.svg b/assets/cursors/cursor-resize-v.svg new file mode 100644 index 0000000000..095be8455d --- /dev/null +++ b/assets/cursors/cursor-resize-v.svg @@ -0,0 +1 @@ + diff --git a/assets/cursors/cursor-type-vertical.svg b/assets/cursors/cursor-type-vertical.svg new file mode 100644 index 0000000000..62b0d50f65 --- /dev/null +++ b/assets/cursors/cursor-type-vertical.svg @@ -0,0 +1 @@ + diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 5528b7cd97..5e34518138 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -483,7 +483,7 @@ shown_when = [ "The Smooth tool, and the Pencil or Blob Brush where Alt gives the Smooth tool, when no path is selected that the Smooth tool can act on: a drag changes nothing.", ] hotspot = "The centre." -designer = false +look = "A ring crossed by a diagonal bar." [[cursor]] id = "Busy" diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index b120d35c4a..436d8306e0 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -29,11 +29,18 @@ pub static CURSOR_ICONS: AppIcons = AppIcons::new( ("cursor-mark-ring", include_bytes!("../../../assets/cursors/cursor-mark-ring.svg")), ("cursor-mark-square", include_bytes!("../../../assets/cursors/cursor-mark-square.svg")), ("cursor-mark-star", include_bytes!("../../../assets/cursors/cursor-mark-star.svg")), + ("cursor-move", include_bytes!("../../../assets/cursors/cursor-move.svg")), + ("cursor-not-allowed", include_bytes!("../../../assets/cursors/cursor-not-allowed.svg")), ("cursor-pen-convert", include_bytes!("../../../assets/cursors/cursor-pen-convert.svg")), ("cursor-pen-curvature", include_bytes!("../../../assets/cursors/cursor-pen-curvature.svg")), ("cursor-pen-join", include_bytes!("../../../assets/cursors/cursor-pen-join.svg")), ("cursor-pen-new", include_bytes!("../../../assets/cursors/cursor-pen-new.svg")), ("cursor-reshape-segment", include_bytes!("../../../assets/cursors/cursor-reshape-segment.svg")), + ("cursor-resize-h", include_bytes!("../../../assets/cursors/cursor-resize-h.svg")), + ("cursor-resize-nesw", include_bytes!("../../../assets/cursors/cursor-resize-nesw.svg")), + ("cursor-resize-nwse", include_bytes!("../../../assets/cursors/cursor-resize-nwse.svg")), + ("cursor-resize-v", include_bytes!("../../../assets/cursors/cursor-resize-v.svg")), + ("cursor-type-vertical", include_bytes!("../../../assets/cursors/cursor-type-vertical.svg")), ], ); @@ -45,6 +52,8 @@ const PIPETTE_TIP: Vec2 = Vec2::new(2.0, 22.0); const CARET: Vec2 = Vec2::new(12.0, 6.0); /// The blade's point of the knife, at the box's upper right. const BLADE_POINT: Vec2 = Vec2::new(20.0, 4.0); +/// The middle of the box: the crossing of the move, resize and not-allowed glyphs and the vertical I-beam's center. +const CENTER: Vec2 = Vec2::new(12.0, 12.0); /// The bottom of the drop below the paint bucket. const BUCKET_DROP: Vec2 = Vec2::new(20.0, 22.0); /// The bottom of the drop beside the Live Paint diamond. @@ -91,12 +100,12 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::GroupSelection => badged(CursorBadge::Add), Cursor::SelectionMove => badged(CursorBadge::Move), Cursor::SelectionCopy => badged(CursorBadge::Copy), - Cursor::Move => system(CursorIcon::Move), + Cursor::Move => tool("cursor-move", CENTER, None), Cursor::Crosshair => PaintedCursor::Crosshair.into(), - Cursor::ResizeH => system(CursorIcon::ResizeHorizontal), - Cursor::ResizeV => system(CursorIcon::ResizeVertical), - Cursor::ResizeNwSe => system(CursorIcon::ResizeNwSe), - Cursor::ResizeNeSw => system(CursorIcon::ResizeNeSw), + Cursor::ResizeH => tool("cursor-resize-h", CENTER, None), + Cursor::ResizeV => tool("cursor-resize-v", CENTER, None), + Cursor::ResizeNwSe => tool("cursor-resize-nwse", CENTER, None), + Cursor::ResizeNeSw => tool("cursor-resize-nesw", CENTER, None), Cursor::ShearH => PaintedCursor::skew(Vec2::new(1.0, 0.0)).into(), Cursor::ShearV => PaintedCursor::skew(Vec2::new(0.0, -1.0)).into(), Cursor::Rotate => turn_toward(0), @@ -112,16 +121,18 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::PenConvert => tool("cursor-pen-convert", TIP, None), Cursor::Curvature => tool("cursor-pen-curvature", TIP, None), Cursor::AnchorPoint => tool("cursor-anchor-point", CARET, None), - Cursor::Text => system(CursorIcon::Text), - Cursor::TypeVertical | Cursor::TypeAreaVertical | Cursor::TypeOnPathVertical => system(CursorIcon::VerticalText), + Cursor::Text => PaintedCursor::IBeam.into(), + Cursor::TypeVertical | Cursor::TypeAreaVertical | Cursor::TypeOnPathVertical => tool("cursor-type-vertical", CENTER, None), Cursor::TypeArea => PaintedCursor::type_on(false).into(), Cursor::TypeOnPath => PaintedCursor::type_on(true).into(), Cursor::Hand => PaintedCursor::Hand.into(), - Cursor::HandGrab => system(CursorIcon::Grabbing), + // The framework draws the hand closed while the primary button is down. + Cursor::HandGrab => PaintedCursor::Hand.into(), Cursor::ZoomIn => PaintedCursor::zoom(false).into(), Cursor::ZoomOut => PaintedCursor::zoom(true).into(), Cursor::Eyedropper => tool("pipette", PIPETTE_TIP, None), - Cursor::NotAllowed => system(CursorIcon::NotAllowed), + Cursor::NotAllowed => tool("cursor-not-allowed", CENTER, None), + // The window-wide wait pointer of a long operation, not a canvas tool's cursor. Cursor::Busy => system(CursorIcon::Progress), Cursor::AddStop => badged(CursorBadge::Add), Cursor::RemoveStop => badged(CursorBadge::Subtract), diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index a0554f26bb..c83bd7fd1c 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -35,6 +35,42 @@ fn every_tool_cursors_hotspot_is_on_its_glyph() { assert!(missed.is_empty(), "hotspots off their glyphs: {missed:?}"); } +/// One tool switches between these looks as the pointer moves (the Curvature pen over an anchor, the +/// Selection arrow over a corner handle, the Hand while it pans, a tool that has nothing to act on, the +/// type tools). The app draws all of them at its own cursor size, so none comes from the desktop's +/// cursor theme at another size; only the window-wide wait pointer of a long operation does. +#[test] +fn a_tools_move_resize_grab_and_not_allowed_cursors_are_drawn_like_its_own() { + use craft::ui::primitives::{painted_image, register_app_icons}; + use craft::ui::runtime::env::Env; + crate::icons::register(); + register_app_icons(&CURSOR_ICONS); + let pairs = [ + (Cursor::Curvature, Cursor::Move), + (Cursor::Arrow, Cursor::ResizeNwSe), + (Cursor::Arrow, Cursor::ResizeH), + (Cursor::Hand, Cursor::HandGrab), + (Cursor::Smooth, Cursor::NotAllowed), + (Cursor::TypeArea, Cursor::Text), + (Cursor::TypeArea, Cursor::TypeVertical), + ]; + crate::testing::ui_context() + .run_ui(Default::default(), |ui| { + let env = Env::of(ui); + for (own, other) in pairs { + for c in [own, other] { + let cb::Cursor::Painted(painted) = tool_cursor(c) else { panic!("{c:?} beside {own:?} comes from the desktop's cursor theme") }; + let (one, two) = (painted_image(&env, &painted, 1.0), painted_image(&env, &painted, 2.0)); + let (Some(one), Some(two)) = (one, two) else { panic!("{c:?} has no image") }; + assert!(two.size[0] > one.size[0] && two.size[1] > one.size[1], "{c:?} grows with the cursor scale"); + } + } + }) + .textures_delta + .clear(); + assert!(matches!(tool_cursor(Cursor::Busy), cb::Cursor::System(_)), "the wait pointer stays the system's"); +} + /// A `cursor-` icon name a cursor uses must be in the set the host registers. #[test] fn every_cursor_icon_the_app_names_is_in_its_set() { From 4e463a7621ede00834e83c007e1510c04881ebf3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 02:24:07 -0800 Subject: [PATCH 36/42] Type: new art from a redefined style is unlinked, default look keeps type plain A graphic style picked with nothing selected and then redefined gave new art and type the look picked with the new definition's isolate and knockout, still linked to the style. New art now links to the style only while its fills, strokes, effects, opacity and blend mode match the style's current definition; otherwise it keeps the look picked without the link, isolate or knockout. appearance.newArt reports the style the same way, and undoing the redefinition links new art again. New type made with the look paint.default gives in a document whose Default Graphic Style was redefined took that look and lost its characters' color, which failed an_open_document_takes_another_profiles_default_fill_stroke_and_font. That look is the document's default, so new type made with it keeps its characters' color, as with the shipped default. --- crates/engine/src/cmd/newart.rs | 37 +++++++++++++++++++++++-------- crates/engine/src/tests/newart.rs | 35 +++++++++++++++++++++++++++++ docs/mcp.md | 6 +++-- 3 files changed, 67 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index 2dfaf626f6..b3b1a95afa 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -273,6 +273,12 @@ fn unplace_all(mut ap: Appearance) -> Appearance { ap } +/// The fills, strokes and effects new art takes from graphic style `g`, placed gradients relative +/// to the unit box. +fn style_look(g: &GraphicStyle) -> Appearance { + if g.unit_box { g.appearance.clone() } else { unplace_all(g.appearance.clone()) } +} + /// How a new object looks ([`Session::new_art_look`]): its appearance and transparency and the /// graphic style it is linked to. pub(crate) struct NewArt { @@ -294,20 +300,29 @@ impl NewArt { /// Give new object `n` (in `d`) this look: its placed gradients land relative to its bounds, and /// it links to the style, taking its isolate and knockout too (type keeps its own transparency - /// unless the look is a graphic style's). + /// unless the look is a graphic style's). A look that no longer matches the style's definition + /// (the style was redefined after it was picked) is given unlinked ([`NewArt::linked_style`]). pub(crate) fn apply(&self, d: &mut vectorcraft_doc::Document, n: &mut Node) { self.place(n); if matches!(n.kind, NodeKind::Text(_)) && !self.styled { return; } (n.opacity, n.blend) = (self.opacity, self.blend); - let style = self.style.as_deref().and_then(|name| d.graphic_style_index(name)); + let style = self.linked_style(d); if let Some(g) = style.and_then(|i| d.graphic_styles.get(i)) { (n.isolate, n.knockout) = (g.isolate, g.knockout); } n.extras_mut().graphic_style = style.map(|i| d.graphic_style_id(i)); } + /// The index in `d` of the graphic style this look links to: its style, while the style's + /// fills, strokes, effects, opacity and blend mode are still the ones this look has. + pub(crate) fn linked_style(&self, d: &Document) -> Option { + let i = d.graphic_style_index(self.style.as_deref()?)?; + let g = d.graphic_styles.get(i)?; + ((g.opacity, g.blend) == (self.opacity, self.blend) && style_look(g).approx_eq(&self.appearance)).then_some(i) + } + /// Give `n` this look's appearance, its placed gradients relative to `n`'s bounds now. pub(crate) fn place(&self, n: &mut Node) { n.appearance = self.appearance.clone().into(); @@ -353,13 +368,16 @@ impl Session { /// The look of new type (`text.create`): the template's fills, strokes and effects when it is /// more than one plain fill and stroke or comes from a graphic style (of this document or - /// another), else none of its own, so the characters' fill and stroke show. The template is - /// not repainted with the fill and stroke proxies. + /// another), else none of its own, so the characters' fill and stroke show. The document's own + /// default look (its redefined Default Graphic Style, which [`reset`] gives new art) leaves type + /// plain as the shipped default does. The template is not repainted with the fill and stroke + /// proxies. pub(crate) fn new_type_look(&self) -> NewArt { let plain = || NewArt::plain(Appearance::default()); let Some(t) = self.template() else { return plain() }; let styled = self.new_art_styled(); - if t.is_basic() && !styled { + let default_look = || self.active().and_then(|st| redefined_default_style(&st.doc)).is_some_and(|g| style_look(g).approx_eq(&t)); + if !styled && (t.is_basic() || default_look()) { return plain(); } let (opacity, blend, style) = self.new_art_transparency(); @@ -422,7 +440,7 @@ impl Session { /// A graphic style clicked with nothing selected: new art takes it (`add`: its fills, strokes /// and effects on top of the template's, unlinked). pub(crate) fn new_art_style(&mut self, g: &GraphicStyle, add: bool) { - let ap = if g.unit_box { g.appearance.clone() } else { unplace_all(g.appearance.clone()) }; + let ap = style_look(g); if add { let t = self.new_art_template_mut(); t.items.extend(ap.items); @@ -568,7 +586,9 @@ fn set_basic(s: &mut Session, p: &Value) -> Result { } fn describe(s: &mut Session, _: &Value) -> Result { - let (opacity, blend, style) = s.new_art_transparency(); + let (opacity, blend, _) = s.new_art_transparency(); + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let style = s.doc().ok().and_then(|st| look.linked_style(&st.doc)).and_then(|i| s.doc().ok()?.doc.graphic_styles.get(i)).map(|g| g.name.clone()); Ok(json!({ "basic": s.prefs.new_art_basic, "appearance": s.new_art(), @@ -586,8 +606,7 @@ pub(crate) fn reset(s: &mut Session) { s.paint = PaintDefaults::default(); let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned(); if let Some(g) = style { - let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) }; - s.take_new_art(ap, 1.0, BlendMode::Normal, None, false); + s.take_new_art(style_look(&g), 1.0, BlendMode::Normal, None, false); } } diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index f7ef210fd0..7f69ea2b99 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -665,3 +665,38 @@ fn new_type_in_another_document_takes_a_basic_styles_look_and_transparency() { assert_eq!((n.opacity, n.blend), (0.5, BlendMode::Multiply), "the style's transparency"); assert_eq!(n.extras().graphic_style, None, "no link to a style of another document"); } + +#[test] +fn new_art_and_type_from_a_style_redefined_after_it_was_picked_keep_the_picked_look_unlinked() { + let mut s = session(); + fancy(&mut s); + run(&mut s, "graphicStyle.new", json!({"name": "Picked"})); + let other = painted(&mut s, 120.0, "#00ff00", "#000000", 3.0); + run(&mut s, "transparency.set", json!({"knockout": "on", "isolate": true})); + run(&mut s, "select.none", json!({})); + run(&mut s, "graphicStyle.apply", json!({"name": "Picked"})); + let picked = s.new_art(); + let redefine = |s: &mut Session| run(s, "graphicStyle.redefine", json!({"name": "Picked", "id": other.0})); + let linked = |s: &mut Session| run(s, "appearance.newArt", json!({}))["graphicStyle"].clone(); + let make = + [("shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 30})), ("text.create", json!({"x": 200, "y": 200, "text": "k"}))]; + redefine(&mut s); + assert_eq!(linked(&mut s), Value::Null); + // Undone, the style has the picked look again, and new art links to it. + run(&mut s, "edit.undo", json!({})); + assert_eq!(linked(&mut s), json!("Picked")); + for (cmd, p) in &make { + run(&mut s, "select.none", json!({})); + run(&mut s, cmd, p.clone()); + assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Picked".to_string(), true)), "{cmd}"); + } + redefine(&mut s); + assert_eq!(linked(&mut s), Value::Null); + for (cmd, p) in &make { + run(&mut s, "select.none", json!({})); + let id = NodeId(run(&mut s, cmd, p.clone())["id"].as_u64().unwrap()); + let n = node(&s, id); + assert_eq!((n.extras().graphic_style, n.isolate, n.opacity), (None, false, 0.5), "{cmd}: the picked transparency, unlinked"); + assert_eq!((n.appearance.effects.len(), n.appearance.fill_paint()), (1, picked.fill_paint()), "{cmd}: the picked look"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 2bc1631657..4fb9b9d513 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11570,12 +11570,14 @@ whole appearance of the last selected object. `appearance.newArt` reports what t resets it. New type (`text.create`) takes the template's fills, strokes and effects when the template is more than one plain fill and stroke or comes from a graphic style; otherwise it has no fills or strokes of its own and its characters keep their -color. With Override Character Color on, its characters lose the fill and stroke the template paints, as when a +color. The look `paint.default` gives in a document whose Default Graphic Style was redefined is the document's default, +and new type made with it keeps its characters' color too. With Override Character Color on, its characters lose the fill and stroke the template paints, as when a graphic style is applied to type; a `color` given to `text.create` keeps the characters' fill. Type made with a graphic style's look takes the style's opacity and blend mode and is linked to it; otherwise the type keeps its own opacity and blend mode. New art and type are linked to the style only in the document the style was picked in, or the selection it was taken from was in; in another document they take the look, with the style's opacity and blend mode, without -the link. When text wrap moves new area type as it is made (an Auto Size frame below a wrap object grows), the +the link. A style redefined after it was picked gives new art and type the look picked, without the link, its isolate +or its knockout. When text wrap moves new area type as it is made (an Auto Size frame below a wrap object grows), the template's placed gradients fit the frame the type ends with. Area type made with `text.create` and `area` takes the template too; Type on a Path and area type made with `text.createInPath` keep the default appearance. `appearance.setNewArtBasic` rejects an `on` value that is not a boolean. Omitting `on` toggles the current preference. From 3ecd0708724343c23f454fd4a8be790490c03e10 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 02:28:43 -0800 Subject: [PATCH 37/42] Part of #10798: the font list's style rows preview their style on the text Hovering a style row of an expanded family in the font list previewed only the family on the selected type. apply_preview now takes the style the picker reports with its preview (FontPickerOutput::preview_style and CharacterControlsOutput::preview_style) and passes it to the font command, so the type shows the hovered style; a family row still previews the family in the closest style it has. Every craft-libs rev moves to storytold/craft-libs#5489's head (4f3e34d0dd), which adds preview_style, gives style rows a sample in their own face, and keeps a typed query when a family's disclosure, its star or a filter is clicked. Cargo.lock changes only the craft-libs source lines. --- Cargo.lock | 182 ++++++++++++------------- Cargo.toml | 82 +++++------ apps/vectorcraft-web/Cargo.toml | 2 +- crates/ui-egui/src/font_menu.rs | 9 +- crates/ui-egui/src/font_menu/tests.rs | 8 +- crates/ui-egui/src/panels/character.rs | 4 +- crates/ui-egui/src/tests/font_menu.rs | 32 ++++- crates/ui-egui/src/tests/nativemenu.rs | 2 +- xtask/src/pdf_deps.rs | 2 +- 9 files changed, 171 insertions(+), 152 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b878d75456..af882877fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1256,7 +1256,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-automation", "craft-behavior", @@ -1298,7 +1298,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "crc32fast", "flate2", @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1331,7 +1331,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "rustix 1.1.6", ] @@ -1339,7 +1339,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1383,7 +1383,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-docpath", @@ -1401,7 +1401,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "crc32fast", "flate2", @@ -1410,7 +1410,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "egui", ] @@ -1418,7 +1418,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "md-5", "rayon", @@ -1427,12 +1427,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-cms", @@ -1452,7 +1452,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-ai-agents", "craft-atomic", @@ -1468,7 +1468,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1478,7 +1478,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "rayon", ] @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1512,7 +1512,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "blake3", "craft-ecproj-format", @@ -1528,7 +1528,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "serde", ] @@ -1536,7 +1536,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-dwg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "acadrust", "craft-dxf", @@ -1565,7 +1565,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-codepage", "encoding_rs", @@ -1577,7 +1577,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "serde", "serde_json", @@ -1587,12 +1587,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-atomic", "dirs", @@ -1602,7 +1602,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1617,7 +1617,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1636,7 +1636,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1645,7 +1645,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "cap-primitives", "craft-atomic", @@ -1668,12 +1668,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "gif", ] @@ -1681,7 +1681,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "flate2", ] @@ -1689,7 +1689,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1702,7 +1702,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1732,7 +1732,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-dds", "craft-jpeg", @@ -1759,7 +1759,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1777,7 +1777,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "thiserror 2.0.21", ] @@ -1785,7 +1785,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1796,7 +1796,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-host", "craft-i18n", @@ -1811,7 +1811,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-i18n", @@ -1825,7 +1825,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-host", @@ -1843,7 +1843,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1855,7 +1855,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "encoding_rs", "image", @@ -1866,7 +1866,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "chrono", "craft-codepage", @@ -1876,7 +1876,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "uds_windows", "winsafe", @@ -1885,7 +1885,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-keymap", @@ -1901,7 +1901,7 @@ dependencies = [ [[package]] name = "craft-pbr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-texture", "thiserror 2.0.21", @@ -1910,7 +1910,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "flate2", "serde", @@ -1921,7 +1921,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1933,7 +1933,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "async-channel", "async-io", @@ -1966,7 +1966,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1975,7 +1975,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-host", @@ -1999,7 +1999,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -2010,7 +2010,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-eps", "flate2", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "encoding_rs", "flate2", @@ -2035,7 +2035,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "dispatch2", "egui", @@ -2048,7 +2048,7 @@ dependencies = [ [[package]] name = "craft-raster3d" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2076,7 +2076,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-atomic", "craft-host", @@ -2093,7 +2093,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "fax", "hayro-ccitt", @@ -2104,7 +2104,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2125,7 +2125,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-keymap", @@ -2137,7 +2137,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2162,7 +2162,7 @@ dependencies = [ [[package]] name = "craft-texture" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "thiserror 2.0.21", ] @@ -2170,7 +2170,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2185,7 +2185,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-atomic", "craft-behavior", @@ -2200,7 +2200,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "serde", "thiserror 2.0.21", @@ -2210,7 +2210,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "serde", "thiserror 2.0.21", @@ -2219,7 +2219,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-keymap", @@ -2234,12 +2234,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2253,7 +2253,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2270,7 +2270,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "accesskit", "craft-behavior", @@ -2308,7 +2308,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2319,7 +2319,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-host", @@ -2337,7 +2337,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-host", @@ -2358,7 +2358,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-host", @@ -2379,7 +2379,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-behavior", "craft-host", @@ -2398,7 +2398,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "base64 0.22.1", "chrono", @@ -2430,7 +2430,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "flate2", "serde", @@ -2441,7 +2441,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2451,7 +2451,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "js-sys", "serde_json", @@ -2462,7 +2462,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "winsafe", ] @@ -2470,7 +2470,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "craft-appkit", "craft-atomic", @@ -2502,7 +2502,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3862,7 +3862,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3871,7 +3871,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3889,7 +3889,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3907,12 +3907,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "flate2", "hayro-ccitt", @@ -4895,7 +4895,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "base64 0.22.1", "bumpalo", @@ -5052,7 +5052,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index a48e3c1330..73e26d5375 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,57 +10,57 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified). -craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with. -craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps. -craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -200,13 +200,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" } # skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa). # It stays at this rev until craft-libs#5222 merges. skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 4db9a1dac2..62605759eb 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 21c19bdd03..47cd2ebbae 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -190,7 +190,7 @@ pub(crate) fn font_fields(app: &mut VectorcraftApp, ui: &mut Ui) { let sample = sample_text(app); let out = show_picker(app, ui, tl!("Font Family"), &s.font_family, sample.as_deref()); // The preview ends before the pick that ends it is applied. - apply_preview(app, out.edit.response.id, out.preview); + apply_preview(app, out.edit.response.id, out.preview, out.preview_style.as_deref()); let style = out.picked_style; let mut applied = false; for event in out.edit.events { @@ -227,8 +227,9 @@ pub(crate) fn apply_family(app: &mut VectorcraftApp, event: EditEvent, s } /// Shows or ends the live preview of the row under the pointer or the keyboard on the selected text, in -/// one interaction that leaves nothing in the history. `owner` is the picker that shows it. -pub(crate) fn apply_preview(app: &mut VectorcraftApp, owner: egui::Id, preview: Preview) { +/// one interaction that leaves nothing in the history. `owner` is the picker that shows it; `style` is the +/// style of a style row, and without one the family takes the closest style it has. +pub(crate) fn apply_preview(app: &mut VectorcraftApp, owner: egui::Id, preview: Preview, style: Option<&str>) { match preview { Preview::Shows(family) => { if app.font_preview_owner.is_none() { @@ -239,7 +240,7 @@ pub(crate) fn apply_preview(app: &mut VectorcraftApp, owner: egui::Id, preview: } } app.font_preview_owner = Some(owner); - let (cmd, params) = font_command(app, &family, None); + let (cmd, params) = font_command(app, &family, style); if let Err(e) = app.session.preview(cmd, ¶ms) { app.ui.status = e.to_string(); } diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 13b7bdf715..4083c56e4e 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -157,10 +157,10 @@ fn a_preview_keeps_the_document_filters_families() { let mut app = app_with_type(&["Source Serif 4", "Inter"]); assert_eq!(used(&mut app), ["inter", "source serif 4"]); // The selected text, the only type in Inter, previewed in Source Serif 4. - super::apply_preview(&mut app, owner, Preview::Shows("Source Serif 4".into())); + super::apply_preview(&mut app, owner, Preview::Shows("Source Serif 4".into()), None); assert!(app.session.active().unwrap().interaction.is_some(), "the preview is open"); assert_eq!(used(&mut app), ["inter", "source serif 4"], "the preview leaves the set as it was"); - super::apply_preview(&mut app, owner, Preview::Shows("Inter".into())); + super::apply_preview(&mut app, owner, Preview::Shows("Inter".into()), None); assert_eq!(used(&mut app), ["inter", "source serif 4"], "previewing back changes nothing"); super::apply_family(&mut app, set("Inter", "Source Serif 4"), None); assert_eq!(used(&mut app), ["source serif 4"], "the pick is an edit: Inter is no longer used"); @@ -281,7 +281,7 @@ fn a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview() { vectorcraft_doc::NodeKind::Text(t) => t.first_style().font_family, _ => String::new(), }; - super::apply_preview(&mut app, owner, Preview::Shows("Source Serif 4".into())); + super::apply_preview(&mut app, owner, Preview::Shows("Source Serif 4".into()), None); assert_eq!(font(&app), "Source Serif 4"); assert!(!app.take_prefs_changed(), "nothing to write yet"); let undo_depth = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); @@ -299,7 +299,7 @@ fn a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview() { assert_eq!(app.ui.engine_prefs["fontPreviewSize"], "large"); assert!(app.session.in_interaction(), "the preview is still open"); assert_eq!(font(&app), "Source Serif 4", "the preview stays on the type"); - super::apply_preview(&mut app, owner, Preview::Ended); + super::apply_preview(&mut app, owner, Preview::Ended, None); assert_eq!(font(&app), "Inter"); app.run("edit.undo", serde_json::json!({})).unwrap(); assert!( diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 88e3999e88..32e46a3c52 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -1253,9 +1253,9 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow } let out = controls.show(ui); hold.store(app, &before); - let CharacterControlsOutput { picker, preview_family, edits, .. } = out; + let CharacterControlsOutput { picker, preview_family, preview_style, edits, .. } = out; if let Some(owner) = picker { - font_menu::apply_preview(app, owner, preview_family); + font_menu::apply_preview(app, owner, preview_family, preview_style.as_deref()); } for event in edits { apply_character_event(app, event); diff --git a/crates/ui-egui/src/tests/font_menu.rs b/crates/ui-egui/src/tests/font_menu.rs index 2045e85976..87124f1cb0 100644 --- a/crates/ui-egui/src/tests/font_menu.rs +++ b/crates/ui-egui/src/tests/font_menu.rs @@ -30,9 +30,9 @@ fn recent_fonts_follow_committed_choices_and_the_count_preference() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({})).unwrap(); let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "Recent fonts", "font": "Inter"})).unwrap()["id"].clone(); - apply_preview(&mut app, owner(), Preview::Shows("Source Serif 4".into())); + apply_preview(&mut app, owner(), Preview::Shows("Source Serif 4".into()), None); assert!(app.recent_fonts().is_empty()); - apply_preview(&mut app, owner(), Preview::Ended); + apply_preview(&mut app, owner(), Preview::Ended, None); assert!(app.recent_fonts().is_empty()); apply_family(&mut app, set("Inter", "Source Serif 4"), None); app.run("text.setStyle", json!({"font": "Inter"})).unwrap(); @@ -161,24 +161,42 @@ fn preview_changes_the_text_live_and_only_a_choice_is_a_step() { let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); assert_eq!(sample_text(&app).as_deref(), Some("Gagaku")); let before = steps(&app); - apply_preview(&mut app, owner(), Preview::Shows("Source Serif 4".into())); + apply_preview(&mut app, owner(), Preview::Shows("Source Serif 4".into()), None); assert_eq!(font_of(&app, id), "Source Serif 4", "previewed on the text"); assert_eq!( crate::panels::character::values(&mut app).family.as_deref(), Some("Inter"), "the picker must still be able to commit the previewed row" ); - apply_preview(&mut app, owner(), Preview::Shows("Source Sans 3".into())); + apply_preview(&mut app, owner(), Preview::Shows("Source Sans 3".into()), None); assert_eq!(font_of(&app, id), "Source Sans 3"); - apply_preview(&mut app, owner(), Preview::Ended); + apply_preview(&mut app, owner(), Preview::Ended, None); assert_eq!((font_of(&app, id), steps(&app)), ("Inter".to_string(), before), "the preview leaves nothing behind"); - apply_preview(&mut app, owner(), Preview::Shows("Source Serif 4".into())); + apply_preview(&mut app, owner(), Preview::Shows("Source Serif 4".into()), None); apply_family(&mut app, set("Inter", "Source Serif 4"), None); assert_eq!((font_of(&app, id), steps(&app)), ("Source Serif 4".to_string(), before + 1), "one step"); app.run("edit.undo", json!({})).unwrap(); assert_eq!(font_of(&app, id), "Inter"); } +/// #10798: a style row under the pointer previews the type in that style; the family row after it previews the family +/// in its own style, and the end of the preview puts the type back. +#[test] +fn a_style_row_previews_its_style_on_the_text() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = selected_inter(&mut app); + let styles = FontDb::global().styles("Inter"); + let style = styles.iter().find(|s| *s != "Regular").unwrap_or_else(|| panic!("Inter has a style besides Regular: {styles:?}")); + apply_preview(&mut app, owner(), Preview::Shows("Inter".into()), Some(style)); + let s = first_style(&app, id); + assert_eq!((s.font_family.as_str(), s.font_style.as_str()), ("Inter", style.as_str()), "the hovered style shows on the text"); + apply_preview(&mut app, owner(), Preview::Shows("Inter".into()), None); + assert_eq!(first_style(&app, id).font_style, "Regular", "the family row shows the type's own style"); + apply_preview(&mut app, owner(), Preview::Shows("Inter".into()), Some(style)); + apply_preview(&mut app, owner(), Preview::Ended, None); + assert_eq!(first_style(&app, id).font_style, "Regular", "the preview leaves nothing behind"); +} + /// A preview whose picker isn't shown any more (the text was deselected, the panel closed) is undone. #[test] fn a_preview_left_open_by_a_menu_that_is_gone_is_undone() { @@ -187,7 +205,7 @@ fn a_preview_left_open_by_a_menu_that_is_gone_is_undone() { let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "Gagaku", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); let steps = app.session.active().unwrap().history.undo.len(); - apply_preview(&mut app, owner(), Preview::Shows("Source Serif 4".into())); + apply_preview(&mut app, owner(), Preview::Shows("Source Serif 4".into()), None); assert!(app.session.in_interaction()); let previewer = app.font_preview_owner.expect("the app records who previews"); end_previews(&mut app, &[previewer]); diff --git a/crates/ui-egui/src/tests/nativemenu.rs b/crates/ui-egui/src/tests/nativemenu.rs index 41b5264479..c80cf770ed 100644 --- a/crates/ui-egui/src/tests/nativemenu.rs +++ b/crates/ui-egui/src/tests/nativemenu.rs @@ -420,7 +420,7 @@ fn the_font_menu_preview_reads_the_menus_when_it_ends() { m.app.run("select.none", json!({})).unwrap(); m.app.run("text.create", json!({"x": 50, "y": 50, "text": "Hi"})).unwrap(); m.frame(vec![]); - let shows = |font: &'static str| move |app: &mut VectorcraftApp| apply_preview(app, owner, Preview::Shows(font.into())); + let shows = |font: &'static str| move |app: &mut VectorcraftApp| apply_preview(app, owner, Preview::Shows(font.into()), None); assert_eq!(read(m, &shows("Source Serif 4")), 1, "the menus were read as the preview began"); let between = read(m, &shows("Source Sans 3")) + read(m, &shows("Inter")); let ended = read(m, &|app| end_previews(app, &[owner])); diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 04cf313ca0..6e4766a8af 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8"; +const REV: &str = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 641b0145e42f366d0d8427e37ac1a1d3fb44342b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 03:16:41 -0800 Subject: [PATCH 38/42] PDF import: text outlined for a second glyph of a character says so A line of type in a font the file carries is kept as outlines when it uses a different glyph for a character than the rest of the file does in that font, because the font kept with the document holds one glyph per character. That line got the warning for scripts whose letters join, so a Latin document reported Indic-style reshaping. It now gets its own warning, which is also one of the warnings on outlines that a layered .ai drops when no outlines are left. Type kept as outlines because it would reshape keeps the old warning. --- crates/pdf/src/import.rs | 4 ++-- crates/pdf/src/import/builder.rs | 14 ++++++++++---- crates/pdf/src/import/entry.rs | 10 +++++++++- crates/pdf/src/lib.rs | 4 ++-- crates/pdf/src/tests/file_fonts.rs | 10 ++++++++++ 5 files changed, 33 insertions(+), 9 deletions(-) diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index 29417779df..4eedb1355f 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -42,8 +42,8 @@ pub(crate) use cid::replacement; #[cfg(test)] pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical}; pub use entry::{ - INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, - holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, + CONFLICTING_GLYPHS_NOTE, INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, + UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, }; #[cfg(test)] pub(crate) use entry::{TEST_MAX_OBJECTS, import_with_reader_options, read}; diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 64da7fb8d5..da34368d7d 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -1,7 +1,7 @@ use super::cid::{CidText, FontInfo, comparable, font_chars, identify_glyph, matching_face, replacement, unify_radical}; use super::entry::{ - MAX_NESTED, OVERPRINT_UNREAD, OVERPRINT_ZERO_MODE, PATTERN_REUSE, RESHAPED_TEXT_NOTE, TEXT_OUTLINES, TOO_MANY_OBJECTS, UNMATCHED_GLYPHS_NOTE, - UNNAMED_CHARACTERS_NOTE, max_objects, + CONFLICTING_GLYPHS_NOTE, MAX_NESTED, OVERPRINT_UNREAD, OVERPRINT_ZERO_MODE, PATTERN_REUSE, RESHAPED_TEXT_NOTE, TEXT_OUTLINES, TOO_MANY_OBJECTS, + UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, max_objects, }; use super::reshaped; use super::state::{ @@ -801,7 +801,13 @@ impl<'p> Builder<'p> { // A line with a glyph the file's font can't keep (another glyph for the same character) // is kept as outlines too, so each glyph draws as the file does. let conflict = line_conflict && !glyphs.is_empty() && !line_type3; - if conflict || (checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink)) { + // The warning names why: the glyph conflict, else type that reshapes as it is set. + let note = if conflict { + Some(CONFLICTING_GLYPHS_NOTE) + } else { + (checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink)).then_some(RESHAPED_TEXT_NOTE) + }; + if let Some(note) = note { outlined = true; if self.mask.is_some() { self.flush_glyphs(); @@ -834,7 +840,7 @@ impl<'p> Builder<'p> { self.flush_masked(); } } - self.warn(RESHAPED_TEXT_NOTE); + self.warn(note); } else { let mut n = Node::new(self.id(), NodeKind::Text(Box::new(t))); n.opacity = opacity; diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index fbc9e1aef5..b36072488a 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -180,16 +180,24 @@ pub const UNMATCHED_GLYPHS_NOTE: &str = "text whose glyphs differ from the insta pub const RESHAPED_TEXT_NOTE: &str = "text that would not look as it does in the file if set as type (a script whose letters join) was kept as outlines"; +/// Warning: type in a font the file carries that draws a character with a different glyph than +/// the rest of the file does in that font (an alternate letter) was kept as outlines: the font kept +/// with the document has one glyph per character ([`crate::import_fonts`]). +pub const CONFLICTING_GLYPHS_NOTE: &str = + "text that uses a different glyph for a character than the rest of its font (such as an alternate letter) was kept as outlines"; + /// The end of the warning that glyphs whose characters the file doesn't name were kept as /// outlines, after "text in" and the font's name. pub const UNNAMED_CHARACTERS_NOTE: &str = "whose characters the file doesn't name (U+FFFD) was kept as outlines"; /// Is `note` one of the warnings that glyphs were kept as outlines ([`OUTLINED_TEXT_NOTE`], -/// [`UNMATCHED_GLYPHS_NOTE`], [`RESHAPED_TEXT_NOTE`], [`UNNAMED_CHARACTERS_NOTE`])? +/// [`UNMATCHED_GLYPHS_NOTE`], [`RESHAPED_TEXT_NOTE`], [`CONFLICTING_GLYPHS_NOTE`], +/// [`UNNAMED_CHARACTERS_NOTE`])? pub fn is_outlines_note(note: &str) -> bool { note == OUTLINED_TEXT_NOTE || note == UNMATCHED_GLYPHS_NOTE || note == RESHAPED_TEXT_NOTE + || note == CONFLICTING_GLYPHS_NOTE || note.starts_with("text in ") && note.ends_with(UNNAMED_CHARACTERS_NOTE) } diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index a7118fd37a..3f244112ab 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -79,8 +79,8 @@ pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_w pub use export::{check_page_sizes, export, export_with_report, page_areas}; pub use file_info::{FileInfo, MAX_TEMPLATE_BYTES, file_info, metadata_template, read_template}; pub use import::{ - INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, - holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, + CONFLICTING_GLYPHS_NOTE, INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, + UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, }; #[cfg(any(test, feature = "read-count"))] pub use import::{form_content_of, function_evaluations_of, imports_of}; diff --git a/crates/pdf/src/tests/file_fonts.rs b/crates/pdf/src/tests/file_fonts.rs index b27dac4f0d..ab4a88f541 100644 --- a/crates/pdf/src/tests/file_fonts.rs +++ b/crates/pdf/src/tests/file_fonts.rs @@ -275,6 +275,16 @@ fn two_glyphs_for_one_character_both_survive_import() { close(&glyph_ink(db, &imported), "imported"); } +/// The line kept as outlines for its other glyph of `a` is Latin type: the warning names the glyph +/// conflict, not a script whose letters join, and is one of the warnings on outlines (which a `.ai` +/// read from its layers drops when no outlines are left). +#[test] +fn a_line_kept_as_outlines_for_another_glyph_names_the_glyph_conflict() { + let warnings = import(&two_glyphs_pdf()).warnings; + assert!(warnings.iter().any(|w| w == CONFLICTING_GLYPHS_NOTE && is_outlines_note(w)), "{warnings:?}"); + assert!(warnings.iter().all(|w| !is_outlines_note(w) || w == CONFLICTING_GLYPHS_NOTE), "{warnings:?}"); +} + /// The license flags (OS/2 `fsType`) of the font a PDF carries go with the font the document keeps: /// a restricted font (0x0002) still draws its type, and a PDF saved from the document draws that /// type as outlines with the license warning instead of embedding the font again. From a1a77ebf84fd490387da137d61f1d029fcdc5dc5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 03:24:56 -0800 Subject: [PATCH 39/42] Recolor Artwork: the canvas stays undimmed while the dialog and a row's Color Picker are open Recolor Artwork previews its colors on the art, but its modal layer dimmed the whole window, canvas included, so the preview could not be judged. The dialog now keeps the canvas of the window it opened in open under its modal layer, as the Color Picker and the color adjustment dialogs do: no scrim over it, and the wheel still scrolls and zooms the view. Other presses on the canvas stay blocked. A Color Picker opened from a row's new color also keeps the canvas undimmed. The picker now registers the canvas, and while it is open over Recolor Artwork the dialog below draws no scrim of its own, so the picker's layer is the only one that dims the window. While the Color Theme Picker is on, its clicks and Shift-drags on the art now reach the canvas. Before, the modal layer blocked them, so a click on the art added no pick. Part of #10590. --- crates/ui-egui/src/dialogs/color_picker.rs | 7 +- crates/ui-egui/src/dialogs/recolor.rs | 32 +++++- crates/ui-egui/src/dialogs/recolor/fixture.rs | 108 ++++++++++++++++++ docs/mcp.md | 5 + 4 files changed, 146 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 938237f5fc..9d6c1af6fc 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -424,12 +424,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let row_swatch = super::recolor::row_swatch_of(&dialogs, parent, &key) .and_then(|(name, lib, to)| view_place(app, &view, &name, &lib, &to)) .filter(|p| picked_row_swatch(app, &view, *p).flatten().is_some()); - let child = ColorPickerDialog::from_request(request) + let mut child = ColorPickerDialog::from_request(request) .eyedropper(true) .add_to_swatches(false) .gamut(gamut(app)) .working_rgb(WorkingRgb) .swatch_view(swatches); + // As for the picker opened on its own, the canvas stays undimmed, so the parent's live preview shows the true + // color; presses on it stay blocked. + if let Some(canvas) = crate::doc_windows::current(app).map(crate::canvas::canvas_id) { + child = child.canvas(canvas).canvas_samples(false); + } let row = super::recolor::row_identity(&dialogs, parent, &key); let id = dialogs.with(|h| h.open_child(child, parent)); // Over Recolor Artwork, the swatches view shows the library that Limit to Library limits to. diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index f270e3227d..f471af1c08 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -132,7 +132,8 @@ use craft::ui::buttons::{IconButton, ToggleButton}; use craft::ui::choice::{Checkbox, Swatch}; use craft::ui::contract::overlay::Anchor; use craft::ui::contract::{ - Bind, CollectionEvent, ColumnSpec, EditResponse, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Trigger, + Bind, CanvasGesture, CollectionEvent, ColumnSpec, EditResponse, Entry, Props as _, Sampler as _, SelectMode, Show as _, ShowCollection as _, + ShowContainer as _, Trigger, }; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id}; use craft::ui::display::{Shade, Text}; @@ -143,7 +144,7 @@ use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::{FormDialog, ResetFooter, ResetPick}; use craft::ui::pickers::Select; use craft::ui::runtime::env::Label; -use craft::ui::runtime::overlay::CloseReason; +use craft::ui::runtime::overlay::{Backdrop, CloseReason}; use craft::ui::runtime::requests::ColorRequest; use craft::ui::sections::{FooterAction, FooterBar}; use craft::ui::table::Table; @@ -1999,11 +2000,15 @@ pub(crate) struct RecolorDialog { picked_row: Option, /// The Color Theme Picker's canvas tool, which the canvas runs while the picker is on. theme_tool: edit_tab::ThemePickTool, + /// The canvas of the window the dialog opened in, which its modal layer leaves undimmed so the preview shows + /// the true colors. + canvas: Option, } impl RecolorDialog { fn new(app: &VectorcraftApp, fields: Fields) -> Self { RecolorDialog { + canvas: crate::doc_windows::current(app).map(crate::canvas::canvas_id), id: dialog_id(KIND), opening: Arc::new(()), feed: Feed::of(app, &fields), @@ -2071,7 +2076,8 @@ impl RecolorDialog { Ok(()) } - fn shown(&mut self, ui: &mut Ui) -> Option> { + /// `covered`: a dialog opened from this one (a row's Color Picker) is open over it. + fn shown(&mut self, ui: &mut Ui, covered: bool) -> Option> { let measuring = craft::ui::runtime::measure::active(ui.ctx()); let finish = self.held.is_accepted(); // The refusal of OK shows until a value changes. @@ -2084,17 +2090,32 @@ impl RecolorDialog { let art = self.fields.bool("__art"); let mut preview = self.fields.bool("preview"); let footer = ResetFooter::new(ui, None, true); + let canvas = self.canvas.filter(|_| !covered); + let theme_pick = self.fields.bool(THEME_PICKER); let RecolorDialog { fields, feed, filed, ends, row_menu, .. } = self; let mut form = FormDialog::new(tl!(TITLE), Bind::bound(fields)).accept_stays_open(true).ok_enabled(!waiting); if art { form = form.preview(Some(Bind::bound(&mut preview))); } + // The dialog opened over this one dims the window around the canvas; a scrim of this one under it would dim + // the canvas again. + if covered { + form = form.shaped(|dialog| dialog.backdrop(Backdrop::None)); + } let mut running = false; let out = form.show(ui, |ui, cx, d| { // A measuring run closes nothing: the real run of the same pass makes the close. if finish && !measuring { cx.request_close_as(CloseReason::Activated); } + // The canvas stays undimmed under the modal layer, and the wheel and a middle drag still scroll it. + if let Some(canvas) = canvas { + cx.keep_view_open(canvas); + // The Color Theme Picker's clicks and Shift-drags on the art reach its canvas tool. + if theme_pick { + cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY); + } + } let ctx = ui.ctx().clone(); let ((), gesture) = craft::ui::runtime::edit::watch_gestures(&ctx, || body(ui, d, feed, filed, ends, row_menu, can)); if !measuring { @@ -2136,8 +2157,9 @@ impl StackDialog for RecolorDialog { Some(KIND) } - fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { - self.shown(ui) + fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option> { + let covered = stack.has_child(self.id); + self.shown(ui, covered) } /// OK as its button gives it: the fields are filed for the app, which answers none until it has diff --git a/crates/ui-egui/src/dialogs/recolor/fixture.rs b/crates/ui-egui/src/dialogs/recolor/fixture.rs index 47e0f722d6..394336039c 100644 --- a/crates/ui-egui/src/dialogs/recolor/fixture.rs +++ b/crates/ui-egui/src/dialogs/recolor/fixture.rs @@ -59,6 +59,114 @@ fn preserve_grays_can_be_clicked_in_a_narrow_localized_dialog() { } } +/// The whole app in a window with Recolor Artwork open over a red square, and a frame driver. +fn open_over_app() -> (VectorcraftApp, impl FnMut(&mut VectorcraftApp, Vec) -> egui::FullOutput) { + use egui::{RawInput, vec2}; + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0)); + let mut time = 0.0; + let mut draw = move |app: &mut VectorcraftApp, events| { + time += 0.25; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }) + }; + draw(&mut app, vec![]); + app.run("ui.recolorDialog", json!({})).unwrap(); + for _ in 0..8 { + draw(&mut app, vec![]); + } + (app, draw) +} + +/// The rects of the modal scrim that the frame `out` painted over the canvas of `app`, at a point of the canvas that +/// no dialog covers. The frame must also paint the scrim somewhere, so the search can find it. +fn scrims_over_canvas(app: &VectorcraftApp, out: &egui::FullOutput) -> usize { + use craft::ui::runtime::env::Env; + use craft::ui::style::rgba_color; + let mut scrim = egui::Color32::TRANSPARENT; + let mut theme = crate::testing::ui_context().run_ui(Default::default(), |ui| scrim = rgba_color(Env::of(ui).tokens.tokens().color.surface.scrim)); + theme.textures_delta.clear(); + let at = app.canvas_view().expect("a canvas").rect.left_top() + egui::vec2(20.0, 20.0); + let nodes = out.platform_output.accesskit_update.as_ref().map(|u| u.nodes.clone()).unwrap_or_default(); + for bounds in nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Dialog).filter_map(|(_, n)| n.bounds()) { + let covers = (bounds.x0..=bounds.x1).contains(&f64::from(at.x)) && (bounds.y0..=bounds.y1).contains(&f64::from(at.y)); + assert!(!covers, "the probe {at:?} lies on the canvas outside every dialog, not in {bounds:?}"); + } + let shapes = crate::tests_labels::flat_painted_shapes(&out.shapes); + let scrims: Vec = shapes + .iter() + .filter_map(|shape| if let egui::Shape::Rect(rect) = shape { Some(rect) } else { None }) + .filter(|rect| rect.fill.a() > 0 && rect.fill.to_opaque() == scrim.to_opaque()) + .map(|rect| rect.rect) + .collect(); + assert!(!scrims.is_empty(), "the modal layer still dims the window around the canvas"); + scrims.iter().filter(|rect| rect.contains(at)).count() +} + +/// Recolor Artwork previews its colors on the art, so its modal layer leaves the canvas undimmed (#10590). +#[test] +fn recolor_artwork_leaves_the_canvas_undimmed() { + let (mut app, mut draw) = open_over_app(); + assert!(app.dialogs().unwrap().with(|host| host.is_open::()), "Recolor Artwork is open"); + let out = draw(&mut app, vec![]); + assert_eq!(scrims_over_canvas(&app, &out), 0, "no scrim over the canvas while Recolor Artwork previews"); + // A click on the canvas stays blocked: it does not reach the tool and clear the selection. + let at = app.canvas_view().unwrap().rect.left_top() + egui::vec2(20.0, 20.0); + let selected = app.session.doc().unwrap().selection.clone(); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + draw(&mut app, vec![Event::PointerMoved(at), press(true)]); + draw(&mut app, vec![press(false)]); + draw(&mut app, vec![]); + assert_eq!(app.session.doc().unwrap().selection, selected, "the click under the dialog leaves the selection"); +} + +/// With the Color Theme Picker on, a click on the art reaches the picker's canvas tool through the dialog's modal +/// layer and becomes a pick. +#[test] +fn a_theme_picker_click_on_the_canvas_is_a_pick() { + let (mut app, mut draw) = open_over_app(); + app.dialogs().unwrap().with(|host| host.get_mut::().map(|d| d.fields.fields.insert(super::THEME_PICKER.into(), json!(true)))); + for _ in 0..3 { + draw(&mut app, vec![]); + } + let at = app.canvas_view().unwrap().to_screen(craft::behavior::kurbo::Point::new(20.0, 20.0)); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + draw(&mut app, vec![Event::PointerMoved(at)]); + draw(&mut app, vec![press(true)]); + draw(&mut app, vec![press(false)]); + for _ in 0..3 { + draw(&mut app, vec![]); + } + let picks = app.dialogs().unwrap().with(|host| host.get::().and_then(|d| d.fields.fields.get(super::THEME_PICKS).cloned())); + let picks = picks.and_then(|p| p.as_array().cloned()).unwrap_or_default(); + assert_eq!(picks.len(), 1, "the click is one pick: {picks:?}"); + let at: Vec = picks[0]["at"].as_array().into_iter().flatten().filter_map(Value::as_f64).collect(); + assert!(at.len() == 2 && (at[0] - 20.0).abs() < 0.5 && (at[1] - 20.0).abs() < 0.5, "at the point clicked: {at:?}"); +} + +/// A Color Picker opened from a row of Recolor Artwork leaves the canvas undimmed too: neither its own scrim nor the +/// one of the dialog below it covers the canvas (#10590). +#[test] +fn a_row_color_picker_leaves_the_canvas_undimmed() { + use craft::color_ui::ui::ColorPickerDialog; + use craft::ui::runtime::requests::ColorRequest; + let (mut app, mut draw) = open_over_app(); + let red = crate::panels::srgba(&vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.get_mut::().map(|d| d.color_request = Some(ColorRequest::new("0", red)))); + for _ in 0..8 { + draw(&mut app, vec![]); + } + assert!(dialogs.with(|host| host.get::().is_some()), "the row's Color Picker is open"); + assert!(dialogs.with(|host| host.is_open::()), "over Recolor Artwork"); + let out = draw(&mut app, vec![]); + assert_eq!(scrims_over_canvas(&app, &out), 0, "no scrim over the canvas while the row's picker is open"); +} + /// Recolor Artwork over an app, in a window-sized fixture. pub(crate) struct Recolor { fixture: Fixture, diff --git a/docs/mcp.md b/docs/mcp.md index 718c5c367c..7c8195963f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8020,6 +8020,11 @@ become the `weights` field, which moves the rows' current colors and previews th beside the link button runs `swatch.newGroup` right away, as its own undo step: Save All Colors saves the new colors of the rows that are not excluded, hold current colors or were added on the Edit tab, and still have one, in row order, and Save Prominent Colors saves the bar's colors in the bar's order. +While the Recolor Artwork dialog is open, the canvas of the window it opened in is not dimmed, so the preview shows the +art's true colors; the wheel scrolls and zooms the view. While the Color Theme Picker is on, its clicks and +Shift-drags on the art reach the canvas; other presses on the canvas stay blocked. A Color Picker opened from a row +leaves the canvas undimmed too. + The Recolor Artwork dialog lists the document's color groups on its right, or under the tabs in a window too narrow for both ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The Show Color Groups button beside the tabs shows or hides the list (the `groupStorage` field, true when the dialog From 664d50c328ffaa9e960e3841fe3ea269f21237d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 03:47:38 -0800 Subject: [PATCH 40/42] Type: a selected look matching the redefined default still styles new type With New Art Has Basic Appearance off, new type took nothing from a selected object whose fills, strokes and effects matched the document's redefined Default Graphic Style without a link to it (after Break Link to Graphic Style, for example), because the check that keeps type plain for the document's default look also caught a look taken from the selection. That check now applies only to the look paint.default gives, so new type takes the selection's fills and effects, and new type made after paint.default still keeps its characters' color. --- crates/engine/src/cmd/newart.rs | 7 ++++--- crates/engine/src/tests/newart.rs | 20 ++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index b3b1a95afa..54eb05b312 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -370,13 +370,14 @@ impl Session { /// more than one plain fill and stroke or comes from a graphic style (of this document or /// another), else none of its own, so the characters' fill and stroke show. The document's own /// default look (its redefined Default Graphic Style, which [`reset`] gives new art) leaves type - /// plain as the shipped default does. The template is not repainted with the fill and stroke - /// proxies. + /// plain as the shipped default does; the same look taken from the selection does not. The + /// template is not repainted with the fill and stroke proxies. pub(crate) fn new_type_look(&self) -> NewArt { let plain = || NewArt::plain(Appearance::default()); let Some(t) = self.template() else { return plain() }; let styled = self.new_art_styled(); - let default_look = || self.active().and_then(|st| redefined_default_style(&st.doc)).is_some_and(|g| style_look(g).approx_eq(&t)); + let default_look = + || !self.paint.inherited && self.active().and_then(|st| redefined_default_style(&st.doc)).is_some_and(|g| style_look(g).approx_eq(&t)); if !styled && (t.is_basic() || default_look()) { return plain(); } diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index 7f69ea2b99..3d9bd36473 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -700,3 +700,23 @@ fn new_art_and_type_from_a_style_redefined_after_it_was_picked_keep_the_picked_l assert_eq!((n.appearance.effects.len(), n.appearance.fill_paint()), (1, picked.fill_paint()), "{cmd}: the picked look"); } } + +#[test] +fn new_type_takes_a_selected_look_that_matches_the_redefined_default_style() { + let mut s = session(); + let src = fancy(&mut s); + run(&mut s, "graphicStyle.redefine", json!({"name": "Default Graphic Style", "id": src.0})); + run(&mut s, "graphicStyle.breakLink", json!({"ids": [src.0]})); + run(&mut s, "appearance.setNewArtBasic", json!({"on": false})); + run(&mut s, "select.set", json!({"ids": [src.0]})); + run(&mut s, "select.none", json!({})); + let n = new_type(&mut s, json!({"x": 200, "y": 200, "text": "in"})); + assert_eq!(n.appearance.items.iter().filter(|i| i.is_fill()).count(), 2, "both fills from the selection"); + assert_eq!(n.appearance.effects.len(), 1, "the drop shadow from the selection"); + // The same look from paint.default is the document's default, so new type stays plain. + run(&mut s, "select.none", json!({})); + run(&mut s, "paint.default", json!({})); + let d = new_type(&mut s, json!({"x": 200, "y": 260, "text": "df"})); + assert!(d.appearance.items.is_empty() && d.appearance.effects.is_empty(), "plain type"); + assert_ne!(char_fill(&d), Paint::None); +} diff --git a/docs/mcp.md b/docs/mcp.md index 4fb9b9d513..3598d401dc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11571,7 +11571,8 @@ resets it. New type (`text.create`) takes the template's fills, strokes and effects when the template is more than one plain fill and stroke or comes from a graphic style; otherwise it has no fills or strokes of its own and its characters keep their color. The look `paint.default` gives in a document whose Default Graphic Style was redefined is the document's default, -and new type made with it keeps its characters' color too. With Override Character Color on, its characters lose the fill and stroke the template paints, as when a +and new type made with it keeps its characters' color too. The same look taken from a selection (New Art Has Basic +Appearance off) gives new type its fills, strokes and effects. With Override Character Color on, its characters lose the fill and stroke the template paints, as when a graphic style is applied to type; a `color` given to `text.create` keeps the characters' fill. Type made with a graphic style's look takes the style's opacity and blend mode and is linked to it; otherwise the type keeps its own opacity and blend mode. New art and type are linked to the style only in the document the style was picked in, or the selection From 0286c7e775e41fcf4bb9d1467801f3b393e977f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 04:26:57 -0800 Subject: [PATCH 41/42] Status bar: drag frames no longer rebuild the artboard navigator The status bar's Rotation menu and artboard navigator were memoized on the document's revision, which rises on every frame of a drag, so the memo missed and both controls were laid out again each frame. The memo now keys on what the navigator lists: the artboards' names in order, with the selected artboard, view angle and language as before. Edits that leave the names alone replay the controls; a rename or a new artboard runs them. The new test moves an object ten times and counts no navigation runs, then renames an artboard and checks the navigator shows the new name. --- crates/ui-egui/src/chrome/status_bar.rs | 41 ++++++++++++++++++++----- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index e4a9e91d82..1593562503 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -39,8 +39,6 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { // An angle between the presets, from the Rotate View tool or `view.rotate`, shows in whole degrees; adding 0.0 // turns the -0 of a small negative angle into 0. let degrees = rotation.round() + 0.0; - let revision = st.map(|d| (d.uid, d.revision)); - let artboards = st.map_or(&[][..], |d| d.doc.artboards.as_slice()); let mut picks = Vec::new(); let shows: Vec> = StatusBarShow::ALL.into_iter().map(|s| Entry::new(s, s.label()).checked(app.ui.status_bar_show == s)).collect(); @@ -95,7 +93,8 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let zoom = ZoomControls { zoom: canvas_zoom, document, scaling, print, shown_zoom, has_view: view.is_some(), lang, picked: Outbox::new(&mut picks) }; let _ = MemoView::new("status-bar-zoom", zoom, show_zoom).show(ui); - let navigation = Navigation { has_view: view.is_some(), turned, degrees, cur, revision, artboards, lang, picked: Outbox::new(&mut picks) }; + let artboards = st.map_or_else(Vec::new, |d| d.doc.artboards.iter().map(|a| a.name.as_str()).collect()); + let navigation = Navigation { has_view: view.is_some(), turned, degrees, cur, artboards, lang, picked: Outbox::new(&mut picks) }; let _ = MemoView::new("status-bar-navigation", navigation, show_navigation).show(ui); Divider::vertical().show(ui); // An empty readout shows a dash. @@ -237,10 +236,9 @@ struct Navigation<'a> { degrees: f64, /// The artboard the navigator shows. cur: usize, - /// The active document's uid and revision. - revision: Option<(u64, u64)>, - #[memo_props(covered_by = "revision", reason = "a document's uid and revision change with every edit of it")] - artboards: &'a [vectorcraft_doc::Artboard], + /// The names of the active document's artboards, in order, which the navigator lists. Edits that leave them + /// alone, such as the frames of a drag, replay the controls. + artboards: Vec<&'a str>, #[memo_props(hash = "an interface language: an index into the languages offered")] lang: crate::i18n::Lang, /// What the controls chose in the pass. @@ -291,7 +289,7 @@ fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) { p.picked.send(NavigationPick::Artboard(json!(to))); } } - let boards: Vec> = p.artboards.iter().enumerate().map(|(i, a)| Entry::new(i, format!("{} {}", i + 1, a.name))).collect(); + let boards: Vec> = p.artboards.iter().enumerate().map(|(i, name)| Entry::new(i, format!("{} {}", i + 1, name))).collect(); let mut go = None; Field::new(tl!("Artboard")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { // With no document the navigator shows a dash, as the info readout does. @@ -433,6 +431,33 @@ mod tests { assert!(panel.enabled("Next Artboard") || panel.enabled("Previous Artboard"), "the navigator counts the new artboard"); } + /// Edits that leave the artboards' names alone, such as the steps of a drag, replay the Rotation menu and the + /// artboard navigator; renaming an artboard runs them, and the navigator shows the new name. + #[test] + fn edits_that_keep_the_artboard_names_replay_the_navigation_controls() { + let runs = || NAVIGATION_RUNS.with(std::cell::Cell::get); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let mut panel = Panel::new(app, status_bar); + panel.room(egui::vec2(1200.0, 300.0)); + panel.frame(); + panel.frame(); + let (before, revision) = (runs(), panel.app().session.active().unwrap().revision); + for _ in 0..10 { + panel.app().run("object.move", json!({"dx": 1, "dy": 0})).unwrap(); + panel.frame(); + } + assert!(panel.app().session.active().unwrap().revision > revision, "each move is an edit of the document"); + assert_eq!(runs(), before, "moves do not run the navigation controls"); + panel.app().run("artboard.rename", json!({"indices": [0], "name": "Front"})).unwrap(); + panel.frame(); + panel.frame(); + assert!(runs() > before, "a rename runs them again"); + assert_eq!(panel.value("Artboard").as_deref(), Some("1 Front"), "and the navigator shows the new name"); + } + /// Scrolling the view moves its center and nothing the navigation controls show, so frames of a wheel pan replay /// them; a new zoom runs only the Zoom field and its presets, not the Rotation menu and the artboard navigator. #[test] From 70273996ecbc8aa46ef4742f6a7db7fd86752606 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 04:51:23 -0800 Subject: [PATCH 42/42] Docs: Revolve on a group draws shaded faces for a see-through member A painted member whose own opacity, or the opacity of a nested group holding it, is below 100% makes Revolve draw the shaded faces instead of one image. --- docs/three-d.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/three-d.md b/docs/three-d.md index a255a853da..ca4ab76973 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -80,7 +80,8 @@ pages describe it. 16,777,216 pixels takes fewer; past that limit at one sample a pixel, or when the solid can't be placed in one image, the effect draws its shaded faces. The image keeps transparency where no surface is, or is white with `background: white`. The image shows opaque solid colors only: a solid painted with a gradient or a pattern, one - with graphics, a paint with an opacity below 100% or in a blending mode other than Normal, and a group member whose opacity mask or blending mode + with graphics, a paint with an opacity below 100% or in a blending mode other than Normal, a painted group member + whose own opacity or the opacity of a nested group holding it is below 100%, and a group member whose opacity mask or blending mode applies to its solid draw the shaded faces, as does a later geometry effect that reshapes paths but leaves images unchanged. Revolve on a group draws every member's surface in one image, and Revolve on a fill or stroke draws an image of that fill's or stroke's surface under the effects after it. The mode