From 546d274e6eff61daba8934eadf884557fb3284e7 Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 07:18:04 +0000 Subject: [PATCH 01/91] .ai import: type takes the installed copy that sets its PDF part's widths When several installed faces answer to a text document font record's PostScript name and the record keeps no version (no key 5), type was set in whichever copy loaded first. Two copies can share the PostScript name, family and style and differ only in their widths (two releases of one font): the type then set at other widths than the file's own page, and envelopes of it could fail their drawn-art check. #6983 left this case out, as only the page's widths tell such copies apart. - `Opened::page_widths` (crates/pdf/src/page_widths.rs) reads the widths the pages give the characters of each font they set type in, from the font dictionaries alone and without importing any page: a simple font's `Widths` from `FirstChar`, a composite font's descendant's `W` under an `Identity-H`/`Identity-V` CMap, each code's character from the font's `ToUnicode` map or, for a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding (ISO 32000-1 9.6.2, 9.7.4.3, 9.10.3, Annex D.2), by `BaseFont` without its subset tag. Zero widths (codes a subset doesn't use) are left out; subsets that give a character two widths give none. - Its cost is bounded by the file: each resource dictionary is walked once, however many pages and forms share it, within 65,536 entries for the whole file, 256 fonts and 4,096 forms; a width array that fonts share by reference is read once, and none past 4 MB of them; a `ToUnicode` map is parsed once for all the fonts that name it, and one over 256 KB decoded, or past 4 MB of maps in all (each charged at most what could be decoded of it), is left unread. `cid_ranges` reads a `W` list's values as it takes them instead of collecting the whole list. A font's widths are shared, not copied. - `postscript_face` (crates/eps/src/import/text.rs) takes, among the faces of the record's name, the first that sets those characters (the first 512 in code-point order) each within 1/1000 em. With no widths, one face, a version in the record, or no face that sets them all, the pick is the one before. The face found first is checked before any other is loaded, and the records of one name and version share their widths and their answer, so each font resolves once whatever the number of records. - The widths reach the text document through `Structure::page_widths` and `Texts::with_page_widths`; the engine reads them once per open and passes them to `ai_layers_alone`, `AiLayers::with_page_widths` and `ai_alone_with` when it reads a `.ai`'s editing copy beside a PDF part (not for a placeholder page). - `without_subset_tag` replaces two copies of the subset-tag strip in the PDF import, and `replacement` (a `ToUnicode` value that names no character) is shared with it. - A fuzz target feeds hostile font dictionaries, `ToUnicode` maps and forms that draw themselves to the reader. Measured on 224 users' files (used locally, never committed): 3 font records in 3 files change copy, each now within 0.5/1000 em of its page; those 3 renders, and no others, change, all closer to the file's own page; envelopes of type that open live go from 185 to 186, none fewer in any file; no file opens another way. Refs #6983 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/fileio/load.rs | 24 +- .../engine/src/cmd/fileio/tests_aiimport.rs | 107 ++++ crates/engine/tests/import_fuzz.rs | 55 +- crates/eps/src/ai_editing/writer/texts.rs | 4 +- crates/eps/src/import/ai/legacy_text.rs | 2 +- crates/eps/src/import/ai/read.rs | 4 + crates/eps/src/import/ai/read/document.rs | 1 + crates/eps/src/import/ate.rs | 68 +- crates/eps/src/import/native/build.rs | 25 +- crates/eps/src/import/native/layers.rs | 69 +- crates/eps/src/import/tests_native.rs | 117 +++- crates/eps/src/import/text.rs | 69 +- crates/pdf/src/import.rs | 1 + crates/pdf/src/import/builder.rs | 6 +- crates/pdf/src/import/cid.rs | 2 +- crates/pdf/src/import_scan.rs | 28 +- crates/pdf/src/import_text.rs | 6 +- crates/pdf/src/lib.rs | 2 + crates/pdf/src/page_widths.rs | 598 ++++++++++++++++++ crates/pdf/src/pages.rs | 7 + docs/file-format-parity.md | 5 +- docs/target-app-parity.md | 3 +- 22 files changed, 1111 insertions(+), 92 deletions(-) create mode 100644 crates/pdf/src/page_widths.rs diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index ff0e14c40d..1e8cfdbe7d 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -255,12 +255,15 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) return None; } let private = opened.illustrator_data()?; - Some(editing_copy_alone(&private, opts)) + // A placeholder page's fonts aren't the art's. + Some(editing_copy_alone(&private, opts, Default::default())) } -/// [`from_editing_data_alone`] of `private`, the editor's copy already read. -fn editing_copy_alone(private: &[u8], opts: &LoadOptions) -> Result<(Document, Vec)> { - vectorcraft_eps::ai_alone_with(private, opts.legacy_names) +/// [`from_editing_data_alone`] of `private`, the editor's copy already read, with `widths`, the +/// widths the file's PDF part gives the characters of its fonts, which tell installed copies of a +/// font apart ([`vectorcraft_eps::AiLayers::with_page_widths`]). +fn editing_copy_alone(private: &[u8], opts: &LoadOptions, widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec)> { + vectorcraft_eps::ai_alone_with(private, opts.legacy_names, widths) .map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})"))) } @@ -444,6 +447,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result Err(e) => Err(err(e)), }; let mut read = restore_or_import(editing, || { + // The widths the PDF part gives the characters of its fonts, which tell installed + // copies of a font apart: read once, when the editing copy is. + let page_widths = std::cell::OnceCell::new(); + let widths = || page_widths.get_or_init(|| opened.as_ref().map(vectorcraft_pdf::Opened::page_widths).unwrap_or_default()).clone(); // Type all from the text document and nothing that needs the PDF part: the layers // alone, the PDF part not imported. Else what was read of the layers is kept for // reading them with the PDF part. @@ -451,7 +458,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?))) { let pages = o.trim_pages(); - match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit, opts.legacy_names) { + match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit, opts.legacy_names, widths()) { Ok((mut doc, warnings)) => { doc.setup.bleed = pages.bleed; editing_data = true; @@ -473,9 +480,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result // decoded draws nothing either): its notes are at most the page's own. let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w)); let copy_alone = || match &private { - Some(private) => Some(editing_copy_alone(private, opts)), + Some(private) => Some(editing_copy_alone(private, opts, widths())), None if layers.is_some() => { - opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts)) + opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts, widths())) } None => None, }; @@ -487,7 +494,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result let (doc, warnings, read) = match alone { Some((doc, warnings)) => (doc, warnings, true), None => { - let layers = layers.or_else(|| private.as_deref().map(vectorcraft_eps::AiLayers::decode)); + let layers = + layers.or_else(|| private.as_deref().map(|p| vectorcraft_eps::AiLayers::decode(p).with_page_widths(widths()))); through_editing_data(layers, opts, r.document, r.warnings, r.user_unit) } }; diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 9d263c8c97..0274232b91 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -2072,3 +2072,110 @@ fn an_illustrator_ai_file_opens_with_its_layers_closed() { assert_eq!(r["restored"], json!(true), "{r}"); assert_eq!(open_rows(&s).1, ["Art", "Hidden"]); } + +/// A `.ai` whose layer `Art` holds one line of type, `Hamburg`, that its text document sets in the +/// font of PostScript name `name` (a font record without a version), and whose PDF part sets it in +/// a subset of that font that gives each character the width `width` gives it, in thousandths of an +/// em. With `square`, the layer and the page have a gray square too. The editing copy's artboard is +/// 200 × 100 pt, and the page `page_width` × 100. +fn type_in_copy_ai(name: &str, square: bool, page_width: f64, width: impl Fn(char) -> f64) -> Vec { + let story = "Hamburg"; + let n = story.chars().count() + 1; + let document = format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 ({name}) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\ + /1 << /1 [ << /0 << /0 ({story}\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 {n} >> ] >> \ + /6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /0 0 /1 10.0 >> >> >> /1 {n} >> ] >> >> \ + /1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8105.5 8176.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \ + << /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 {n} >> >> ] >> ] >> ] >> ] >> ] >> ] >> >> ] /2 << /1 12.0 >> >>\n" + ); + let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n"; + let (art, drawn) = + if square { (format!("0.5 g\n{}f\n{text}", ai::rect(120.0, 20.0, 160.0, 60.0)), "0.5 g 120 20 40 40 re f ") } else { (text.to_string(), "") }; + let body = format!( + "%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", + ai::layer("Art", &art), + lines.join("\n") + ); + let data = ai::editing_data(200.0, 100.0, &body); + let widths: Vec = (32u8..=126).map(char::from).map(|c| if story.contains(c) { width(c).to_string() } else { "0".into() }).collect(); + let page = PdfPage { + resources: format!( + "/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>", + widths.join(" ") + ), + entries: format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(1)), + // A page that is only type, with its art box, isn't a placeholder. + art: Some([0.0, 0.0, page_width, 100.0]), + ..PdfPage::new(page_width, 100.0, &format!("{drawn}BT /F1 10 Tf 14 65 Td ({story}) Tj ET")) + }; + pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len())], None) +} + +/// Type from the text document of a `.ai` whose font record keeps no version, where two installed +/// copies of the font share its PostScript name, family and style and differ in their widths, is +/// set in the copy that sets its characters at the widths the file's PDF part gives them: whether +/// its layers open alone, with the PDF part imported, or from the editing copy alone because the PDF +/// part is only type (read after the layers alone, on a page of another size, were not used). +#[test] +fn type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in() { + let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewtest Ink", "PagewtestInk-Regular")); + let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }; + // (a square beside the type, the page's width, the options, whether the PDF part is imported) + let cases = [ + (true, 200.0, &LoadOptions::default(), false), + (true, 200.0, &trim, true), + (false, 200.0, &LoadOptions::default(), false), + (false, 200.0, &trim, true), + (false, 260.0, &LoadOptions::default(), true), + ]; + for (square, page_width, opts, imported) in cases { + let file = type_in_copy_ai("PagewtestInk-Regular", square, page_width, &width); + let before = vectorcraft_pdf::imports_of(&file); + let loaded = load_with("copies.ai", &file, opts).unwrap(); + let case = format!("square {square}, page {page_width}, {:?}: {:?}", opts.crop, loaded.warnings); + assert!(loaded.editing_data, "{case}"); + assert_eq!(vectorcraft_pdf::imports_of(&file) > before, imported, "{case}"); + let art = loaded.doc.layers[0].children().unwrap(); + assert_eq!(art.len(), 1 + usize::from(square), "{case}"); + let Some(NodeKind::Text(t)) = art.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(_))) else { panic!("type: {case}") }; + assert_eq!(t.plain_text(), "Hamburg"); + assert_eq!(db.style_face(&t.runs[0].style).unwrap().version, "1.1", "{case}"); + } +} + +/// Installs two copies of family `family` and PostScript name `name`: Inter as version 1.0, loaded +/// first, and Source Sans 3 as 1.1, whose advances (thousandths of an em) the returned function gives. +fn install_width_copies(family: &str, name: &str) -> impl Fn(char) -> f64 + use<> { + let db = vectorcraft_text::FontDb::global(); + for (inter, version) in [(true, "1.0"), (false, "1.1")] { + let font = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", version, name)).unwrap(); + assert_eq!(db.add_font(font), 1); + } + let newer = db.postscript_faces(name).into_iter().find(|f| f.version == "1.1").unwrap(); + move |c: char| newer.advance(newer.glyph_for(c)) * 1000.0 / newer.units_per_em() +} + +/// Type the PDF part's widths set in the second copy of its font is saved as `.ai` with that +/// copy's version in its font record, so it opens in the same copy again, from the editing copy +/// alone as from the whole file. +#[test] +fn type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save() { + let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewrt Ink", "PagewrtInk-Regular")); + let mut s = Session::new(); + let r = open(&mut s, "copies.ai", &type_in_copy_ai("PagewrtInk-Regular", true, 200.0, &width), json!({})).unwrap(); + let saved = s.execute("file.saveCopy", &json!({"format": "ai"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let versions = |doc: &vectorcraft_doc::Document| -> Vec { + let art = doc.layers[0].children().unwrap(); + art.iter() + .filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(db.style_face(&t.runs[0].style).unwrap().version.clone()) } else { None }) + .collect() + }; + assert_eq!(versions(&s.doc().unwrap().doc), ["1.1"], "{r}"); + let loaded = load_with("saved.ai", &bytes, &LoadOptions { native: false, ..Default::default() }).unwrap(); + assert!(loaded.editing_data, "{:?}", loaded.warnings); + assert_eq!(versions(&loaded.doc), ["1.1"], "{:?}", loaded.warnings); + let private = vectorcraft_pdf::illustrator_data(&bytes, None).unwrap(); + assert_eq!(versions(&vectorcraft_eps::ai_alone(&private).unwrap().0), ["1.1"]); +} diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 058476d071..dd124c59ed 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -6,7 +6,8 @@ //! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files, //! opcodes with random contents) opened or placed, nor EPS and PostScript files //! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of -//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents +//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a +//! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents //! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor the //! font files a folder search reads (damaged fonts, collections whose headers give any count of //! faces), nor scripts written for the reference app checked without running them (garbage, @@ -896,6 +897,58 @@ proptest! { } } +/// A font dictionary whose widths are hostile, for [`vectorcraft_pdf::Opened::page_widths`]: any +/// subtype, encoding and first code, widths that are huge, negative or not numbers, a composite +/// font's `W` of any shape, and the `ToUnicode` map of object 5. +fn arb_width_font() -> impl Strategy { + ( + prop::sample::select(vec!["/TrueType", "/Type1", "/Type0", "/Type3", "/MMType1", "7"]), + prop::sample::select(vec!["/WinAnsiEncoding", "/Identity-H", "/Identity-V", "/MacRomanEncoding", "<< /Differences [65 /A] >>", "null"]), + prop::sample::select(vec!["0", "65", "-5", "255", "256", "4294967295", "1e30", "/X"]), + prop::collection::vec(prop::sample::select(vec!["500", "0", "-1", "1e40", "NaN", "null", "[1 2]", "/W"]), 0..12), + prop::collection::vec(prop::sample::select(vec!["1", "[500 600]", "65", "4294967295", "300", "-1", "[]", "1e9", "0 65535 7"]), 0..10), + prop::sample::select(vec!["/ABCDEF+Fuzz", "/Fuzz", "/ABCDEF+", "/+", "()", "/Fuzz-Identity-H"]), + any::(), + ) + .prop_map(|(subtype, encoding, first, widths, w, name, mapped)| { + let map = if mapped { "/ToUnicode 5 0 R" } else { "" }; + format!( + "<< /Type /Font /Subtype {subtype} /BaseFont {name} /Encoding {encoding} /FirstChar {first} /Widths [{}] {map} \ + /DescendantFonts [<< /Subtype /CIDFontType2 /BaseFont {name} /W [{}] >>] >>", + widths.join(" "), + w.join(" ") + ) + }) +} + +proptest! { + #![proptest_config(config())] + + /// The widths a page's fonts give their characters (read for a `.ai`'s text document) are read + /// without a panic from hostile font dictionaries, `ToUnicode` maps of any text, and forms that + /// draw themselves. + #[test] + fn pdf_font_widths_never_panic( + fonts in prop::collection::vec(arb_width_font(), 1..4), + cmap in prop::collection::vec(prop::sample::select(vec![ + "begincmap", "1 begincodespacerange", "<0000> ", "<00> ", "endcodespacerange", "2 beginbfchar", "<0001> <0041>", + "<0002> ", "<41> ", "1 beginbfrange", "<0000> <0000>", " <0000> <0041>", "<0001> <0003> [<0041> <0042>]", + "endbfrange", "endbfchar", "endcmap", "/Identity-H usecmap", "99999999999 beginbfchar", + ]), 0..12), + ) { + let list: Vec = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect(); + let map = cmap.join("\n"); + let form = format!( + "<< /Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /Font << /F0 {} >> /XObject << /X0 6 0 R >> >> /Length 0 >>\nstream\n\nendstream", + fonts[0] + ); + let more = [format!("<< /Length {} >>\nstream\n{map}\nendstream", map.len() + 1).into_bytes(), form.into_bytes()]; + let pdf = handmade_pdf_with("", &format!("<< /Font << {} >> /XObject << /X0 6 0 R >> >>", list.join(" ")), "[0 0 100 100]", &more); + let read = catch_quiet(|| vectorcraft_pdf::open_pdf(&pdf, None).ok().map(|o| o.page_widths())); + prop_assert!(read.is_ok(), "{fonts:?} {cmap:?}: {read:?}"); + } +} + /// A dictionary value: one the reader reads, or one it skips over but can't parse (a name with a /// broken `#` escape, a number with a stray `-`). fn arb_dict_value() -> impl Strategy { diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 506d13d9fc..d7a85dee26 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -612,7 +612,7 @@ fn font_name(st: &CharStyle) -> FontRecord { .collect(); let name = face.postscript_name(); // The reader takes the face of a name alone as `postscript_face` finds it. - let by_name = crate::import::postscript_face(&name, None).is_some_and(|f| f.id() == face.id()); + let by_name = crate::import::postscript_face(&name, None, None).is_some_and(|f| f.id() == face.id()); let version = if design.is_empty() && by_name { String::new() } else { face.version.clone() }; FontRecord { name, truetype: face.is_truetype(), design, version } } @@ -659,7 +659,7 @@ fn fixed(v: f32) -> i64 { fn font_kept(st: &CharStyle) -> bool { let record = font_name(st); let version = crate::import::record_version(&record.version); - let (family, style, read) = crate::import::document_font(&record.name, version); + let (family, style, read) = crate::import::document_font(&record.name, version, None); let db = vectorcraft_text::FontDb::global(); let face = |family: &str, style: &str, version: Option<&str>| db.face_version(family, style, version).map(|f| f.id()); family == st.font_family diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index a3864b43d0..e35f61cb54 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -564,7 +564,7 @@ impl Reader<'_> { st.cmap = cmap; // The installed face of that PostScript name, as type from a text document // takes it; else the name split into a family and style. - let text = super::super::super::text::named_font(name, None); + let text = super::super::super::text::named_font(name, None, None); let (family, style, version) = text.unwrap_or_else(|| { let (family, style) = super::super::super::text::family_style(name); (family, style, None) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index b045dd128f..7433243a10 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -217,6 +217,10 @@ pub struct Structure { /// name of the art style that gives each: the styles that are one paint, a pattern this read /// (see `ate::Texts::with_patterns`). pub text_patterns: HashMap, + /// The widths a `.ai`'s PDF part gives the characters of its fonts, which tell installed copies + /// of a font apart for type whose font record keeps no version (see + /// `ate::Texts::with_page_widths`): none until the importer sets them. + pub page_widths: vectorcraft_pdf::PageWidths, /// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not. pub canvas_scale: f64, /// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 258d7d584b..06e2de112e 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1395,6 +1395,7 @@ impl<'a> Reader<'a> { }, styles_read, text_patterns, + page_widths: Default::default(), canvas_scale: self.canvas_scale, symbols_own_size: self.symbols_own_size, xml_ids: self.xml_ids, diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index c971b250f2..9cb3273803 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -23,6 +23,7 @@ //! a layout has its point type's anchor at its frame's point. See [`Story::place`]. use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen}; use vectorcraft_color::{Color, Paint}; @@ -564,15 +565,20 @@ struct DocFont { /// Key 5, when the record keeps it: the font's version string (name ID 5), which tells installed /// copies of one font apart. version: Option, - /// [`Self::font`]'s answer, found once for every run that names the record. - font: std::sync::OnceLock, + /// The widths the file's page gives the font's characters, when it has them + /// ([`Texts::with_page_widths`]): without a version, they tell the copies apart. Every record + /// of the font shares them. + widths: Option>, + /// [`Self::font`]'s answer, found once for every run that names the record, and shared by the + /// records of the same name and version, which give the same answer. + font: Arc>, } impl DocFont { /// The font type set in this record's font takes: the installed copy it names /// ([`super::text::document_font`]). fn font(&self) -> &Font { - self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref())) + self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref(), self.widths.as_deref())) } } @@ -616,6 +622,17 @@ impl Texts { Texts { patterns, ..self } } + /// The text document with the widths `page` (the file's page, [`vectorcraft_pdf::PageWidths`]) + /// gives the characters of its fonts, by each record's PostScript name: a record that keeps no + /// version is set in the installed copy of its font that sets them at those widths + /// ([`super::text::postscript_face`]). + pub(super) fn with_page_widths(mut self, page: &vectorcraft_pdf::PageWidths) -> Texts { + for f in &mut self.fonts { + f.widths = page.widths(super::text::bare_name(&f.name)).cloned(); + } + self + } + /// The text document in the editing copy `data`, if it has one that can be read. pub(super) fn read(data: &[u8]) -> Option { fn find(h: &[u8], n: &[u8], from: usize) -> Option { @@ -643,6 +660,8 @@ impl Texts { return None; } let doc = names::numbered(read(&bytes)?); + // Records of one name and version share their answer. + let mut answers: HashMap<(String, Option), Arc>> = HashMap::new(); let fonts = doc .get("0")? .get("1")? @@ -652,11 +671,10 @@ impl Texts { .map(|f| { let record = f.get("0").and_then(|f| f.get("0")); let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str); - DocFont { - name: text("0").unwrap_or_default().to_string(), - version: text("5").and_then(record_version).map(str::to_string), - font: std::sync::OnceLock::new(), - } + let name = text("0").unwrap_or_default().to_string(); + let version = text("5").and_then(record_version).map(str::to_string); + let font = answers.entry((name.clone(), version.clone())).or_default().clone(); + DocFont { name, version, widths: None, font } }) .collect(); let main = doc.get("1")?; @@ -1592,6 +1610,40 @@ fn art_scale(to_doc: Affine) -> f64 { mod tests { use super::*; + /// The records of a text document's font list that name one font share the widths the file's + /// page gives it and the face they resolve to, however many there are: 20,000 records of a font + /// whose page gives 4,096 characters hold one copy of those widths, and resolve once. A record + /// of another version is resolved apart. + #[test] + fn records_of_one_font_share_its_page_widths_and_answer() { + let n = 20_000; + let records = "<< /0 << /0 << /0 (Sharetest-Regular) >> >> >> ".repeat(n) + "<< /0 << /0 << /0 (Sharetest-Regular) /5 (2.0) >> >> >>"; + let doc = format!("/0 << /1 << /0 [ {records} ] >> /8 << /0 [ ] >> >>\n/1 << /1 [ ] /2 << >> >>\n"); + let data = + format!("%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", crate::ps::ascii85(doc.as_bytes())); + let mut cmap = String::from("begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n16 beginbfrange\n"); + for hi in 1..=16u32 { + cmap.push_str(&format!("<{hi:02X}00> <{hi:02X}FF> <{hi:02X}00>\n")); + } + cmap.push_str("endbfrange\nendcmap\n"); + let extra = vectorcraft_testkit::pdf::first_extra(1); + let font = format!( + "/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+Sharetest-Regular /Encoding /Identity-H /ToUnicode {extra} 0 R \ + /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+Sharetest-Regular /W [256 4351 500] >>] >> >>" + ); + let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") }; + let pdf = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None); + let widths = vectorcraft_pdf::open_pdf(&pdf, None).unwrap().page_widths(); + let shared = widths.widths("Sharetest-Regular").unwrap(); + assert_eq!(shared.len(), 4096); + let texts = Texts::read(data.as_bytes()).unwrap().with_page_widths(&widths); + assert_eq!(texts.fonts.len(), n + 1); + assert!(texts.fonts.iter().all(|f| f.widths.as_ref().is_some_and(|w| Arc::ptr_eq(w, shared)))); + let first = &texts.fonts[0].font; + assert!(texts.fonts[..n].iter().all(|f| Arc::ptr_eq(&f.font, first))); + assert!(texts.fonts.last().is_some_and(|f| !Arc::ptr_eq(&f.font, first)), "another version resolves apart"); + } + #[test] fn right_to_left_paragraphs_swap_left_and_right_alignment() { let texts = Texts { diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 86d6976d89..5374730368 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -178,17 +178,25 @@ impl ReadText { self.frames.get_or_insert_with(|| ai::text_frames(data)) } - /// The text document of `data` ([`Texts::read`]), if it has one that can be read. - fn texts(&mut self, data: &[u8]) -> Option<&Texts> { + /// The text document of `data` ([`Texts::read`]), if it has one that can be read, with the widths + /// `page_widths` the file's page gives its fonts ([`Texts::with_page_widths`]). They are given + /// when it is first read, before any of its fonts is found: each is found once, with the widths + /// it has then. Every check and build of one open passes the same widths. + fn texts(&mut self, data: &[u8], page_widths: &vectorcraft_pdf::PageWidths) -> Option<&Texts> { self.forget_in_tests(); - self.texts.get_or_insert_with(|| Texts::read(data)).as_ref() + self.texts.get_or_insert_with(|| Texts::read(data).map(|t| t.with_page_widths(page_widths))).as_ref() } /// [`Self::texts`] with its characters painted by `patterns` ([`Texts::with_patterns`]). - fn texts_with(&mut self, data: &[u8], patterns: std::collections::HashMap) -> Option<&Texts> { + fn texts_with( + &mut self, + data: &[u8], + patterns: std::collections::HashMap, + page_widths: &vectorcraft_pdf::PageWidths, + ) -> Option<&Texts> { self.forget_in_tests(); - let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_patterns(patterns)); - self.texts.insert(texts).as_ref() + let read = self.texts.take().unwrap_or_else(|| Texts::read(data).map(|t| t.with_page_widths(page_widths))); + self.texts.insert(read.map(|t| t.with_patterns(patterns))).as_ref() } } @@ -217,7 +225,7 @@ fn type_all_made(structure: &Structure, data: &[u8], text: &mut ReadText) -> boo for info in &mut infos { info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(structure.to_doc * p.clone()))); } - let Some(texts) = text.texts(data) else { return false }; + let Some(texts) = text.texts(data, &structure.page_widths) else { return false }; let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos .iter() @@ -336,6 +344,7 @@ pub(super) fn build_weighing( envelopes_drawn, styles_read, text_patterns, + page_widths, canvas_scale, symbols_own_size, xml_ids, @@ -496,7 +505,7 @@ pub(super) fn build_weighing( // The page's type that needs no text object of the layers: the layers' own legacy text, or // placed files that show it. let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?; - let texts = text.texts_with(data, text_patterns); + let texts = text.texts_with(data, text_patterns, &page_widths); // Each story is read once, however many text objects name it. let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index d46da2b8ff..ef22d928b9 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -149,7 +149,7 @@ pub fn layered_ai_from( all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part")); all }; - let AiLayers { data, structure, alone, mut text } = layers; + let AiLayers { data, structure, alone, mut text, page_widths } = layers; let data = match data { Ok(data) => data, Err(why) => return (visible, unread(warnings, &why), false), @@ -189,10 +189,17 @@ pub fn layered_ai_from( add_notes(&mut all, read.notes()); (visible, all, false) }; + // The layers read, with the widths the PDF part gives the characters of its fonts. + let read = || { + ai::read_over_page(&data, false, names).map(|mut structure| { + structure.page_widths = page_widths.clone(); + structure + }) + }; // The envelopes of type the page doesn't hold against layers that don't draw as it, and how many // envelopes of type the layers had. let (mut free, mut count) = (None, 0); - let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| { + let built = structure.unwrap_or_else(|| read().map(Box::new)).and_then(|structure| { count = structure.warped_type.envelope_count(); build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text) }); @@ -205,7 +212,7 @@ pub fn layered_ai_from( let live = free.is_none() && matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers)); if !live && let Some((mut done, notes)) = alone.and_then(|(pages, unit)| { - let mut structure = ai::read_over_page(&data, false, names).ok()?; + let mut structure = read().ok()?; // With none free, nothing needs settling again: every envelope keeps its drawn art. if let Some(free) = free.as_deref().filter(|free| !free.is_empty()) { structure.warped_type.open_alone(free, count); @@ -244,32 +251,41 @@ fn holds_type_envelope(nodes: &[Arc]) -> bool { /// reading it, when the file's text document makes all of its type and nothing in its layers needs /// the PDF part (see `build_without_page`). Nothing is compared with the PDF part. Else, as the /// error, what was decoded and read of the editing copy, for [`layered_ai_from`] once the PDF part -/// is imported. `names`: the encoding of names that aren't UTF-8. -pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec), AiLayers> { +/// is imported. `names`: the encoding of names that aren't UTF-8. `page_widths`: the widths the +/// PDF part gives the characters of its fonts, which tell installed copies of a font apart +/// ([`AiLayers::with_page_widths`]). +pub fn ai_layers_alone( + private: &[u8], + pages: &[(f64, f64)], + unit: f64, + names: ai::NameEncoding, + page_widths: vectorcraft_pdf::PageWidths, +) -> Result<(Document, Vec), AiLayers> { let data = match ai::decode_private(private) { Ok(data) => data, - Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default() }), + Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default(), page_widths }), }; if !has_layers(&data) { - return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default() }); + return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default(), page_widths }); } // An image past the hard limits is read as an unread box, which the PDF part's art replaces. - let structure = match ai::read_over_page(&data, false, names) { + let mut structure = match ai::read_over_page(&data, false, names) { Ok(structure) => structure, - Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default() }), + Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default(), page_widths }), }; + structure.page_widths = page_widths.clone(); let mut text = Box::::default(); // An envelope of type opens live only where the layers with it draw as the page, as the other // live envelopes do: the PDF part is imported to compare them with. Should none open live, the // layers open alone as they would have, the envelopes keeping their drawn art ([`layered_ai_from`]). if structure.warped_type.has_envelopes() && alone_scale(&structure, &data, pages, unit, &mut text).is_some() { let alone = Some((pages.to_vec(), unit)); - return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text }); + return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text, page_widths }); } match build_without_page(structure, &data, pages, unit, &mut text) { Ok(Ok((doc, notes))) => Ok((doc, notes)), - Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text }), - Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text }), + Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text, page_widths }), + Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text, page_widths }), } } @@ -286,12 +302,27 @@ pub struct AiLayers { alone: Option<(Vec<(f64, f64)>, f64)>, /// The text objects' frames and the text document of the editing copy, as far as they were read. text: Box, + /// The widths the PDF part gives the characters of its fonts ([`Self::with_page_widths`]). + page_widths: vectorcraft_pdf::PageWidths, } impl AiLayers { /// The editing copy `private` (as [`layered_ai`] takes it), decoded. pub fn decode(private: &[u8]) -> Self { - Self { data: ai::decode_private(private), structure: None, alone: None, text: Box::default() } + Self { data: ai::decode_private(private), structure: None, alone: None, text: Box::default(), page_widths: Default::default() } + } + + /// The editing copy with `page_widths`, the widths the file's PDF part gives the characters of + /// its fonts ([`vectorcraft_pdf::Opened::page_widths`]): type whose font record keeps no + /// version is set in the installed copy of its font that sets them at those widths, where + /// several copies answer to its name. The layers read before take them too, and a text document + /// read before is read again with them, since its fonts are found once, with the widths they had + /// then. + pub fn with_page_widths(mut self, page_widths: vectorcraft_pdf::PageWidths) -> Self { + if let Some(Ok(structure)) = &mut self.structure { + structure.page_widths = page_widths.clone(); + } + Self { page_widths, text: Box::default(), ..self } } } @@ -581,13 +612,17 @@ fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) { /// Editing data written on a large canvas comes in at its declared scale: no page holds the size. /// Names that aren't UTF-8 are read as Windows-1252 ([`ai_alone_with`]). pub fn ai_alone(private: &[u8]) -> Result<(Document, Vec), String> { - ai_alone_with(private, ai::NameEncoding::default()) + ai_alone_with(private, ai::NameEncoding::default(), Default::default()) } -/// [`ai_alone`], with the names that aren't UTF-8 read in `names`. -pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec), String> { +/// [`ai_alone`], with the names that aren't UTF-8 read in `names`, and `page_widths`, the widths the +/// file's PDF part gives the characters of its fonts when it has one that holds the art +/// ([`AiLayers::with_page_widths`]). +pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding, page_widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec), String> { let data = ai::decode_private(private)?; - build_from(ai::read_in(&data, true, names)?, &data, None, Page::Artboard, false, false, 1.0) + let mut structure = ai::read_in(&data, true, names)?; + structure.page_widths = page_widths; + build_from(structure, &data, None, Page::Artboard, false, false, 1.0) } /// [`ai_alone`] for a `.ai` whose PDF part can't be read, its first page `page` (width and height) diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index dbac845dad..8780c92c6a 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3452,6 +3452,105 @@ fn type_from_the_text_document_takes_the_version_its_font_record_keeps() { assert_eq!(version("/0 (VertestInk-Regular) /VersionString (1.1)"), "1.1"); } +/// The widths a `.ai`'s PDF part gives the characters of `text` in its font `name` (a subset of +/// it, a TrueType font in `WinAnsiEncoding`): those `width` gives each, in thousandths of an em. +fn page_widths(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths { + let widths: Vec = (32u8..=126).map(char::from).map(|c| if text.contains(c) { width(c).to_string() } else { "0".into() }).collect(); + let font = format!( + "/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>", + widths.join(" ") + ); + let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") }; + vectorcraft_pdf::open_pdf(&vectorcraft_testkit::pdf::pdf_with(&[page], &[], None), None).unwrap().page_widths() +} + +/// [`page_widths`] of a composite font (`Identity-H`, a TrueType CIDFont) whose `ToUnicode` map gives +/// CID 1 the first character of `text`, CID 2 the next and so on, `W` their widths. +fn page_widths_cid(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths { + let chars: Vec = text.chars().collect(); + let pairs: Vec = chars.iter().enumerate().map(|(i, c)| format!("<{:04X}> <{:04X}>", i + 1, u32::from(*c))).collect(); + let cmap = format!( + "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n{} beginbfchar\n{}\nendbfchar\nendcmap\n", + pairs.len(), + pairs.join("\n") + ); + let w: Vec = chars.iter().map(|c| width(*c).to_string()).collect(); + let extra = vectorcraft_testkit::pdf::first_extra(1); + let font = format!( + "/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+{name}-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \ + /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+{name} /W [1 [{}]] >>] >> >>", + w.join(" ") + ); + let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") }; + let file = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None); + vectorcraft_pdf::open_pdf(&file, None).unwrap().page_widths() +} + +/// The advance of `c` in installed `face`, in thousandths of an em. +fn advance(face: &vectorcraft_text::FontFace, c: char) -> f64 { + face.advance(face.glyph_for(c)) * 1000.0 / face.units_per_em() +} + +/// The version of the face that type from the text document of a `.ai` whose font record is +/// `record` (in place of `/0 (Helvetica)`) is set in, its layers read alone with `widths`, the +/// widths its PDF part gives the characters of its fonts. +fn version_on_page(record: &str, widths: vectorcraft_pdf::PageWidths) -> String { + let doc = text_document(&[("Hamburg\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]).replacen("/0 (Helvetica)", record, 1); + let file = private(&native_with_text(&layer("Art", true, &text_object(0)), &doc)); + let names = crate::NameEncoding::default(); + let Ok((d, notes)) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, widths) else { panic!("{record}: opened with the page") }; + let texts = text_of(&d.layers[0]); + assert_eq!(texts.len(), 1, "{record}: {notes:?}"); + vectorcraft_text::FontDb::global().style_face(&texts[0].runs[0].style).unwrap().version.clone() +} + +/// Two installed copies of one font can share its PostScript name, family and style, and differ +/// in their glyphs' widths alone. Type from the text document of a `.ai` whose font record keeps no +/// version is set in the copy that sets the characters its PDF part draws at the widths the PDF +/// part gives them, also when the record spells the name with other punctuation. Without those +/// widths, or when no copy sets the characters at them, it takes the copy it took before (the first +/// loaded); a version the record keeps decides first. The widths of a simple font in +/// `WinAnsiEncoding` and of a composite font with a `ToUnicode` map both tell the copies apart. +#[test] +fn type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths() { + install(&[(true, ("Widtest Ink", "Regular", "1.0", "WidtestInk-Regular")), (false, ("Widtest Ink", "Regular", "1.1", "WidtestInk-Regular"))]); + let copies = vectorcraft_text::FontDb::global().postscript_faces("WidtestInk-Regular"); + let copy = |version: &str| copies.iter().find(|f| f.version == version).unwrap().clone(); + let (old, new) = (copy("1.0"), copy("1.1")); + assert!((advance(&old, 'H') - advance(&new, 'H')).abs() > 10.0, "the copies set the type at other widths"); + let on = |name: &str, face: &vectorcraft_text::FontFace| page_widths(name, "Hamburg", |c| advance(face, c)); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", Default::default()), "1.0"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &new)), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &old)), "1.0"); + // Widths a file rounds are within 1/1000 em of the advances; farther off, they aren't the copy's. + let off = |by: f64| page_widths("WidtestInk-Regular", "Hamburg", |c| advance(&new, c) + by); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(0.9)), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(-0.9)), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(2.0)), "1.0"); + // A record whose name differs from the copies' in punctuation alone, as its PDF part's font. + assert_eq!(version_on_page("/0 (Widtest-Ink-Regular)", on("Widtest-Ink-Regular", &new)), "1.1"); + // Widths of another font, or no copy setting the characters at the PDF part's widths. + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("OtherInk-Regular", &new)), "1.0"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths("WidtestInk-Regular", "Hamburg", |_| 1000.0)), "1.0"); + // A version the record keeps picks the copy, and one that isn't installed gives the copy it gave. + assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (1.0)", on("WidtestInk-Regular", &new)), "1.0"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (9.9)", on("WidtestInk-Regular", &new)), "1.0"); + // The widths of a composite font. + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&new, c))), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&old, c))), "1.0"); + // A font installed once is set in that copy whatever the widths. + install(&[(true, ("Onewtest Ink", "Regular", "1.0", "OnewtestInk-Regular"))]); + assert_eq!(version_on_page("/0 (OnewtestInk-Regular)", on("OnewtestInk-Regular", &new)), "1.0"); + // Of several copies that set the characters at the widths, the first in the order the faces + // are found (the first loaded). + install(&[ + (true, ("Firstwtest Ink", "Regular", "1.0", "FirstwtestInk-Regular")), + (false, ("Firstwtest Ink", "Regular", "1.1", "FirstwtestInk-Regular")), + (false, ("Firstwtest Ink", "Regular", "1.2", "FirstwtestInk-Regular")), + ]); + assert_eq!(version_on_page("/0 (FirstwtestInk-Regular)", on("FirstwtestInk-Regular", &new)), "1.1"); +} + /// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character /// Style]` and `[Normal Paragraph Style]` before the text document's base attributes. A Large /// Canvas copy (1:10) writes the styles at the art's scale (1.2 for 12 points, 0.6 for a 6-point @@ -6051,7 +6150,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() { let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; // A PDF part the layers don't draw as. let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, false, 1.0, names); assert!(read, "{notes:?}"); @@ -6060,7 +6159,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() { assert_eq!(loose, [("Note".to_string(), true), ("FLUX".to_string(), false)], "{notes:?}"); assert!(notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}"); // A PDF part that draws as those layers, with the drawn art: the envelope opens live. - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; let (d, notes, read) = crate::layered_ai_from(layers, d, vec![], false, false, 1.0, names); assert!(read, "{notes:?}"); let (envelopes, loose) = envelopes_and_type(&d); @@ -6088,7 +6187,7 @@ fn layers_that_open_alone_read_their_text_once() { let doc = unsplit_text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Mid\r", 2, (8191.5, 8191.5), (0.0, 0.0), -10.0)]); let art = layer("Art", true, &format!("{}\n{}{}", square(10, 10), text_object(0), text_object(1))); let file = private(&native_with_text(&art, &doc)); - let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default()).ok(); + let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default(), Default::default()).ok(); let (opened, texts, frames) = text_reads(false, open); let Some((d, notes)) = opened else { panic!("didn't open without the page") }; assert_eq!((texts, frames), (1, 1), "{notes:?}"); @@ -6107,7 +6206,7 @@ fn layers_whose_text_document_cannot_be_read_read_it_once_with_the_page() { let file = private(&native_with_text(&art, "not a text document")); let names = crate::NameEncoding::default(); let open = || { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, pdf_part(10.0, 86.0), vec![], false, false, 1.0, names) }; let (opened, texts, frames) = text_reads(false, open); @@ -6134,7 +6233,7 @@ fn an_envelope_of_type_waiting_on_the_page_reads_the_text_once() { let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) }; // A PDF part the layers don't draw as: they open alone, after a build with the page and one without. @@ -6218,7 +6317,7 @@ fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_dr let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, true, 1.0, names); assert!(read, "{notes:?}"); let (envelopes, loose) = envelopes_and_type(&d); @@ -6312,7 +6411,7 @@ fn layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_di let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) }; // The layers alone, with the envelope's drawn art: what the page draws. @@ -6355,7 +6454,7 @@ fn trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_ let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document, trust: bool| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, trust, 1.0, names) }; let (mut page, _, _) = open(pdf_part(80.0, 80.0), false); @@ -6394,7 +6493,7 @@ fn layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_do let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) }; // The layers alone, with the drawn art of both envelopes, but the first's: the page draws diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index 3de16d7bbf..c3bb2f4d7a 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -44,7 +44,7 @@ fn style_word(w: &str) -> String { /// A font's PostScript name without a subset prefix (`ABCDEF+`) or the `*1` of a re-encoded copy /// (`ABCDEF+RollerBabyBV*1` is `RollerBabyBV`). -fn bare_name(name: &str) -> &str { +pub(super) fn bare_name(name: &str) -> &str { let name = match name.split_once('+') { Some((prefix, rest)) if prefix.len() == 6 && prefix.bytes().all(|b| b.is_ascii_uppercase()) => rest, _ => name, @@ -56,14 +56,15 @@ fn bare_name(name: &str) -> &str { } /// The font of type that a text document's font record names: by `name`, its PostScript name, and -/// `version`, the version string (name ID 5) the record keeps, if any. An installed face of that -/// name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) and the -/// family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is +/// `version`, the version string (name ID 5) the record keeps, if any; `widths`, the widths the +/// file's page gives the font's characters, if it has them ([`postscript_face`]). An installed face +/// of that name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) +/// and the family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is /// Microsoft YaHei). → (family, style, version). /// /// [`FontDb::find_family`]: vectorcraft_text::FontDb::find_family -pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, String, Option) { - named_font(name, version).unwrap_or_else(|| { +pub(crate) fn document_font(name: &str, version: Option<&str>, widths: Option<&vectorcraft_pdf::FontWidths>) -> (String, String, Option) { + named_font(name, version, widths).unwrap_or_else(|| { let (family, style) = family_style(name); let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); (family, style, None) @@ -71,37 +72,69 @@ pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, Strin } /// The font of type set in the installed face of PostScript name `name` (a subset prefix and a -/// re-encoded copy's `*1` aside) in `version` ([`postscript_face`]): that face's own family and -/// style, and its version when the family and style alone resolve to another installed copy of -/// the font. A library can keep two copies under one family and style that differ in their -/// PostScript names or their versions, and draw the same text at different widths. → (family, -/// style, version); `None` when no installed face has the name. -pub(crate) fn named_font(name: &str, version: Option<&str>) -> Option<(String, String, Option)> { - let face = postscript_face(bare_name(name), version)?; +/// re-encoded copy's `*1` aside) in `version`, or that sets the characters at `widths` +/// ([`postscript_face`]): that face's own family and style, and its version when the family and +/// style alone resolve to another installed copy of the font. A library can keep two copies under +/// one family and style that differ in their PostScript names or their versions, and draw the same +/// text at different widths. → (family, style, version); `None` when no installed face has the name. +pub(crate) fn named_font( + name: &str, + version: Option<&str>, + widths: Option<&vectorcraft_pdf::FontWidths>, +) -> Option<(String, String, Option)> { + let face = postscript_face(bare_name(name), version, widths)?; // As the PDF import names a version: only one that the family and style don't resolve to. let default = vectorcraft_text::FontDb::global().face(&face.family, &face.style); let version = default.filter(|d| d.version != face.version).map(|_| face.version.clone()); Some((face.family.clone(), face.style.clone(), version)) } +/// How far an installed face's advance may be from the width a page gives a character, in +/// thousandths of an em, for the face to set it at that width: files write widths rounded. +const PAGE_WIDTH_SLACK: f64 = 1.0; + +/// The most characters of a page's font [`sets_page_widths`] compares. +const MAX_WIDTHS_COMPARED: usize = 512; + +/// Does installed `face` set the characters of `widths` (a page's, [`vectorcraft_pdf::FontWidths`]) +/// at their widths, each within [`PAGE_WIDTH_SLACK`]? The first [`MAX_WIDTHS_COMPARED`] characters +/// in code-point order are compared; a character the face has no glyph for isn't set at its width. +fn sets_page_widths(face: &vectorcraft_text::FontFace, widths: &vectorcraft_pdf::FontWidths) -> bool { + let k = 1000.0 / face.units_per_em(); + widths.iter().take(MAX_WIDTHS_COMPARED).all(|(c, w)| { + let gid = face.glyph_for(*c); + gid != 0 && (face.advance(gid) * k - f64::from(*w)).abs() <= PAGE_WIDTH_SLACK + }) +} + /// The installed face of PostScript name `name` (without a subset prefix), among the installed /// faces that answer to it ([`FontDb::postscript_faces`]): those of exactly that name when there /// are any (PostScript names are case-sensitive, so `SampleSans` isn't the face named /// `SAMPLESANS`, and `SampleSerif-Bold` isn't `SampleSerifBold`), and of those the one in -/// `version` when it is installed, else the first. `None` when no installed face has the name. +/// `version` when it is installed. Without a version, copies whose names, family and style are all +/// one can still set the type at other widths: of those, the first that sets the characters of +/// `widths` (the file's page's, when it has them) at their widths ([`sets_page_widths`], which +/// compares the first 512 characters). Else the first. `None` when no installed face has the name. /// /// [`FontDb::postscript_faces`]: vectorcraft_text::FontDb::postscript_faces -pub(crate) fn postscript_face(name: &str, version: Option<&str>) -> Option> { +pub(crate) fn postscript_face( + name: &str, + version: Option<&str>, + widths: Option<&vectorcraft_pdf::FontWidths>, +) -> Option> { let db = vectorcraft_text::FontDb::global(); let found = db.find_postscript(name)?; - if found.postscript_name() == name && version.is_none_or(|v| v == found.version) { + let widths = widths.filter(|_| version.is_none()); + let on_page = |f: &vectorcraft_text::FontFace| widths.is_none_or(|w| sets_page_widths(f, w)); + if found.postscript_name() == name && version.is_none_or(|v| v == found.version) && on_page(&found) { return Some(found); } let faces = db.postscript_faces(name); let named: Vec<_> = faces.iter().filter(|f| f.postscript_name() == name).cloned().collect(); let pool = if named.is_empty() { faces } else { named }; let in_version = version.and_then(|v| pool.iter().find(|f| f.version == v).cloned()); - Some(in_version.or_else(|| pool.into_iter().next()).unwrap_or(found)) + let by_widths = || pool.iter().find(|f| on_page(f)).cloned(); + Some(in_version.or_else(by_widths).or_else(|| pool.into_iter().next()).unwrap_or(found)) } /// A font's family and style from its PostScript name, without a subset prefix (`ABCDEF+`) or the @@ -620,7 +653,7 @@ impl Interp<'_> { } // The installed face of that PostScript name, as type from a text document takes it; else // the available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei". - let (font_family, font_style, font_version) = document_font(&name, None); + let (font_family, font_style, font_version) = document_font(&name, None, None); let fill = if self.g.paint.is_none() { Paint::solid(vectorcraft_color::Color::BLACK) } else { self.g.paint.clone() }; let style = CharStyle { font_family, font_style, font_version, size, fill, stroke: Paint::None, ..CharStyle::default() }; let mut t = TextObject::point(Point::ZERO, text, style); diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index e5a5e2e382..46bf544e9f 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -38,6 +38,7 @@ mod entry; mod reshaped; mod state; +pub(crate) use cid::replacement; #[cfg(test)] pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical}; #[cfg(any(test, feature = "read-count"))] diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index e6e34ae429..677a0d4c67 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -842,11 +842,7 @@ impl<'p> Builder<'p> { let data = o.font_data(); let name = self.fonts.get(&key).map(|f| f.name.clone()).or_else(|| data.as_ref().and_then(|d| d.postscript_name.clone())); let (weight, italic) = data.as_ref().map_or((None, false), |d| (d.weight, d.is_italic)); - // A subset's six-letter tag. - let ps = name.as_deref().map(|n| match n.split_once('+') { - Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest.to_string(), - _ => n.to_string(), - }); + let ps = name.as_deref().map(|n| crate::import_scan::without_subset_tag(n).to_string()); let installed = ps.as_deref().and_then(|ps| vectorcraft_text::FontDb::global().find_postscript(ps)); let n = match (installed, name) { (Some(face), _) => FontInfo { family: face.family.clone(), style: face.style.clone(), face: Some(face) }, diff --git a/crates/pdf/src/import/cid.rs b/crates/pdf/src/import/cid.rs index 60a28d15e1..b862ed336e 100644 --- a/crates/pdf/src/import/cid.rs +++ b/crates/pdf/src/import/cid.rs @@ -70,7 +70,7 @@ impl CidText { } /// A ToUnicode value that names no character: U+FFFD alone (#708). -pub(super) fn replacement(u: &craft_pdf::interpret::hayro_cmap::BfString) -> bool { +pub(crate) fn replacement(u: &craft_pdf::interpret::hayro_cmap::BfString) -> bool { use craft_pdf::interpret::hayro_cmap::BfString; match u { BfString::Char(c) => *c == char::REPLACEMENT_CHARACTER, diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index b65254eafa..c2b81afc65 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -1041,19 +1041,26 @@ pub(crate) fn vertical_metrics(f: &Dict<'_>, embedded: bool) -> Option /// Each CID a `W` or `W2` array (`per` numbers a CID) gives values for, and its values: `c [v…]` /// gives CIDs from c on their values in turn, `c_first c_last v…` the same values to each of the -/// range. At most [`MAX_CIDS`] CIDs are read. -fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) { +/// range. At most [`MAX_CIDS`] CIDs are read, and a list's values only as far as they take; `per` +/// is 1 or 3. +pub(crate) fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) { let mut it = a.flex_iter(); let mut read = 0; loop { if let Some((first, list)) = it.next::<(u32, Array<'_>)>() { - let values: Vec = list.iter::().collect(); - for (cid, v) in (first..=u32::MAX).zip(values.chunks_exact(per)) { + // Read as they are given, no more than the CIDs read take. + let mut values = list.iter::(); + let mut v = [0.0; 3]; + for cid in first..=u32::MAX { + let Some(group) = v.get_mut(..per) else { return }; + if group.iter_mut().any(|slot| values.next().map(|x| *slot = x).is_none()) { + break; + } read += 1; if read > MAX_CIDS { return; } - each(cid, v); + each(cid, group); } } else if per == 1 && let Some((first, last, w)) = it.next::<(u32, u32, f64)>() @@ -1081,11 +1088,20 @@ fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) { } } +/// A font's PostScript name without its subset's six-letter tag (`ABCDEF+Name` is `Name`, ISO +/// 32000-1 §9.6.4). +pub(crate) fn without_subset_tag(name: &str) -> &str { + match name.split_once('+') { + Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest, + _ => name, + } +} + /// The PostScript name of font `f`: its `BaseFont`. A composite (Type 0) font's `BaseFont` is its /// CIDFont's name, a hyphen and its CMap's (`Name-Identity-H`, ISO 32000-1 §9.7.6.1), so its /// descendant CIDFont's `BaseFont` is taken, the font program's own name (§9.7.4.1); without one, /// the `BaseFont` without the CMap's name on its end. -fn font_name(f: &Dict<'_>) -> Option { +pub(crate) fn font_name(f: &Dict<'_>) -> Option { if f.get::>(b"Subtype").is_some_and(|s| s.as_ref() == b"Type3") { if let Some(base) = f.get::>(b"BaseFont") { return Some(String::from_utf8_lossy(base.as_ref()).into_owned()); diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index ec4fff092a..e301a91c3a 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -1148,11 +1148,7 @@ impl Families { /// The family and style of a font with base (PostScript) name `name`, or of weight `weight` /// and slant `italic` when the name has no style; whether the family is available. pub fn resolve(&self, name: &str, weight: Option, italic: bool) -> (String, String, bool) { - // A subset's six-letter tag. - let name = match name.split_once('+') { - Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest, - _ => name, - }; + let name = crate::import_scan::without_subset_tag(name); // An installed face of that exact PostScript name: its own family and style. if let Some((family, style)) = vectorcraft_text::FontDb::global().by_postscript_name(name) { return (family, style, true); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index a5f93a2a76..cd070d8c6f 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -61,6 +61,7 @@ mod lab_spot; mod linearize; mod marks; mod output; +mod page_widths; mod pages; mod patch; mod pdfx; @@ -83,6 +84,7 @@ 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, }; +pub use page_widths::{FontWidths, PageWidths}; #[cfg(any(test, feature = "read-count"))] pub use pages::reads_of; pub use pages::{ diff --git a/crates/pdf/src/page_widths.rs b/crates/pdf/src/page_widths.rs new file mode 100644 index 0000000000..aa1f122fcd --- /dev/null +++ b/crates/pdf/src/page_widths.rs @@ -0,0 +1,598 @@ +//! The widths a PDF's pages give the characters of the fonts they set type in, read from the font +//! dictionaries alone (no page is drawn): a simple font's `Widths` from its `FirstChar`, or a +//! composite font's descendant's `W`, each code's character from the font's `ToUnicode` map, or for +//! a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding (ISO 32000-1 +//! §9.6.2, §9.6.6, §9.7.4.3, §9.10.3, Annex D.2). + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::rc::Rc; +use std::sync::Arc; + +use craft_pdf::interpret::hayro_cmap::{BfString, CMap}; +use craft_pdf::syntax::object::{Array, Dict, Name, ObjRef, ObjectIdentifier, Stream}; +use craft_pdf::syntax::page::Resources; + +use crate::import::replacement; +use crate::import_scan::{cid_ranges, font_name, without_subset_tag}; + +/// The most fonts read. +const MAX_FONTS: usize = 256; +/// The most form XObjects looked into, and how deep they may nest. +const MAX_FORMS: usize = 4096; +const MAX_FORM_DEPTH: u32 = 16; +/// The most entries of font and XObject resource dictionaries looked at, all pages and forms of the +/// file together (one budget for the whole file, not one a page). +const MAX_KEYS: usize = 1 << 16; +/// The most bytes of width arrays (`Widths`, `W`) read, all fonts together; an array that fonts +/// share by reference is read once. A subset's array is a few kilobytes. +const MAX_WIDTH_TEXT: usize = 4 << 20; +/// The most characters of a font kept. +const MAX_CHARS: usize = 4096; +/// The largest `ToUnicode` map read, decoded: a subset's map names a few hundred codes. A longer one +/// is left unread. +const MAX_TO_UNICODE: usize = 256 << 10; +/// The most bytes of `ToUnicode` maps decoded, all fonts together. +const MAX_TO_UNICODE_TOTAL: usize = 4 << 20; +/// How far apart two widths a file gives one character of one font may be and still be one width, +/// in thousandths of an em: files write widths rounded. +const SAME_WIDTH: f32 = 1.0; + +/// The widths a page gives the characters of one font, in thousandths of an em, by character. +pub type FontWidths = BTreeMap; + +/// The advance widths, in thousandths of an em, that a PDF's pages give the characters of the fonts +/// they set type in, by each font's PostScript name (its `BaseFont` without a subset prefix): what +/// the copy of the font the file was set in draws them at. A `.ai`'s PDF part has them for the type +/// its text document holds, so they tell installed copies of one font apart. A font whose subsets +/// give one character two widths gives none. Cloning it, or a font's widths, shares them. +#[derive(Clone, Debug, Default)] +pub struct PageWidths { + fonts: Arc>>, +} + +impl PageWidths { + /// Each character the pages set in the font of PostScript name `name` (exactly, without a + /// subset prefix) and its width (at most 4096 characters): `None` when the pages set none in + /// that font, or its subsets give a character two widths. + pub fn widths(&self, name: &str) -> Option<&Arc> { + self.fonts.get(name) + } +} + +/// Which dictionary `d` is, to look at it once: where its text lies in the file as read. One +/// dictionary that pages or forms share is read from the same place each time (one in an object +/// stream lies in that stream's decoded data, which the reader keeps); telling it by its contents +/// would hash it again for each of them. +fn dict_key(d: &Dict<'_>) -> (usize, usize) { + let text = d.data(); + (text.as_ptr() as usize, text.len()) +} + +/// Each CID a composite font's `W` gives a width, and that width. +type CidWidths = Rc<[(u32, f32)]>; + +/// What [`page_widths`] has read so far. +#[derive(Default)] +struct Walk { + /// Each font's characters and widths; `None` when two subsets disagree. + fonts: HashMap>, + /// The font dictionaries, form XObjects and resource dictionaries already looked at. + seen_fonts: HashSet<(usize, usize)>, + seen_forms: HashSet, + walked: HashSet<(usize, usize)>, + /// The `ToUnicode` maps parsed, by their stream: `None` for one that can't be read. + maps: HashMap>>, + /// The width arrays that fonts name by reference, read: a simple font's `Widths` (its first 256 + /// numbers) and a composite font's `W` (each CID and its width). + simple_widths: HashMap>>, + cid_widths: HashMap>, + /// How many entries of resource dictionaries have been looked at. + looked: usize, + /// How many bytes of `ToUnicode` maps have been decoded. + decoded: usize, + /// How many width arrays have been read, and how many bytes of them. + arrays_read: usize, + width_text: usize, +} + +impl Walk { + /// Note `widths`, characters of the font of PostScript name `name` and their widths. A width + /// another subset gave the character already must be the same. + fn add(&mut self, name: String, widths: Vec<(char, f32)>) { + let slot = self.fonts.entry(name).or_insert_with(|| Some(BTreeMap::new())); + let Some(have) = slot else { return }; + for (c, w) in widths { + if have.get(&c).is_some_and(|was| (was - w).abs() > SAME_WIDTH) { + *slot = None; + return; + } + if have.len() < MAX_CHARS { + have.insert(c, w); + } + } + } + + /// Look at one more entry of a resource dictionary: `false` once [`MAX_KEYS`] have been. + fn look(&mut self) -> bool { + self.looked += 1; + self.looked <= MAX_KEYS + } + + /// The `ToUnicode` map `s`, parsed once however many fonts name it: `None` when it decodes to + /// more than [`MAX_TO_UNICODE`] bytes, when the maps decoded so far reach + /// [`MAX_TO_UNICODE_TOTAL`], or when it can't be read. A map is charged what was decoded of it, + /// at most the limit: a stream written plain comes back whole without being decoded. + fn character_map(&mut self, s: &Stream<'_>) -> Option> { + let id = s.obj_id(); + if !self.maps.contains_key(&id) { + let left = MAX_TO_UNICODE_TOTAL.saturating_sub(self.decoded).min(MAX_TO_UNICODE + 1); + let data = s.decoded_within(left).ok(); + self.decoded += data.as_ref().map_or(left, |d| d.len().min(left)); + let map = data.filter(|d| d.len() < left && d.len() <= MAX_TO_UNICODE).and_then(|d| CMap::parse(&d, |_| None)); + self.maps.insert(id, map.map(Rc::new)); + } + self.maps.get(&id)?.clone() + } + + /// Count `array`'s text against [`MAX_WIDTH_TEXT`]: `None` once the width arrays read reach it. + fn width_array<'a>(&mut self, array: Option>) -> Option> { + let array = array.filter(|_| self.width_text < MAX_WIDTH_TEXT)?; + self.arrays_read += 1; + self.width_text += array.data().len(); + Some(array) + } + + /// The first 256 numbers of simple font `f`'s `Widths`, read once for all the fonts that name + /// the same array. + fn simple_widths(&mut self, f: &Dict<'_>) -> Option> { + let read = |w: &mut Self| w.width_array(f.get::>(b"Widths")).map(|a| a.iter::().take(256).collect::>()); + let Some(r) = f.get_ref(b"Widths") else { return read(self) }; + if let Some(have) = self.simple_widths.get(&r) { + return have.clone(); + } + let got = read(self); + self.simple_widths.insert(r, got.clone()); + got + } + + /// Each CID that composite font descendant `d`'s `W` gives a width, and the width, read once for all + /// the fonts that name the same array. + fn cid_widths(&mut self, d: &Dict<'_>) -> Option { + let read = |w: &mut Self| { + let a = w.width_array(d.get::>(b"W"))?; + let mut out = Vec::new(); + cid_ranges(&a, 1, |cid, v| { + if let [w0] = v { + out.push((cid, *w0 as f32)); + } + }); + Some(out.into()) + }; + let Some(r) = d.get_ref(b"W") else { return read(self) }; + if let Some(have) = self.cid_widths.get(&r) { + return have.clone(); + } + let got = read(self); + self.cid_widths.insert(r, got.clone()); + got + } +} + +/// [`PageWidths`] of the fonts of `pages` (each page's resources) and of the forms they draw. +pub(crate) fn page_widths<'a>(pages: impl IntoIterator>) -> PageWidths { + let walk = walk(pages); + let fonts = walk.fonts.into_iter().filter_map(|(name, w)| Some((name, Arc::new(w.filter(|w| !w.is_empty())?)))).collect(); + PageWidths { fonts: Arc::new(fonts) } +} + +/// Read the fonts of `pages` and of the forms they draw. Each resource dictionary is walked once, +/// though pages and forms share it; a form without resources of its own takes those of what draws +/// it, which are walked already. At most [`MAX_KEYS`] entries are looked at. +fn walk<'a>(pages: impl IntoIterator>) -> Walk { + let mut w = Walk::default(); + let mut stack: Vec<(Resources<'a>, u32)> = pages.into_iter().map(|r| (r.clone(), 0)).collect(); + while let Some((res, depth)) = stack.pop() { + if w.walked.insert(dict_key(&res.fonts)) { + for key in res.fonts.keys() { + if w.seen_fonts.len() >= MAX_FONTS || !w.look() { + break; + } + let Some(f) = res.fonts.get::>(key.as_ref()) else { continue }; + if w.seen_fonts.insert(dict_key(&f)) + && let Some((name, widths)) = font_widths(&f, &mut w) + { + w.add(name, widths); + } + } + } + if depth >= MAX_FORM_DEPTH || !w.walked.insert(dict_key(&res.x_objects)) { + continue; + } + for key in res.x_objects.keys() { + if w.seen_forms.len() >= MAX_FORMS || !w.look() { + break; + } + let Some(s) = res.x_objects.get::>(key.as_ref()) else { continue }; + let d = s.dict(); + let form = d.get::>(b"Subtype").is_some_and(|t| t.as_ref() == b"Form"); + if let (true, Some(own)) = (form, d.get::>(b"Resources")) + && w.seen_forms.insert(s.obj_id()) + { + stack.push((Resources::from_scope(Some(own), res.clone()), depth + 1)); + } + } + } + w +} + +/// The PostScript name of font `f` (its `BaseFont` without a subset prefix) and the width of each +/// character it names, at most [`MAX_CHARS`]. A code's character comes from the font's `ToUnicode` +/// map or, for a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding; +/// a composite font's codes are its CIDs, so only under an `Identity-H` or `Identity-V` CMap. A +/// width of 0 is a code the subset doesn't use, and is left out. `None` for a Type 3 font (its +/// widths are in its own glyph space) and a font whose codes' characters can't be told. +fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32)>)> { + let subtype = f.get::>(b"Subtype")?; + if subtype.as_ref() == b"Type3" { + return None; + } + let name = without_subset_tag(&font_name(f)?).to_string(); + let composite = subtype.as_ref() == b"Type0"; + let encoding = f.get::>(b"Encoding"); + let to_unicode = f.get::>(b"ToUnicode").and_then(|s| walk.character_map(&s)); + let win_ansi = !composite && encoding.as_ref().is_some_and(|e| e.as_ref() == b"WinAnsiEncoding"); + if to_unicode.is_none() && !win_ansi { + return None; + } + let char_of = |code: u32| match &to_unicode { + Some(map) => match map.lookup_bf_string(code).filter(|u| !replacement(u)) { + Some(BfString::Char(c)) => Some(c), + _ => None, + }, + None => win_ansi_char(code), + }; + let width = |w: f32| (w.is_finite() && w > 0.0 && w < 1e5).then_some(w); + let mut widths = Vec::new(); + if composite { + if !encoding.is_some_and(|e| matches!(e.as_ref(), b"Identity-H" | b"Identity-V")) { + return None; + } + let d = f.get::>(b"DescendantFonts").and_then(|a| a.iter::>().next())?; + for (cid, w) in walk.cid_widths(&d)?.iter() { + if widths.len() >= MAX_CHARS { + break; + } + if let (Some(c), Some(w)) = (char_of(*cid), width(*w)) { + widths.push((c, w)); + } + } + } else { + let first = f.get::(b"FirstChar")?; + // A simple font's codes are bytes. + for (code, w) in (first..256).zip(walk.simple_widths(f)?.iter()) { + if let (Some(c), Some(w)) = (char_of(code), width(*w)) { + widths.push((c, w)); + } + } + } + Some((name, widths)) +} + +/// The character of code `code` in `WinAnsiEncoding` (ISO 32000-1 Annex D.2), which is Windows-1252 +/// but for the codes it leaves unused: `None` for those, for the controls, and for 160 and 173, which +/// it gives the space and the hyphen a second time. +fn win_ansi_char(code: u32) -> Option { + /// Codes 128 to 159; `\0` where the encoding has no character. + const HIGH: [char; 32] = [ + '\u{20AC}', '\0', '\u{201A}', '\u{192}', '\u{201E}', '\u{2026}', '\u{2020}', '\u{2021}', '\u{2C6}', '\u{2030}', '\u{160}', '\u{2039}', + '\u{152}', '\0', '\u{17D}', '\0', '\0', '\u{2018}', '\u{2019}', '\u{201C}', '\u{201D}', '\u{2022}', '\u{2013}', '\u{2014}', '\u{2DC}', + '\u{2122}', '\u{161}', '\u{203A}', '\u{153}', '\0', '\u{17E}', '\u{178}', + ]; + match code { + 0x20..=0x7E | 0xA1..=0xAC | 0xAE..=0xFF => char::from_u32(code), + 0x80..=0x9F => HIGH.get(usize::try_from(code - 0x80).ok()?).copied().filter(|c| *c != '\0'), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; + + /// A simple font named `name`, in `encoding`, whose widths from code `first` on are `widths`. + fn simple(subtype: &str, name: &str, encoding: &str, first: u32, widths: &str) -> String { + format!("<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /Encoding /{encoding} /FirstChar {first} /Widths [{widths}] >>") + } + + /// The pages' fonts are read from their resources and from the forms they draw, a subset's + /// prefix aside: a simple font's characters from `WinAnsiEncoding` (a code 0 wide is left out) + /// or its `ToUnicode` map, a composite font's from its `ToUnicode` map, by CID. The subsets of one + /// font come together; a font whose subsets give a character two widths, a font in another + /// encoding without a `ToUnicode` map, and a Type 3 font give none. + #[test] + fn the_pages_give_each_font_the_widths_of_its_characters() { + let extra = first_extra(2); + let fonts = [ + simple("TrueType", "ABCDEF+Sample-Regular", "WinAnsiEncoding", 65, "600 0 520.5"), + simple("Type1", "GHIJKL+Sample-Regular", "WinAnsiEncoding", 128, "700"), + format!( + "<< /Type /Font /Subtype /Type0 /BaseFont /MNOPQR+Wide-Bold-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \ + /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /MNOPQR+Wide-Bold /W [3 [250 610]] >>] >>" + ), + simple("Type1", "Roman-Mac", "MacRomanEncoding", 65, "500"), + format!( + "<< /Type /Font /Subtype /Type1 /BaseFont /Mapped /Encoding /MacRomanEncoding /FirstChar 3 /Widths [333] /ToUnicode {extra} 0 R >>" + ), + "<< /Type /Font /Subtype /Type3 /BaseFont /Drawn /Encoding /WinAnsiEncoding /FirstChar 65 /Widths [1] /FontMatrix [1 0 0 1 0 0] >>" + .to_string(), + simple("TrueType", "STUVWX+Clash", "WinAnsiEncoding", 65, "640"), + ]; + let resources = |fonts: &[String], more: &str| { + let list: Vec = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect(); + format!("/Font << {} >> {more}", list.join(" ")) + }; + let first = PdfPage { resources: resources(&fonts, &format!("/XObject << /Fm0 {} 0 R >>", extra + 1)), ..PdfPage::new(100.0, 100.0, "") }; + let second = PdfPage { + resources: resources(&[simple("TrueType", "YZABCD+Clash", "WinAnsiEncoding", 65, "600")], ""), + ..PdfPage::new(100.0, 100.0, "") + }; + let cmap = + "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n2 beginbfchar\n<0003> <0020>\n<0004> <03A9>\nendbfchar\nendcmap\n"; + let form_font = simple("TrueType", "EFGHIJ+Formed", "WinAnsiEncoding", 97, "480"); + let file = pdf_with( + &[first, second], + &[ + &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()), + &format!( + "<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Resources << /Font << /F0 {form_font} >> >> /Length 0 >>\nstream\n\nendstream" + ), + ], + None, + ); + let widths = crate::open_pdf(&file, None).unwrap().page_widths(); + let got = |name: &str| widths.widths(name).map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::>()); + assert_eq!(got("Sample-Regular"), Some(vec![('A', 600.0), ('C', 520.5), ('€', 700.0)])); + assert_eq!(got("Wide-Bold"), Some(vec![(' ', 250.0), ('Ω', 610.0)])); + assert_eq!(got("Mapped"), Some(vec![(' ', 333.0)])); + assert_eq!(got("Formed"), Some(vec![('a', 480.0)])); + for none in ["ABCDEF+Sample-Regular", "Roman-Mac", "Drawn", "Clash", "Missing"] { + assert_eq!(got(none), None, "{none}"); + } + } + + /// [`super::walk`] of the pages of `file`. + fn walked(file: &[u8]) -> super::Walk { + let o = crate::open_pdf(file, None).unwrap(); + let pages = o.pdf.pages(); + super::walk(pages.iter().map(|p| p.resources())) + } + + /// Each resource dictionary is walked once: forms without resources of their own (which take + /// those of what draws them), forms that share one, and pages that share one look at each + /// entry once, so a file of thousands of them reads in time in proportion to it. + #[test] + fn shared_resources_are_walked_once() { + let n = 4000; + let extra = first_extra(1); + let font = simple("TrueType", "Shared", "WinAnsiEncoding", 65, "500"); + // Forms without resources, then forms that share one resource dictionary (the last object). + let shared = extra + 2 * n; + let forms: Vec = (0..2 * n) + .map(|i| { + let own = if i < n { String::new() } else { format!("/Resources {shared} 0 R ") }; + format!("<< /Type /XObject /Subtype /Form /BBox [0 0 1 {i}] {own}/Length 0 >>\nstream\n\nendstream") + }) + .chain(std::iter::once(format!("<< /Font << /F0 {} >> >>", simple("TrueType", "Formed", "WinAnsiEncoding", 66, "600")))) + .collect(); + let names: Vec = (0..2 * n).map(|i| format!("/X{i} {} 0 R", extra + i)).collect(); + let page = PdfPage { resources: format!("/Font << /F0 {font} >> /XObject << {} >>", names.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let refs: Vec<&str> = forms.iter().map(String::as_str).collect(); + let w = walked(&pdf_with(&[page], &refs, None)); + assert!(w.fonts.contains_key("Shared") && w.fonts.contains_key("Formed")); + // The page's font and forms, and the shared dictionary's font. + assert!(w.looked <= 1 + 2 * n + 1, "{} entries looked at", w.looked); + // A thousand pages that share one font dictionary of 4000 entries. + let pages_n = 1000; + let extra = first_extra(pages_n); + let entries: Vec = (0..n).map(|i| format!("/F{i} {} 0 R", extra + 1 + i % 50)).collect(); + let objects: Vec = std::iter::once(format!("<< {} >>", entries.join(" "))) + .chain((0..50).map(|i| simple("TrueType", &format!("S{i}"), "WinAnsiEncoding", 65, "500"))) + .collect(); + let pages: Vec = + (0..pages_n).map(|_| PdfPage { resources: format!("/Font {extra} 0 R"), ..PdfPage::new(100.0, 100.0, "") }).collect(); + let refs: Vec<&str> = objects.iter().map(String::as_str).collect(); + let w = walked(&pdf_with(&pages, &refs, None)); + assert_eq!(w.fonts.len(), 50); + assert!(w.looked <= n, "{} entries looked at", w.looked); + } + + /// Past [`super::MAX_FONTS`] fonts no more entries are looked at. + #[test] + fn fonts_past_the_most_read_are_not_looked_at() { + let fonts: Vec = + (0..super::MAX_FONTS + 100).map(|i| format!("/F{i} {}", simple("TrueType", &format!("N{i}"), "WinAnsiEncoding", 65, "500"))).collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let w = walked(&pdf_with(&[page], &[], None)); + assert_eq!(w.fonts.len(), super::MAX_FONTS); + assert!(w.looked <= super::MAX_FONTS + 1, "{} entries looked at", w.looked); + } + + /// Past [`super::MAX_KEYS`] entries of resource dictionaries, none are looked at: a font + /// dictionary of more entries than that, all naming one font, is looked at that far. + #[test] + fn entries_past_the_most_looked_at_are_left() { + let extra = first_extra(1); + let entries: Vec = (0..super::MAX_KEYS + 1000).map(|i| format!("/F{i} {extra} 0 R")).collect(); + let page = PdfPage { resources: format!("/Font << {} >>", entries.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let w = walked(&pdf_with(&[page], &[&simple("TrueType", "Many", "WinAnsiEncoding", 65, "500")], None)); + assert_eq!(w.fonts.len(), 1); + assert!(w.looked <= super::MAX_KEYS + 1, "{} entries looked at", w.looked); + } + + /// A width array that fonts share by reference is read once for all of them: 128 composite + /// fonts naming one `W` and 128 simple fonts naming one `Widths`, each of 100,000 numbers. + #[test] + fn a_width_array_fonts_share_is_read_once() { + let numbers = 100_000; + let big: String = std::iter::repeat_n("500 ", numbers).collect(); + let extra = first_extra(1); + let cmap = "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfrange\n<0000> <00FF> <0041>\nendbfrange\nendcmap\n"; + let fonts: Vec = (0..256) + .map(|i| { + if i % 2 == 0 { + format!( + "/F{i} << /Type /Font /Subtype /Type0 /BaseFont /W{i} /Encoding /Identity-H /ToUnicode {} 0 R \ + /DescendantFonts [<< /Subtype /CIDFontType2 /W {extra} 0 R >>] >>", + extra + 1 + ) + } else { + format!( + "/F{i} << /Type /Font /Subtype /TrueType /BaseFont /S{i} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths {} 0 R >>", + extra + 2 + ) + } + }) + .collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let file = pdf_with( + &[page], + &[&format!("[0 [{big}]]"), &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()), &format!("[{big}]")], + None, + ); + let w = walked(&file); + assert_eq!(w.arrays_read, 2); + assert!(w.width_text <= 2 * (big.len() + 10), "{} bytes of width arrays read", w.width_text); + assert_eq!(w.fonts.len(), 256); + assert!(w.fonts.values().all(|f| f.as_ref().is_some_and(|f| f.get(&'A') == Some(&500.0)))); + } + + /// Past [`super::MAX_WIDTH_TEXT`] bytes of width arrays no more are read: of six fonts each with + /// an array of a million bytes, the sixth gives no widths. + #[test] + fn width_arrays_past_the_most_read_are_left() { + let big: String = std::iter::repeat_n("500 ", 250_000).collect(); + let extra = first_extra(1); + let fonts: Vec = (0..6) + .map(|i| { + format!( + "/F{i} << /Type /Font /Subtype /TrueType /BaseFont /M{i} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths {} 0 R >>", + extra + i + ) + }) + .collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let arrays: Vec = (0..6).map(|_| format!("[{big}]")).collect(); + let refs: Vec<&str> = arrays.iter().map(String::as_str).collect(); + let w = walked(&pdf_with(&[page], &refs, None)); + assert_eq!(w.arrays_read, 5); + assert_eq!(w.fonts.values().filter(|f| f.as_ref().is_some_and(|f| !f.is_empty())).count(), 5); + } + + /// [`crate::import_scan::cid_ranges`] gives each CID of a `W` its values, a list's in turn (an + /// incomplete last group left out) and a range's to each, and reads no more of a long list than + /// the CIDs it takes. + #[test] + fn cid_ranges_give_each_cid_its_values() { + let extra = first_extra(1); + let long: String = std::iter::repeat_n("7 ", 70_000).collect(); + let arrays = ["[1 [10 20 30] 100 102 7]".to_string(), "[1 [1 2 3 4 5 6 7]]".to_string(), format!("[0 [{long}]]")]; + let page = PdfPage { + resources: format!("/Properties << /A {extra} 0 R /B {} 0 R /C {} 0 R >>", extra + 1, extra + 2), + ..PdfPage::new(10.0, 10.0, "") + }; + let refs: Vec<&str> = arrays.iter().map(String::as_str).collect(); + let file = pdf_with(&[page], &refs, None); + let o = crate::open_pdf(&file, None).unwrap(); + let pages = o.pdf.pages(); + let props = &pages.iter().next().unwrap().resources().properties; + let ranges = |key: &str, per: usize| { + let mut out = vec![]; + crate::import_scan::cid_ranges(&props.get::>(key).unwrap(), per, |cid, v| { + out.push((cid, v.to_vec())) + }); + out + }; + let one = |v: &[(u32, f64)]| v.iter().map(|(c, w)| (*c, vec![*w])).collect::>(); + assert_eq!(ranges("A", 1), one(&[(1, 10.0), (2, 20.0), (3, 30.0), (100, 7.0), (101, 7.0), (102, 7.0)])); + assert_eq!(ranges("B", 3), [(1, vec![1.0, 2.0, 3.0]), (2, vec![4.0, 5.0, 6.0])]); + assert_eq!(ranges("C", 1).len(), 65_536); + } + + /// A `ToUnicode` map written plain and longer than the limits is charged no more than a + /// decoded one could be: the small maps of the other fonts are still read. + #[test] + fn a_long_plain_map_leaves_the_others_read() { + let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n"); + while big.len() <= super::MAX_TO_UNICODE_TOTAL + 1000 { + big.push_str("1 beginbfchar\n<0001> <0041>\nendbfchar\n"); + } + big.push_str("endcmap\n"); + let small = "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfchar\n<0001> <0042>\nendbfchar\nendcmap\n"; + let extra = first_extra(1); + let cid = |name: &str, map: usize| { + format!( + "<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R /DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500]] >>] >>", + extra + map + ) + }; + let n = 40; + let fonts: Vec = + std::iter::once(format!("/A {}", cid("Big", 0))).chain((0..n).map(|i| format!("/F{i} {}", cid(&format!("Small{i}"), 1 + i)))).collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let objects: Vec = std::iter::once(format!("<< /Length {} >>\nstream\n{big}endstream", big.len())) + .chain((0..n).map(|_| format!("<< /Length {} >>\nstream\n{small}endstream", small.len()))) + .collect(); + let refs: Vec<&str> = objects.iter().map(String::as_str).collect(); + let w = walked(&pdf_with(&[page], &refs, None)); + assert!(w.fonts.get("Big").is_some_and(Option::is_none) || !w.fonts.contains_key("Big")); + assert_eq!((0..n).filter(|i| w.fonts.get(&format!("Small{i}")).is_some_and(|f| f.as_ref().is_some_and(|m| !m.is_empty()))).count(), n); + assert!(w.decoded <= super::MAX_TO_UNICODE + 1 + n * small.len(), "{} bytes charged", w.decoded); + } + + /// A `ToUnicode` map is parsed once however many fonts name it, and one longer than + /// [`super::MAX_TO_UNICODE`] decoded is left unread, whether its stream is written plain or + /// compressed: its fonts give no widths. + #[test] + fn a_to_unicode_map_is_read_once_and_only_up_to_its_limit() { + use std::io::Write as _; + let small = + "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfchar\n<0001> <0041>\nendbfchar\nendcmap\n".to_string(); + let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n"); + while big.len() <= super::MAX_TO_UNICODE { + big.push_str("1 beginbfchar\n<0001> <0041>\nendbfchar\n"); + } + big.push_str("endcmap\n"); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + z.write_all(big.as_bytes()).unwrap(); + let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02X}")).collect(); + let extra = first_extra(1); + let cid = |name: &str, map: usize| { + format!( + "<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \ + /DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500]] >>] >>", + extra + map + ) + }; + let fonts: Vec = (0..64).map(|i| format!("/F{i} {}", cid(&format!("U{i}"), i % 3))).collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let file = pdf_with( + &[page], + &[ + &format!("<< /Length {} >>\nstream\n{small}endstream", small.len()), + &format!("<< /Length {} >>\nstream\n{big}endstream", big.len()), + &format!("<< /Length {} /Filter [/ASCIIHexDecode /FlateDecode] >>\nstream\n{hex}>\nendstream", hex.len() + 1), + ], + None, + ); + let w = walked(&file); + assert_eq!(w.maps.len(), 3, "each map parsed once"); + // Each long one charged up to just past the limit. + assert!(w.decoded <= small.len() + 2 * (super::MAX_TO_UNICODE + 1), "{} bytes charged", w.decoded); + assert_eq!(w.maps.values().filter(|m| m.is_some()).count(), 1, "the long ones left unread"); + let widths = crate::open_pdf(&file, None).unwrap().page_widths(); + assert_eq!(widths.widths("U0").map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::>()), Some(vec![('A', 500.0)])); + assert!(widths.widths("U1").is_none() && widths.widths("U2").is_none()); + // Every font of the name shares one map of its widths. + assert!(std::sync::Arc::ptr_eq(widths.widths("U0").unwrap(), widths.clone().widths("U0").unwrap())); + } +} diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 64e6217148..1c9a2c3908 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -276,6 +276,13 @@ impl Opened { crate::file_info::file_info_in(&self.pdf) } + /// The widths the pages give the characters of the fonts they set type in, from the fonts' + /// dictionaries ([`crate::PageWidths`]), without importing any page's art. + pub fn page_widths(&self) -> crate::PageWidths { + let pages = self.pdf.pages(); + crate::page_widths::page_widths(pages.iter().map(|p| p.resources())) + } + /// How many pages the PDF has, as [`info`] lists them. pub fn page_count(&self) -> usize { self.pdf.pages().len() diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0cc9985a9c..3e87bbb974 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (`.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where several copies share its PostScript name, follows #6983; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -59,7 +59,7 @@ private editing data. VectorCraft: and the paragraph's hyphenation options and tab stops. Stroked type keeps its stroke's cap, join and miter limit. Type filled or stroked with a pattern keeps its pattern, placed in the document as a path's pattern fill would be: a character's paint names an art style of one paint, and the pattern is in that style (its colour in the text document is black). A pattern the file - doesn't define, or a style that isn't a pattern, keeps the colour as before. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one + doesn't define, or a style that isn't a pattern, keeps the colour as before. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. A record that keeps no version, in a `.ai` with a PDF part, takes among those faces the first that sets the characters the PDF part draws in that font (the first 512 in code-point order) each within 1/1000 em of the width the PDF part gives it (its `Widths` or `W`, each code's character from the font's `ToUnicode` map or, for a simple font without one, `WinAnsiEncoding`): two copies can share a name, family and style and set the type at other widths (two releases of one font). Without such widths, or with no face that sets them all, it takes the first, as before. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one frame whose last lines the file sets but which don't fit here (the fallback font, or a descent past the frame's bottom) 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, with a warning when it does. RGB in the PDF page's `ICCBased` spaces keeps the file's numbers in a `.ai` (the `uncalibrated_rgb` @@ -361,6 +361,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | `.ai` import: type from the text document whose font record keeps no version (no key 5), where several installed faces answer to the record's PostScript name, is set in the one whose advances match the widths the file's PDF part gives the characters it draws in that font: the case #6983 left out, two copies of one PostScript name, family and style (two releases of one font) that differ only in their widths. The PDF part's fonts are read from their dictionaries alone, without importing its pages (`Opened::page_widths`, which looks into the forms they draw too): a simple font's `Widths` from its `FirstChar`, a composite font's descendant's `W` under an `Identity-H` or `Identity-V` CMap, each code's character from the font's `ToUnicode` map or, for a simple font without one, `WinAnsiEncoding` (ISO 32000-1 §9.6.2, §9.7.4.3, §9.10.3, Annex D.2), by `BaseFont` without its subset prefix. A code 0 wide is one the subset doesn't use and is left out; a font whose subsets give one character two widths gives none. Each resource dictionary is walked once, though pages and forms share it, and at most 65,536 of their entries (for the whole file, all pages together), 256 fonts and 4,096 forms are looked at; a width array that fonts share by reference is read once, and no more are read past 4 MB of them; a `ToUnicode` map is parsed once for all the fonts that name it, and one longer than 256 KB decoded, or past 4 MB of maps in all (each charged at most what could be decoded of it), is left unread. All the records of one font share its widths and the face they resolve to, so a text document of many records of one font holds one copy of them. Of the faces `postscript_face` finds for the name, the first that sets those characters (the first 512 of them in code-point order) each within 1/1000 em of its width takes the type, and the type names its version as before. With no widths for the font, one face, a version in the record (installed or not), or no face that sets them all, the face is the one taken before; each record is still resolved once. It applies whether the layers open alone, with the PDF part imported, or from the editing data alone beside a PDF part that is only type; a `.ai` saved without its PDF part, EPS and legacy `.ai` are unchanged. On 224 users' files (used locally, never committed), 332 font records have widths to compare: 299 already took a face that sets every character within 1/1000 em, 29 have none that does and keep their face, 1 keeps the version its record names, and 3 (one font installed in two releases, in 3 files) change copy, from up to 66/1000 em off the page to within 0.5/1000 em. Those 3 renders at 40 ppi, and no others, change, all closer to the file's own page (30.0% → 24.5%, 18.0% → 12.3% and 1.03% → 0.02% of the page differing; in the first two only that font's type changes, and the rest that differs is untouched); envelopes of type that open live go from 185 to 186, none fewer in any file; no file opens another way; in one file the note on type in an envelope gives way to the note of how far the layers differ from the page (0.2%), as its envelope now opens live. Tests: `page_widths::tests::the_pages_give_each_font_the_widths_of_its_characters`, `shared_resources_are_walked_once`, `fonts_past_the_most_read_are_not_looked_at`, `a_to_unicode_map_is_read_once_and_only_up_to_its_limit`, `a_long_plain_map_leaves_the_others_read`, `a_width_array_fonts_share_is_read_once`, `width_arrays_past_the_most_read_are_left`, `cid_ranges_give_each_cid_its_values` (`vectorcraft-pdf`), `tests_native::type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths`, `ate::tests::records_of_one_font_share_its_page_widths_and_answer` (`vectorcraft-eps`), `tests_aiimport::type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in`, `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save`, and the fuzz target `import_fuzz::pdf_font_widths_never_panic` (`vectorcraft-engine`). Scores unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) came in with butt caps, miter joins and a miter limit of 10 whatever the file stroked it with, while paths kept the graphics state's. The characters' stroke now takes the line cap (`J`), line join (`j`) and miter limit (`M`) of the graphics state, as a path's stroke does, and glyphs stroked with other ones start a run of their own, also a glyph filled and then stroked otherwise than the run its fill joined, so the glyphs before it keep their stroke (#7741). Test `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`. Scores and estimates unchanged. | | 2026-11-13 | minor | `.ai` and EPS import: layers that don't draw as the page, even with the drawn art of every live envelope put back, no longer put back the drawn art of every envelope of type. Each live envelope of type is weighed in the page check's own drawing of the pages it lies on, on the pixels that it and its drawn art ink there (the two drawn together on a layer of their own, without the rest of the layers; a pixel inks with an alpha above 8 of 255): it keeps its drawn art and its type, hidden, with the note, where the layers with it differ from the page in more of those pixels than its own check allows against its drawn art (10% of them, or 3% differing with all their neighbours, away from type), or where the envelopes of type that stay live, in the order they were read, would together differ there in more of a page than half of what the page check allows (a budget of the same size as the one their own checks share, kept apart from it). Art that differs elsewhere on the page no longer costs them their editable type; art that differs on their pixels still does. An envelope of type that a clip group or a clipping sublayer clips, an opacity mask masks, or a group with an appearance of its own, another envelope, a repeat or a blend holds keeps its drawn art as before, wherever it lies: drawn on its own it would be weighed elsewhere than it draws, and what holds it can draw it onto the page from off it. An envelope on no page stays live, as the page check doesn't see it, unless the page holds all the art that prints (an EPS's page that is its art's box, where art past the page is compared too): there one reaching past the page keeps its drawn art. Past 12 of them on the pages, all keep it. This holds where the editing data is trusted, where the objects that differ come in as the page's art (the placed files' other placement weighed on its own, as it draws them elsewhere under or over the envelopes; layers that draw as the page with only the envelopes the page holds put back are used as they are; where none of the objects that differ can then come in as the page's art, because an object holds type, the drawn art of every envelope of type is put back and that is tried again, as before), and for a `.ai` whose layers would open alone, which still opens alone: its envelopes of type are all settled again as they were with the page, in the same order and with the same checks, so each that opens live draws as it was weighed, and those the page held get their drawn art back. Where putting the drawn art of every live envelope back makes the layers draw as the page, it is still put back (#5065). In 224 users' files (used locally, never committed): envelopes of type that open live go from 174 to 186, in 8 files, none fewer in any file; no file changes between its layers and its PDF part; 7 renders change, by at most 0.7% of their pixels at 40 ppi (1 closer to the page, 1 alike, 5 further, by at most 0.7 of a percentage point, where VectorCraft's own envelope draws a little apart from the drawn art, within its check); the note for type in an envelope goes from 6 files. Of the 14 envelopes of type that had opened live and lost it to the page check, 2 keep their drawn art: one where the page draws something else where it is, and one in a file that comes in as its PDF part (#7141). Tests `build::candidate_tests::the_page_holds_back_only_envelopes_of_type_where_it_differs_from_them`, `envelopes_of_type_stay_live_within_half_of_what_the_page_check_allows`, `an_envelope_of_type_differing_in_more_of_its_pixels_than_its_check_allows_is_held_back`, `envelopes_of_type_the_layers_dont_draw_in_place_are_held_back`, `on_a_page_that_holds_all_the_art_an_envelope_of_type_past_it_is_held_back`, `objects_come_in_as_the_page_art_with_every_envelope_of_type_put_back_where_a_live_one_holds_a_difference`, `tests_native::layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_doesnt_hold`, `trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_page_doesnt_hold_live`, `layers_with_objects_that_come_in_as_the_page_art_keep_an_envelope_of_type_that_draws_as_the_page_live`, `trusted_layers_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `trusted_layers_leave_an_envelope_of_type_the_page_draws_otherwise_its_drawn_art`, `build::candidate_tests::the_other_placement_of_placed_files_is_weighed_on_its_own`, `layers_that_draw_as_the_page_with_the_held_envelopes_of_type_put_back_are_used_so` | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f393c7b8d8..5eeaededb5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (`.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, follows #6983; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -61,6 +61,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | `.ai` import: type from the text document whose font record keeps no version, where installed copies of one PostScript name, family and style differ only in their widths, is set in the copy that sets the characters the file's PDF part draws at the widths the PDF part gives them, read from its font dictionaries without importing its pages (follows #6983; details in [file-format-parity.md](file-format-parity.md); tests in `crates/pdf/src/page_widths.rs`, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`, `records_of_one_font_share_its_page_widths_and_answer` in `crates/eps/src/import/ate.rs`, `type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in` and `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save` in `crates/engine/src/cmd/fileio/tests_aiimport.rs`, `pdf_font_widths_never_panic` in `crates/engine/tests/import_fuzz.rs`). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); area score and estimate unchanged. | From 5fb65f8448c5dc5443bc9d104c2c1a161cd633ed Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 16:53:26 +0000 Subject: [PATCH 02/91] pdf: page widths: a character's widths must all agree, not each the one before `Walk::add` compared each width a subset gave a character with the last one kept, and kept the new one. Widths that drift a little at a time (600, 600.8, 601.6) passed though the first and last are further apart than `SAME_WIDTH`, and the same subsets read in another order gave none. It now keeps the narrowest and widest width of each character and gives the font none once they are more than `SAME_WIDTH` apart; the width kept is the first one read. Test `widths_that_drift_apart_over_several_subsets_give_none`. Co-Authored-By: Claude Opus 5.5 --- crates/pdf/src/page_widths.rs | 49 +++++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/pdf/src/page_widths.rs b/crates/pdf/src/page_widths.rs index aa1f122fcd..2632aa5449 100644 --- a/crates/pdf/src/page_widths.rs +++ b/crates/pdf/src/page_widths.rs @@ -76,6 +76,8 @@ type CidWidths = Rc<[(u32, f32)]>; struct Walk { /// Each font's characters and widths; `None` when two subsets disagree. fonts: HashMap>, + /// The narrowest and widest width given each character of each font so far. + bounds: HashMap>, /// The font dictionaries, form XObjects and resource dictionaries already looked at. seen_fonts: HashSet<(usize, usize)>, seen_forms: HashSet, @@ -96,18 +98,23 @@ struct Walk { } impl Walk { - /// Note `widths`, characters of the font of PostScript name `name` and their widths. A width - /// another subset gave the character already must be the same. + /// Note `widths`, characters of the font of PostScript name `name` and their widths. All the + /// widths given one character, by this and the other subsets, must be the same: no two more + /// than [`SAME_WIDTH`] apart. fn add(&mut self, name: String, widths: Vec<(char, f32)>) { - let slot = self.fonts.entry(name).or_insert_with(|| Some(BTreeMap::new())); + let slot = self.fonts.entry(name.clone()).or_insert_with(|| Some(BTreeMap::new())); let Some(have) = slot else { return }; + let bounds = self.bounds.entry(name).or_default(); for (c, w) in widths { - if have.get(&c).is_some_and(|was| (was - w).abs() > SAME_WIDTH) { - *slot = None; - return; - } - if have.len() < MAX_CHARS { + if let Some((lo, hi)) = bounds.get_mut(&c) { + (*lo, *hi) = (lo.min(w), hi.max(w)); + if *hi - *lo > SAME_WIDTH { + *slot = None; + return; + } + } else if have.len() < MAX_CHARS { have.insert(c, w); + bounds.insert(c, (w, w)); } } } @@ -488,6 +495,32 @@ mod tests { assert_eq!(w.fonts.values().filter(|f| f.as_ref().is_some_and(|f| !f.is_empty())).count(), 5); } + /// Widths that drift past [`super::SAME_WIDTH`] over several subsets are two widths, though + /// each lies within it of the one read before: subsets giving `A` 600, 600.8 and 601.6 give the + /// font none, as do subsets giving `B` 501.5, 500.6 and 500. Two within it still give one. Each + /// subset is on a page of its own, so they are read in turn (a font dictionary's entries come in + /// no set order). + #[test] + fn widths_that_drift_apart_over_several_subsets_give_none() { + let tags = ["AAAAAA", "BBBBBB", "CCCCCC"]; + let pages: Vec = (0..3) + .map(|i| { + let mut fonts = vec![ + format!("/D {}", simple("TrueType", &format!("{}+Drift", tags[i]), "WinAnsiEncoding", 65, ["600", "600.8", "601.6"][i])), + format!("/B {}", simple("TrueType", &format!("{}+Back", tags[i]), "WinAnsiEncoding", 65, ["0 501.5", "0 500.6", "0 500"][i])), + ]; + if i < 2 { + fonts.push(format!("/S {}", simple("TrueType", &format!("{}+Steady", tags[i]), "WinAnsiEncoding", 65, ["600", "600.8"][i]))); + } + PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") } + }) + .collect(); + let widths = crate::open_pdf(&pdf_with(&pages, &[], None), None).unwrap().page_widths(); + assert!(widths.widths("Drift").is_none()); + assert!(widths.widths("Back").is_none()); + assert!(widths.widths("Steady").is_some_and(|w| w.contains_key(&'A'))); + } + /// [`crate::import_scan::cid_ranges`] gives each CID of a `W` its values, a list's in turn (an /// incomplete last group left out) and a range's to each, and reads no more of a long list than /// the CIDs it takes. From 51ce7e9b9df5483b79102a619f2cc046b5ca41f7 Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 16:53:26 +0000 Subject: [PATCH 03/91] pdf: page widths: a ToUnicode map that can't be read gives no widths A simple font in `WinAnsiEncoding` whose `ToUnicode` map was left unread (past the size limits, or not a map at all) took its characters from the encoding, as a font without a map does, so a code the map gives another character lent its width to the encoding's. Only a font with no `ToUnicode` entry now falls back to its encoding; one whose map can't be read gives no widths. Test `a_to_unicode_map_that_cant_be_read_gives_no_widths`. Co-Authored-By: Claude Opus 5.5 --- crates/pdf/src/page_widths.rs | 38 ++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/pdf/src/page_widths.rs b/crates/pdf/src/page_widths.rs index 2632aa5449..8f63f91f95 100644 --- a/crates/pdf/src/page_widths.rs +++ b/crates/pdf/src/page_widths.rs @@ -246,7 +246,13 @@ fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32) let name = without_subset_tag(&font_name(f)?).to_string(); let composite = subtype.as_ref() == b"Type0"; let encoding = f.get::>(b"Encoding"); - let to_unicode = f.get::>(b"ToUnicode").and_then(|s| walk.character_map(&s)); + // Only a font without a `ToUnicode` map falls back to its encoding: one whose map can't be + // read gives none. + let to_unicode = match f.get::>(b"ToUnicode") { + Some(s) => Some(walk.character_map(&s)?), + None if f.contains_key(b"ToUnicode") => return None, + None => None, + }; let win_ansi = !composite && encoding.as_ref().is_some_and(|e| e.as_ref() == b"WinAnsiEncoding"); if to_unicode.is_none() && !win_ansi { return None; @@ -521,6 +527,36 @@ mod tests { assert!(widths.widths("Steady").is_some_and(|w| w.contains_key(&'A'))); } + /// Only a simple font without a `ToUnicode` map takes its characters from `WinAnsiEncoding`: + /// one whose map is left unread (longer than [`super::MAX_TO_UNICODE`]) or isn't a stream gives + /// no widths. + #[test] + fn a_to_unicode_map_that_cant_be_read_gives_no_widths() { + let mut big = String::from("begincmap\n1 begincodespacerange\n<00> \nendcodespacerange\n"); + while big.len() <= super::MAX_TO_UNICODE { + big.push_str("1 beginbfchar\n<41> <0042>\nendbfchar\n"); + } + big.push_str("endcmap\n"); + let extra = first_extra(1); + let font = |name: &str, to_unicode: &str| { + format!("<< /Type /Font /Subtype /TrueType /BaseFont /{name} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths [600]{to_unicode} >>") + }; + let page = PdfPage { + resources: format!( + "/Font << /F0 {} /F1 {} /F2 {} >>", + font("Unread", &format!(" /ToUnicode {extra} 0 R")), + font("Named", " /ToUnicode /Identity-H"), + font("Plain", "") + ), + ..PdfPage::new(100.0, 100.0, "") + }; + let file = pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{big}endstream", big.len())], None); + let widths = crate::open_pdf(&file, None).unwrap().page_widths(); + assert!(widths.widths("Unread").is_none()); + assert!(widths.widths("Named").is_none()); + assert_eq!(widths.widths("Plain").map(|w| w.get(&'A').copied()), Some(Some(600.0))); + } + /// [`crate::import_scan::cid_ranges`] gives each CID of a `W` its values, a list's in turn (an /// incomplete last group left out) and a range's to each, and reads no more of a long list than /// the CIDs it takes. From 5f9017da2e79f15d81673c03261e9cf594c3104f Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 23:02:24 +0000 Subject: [PATCH 04/91] docs: note the installed copy that sets the PDF part's widths (#8087) in the File formats rows and evidence The area rows and the evidence list name the change and its tests, as AGENTS.md asks of a change that lands. Scores and estimates unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/target-app-parity.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5eeaededb5..445f967b5f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -270,9 +270,9 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on guide and blend spine rows (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | @@ -535,7 +535,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, row menu commands beyond Collect for Export (now on every layer, sublayer, group and object row), menus on guide and blend spine rows, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | | Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812; distance and angle labels while drawing, #2983) | 2–4; status-bar X/Y uses the active ruler origin and General units | -| File formats | 6 | 85% | PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | +| File formats | 6 | 85% | `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (#8087, follows #6983; scores and estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done, as are the Japanese papers in its Media list: JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判, beside the ISO B4/B5 that settings saved before them keep) | 1–2 | | Automation | 3 | 65% | scripting surface, batch (MCP drops malformed app replies without replay; Variables: text/visibility variables bound to objects, an object may carry several, dataset rows applied in one undo step, panel and Window › Variables with dialogs; image/graph kinds and dataset import/export open) | 6–10 | @@ -585,6 +585,8 @@ since 2026-10-01. ## Evidence: what ships today, by area +- **`.ai` type in the copy its PDF part sets (#8087, follows #6983):** `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs` covers two installed copies of one font that differ only in their widths: type whose font record keeps no version is set in the copy that sets the characters at the widths the PDF part gives them. `records_of_one_font_share_its_page_widths_and_answer` in `crates/eps/src/import/ate.rs` checks that records of one font share those widths and the answer. The tests in `crates/pdf/src/page_widths.rs` cover reading the widths from the font dictionaries alone (simple and composite fonts, `ToUnicode` maps, `WinAnsiEncoding`, forms) within the file's bounds; a font whose subsets give a character widths more than 1/1000 em apart, or whose `ToUnicode` map can't be read, gives none. `type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in` and `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save` in `crates/engine/src/cmd/fileio/tests_aiimport.rs` cover opening and a save and reopen; `pdf_font_widths_never_panic` in `crates/engine/tests/import_fuzz.rs` feeds hostile font dictionaries. Synthetic files written in the tests, with the copies of a font the test installs itself; no fixtures added. Scores and hours unchanged. + - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. From 931b0cd469e7208ce87104aa9d803c503c642851 Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 23:10:34 +0000 Subject: [PATCH 05/91] docs: the first File formats row names the saved editing copy's limits (#868) It still said Illustrator's editing data isn't written, while the other two File formats rows give what a saved `.ai`'s editing copy leaves out. It now has their words. Scores and estimates unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 445f967b5f..b220c8b45a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -270,7 +270,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on guide and blend spine rows (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | From 40d1bef059fe2ae4389a8083da6e03e528c2cea3 Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 23:45:35 +0000 Subject: [PATCH 06/91] docs: roadmap M4 Files row notes #8087 The status line, the M4 Files row and the revision history name the change, as AGENTS.md asks of a change that lands. Estimates unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/roadmap.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index bfaa10db30..d71364fe34 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, #8087; scores and estimates unchanged; previously: M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -160,7 +160,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | -| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | @@ -212,6 +212,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | M4: `.ai` import (#8087, follows #6983): type from the text document whose font record keeps no version, where installed copies of one font differ only in their widths, is set in the copy that sets the characters at the widths the file's PDF part gives them; details in [file-format-parity.md](file-format-parity.md). Scores and estimates unchanged. | | 2026-11-16 | minor | M1: rows or the selected-art square dragged over the Layers panel's list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | From 400b4c96f9942a57616eb5be474b87591e3a9dcd Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 17 Nov 2026 06:09:11 +0000 Subject: [PATCH 07/91] pdf: page widths: bound the work of looking up a font's characters In the pinned CMap, each lookup of a code in a `bfrange` copies the range's whole destination and decodes it, so a `ToUnicode` map under the 256 KB limit with one long destination, shared by many fonts whose `W` names every CID, cost millions of long copies. `MAX_CHARS` didn't stop it, since such lookups give no character. - A `ToUnicode` map holding a string longer than 128 bytes decoded (`MAX_DESTINATION`: hex, literal, or any ASCII85 string, whose `z` stands for four bytes), or written as a binary CMap, is left unread, as one past the size limits is: its fonts give no widths. The scan steps over dictionaries (`<<`) and comments as the CMap reader does. - A composite font looks up at most `MAX_LOOKUPS` (16,384) of its codes with a width, in `W` order, and keeps what it found among them. Tests `a_to_unicode_map_with_a_long_destination_is_left_unread` and `codes_past_the_most_looked_up_are_left`, each failing without its part. Co-Authored-By: Claude Opus 5.5 --- crates/pdf/src/page_widths.rs | 159 ++++++++++++++++++++++++++++++++-- 1 file changed, 153 insertions(+), 6 deletions(-) diff --git a/crates/pdf/src/page_widths.rs b/crates/pdf/src/page_widths.rs index 8f63f91f95..eb2ab53ff5 100644 --- a/crates/pdf/src/page_widths.rs +++ b/crates/pdf/src/page_widths.rs @@ -33,6 +33,13 @@ const MAX_CHARS: usize = 4096; const MAX_TO_UNICODE: usize = 256 << 10; /// The most bytes of `ToUnicode` maps decoded, all fonts together. const MAX_TO_UNICODE_TOTAL: usize = 4 << 20; +/// The longest string a `ToUnicode` map read may hold, decoded, in bytes: a destination is a +/// character or a short run of them (a ligature's), and each lookup of a code in a range copies its +/// range's whole destination. A map with a longer one is left unread. +const MAX_DESTINATION: usize = 128; +/// The most codes of a composite font whose characters are looked up (its first, in `W` order): +/// [`MAX_CHARS`] bounds the characters kept, not the codes looked at to find them. +const MAX_LOOKUPS: usize = 4 * MAX_CHARS; /// How far apart two widths a file gives one character of one font may be and still be one width, /// in thousandths of an em: files write widths rounded. const SAME_WIDTH: f32 = 1.0; @@ -127,7 +134,8 @@ impl Walk { /// The `ToUnicode` map `s`, parsed once however many fonts name it: `None` when it decodes to /// more than [`MAX_TO_UNICODE`] bytes, when the maps decoded so far reach - /// [`MAX_TO_UNICODE_TOTAL`], or when it can't be read. A map is charged what was decoded of it, + /// [`MAX_TO_UNICODE_TOTAL`], when it holds a string longer than [`MAX_DESTINATION`], or when it + /// can't be read. A map is charged what was decoded of it, /// at most the limit: a stream written plain comes back whole without being decoded. fn character_map(&mut self, s: &Stream<'_>) -> Option> { let id = s.obj_id(); @@ -135,7 +143,9 @@ impl Walk { let left = MAX_TO_UNICODE_TOTAL.saturating_sub(self.decoded).min(MAX_TO_UNICODE + 1); let data = s.decoded_within(left).ok(); self.decoded += data.as_ref().map_or(left, |d| d.len().min(left)); - let map = data.filter(|d| d.len() < left && d.len() <= MAX_TO_UNICODE).and_then(|d| CMap::parse(&d, |_| None)); + let map = data + .filter(|d| d.len() < left && d.len() <= MAX_TO_UNICODE && !d.starts_with(b"bcmap") && longest_string(d) <= MAX_DESTINATION) + .and_then(|d| CMap::parse(&d, |_| None)); self.maps.insert(id, map.map(Rc::new)); } self.maps.get(&id)?.clone() @@ -233,7 +243,8 @@ fn walk<'a>(pages: impl IntoIterator>) -> Walk { } /// The PostScript name of font `f` (its `BaseFont` without a subset prefix) and the width of each -/// character it names, at most [`MAX_CHARS`]. A code's character comes from the font's `ToUnicode` +/// character it names, at most [`MAX_CHARS`] (of a composite font, among its first [`MAX_LOOKUPS`] +/// codes with a width). A code's character comes from the font's `ToUnicode` /// map or, for a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding; /// a composite font's codes are its CIDs, so only under an `Identity-H` or `Identity-V` CMap. A /// width of 0 is a code the subset doesn't use, and is left out. `None` for a Type 3 font (its @@ -271,11 +282,14 @@ fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32) return None; } let d = f.get::>(b"DescendantFonts").and_then(|a| a.iter::>().next())?; + let mut looked = 0; for (cid, w) in walk.cid_widths(&d)?.iter() { - if widths.len() >= MAX_CHARS { + if widths.len() >= MAX_CHARS || looked >= MAX_LOOKUPS { break; } - if let (Some(c), Some(w)) = (char_of(*cid), width(*w)) { + let Some(w) = width(*w) else { continue }; + looked += 1; + if let Some(c) = char_of(*cid) { widths.push((c, w)); } } @@ -283,7 +297,8 @@ fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32) let first = f.get::(b"FirstChar")?; // A simple font's codes are bytes. for (code, w) in (first..256).zip(walk.simple_widths(f)?.iter()) { - if let (Some(c), Some(w)) = (char_of(code), width(*w)) { + let Some(w) = width(*w) else { continue }; + if let Some(c) = char_of(code) { widths.push((c, w)); } } @@ -291,6 +306,63 @@ fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32) Some((name, widths)) } +/// The decoded length, in bytes, of the longest string in CMap text `data`: a hex string's digits +/// halved, or a literal string's bytes (escapes counted as written, so at least its length). A `<<` +/// opens a dictionary, not a string, and a `%` outside a string starts a comment. An ASCII85 +/// string (`<~`), which no `ToUnicode` map writes and whose `z` stands for four bytes, counts as +/// longer than any. +fn longest_string(data: &[u8]) -> usize { + let mut longest = 0; + let mut i = 0; + while let Some(&b) = data.get(i) { + i += 1; + let len = match b { + b'%' => { + while data.get(i).is_some_and(|b| !matches!(b, b'\n' | b'\r')) { + i += 1; + } + continue; + } + b'<' if data.get(i) == Some(&b'~') => return usize::MAX, + b'<' if data.get(i) == Some(&b'<') => { + i += 1; + continue; + } + b'<' => { + let mut digits = 0; + while let Some(&b) = data.get(i) { + i += 1; + if b == b'>' { + break; + } + digits += usize::from(b.is_ascii_hexdigit()); + } + digits.div_ceil(2) + } + b'(' => { + let (mut depth, mut len) = (1usize, 0); + while let Some(&b) = data.get(i) { + i += 1; + match b { + b'\\' => i += 1, + b'(' => depth += 1, + b')' => depth -= 1, + _ => {} + } + if depth == 0 { + break; + } + len += 1; + } + len + } + _ => continue, + }; + longest = longest.max(len); + } + longest +} + /// The character of code `code` in `WinAnsiEncoding` (ISO 32000-1 Annex D.2), which is Windows-1252 /// but for the codes it leaves unused: `None` for those, for the controls, and for 160 and 173, which /// it gives the space and the hyphen a second time. @@ -557,6 +629,81 @@ mod tests { assert_eq!(widths.widths("Plain").map(|w| w.get(&'A').copied()), Some(Some(600.0))); } + /// A `ToUnicode` map with a destination longer than [`super::MAX_DESTINATION`] is left unread, + /// though the whole map is under [`super::MAX_TO_UNICODE`]: each lookup of a code in its range + /// would copy the whole destination. A hex destination of 60,000 characters, a literal one of + /// 600, and ASCII85 ones (`z` stands for four bytes, and one can hide the rest of its line + /// behind a `%` the pre-scan would take for a comment) are all left unread. A map with a long + /// name in a dictionary (`<<`) and a comment with an unclosed `(`, more than the limit before + /// the map's end, is still read. + #[test] + fn a_to_unicode_map_with_a_long_destination_is_left_unread() { + let head = "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfchar\n<0001> <0041>\nendbfchar\n"; + let range = |dst: &str| format!("{head}1 beginbfrange\n<0100> <01FF> {dst}\nendbfrange\nendcmap\n"); + let hex = range(&format!("<{}>", "0042".repeat(60_000))); + let literal = range(&format!("({})", "B".repeat(600))); + let zeros = range(&format!("<~{}~>", "z".repeat(1_000))); + let hidden = format!("{head}<~>%~> 1 beginbfrange <0100> <01FF> <{}> endbfrange\nendcmap\n", "0042".repeat(300)); + let padding = "1 beginbfchar\n<0002> <0042>\nendbfchar\n".repeat(10); + let short = format!( + "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 /{} 1 >> def\n% (an unclosed comment\n{head}{padding}endcmap\n", + "A".repeat(600) + ); + assert!(hex.len() < super::MAX_TO_UNICODE); + let extra = first_extra(1); + let names = ["Hex", "Literal", "Zeros", "Hidden", "Short"]; + let fonts: Vec = names + .iter() + .enumerate() + .map(|(i, name)| { + format!( + "/{name} << /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \ + /DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500] 256 511 500] >>] >>", + extra + i + ) + }) + .collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let maps: Vec = + [hex, literal, zeros, hidden, short].iter().map(|m| format!("<< /Length {} >>\nstream\n{m}endstream", m.len())).collect(); + let refs: Vec<&str> = maps.iter().map(String::as_str).collect(); + let file = pdf_with(&[page], &refs, None); + let widths = crate::open_pdf(&file, None).unwrap().page_widths(); + for unread in ["Hex", "Literal", "Zeros", "Hidden"] { + assert!(widths.widths(unread).is_none(), "{unread}"); + } + let short = widths.widths("Short").map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::>()); + assert_eq!(short, Some(vec![('A', 500.0)])); + } + + /// Past [`super::MAX_LOOKUPS`] codes of a composite font, no more are looked up, though few of + /// them gave a character: of two fonts whose `W` gives all 65,536 CIDs a width, the one whose + /// map gives CID 1 a character gives its width, and the one whose map only gives CID 20,000 one + /// gives none. + #[test] + fn codes_past_the_most_looked_up_are_left() { + let cmap = |code: &str| { + format!("begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfchar\n<{code}> <0041>\nendbfchar\nendcmap\n") + }; + const { assert!(20_000 > super::MAX_LOOKUPS) }; + let extra = first_extra(1); + let font = |name: &str, map: usize| { + format!( + "/{name} << /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \ + /DescendantFonts [<< /Subtype /CIDFontType2 /W {} 0 R >>] >>", + extra + map, + extra + 2 + ) + }; + let page = PdfPage { resources: format!("/Font << {} {} >>", font("Near", 0), font("Far", 1)), ..PdfPage::new(100.0, 100.0, "") }; + let maps: Vec = + ["0001", "4E20"].iter().map(|c| cmap(c)).map(|m| format!("<< /Length {} >>\nstream\n{m}endstream", m.len())).collect(); + let file = pdf_with(&[page], &[&maps[0], &maps[1], "[0 65535 500]"], None); + let widths = crate::open_pdf(&file, None).unwrap().page_widths(); + assert_eq!(widths.widths("Near").map(|w| w.get(&'A').copied()), Some(Some(500.0))); + assert!(widths.widths("Far").is_none()); + } + /// [`crate::import_scan::cid_ranges`] gives each CID of a `W` its values, a list's in turn (an /// incomplete last group left out) and a range's to each, and reads no more of a long list than /// the CIDs it takes. From c04ffd5f3fa4b58328b81251794b46b63108e1d6 Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 17 Nov 2026 07:41:26 +0000 Subject: [PATCH 08/91] docs: roadmap: the copy pick's fallback and its 512 characters (#8087) The status line and the revision history said type is set in the copy that sets its characters at the PDF part's widths. The pick compares the first 512 characters, and without those widths, or with no copy that sets them all, it is the one before; both entries now say so. Co-Authored-By: Claude Opus 5.5 --- docs/roadmap.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index d71364fe34..d9d03a3300 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, #8087; scores and estimates unchanged; previously: M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), #8087; scores and estimates unchanged; previously: M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -212,7 +212,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| -| 2026-11-16 | minor | M4: `.ai` import (#8087, follows #6983): type from the text document whose font record keeps no version, where installed copies of one font differ only in their widths, is set in the copy that sets the characters at the widths the file's PDF part gives them; details in [file-format-parity.md](file-format-parity.md). Scores and estimates unchanged. | +| 2026-11-16 | minor | M4: `.ai` import (#8087, follows #6983): type from the text document whose font record keeps no version, where installed copies of one font differ only in their widths, is set in the copy that sets the characters at the widths the file's PDF part gives them, compared on its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before; details in [file-format-parity.md](file-format-parity.md). Scores and estimates unchanged. | | 2026-11-16 | minor | M1: rows or the selected-art square dragged over the Layers panel's list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | From 76892e8abfc540cf4b6d89e202d0826d2b2121a1 Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 17 Nov 2026 08:34:34 +0000 Subject: [PATCH 09/91] docs: the parity status line and revision row give the copy pick's limits (#8087) As the roadmap now does: the pick compares the first 512 characters, and without the PDF part's widths, or with no installed copy that sets them all, it is the one before. Co-Authored-By: Claude Opus 5.5 --- docs/target-app-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b220c8b45a..e6e5a4dc4c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (`.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, follows #6983; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (`.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), follows #6983; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -61,7 +61,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-16 | minor | `.ai` import: type from the text document whose font record keeps no version, where installed copies of one PostScript name, family and style differ only in their widths, is set in the copy that sets the characters the file's PDF part draws at the widths the PDF part gives them, read from its font dictionaries without importing its pages (follows #6983; details in [file-format-parity.md](file-format-parity.md); tests in `crates/pdf/src/page_widths.rs`, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`, `records_of_one_font_share_its_page_widths_and_answer` in `crates/eps/src/import/ate.rs`, `type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in` and `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save` in `crates/engine/src/cmd/fileio/tests_aiimport.rs`, `pdf_font_widths_never_panic` in `crates/engine/tests/import_fuzz.rs`). Scores and estimates unchanged. | +| 2026-11-16 | minor | `.ai` import: type from the text document whose font record keeps no version, where installed copies of one PostScript name, family and style differ only in their widths, is set in the copy that sets the characters the file's PDF part draws at the widths the PDF part gives them, read from its font dictionaries without importing its pages; the pick compares the first 512 characters, and without those widths, or with no copy that sets them all, it is the one before (follows #6983; details in [file-format-parity.md](file-format-parity.md); tests in `crates/pdf/src/page_widths.rs`, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`, `records_of_one_font_share_its_page_widths_and_answer` in `crates/eps/src/import/ate.rs`, `type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in` and `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save` in `crates/engine/src/cmd/fileio/tests_aiimport.rs`, `pdf_font_widths_never_panic` in `crates/engine/tests/import_fuzz.rs`). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); area score and estimate unchanged. | From fc318eb2c0fe198b4185a8b8fd6ff3c1089cdb3a Mon Sep 17 00:00:00 2001 From: Drew Dibble Date: Tue, 17 Nov 2026 16:52:48 -0700 Subject: [PATCH 10/91] 3D: a ring of overlapping faces is broken at one of its own faces Where overlapping faces of a solid are put in the order of their depths (local_order, also Revolve's surface_order) and some lie in front of one another in a ring, no order draws them all correctly. When the sort could draw no face next, it drew the first face left by depth, whether or not that face was part of a ring. A face that is only in front of a ring's face, and comes before the ring by depth, was then drawn under it: dashed strokes on bars that overlap in a ring, extruded as a 3D group, had whole wall panels drawn over their dashes. The sort now follows the faces that go before the first face left back, among the faces that come before the next face drawn last, to a ring that waits for no other of them (Tarjan's algorithm on the pairs reversed, stopped at the first component completed). That ring gives up its own face that comes first in the order of their depths, and the faces left are looked at afresh, since they may be a smaller ring or none. Only pairs of a ring, and pairs with a face drawn last, are then drawn the wrong way round. A face drawn last (a cap) still follows every face before it. Cost and memory: - Comparing pairs and looking for rings share MAX_LOCAL_CHECKS steps: every face and pair looked at takes a step, and a face's list of the faces before it is charged before it is read. Past the limit the first face left by depth goes next, as before. - A first face left that waits only for the next face drawn last, or faces after it, goes next with no search and no step: each face keeps a count of the faces not drawn before it that come before the face drawn last. - The search goes on from where it stopped, less the group that gave up a face, so rings apart or one behind the other take a few steps a face. A ring that is still a ring after it gives up a face is walked again, so a large ring can cost about the square of its faces. - The pairs are held as two u32 (8 bytes), dropped once each face's list of the faces after it is made; both kinds of list are one array of 4 bytes a pair. The lists of the faces before each face take a step a pair to make, not taken from the limit, and are made only when the room left is at least a quarter of the pairs, so making them costs no more than four times the room left. A solid whose comparing leaves less breaks its rings at the first face left by depth. draw_order, cut_stroke_faces and in_one_order are unchanged. Tests (solids::tests): - a_face_in_front_of_a_cycle_waits_for_it: [0, 2, 3, 1] where the first face by depth gave [3, 0, 2, 1]; with a cap, it stays last. - the_faces_left_are_looked_at_afresh_after_each_face_released, the_ring_released_waits_for_no_face_outside_it, a_ring_is_looked_for_before_the_next_face_drawn_last. - breaking_a_ring_draws_no_more_pairs_wrong_than_the_first_face_by_depth: 6,000 random sets (up to 30 faces, pairs shuffled and repeated, up to four faces drawn last), each held to the order worked out plainly. - breaking_rings_stops_at_its_room, breaking_rings_takes_a_few_steps_a_face_but_for_a_ring_of_many_pairs: the steps are counted, not timed, and bounded from above. - a_face_that_waits_only_for_the_face_drawn_last_costs_no_search: 1,000 such faces before a ring take no search. - the_lists_for_rings_are_made_only_with_room_for_a_quarter_of_the_pairs. - a_list_longer_than_the_room_left_is_not_read: the entries read are counted where they are read, and stay within the room. - a_depth_cycle_keeps_the_cap_last is unchanged and passes. With no ring looked for, the ring tests fail; without the skip or the room for the lists, their tests fail. Docs: docs/three-d.md, docs/revolve.md, docs/effects-parity.md, docs/target-app-parity.md. Part of #7023. --- crates/effects/src/solids.rs | 347 ++++++++++++++++++++-- crates/effects/src/solids/tests.rs | 450 ++++++++++++++++++++++++++++- docs/effects-parity.md | 7 +- docs/revolve.md | 2 +- docs/target-app-parity.md | 4 +- docs/three-d.md | 34 ++- 6 files changed, 798 insertions(+), 46 deletions(-) diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 19b134f53b..80b0ebaf6f 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -934,8 +934,9 @@ impl Placed { } } -/// The most pairs of faces [`local_order`] compares, and the most [`cut_stroke_faces`] compares; -/// the pairs they have not reached by then keep the order of their depths. +/// The most pairs of faces [`local_order`] compares, together with the steps it takes to break +/// rings of them ([`drawn_in_pairs_order`]), and the most pairs [`cut_stroke_faces`] compares; the +/// pairs they have not reached by then keep the order of their depths. const MAX_LOCAL_CHECKS: usize = 4_000_000; /// The polygon of `f` and the sign of its turns, when `f` is a face turned toward the viewer other @@ -1164,11 +1165,11 @@ fn half(p: &[Point], values: &[f64], sign: f64) -> Vec { /// their depths where they overlap: the face nearer the viewer there goes after the other. A fill /// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each /// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays -/// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`. +/// where its depth puts it. A cycle of such pairs is broken at one of its own faces +/// ([`drawn_in_pairs_order`]). /// A face drawn last (a planar end turned toward the viewer, at depth `f64::MAX`) keeps its place: /// no face moves across it. Otherwise `order` as it is. fn local_order(faces: &[Placed], order: Vec) -> Vec { - use std::cmp::Reverse; // The faces of each shape that take part, from left to right for a sweep along x. let mut shapes: Vec> = vec![]; for (k, f) in faces.iter().enumerate() { @@ -1180,7 +1181,7 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { } shapes[f.member].push(k); } - if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) { + if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) || u32::try_from(faces.len()).is_err() { return order; } for list in &mut shapes { @@ -1223,9 +1224,9 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { // faces with a polygon and a plane that overlap goes in the order of their depths there. let mut sweep: Vec = (0..faces.len()).filter(|&k| faces[k].outline.len() >= 3 && faces[k].plane.is_some()).collect(); sweep.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0)); - // For each face, the faces drawn after it, and for each, how many go before it. - let mut after: Vec> = vec![vec![]; faces.len()]; - let mut waits = vec![0usize; faces.len()]; + // Each pair in its order: a face, and a face drawn after it (as `u32`: there are fewer faces + // than that, which is checked above). + let mut pairs: Vec<(u32, u32)> = vec![]; 'pairs: for (i, &k) in sweep.iter().enumerate() { let a = &faces[k]; for &j in sweep.iter().skip(i + 1).take_while(|&&j| faces[j].bounds.x0 < a.bounds.x1) { @@ -1243,38 +1244,117 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { let Some(a_nearer) = nearer_where_overlapping(a, b) else { continue }; a_nearer }; - let (back, front) = if a_later { (j, k) } else { (k, j) }; - after[back].push(front); - waits[front] += 1; + pairs.push(if a_later { (j as u32, k as u32) } else { (k as u32, j as u32) }); } } - // Each step draws the face that comes first in `order` of those whose faces before are drawn. + // Breaking rings has what is left of the limit. + let last: Vec = faces.iter().map(|f| f.depth >= f64::MAX).collect(); + let mut room = MAX_LOCAL_CHECKS.saturating_sub(checks); + drawn_in_pairs_order(order, &position, &last, pairs, &mut room) +} + +/// `order` with each face after the faces that go before it: each of `pairs` is a face and a face +/// drawn after it, `position` is each face's place in `order`, and `last` says of each face +/// whether it is drawn last. Each step draws the face that comes first in `order` of those whose +/// faces before are drawn. A face drawn last goes only after every face before it in `order`, so +/// a face before it never waits for it or for a face after it: those pairs, with the face drawn +/// last itself or with a face that follows it, are drawn the wrong way round. +/// +/// When no face can go next, some of the faces left go before each other in a ring, or wait for a +/// face drawn last or one that follows it. The faces that go before the first face left in `order` +/// are followed back, among the faces that come before the next face drawn last, to the first +/// group found that waits for no other of them ([`RingFinder::behind`]): a ring, or one face. That +/// group gives up its face that comes first in `order`. So when the first face left is in the +/// group, it goes next, as it would with no ring looked for; when it only waits for the group, a +/// face of the group goes instead, and the only other pairs drawn the wrong way round are pairs of +/// a ring. +/// +/// Every face and pair looked at takes one from `room`. The search is kept from one stop to the +/// next and goes on from where it stopped, and a face that is drawn is dropped from a list the +/// next time the list is looked at, so rings of a few faces take a few steps a face whether they +/// stand apart, all lie behind one face or lie one behind the other. Two costs are not in +/// proportion to the faces. A ring that is still a ring after it gives up a face is walked again +/// from the face the search reached it by, so a large ring can cost about its pairs for each face +/// it gives up: the square of its faces, even when each waits for few others (3,200 faces with +/// four pairs each at random take about 3,000,000 steps). And a face at or +/// after the next face drawn last is passed over again each time a face that waits for it is +/// looked at. Once `room` runs out the first face left in `order` goes next, ring or not. +/// A first face left that waits only for the next face drawn last or faces after it goes next +/// with no search, at no cost. +/// +/// An `order` and `position` that do not agree, or a pair of a face that is not in them, give +/// `order` back. +/// +/// The pairs come at 8 bytes each and are dropped once the lists of the faces after each face +/// are made, 4 bytes a pair; the lists of the faces before each face, as many again, are made +/// when a ring is first looked for, a step a pair not taken from `room`, and only when the room +/// left is at least a quarter of the pairs: with less, no ring is looked for and the first face +/// left goes next. So a solid whose comparing of pairs leaves less than a quarter of its pairs +/// of the limit breaks its rings as before rings were looked for. +fn drawn_in_pairs_order(order: Vec, position: &[usize], last: &[bool], pairs: Vec<(u32, u32)>, room: &mut usize) -> Vec { + use std::cmp::Reverse; + let n = order.len(); + // `order` holds each face once when each face's place in it is the place `position` gives. + let agree = position.len() == n && last.len() == n && order.iter().enumerate().all(|(at, &k)| position.get(k) == Some(&at)); + if !agree || u32::try_from(pairs.len()).is_err() || pairs.iter().any(|&(back, front)| back as usize >= n || front as usize >= n) { + return order; + } + // For each face, how many faces not drawn yet go before it, and the faces drawn after it. + let mut waits = vec![0usize; n]; + for &(_, front) in &pairs { + waits[front as usize] += 1; + } + let after = Lists::from_pairs(n, pairs.iter().map(|&(back, front)| (back as usize, front as usize))); + drop(pairs); let mut ready: std::collections::BinaryHeap> = - (0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect(); + (0..n).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect(); // The faces drawn last, in `order`: each goes only after every face before it in `order`. - let last: Vec = order.iter().copied().filter(|&k| faces[k].depth >= f64::MAX).collect(); + let lasts: Vec = order.iter().copied().filter(|&k| last[k]).collect(); let mut next_last = 0usize; - let mut drawn = vec![false; faces.len()]; - let mut out = Vec::with_capacity(order.len()); + let mut drawn = vec![false; n]; + let mut out = Vec::with_capacity(n); let mut first = 0usize; - while out.len() < order.len() { - while last.get(next_last).is_some_and(|&k| drawn[k]) { + let mut rings: Option = None; + // For each face, how many faces not drawn yet go before it among the first `counted` of + // `order`, which keeps up with the next face drawn last. + let mut early = vec![0u32; n]; + let mut counted = 0usize; + while out.len() < n { + while lasts.get(next_last).is_some_and(|&k| drawn[k]) { next_last += 1; } - let limit = last.get(next_last).map_or(usize::MAX, |&k| position[k]); + let limit = lasts.get(next_last).map_or(usize::MAX, |&k| position[k]); + while counted < limit.min(n) { + if let Some(&back) = order.get(counted).filter(|&&back| !drawn[back]) { + for &j in after.list(back) { + early[j as usize] += 1; + } + } + counted += 1; + } let k = match ready.peek() { Some(&Reverse((at, k))) if at < limit => { ready.pop(); k } _ => { - // A cycle, or the faces left to draw before a face drawn last wait for faces after - // it: the first face in `order` not drawn yet goes next. while order.get(first).is_some_and(|&k| drawn[k]) { first += 1; } - let Some(&k) = order.get(first) else { break }; - k + let Some(&next) = order.get(first) else { break }; + // The face drawn last goes in its turn, and so does a face that waits only for it or + // faces after it: no face it waits for can go first. Any other face waits for a + // face before the face drawn last: the group behind it gives up a face, while there + // is room to look for one. The lists of the faces before each face take a step a + // pair to make, which is not taken from `room`: they are made only when the room + // left is at least a quarter of the pairs, so making them costs no more than four + // times the room left. + let mut released = None; + let room_for_lists = rings.is_some() || room.saturating_mul(4) >= after.faces.len(); + if *room > 0 && position[next] < limit && early[next] > 0 && room_for_lists { + released = rings.get_or_insert_with(|| RingFinder::new(&after)).behind(next, &drawn, position, limit, room); + } + released.unwrap_or(next) } }; if drawn[k] { @@ -1282,8 +1362,13 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { } drawn[k] = true; out.push(k); - for &j in &after[k] { + let was_counted = position[k] < counted; + for &j in after.list(k) { + let j = j as usize; waits[j] = waits[j].saturating_sub(1); + if was_counted { + early[j] = early[j].saturating_sub(1); + } if waits[j] == 0 && !drawn[j] { ready.push(Reverse((position[j], j))); } @@ -1292,6 +1377,217 @@ fn local_order(faces: &[Placed], order: Vec) -> Vec { out } +/// A list of faces for each of some faces, all in one array: the faces after each face, or the +/// faces before it. +struct Lists { + /// The list of face `k` is `faces[starts[k]..starts[k + 1]]`. + starts: Vec, + faces: Vec, +} + +impl Lists { + /// For each of `n` faces, the second faces of the `pairs` it is first in, in the order of + /// `pairs`. There are fewer than 2^32 faces and pairs ([`drawn_in_pairs_order`] checks this); + /// a pair with a face that is not one of the `n` is left out. + fn from_pairs(n: usize, pairs: impl Iterator + Clone) -> Self { + let pairs = pairs.filter(move |&(first, second)| first < n && second < n); + let mut starts = vec![0u32; n + 1]; + for (first, _) in pairs.clone() { + if let Some(count) = starts.get_mut(first + 1) { + *count += 1; + } + } + for k in 1..starts.len() { + starts[k] += starts[k - 1]; + } + let mut filled = starts.clone(); + let mut faces = vec![0u32; starts.last().map_or(0, |&end| end as usize)]; + for (first, second) in pairs { + if let Some(at) = filled.get_mut(first) { + if let Some(slot) = faces.get_mut(*at as usize) { + *slot = second as u32; + } + *at += 1; + } + } + Lists { starts, faces } + } + + /// The list of face `k`; none for a face that is not one of them. + fn list(&self, k: usize) -> &[u32] { + let (Some(&start), Some(&end)) = (self.starts.get(k), self.starts.get(k + 1)) else { return &[] }; + self.faces.get(start as usize..end as usize).unwrap_or_default() + } + + /// Each list's faces and the face it is the list of, as pairs. + fn pairs(&self) -> impl Iterator + Clone + '_ { + (0..self.starts.len().saturating_sub(1)).flat_map(move |k| self.list(k).iter().map(move |&j| (k, j as usize))) + } +} + +#[cfg(test)] +thread_local! { + /// The entries of the lists of faces before each face that [`RingFinder`] has read, counted + /// where they are read, for tests to hold the reading to the room. + pub(super) static LIST_ENTRIES_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// No place among the faces reached, in [`RingFinder`]. +const NONE: usize = usize::MAX; + +/// Finds the ring behind a face for [`drawn_in_pairs_order`], and keeps its search from one stop to +/// the next. +/// +/// Every index it holds is in range: the faces of its lists are faces of the pairs +/// [`drawn_in_pairs_order`] checked against the number of faces, which is the length of the +/// `drawn` and `position` it is given, and the places it keeps are places in its own lists. +struct RingFinder { + /// For each face, the faces that go before it, lowest first. + before: Lists, + /// For each face, where its list in `before` now ends: the faces found drawn are dropped + /// from it, and those left moved up. + ends: Vec, + /// For each face, its place in `reached`; [`NONE`] for a face not reached. + marks: Vec, + /// The faces reached, in the order reached. Every one is in a group not completed yet. + reached: Vec, + /// For each face reached, the earliest place in `reached` it leads back to. + low: Vec, + /// The path from the first face reached to the one being looked at. + path: Vec, + /// The `limit` the faces reached were reached under; `None` with none reached yet. + limit: Option, +} + +/// A face on the path of [`RingFinder`]: its place in `reached`, and the entry of its list being +/// looked at. +struct Step { + place: usize, + entry: usize, +} + +impl RingFinder { + /// A finder for the faces of `after`, the faces drawn after each face. + fn new(after: &Lists) -> Self { + let n = after.starts.len() - 1; + let before = Lists::from_pairs(n, after.pairs().map(|(back, front)| (front, back))); + let ends = before.starts.get(1..).unwrap_or_default().to_vec(); + RingFinder { before, ends, marks: vec![NONE; n], reached: vec![], low: vec![], path: vec![], limit: None } + } + + /// The face to draw next when `start`, the first face not `drawn`, whose `position` is before + /// `limit`, waits for a face. Of the faces that are not drawn and come before `limit`, those + /// that go before `start` are followed back to the first group found whose faces wait for no + /// other such face: a ring of faces that go before each other, or one face. The answer is the + /// face of that group with the lowest `position`. Every face and every pair looked at takes + /// one from `room`; `None` when it runs out. + /// + /// The faces are followed depth first, each face's faces before it lowest first, and the first + /// strongly connected component completed is the group (Tarjan's algorithm, stopped there): + /// it leads to no other component. The search is kept, less that group, and the next call + /// goes on with it: the faces drawn since are the group's own and faces that waited for + /// nothing else, and none of those is in a group with a face still on the path, so what the + /// search knows of the faces left still holds. It starts afresh when `limit` moves, which + /// brings in faces it passed over. + fn behind(&mut self, start: usize, drawn: &[bool], position: &[usize], limit: usize, room: &mut usize) -> Option { + if self.limit != Some(limit) { + self.forget(0); + self.limit = Some(limit); + } + // The end of the path may be drawn: faces that only waited for the last group. + while let Some(place) = self.path.last().map(|step| step.place).filter(|&place| drawn[self.reached[place]]) { + self.forget(place); + } + if self.reached.first() != Some(&start) { + self.forget(0); + if !self.reach(start, drawn, room) { + return None; + } + } + while let Some(step) = self.path.last_mut() { + if *room == 0 { + return None; + } + *room -= 1; + let place = step.place; + let face = self.reached[place]; + if step.entry < self.ends[face] as usize { + let earlier = self.before.faces[step.entry] as usize; + if drawn[earlier] || position[earlier] >= limit { + step.entry += 1; + } else if self.marks[earlier] != NONE { + self.low[place] = self.low[place].min(self.marks[earlier]); + step.entry += 1; + } else { + // The entry is passed once the faces behind it are looked at. + if !self.reach(earlier, drawn, room) { + return None; + } + } + continue; + } + // Every face before this one is looked at: it ends a group when it leads no further + // back than itself. + let leads = self.low[place]; + if leads == place { + let found = self.reached[place..].iter().copied().min_by_key(|&face| position[face]); + // The face before it on the path keeps its entry for this one, to look at what is + // left of the group next time. + self.forget(place); + return found; + } + self.path.pop(); + if let Some(parent) = self.path.last_mut() { + self.low[parent.place] = self.low[parent.place].min(leads); + parent.entry += 1; + } + } + None + } + + /// Adds `face` to the faces reached and to the end of the path, at the start of its list, with + /// the faces now `drawn` dropped from the list: a step from `room` for each face the list held, + /// taken before the list is read. `false`, with `room` emptied and nothing read, when the list + /// is longer than the room left. + fn reach(&mut self, face: usize, drawn: &[bool], room: &mut usize) -> bool { + let (start, end) = (self.before.starts[face] as usize, self.ends[face] as usize); + let Some(left) = room.checked_sub(end - start) else { + *room = 0; + return false; + }; + *room = left; + #[cfg(test)] + LIST_ENTRIES_READ.with(|read| read.set(read.get() + (end - start))); + let mut kept = start; + for entry in start..end { + let earlier = self.before.faces[entry]; + if !drawn[earlier as usize] { + self.before.faces[kept] = earlier; + kept += 1; + } + } + // `kept` is no more than the end it replaces. + self.ends[face] = kept as u32; + let place = self.reached.len(); + self.marks[face] = place; + self.path.push(Step { place, entry: start }); + self.low.push(place); + self.reached.push(face); + true + } + + /// Takes out the faces reached from `place` on, and their part of the path. + fn forget(&mut self, place: usize) { + for face in self.reached.drain(place.min(self.reached.len())..) { + self.marks[face] = NONE; + } + self.low.truncate(place); + while self.path.last().is_some_and(|step| step.place >= place) { + self.path.pop(); + } + } +} + /// Whether face `a` is nearer the viewer than face `b` where their polygons overlap on the drawing, /// measured at the middle of the overlap. `None` when they do not overlap, when either polygon is /// not convex, or when they are at the same depth there. @@ -1425,7 +1721,8 @@ fn draw_order(faces: &[Placed], sealed: bool) -> Vec { /// of overlapping faces with a convex polygon and a plane goes in the order of its depths there, /// the face nearer the viewer after the other ([`local_order`]), and each step draws the face that /// comes first in the given order of those whose faces before are drawn, so a face without a plane -/// or a convex polygon can also move. Otherwise the order given. +/// or a convex polygon can also move. Faces that lie in front of one another in a ring give up one +/// of the ring's own faces ([`drawn_in_pairs_order`]). Otherwise the order given. pub(crate) fn surface_order<'a>(faces: impl IntoIterator, f64)>) -> Vec { let placed: Vec = faces .into_iter() diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 378299d514..87c64060ee 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -906,10 +906,10 @@ fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() { } } -/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap -/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at -/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer -/// than 0. 3 is the cap. +/// A cycle of overlapping stroke faces is broken at its own face that comes first by depth, and a +/// cap drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; +/// 2 at x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 +/// nearer than 0. 3 is the cap. #[test] fn a_depth_cycle_keeps_the_cap_last() { let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; @@ -937,6 +937,448 @@ fn a_depth_cycle_keeps_the_cap_last() { assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]); } +/// A face that lies in front of a face of a cycle, without being part of the cycle, waits for that +/// face. 0, 1 and 2 overlap in a cycle (as in `a_depth_cycle_keeps_the_cap_last`); 3, at x 16 to +/// 26 and flat at z 2, is nearer than 2 where they overlap, but its center is the farthest of all, +/// so it comes first by depth. The cycle is broken at 0, its first face by depth, and 3 follows 2. +/// Breaking it at the first face by depth of all the faces left drew 3 first, under 2. +#[test] +fn a_face_in_front_of_a_cycle_waits_for_it() { + let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; + let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed { + depth, + side: true, + away: false, + bounds: Rect::new(x, 0.0, x + 10.0, 10.0), + member: 0, + paints: Paints::Other, + outline: square(x), + plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + }; + let flat = [0.0, 0.0, 1.0]; + let walls = || [at(1.0, 0.0, flat, 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, flat, 1.0), at(-5.0, 16.0, flat, 2.0)]; + assert_eq!(draw_order(&walls(), true), [0, 2, 3, 1]); + // With the cap of `a_depth_cycle_keeps_the_cap_last` as well, it still goes last. + let cap = + Placed { depth: f64::MAX, side: false, bounds: Rect::new(0.0, 0.0, 26.0, 10.0), outline: vec![], plane: None, ..at(0.0, 0.0, flat, 0.0) }; + let capped: Vec = walls().into_iter().chain([cap]).collect(); + assert_eq!(draw_order(&capped, true), [0, 2, 3, 1, 4]); +} + +/// `order` with the pairs `before` (each first face drawn before the second) in their own order +/// ([`drawn_in_pairs_order`]), within `room` steps of looking for rings, and the steps taken; the +/// faces of `last` are drawn last. +fn in_pairs_order(order: &[usize], before: &[(usize, usize)], last: &[usize], room: usize) -> (Vec, usize) { + let n = order.len(); + let mut position = vec![0; n]; + for (at, &k) in order.iter().enumerate() { + position[k] = at; + } + let last: Vec = (0..n).map(|k| last.contains(&k)).collect(); + let mut left = room; + let drawn = drawn_in_pairs_order(order.to_vec(), &position, &last, narrow(before), &mut left); + (drawn, room - left) +} + +/// What [`drawn_in_pairs_order`] is to give with room enough, worked out plainly: at every stop +/// the faces behind the first face left are followed afresh, with nothing kept and no face taken +/// out of a list. +fn in_pairs_order_plainly(order: &[usize], before: &[(usize, usize)], last: &[usize]) -> Vec { + /// The first group completed behind `face`, among the faces `open`: its faces, or `None` while + /// its group goes on. `earlier` lists the faces before each face, lowest first. + fn group(face: usize, open: &[bool], earlier: &[Vec], reached: &mut Vec, low: &mut Vec) -> Option> { + let place = reached.len(); + reached.push(face); + low.push(place); + for &e in earlier[face].iter().filter(|&&e| open[e]) { + match reached.iter().position(|&f| f == e) { + Some(at) => low[place] = low[place].min(at), + None => { + let found = group(e, open, earlier, reached, low); + if found.is_some() { + return found; + } + low[place] = low[place].min(low[reached.iter().position(|&f| f == e).unwrap()]); + } + } + } + (low[place] == place).then(|| reached[place..].to_vec()) + } + let n = order.len(); + let mut at = vec![0; n]; + for (place, &k) in order.iter().enumerate() { + at[k] = place; + } + let mut earlier = vec![vec![]; n]; + for &(first, then) in before { + earlier[then].push(first); + } + earlier.iter_mut().for_each(|list| list.sort_unstable()); + let mut drawn = vec![false; n]; + let mut out: Vec = vec![]; + while out.len() < n { + let left: Vec = order.iter().copied().filter(|&k| !drawn[k]).collect(); + let limit = left.iter().find(|k| last.contains(k)).map_or(usize::MAX, |&k| at[k]); + let waits = |k: usize| earlier[k].iter().any(|&e| !drawn[e]); + let next = match left.iter().copied().find(|&k| at[k] < limit && !waits(k)) { + Some(ready) => ready, + None if at[left[0]] >= limit => left[0], + None => { + let open: Vec = (0..n).map(|k| !drawn[k] && at[k] < limit).collect(); + let found = group(left[0], &open, &earlier, &mut vec![], &mut vec![]).unwrap(); + found.into_iter().min_by_key(|&k| at[k]).unwrap() + } + }; + drawn[next] = true; + out.push(next); + } + out +} + +/// `pairs` as [`drawn_in_pairs_order`] takes them. +fn narrow(pairs: &[(usize, usize)]) -> Vec<(u32, u32)> { + pairs.iter().map(|&(first, then)| (first as u32, then as u32)).collect() +} + +/// The pairs of `before` that `drawn` draws the wrong way round. +fn broken(drawn: &[usize], before: &[(usize, usize)]) -> Vec<(usize, usize)> { + let mut at = vec![0; drawn.len()]; + for (place, &k) in drawn.iter().enumerate() { + at[k] = place; + } + before.iter().copied().filter(|&(first, then)| at[first] > at[then]).collect() +} + +/// After a ring's face is released, the faces left are looked at afresh: they may be a smaller +/// ring and faces in none. Two rings share face 1: 0 before 1 before 4 before 0, and 1 before 2 +/// before 3 before 1. By depth the order is 3, 2, 0, 4, 1. The five wait for no other face, so the +/// first stop releases 3, the first of them by depth. That leaves the one ring 0, 1, 4 and face +/// 2, which only waits for 1: 0 is released, and 2 follows 1. Only pairs of a ring are drawn the +/// wrong way round. Taking the first face left by depth at each stop drew 2 before 1 as well. +#[test] +fn the_faces_left_are_looked_at_afresh_after_each_face_released() { + let before = [(0, 1), (1, 4), (4, 0), (1, 2), (2, 3), (3, 1)]; + let (drawn, _) = in_pairs_order(&[3, 2, 0, 4, 1], &before, &[], usize::MAX); + assert_eq!(drawn, [3, 0, 1, 2, 4]); + assert_eq!(broken(&drawn, &before), [(4, 0), (2, 3)]); + assert_eq!(broken(&in_pairs_order(&[3, 2, 0, 4, 1], &before, &[], 0).0, &before), [(4, 0), (1, 2), (2, 3)]); +} + +/// A ring is the one behind the first face left by depth that waits for no face outside it: 0 +/// comes first by depth and waits for the ring 1, 2, 3, which waits for the ring 4, 5, 6. The far +/// ring is broken first (at 4) and drawn, then the near one (at 1), and 0 follows 1; one pair of +/// each ring is drawn the wrong way round, and no pair between them. Taking the first face left by +/// depth drew 0 first, under 1. +#[test] +fn the_ring_released_waits_for_no_face_outside_it() { + let before = [(1, 0), (1, 2), (2, 3), (3, 1), (4, 1), (4, 5), (5, 6), (6, 4)]; + let (drawn, _) = in_pairs_order(&[0, 1, 2, 3, 4, 5, 6], &before, &[], usize::MAX); + assert_eq!(drawn, [4, 5, 6, 1, 0, 2, 3]); + assert_eq!(broken(&drawn, &before), [(3, 1), (6, 4)]); + assert_eq!(broken(&in_pairs_order(&[0, 1, 2, 3, 4, 5, 6], &before, &[], 0).0, &before), [(1, 0), (3, 1), (4, 1), (6, 4)]); +} + +/// A ring is looked for among the faces that come before the next face drawn last: 1 comes first +/// by depth and waits for 4, a face of the ring 2, 3, 4, and for 0, which is drawn last. 0 waits +/// for no face, so it is a group of its own behind 1, but no face before it by depth can wait for +/// it. The ring gives up 2, and 1 follows 4; the pair of 1 and 0 cannot be kept. Stopping at 0 +/// drew 1 first, under 4. +#[test] +fn a_ring_is_looked_for_before_the_next_face_drawn_last() { + let before = [(2, 3), (3, 4), (4, 2), (4, 1), (0, 1)]; + let (drawn, _) = in_pairs_order(&[1, 2, 3, 4, 0], &before, &[0], usize::MAX); + assert_eq!(drawn, [2, 3, 4, 1, 0]); + assert_eq!(broken(&drawn, &before), [(4, 2), (0, 1)]); + assert_eq!(broken(&in_pairs_order(&[1, 2, 3, 4, 0], &before, &[0], 0).0, &before), [(4, 2), (4, 1), (0, 1)]); + // A face that waits only for a face after the one drawn last goes before the faces that wait + // for it: 0 waits for 1, 1 for 3, and 2 is drawn last. + let before = [(1, 0), (3, 1)]; + assert_eq!(in_pairs_order(&[0, 1, 2, 3], &before, &[2], usize::MAX).0, [1, 0, 2, 3]); + assert_eq!(in_pairs_order(&[0, 1, 2, 3], &before, &[2], 0).0, [0, 1, 2, 3]); +} + +/// Looking for rings is counted, and past the room given the first face not drawn yet goes next, +/// as before rings were looked for: the pairs of `a_face_in_front_of_a_cycle_waits_for_it`. A +/// face drawn last keeps every face before it by depth before it, ring or not. An order and +/// places in it that do not agree (an order that is not each face once), or a pair of a face that +/// is not in them, give the order back. +#[test] +fn breaking_rings_stops_at_its_room() { + let before = [(1, 0), (0, 2), (2, 1), (2, 3)]; + let order = [3, 0, 1, 2]; + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(drawn, [0, 2, 3, 1]); + // The faces and pairs behind 3. + assert!((4..=16).contains(&steps), "{steps} steps"); + assert_eq!(in_pairs_order(&order, &before, &[], steps), (vec![0, 2, 3, 1], steps)); + for room in [0, 1, steps - 1] { + let (drawn, taken) = in_pairs_order(&order, &before, &[], room); + assert_eq!(drawn, [3, 0, 2, 1], "{room}"); + assert!(taken <= room, "{room}"); + } + // 0 is drawn last: 3, before it by depth, goes before it, and the ring's other faces after. + assert_eq!(in_pairs_order(&order, &before, &[0], usize::MAX).0, [3, 0, 2, 1]); + // 2 is drawn last: every other face is before it by depth, so 3 and 1, which wait only for + // it, go when they come first of the faces behind the first face left, and 0 follows 1. + assert_eq!(in_pairs_order(&order, &before, &[2], usize::MAX).0, [3, 1, 0, 2]); + assert_eq!(in_pairs_order(&order, &before, &[2], 0).0, [3, 0, 1, 2]); + let mut room = usize::MAX; + let position = [1, 2, 3, 0]; + assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 3], narrow(&before), &mut room), order); + assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 4], vec![(9, 0)], &mut room), order); + assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 4], vec![(0, 4)], &mut room), order); + assert_eq!(drawn_in_pairs_order(order[..3].to_vec(), &position, &[false; 4], narrow(&before), &mut room), order[..3]); + assert_eq!(drawn_in_pairs_order(order.to_vec(), &position[..3], &[false; 4], narrow(&before), &mut room), order); + assert_eq!(drawn_in_pairs_order(order.to_vec(), &[1, 2, 0, 3], &[false; 4], narrow(&before), &mut room), order); + assert_eq!(drawn_in_pairs_order(vec![0, 0, 1, 2], &[0, 2, 3, 0], &[false; 4], narrow(&before), &mut room), [0, 0, 1, 2]); + assert_eq!(drawn_in_pairs_order(vec![0, 1, 2, 4], &[0, 1, 2, 3], &[false; 4], narrow(&before), &mut room), [0, 1, 2, 4]); + assert_eq!(room, usize::MAX); +} + +/// A first face left that waits only for the face drawn last goes next with no search: 1,000 +/// such faces before a ring cost nothing, and the ring behind them still has its room. Each face +/// i < 1,000 waits for 1,004, which is drawn last; 1,000 to 1,003 are the pairs of +/// `breaking_rings_stops_at_its_room`, where 1,003 comes first by depth and waits for the ring. +#[test] +fn a_face_that_waits_only_for_the_face_drawn_last_costs_no_search() { + let waiting = 1000usize; + let (r, last) = (waiting, waiting + 4); + let mut before: Vec<(usize, usize)> = (0..waiting).map(|f| (last, f)).collect(); + before.extend([(r + 1, r), (r, r + 2), (r + 2, r + 1), (r + 2, r + 3)]); + let order: Vec = (0..waiting).chain([r + 3, r, r + 1, r + 2, last]).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[last], usize::MAX); + let expected: Vec = (0..waiting).chain([r, r + 2, r + 3, r + 1, last]).collect(); + assert_eq!(drawn, expected); + assert!(steps < 20, "{steps} steps"); + // The room the ring takes is enough, whatever waits before it. + assert_eq!(in_pairs_order(&order, &before, &[last], before.len().div_ceil(4).max(steps)).0, expected); +} + +/// The lists of the faces before each face are made only when the room left is at least a +/// quarter of the pairs: with less, no ring is looked for, however few steps the ring would take. +/// A ring of three behind 3,000 faces in a chain (each before the next). +#[test] +fn the_lists_for_rings_are_made_only_with_room_for_a_quarter_of_the_pairs() { + let chain = 3000usize; + let r = chain; + let mut before: Vec<(usize, usize)> = (0..chain - 1).map(|f| (f, f + 1)).collect(); + before.extend([(r + 1, r), (r, r + 2), (r + 2, r + 1), (r + 2, r + 3)]); + // As in `breaking_rings_stops_at_its_room`: 3 comes first by depth of the four and waits for + // the ring. + let order: Vec = (0..chain).chain([r + 3, r, r + 1, r + 2]).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(drawn[chain..], [r, r + 2, r + 3, r + 1]); + assert!(steps < 20, "{steps} steps"); + let quarter = before.len().div_ceil(4); + let (drawn, steps) = in_pairs_order(&order, &before, &[], quarter - 1); + assert_eq!(drawn[chain..], [r + 3, r, r + 2, r + 1]); + assert_eq!(steps, 0); + assert_eq!(in_pairs_order(&order, &before, &[], quarter).0[chain..], [r, r + 2, r + 3, r + 1]); +} + +/// A list of the faces before a face is read only when the room left holds it: with less, no +/// entry of it is read, and the first face left goes next. Face 0 comes first by depth and waits +/// for 1, which waits for 2,000 faces after it in `order`, each waiting for 1: a ring of 1 with +/// each of them. +#[test] +fn a_list_longer_than_the_room_left_is_not_read() { + let wide = 2000usize; + let mut before = vec![(1, 0)]; + before.extend((2..2 + wide).flat_map(|f| [(f, 1), (1, f)])); + let order: Vec = (0..2 + wide).collect(); + // Room for the lists (a quarter of the pairs) but not for 1's list, and room for it. + for room in [before.len().div_ceil(4), wide - 1, wide + 3] { + super::LIST_ENTRIES_READ.with(|read| read.set(0)); + let (drawn, taken) = in_pairs_order(&order, &before, &[], room); + let read = super::LIST_ENTRIES_READ.with(|read| read.get()); + assert!(read <= taken && taken <= room, "room {room}: {read} entries read, {taken} steps"); + assert_eq!(drawn.len(), order.len()); + } +} + +/// The steps of breaking rings are counted, not timed, and for rings of a few faces they are a +/// few a face however the rings lie: apart, each with a face in front of it that comes first by +/// depth; all behind one face, itself in a ring whose other faces come first in its list; and one +/// behind the other. The search goes on from where it stopped, and a face drawn is dropped from +/// a list the next time the list is looked at. A ring that is still a ring after it gives up a +/// face is walked again, so a large ring can take about its pairs for each face it gives up, the +/// square of its faces even when each waits for few others. With too little room the rings not +/// reached are broken at the first face left by depth, as before. +#[test] +fn breaking_rings_takes_a_few_steps_a_face_but_for_a_ring_of_many_pairs() { + // Ring r: faces 4r, 4r + 1 and 4r + 2 in a ring, and 4r + 3 after 4r + 2. + let rings = 2000usize; + let mut before = vec![]; + for r in 0..rings { + let f = 4 * r; + before.extend([(f + 1, f), (f, f + 2), (f + 2, f + 1), (f + 2, f + 3)]); + } + // By depth: every fourth face first, then the rings. + let order: Vec = (0..rings).map(|r| 4 * r + 3).chain((0..rings).flat_map(|r| [4 * r, 4 * r + 1, 4 * r + 2])).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(broken(&drawn, &before), (0..rings).map(|r| (4 * r + 1, 4 * r)).collect::>()); + assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings apart"); + // With no room the fourth faces go first, under the faces they are in front of. + assert_eq!(broken(&in_pairs_order(&order, &before, &[], 0).0, &before).len(), 2 * rings); + + // Face 0, first by depth, is in a ring with 1 and 2, which come first in its list, and after a + // face of each ring r: faces 3r + 3, 3r + 4 and 3r + 5. + let rings = 3000usize; + let mut before = vec![(1, 0), (0, 2), (2, 1)]; + for r in 0..rings { + let f = 3 * r + 3; + before.extend([(f, f + 1), (f + 1, f + 2), (f + 2, f), (f, 0)]); + } + let order: Vec = (0..3 * rings + 3).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + // One pair of each ring, face 0's among them, and no pair of face 0 with another ring's face. + assert_eq!(broken(&drawn, &before), [(1, 0)].into_iter().chain((0..rings).map(|r| (3 * r + 5, 3 * r + 3))).collect::>()); + assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings behind one face"); + // The same with a face drawn last that every ring's first face waits for: it is passed over + // each time, and nothing after it in a list is looked at twice for that. + let cap = 3 * rings + 3; + let capped: Vec<(usize, usize)> = (0..rings).map(|r| (cap, 3 * r + 3)).chain(before.iter().copied()).collect(); + let order: Vec = (0..=cap).collect(); + let (drawn, steps) = in_pairs_order(&order, &capped, &[cap], usize::MAX); + assert_eq!(broken(&drawn, &capped).len(), 2 * rings + 1); + assert!(steps <= 5 * order.len(), "{steps} steps for {rings} rings behind one face, before a face drawn last"); + + // Ring r: faces 3r, 3r + 1 and 3r + 2, the first after the last face of ring r + 1. + let rings = 3000usize; + let mut before = vec![]; + for r in 0..rings { + let f = 3 * r; + before.extend([(f, f + 1), (f + 1, f + 2), (f + 2, f)]); + if r + 1 < rings { + before.push((f + 5, f)); + } + } + let order: Vec = (0..3 * rings).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + // One pair of each ring, and no pair between rings. + assert_eq!(broken(&drawn, &before).len(), rings); + assert!(broken(&drawn, &before).iter().all(|&(first, then)| first / 3 == then / 3)); + assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings one behind the other"); + let (short, taken) = in_pairs_order(&order, &before, &[], steps / 2); + assert!(broken(&short, &before).len() > rings && taken <= steps / 2, "{} pairs, {taken} steps", broken(&short, &before).len()); + assert_eq!(short.len(), order.len()); + + // One ring: each of 200 faces before the next 99. + let faces = 200usize; + let before: Vec<(usize, usize)> = (0..faces).flat_map(|f| (1..100).map(move |d| (f, (f + d) % faces))).collect(); + let order: Vec = (0..faces).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(drawn, order); + // Each face it gives up walks the ring again, so it takes many times its pairs (the cost the + // docs name), but no more than about its pairs for each face. + assert!(steps < 2 * faces * before.len(), "{steps} steps for a ring of {} pairs", before.len()); + + // Pairs at random, about four a face: one large ring and faces around it. + let steps_of = |faces: usize| { + let mut next = numbers(faces as u64); + let before: Vec<(usize, usize)> = (0..2 * faces) + .map(|_| ((next() * faces as f64) as usize, (next() * faces as f64) as usize)) + .filter(|(first, then)| first != then) + .collect(); + let order: Vec = (0..faces).collect(); + let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX); + assert_eq!(drawn.len(), faces); + steps + }; + // No more than the square of the faces. + let (few, more) = (steps_of(800), steps_of(1600)); + assert!(few < 800 * 800 && more < 1600 * 1600, "{few} steps for 800 faces, {more} for 1,600"); +} + +/// Numbers from 0 to 1 that are the same on every run. +fn numbers(mut seed: u64) -> impl FnMut() -> f64 { + move || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 11) as f64 / (1u64 << 53) as f64 + } +} + +/// A ring gives up its own face that comes first by depth, which draws no more pairs the wrong +/// way round than taking the first face left by depth, ring or not, as before: on 6,000 sets of +/// pairs at random (4 to 30 faces, sparse and dense, agreeing with the depths mostly or half the +/// time, the pairs in any order and some twice, with up to four faces drawn last) none has more, and they have fewer in all. Every face +/// is drawn once, a face drawn last follows every face before it by depth, and the order of every +/// set is the one that looking afresh at every stop gives. One of them is a +/// set where the ring's face that waits for the fewest faces drew 4 pairs wrong against 3. +#[test] +fn breaking_a_ring_draws_no_more_pairs_wrong_than_the_first_face_by_depth() { + let order = [3, 6, 4, 1, 0, 2, 5]; + let before = [ + (1, 0), + (2, 0), + (0, 3), + (0, 4), + (5, 0), + (6, 0), + (1, 2), + (1, 3), + (4, 1), + (5, 1), + (4, 2), + (5, 2), + (6, 2), + (3, 4), + (3, 6), + (5, 4), + (6, 4), + (5, 6), + ]; + assert_eq!(broken(&in_pairs_order(&order, &before, &[], 0).0, &before).len(), 3); + assert_eq!(broken(&in_pairs_order(&order, &before, &[], usize::MAX).0, &before).len(), 3); + + let mut next = numbers(7023); + let (mut with_rings, mut without, mut fewer) = (0usize, 0usize, 0usize); + for set in 0..6000 { + let n = 4 + (next() * 27.0) as usize; + let (dense, agrees) = (0.05 + 0.8 * next() * next(), if set % 2 == 0 { 0.5 } else { 0.85 }); + // The order by depth: the faces shuffled. + let mut order: Vec = (0..n).collect(); + for k in (1..n).rev() { + order.swap(k, (next() * (k + 1) as f64) as usize); + } + let mut before = vec![]; + for a in 0..n { + for b in a + 1..n { + if next() < dense { + before.push(if next() < agrees { (order[a], order[b]) } else { (order[b], order[a]) }); + } + } + } + // The pairs in any order, and in every fifth set some of them twice. + for k in (1..before.len()).rev() { + before.swap(k, (next() * (k + 1) as f64) as usize); + } + if set % 5 == 0 { + let again: Vec<(usize, usize)> = before.iter().copied().filter(|_| next() < 0.3).collect(); + before.extend(again); + } + // No face drawn last, or up to four. + let last: Vec = (0..set % 5).map(|_| order[(next() * n as f64) as usize]).collect(); + let (drawn, _) = in_pairs_order(&order, &before, &last, usize::MAX); + // Keeping the search from stop to stop gives what looking afresh at every stop gives. + assert_eq!(drawn, in_pairs_order_plainly(&order, &before, &last), "set {set}: {order:?} {before:?} {last:?}"); + let (plainly, _) = in_pairs_order(&order, &before, &last, 0); + let mut once = drawn.clone(); + once.sort_unstable(); + assert_eq!(once, (0..n).collect::>(), "set {set}"); + for &cap in &last { + let (at, place) = (order.iter().position(|&f| f == cap).unwrap(), drawn.iter().position(|&f| f == cap).unwrap()); + assert!(order[..at].iter().all(|f| drawn[..place].contains(f)), "set {set}"); + } + let (rings, plain) = (broken(&drawn, &before).len(), broken(&plainly, &before).len()); + assert!(rings <= plain, "set {set}: {rings} pairs wrong, {plain} with the first face by depth; {order:?} {before:?} {last:?}"); + with_rings += rings; + without += plain; + fewer += usize::from(rings < plain); + } + assert!(fewer > 500 && with_rings < without, "{with_rings} pairs wrong, {without} with the first face by depth, fewer in {fewer} sets"); +} + /// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a /// face of the same shape's stroke drawn before it: the wall then goes just before that face. A /// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an diff --git a/docs/effects-parity.md b/docs/effects-parity.md index cb857e15cd..d4c3df8d2b 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -1,6 +1,6 @@ # Effects parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: Extrude & Bevel, Inflate and Rotate seams have round joins under a white light and in the 3D (Classic) effects too, no longer reaching past the solid as thorns; previously: Effect Gallery: a thumbnail for each filter and an in-dialog preview on an original drawing; the 1–2 h for those is done; Extrude & Bevel, Inflate and Rotate merge contours that cross, touch or overlap, as type often draws a glyph, before building a solid; previously: Extrude & Bevel, Inflate and Rotate apply to groups and layers, their objects turning about one shared axis (#4506); the Transform effect's copies of a path with a fill and a stroke (or several fills and strokes, an even-odd fill, or a partly transparent one) are drawn each above the one before, as Expand Appearance makes them (#5920); Expand Appearance makes each copy of a path's Transform effect an object of its own (#5612); previously: Pixelate › Color Halftone: Max Radius in pixels of the Document Raster Effects resolution, 4–127 px, with older documents converted on opening and radii written back in points for older app versions (#3260); Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); previously: Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (Extrude & Bevel, Inflate and Revolve: a ring of overlapping faces is broken at one of its own faces, so a face in front of a ring's face is not drawn under it, #7023; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: Extrude & Bevel, Inflate and Rotate seams have round joins under a white light and in the 3D (Classic) effects too, no longer reaching past the solid as thorns; previously: Effect Gallery: a thumbnail for each filter and an in-dialog preview on an original drawing; the 1–2 h for those is done; Extrude & Bevel, Inflate and Rotate merge contours that cross, touch or overlap, as type often draws a glyph, before building a solid; previously: Extrude & Bevel, Inflate and Rotate apply to groups and layers, their objects turning about one shared axis (#4506); the Transform effect's copies of a path with a fill and a stroke (or several fills and strokes, an even-odd fill, or a partly transparent one) are drawn each above the one before, as Expand Appearance makes them (#5920); Expand Appearance makes each copy of a path's Transform effect an object of its own (#5612); previously: Pixelate › Color Halftone: Max Radius in pixels of the Document Raster Effects resolution, 4–127 px, with older documents converted on opening and radii written back in points for older app versions (#3260); Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); previously: Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) Every entry of Illustrator's Effect menu, by its public feature name, against VectorCraft's effects catalogue (`effect_catalog()` in `crates/effects/src/lib.rs`) and the Effect menu built from it @@ -178,8 +178,8 @@ VectorCraft choices; an original approximation, never compared with another appl | Item | Ours | |---|---| -| Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims that also closes a partial sweep's cut sides, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | -| Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | +| Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims that also closes a partial sweep's cut sides, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, a ring of them broken at one of its own faces, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | +| Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, a ring of overlapping faces broken at one of its own faces, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art: none | | Turntable (30.0 beta) | none | @@ -193,6 +193,7 @@ angular cut caps, exact visibility, the rest of 3D Classic (Map Art), Turntable) | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | 3D and Materials: where faces put in the order of their depths where they overlap (Extrude & Bevel, Inflate, Revolve) lie in front of one another in a ring, a ring that waits for no face outside it gives up its own first face by depth, so a face in front of a ring's face is no longer drawn under it ([three-d.md](three-d.md), #7023; `a_face_in_front_of_a_cycle_waits_for_it` in `crates/effects/src/solids/tests.rs`). Scores and estimates unchanged. | | 2026-11-17 | minor | Distort & Transform › Twist: handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral instead of pieces meeting at kinks (#7069; `twist_joins_its_pieces_smoothly` in `crates/effects/src/tests.rs`). Scores and estimates unchanged. | | 2026-11-12 | minor | The seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins (the seams of Revolve and of colored lights, and 3D (Classic) Wireframe edges, were already round): no thorns on edge-on facets, and facets with no neighbor now have rounded convex corners ([three-d.md](three-d.md#seams)); scores and estimates unchanged | | 2026-11-10 | minor | Effect Gallery: each filter has a thumbnail, and the dialog has a preview of the visible stack (or the browsed filter when the stack is empty). Both are an original landscape drawing passed through the filter ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)). The canvas preview and one-undo OK are unchanged. Remaining hours for the gallery's thumbnails and in-dialog preview: 1–2 → none. Counts unchanged (57/57). | diff --git a/docs/revolve.md b/docs/revolve.md index 922a1218e2..c7de7062e6 100644 --- a/docs/revolve.md +++ b/docs/revolve.md @@ -111,7 +111,7 @@ with the standard command. - One Revolve per source object. Edit its options rather than applying another. - Object-level Revolve uses the top visible fill, falling back to a stroke. Per-item Revolve uses that item's paint. - Smooth diffuse shading, one to ten directional lights, no textures, cast shadows or physical materials. Smooth shading interpolates lighting in projected triangles; it does not smooth the silhouette or add specular highlights. -- Faces are drawn back to front by the depths of their centers. When that order draws the nearer of two overlapping faces of a surface first, every pair of overlapping faces goes in the order of their depths at the middle of where they overlap; the sort compares at most 4,000,000 pairs (VectorCraft's own limit), and the pairs past that keep the depths of their centers. Caps facing the camera cover their rim seams; a cap facing away is drawn behind the body except where it is nearer than a body face it overlaps. Intersecting profiles can have incorrect visibility. +- Faces are drawn back to front by the depths of their centers. When that order draws the nearer of two overlapping faces of a surface first, every pair of overlapping faces goes in the order of their depths at the middle of where they overlap; faces that lie in front of one another in a ring, so that no order draws them all correctly, give up the ring's own face that comes first by depth, as [Extrude & Bevel's do](three-d.md). The sort compares pairs and looks for rings within 4,000,000 steps in all (VectorCraft's own limit); the pairs past that keep the depths of their centers, and a ring past it is broken at the first face left by depth. Caps facing the camera cover their rim seams; a cap facing away is drawn behind the body except where it is nearer than a body face it overlaps. Intersecting profiles can have incorrect visibility. - Curves use sixteen samples per segment, and as few as four when a surface would otherwise pass its limits. Surfaces are limited to 16,384 profile points and 163,840 faces, the members of a group together. A straight segment takes one point, a curve takes at least four, and each contour takes one. Smooth shaded side quads become two triangles and share the face limit. A continuous cap retains its original radial mesh cost within this limit, and each region of a cut side counts as one face. Projected ring curves have a 0.001-point fitting tolerance and a shared 32,768-curve limit. - Axis, bounds and ordinary selection handles continue to refer to the editable 2D source profile. - Extrude & Bevel, Inflate and Rotate are described in [three-d.md](three-d.md). Materials remain unimplemented. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..f5d060fbee 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (3D: a ring of overlapping faces is broken at one of its own faces, so a face in front of a ring's face is not drawn under it, #7023; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -61,6 +61,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | 3D: where overlapping faces lie in front of one another in a ring, a ring that waits for no face outside it gives up its own first face by depth and the faces left are looked at afresh, so a face in front of a ring's face is no longer drawn under it, and no more pairs are drawn the wrong way round than before (#7023; `a_face_in_front_of_a_cycle_waits_for_it`, `breaking_a_ring_draws_no_more_pairs_wrong_than_the_first_face_by_depth` in `crates/effects/src/solids/tests.rs`). Scores and estimates unchanged. | | 2026-11-17 | minor | Distort & Transform › Twist: handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral instead of pieces meeting at kinks (#7069; `twist_joins_its_pieces_smoothly` in `crates/effects/src/tests.rs`). Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | @@ -1451,6 +1452,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With caps and opaque paint, Extrude & Bevel (both kinds) and Inflate draw each side face of the fill's solid before the faces of the same object's strokes that overlap it (strokes on closed paths without dashes, a width profile or a brush, in a solid color or an opaque gradient), so the stroke's walls cover the fill's walls at concave corners instead of showing stripes of the fill. Tests: `solids::tests::a_fills_walls_are_drawn_before_the_stroke_faces_over_them`, `solids::tests::the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps`, `solid::tests::facets_tell_the_sides_from_the_ends_and_the_faces_turned_away`. - When the fill and strokes are at full opacity with Normal blending, under a stroke that leaves parts of the fill's edge uncovered (dashed, with a width profile or a brush, on an open subpath, or in a paint that may show through), Extrude & Bevel (both kinds) and Inflate cut each stroke face that passes through a face of the fill's solid, or of another of the shape's strokes, where their depths meet, and draw the faces of the shape's fill and strokes that overlap in the order of their depths where they overlap, instead of by the depths of their centers. Inflate orders a plain stroke the same way, since its fill can rise in front of the stroke. The fill no longer paints over a nearer dash, and a dash's end no longer covers the fill wall in front of it; a fill wall in a gap between dashes stays visible. The same order applies inside a group member's own opacity mask or blending mode, to a gradient with transparent stops under a colored light with graphics on its caps, and to Inflate in gradients under a colored light. Tests: `solids::tests::fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap`, `solids::tests::local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order`, `solids::tests::a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet`, `solids::tests::a_masked_members_fill_and_stroke_faces_go_in_one_order`, `solids::tests::a_colored_inflate_in_gradients_draws_its_faces_in_one_order`, `solids::tests::a_depth_cycle_keeps_the_cap_last`, `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`. - A graphic mapped onto Extrude & Bevel's cap or onto a Plane is drawn once when the fill is a gradient with transparent stops under a colored light and the object has a stroke (dashed or plain) with the same opacity and blending mode: the fill and stroke share it, as they do without the mask, and it is drawn after the stroke's cap with the mask of the stroke's surface (none for an opaque stroke), instead of once on the fill's cap and again on the stroke's. Members of a 3D group drawn with a mask keep graphics of their own. Unmasked fills and strokes alone draw as before. Tests: `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`, `solids::graphics::tests::a_plane_in_a_transparent_gradient_with_a_stroke_draws_its_graphic_once`, `solids::graphics::tests::members_in_transparent_gradients_keep_graphics_of_their_own`. + - Where the faces put in the order of their depths where they overlap lie in front of one another in a ring (a strongly connected component of the pairs), the faces that go before the first face left by depth are followed back, among the faces that come before the next face drawn last, to a ring that waits for no other of them, and that ring gives up its own face that comes first by depth; the faces left are then looked at afresh, since they may be a smaller ring or none. So a face that is in front of a face of a ring without being part of it is drawn after that face rather than first, and the pairs drawn the wrong way round are pairs of a ring, or pairs of a face with a face drawn last or one that follows it, when that one should have gone first (a face drawn last, such as a cap, still follows every face before it by depth). On 6,000 sets of pairs at random this drew no more pairs the wrong way round than taking the first face left by depth, in any set, and fewer in all; giving up the ring's face that waits for the fewest faces drew fewer still in all but more in one to five sets in a hundred, so it was not chosen. The steps count toward the 4,000,000 the comparing of pairs counts toward (VectorCraft's own limit, one for both): a step for each face and pair looked at while looking for rings (making the lists a ring is looked for in, a step a pair, is not counted). The search goes on from where it stopped at the last ring, and a face that is drawn is dropped from a list the next time the list is looked at, so rings of a few faces take a few steps a face whether they stand apart, all lie behind one face or lie one behind the other. A ring that is still a ring after it gives up a face is walked again from the face the search reached it by, so a large ring can cost about its pairs for each face it gives up, the square of its faces even when each waits for few others (3,200 faces with four pairs each at random take about 3,000,000 steps, and about 4,000 reach the limit); and a face at or after the next face drawn last is passed over again each time a face that waits for it is looked at. A first face left that waits only for the next face drawn last or faces after it goes next with no search, at no cost. The pairs are kept as lists of 4 bytes a pair, once for the faces after each face and once more for the faces before each face when a ring is first looked for, and only when the steps left are at least a quarter of the pairs, so making them costs no more than four times the steps left; with fewer, no ring is looked for, so a solid whose comparing of pairs leaves less than a quarter of its pairs of the limit breaks its rings at the first face left by depth, as before. Past the limit the first face left by depth goes next, ring or not, as before, and a face drawn last still follows every face before it by depth (#7023). Revolve's faces share the order. Tests: `solids::tests::a_face_in_front_of_a_cycle_waits_for_it`, `solids::tests::the_faces_left_are_looked_at_afresh_after_each_face_released`, `solids::tests::the_ring_released_waits_for_no_face_outside_it`, `solids::tests::a_ring_is_looked_for_before_the_next_face_drawn_last`, `solids::tests::breaking_a_ring_draws_no_more_pairs_wrong_than_the_first_face_by_depth`, `solids::tests::breaking_rings_stops_at_its_room`, `solids::tests::breaking_rings_takes_a_few_steps_a_face_but_for_a_ring_of_many_pairs`, `solids::tests::a_face_that_waits_only_for_the_face_drawn_last_costs_no_search`, `solids::tests::the_lists_for_rings_are_made_only_with_room_for_a_quarter_of_the_pairs`, `solids::tests::a_list_longer_than_the_room_left_is_not_read`, `solids::tests::a_depth_cycle_keeps_the_cap_last`. - Revolve and Revolve (Classic) draw two overlapping faces of a surface in the order of their depths where they overlap, instead of by the depths of their centers, on one object and across a group's members, so a tilted profile with long edges or a profile of several contours no longer draws a nearer face under a farther one. A surface whose faces were already in the right order keeps it. Tests: `solids::tests_revolve_order::a_revolved_surface_draws_the_nearer_of_two_overlapping_faces_last`, `solids::tests_revolve_order::a_revolved_groups_members_draw_the_nearer_of_two_overlapping_faces_last`, `solids::tests_revolve_order::a_classic_revolved_surface_draws_the_nearer_of_two_overlapping_facets_last`, `solids::tests_revolve_order::a_surface_already_in_order_keeps_it`, `solids::tests_revolve_order::surface_order_puts_the_nearer_face_where_they_overlap_last`, `tests::a_revolved_face_measures_its_depth_on_its_plane`. - Under a colored light, an Inflate fill and strokes in solid colors, opaque with Normal blending, also draw their faces in that one order, inside a group member's own opacity mask too, instead of each solid as one composite with the stroke's faces over every fill face. Each face keeps the composite's paint, light ramps and seam width; a lone solid, the solids of an object with a translucent or blended fill or stroke, and such solids holding more than 30,720 faces together (VectorCraft's own limit) are still drawn as one composite each. Tests: `solids::tests::colored_solid_fills_and_strokes_share_face_depth_order`, `solids::tests::a_colored_solid_face_on_its_own_keeps_the_composites_colors`, `solids::tests::colored_solid_inflate_batches_channels_and_clips_once_per_surface`, `solids::tests::colored_solids_past_the_face_limit_draw_as_composites`. - Without a twist, a tapered Extrude & Bevel wall (and each bevel band) is one flat face; only a twist cuts walls into slices, so no seam between slices paints a light tick or a light line on a tapered, untwisted wall (#7019). Test: `solid::tests::a_tapered_wall_is_one_flat_face_and_a_twisted_one_is_sliced`. diff --git a/docs/three-d.md b/docs/three-d.md index 4f8d4003b5..d8ee25a857 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -199,18 +199,27 @@ The rest is our reading: uncovered, such as the gaps between dashes. Each face of such a stroke that passes through a face of the fill's solid, or through a face of another of the shape's strokes, where the two overlap in the drawing is cut where their depths meet, and the faces of the shape's fill and strokes that overlap are drawn in the order of their - depths where they overlap, with caps on or off. A fill wall in a gap stays in its own depth order. Inflate's - curved surfaces follow this only as closely as their flat facets do. A solid painted with a gradient that has - transparent stops under a light that is not white is drawn with an opacity mask: its faces keep their places in - this order, in runs that each carry the mask, and a graphic drawn after one of its faces carries the mask too - ([Graphics](#graphics)). Such a gradient, and a gradient with transparent stops under the classic effects' - shading, is placed once on the whole solid when it has no placement of its own, so its colors and its - transparency line up across the faces. A member of a 3D group with its own opacity - mask or blending mode draws its fill's and strokes' faces in this order inside that mask or blending mode when - they are opaque with Normal blending. Otherwise each solid is drawn on its own with its opacity and blending, the - lower item's first. With a light that is not white, a puffed, shaded Inflate surface in a solid color takes its - place in this order too, each of its faces drawn with its own light ramps; a lone solid of that kind is still - drawn as one composite, and so is each such solid when they hold more than 30,720 faces together. + depths where they overlap, with caps on or off. A fill wall in a gap stays in its own depth order. Where such + faces lie in front of one another in a ring, so that no order draws them all correctly, a ring that waits for no + face outside it gives up its own face that comes first in the order of their depths, and the faces left are + looked at afresh, as they may be a smaller ring or none. A face that is only in front of a face of a ring is + still drawn after that face. Comparing the faces and looking for rings share one limit of 4,000,000 steps + (VectorCraft's own). Rings of a few faces take a few steps a face. A ring that is still a ring after it gives up + a face is walked again, so a large ring can cost about the square of its faces (some 4,000 faces tangled at + random reach the limit). The lists a ring is looked for in are made only when the steps left are at least a + quarter of the pairs, so a solid whose comparing uses nearly all of the limit breaks its rings as before; and a + face that waits only for a face drawn last goes in its turn with no search. Past the limit the first face left by + depth goes next, ring or not. Inflate's curved surfaces follow this only as closely as their flat facets do. A + solid painted with a gradient that has transparent stops under a light that is not white is drawn with an opacity + mask: its faces keep their places in this order, in runs that each carry the mask, and a graphic drawn after one + of its faces carries the mask too ([Graphics](#graphics)). Such a gradient, and a gradient with transparent stops + under the classic effects' shading, is placed once on the whole solid when it has no placement of its own, so its + colors and its transparency line up across the faces. A member of a 3D group with its own opacity mask or + blending mode draws its fill's and strokes' faces in this order inside that mask or blending mode when they are + opaque with Normal blending. Otherwise each solid is drawn on its own with its opacity and blending, the lower + item's first. With a light that is not white, a puffed, shaded Inflate surface in a solid color takes its place + in this order too, each of its faces drawn with its own light ramps; a lone solid of that kind is still drawn as + one composite, and so is each such solid when they hold more than 30,720 faces together. - The solids turn, twist and taper about the center of the bounds of all their shapes, Inflate's grid covers those bounds, and with Perspective one eye sees every solid. A stroke too narrow to hold a point of Inflate's grid stays flat. @@ -627,6 +636,7 @@ Release measurements and a repeatable CLI scene are in [3D lighting performance] | Date | Change | |---|---| +| 2026-11-17 | Where overlapping faces lie in front of one another in a ring, the ring's own first face by depth is drawn before the faces of the ring it waits for and the rest are looked at afresh, so a face in front of a ring's faces without being one of them is no longer drawn under them (#7023). | | 2026-11-13 | Extrude & Bevel cuts its walls into slices only for a twist. A taper alone keeps each wall flat, so it is one face, without the light ticks at the joints between slices or the light line down a wall (#7019). Inflate still slices its sides for a taper. | | 2026-11-12 | The seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins (the seams of Revolve and of colored lights, and 3D (Classic) Wireframe edges, were already round): no thorns on edge-on facets, and facets with no neighbor now have rounded convex corners ([Seams](#seams)). | | 2026-11-08 | Contours that cross, touch or overlap are merged by vectorcraft-pathops before Extrude & Bevel, Inflate and Rotate build a solid, sharing its limits; others are built as drawn. | From 17d9f39eaf4086b176e10cd7fbff85ff71d8456d Mon Sep 17 00:00:00 2001 From: Drew Dibble Date: Tue, 17 Nov 2026 21:17:29 -0700 Subject: [PATCH 11/91] Docs: the #7023 ring fix in the roadmap's M9 row, status line and revision history --- docs/roadmap.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 258b86d04a..3a6020bc8d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (3D: a ring of overlapping faces is broken at one of its own faces, so a face in front of a ring's face is not drawn under it, #7023; scores and estimates unchanged; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -165,7 +165,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | -| M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | +| M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets, a ring of overlapping faces broken at one of its own faces (#7023); SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | @@ -212,6 +212,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | 3D (#7023): where overlapping faces of a solid lie in front of one another in a ring, the sort drew the first face left by depth when no face could go next, whether or not that face was in the ring, so a face only in front of a ring's face could be drawn under it. A ring that waits for no face outside it now gives up its own first face by depth. Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | | 2026-11-16 | minor | PDF import: fill and stroke rendering (text rendering modes 2 and 6) draws all the glyphs of a text-showing operator (`Tj`, `TJ`, `'`, `"`) filled, then the same glyphs stroked, so a word shown at once came in as two type objects: a stroke-only copy over a fill-only one. Each stroke is now matched, in order, to the glyph filled with the same placement (where, how large, how wide, slanted and turned) in the same font with the same text on the line, and only that glyph takes the stroke, so the word comes in as one type object, filled and stroked; glyphs stroked with another join part way through still split into runs of their own, and stroked type over no filled glyph (modes 1 and 5) stays stroke only (#8015; `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. | From 214493b44c8abfba10b59d12f20397e3280771b6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 18:27:24 -0800 Subject: [PATCH 12/91] =?UTF-8?q?Scripts:=20the=20Other=20Script=E2=80=A6?= =?UTF-8?q?=20warning=20lists=20what=20the=20script=20reaches=20outside=20?= =?UTF-8?q?the=20document?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The warning before File › Scripts › Other Script… runs a script now runs script.check on it, which does not run any of it, and lists what the check finds: each outside-the-document category of the report (files the script writes, moves or deletes, files it opens in other apps, messages to other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has, and the files its `#include` lines name. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short at its limit. A script that reaches nothing gets the warning as before. The labels are Check Script…'s. Run still runs the script. The report is in the dialog's protected `__reaches` field, which ui.dialog.set cannot change. Scripts from the Scripts folder still run without the warning. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/script_check.rs | 10 +-- crates/ui-egui/src/dialogs/script_run.rs | 88 ++++++++++++++++++- crates/ui-egui/src/tests/script_run.rs | 99 ++++++++++++++++++++++ docs/mcp.md | 9 +- docs/target-app-parity.md | 1 + 6 files changed, 200 insertions(+), 9 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..da4575a87b 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -2029,7 +2029,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`, and `__reaches`: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker)", ), ( "ui.runInstalledScript", diff --git a/crates/ui-egui/src/dialogs/script_check.rs b/crates/ui-egui/src/dialogs/script_check.rs index e134cf1b39..fd22e6bd11 100644 --- a/crates/ui-egui/src/dialogs/script_check.rs +++ b/crates/ui-egui/src/dialogs/script_check.rs @@ -123,7 +123,7 @@ pub(crate) fn problem_label(code: &str) -> Option<&'static str> { } /// Where something is: `line 12`, or `lib/a.jsxinc, line 3` in an included file. -fn place(item: &Value) -> String { +pub(super) fn place(item: &Value) -> String { let line = item["line"].as_u64().map(|l| l.to_string()); match (item["file"].as_str(), line) { (Some(file), Some(line)) => crate::i18n::fmt(tl!("{file}, line {line}"), &[("file", file), ("line", &line)]), @@ -164,7 +164,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } /// A row of a section: `text` (user data in `mono`), then a count and lines, dimmed. -fn row(ui: &mut egui::Ui, t: &Tokens, text: &str, mono: bool, note: &str) { +pub(super) fn row(ui: &mut egui::Ui, t: &Tokens, text: &str, mono: bool, note: &str) { ui.horizontal_wrapped(|ui| { let text = egui::RichText::new(text).color(t.text_strong); ui.label(if mono { text.monospace() } else { text.size(12.5) }); @@ -175,7 +175,7 @@ fn row(ui: &mut egui::Ui, t: &Tokens, text: &str, mono: bool, note: &str) { } /// `count` and `lines` of an entry as a note: `3 · lines 4, 9, 12`. -fn tally(item: &Value) -> String { +pub(super) fn tally(item: &Value) -> String { let count = item["count"].as_u64().unwrap_or_default(); match lines(item) { l if l.is_empty() => count.to_string(), @@ -183,13 +183,13 @@ fn tally(item: &Value) -> String { } } -fn section(ui: &mut egui::Ui, heading: &str, rows: impl FnOnce(&mut egui::Ui)) { +pub(super) fn section(ui: &mut egui::Ui, heading: &str, rows: impl FnOnce(&mut egui::Ui)) { ui.add_space(8.0); widgets::section_header(ui, heading); rows(ui); } -fn list<'r>(r: &'r Value, key: &str) -> &'r [Value] { +pub(super) fn list<'r>(r: &'r Value, key: &str) -> &'r [Value] { r[key].as_array().map_or(&[][..], Vec::as_slice) } diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f8baa7b7de..94f53b7ca0 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -5,7 +5,16 @@ //! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it //! asks for a `.js` or `.jsx` file (the web opens the browser's file picker). With Preferences › //! General › Show External Script Warning off, the chosen script runs at once. Warning fields: -//! `name`, `script` (`script.run`'s params) and `dontShow` (true: turn the warning off). +//! `name`, `script` (`script.run`'s params), `dontShow` (true: turn the warning off) and +//! `__reaches`, which `ui.dialog.set` cannot set: the `kind`, `needs`, `outside`, `includes` and +//! `truncated` of `script.check`'s report on the script, read without running it (a path also +//! checks the files its `#include` lines name), or null when the check fails. The warning lists +//! what the report finds the script reaches outside the document (each of `script.check`'s +//! `outside` categories, such as files it writes, moves or deletes, files it opens in other apps, +//! the network, native code, environment variables and code the checker can't read), the files +//! and dialogs it needs, features only the reference app has, and its includes. It says when the +//! script is too large to check, compiled or not a script, when the check failed, and when a list +//! was cut short at its limit. The listing is information: Run runs the script as before. //! //! A script's dialog (kind `scriptDialog`) has the fields `kind` (alert, confirm or prompt), //! `message`, `title` (null: Script Alert), `errorIcon`, `noAsDefault` and `value` (the prompt's @@ -151,15 +160,90 @@ pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result Value { + let check = match (params.get("path"), params.get("source")) { + (Some(path), _) => json!({"path": path, "includes": true}), + (None, Some(source)) => json!({"data": source}), + (None, None) => return Value::Null, + }; + let Ok(r) = app.session.execute("script.check", &check) else { return Value::Null }; + json!({"kind": r["kind"], "needs": r["needs"], "outside": r["outside"], "includes": r["includes"], "truncated": r["truncated"]}) +} + +/// What the report `r` finds the script reaches outside the document; nothing for a script that +/// was checked and reaches nothing. A failed check (null) says the script was not read. +fn reach_rows(ui: &mut egui::Ui, r: &Value, t: &Tokens) { + use super::script_check::{list, need_label, outside_label, place, row, section, status_label, tally}; + let unchecked = match r["kind"].as_str() { + Some("script") => None, + Some("compiled") => Some(tl!("Compiled script: ask its author for the .jsx file")), + Some("tooLarge") => Some(tl!("Too large to check")), + _ if r.is_null() => Some(tl!("Not read")), + _ => Some(tl!("Not a script for the reference app")), + }; + if let Some(text) = unchecked { + ui.add_space(8.0); + widgets::dim_label(ui, text); + return; + } + let outside: Vec<(&str, &Value)> = list(r, "outside").iter().filter_map(|o| Some((o["id"].as_str().and_then(outside_label)?, o))).collect(); + let needs: Vec<&str> = + list(r, "needs").iter().filter_map(Value::as_str).filter(|n| matches!(*n, "files" | "dialogs" | "hostOnly")).filter_map(need_label).collect(); + let includes = list(r, "includes"); + let truncated = r["truncated"].as_bool() == Some(true); + if outside.is_empty() && needs.is_empty() && includes.is_empty() && !truncated { + return; + } + ui.add_space(8.0); + widgets::dim_label(ui, tl!("VectorCraft read this script without running it.")); + egui::ScrollArea::vertical().id_salt("script-reaches").max_height(220.0).show(ui, |ui| { + if !outside.is_empty() || !needs.is_empty() { + section(ui, tl!("Outside the document"), |ui| { + for (label, o) in outside { + let modes: Vec<&str> = list(o, "modes").iter().filter_map(Value::as_str).collect(); + let label = if modes.is_empty() { label.to_string() } else { format!("{label} ({})", modes.join(", ")) }; + row(ui, t, &label, false, &tally(o)); + } + for need in needs { + row(ui, t, need, false, ""); + } + }); + } + if !includes.is_empty() { + section(ui, tl!("Includes"), |ui| { + for i in includes { + let status = i["status"].as_str().and_then(status_label).unwrap_or_default(); + let note = [status.to_string(), place(i)].into_iter().filter(|s| !s.is_empty()).collect::>().join(" · "); + row(ui, t, i["value"].as_str().unwrap_or_default(), true, ¬e); + } + }); + } + }); + if truncated { + ui.add_space(6.0); + widgets::dim_label(ui, tl!("Some lists were cut short at their limit.")); + } +} + fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new(d.fields.get("name").and_then(Value::as_str).unwrap_or_default()).font(theme::semibold(12.5)).color(t.text_strong)); ui.add_space(4.0); ui.label(tl!("A script can change the open documents and can write files through the commands it runs. Run only scripts you trust.")); + if let Some(r) = d.fields.get(REACHES) { + reach_rows(ui, r, &t); + } ui.add_space(8.0); let dont_show = d.fields.get("dontShow").and_then(Value::as_bool).unwrap_or(false); if widgets::check(ui, tl!("Do not show this warning again"), dont_show, true) { diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fee27caa13..579f55b4e4 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -640,6 +640,105 @@ fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { finish(&mut app); } +/// The warning before a run lists the files the script writes, read without running it. +#[test] +fn the_warning_lists_the_files_a_script_writes() { + let mut app = app(); + let source = "var f = new File(Folder.temp + '/out.txt');\nf.open('w');\nf.write('x');\nf.close();\n"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "write.js"})).unwrap().unwrap(); + assert!(!app.session.script_running()); + let texts = dialog_texts(&mut app); + let writes = dialogs::script_check::outside_label("filesWritten").unwrap(); + assert!(texts.iter().any(|t| t.starts_with(writes) && t.contains("(w)")), "{texts:?}"); + assert!(texts.iter().any(|t| t == dialogs::script_check::need_label("files").unwrap()), "{texts:?}"); + assert!(texts.iter().any(|t| t == "Outside the document"), "{texts:?}"); + // The warning holds the report as `__reaches`, which `ui.dialog.set` cannot change. + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["__reaches"]["outside"][0]["id"], "filesWritten"); + assert!(dialogs::protected_field(d, "__reaches")); + dialogs::cancel(&mut app); + finish(&mut app); +} + +/// A script that reaches nothing outside the document gets the warning with nothing more. +#[test] +fn the_warning_for_a_script_that_reaches_nothing_lists_nothing_more() { + let mut app = app(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": DRAW, "name": "draw.js"})).unwrap().unwrap(); + let texts = dialog_texts(&mut app); + assert!(texts.iter().any(|t| t.starts_with("A script can change the open documents")), "{texts:?}"); + for heading in ["Outside the document", "Includes", "VectorCraft read this script without running it."] { + assert!(!texts.iter().any(|t| t == heading), "{heading}: {texts:?}"); + } + confirm(&mut app).unwrap(); + finish(&mut app); + assert_eq!(objects(&app), 2); +} + +/// A script file's warning also lists what the files its `#include` lines name reach. +#[test] +fn the_warning_lists_what_a_scripts_included_files_reach() { + let mut app = app(); + let dir = folder("includes"); + std::fs::create_dir_all(dir.join("lib")).unwrap(); + std::fs::write(dir.join("main.jsx"), "#include 'lib/net.jsxinc'\n").unwrap(); + std::fs::write(dir.join("lib/net.jsxinc"), "var s = new Socket();\n").unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": dir.join("main.jsx").to_string_lossy()})).unwrap().unwrap(); + let texts = dialog_texts(&mut app); + assert!(texts.iter().any(|t| t == "lib/net.jsxinc"), "{texts:?}"); + assert!(texts.iter().any(|t| t == dialogs::script_check::need_label("hostOnly").unwrap()), "{texts:?}"); + dialogs::cancel(&mut app); + finish(&mut app); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A script the checker could not read as a script gets a warning that says so, not the warning of +/// a script that was checked and reaches nothing. +#[test] +fn the_warning_says_when_a_script_was_not_checked() { + let missing = std::env::temp_dir().join(format!("vc-script-run-ui-missing-{}.js", std::process::id())); + for (params, text) in [ + (json!({"source": "export const b = 2;", "name": "module.js"}), "Not a script for the reference app"), + (json!({"source": "var a = 1;\u{0}", "name": "binary.js"}), "Not a script for the reference app"), + (json!({"source": "@JSXBIN@ES@2.0@MyBbyBn0ABJAnA", "name": "compiled.js"}), "Compiled script: ask its author for the .jsx file"), + (json!({"path": missing.to_string_lossy()}), "Not read"), + ] { + let mut app = app(); + menus::run_ui_command(&mut app, "ui.runScript", ¶ms).unwrap().unwrap(); + let texts = dialog_texts(&mut app); + assert!(texts.iter().any(|t| t == text), "{params}: {texts:?}"); + dialogs::cancel(&mut app); + finish(&mut app); + } +} + +/// A script whose report was cut short at a list's limit says so, also when nothing else is listed. +#[test] +fn the_warning_says_when_a_list_was_cut_short() { + let mut app = app(); + let source: String = (0..=1000).map(|n| format!("x = app.m{n};\n")).collect(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "many.js"})).unwrap().unwrap(); + let texts = dialog_texts(&mut app); + assert!(texts.iter().any(|t| t == "Some lists were cut short at their limit."), "{texts:?}"); + dialogs::cancel(&mut app); + finish(&mut app); +} + +/// A script over the checker's size limit gets a warning that says it was too large to check. +#[test] +fn the_warning_says_when_a_script_is_too_large_to_check() { + let mut app = app(); + let dir = folder("large"); + let path = dir.join("large.js"); + std::fs::write(&path, vec![b' '; vectorcraft_engine::script::MAX_SOURCE_BYTES + 1]).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap(); + let texts = dialog_texts(&mut app); + assert!(texts.iter().any(|t| t == "Too large to check"), "{texts:?}"); + dialogs::cancel(&mut app); + finish(&mut app); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_new_app_shows_the_warning_by_default() { assert!(Session::new().prefs.show_external_script_warning); diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..b0b7d1cfe3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2605,7 +2605,14 @@ vectorcraft-cli run --cmd script.check --params '{"path": "Tidy Layers.jsx"}' `script.run {path? | source?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents. File › Scripts › Other Script… (Cmd+F12) picks a `.js` or `.jsx` file and runs it the same way; the help page https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html -describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any +describes that menu item. Its warning before the run lists what `script.check` finds the script reaches outside +the document, read without running it: each `outside` category of the report (files it writes, moves or deletes, +files it opens in other apps, messages to other apps, the network, native code, environment variables, the reference +app's preferences and code the checker can't read), the files and dialogs it needs, features only the reference app +has, and the files its `#include` lines name. It says when the script is too large to check, compiled or not a +script, when the check failed, and when a list was cut short at its limit. The listing does not stop the run. A +script from the Scripts folder runs without the warning. +Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and `ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..3e6fa55d4b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,6 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. + - Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`. - Scripts: a canceled request stops a run that sleeps in `$.sleep`, waits at a dialog or waits for approval to grow at the run's next slice, before its wake time or an answer, and every document goes back to its state before the run. VectorCraft's own rule. `crates/engine/src/tests/script_dollar.rs`, `crates/engine/src/tests/script_dialogs.rs`, `crates/engine/src/tests/script_run.rs`. From d62c72305667415a97dd0615f44565c7feb407a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 06:22:17 -0800 Subject: [PATCH 13/91] Scripts: ui.runScript's source description lists the warning's __reaches The generated catalog in crates/mcp/src/ui_catalog.rs described the `__reaches` field of the `scriptRun` dialog, but the source entry in crates/ui-egui/src/menus/ui_commands.rs did not, so `cargo xtask ui-commands --check` failed. The source entry now carries the same text. --- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..4f8d017b1c 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -2030,7 +2030,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`, and `__reaches`: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker)", ), ( crate::scripts_menu::COMMAND, From 7c9b2a85a24397622a49b0137f0eadad7a095b58 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:27:56 -0800 Subject: [PATCH 14/91] Scripts: text frames, text ranges and fonts for scripts document.textFrames lists the document's type and makes point type, area type and type on a path. A TextFrame gives its kind, contents, text range, characters, words and paragraphs, outlines, and point and area conversion. A TextRange gives its contents, offsets, sub-collections, character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after). app.textFonts lists the fonts. Offsets count UTF-16 code units. A range follows edits made through these objects and throws Stale text range after the frame's text changes another way. Each change runs an existing text command inside the run's transaction, and a value a range already has runs no command. --- crates/engine/src/script/dom.rs | 18 +- crates/engine/src/script/dom/text.rs | 1557 +++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_text.rs | 394 +++++ .../tests/it/script_host_vs_scriptcheck.rs | 61 +- docs/mcp.md | 46 + docs/target-app-parity.md | 3 +- 7 files changed, 2072 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/script/dom/text.rs create mode 100644 crates/engine/src/tests/script_text.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 241720f786..d467345a2c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod text; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -92,6 +94,7 @@ pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + text: text::TextState, } impl State { @@ -151,7 +154,7 @@ fn method(link: &Link, f: Member) -> HostMember { } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document or page item `this` is still there. +/// the check that a document, page item or text range `this` is still there. fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); @@ -162,9 +165,12 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" => { + "PageItem" | "TextFrame" => { item_of(&h, arg(&a, 0))?; } + "TextRange" => { + text::check_range(&h, arg(&a, 0))?; + } _ => {} } Err(HostError::Error(message.clone())) @@ -1707,6 +1713,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { + text::install_enums(realm)?; for (name, members) in ENUMS { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; @@ -1720,6 +1727,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), ]); + application.push(("textFonts".into(), text::app_text_fonts(l))); application.push(later(l, "Application", "beep")); let preset = { let l = link.clone(); @@ -1758,10 +1766,11 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin)), ("convertCoordinate", method(l, doc_convert)), ("pageItems", get(l, doc_page_items)), + ("textFrames", text::doc_text_frames(l)), ("selection", property(l, doc_selection, doc_set_selection)), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] + ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] .into_iter() .map(|m| later(l, "Document", m)), ); @@ -1828,7 +1837,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "PageItem", m)), ); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(text::classes(l)); classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs new file mode 100644 index 0000000000..fb2bd54daa --- /dev/null +++ b/crates/engine/src/script/dom/text.rs @@ -0,0 +1,1557 @@ +//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its +//! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and +//! `paragraphAttributes`, and `app.textFonts`, as the help pages +//! , +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so +//! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves +//! out to the whole character. One item of `characters` is one code point. +//! - `contents` gives each paragraph break as `\r` and each forced line break as `\u0003`; written +//! text may use `\r`, `\n` or `\r\n` for a paragraph break. +//! - A word is a run of characters that are not white space. A paragraph ends after its break, and +//! a range's `words` and `paragraphs` are the whole words and paragraphs it touches. +//! - A range keeps its place while the script edits the frame through the object model: an edit +//! before it moves it, an edit over it shrinks it to the edit, and an insertion at one of its +//! ends joins it. When the frame's text changes in any other way (`vc.run`, an undo), every +//! range made before is stale and throws `Stale text range`. +//! - A character attribute read on a range whose characters differ gives the first character's +//! value; set on an empty range it changes nothing. A paragraph attribute reads the first +//! paragraph the range touches and sets every one of them. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; +use std::sync::{Arc, Weak}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref}; + +use super::{ + Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item, editable, float, + frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, typename_of, + whole, with_doc, +}; +use crate::{DocState, Document, NodeId, NodeKind}; + +/// The error of a text range, or of a collection of one, whose frame's text changed other than +/// through the object model. +pub const STALE_RANGE: &str = "Stale text range"; +/// The most edits a frame keeps for moving its ranges; a range made before the oldest kept edit +/// is stale. +const MAX_EDITS: usize = 100_000; + +/// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units. +pub(super) struct Index { + text: String, + /// The UTF-16 offset of each character's start, and the text's length last. + chars: Vec, + /// The byte offset of each character's start, and the text's length in bytes last. + bytes: Vec, + words: Vec<(usize, usize)>, + paras: Vec<(usize, usize)>, +} + +impl Index { + fn new(text: String) -> Self { + let mut chars = Vec::with_capacity(text.len() + 1); + let mut bytes = Vec::with_capacity(text.len() + 1); + let (mut words, mut paras) = (Vec::new(), Vec::new()); + let (mut u, mut word, mut para) = (0, None, 0); + for (b, c) in text.char_indices() { + chars.push(u); + bytes.push(b); + if c.is_whitespace() { + if let Some(w) = word.take() { + words.push((w, u)); + } + } else if word.is_none() { + word = Some(u); + } + u += c.len_utf16(); + if c == '\n' { + paras.push((para, u)); + para = u; + } + } + if let Some(w) = word { + words.push((w, u)); + } + paras.push((para, u)); + chars.push(u); + bytes.push(text.len()); + Self { text, chars, bytes, words, paras } + } + + fn len(&self) -> usize { + self.chars.last().copied().unwrap_or(0) + } + + /// The byte offset of UTF-16 offset `u`; inside a surrogate pair, the start of its character, + /// or with `up` the end of it. + fn byte(&self, u: usize, up: bool) -> usize { + let i = self.chars.partition_point(|&c| c < u); + match self.chars.get(i) { + Some(&c) if c == u || up => self.bytes.get(i).copied().unwrap_or(self.text.len()), + _ => i.checked_sub(1).and_then(|i| self.bytes.get(i)).copied().unwrap_or(0), + } + } + + /// The characters whose start is in `s..e`, each as a UTF-16 span. + fn chars_in(&self, s: usize, e: usize) -> std::ops::Range { + let count = self.chars.len().saturating_sub(1); + let a = self.chars[..count].partition_point(|&c| c < s); + let b = self.chars[..count].partition_point(|&c| c < e); + a..b.max(a) + } + + fn char_span(&self, i: usize) -> Option<(usize, usize)> { + Some((*self.chars.get(i)?, *self.chars.get(i + 1)?)) + } +} + +/// The words or paragraphs of `spans` that `s..e` touches: those it overlaps, or, for an empty +/// range, the one with a character at it, or the last one when it ends there. Only an empty range +/// touches the empty paragraph after a break at the end of the text. +fn touched(spans: &[(usize, usize)], s: usize, e: usize) -> std::ops::Range { + if s == e { + let i = spans.partition_point(|&(_, y)| y <= s); + if spans.get(i).is_some_and(|&(x, _)| x <= s) { + return i..i + 1; + } + return match spans.last() { + Some(&(_, y)) if i == spans.len() && y == s => i - 1..i, + _ => i..i, + }; + } + let a = spans.partition_point(|&(_, y)| y <= s); + let b = spans.partition_point(|&(x, _)| x < e); + a..b.max(a) +} + +#[derive(Clone, Copy)] +struct Edit { + stamp: u64, + at: usize, + removed: usize, + inserted: usize, +} + +/// What the object model knows of one frame's text: the document it was read from, the text, the +/// edits made through the model, and the oldest range generation still valid. +struct Log { + doc: Weak, + index: Rc, + stamp: u64, + floor: u64, + edits: Vec, +} + +/// A document's uid, the document, and the ids of its type objects then. +type FrameList = (u64, Weak, Rc>); + +/// Word or paragraph spans, in UTF-16 units. +type Spans = [(usize, usize)]; + +/// The text state of one run. +#[derive(Default)] +pub(in crate::script) struct TextState { + frames: RefCell>, + /// A document's uid, the document, and the ids of its type objects in paint order. + list: RefCell>, + /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character + /// names that is not installed is added at the end. + fonts: RefCell>>, +} + +fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { + match &st.doc.node(id)?.kind { + NodeKind::Text(t) => Some(t), + _ => None, + } +} + +fn same_text(t: &TextObject, s: &str) -> bool { + let mut rest = s; + for r in &t.runs { + match rest.strip_prefix(r.text.as_str()) { + Some(after) => rest = after, + None => return false, + } + } + rest.is_empty() +} + +/// The frame's index and its generation now, read again when its document changed. +fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc, u64), HostError> { + let t = text_of(st, id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let mut frames = h.dom.text.frames.borrow_mut(); + let key = (st.uid, id.0); + let now = Arc::as_ptr(&st.doc); + match frames.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) => {} + Some(l) => { + if !same_text(t, &l.index.text) { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + l.index = Rc::new(Index::new(t.plain_text())); + } + l.doc = Arc::downgrade(&st.doc); + } + None => { + let l = Log { doc: Arc::downgrade(&st.doc), index: Rc::new(Index::new(t.plain_text())), stamp: 0, floor: 0, edits: Vec::new() }; + frames.insert(key, l); + } + } + let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok((l.index.clone(), l.stamp)) +} + +/// A text range: its frame, its span in UTF-16 units and the generation it was made at. +#[derive(Clone, Copy)] +struct Span { + item: Item, + start: usize, + end: usize, + stamp: u64, +} + +/// The span and index of `r` now. +fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u64), HostError> { + with_doc(h, r.item.doc, |_, st| { + let (index, stamp) = observe(h, st, r.item.id)?; + let frames = h.dom.text.frames.borrow(); + let l = frames.get(&(st.uid, r.item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + if r.stamp < l.floor || r.stamp > l.stamp { + return Err(HostError::Error(STALE_RANGE.into())); + } + let (mut s, mut e) = (r.start, r.end); + let from = l.edits.partition_point(|x| x.stamp <= r.stamp); + for x in &l.edits[from..] { + let moved = |v: usize| v - x.removed + x.inserted; + s = if s <= x.at { + s + } else if s >= x.at + x.removed { + moved(s) + } else { + x.at + }; + e = if e < x.at { + e + } else if e >= x.at + x.removed { + moved(e) + } else { + x.at + }; + } + let len = index.len(); + let e = e.min(len); + Ok((index, s.min(e), e, stamp)) + }) +} + +/// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`. +/// When the text is not what that edit gives, every earlier range goes stale. +fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let now = t.plain_text(); + let (a, b) = (before.byte(at, false), before.byte(at + removed, true)); + let expected = before.text.len() - (b - a) + inserted.len() == now.len() + && now.as_bytes().starts_with(&before.text.as_bytes()[..a]) + && now.as_bytes().ends_with(&before.text.as_bytes()[b..]) + && now.get(a..a + inserted.len()) == Some(inserted); + let mut frames = h.dom.text.frames.borrow_mut(); + let l = frames.get_mut(&(st.uid, item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + l.stamp += 1; + if expected { + l.edits.push(Edit { stamp: l.stamp, at, removed, inserted: inserted.encode_utf16().count() }); + if l.edits.len() > MAX_EDITS { + let keep = l.edits.split_off(MAX_EDITS / 2); + l.floor = keep.first().map_or(l.stamp, |x| x.stamp - 1); + l.edits = keep; + } + } else { + l.floor = l.stamp; + l.edits.clear(); + } + l.index = Rc::new(Index::new(now)); + l.doc = Arc::downgrade(&st.doc); + Ok(()) + }) +} + +// ---- handles ---- + +fn usize_of(n: f64) -> Option { + whole(n).and_then(|v| usize::try_from(v).ok()) +} + +fn range_ref(h: &Host, item: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data { + let [high, low] = id_parts(item.id); + host_ref(class, &[float(h.run), float(item.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)]) +} + +/// The span `d` names, when it is an object of one of `classes`. +fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result { + let handle = classes.iter().find_map(|c| handle_of(d, c)); + let Some(&[run, uid, high, low, s, e, stamp]) = handle.as_deref() else { + return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange")))); + }; + let frame = item_of(h, &host_ref("TextFrame", &[run, uid, high, low])).map_err(|_| HostError::Error(STALE_RANGE.into()))?; + let (Some(start), Some(end), Some(stamp)) = (usize_of(s), usize_of(e), whole(stamp)) else { return Err(HostError::Error(STALE_RANGE.into())) }; + Ok(Span { item: frame, start, end, stamp }) +} + +/// The text frame `this` names. +fn this_frame(h: &Host, a: &[Data]) -> std::result::Result { + if handle_of(arg(a, 0), "TextFrame").is_none() { + return Err(HostError::Type("this is not a TextFrame".into())); + } + item_of(h, arg(a, 0)) +} + +/// The whole text of the frame as a span. +fn whole_span(h: &Host, item: Item) -> std::result::Result<(Rc, Span), HostError> { + with_doc(h, item.doc, |_, st| { + let (index, stamp) = observe(h, st, item.id)?; + let len = index.len(); + Ok((index, Span { item, start: 0, end: len, stamp })) + }) +} + +fn this_range(h: &Host, a: &[Data]) -> std::result::Result { + span_of(h, arg(a, 0), &["TextRange"]) +} + +/// Fails when `d` is not a text range, or is a stale one. +pub(super) fn check_range(h: &Host, d: &Data) -> std::result::Result<(), HostError> { + resolve(h, span_of(h, d, &["TextRange"])?).map(|_| ()) +} + +/// The span of `this`: a text range, or a text frame's whole text. +fn this_text(h: &Host, a: &[Data], class: &str) -> std::result::Result { + if handle_of(arg(a, 0), "TextFrame").is_some() { + return Ok(whole_span(h, item_of(h, arg(a, 0))?)?.1); + } + span_of(h, arg(a, 0), &[class]) +} + +// ---- contents ---- + +/// The model's text as `contents` gives it. +fn to_script(s: &str) -> String { + s.chars() + .map(|c| match c { + '\n' => '\r', + '\u{2028}' => '\u{3}', + c => c, + }) + .collect() +} + +/// Text a script wrote, as the model keeps it. +fn from_script(s: &str) -> String { + s.replace("\r\n", "\n") + .chars() + .map(|c| match c { + '\r' => '\n', + '\u{3}' => '\u{2028}', + c => c, + }) + .collect() +} + +fn read_contents(h: &Host, r: Span) -> Answer { + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + Ok(text(to_script(&index.text[a..b]))) +} + +/// Replaces the text of `r` with `value`, as one `text.editRange`. +fn write_contents(h: &Host, r: Span, value: &Data) -> Answer { + let Data::String(v) = value else { return Err(HostError::Type("contents must be a string".into())) }; + let insert = from_script(v); + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + if index.text[a..b] == insert { + return Ok(Data::Undefined); + } + let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count()); + edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; + record(h, r.item, &index, s, e - s, &insert)?; + Ok(Data::Undefined) +} + +fn frame_contents(h: &Host, a: &[Data]) -> Answer { + let (_, r) = whole_span(h, this_frame(h, a)?)?; + read_contents(h, r) +} + +fn frame_set_contents(h: &Host, a: &[Data]) -> Answer { + let (_, r) = whole_span(h, this_frame(h, a)?)?; + write_contents(h, r, arg(a, 1)) +} + +fn range_contents(h: &Host, a: &[Data]) -> Answer { + read_contents(h, this_range(h, a)?) +} + +fn range_set_contents(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_range(h, a)?, arg(a, 1)) +} + +// ---- TextFrame ---- + +fn frame_kind(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(text(match t.kind { + TextKind::Point => "TextType.POINTTEXT", + TextKind::Area { .. } => "TextType.AREATEXT", + TextKind::OnPath { .. } => "TextType.PATHTEXT", + })) + }) +} + +fn frame_orientation(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(text(if t.vertical { "TextOrientation.VERTICAL" } else { "TextOrientation.HORIZONTAL" })) + }) +} + +fn frame_range(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + let (_, r) = whole_span(h, item)?; + Ok(range_ref(h, item, r.start, r.end, r.stamp, "TextRange")) +} + +fn sub(h: &Host, a: &[Data], class: &str) -> Answer { + let r = this_text(h, a, "TextRange")?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, class)) +} + +fn characters(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Characters") +} + +fn words(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Words") +} + +fn paragraphs(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Paragraphs") +} + +fn character_attributes(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "CharacterAttributes") +} + +fn paragraph_attributes(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "ParagraphAttributes") +} + +/// The id a command's result gives under `ids` (the first) or `id`. +fn result_id(d: &Data) -> Option { + let Data::Object(o) = d else { return None }; + let n = |v: &Data| if let Data::Number(n) = v { whole(*n) } else { None }; + o.iter() + .find_map(|(k, v)| match (k.as_str(), v) { + ("ids", Data::Array(ids)) => ids.first().and_then(n), + ("id", v) => n(v), + _ => None, + }) + .map(NodeId) +} + +fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { + let id = id.ok_or_else(|| HostError::Error("the command made no object".into()))?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, id)) +} + +/// `createOutline()`: Type › Create Outlines for the frame alone. → the group of outlines. +fn frame_outline(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + let r = on_doc(h, item.doc.uid, true, |h| { + command(h, "select.set", &json!({"ids": [item.id.0]}))?; + command(h, "type.createOutlines", &json!({})) + })?; + new_ref(h, item.doc, result_id(&r)) +} + +/// Converts area type to point type (`area` false) or point type to area type. +fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer { + let item = this_frame(h, a)?; + let kind_ok = with_doc(h, item.doc, |_, st| { + text_of(st, item.id).map(|t| if to_area { matches!(t.kind, TextKind::Point) } else { matches!(t.kind, TextKind::Area { .. }) }) + }); + match kind_ok { + None => return Err(HostError::Error(STALE_ITEM.into())), + Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))), + Some(true) => {} + } + let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" }; + let r = edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; + new_ref(h, item.doc, result_id(&r).or(Some(item.id))) +} + +fn frame_to_point(h: &Host, a: &[Data]) -> Answer { + convert(h, a, false) +} + +fn frame_to_area(h: &Host, a: &[Data]) -> Answer { + convert(h, a, true) +} + +// ---- TextRange ---- + +fn range_parent(h: &Host, a: &[Data]) -> Answer { + let r = this_range(h, a)?; + resolve(h, r)?; + Ok(with_doc(h, r.item.doc, |_, st| item_ref(h, st, r.item.id))) +} + +fn range_start(h: &Host, a: &[Data]) -> Answer { + let (_, s, _, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float(s as u64))) +} + +fn range_end(h: &Host, a: &[Data]) -> Answer { + let (_, _, e, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float(e as u64))) +} + +fn range_length(h: &Host, a: &[Data]) -> Answer { + let (_, s, e, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float((e - s) as u64))) +} + +/// `remove()`: deletes the range's text. +fn range_remove(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_range(h, a)?, &text("")) +} + +/// `getParagraphLength()`: the length of the first paragraph the range touches, its break included. +fn range_paragraph_length(h: &Host, a: &[Data]) -> Answer { + let (index, s, e, _) = resolve(h, this_range(h, a)?)?; + let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x); + Ok(num(float(p as u64))) +} + +/// `getTextRunLength()`: the length from the range's start to the end of the run of characters +/// with one style it starts in, within the range. +fn range_run_length(h: &Host, a: &[Data]) -> Answer { + let r = this_range(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + let b = index.byte(s, false); + let run_end = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let mut at = 0; + for run in &t.runs { + at += run.text.len(); + if at > b { + return Ok(at); + } + } + Ok(at) + })?; + let u = index.text[..run_end.min(index.text.len())].encode_utf16().count(); + Ok(num(float((u.min(e).max(s) - s) as u64))) +} + +// ---- collections of a range ---- + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Part { + Characters, + Words, + Paragraphs, +} + +const PARTS: [(&str, Part); 3] = [("Characters", Part::Characters), ("Words", Part::Words), ("Paragraphs", Part::Paragraphs)]; + +fn part_of(d: &Data) -> Option { + PARTS.iter().find(|(c, _)| handle_of(d, c).is_some()).map(|(_, p)| *p) +} + +fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(Span, Part), HostError> { + let part = part_of(arg(a, 0)).ok_or_else(|| HostError::Type("this is not a collection of text".into()))?; + Ok((span_of(h, arg(a, 0), &["Characters", "Words", "Paragraphs"])?, part)) +} + +/// The spans of a collection, as a range of item numbers and the spans to look them up in. +fn part_spans(index: &Index, part: Part, s: usize, e: usize) -> (std::ops::Range, Option<&Spans>) { + match part { + Part::Characters => (index.chars_in(s, e), None), + Part::Words => (touched(&index.words, s, e), Some(&index.words)), + Part::Paragraphs => (touched(&index.paras, s, e), Some(&index.paras)), + } +} + +fn part_length(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + Ok(num(float(part_spans(&index, part, s, e).0.len() as u64))) +} + +fn part_parent(h: &Host, a: &[Data]) -> Answer { + let (r, _) = this_part(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, "TextRange")) +} + +fn part_at(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let (index, s, e, stamp) = resolve(h, r)?; + let (items, spans) = part_spans(&index, part, s, e); + let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) }; + let span = match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + Ok(span.map_or(Data::Undefined, |(x, y)| range_ref(h, r.item, x, y, stamp, "TextRange"))) +} + +// ---- character attributes ---- + +#[derive(Clone, Copy)] +enum Attr { + Size, + Leading, + AutoLeading, + Tracking, + BaselineShift, + HorizontalScale, + VerticalScale, + Rotation, + Underline, + StrikeThrough, + TextFont, +} + +const ATTRS: [(&str, Attr); 11] = [ + ("size", Attr::Size), + ("leading", Attr::Leading), + ("autoLeading", Attr::AutoLeading), + ("tracking", Attr::Tracking), + ("baselineShift", Attr::BaselineShift), + ("horizontalScale", Attr::HorizontalScale), + ("verticalScale", Attr::VerticalScale), + ("rotation", Attr::Rotation), + ("underline", Attr::Underline), + ("strikeThrough", Attr::StrikeThrough), + ("textFont", Attr::TextFont), +]; + +/// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with +/// the paragraph they are in: one entry for each run and paragraph the range covers. For an empty +/// range, the style of the character before it, or of the first one. +fn styles_in(t: &TextObject, a: usize, b: usize) -> std::result::Result, HostError> { + let mut out = Vec::new(); + let (mut at, mut para) = (0, 0); + let effective = |s: &CharStyle| t.effective_char_style(s).ok_or_else(|| HostError::Error("the text's transform cannot be measured".into())); + for run in &t.runs { + let end = at + run.text.len(); + let bytes = run.text.as_bytes(); + let breaks = |from: usize, to: usize| bytes.get(from - at..to - at).map_or(0, |s| s.iter().filter(|&&c| c == b'\n').count()); + if a == b && at < a.max(1) && a <= end { + let lo = a.saturating_sub(1).max(at); + out.push((effective(&run.style)?, para + breaks(at, lo))); + break; + } + if a < end && at < b { + let (lo, hi) = (a.max(at), b.min(end)); + let style = effective(&run.style)?; + let mut p = para + breaks(at, lo); + out.push((style.clone(), p)); + for (k, _) in bytes.get(lo - at..hi - at).unwrap_or_default().iter().enumerate().filter(|&(_, &c)| c == b'\n') { + p += 1; + if lo + k + 1 < hi { + out.push((style.clone(), p)); + } + } + } + para += bytes.iter().filter(|&&c| c == b'\n').count(); + at = end; + } + if out.is_empty() + && let Some(r) = t.runs.first() + { + out.push((effective(&r.style)?, 0)); + } + Ok(out) +} + +/// The bytes in `a..b` whose characters have auto leading, each stretch with the leading its +/// characters' auto leading sets them with, in document points; touching stretches with the same +/// leading are one. +fn auto_leading_spans(t: &TextObject, a: usize, b: usize) -> std::result::Result, HostError> { + let mut out: Vec<(usize, usize, f64)> = Vec::new(); + let mut push = |from: usize, to: usize, leading: f64| match out.last_mut() { + Some(last) if last.1 == from && same(&num(last.2), &num(leading)) => last.1 = to, + _ => out.push((from, to, leading)), + }; + let (mut at, mut para) = (0, 0); + for run in &t.runs { + let end = at + run.text.len(); + let bytes = run.text.as_bytes(); + if a < end && at < b { + let style = t.effective_char_style(&run.style).ok_or_else(|| HostError::Error("the text's transform cannot be measured".into()))?; + if style.leading.is_none() { + let (lo, hi) = (a.max(at), b.min(end)); + let auto = |p: usize| t.para_at(p).justification.auto_leading_for(style.size); + let mut p = para + bytes.get(..lo - at).unwrap_or_default().iter().filter(|&&c| c == b'\n').count(); + let mut from = lo; + for (k, _) in bytes.get(lo - at..hi - at).unwrap_or_default().iter().enumerate().filter(|&(_, &c)| c == b'\n') { + let to = lo + k + 1; + push(from, to, auto(p)); + p += 1; + from = to; + } + if from < hi { + push(from, hi, auto(p)); + } + } + } + para += bytes.iter().filter(|&&c| c == b'\n').count(); + at = end; + } + Ok(out) +} + +fn same(a: &Data, b: &Data) -> bool { + match (a, b) { + (Data::Number(x), Data::Number(y)) => (x - y).abs() < 1e-9, + _ => a == b, + } +} + +fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize) -> Data { + match attr { + Attr::Size => num(s.size), + Attr::Leading => num(s.leading.unwrap_or_else(|| t.para_at(para).justification.auto_leading_for(s.size))), + Attr::AutoLeading => Data::Bool(s.leading.is_none()), + Attr::Tracking => num(s.tracking), + Attr::BaselineShift => num(s.baseline_shift), + Attr::HorizontalScale => num(s.h_scale), + Attr::VerticalScale => num(s.v_scale), + Attr::Rotation => num(s.rotation), + Attr::Underline => Data::Bool(s.underline), + Attr::StrikeThrough => Data::Bool(s.strikethrough), + Attr::TextFont => font_ref(h, &s.font_family, &s.font_style), + } +} + +/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after. +fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> { + let finite = || number(v, name); + Ok(match attr { + Attr::Size => { + let n = finite()?; + if !(0.1..=1296.0).contains(&n) { + return Err(HostError::Range("size must be from 0.1 to 1296 points".into())); + } + (json!({"size": n}), num(n)) + } + Attr::Leading => { + let n = finite()?; + if !(0.1..=5000.0).contains(&n) { + return Err(HostError::Range("leading must be from 0.1 to 5000 points".into())); + } + (json!({"leading": n}), num(n)) + } + Attr::AutoLeading => { + if boolean(v, name)? { + (json!({"leading": "auto"}), Data::Bool(true)) + } else { + let (t, s, para) = first; + let n = s.leading.unwrap_or_else(|| t.para_at(para).justification.auto_leading_for(s.size)); + (json!({"leading": n}), Data::Bool(false)) + } + } + Attr::Tracking => { + let n = finite()?; + if !(-1000.0..=10_000.0).contains(&n) { + return Err(HostError::Range("tracking must be from -1000 to 10000".into())); + } + (json!({"tracking": n}), num(n)) + } + Attr::BaselineShift => { + let n = finite()?; + if n.abs() > 1296.0 { + return Err(HostError::Range("baselineShift must be from -1296 to 1296 points".into())); + } + (json!({"baselineShift": n}), num(n)) + } + Attr::HorizontalScale | Attr::VerticalScale => { + let n = finite()?; + if !(1.0..=10_000.0).contains(&n) { + return Err(HostError::Range(format!("{name} must be from 1 to 10000 percent"))); + } + let key = if matches!(attr, Attr::HorizontalScale) { "hScale" } else { "vScale" }; + (json!({ key: n }), num(n)) + } + Attr::Rotation => { + let n = finite()?; + if n.abs() > 360.0 { + return Err(HostError::Range("rotation must be from -360 to 360 degrees".into())); + } + (json!({"rotation": n}), num(n)) + } + Attr::Underline => { + let b = boolean(v, name)?; + (json!({"underline": b}), Data::Bool(b)) + } + Attr::StrikeThrough => { + let b = boolean(v, name)?; + (json!({"strikethrough": b}), Data::Bool(b)) + } + Attr::TextFont => { + let (family, style) = font_of(h, v)?; + (json!({"font": family, "style": style}), font_ref(h, &family, &style)) + } + }) +} + +/// The span of `this` for a character or paragraph attribute: a text range, its +/// `characterAttributes` or `paragraphAttributes`, or a text frame's whole text. +fn attr_span(h: &Host, a: &[Data], class: &str) -> std::result::Result { + if handle_of(arg(a, 0), "TextRange").is_some() { + return this_range(h, a); + } + this_text(h, a, class) +} + +fn read_attr(h: &Host, a: &[Data], attr: Attr) -> Answer { + let r = attr_span(h, a, "CharacterAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (ba, bb) = (index.byte(s, false), index.byte(e, true)); + with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(styles_in(t, ba, bb)?.first().map_or(Data::Undefined, |(st, p)| attr_value(h, attr, t, st, *p))) + }) +} + +fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { + let r = attr_span(h, a, "CharacterAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (ba, bb) = (index.byte(s, false), index.byte(e, true)); + let (param, unchanged, fixed) = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let styles = styles_in(t, ba, bb)?; + let first = styles.first().map(|(s, p)| (s.clone(), *p)).unwrap_or_else(|| (CharStyle::default(), 0)); + let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?; + let unchanged = ba == bb || styles.iter().all(|(st, p)| same(&attr_value(h, attr, t, st, *p), &wants)); + let fixed = match (attr, &wants) { + (Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?), + _ => None, + }; + if let Some(bad) = fixed.iter().flatten().map(|(_, _, l)| *l).find(|l| !(0.1..=5000.0).contains(l)) { + return Err(HostError::Range(format!("autoLeading cannot be turned off: the auto leading here is {bad} points, outside 0.1 to 5000"))); + } + Ok::<_, HostError>((param, unchanged, fixed)) + })?; + if unchanged { + return Ok(Data::Undefined); + } + if let Some(spans) = fixed { + // Each character with auto leading keeps the leading it is set with now. + super::atomically(h, |h| { + for (start, end, leading) in &spans { + let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading}); + edit_item(h, r.item, "text.setRangeStyle", &p)?; + } + Ok(()) + })?; + return Ok(Data::Undefined); + } + let mut p = param; + if let Some(o) = p.as_object_mut() { + o.insert("id".into(), json!(r.item.id.0)); + o.insert("start".into(), json!(ba)); + o.insert("end".into(), json!(bb)); + } + let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?; + if let Attr::TextFont = attr { + let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?; + } + Ok(Data::Undefined) +} + +/// Fails, after the font is set, when `text.setRangeStyle` warned that the font is not available +/// or when characters in bytes `a..b` kept another font because Missing Glyph Protection is on. +fn font_applied(h: &Host, item: Item, (a, b): (usize, usize), (family, style): (&str, &str), answer: &Data) -> std::result::Result<(), HostError> { + if let Data::Object(o) = answer + && let Some((_, Data::String(w))) = o.iter().find(|(k, _)| k == "warning") + { + return Err(HostError::Error(format!("textFont: {w}"))); + } + let kept = with_doc(h, item.doc, |_, st| { + let Some(t) = text_of(st, item.id) else { return 0 }; + let mut at = 0; + let mut kept = 0; + for run in &t.runs { + let end = at + run.text.len(); + let other = !run.style.font_family.eq_ignore_ascii_case(family) || !run.style.font_style.eq_ignore_ascii_case(style); + if other && a < end && at < b { + kept += run.text.get(a.max(at) - at..b.min(end) - at).map_or(0, |s| s.chars().count()); + } + at = end; + } + kept + }); + if kept > 0 { + let noun = if kept == 1 { "character, which keeps its" } else { "characters, which keep their" }; + return Err(HostError::Error(format!("textFont: the font has no glyph for {kept} {noun} font because Missing Glyph Protection is on"))); + } + Ok(()) +} + +// ---- paragraph attributes ---- + +#[derive(Clone, Copy)] +enum ParaAttr { + Justification, + FirstLineIndent, + LeftIndent, + RightIndent, + SpaceBefore, + SpaceAfter, +} + +const PARA_ATTRS: [(&str, ParaAttr); 6] = [ + ("justification", ParaAttr::Justification), + ("firstLineIndent", ParaAttr::FirstLineIndent), + ("leftIndent", ParaAttr::LeftIndent), + ("rightIndent", ParaAttr::RightIndent), + ("spaceBefore", ParaAttr::SpaceBefore), + ("spaceAfter", ParaAttr::SpaceAfter), +]; + +const JUSTIFICATIONS: [(&str, &str); 7] = [ + ("LEFT", "left"), + ("CENTER", "center"), + ("RIGHT", "right"), + ("FULLJUSTIFYLASTLINELEFT", "justifyLeft"), + ("FULLJUSTIFYLASTLINECENTER", "justifyCenter"), + ("FULLJUSTIFYLASTLINERIGHT", "justifyRight"), + ("FULLJUSTIFY", "justifyAll"), +]; + +/// The text of paragraph `i` of `index`, its break included. +fn para_text(index: &Index, i: usize) -> &str { + index.paras.get(i).and_then(|&(x, y)| index.text.get(index.byte(x, false)..index.byte(y, false))).unwrap_or_default() +} + +/// The value of `attr` in paragraph `i` of `t`, whose text `index` holds. Auto alignment reads as +/// the side it aligns to: right in a right-to-left paragraph, left otherwise. +fn para_value(attr: ParaAttr, t: &TextObject, index: &Index, i: usize) -> Data { + let p = t.para_at(i); + match attr { + ParaAttr::Justification => text(format!( + "Justification.{}", + match p.justify { + Justify::Auto if vectorcraft_text::paragraph_is_rtl(para_text(index, i), p.direction) => "RIGHT", + Justify::Auto | Justify::Left => "LEFT", + Justify::Center => "CENTER", + Justify::Right => "RIGHT", + Justify::JustifyLeft => "FULLJUSTIFYLASTLINELEFT", + Justify::JustifyCenter => "FULLJUSTIFYLASTLINECENTER", + Justify::JustifyRight => "FULLJUSTIFYLASTLINERIGHT", + Justify::JustifyAll => "FULLJUSTIFY", + } + )), + ParaAttr::FirstLineIndent => num(p.first_line_indent), + ParaAttr::LeftIndent => num(p.left_indent), + ParaAttr::RightIndent => num(p.right_indent), + ParaAttr::SpaceBefore => num(p.space_before), + ParaAttr::SpaceAfter => num(p.space_after), + } +} + +/// The command and parameter that set `attr` to `v`, and the value it reads as after. +fn para_param(attr: ParaAttr, name: &str, v: &Data) -> std::result::Result<(&'static str, Value, Data), HostError> { + if let ParaAttr::Justification = attr { + let found = match v { + Data::String(s) => s.strip_prefix("Justification.").and_then(|m| JUSTIFICATIONS.iter().find(|(k, _)| *k == m)), + _ => None, + }; + let (_, value) = found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?; + return Ok(("text.setStyle", json!({"justify": value}), v.clone())); + } + let n = number(v, name)?; + if n.abs() > 1296.0 { + return Err(HostError::Range(format!("{name} must be from -1296 to 1296 points"))); + } + let key = match attr { + ParaAttr::FirstLineIndent => "firstLineIndent", + ParaAttr::LeftIndent => "leftIndent", + ParaAttr::RightIndent => "rightIndent", + ParaAttr::SpaceBefore => "spaceBefore", + _ => "spaceAfter", + }; + Ok(("text.setFormat", json!({ key: n }), num(n))) +} + +/// The paragraphs a range touches, by number, and the bytes from the first one's start to the last +/// one's start, which select exactly those paragraphs for `text.setFormat` and `text.setStyle`. +fn para_range(index: &Index, s: usize, e: usize) -> (std::ops::Range, usize, usize) { + let paras = touched(&index.paras, s, e); + let start = |i: usize| index.paras.get(i).map_or(index.text.len(), |&(x, _)| index.byte(x, false)); + let (ba, bb) = (start(paras.start), start(paras.end.saturating_sub(1).max(paras.start))); + (paras, ba, bb) +} + +fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer { + let r = attr_span(h, a, "ParagraphAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (paras, _, _) = para_range(&index, s, e); + with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(para_value(attr, t, &index, paras.start)) + }) +} + +fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { + let r = attr_span(h, a, "ParagraphAttributes")?; + let (id, param, wants) = para_param(attr, name, arg(a, 1))?; + let (index, s, e, _) = resolve(h, r)?; + let (paras, ba, bb) = para_range(&index, s, e); + let unchanged = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + // An explicit alignment replaces Auto even where Auto aligns to the same side. + let auto = |i: usize| matches!(attr, ParaAttr::Justification) && t.para_at(i).justify == Justify::Auto; + Ok::<_, HostError>(paras.clone().all(|i| !auto(i) && same(¶_value(attr, t, &index, i), &wants))) + })?; + if unchanged { + return Ok(Data::Undefined); + } + let mut p = param; + if let Some(o) = p.as_object_mut() { + o.insert("id".into(), json!(r.item.id.0)); + o.insert("start".into(), json!(ba)); + o.insert("end".into(), json!(bb)); + } + edit_item(h, r.item, id, &p)?; + Ok(Data::Undefined) +} + +// ---- TextFrames ---- + +fn doc_text_frames_impl(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("TextFrames", &[float(h.run), float(doc.uid)])) +} + +/// `document.textFrames`. +pub(super) fn doc_text_frames(link: &Link) -> HostMember { + get(link, doc_text_frames_impl) +} + +/// The ids of the document's type objects in paint order, kept while the document is unchanged. +fn frame_ids(h: &Host, st: &DocState) -> Rc> { + if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow() + && *uid == st.uid + && std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc)) + { + return ids.clone(); + } + let ids: Vec = page_items(h, st).iter().copied().filter(|i| text_of(st, *i).is_some()).collect(); + let ids = Rc::new(ids); + *h.dom.text.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), ids.clone())); + ids +} + +fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "TextFrames") +} + +fn frames_length(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64))) +} + +fn frames_parent(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn frames_at(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn frames_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = frame_ids(h, st); + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn frames_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => frames_by_name(h, a), + Data::Number(_) => match frames_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `TextOrientation` as `text.create`'s `vertical`, `undefined` horizontal. +fn vertical_of(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(false), + Data::String(s) if s == "TextOrientation.HORIZONTAL" => Ok(false), + Data::String(s) if s == "TextOrientation.VERTICAL" => Ok(true), + _ => Err(HostError::Type("orientation must be a TextOrientation value".into())), + } +} + +/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`. +fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer { + let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?; + let r = on_doc(h, doc.uid, true, |h| command(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; + new_ref(h, doc, result_id(&r)) +} + +/// `add()`: empty point type at the origin. +fn frames_add(h: &Host, a: &[Data]) -> Answer { + point_text(h, frames_doc(h, a)?, None, false) +} + +/// `pointText(anchor, orientation?)`. +fn frames_point_text(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let anchor = point(arg(a, 1), "anchor")?; + point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?) +} + +/// Turns the path `d` names into area type or type on a path with `text.createInPath`. +fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { + let doc = frames_doc(h, a)?; + if handle_of(arg(a, 1), "PathItem").is_none() { + return Err(HostError::Type("textPath must be a PathItem".into())); + } + let path = item_of(h, arg(a, 1))?; + if path.doc.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) { + return Err(HostError::Error("TextFrames: threading and path positions are not available yet".into())); + } + let orientation = if on_path { 4 } else { 2 }; + let vertical = vertical_of(arg(a, orientation))?; + let mode = if on_path { "onPath" } else { "area" }; + let r = + on_doc(h, doc.uid, true, |h| command(h, "text.createInPath", &json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical})))?; + new_ref(h, doc, result_id(&r)) +} + +/// `areaText(textPath, orientation?, baseFrame?, postFix?)`. +fn frames_area_text(h: &Host, a: &[Data]) -> Answer { + in_path(h, a, false, &[3, 4]) +} + +/// `pathText(textPath, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)`. +fn frames_path_text(h: &Host, a: &[Data]) -> Answer { + in_path(h, a, true, &[2, 3, 5, 6]) +} + +/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. +fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let (ids, refused) = with_doc(h, doc, |_, st| { + let ids = frame_ids(h, st); + let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); + let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); + (ids, refused) + }); + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- fonts ---- + +/// The run's font list, read once. +fn with_fonts(h: &Host, f: impl FnOnce(&mut Vec<(String, String)>) -> T) -> T { + let mut fonts = h.dom.text.fonts.borrow_mut(); + let list = fonts.get_or_insert_with(|| { + let db = vectorcraft_text::FontDb::global(); + let mut v = Vec::new(); + for family in db.menu_family_list().iter() { + for style in db.styles(family) { + v.push((family.clone(), style)); + } + } + v + }); + f(list) +} + +/// A `TextFont` for `family` and `style`, added to the run's list when it is not there. +fn font_ref(h: &Host, family: &str, style: &str) -> Data { + let i = with_fonts(h, |list| match list.iter().position(|(f, s)| f.eq_ignore_ascii_case(family) && s.eq_ignore_ascii_case(style)) { + Some(i) => i, + None => { + list.push((family.to_string(), style.to_string())); + list.len() - 1 + } + }); + host_ref("TextFont", &[float(h.run), float(i as u64)]) +} + +/// The family and style of the `TextFont` `d`. +fn font_of(h: &Host, d: &Data) -> std::result::Result<(String, String), HostError> { + let Some(&[run, i]) = handle_of(d, "TextFont").as_deref() else { return Err(HostError::Type("textFont must be a TextFont".into())) }; + if whole(run) != Some(h.run) { + return Err(HostError::Error("Stale text font".into())); + } + usize_of(i).and_then(|i| with_fonts(h, |list| list.get(i).cloned())).ok_or_else(|| HostError::Error("Stale text font".into())) +} + +fn fonts_length(h: &Host, _: &[Data]) -> Answer { + Ok(num(float(with_fonts(h, |l| l.len()) as u64))) +} + +fn fonts_at(h: &Host, a: &[Data]) -> Answer { + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let found = with_fonts(h, |l| i < l.len()); + Ok(if found { host_ref("TextFont", &[float(h.run), float(i as u64)]) } else { Data::Undefined }) +} + +/// `textFonts.getByName(name)`: the PostScript name, then the family and style with a space. +fn fonts_by_name(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + if name.len() > super::MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let named = vectorcraft_text::FontDb::global().by_postscript_name(name); + let i = with_fonts(h, |l| { + h.charge_call(l.len() as u64)?; + let by_ps = named.as_ref().and_then(|(f, s)| l.iter().position(|(lf, ls)| lf.eq_ignore_ascii_case(f) && ls.eq_ignore_ascii_case(s))); + Ok::<_, HostError>(by_ps.or_else(|| l.iter().position(|(f, s)| format!("{f} {s}").eq_ignore_ascii_case(name)))) + })?; + i.map(|i| host_ref("TextFont", &[float(h.run), float(i as u64)])).ok_or_else(|| HostError::Error(NOT_FOUND.into())) +} + +fn fonts_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => fonts_by_name(h, a), + Data::Number(_) => match fonts_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +fn font_family(h: &Host, a: &[Data]) -> Answer { + Ok(text(font_of(h, arg(a, 0))?.0)) +} + +fn font_style(h: &Host, a: &[Data]) -> Answer { + Ok(text(font_of(h, arg(a, 0))?.1)) +} + +/// The font's PostScript name, or its family and style joined by a hyphen when the font is not +/// installed. +fn font_name(h: &Host, a: &[Data]) -> Answer { + let (family, style) = font_of(h, arg(a, 0))?; + let face = vectorcraft_text::FontDb::global().face(&family, &style); + Ok(text(face.map_or_else(|| format!("{family}-{style}").replace(' ', ""), |f| f.postscript_name()))) +} + +fn app_text_fonts_impl(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("TextFonts", &[])) +} + +/// `app.textFonts`. +pub(super) fn app_text_fonts(link: &Link) -> HostMember { + get(link, app_text_fonts_impl) +} + +fn app_ref(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Application", &[])) +} + +/// A font's `parent`, `app`, once the font is checked. +fn font_parent(h: &Host, a: &[Data]) -> Answer { + font_of(h, arg(a, 0))?; + Ok(host_ref("Application", &[])) +} + +// ---- classes ---- + +/// A member listed on the help pages that a script cannot set yet. Assigning it throws, after the +/// read's own checks of `this`. +fn read_only(link: &Link, g: super::Member, class: &'static str, name: &'static str) -> HostMember { + let message = format!("{class}.{name} cannot be set yet"); + let get = function(link, g); + let read = get.clone(); + HostMember::Property { + get, + set: Rc::new(move |a: Vec| { + read(a.into_iter().take(1).collect())?; + Err(HostError::Error(message.clone())) + }), + } +} + +fn attr_members(link: &Link) -> Vec<(String, HostMember)> { + let mut out = Vec::new(); + for (name, attr) in ATTRS { + let l = link.clone(); + let g: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + read_attr(&h, &a, attr) + }); + let l = link.clone(); + let s: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + write_attr(&h, &a, attr, name) + }); + out.push((name.to_string(), HostMember::Property { get: g, set: s })); + } + out +} + +fn para_members(link: &Link) -> Vec<(String, HostMember)> { + let mut out = Vec::new(); + for (name, attr) in PARA_ATTRS { + let l = link.clone(); + let g: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + read_para(&h, &a, attr) + }); + let l = link.clone(); + let s: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + write_para(&h, &a, attr, name) + }); + out.push((name.to_string(), HostMember::Property { get: g, set: s })); + } + out +} + +/// The enumerations type uses. +const ENUMS: &[(&str, &[&str])] = &[ + ("TextType", &["AREATEXT", "PATHTEXT", "POINTTEXT"]), + ("TextOrientation", &["HORIZONTAL", "VERTICAL"]), + ( + "Justification", + &["CENTER", "FULLJUSTIFY", "FULLJUSTIFYLASTLINECENTER", "FULLJUSTIFYLASTLINELEFT", "FULLJUSTIFYLASTLINERIGHT", "LEFT", "RIGHT"], + ), +]; + +/// Adds the enumerations type uses to `realm`. +pub(super) fn install_enums(realm: &mut Realm) -> std::result::Result<(), RunError> { + for (name, members) in ENUMS { + let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } + Ok(()) +} + +/// The classes of type, `TextFrame` among them, which inherits from `PageItem`. +pub(super) fn classes(l: &Link) -> Vec { + let mut frame = named(vec![ + ("kind", get(l, frame_kind)), + ("contents", property(l, frame_contents, frame_set_contents)), + ("textRange", get(l, frame_range)), + ("characters", get(l, characters)), + ("words", get(l, words)), + ("paragraphs", get(l, paragraphs)), + ("orientation", read_only(l, frame_orientation, "TextFrame", "orientation")), + ("createOutline", method(l, frame_outline)), + ("convertAreaObjectToPointObject", method(l, frame_to_point)), + ("convertPointObjectToAreaObject", method(l, frame_to_area)), + ]); + frame.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "story", + "nextFrame", + "previousFrame", + "textPath", + "anchor", + "antialias", + "columnCount", + "columnGutter", + "rowCount", + "rowGutter", + "startTValue", + "endTValue", + "opticalAlignment", + "matrix", + "textSelection", + ] + .into_iter() + .map(|m| super::later(l, "TextFrame", m)), + ); + let mut range = named(vec![ + ("typename", typename_of("TextRange")), + ("parent", get(l, range_parent)), + ("contents", property(l, range_contents, range_set_contents)), + ("start", read_only(l, range_start, "TextRange", "start")), + ("end", read_only(l, range_end, "TextRange", "end")), + ("characterOffset", read_only(l, range_start, "TextRange", "characterOffset")), + ("length", read_only(l, range_length, "TextRange", "length")), + ("characters", get(l, characters)), + ("words", get(l, words)), + ("paragraphs", get(l, paragraphs)), + ("characterAttributes", get(l, character_attributes)), + ("paragraphAttributes", get(l, paragraph_attributes)), + ("getParagraphLength", method(l, range_paragraph_length)), + ("getTextRunLength", method(l, range_run_length)), + ("remove", method(l, range_remove)), + ]); + range.extend(attr_members(l)); + range.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "story", + "kerning", + "characterStyles", + "paragraphStyles", + "textSelection", + "changeCaseTo", + "select", + "deSelect", + "duplicate", + "move", + "getLocalCharOverridesJSON", + "getLocalParaOverridesJSON", + ] + .into_iter() + .map(|m| super::later(l, "TextRange", m)), + ); + let part = |name: &'static str| { + class( + name, + None, + named(vec![("typename", typename_of(name)), ("length", get(l, part_length)), ("parent", get(l, part_parent))]), + Some(function(l, part_at)), + ) + }; + let mut chars = named(vec![("typename", typename_of("CharacterAttributes"))]); + chars.extend(attr_members(l)); + let mut paras = named(vec![("typename", typename_of("ParagraphAttributes"))]); + paras.extend(para_members(l)); + vec![ + class("TextFrame", Some("PageItem"), frame, None), + class("TextRange", None, range, None), + part("Characters"), + part("Words"), + part("Paragraphs"), + class("CharacterAttributes", None, chars, None), + class("ParagraphAttributes", None, paras, None), + class( + "TextFrames", + None, + named(vec![ + ("typename", typename_of("TextFrames")), + ("length", get(l, frames_length)), + ("parent", get(l, frames_parent)), + ("index", method(l, frames_index)), + ("getByName", method(l, frames_by_name)), + ("add", method(l, frames_add)), + ("pointText", method(l, frames_point_text)), + ("areaText", method(l, frames_area_text)), + ("pathText", method(l, frames_path_text)), + ("removeAll", method(l, frames_remove_all)), + ]), + Some(function(l, frames_at)), + ), + class( + "TextFonts", + None, + named(vec![ + ("typename", typename_of("TextFonts")), + ("length", get(l, fonts_length)), + ("parent", get(l, app_ref)), + ("index", method(l, fonts_index)), + ("getByName", method(l, fonts_by_name)), + ]), + Some(function(l, fonts_at)), + ), + class( + "TextFont", + None, + named(vec![ + ("typename", typename_of("TextFont")), + ("name", get(l, font_name)), + ("family", get(l, font_family)), + ("style", get(l, font_style)), + ("parent", get(l, font_parent)), + ]), + None, + ), + ] +} + +#[cfg(test)] +mod tests { + use super::{Index, touched}; + + #[test] + fn index_counts_utf16_units_and_splits_words_and_paragraphs() { + let i = Index::new("a\u{1F600}b c\nd".into()); + assert_eq!(i.len(), 8); + assert_eq!(i.chars, vec![0, 1, 3, 4, 5, 6, 7, 8]); + assert_eq!(i.byte(2, false), 1); + assert_eq!(i.byte(2, true), 5); + assert_eq!(i.words, vec![(0, 4), (5, 6), (7, 8)]); + assert_eq!(i.paras, vec![(0, 7), (7, 8)]); + assert_eq!(i.chars_in(1, 4), 1..3); + } + + #[test] + fn only_an_empty_range_touches_the_empty_paragraph_at_the_end() { + let i = Index::new("a\n".into()); + assert_eq!(i.paras, vec![(0, 2), (2, 2)]); + assert_eq!(touched(&i.paras, 0, 2), 0..1); + assert_eq!(touched(&i.paras, 0, 1), 0..1); + assert_eq!(touched(&i.paras, 2, 2), 1..2); + assert_eq!(touched(&i.paras, 1, 1), 0..1); + let e = Index::new(String::new()); + assert_eq!(touched(&e.paras, 0, 0), 0..1); + assert_eq!(touched(&e.words, 0, 0), 0..0); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..cd2a81daeb 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -178,6 +178,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_text; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs new file mode 100644 index 0000000000..6d9f6614f1 --- /dev/null +++ b/crates/engine/src/tests/script_text.rs @@ -0,0 +1,394 @@ +//! Type in the script object model: `textFrames`, text ranges, their attributes and `textFonts`. + +use serde_json::{Value, json}; +use vectorcraft_doc::Justify; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A 400 × 300 pt document with point type holding `text`. +fn doc_with(text: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap(); + (s, NodeId(id)) +} + +fn plain(s: &Session, id: NodeId) -> String { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } +} + +fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.size)).collect(), + _ => panic!("not text"), + } +} + +#[test] +fn text_frames_add_point_area_and_path_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 200, "height": 100})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + var area = d.textFrames.areaText(p[0]); area.contents = 'Area';\ + var path = d.textFrames.pathText(p[1]); path.contents = 'Path';\ + var pt = d.textFrames.add(); pt.contents = 'Point';\ + var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ + vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ + vc.log(pt.typename); vc.log(pt instanceof TextFrame && pt instanceof PageItem);\ + vc.log(d.textFrames[3].contents); vc.log(d.textFrames[9] === undefined);\ + vc.log(at.orientation); vc.log(d.textFrames.parent.typename);", + ); + assert_eq!(out[0], json!(4)); + assert_eq!(out[1], json!(["TextType.AREATEXT", "TextType.PATHTEXT", "TextType.POINTTEXT"])); + assert_eq!(out[2..], [json!("TextFrame"), json!(true), json!("At"), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")]); + assert_eq!(undo_steps(&s), before + 1); + // A path of another kind, or no path, is refused. + assert!(failure(&mut s, "app.activeDocument.textFrames.areaText(app.activeDocument.textFrames[0]);").contains("PathItem")); + assert!(failure(&mut s, "app.activeDocument.textFrames.pointText([1]);").contains("anchor")); + assert!(failure(&mut s, "app.activeDocument.textFrames.pointText([1, 2], 'up');").contains("TextOrientation")); + assert_eq!(undo_steps(&s), before + 1); + // pathText takes its orientation fourth, after the start and end positions it does not take yet. + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 250}, {"x": 300, "y": 260}], "closed": false})).unwrap(); + let find = "var d = app.activeDocument, p = d.pageItems, q; for (var i = 0; i < p.length; i++) if (p[i].typename == 'PathItem') q = p[i];"; + assert!(failure(&mut s, &format!("{find} d.textFrames.pathText(q, 0.5);")).contains("not available yet")); + let out = log(&mut s, &format!("{find} vc.log(d.textFrames.pathText(q, undefined, undefined, TextOrientation.VERTICAL).orientation);")); + assert_eq!(out, vec![json!("TextOrientation.VERTICAL")]); +} + +#[test] +fn contents_reads_paragraph_breaks_as_r_and_accepts_every_break() { + let (mut s, id) = doc_with("x"); + let out = log(&mut s, "var t = app.activeDocument.textFrames[0]; t.contents = 'a\\rb\\r\\nc\\nd\\u0003e'; vc.log(t.contents);"); + assert_eq!(out, vec![json!("a\rb\rc\rd\u{3}e")]); + assert_eq!(plain(&s, id), "a\nb\nc\nd\u{2028}e"); + assert!(failure(&mut s, "app.activeDocument.textFrames[0].contents = 5;").contains("contents must be a string")); +} + +#[test] +fn offsets_count_utf16_units_and_keep_surrogate_pairs_whole() { + let (mut s, _) = doc_with("a\u{1F600}b cd"); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].textRange, c = r.characters;\ + vc.log([r.length, r.start, r.end, c.length]);\ + vc.log([c[1].start, c[1].length, c[2].start, c[2].contents]);\ + vc.log([r.words.length, r.words[1].contents, r.words[0].characters.length]);\ + vc.log(app.activeDocument.textFrames[0].contents.length === r.length);", + ); + assert_eq!(out, vec![json!([7, 0, 7, 6]), json!([1, 2, 3, "b"]), json!([2, "cd", 3]), json!(true)]); +} + +#[test] +fn the_first_character_of_each_word_grows_in_one_undo_step() { + let (mut s, id) = doc_with("one two"); + let before = undo_steps(&s); + log( + &mut s, + "var text = app.activeDocument.textFrames[0].textRange;\ + for (var j = 0; j < text.words.length; j++) { var f = text.words[j].characters[0]; f.size = f.size * 1.5; }", + ); + assert_eq!(sizes(&s, id), vec![("o".into(), 18.0), ("ne ".into(), 12.0), ("t".into(), 18.0), ("wo".into(), 12.0)]); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn ranges_follow_model_edits_and_go_stale_after_other_edits() { + let (mut s, id) = doc_with("one two three"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], w = t.words, second = w[1], third = w[2];\ + w[0].contents = 'first'; vc.log([second.contents, second.start, third.contents]);\ + second.contents = ''; vc.log([second.length, third.contents, t.contents]);", + ); + assert_eq!(out, vec![json!(["two", 6, "three"]), json!([0, "three", "first three"])]); + let source = format!("var r = app.activeDocument.textFrames[0].words[0]; vc.run('text.setText', {{id: {}, text: 'other'}}); r.contents;", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{e}"); + let e = failure(&mut s, "var t = app.activeDocument.textFrames[0], r = t.textRange; t.remove(); r.contents;"); + assert!(e.contains("Stale text range"), "{e}"); + // A change reversed before the range is read leaves the text the range knew. + let (mut s, id) = doc_with("one two"); + let source = format!( + "var r = app.activeDocument.textFrames[0].words[1]; vc.run('text.setText', {{id: {0}, text: 'other'}});\ + vc.run('text.setText', {{id: {0}, text: 'one two'}}); vc.log([r.contents, r.start]);", + id.0 + ); + assert_eq!(log(&mut s, &source), vec![json!(["two", 4])]); +} + +#[test] +fn bad_attribute_values_are_refused_without_a_change() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + for (src, want) in [ + ("r.size = 0;", "size must be from 0.1"), + ("r.size = 'big';", "size must be a finite number"), + ("r.size = NaN;", "not a finite number"), + ("r.leading = 0;", "leading must be from 0.1"), + ("r.characterAttributes.tracking = 1e9;", "tracking"), + ("r.underline = 1;", "underline must be true or false"), + ("r.textFont = 'Arial';", "textFont must be a TextFont"), + ("r.paragraphAttributes.justification = 'LEFT';", "Justification value"), + ("r.paragraphAttributes.leftIndent = 5000;", "leftIndent"), + ("r.length = 1;", "cannot be set yet"), + ] { + let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}")); + assert!(e.contains(want), "{src}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(sizes(&s, id), vec![("abc".into(), 12.0)]); +} + +#[test] +fn setting_the_value_a_range_has_records_no_undo_step() { + let (mut s, _) = doc_with("abc"); + let before = undo_steps(&s); + log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange; r.size = r.size; r.underline = false;\ + t.contents = t.contents; r.paragraphAttributes.leftIndent = 0; r.characters[0].characterAttributes.size = 12;", + ); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn paragraph_attributes_set_the_paragraphs_a_range_touches() { + let (mut s, _) = doc_with("first\nsecond"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], p = t.paragraphs;\ + vc.log([p.length, p[0].contents, p[1].contents]);\ + p[1].paragraphAttributes.justification = Justification.CENTER; p[1].paragraphAttributes.leftIndent = 9;\ + vc.log([p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ + vc.log([p[0].paragraphAttributes.leftIndent, p[1].paragraphAttributes.leftIndent, p[1].getParagraphLength()]);", + ); + assert_eq!(out[0], json!([2, "first\r", "second"])); + assert_eq!(out[1], json!(["Justification.LEFT", "Justification.CENTER"])); + assert_eq!(out[2], json!([0, 9, 6])); + // A paragraph whose range ends after its break sets only itself. + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; p[0].paragraphAttributes.justification = Justification.RIGHT;\ + p[0].paragraphAttributes.spaceAfter = 4;\ + vc.log([p[0].justification === undefined, p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ + vc.log([p[0].paragraphAttributes.spaceAfter, p[1].paragraphAttributes.spaceAfter]);", + ); + assert_eq!(out, vec![json!([true, "Justification.RIGHT", "Justification.CENTER"]), json!([4, 0])]); + // The empty paragraph after a final break belongs only to an empty range at the end. + let (mut s, id) = doc_with("a\n"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], p = t.paragraphs; p[0].paragraphAttributes.spaceAfter = 4;\ + vc.log([p.length, p[0].paragraphs.length, p[0].paragraphAttributes.spaceAfter]);", + ); + assert_eq!(out, vec![json!([1, 1, 4])]); + let after: Vec = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (0..2).map(|i| t.para_at(i).space_after).collect(), + _ => panic!("not text"), + }; + assert_eq!(after, vec![4.0, 0.0]); +} + +#[test] +fn auto_leading_reads_the_paragraph_of_the_range_inside_one_run() { + let (mut s, id) = doc_with("first\nsecond"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 6, "end": 6, "autoLeading": 200})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; vc.log([p[0].leading, p[1].leading, p[1].characters[0].leading]);\ + p[1].autoLeading = false; vc.log([p[0].autoLeading, p[1].autoLeading, p[1].leading]);", + ); + assert_eq!(out, vec![json!([14.4, 24, 24]), json!([true, false, 24])]); + let leadings: Vec<(String, Option)> = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.leading)).collect(), + _ => panic!("not text"), + }; + assert_eq!(leadings, vec![("first\n".into(), None), ("second".into(), Some(24.0))]); +} + +#[test] +fn a_font_that_missing_glyph_protection_keeps_off_some_characters_throws() { + let (from, to, c) = ("Source Sans 3", "JetBrains Mono", '\u{180}'); + let db = vectorcraft_text::FontDb::global(); + let covers = |f: &str| db.face(f, "Regular").is_some_and(|face| face.covers(c)); + if !covers(from) || covers(to) { + return; // Installed fonts of these names cover other characters. + } + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "a\u{180}c", "font": from})).unwrap(); + let pick = format!("var r = app.activeDocument.textFrames[0].textRange, f = app.textFonts.getByName('{to} Regular');"); + let e = failure(&mut s, &format!("{pick} r.textFont = f;")); + assert!(e.contains("textFont: the font has no glyph for 1 character, which keeps its font"), "{e}"); + // Characters the font can draw take it without an error. + let out = log(&mut s, &format!("{pick} r.characters[0].textFont = f; vc.log(r.characters[0].textFont.family);")); + assert_eq!(out, vec![json!(to)]); +} + +#[test] +fn turning_auto_leading_off_keeps_each_characters_leading() { + let (mut s, id) = doc_with("ab\ncd"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 3, "end": 3, "autoLeading": 200})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "size": 24})).unwrap(); + let before = undo_steps(&s); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.autoLeading = false; vc.log(r.autoLeading);"); + assert_eq!(out, vec![json!(false)]); + assert_eq!(undo_steps(&s), before + 1); + let leadings: Vec<(String, Option)> = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.leading.map(|l| (l * 1000.0).round() as i64))).collect(), + _ => panic!("not text"), + }; + let want = [("a", 14_400), ("b", 28_800), ("\n", 14_400), ("cd", 24_000)]; + assert_eq!(leadings, want.iter().map(|(t, l)| (t.to_string(), Some(*l))).collect::>()); + // Paragraphs and runs with the same leading take one command. + let (mut s, _) = doc_with("one\ntwo\nthree"); + let r = run(&mut s, "app.activeDocument.textFrames[0].textRange.autoLeading = false;").unwrap(); + let calls: Vec<(Value, Value)> = r["slowestCommands"].as_array().unwrap().iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect(); + assert_eq!(calls, vec![(json!("text.setRangeStyle"), json!(1))]); + // Auto leading that a fixed leading cannot hold is refused before anything changes. + let (mut s, id) = doc_with("ab\ncd"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 3, "end": 3, "autoLeading": 0})).unwrap(); + let before = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.autoLeading = false;"); + assert!(e.contains("autoLeading cannot be turned off"), "{e}"); + assert_eq!(undo_steps(&s), before); + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_none())), + _ => panic!("not text"), + } +} + +#[test] +fn an_explicit_alignment_replaces_auto_alignment() { + let justify = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.para_at(0).justify, + _ => panic!("not text"), + }; + for (text, reads) in [("abc", "Justification.LEFT"), ("\u{5e9}\u{5dc}\u{5d5}\u{5dd}", "Justification.RIGHT")] { + let (mut s, id) = doc_with(text); + assert_eq!(justify(&s, id), Justify::Auto); + let before = undo_steps(&s); + let out = log( + &mut s, + "var a = app.activeDocument.textFrames[0].textRange.paragraphAttributes; vc.log(a.justification);\ + a.justification = Justification.LEFT; vc.log(a.justification);", + ); + assert_eq!(out, vec![json!(reads), json!("Justification.LEFT")], "{text}"); + assert_eq!(justify(&s, id), Justify::Left, "{text}"); + assert_eq!(undo_steps(&s), before + 1, "{text}"); + } + // Each paragraph on Auto reads by its own text. + let (mut s, _) = doc_with("abc\n\u{5e9}\u{5dc}\u{5d5}\u{5dd}\nd"); + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; var j = function (i) { return p[i].paragraphAttributes.justification; }; vc.log([j(0), j(1), j(2)]);", + ); + assert_eq!(out, vec![json!(["Justification.LEFT", "Justification.RIGHT", "Justification.LEFT"])]); +} + +#[test] +fn a_stale_range_has_no_parent() { + let (mut s, id) = doc_with("abc"); + let source = format!("var r = app.activeDocument.textFrames[0].textRange; vc.run('text.setText', {{id: {}, text: 'x'}}); r.parent;", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{e}"); +} + +#[test] +fn members_not_built_yet_throw_after_the_stale_check() { + let (mut s, id) = doc_with("abc"); + let e = failure(&mut s, "app.activeDocument.textFrames[0].lines;"); + assert!(e.contains("TextFrame.lines is not available yet"), "{e}"); + let e = failure(&mut s, "var t = app.activeDocument.textFrames[0]; t.remove(); t.lines;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.lines;"); + assert!(e.contains("TextRange.lines is not available yet"), "{e}"); + for member in ["r.lines", "r.start = 1"] { + let source = + format!("var r = app.activeDocument.textFrames[0].textRange; vc.run('text.setText', {{id: {}, text: 'other'}}); {member};", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{member}: {e}"); + } +} + +#[test] +fn text_fonts_list_and_assign_fonts_by_name() { + let (mut s, id) = doc_with("abc"); + let out = log( + &mut s, + "var f = app.textFonts, m = '';\ + try { f.getByName('No Such Font Anywhere'); } catch (e) { m = e.message; } vc.log(m);\ + try { f.index('No Such Font Anywhere'); } catch (e) { m = e.message; } vc.log(m);\ + vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[f.length - 1];\ + r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ + vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);", + ); + assert_eq!(out, vec![json!("Not found"), json!("Not found"), json!(true), json!(true), json!(true), json!(true)]); + let family = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs[0].style.font_family.clone(), + _ => panic!("not text"), + }; + let listed = log(&mut s, "var f = app.textFonts; vc.log(f[f.length - 1].family);"); + assert_eq!(listed, vec![json!(family)]); +} + +#[test] +fn create_outline_and_conversions_return_the_new_objects() { + let (mut s, id) = doc_with("Hi"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], m = '';\ + try { t.convertAreaObjectToPointObject(); } catch (e) { m = e.message; } vc.log(m);\ + var a = t.convertPointObjectToAreaObject(); vc.log(a.kind);\ + var p = a.convertAreaObjectToPointObject(); vc.log(p.kind); vc.log(p.contents);\ + var g = p.createOutline(); vc.log(g.typename); vc.log(app.activeDocument.textFrames.length);", + ); + assert_eq!(out[0], json!("the text frame is not area type")); + assert_eq!(out[1..], [json!("TextType.AREATEXT"), json!("TextType.POINTTEXT"), json!("Hi"), json!("GroupItem"), json!(0)]); + assert!(s.active().unwrap().doc.node(id).is_none()); +} + +#[test] +fn text_members_refuse_objects_of_other_classes() { + let (mut s, _) = doc_with("abc"); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[1]);"); + assert!(e.contains("this is not a TextFrame"), "{e}"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); + assert!(e.contains("this is not a TextRange"), "{e}"); + let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['TextFont', 0, 0]; app.activeDocument.textFrames[0].textRange.textFont = f;"); + assert!(e.contains("not plain data"), "{e}"); + // A font from an earlier run of a named engine is stale. + run(&mut s, "#targetengine keepfont\nvar held = app.textFonts[0];").unwrap(); + for member in ["held.family", "held.parent"] { + let e = failure(&mut s, &format!("#targetengine keepfont\n{member};")); + assert!(e.contains("Stale text font"), "{member}: {e}"); + } +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..c7e7000f13 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -81,7 +81,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + selection textFonts typename", ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), @@ -90,7 +90,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ + rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames typename \ views views= width", ), ("Layer.", "prototype"), @@ -121,12 +121,67 @@ const INSIDE: &[(&str, &str)] = &[ ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), + ( + "", + "CharacterAttributes Characters Justification ParagraphAttributes Paragraphs TextFont TextFonts TextFrame TextFrames \ + TextOrientation TextRange TextType Words", + ), + ("TextFrames.", "prototype"), + ("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"), + ("TextFrame.", "prototype"), + ( + "TextFrame.prototype.", + "anchor anchor= antialias antialias= characters columnCount columnCount= columnGutter columnGutter= constructor \ + contents contents= convertAreaObjectToPointObject convertPointObjectToAreaObject createOutline endTValue endTValue= \ + insertionPoints insertionPoints= kind lines lines= matrix matrix= nextFrame nextFrame= opticalAlignment \ + opticalAlignment= orientation orientation= paragraphs previousFrame previousFrame= rowCount rowCount= rowGutter \ + rowGutter= startTValue startTValue= story story= textPath textPath= textRange textRanges textRanges= textSelection \ + textSelection= words", + ), + ("TextRange.", "prototype"), + ( + "TextRange.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ + characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ + duplicate duplicate= end end= getLocalCharOverridesJSON getLocalCharOverridesJSON= getLocalParaOverridesJSON \ + getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale horizontalScale= insertionPoints \ + insertionPoints= kerning kerning= leading leading= length length= lines lines= move move= paragraphAttributes \ + paragraphStyles paragraphStyles= paragraphs parent remove rotation rotation= select select= size size= start start= \ + story story= strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ + tracking tracking= typename underline underline= verticalScale verticalScale= words", + ), + ("Characters.", "prototype"), + ("Characters.prototype.", "constructor length parent typename"), + ("Words.", "prototype"), + ("Words.prototype.", "constructor length parent typename"), + ("Paragraphs.", "prototype"), + ("Paragraphs.prototype.", "constructor length parent typename"), + ("CharacterAttributes.", "prototype"), + ( + "CharacterAttributes.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ + rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ + underline= verticalScale verticalScale=", + ), + ("ParagraphAttributes.", "prototype"), + ( + "ParagraphAttributes.prototype.", + "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ + rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", + ), + ("TextFonts.", "prototype"), + ("TextFonts.prototype.", "constructor getByName index length parent typename"), + ("TextFont.", "prototype"), + ("TextFont.prototype.", "constructor family name parent style typename"), + ("Justification.", "CENTER FULLJUSTIFY FULLJUSTIFYLASTLINECENTER FULLJUSTIFYLASTLINELEFT FULLJUSTIFYLASTLINERIGHT LEFT RIGHT"), + ("TextOrientation.", "HORIZONTAL VERTICAL"), + ("TextType.", "AREATEXT PATHTEXT POINTTEXT"), ]; /// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` /// and the page item types. const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/docs/mcp.md b/docs/mcp.md index 9bc2be8efc..aedf2b0a74 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2680,6 +2680,52 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type + objects in paint order, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and + `removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both + with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn + a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` + value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not + available yet. A `TextFrame` + (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, + `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, + `createOutline()` (Type › Create Outlines, giving the group of outlines), `convertPointObjectToAreaObject()` and + `convertAreaObjectToPointObject()`. A `TextRange` (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) has + `contents`, `start`, `end`, `characterOffset` (the same as `start`), `length`, `parent` (its frame), `characters`, + `words`, `paragraphs`, `characterAttributes`, `paragraphAttributes`, `getParagraphLength()`, `getTextRunLength()` and + `remove()`, and the character attributes themselves. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to + 5000 pt), `autoLeading`, `tracking` (-1000 to 10000), `baselineShift` (-1296 to 1296 pt), `horizontalScale` and + `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough` and `textFont`, + set with `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are + `justification` (a `Justification` value, set with `text.setStyle`; the Auto alignment new type has reads as `LEFT`, + or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`, + `spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts` + (https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/) lists every style of every family in the font menu, with + `length`, `[i]`, `index(key)` and `getByName(name)`, which takes a PostScript name or the family and style joined by a + space; a `TextFont` has `name` (its PostScript name), `family` and `style`. The enumerations `TextType`, + `TextOrientation` and `Justification` hold strings such as `"Justification.CENTER"`. + VectorCraft's own rules: offsets and lengths count UTF-16 code units, as a JavaScript string does, and an offset + inside a surrogate pair takes in its whole character; one item of `characters` is one code point. `contents` gives a + paragraph break as `\r` and a forced line break as `\u0003`, and takes `\r`, `\n` or `\r\n` for a paragraph break. A + word is a run of characters that are not white space; a range's `words` and `paragraphs` are the whole words and + paragraphs it touches, a paragraph's break belonging to it; the empty paragraph after a break at the end of the text + belongs only to an empty range there. A range keeps its place while the script edits the frame + through these objects: an edit before it moves it, an edit over it shrinks it, and an insertion at one of its ends + joins it. When a member finds the frame's text different from the text these objects last saw, because `vc.run` + or an undo changed it, a range made before throws `Stale text range`; a change that was reversed before that read + leaves the text as the range knew it, and the range keeps working. A range made before the frame's last 100,000 + edits through these objects throws `Stale text range` too. A character attribute + read on characters that differ gives the first one's value, and set on an empty range it changes nothing. Setting + `autoLeading` to false gives each character with auto leading the leading it is set with at that moment, from its + own size and its paragraph's auto leading percentage, with one `text.setRangeStyle` for each stretch of characters + that take the same leading; when one of those values is outside 0.1 to 5000 pt, it throws + and changes nothing. A paragraph attribute reads the first paragraph the range touches and sets every one of them. A value a range already + has runs no command. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws + when `text.setRangeStyle` warns that the font is not available, or when Missing Glyph Protection keeps characters the + font has no glyph for in their font, giving how many. A `TextFont` from an earlier run throws + `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and + `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, `length` and + `orientation` cannot be set yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..f6a957cad0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,8 @@ 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From efe9c3430446a89323439000f8f9933ab5b302ee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:11:55 -0800 Subject: [PATCH 15/91] Docs: text ranges keep up to 100,000 edits and drop the older half past that docs/mcp.md said a range made before the frame's last 100,000 edits goes stale. The record keeps up to 100,000 edits and, when it grows past that, drops the older half, so a range goes stale only when it was made before the newest dropped edit (text.rs MAX_EDITS and record). --- docs/mcp.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index aedf2b0a74..ea5b9028af 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2713,8 +2713,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot through these objects: an edit before it moves it, an edit over it shrinks it, and an insertion at one of its ends joins it. When a member finds the frame's text different from the text these objects last saw, because `vc.run` or an undo changed it, a range made before throws `Stale text range`; a change that was reversed before that read - leaves the text as the range knew it, and the range keeps working. A range made before the frame's last 100,000 - edits through these objects throws `Stale text range` too. A character attribute + leaves the text as the range knew it, and the range keeps working. These objects keep a record of up to 100,000 of the + frame's edits; when it grows past that, they drop the older half of it, and a range made before the newest dropped + edit throws `Stale text range` too. A character attribute read on characters that differ gives the first one's value, and set on an empty range it changes nothing. Setting `autoLeading` to false gives each character with auto leading the leading it is set with at that moment, from its own size and its paragraph's auto leading percentage, with one `text.setRangeStyle` for each stretch of characters From c691279f722897fc18c241729e7584bddeee9148 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:50:30 -0800 Subject: [PATCH 16/91] Scripts: covered text ranges hold the new text, and text members report stale ranges - An edit over the end of a text range takes that end to the end of the edit's new text, so a range the edit covers holds the new text instead of becoming empty. - The edit record keeps the frame's last 100,000 edits and drops only the oldest one past that. - A numeric leading set on characters with auto leading turns auto leading off even when it equals the auto value. - typename of a stale text range, its collections and attribute objects throws Stale text range, as the other members do; TextFrames and TextFont check their document and run first. - createOutline() gives null when the type has nothing to outline, instead of throwing after the command removed the frame. - New frames, outlines and conversions read the new id from the command's JSON result, so ids above 2^53 stay exact. - Character attribute reads look up only the first style of the range. - The font assignment test picks a font that draws "abc". Docs: docs/mcp.md, docs/gaps.md (G6). --- crates/engine/src/script/dom/text.rs | 160 +++++++++++++++++-------- crates/engine/src/tests/script_text.rs | 100 ++++++++++++++-- docs/gaps.md | 7 +- docs/mcp.md | 19 +-- 4 files changed, 217 insertions(+), 69 deletions(-) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index fb2bd54daa..a6dacdce55 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -15,15 +15,19 @@ //! - A word is a run of characters that are not white space. A paragraph ends after its break, and //! a range's `words` and `paragraphs` are the whole words and paragraphs it touches. //! - A range keeps its place while the script edits the frame through the object model: an edit -//! before it moves it, an edit over it shrinks it to the edit, and an insertion at one of its -//! ends joins it. When the frame's text changes in any other way (`vc.run`, an undo), every -//! range made before is stale and throws `Stale text range`. +//! before it moves it, an edit over one of its ends takes that end to the edge of the edit's new +//! text, so a range the edit covers holds the new text, and an insertion at one of its ends joins +//! it. When a member finds the frame's text different from the text the model last saw, because +//! `vc.run` or an undo changed it, every range made before is stale and throws +//! `Stale text range`; a change reversed before that read leaves the ranges as they were. +//! - The model keeps the frame's last [`MAX_EDITS`] edits; a range made before an edit that is no +//! longer kept is stale. //! - A character attribute read on a range whose characters differ gives the first character's //! value; set on an empty range it changes nothing. A paragraph attribute reads the first //! paragraph the range touches and sets every one of them. use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::rc::Rc; use std::sync::{Arc, Weak}; @@ -148,7 +152,21 @@ struct Log { index: Rc, stamp: u64, floor: u64, - edits: Vec, + edits: VecDeque, +} + +impl Log { + /// Records an edit the model made: `removed` units at `at` replaced by `inserted` units. Past + /// [`MAX_EDITS`] the oldest edit is dropped, and ranges made before it go stale. + fn push(&mut self, at: usize, removed: usize, inserted: usize) { + self.stamp += 1; + self.edits.push_back(Edit { stamp: self.stamp, at, removed, inserted }); + if self.edits.len() > MAX_EDITS + && let Some(dropped) = self.edits.pop_front() + { + self.floor = dropped.stamp; + } + } } /// A document's uid, the document, and the ids of its type objects then. @@ -204,7 +222,7 @@ fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc { - let l = Log { doc: Arc::downgrade(&st.doc), index: Rc::new(Index::new(t.plain_text())), stamp: 0, floor: 0, edits: Vec::new() }; + let l = Log { doc: Arc::downgrade(&st.doc), index: Rc::new(Index::new(t.plain_text())), stamp: 0, floor: 0, edits: VecDeque::new() }; frames.insert(key, l); } } @@ -232,7 +250,7 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u } let (mut s, mut e) = (r.start, r.end); let from = l.edits.partition_point(|x| x.stamp <= r.stamp); - for x in &l.edits[from..] { + for x in l.edits.range(from..) { let moved = |v: usize| v - x.removed + x.inserted; s = if s <= x.at { s @@ -241,12 +259,13 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u } else { x.at }; - e = if e < x.at { + // An end inside the removed text goes to the end of the new text. + e = if e < x.at || (e == x.at && x.removed > 0) { e } else if e >= x.at + x.removed { moved(e) } else { - x.at + x.at + x.inserted }; } let len = index.len(); @@ -268,15 +287,10 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser && now.get(a..a + inserted.len()) == Some(inserted); let mut frames = h.dom.text.frames.borrow_mut(); let l = frames.get_mut(&(st.uid, item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; - l.stamp += 1; if expected { - l.edits.push(Edit { stamp: l.stamp, at, removed, inserted: inserted.encode_utf16().count() }); - if l.edits.len() > MAX_EDITS { - let keep = l.edits.split_off(MAX_EDITS / 2); - l.floor = keep.first().map_or(l.stamp, |x| x.stamp - 1); - l.edits = keep; - } + l.push(at, removed, inserted.encode_utf16().count()); } else { + l.stamp += 1; l.floor = l.stamp; l.edits.clear(); } @@ -460,17 +474,10 @@ fn paragraph_attributes(h: &Host, a: &[Data]) -> Answer { sub(h, a, "ParagraphAttributes") } -/// The id a command's result gives under `ids` (the first) or `id`. -fn result_id(d: &Data) -> Option { - let Data::Object(o) = d else { return None }; - let n = |v: &Data| if let Data::Number(n) = v { whole(*n) } else { None }; - o.iter() - .find_map(|(k, v)| match (k.as_str(), v) { - ("ids", Data::Array(ids)) => ids.first().and_then(n), - ("id", v) => n(v), - _ => None, - }) - .map(NodeId) +/// The id a command's result, as the command gave it, holds under `ids` (the first) or `id`. It is +/// read from the JSON, where an id above 2^53 is still exact. +fn result_id(v: &Value) -> Option { + v.get("ids").and_then(|ids| ids.get(0)).or_else(|| v.get("id")).and_then(Value::as_u64).map(NodeId) } fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { @@ -480,14 +487,18 @@ fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { Ok(item_ref(h, st, id)) } -/// `createOutline()`: Type › Create Outlines for the frame alone. → the group of outlines. +/// `createOutline()`: Type › Create Outlines for the frame alone. → the group of outlines, or +/// `null` when the type has nothing to outline and the command removed it. fn frame_outline(h: &Host, a: &[Data]) -> Answer { let item = this_frame(h, a)?; - let r = on_doc(h, item.doc.uid, true, |h| { + let (_, r) = on_doc(h, item.doc.uid, true, |h| { command(h, "select.set", &json!({"ids": [item.id.0]}))?; - command(h, "type.createOutlines", &json!({})) + super::command_value(h, "type.createOutlines", &json!({})) })?; - new_ref(h, item.doc, result_id(&r)) + match result_id(&r) { + Some(id) => new_ref(h, item.doc, Some(id)), + None => Ok(Data::Null), + } } /// Converts area type to point type (`area` false) or point type to area type. @@ -502,7 +513,7 @@ fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer { Some(true) => {} } let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" }; - let r = edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; + let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?; new_ref(h, item.doc, result_id(&r).or(Some(item.id))) } @@ -658,8 +669,9 @@ const ATTRS: [(&str, Attr); 11] = [ /// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with /// the paragraph they are in: one entry for each run and paragraph the range covers. For an empty -/// range, the style of the character before it, or of the first one. -fn styles_in(t: &TextObject, a: usize, b: usize) -> std::result::Result, HostError> { +/// range, the style of the character before it, or of the first one. With `first`, only the first +/// entry. +fn styles_in(t: &TextObject, a: usize, b: usize, first: bool) -> std::result::Result, HostError> { let mut out = Vec::new(); let (mut at, mut para) = (0, 0); let effective = |s: &CharStyle| t.effective_char_style(s).ok_or_else(|| HostError::Error("the text's transform cannot be measured".into())); @@ -677,6 +689,9 @@ fn styles_in(t: &TextObject, a: usize, b: usize) -> std::result::Result Answer { let (ba, bb) = (index.byte(s, false), index.byte(e, true)); with_doc(h, r.item.doc, |_, st| { let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - Ok(styles_in(t, ba, bb)?.first().map_or(Data::Undefined, |(st, p)| attr_value(h, attr, t, st, *p))) + Ok(styles_in(t, ba, bb, true)?.first().map_or(Data::Undefined, |(st, p)| attr_value(h, attr, t, st, *p))) }) } @@ -851,10 +866,12 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { let (ba, bb) = (index.byte(s, false), index.byte(e, true)); let (param, unchanged, fixed) = with_doc(h, r.item.doc, |_, st| { let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - let styles = styles_in(t, ba, bb)?; + let styles = styles_in(t, ba, bb, false)?; let first = styles.first().map(|(s, p)| (s.clone(), *p)).unwrap_or_else(|| (CharStyle::default(), 0)); let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?; - let unchanged = ba == bb || styles.iter().all(|(st, p)| same(&attr_value(h, attr, t, st, *p), &wants)); + // A leading set on characters with auto leading fixes it even where auto gives that value. + let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants); + let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p)); let fixed = match (attr, &wants) { (Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?), _ => None, @@ -1132,7 +1149,8 @@ fn vertical_of(d: &Data) -> std::result::Result { /// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`. fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer { let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?; - let r = on_doc(h, doc.uid, true, |h| command(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; + let (_, r) = + on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; new_ref(h, doc, result_id(&r)) } @@ -1164,8 +1182,8 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { let orientation = if on_path { 4 } else { 2 }; let vertical = vertical_of(arg(a, orientation))?; let mode = if on_path { "onPath" } else { "area" }; - let r = - on_doc(h, doc.uid, true, |h| command(h, "text.createInPath", &json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical})))?; + let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical}); + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; new_ref(h, doc, result_id(&r)) } @@ -1311,6 +1329,37 @@ fn font_parent(h: &Host, a: &[Data]) -> Answer { // ---- classes ---- +fn range_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, this_range(h, a)?)?; + Ok(text("TextRange")) +} + +fn part_typename(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + resolve(h, r)?; + Ok(text(PARTS.iter().find(|(_, p)| *p == part).map_or("Characters", |(c, _)| c))) +} + +fn char_attrs_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, span_of(h, arg(a, 0), &["CharacterAttributes"])?)?; + Ok(text("CharacterAttributes")) +} + +fn para_attrs_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, span_of(h, arg(a, 0), &["ParagraphAttributes"])?)?; + Ok(text("ParagraphAttributes")) +} + +fn frames_typename(h: &Host, a: &[Data]) -> Answer { + frames_doc(h, a)?; + Ok(text("TextFrames")) +} + +fn font_typename(h: &Host, a: &[Data]) -> Answer { + font_of(h, arg(a, 0))?; + Ok(text("TextFont")) +} + /// A member listed on the help pages that a script cannot set yet. Assigning it throws, after the /// read's own checks of `this`. fn read_only(link: &Link, g: super::Member, class: &'static str, name: &'static str) -> HostMember { @@ -1424,7 +1473,7 @@ pub(super) fn classes(l: &Link) -> Vec { .map(|m| super::later(l, "TextFrame", m)), ); let mut range = named(vec![ - ("typename", typename_of("TextRange")), + ("typename", get(l, range_typename)), ("parent", get(l, range_parent)), ("contents", property(l, range_contents, range_set_contents)), ("start", read_only(l, range_start, "TextRange", "start")), @@ -1466,13 +1515,13 @@ pub(super) fn classes(l: &Link) -> Vec { class( name, None, - named(vec![("typename", typename_of(name)), ("length", get(l, part_length)), ("parent", get(l, part_parent))]), + named(vec![("typename", get(l, part_typename)), ("length", get(l, part_length)), ("parent", get(l, part_parent))]), Some(function(l, part_at)), ) }; - let mut chars = named(vec![("typename", typename_of("CharacterAttributes"))]); + let mut chars = named(vec![("typename", get(l, char_attrs_typename))]); chars.extend(attr_members(l)); - let mut paras = named(vec![("typename", typename_of("ParagraphAttributes"))]); + let mut paras = named(vec![("typename", get(l, para_attrs_typename))]); paras.extend(para_members(l)); vec![ class("TextFrame", Some("PageItem"), frame, None), @@ -1486,7 +1535,7 @@ pub(super) fn classes(l: &Link) -> Vec { "TextFrames", None, named(vec![ - ("typename", typename_of("TextFrames")), + ("typename", get(l, frames_typename)), ("length", get(l, frames_length)), ("parent", get(l, frames_parent)), ("index", method(l, frames_index)), @@ -1515,7 +1564,7 @@ pub(super) fn classes(l: &Link) -> Vec { "TextFont", None, named(vec![ - ("typename", typename_of("TextFont")), + ("typename", get(l, font_typename)), ("name", get(l, font_name)), ("family", get(l, font_family)), ("style", get(l, font_style)), @@ -1528,7 +1577,24 @@ pub(super) fn classes(l: &Link) -> Vec { #[cfg(test)] mod tests { - use super::{Index, touched}; + use std::collections::VecDeque; + use std::rc::Rc; + use std::sync::Weak; + + use super::{Index, Log, MAX_EDITS, touched}; + + #[test] + fn the_edit_log_keeps_the_last_edits_and_drops_only_older_ones() { + let mut l = Log { doc: Weak::new(), index: Rc::new(Index::new(String::new())), stamp: 0, floor: 0, edits: VecDeque::new() }; + for _ in 0..MAX_EDITS { + l.push(0, 0, 1); + } + assert_eq!((l.edits.len(), l.floor), (MAX_EDITS, 0)); + l.push(0, 0, 1); + // Only the first edit is dropped: a range made after it still moves through every later edit. + assert_eq!((l.edits.len(), l.floor), (MAX_EDITS, 1)); + assert_eq!(l.edits.front().map(|x| x.stamp), Some(2)); + } #[test] fn index_counts_utf16_units_and_splits_words_and_paragraphs() { diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 6d9f6614f1..10f3d2f3f1 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -143,6 +143,19 @@ fn ranges_follow_model_edits_and_go_stale_after_other_edits() { assert_eq!(log(&mut s, &source), vec![json!(["two", 4])]); } +#[test] +fn a_range_an_edit_covers_holds_the_edits_new_text() { + let (mut s, _) = doc_with("abc"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], first = t.characters[0], r = t.characters[1];\ + t.characters[2].contents = 'ZZ'; vc.log([first.contents, r.contents]);\ + t.contents = 'XY'; vc.log([r.contents, r.start, r.length, first.contents]);", + ); + // A range that ends where an edit starts keeps its end; one inside the edit takes the new text. + assert_eq!(out, vec![json!(["a", "b"]), json!(["XY", 0, 2, "XY"])]); +} + #[test] fn bad_attribute_values_are_refused_without_a_change() { let (mut s, id) = doc_with("abc"); @@ -178,6 +191,23 @@ fn setting_the_value_a_range_has_records_no_undo_step() { assert_eq!(undo_steps(&s), before); } +#[test] +fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.leading = r.leading; vc.log([r.autoLeading, r.leading]);"); + assert_eq!(out, vec![json!([false, 14.4])]); + assert_eq!(undo_steps(&s), before + 1); + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - 14.4).abs() < 1e-9)), "{:?}", t.runs), + _ => panic!("not text"), + } + // A fixed leading set to its own value is still no change. + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.leading = 14.4; vc.log(r.autoLeading);"); + assert_eq!(out, vec![json!(false)]); + assert_eq!(undo_steps(&s), before + 1); +} + #[test] fn paragraph_attributes_set_the_paragraphs_a_range_touches() { let (mut s, _) = doc_with("first\nsecond"); @@ -321,6 +351,21 @@ fn a_stale_range_has_no_parent() { assert!(e.contains("Stale text range"), "{e}"); } +#[test] +fn a_stale_range_and_its_collections_have_no_typename() { + let (mut s, id) = doc_with("abc"); + let source = format!( + "var r = app.activeDocument.textFrames[0].textRange, all = [r, r.characters, r.words, r.paragraphs, r.characterAttributes, r.paragraphAttributes];\ + var names = []; for (var i = 0; i < all.length; i++) names.push(all[i].typename); vc.log(names);\ + vc.run('text.setText', {{id: {}, text: 'other'}}); var m = [];\ + for (var i = 0; i < all.length; i++) {{ try {{ m.push(all[i].typename); }} catch (e) {{ m.push(e.message); }} }} vc.log(m);", + id.0 + ); + let out = log(&mut s, &source); + assert_eq!(out[0], json!(["TextRange", "Characters", "Words", "Paragraphs", "CharacterAttributes", "ParagraphAttributes"])); + assert_eq!(out[1], json!(vec!["Stale text range"; 6])); +} + #[test] fn members_not_built_yet_throw_after_the_stale_check() { let (mut s, id) = doc_with("abc"); @@ -340,23 +385,31 @@ fn members_not_built_yet_throw_after_the_stale_check() { #[test] fn text_fonts_list_and_assign_fonts_by_name() { + // The last font in the menu that draws "abc", so Missing Glyph Protection keeps no character. + let db = vectorcraft_text::FontDb::global(); + let listed: Vec<(String, String)> = db.menu_family_list().iter().flat_map(|f| db.styles(f).into_iter().map(move |st| (f.clone(), st))).collect(); + let covers = |(f, st): &&(String, String)| db.face(f, st).is_some_and(|face| "abc".chars().all(|c| face.covers(c))); + let Some((pos, (family, style))) = listed.iter().enumerate().rev().find(|(_, fs)| covers(fs)) else { + return; // No installed font draws "abc". + }; let (mut s, id) = doc_with("abc"); let out = log( &mut s, - "var f = app.textFonts, m = '';\ - try { f.getByName('No Such Font Anywhere'); } catch (e) { m = e.message; } vc.log(m);\ - try { f.index('No Such Font Anywhere'); } catch (e) { m = e.message; } vc.log(m);\ - vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[f.length - 1];\ - r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ - vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);", + &format!( + "var f = app.textFonts, m = '';\ + try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\ + vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ + vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);" + ), ); - assert_eq!(out, vec![json!("Not found"), json!("Not found"), json!(true), json!(true), json!(true), json!(true)]); - let family = match &s.active().unwrap().doc.node(id).unwrap().kind { - NodeKind::Text(t) => t.runs[0].style.font_family.clone(), + assert_eq!(out, vec![json!("Not found"), json!("Not found"), json!(true), json!([family, style]), json!(true), json!(true), json!(true)]); + let set = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (t.runs[0].style.font_family.clone(), t.runs[0].style.font_style.clone()), _ => panic!("not text"), }; - let listed = log(&mut s, "var f = app.textFonts; vc.log(f[f.length - 1].family);"); - assert_eq!(listed, vec![json!(family)]); + assert_eq!(&set, &(family.clone(), style.clone())); } #[test] @@ -375,6 +428,31 @@ fn create_outline_and_conversions_return_the_new_objects() { assert!(s.active().unwrap().doc.node(id).is_none()); } +#[test] +fn outlining_type_with_nothing_to_outline_gives_null() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = + log(&mut s, "var d = app.activeDocument, t = d.textFrames.add(); var g = t.createOutline(); vc.log([g === null, d.textFrames.length]);"); + assert_eq!(out, vec![json!([true, 0])]); +} + +#[test] +fn type_made_with_a_large_id_is_the_new_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The second frame's id, 2^53 + 1, is not exact as a number. + let big = 1u64 << 53; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log( + &mut s, + "var d = app.activeDocument, a = d.textFrames.add(), b = d.textFrames.pointText([5, 5]); b.contents = 'second';\ + vc.log([a === b, a.contents, b.createOutline().typename]);", + ); + assert_eq!(out, vec![json!([false, "", "GroupItem"])]); + assert_eq!(plain(&s, NodeId(big)), ""); +} + #[test] fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..47a1680f6e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -807,9 +807,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the - other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new - documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` +- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, stories and threads + of type, and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open + documents, new documents, each document's selection and its page items, its text frames with their text ranges and + character and paragraph attributes, and the installed fonts. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index ea5b9028af..bd7785031b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2689,7 +2689,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot available yet. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, - `createOutline()` (Type › Create Outlines, giving the group of outlines), `convertPointObjectToAreaObject()` and + `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to + outline and the command removes it), `convertPointObjectToAreaObject()` and `convertAreaObjectToPointObject()`. A `TextRange` (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) has `contents`, `start`, `end`, `characterOffset` (the same as `start`), `length`, `parent` (its frame), `characters`, `words`, `paragraphs`, `characterAttributes`, `paragraphAttributes`, `getParagraphLength()`, `getTextRunLength()` and @@ -2710,18 +2711,20 @@ app through the global object `vc`, and writes to the Script Console and runs ot word is a run of characters that are not white space; a range's `words` and `paragraphs` are the whole words and paragraphs it touches, a paragraph's break belonging to it; the empty paragraph after a break at the end of the text belongs only to an empty range there. A range keeps its place while the script edits the frame - through these objects: an edit before it moves it, an edit over it shrinks it, and an insertion at one of its ends - joins it. When a member finds the frame's text different from the text these objects last saw, because `vc.run` - or an undo changed it, a range made before throws `Stale text range`; a change that was reversed before that read - leaves the text as the range knew it, and the range keeps working. These objects keep a record of up to 100,000 of the - frame's edits; when it grows past that, they drop the older half of it, and a range made before the newest dropped - edit throws `Stale text range` too. A character attribute + through these objects: an edit before it moves it, an edit over one of its ends takes that end to the edge of the + edit's new text, so a range the edit covers holds the new text, and an insertion at one of its ends joins it. When a + member finds the frame's text different from the text these objects last saw, because `vc.run` or an undo changed + it, a range made before throws `Stale text range`, and so does its `typename`; a change that was reversed before + that read leaves the text as the range knew it, and the range keeps working. These objects keep a record of the + frame's last 100,000 edits, and a range made before an edit that is no longer in that record throws + `Stale text range` too. A character attribute read on characters that differ gives the first one's value, and set on an empty range it changes nothing. Setting `autoLeading` to false gives each character with auto leading the leading it is set with at that moment, from its own size and its paragraph's auto leading percentage, with one `text.setRangeStyle` for each stretch of characters that take the same leading; when one of those values is outside 0.1 to 5000 pt, it throws and changes nothing. A paragraph attribute reads the first paragraph the range touches and sets every one of them. A value a range already - has runs no command. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws + has runs no command; a `leading` set on characters with auto leading turns their auto leading off even when it equals + the auto leading. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws when `text.setRangeStyle` warns that the font is not available, or when Missing Glyph Protection keeps characters the font has no glyph for in their font, giving how many. A `TextFont` from an earlier run throws `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and From b7893282bad1d8e003249f2d49bf606b6e61f3a1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:28:30 -0800 Subject: [PATCH 17/91] Scripts: text ranges made before File > Revert go stale A text range kept working after file.revert when the file read back held the same text, because the frame's record compared only the text. The record now keeps the document's revert count, and a range made before a revert throws Stale text range. --- crates/engine/src/script/dom/text.rs | 32 ++++++++++++++++++-------- crates/engine/src/tests/script_text.rs | 19 +++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 44 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index a6dacdce55..c3ca9d1dbe 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -19,7 +19,9 @@ //! text, so a range the edit covers holds the new text, and an insertion at one of its ends joins //! it. When a member finds the frame's text different from the text the model last saw, because //! `vc.run` or an undo changed it, every range made before is stale and throws -//! `Stale text range`; a change reversed before that read leaves the ranges as they were. +//! `Stale text range`; a change reversed before that read leaves the ranges as they were. After +//! File › Revert every range made before is stale, even when the file read back holds the same +//! text. //! - The model keeps the frame's last [`MAX_EDITS`] edits; a range made before an edit that is no //! longer kept is stale. //! - A character attribute read on a range whose characters differ gives the first character's @@ -145,10 +147,12 @@ struct Edit { inserted: usize, } -/// What the object model knows of one frame's text: the document it was read from, the text, the -/// edits made through the model, and the oldest range generation still valid. +/// What the object model knows of one frame's text: the document it was read from and its revert +/// count then, the text, the edits made through the model, and the oldest range generation still +/// valid. struct Log { doc: Weak, + reverts: u64, index: Rc, stamp: u64, floor: u64, @@ -204,25 +208,34 @@ fn same_text(t: &TextObject, s: &str) -> bool { rest.is_empty() } -/// The frame's index and its generation now, read again when its document changed. +/// The frame's index and its generation now, read again when its document changed. After File › +/// Revert every earlier range goes stale, even when the file read back holds the same text. fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc, u64), HostError> { let t = text_of(st, id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let mut frames = h.dom.text.frames.borrow_mut(); let key = (st.uid, id.0); let now = Arc::as_ptr(&st.doc); match frames.get_mut(&key) { - Some(l) if std::ptr::eq(l.doc.as_ptr(), now) => {} + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => {} Some(l) => { - if !same_text(t, &l.index.text) { + if l.reverts != st.reverts || !same_text(t, &l.index.text) { l.stamp += 1; l.floor = l.stamp; l.edits.clear(); l.index = Rc::new(Index::new(t.plain_text())); } l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; } None => { - let l = Log { doc: Arc::downgrade(&st.doc), index: Rc::new(Index::new(t.plain_text())), stamp: 0, floor: 0, edits: VecDeque::new() }; + let l = Log { + doc: Arc::downgrade(&st.doc), + reverts: st.reverts, + index: Rc::new(Index::new(t.plain_text())), + stamp: 0, + floor: 0, + edits: VecDeque::new(), + }; frames.insert(key, l); } } @@ -287,7 +300,7 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser && now.get(a..a + inserted.len()) == Some(inserted); let mut frames = h.dom.text.frames.borrow_mut(); let l = frames.get_mut(&(st.uid, item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; - if expected { + if expected && l.reverts == st.reverts { l.push(at, removed, inserted.encode_utf16().count()); } else { l.stamp += 1; @@ -296,6 +309,7 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser } l.index = Rc::new(Index::new(now)); l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; Ok(()) }) } @@ -1585,7 +1599,7 @@ mod tests { #[test] fn the_edit_log_keeps_the_last_edits_and_drops_only_older_ones() { - let mut l = Log { doc: Weak::new(), index: Rc::new(Index::new(String::new())), stamp: 0, floor: 0, edits: VecDeque::new() }; + let mut l = Log { doc: Weak::new(), reverts: 0, index: Rc::new(Index::new(String::new())), stamp: 0, floor: 0, edits: VecDeque::new() }; for _ in 0..MAX_EDITS { l.push(0, 0, 1); } diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 10f3d2f3f1..36dff46fa0 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -143,6 +143,25 @@ fn ranges_follow_model_edits_and_go_stale_after_other_edits() { assert_eq!(log(&mut s, &source), vec![json!(["two", 4])]); } +#[test] +fn ranges_made_before_file_revert_go_stale_even_when_the_text_is_the_same() { + let (mut s, _) = doc_with("one two"); + let path = std::env::temp_dir().join(format!("vc-text-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.words[1];\ + vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\ + var now = app.activeDocument.textFrames[0];\ + vc.log(now.contents); try { vc.log(r.contents); } catch (e) { vc.log(e.message); }\ + vc.log(now.words[1].contents);", + ); + let _ = std::fs::remove_file(&path); + assert_eq!(out[0], json!("one two"), "the reverted file holds the same text"); + assert!(out[1].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert_eq!(out[2], json!("two"), "a range made after the revert reads the reverted text"); +} + #[test] fn a_range_an_edit_covers_holds_the_edits_new_text() { let (mut s, _) = doc_with("abc"); diff --git a/docs/mcp.md b/docs/mcp.md index bd7785031b..a75c5386f5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2715,7 +2715,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot edit's new text, so a range the edit covers holds the new text, and an insertion at one of its ends joins it. When a member finds the frame's text different from the text these objects last saw, because `vc.run` or an undo changed it, a range made before throws `Stale text range`, and so does its `typename`; a change that was reversed before - that read leaves the text as the range knew it, and the range keeps working. These objects keep a record of the + that read leaves the text as the range knew it, and the range keeps working. After `file.revert`, a range made + before throws `Stale text range` even when the file read back holds the same text. These objects keep a record of the frame's last 100,000 edits, and a range made before an edit that is no longer in that record throws `Stale text range` too. A character attribute read on characters that differ gives the first one's value, and set on an empty range it changes nothing. Setting From d82fe4e8d90b9d6a80632593fc820d009770d973 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:54:45 -0800 Subject: [PATCH 18/91] Scripts: nextFrame, previousFrame, story and document.stories for threaded type Text frames get nextFrame, previousFrame and story, and documents get stories, a Stories collection with one story for each thread and each type object in no thread. Assigning nextFrame or previousFrame links the last frame of one story to the first frame of another, and null breaks the link with each frame keeping its text; loops, links to the frame itself or into the middle of a story, point type, frames of another document and hidden or locked frames are refused with nothing changed. A story of two or more frames reads and writes its text across its frames in UTF-16 units, and areaText and pathText take baseFrame and postFix to thread the new frame to an existing one. The new command text.thread.setNeighbor {id, side, neighbor} links or breaks by id without a selection, for MCP, the CLI and vc.run. --- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/threads.rs | 115 +++ crates/engine/src/script/dom.rs | 1 + crates/engine/src/script/dom/text.rs | 34 +- crates/engine/src/script/dom/text/threads.rs | 786 ++++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_threads.rs | 596 +++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 34 +- docs/gaps.md | 6 +- docs/mcp.md | 41 +- docs/target-app-parity.md | 1 + 11 files changed, 1598 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/script/dom/text/threads.rs create mode 100644 crates/engine/src/tests/script_threads.rs diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..26514918aa 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -669,6 +669,7 @@ pub(super) const ALLOWED: &[&str] = &[ "text.thread.info", "text.thread.releaseSelection", "text.thread.remove", + "text.thread.setNeighbor", "text.touchType", "threeD.addGraphic", "threeD.mapArt", diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index f4f807cb15..1a79fbfbc9 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -59,6 +59,15 @@ pub fn specs() -> Vec { has_doc, break_thread ), + cmd!( + "text.thread.setNeighbor", + "Thread Text", + [], + None, + "{id, side: \"next\"|\"previous\", neighbor: id|null} link area type or type on a path `id` to the frame that follows it (`next`) or comes before it (`previous`) in its story, or with null break that one link, as a script's `nextFrame` and `previousFrame` assignments do. Linking joins two stories: `id` must be the last frame of its story for `next` (the first for `previous`) and `neighbor` the first (the last) of another one, and the second story's text flows on after the first's. Breaking a link makes each side of it a story of its own: no text moves across the break, and the frames after it flow their own text again from their first frame, which now starts a paragraph. An error, with nothing changed, for point type or other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a frame of either story that is hidden or locked; a link that is already there, or a break where there is no link, changes nothing and records no undo step; the selection is kept → {changed: bool, threads: [[id…]] (the stories of the frames involved, after the change, a one-frame story as [id])}", + has_doc, + set_neighbor + ), cmd!(query "text.thread.info", "Threads", [], None, "{} → [[id…]] every thread in order", has_doc, |s, _| { Ok(json!(s.doc()?.doc.text_threads.iter().map(|t| t.iter().map(|i| i.0).collect::>()).collect::>())) }), @@ -986,5 +995,111 @@ fn break_thread(s: &mut Session, p: &Value) -> Result { ok() } +/// The frames of the story `id` is a frame of, in thread order: its thread's area type and type on +/// a path, each once, or `id` alone when it is in no thread. +fn chain_of(d: &Document, id: NodeId) -> Vec { + let mut frames = story_of(d, id); + let mut seen = Ids::default(); + frames.retain(|f| seen.insert(*f)); + if frames.len() < 2 { vec![id] } else { frames } +} + +fn chain_ids(chains: &[&[NodeId]]) -> Value { + json!(chains.iter().filter(|c| !c.is_empty()).map(|c| c.iter().map(|i| i.0).collect::>()).collect::>()) +} + +/// `text.thread.setNeighbor`: link a frame to the frame after or before it, or break that link. +fn set_neighbor(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.thread.setNeighbor"; + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?; + let next = match p.get("side").and_then(Value::as_str) { + Some("next") => true, + Some("previous") => false, + _ => return Err(bad(C, "`side` must be \"next\" or \"previous\"")), + }; + let neighbor = match p.get("neighbor") { + None => return Err(bad(C, "missing `neighbor` (an id, or null to break the link)")), + Some(Value::Null) => None, + Some(v) => Some(checked_id(s, v, C)?), + }; + let d = &s.doc()?.doc; + if text_of(d, id).is_none() { + return Err(bad(C, "`id` must be area type or type on a path")); + } + let locked = |frames: &[NodeId]| { + let editable = d.editable(); + frames.iter().any(|f| !editable(*f)) + }; + let chain = chain_of(d, id); + let Some(n) = neighbor else { + // Break the link on that side: the frames before it and the frames after it. + let i = chain.iter().position(|f| *f == id).unwrap_or(0); + let at = if next { i + 1 } else { i }; + if at == 0 || at >= chain.len() { + return Ok(json!({"changed": false, "threads": chain_ids(&[&chain])})); + } + if locked(&chain) { + return Err(bad(C, "a frame of the story is hidden or locked")); + } + let (head, tail) = (chain[..at].to_vec(), chain[at..].to_vec()); + let cut: Ids = chain.iter().copied().collect(); + s.edit("Break Thread", |d, _| { + d.text_threads.retain(|t| !t.iter().any(|f| cut.contains(f))); + for part in [&head, &tail] { + if part.len() >= 2 { + d.text_threads.push(part.clone()); + } + } + // The first frame after the break starts its story, which flows again on this edit so + // that its numbered paragraphs count from 1. + if let Some(f) = tail.first() { + touch(d, *f); + } + if let Some(NodeKind::Text(t)) = tail.first().and_then(|f| d.node_mut(*f)).map(|n| &mut n.kind) + && t.first_para_continues + { + t.first_para_continues = false; + refresh_bounds(t); + } + Ok(()) + })?; + return Ok(json!({"changed": true, "threads": chain_ids(&[&head, &tail])})); + }; + if n == id { + return Err(bad(C, "a frame cannot be linked to itself")); + } + if text_of(d, n).is_none() { + return Err(bad(C, "`neighbor` must be area type or type on a path")); + } + // `first` is to flow into `second`. + let (first, second) = if next { (id, n) } else { (n, id) }; + let (a, b) = if next { (chain, chain_of(d, n)) } else { (chain_of(d, n), chain) }; + if a.contains(&second) { + if a.windows(2).any(|w| w == [first, second]) { + return Ok(json!({"changed": false, "threads": chain_ids(&[&a])})); + } + return Err(bad(C, "the two frames are already in one story: the link would make a loop or reorder it")); + } + if a.last() != Some(&first) { + return Err(bad(C, format!("frame {} already has a next frame: break that link first", first.0))); + } + if b.first() != Some(&second) { + return Err(bad(C, format!("frame {} already has a previous frame: break that link first", second.0))); + } + if locked(&a) || locked(&b) { + return Err(bad(C, "a frame of either story is hidden or locked")); + } + let joined: Vec = a.iter().chain(&b).copied().collect(); + let affected: Ids = joined.iter().copied().collect(); + s.edit("Thread Text", |d, _| { + d.text_threads.retain(|t| !t.iter().any(|f| affected.contains(f))); + d.text_threads.push(joined.clone()); + // Force a re-flow of the joined story on this edit. + touch(d, first); + Ok(()) + })?; + Ok(json!({"changed": true, "threads": chain_ids(&[&joined])})) +} + #[cfg(test)] mod tests; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d467345a2c..49ae9d1138 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1767,6 +1767,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("convertCoordinate", method(l, doc_convert)), ("pageItems", get(l, doc_page_items)), ("textFrames", text::doc_text_frames(l)), + ("stories", text::threads::doc_stories(l)), ("selection", property(l, doc_selection, doc_set_selection)), ]); document.extend( diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index c3ca9d1dbe..822e34e954 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -44,6 +44,8 @@ use super::{ }; use crate::{DocState, Document, NodeId, NodeKind}; +pub(super) mod threads; + /// The error of a text range, or of a collection of one, whose frame's text changed other than /// through the object model. pub const STALE_RANGE: &str = "Stale text range"; @@ -188,6 +190,7 @@ pub(in crate::script) struct TextState { /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character /// names that is not installed is added at the end. fonts: RefCell>>, + stories: threads::StoryState, } fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { @@ -1191,24 +1194,32 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { return Err(HostError::Error(super::CROSS_DOCUMENT.into())); } if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) { - return Err(HostError::Error("TextFrames: threading and path positions are not available yet".into())); + return Err(HostError::Error("TextFrames: path positions are not available yet".into())); } - let orientation = if on_path { 4 } else { 2 }; + let (orientation, base) = if on_path { (4, 5) } else { (2, 3) }; let vertical = vertical_of(arg(a, orientation))?; + let base = threads::base_frame(h, doc, arg(a, base), arg(a, base + 1))?; + if base.is_some() { + threads::check_base_path(h, path)?; + } let mode = if on_path { "onPath" } else { "area" }; let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical}); let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; - new_ref(h, doc, result_id(&r)) + let id = result_id(&r); + if let (Some((base, postfix)), Some(id)) = (base, id) { + threads::thread_new(h, base, id, postfix)?; + } + new_ref(h, doc, id) } /// `areaText(textPath, orientation?, baseFrame?, postFix?)`. fn frames_area_text(h: &Host, a: &[Data]) -> Answer { - in_path(h, a, false, &[3, 4]) + in_path(h, a, false, &[]) } /// `pathText(textPath, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)`. fn frames_path_text(h: &Host, a: &[Data]) -> Answer { - in_path(h, a, true, &[2, 3, 5, 6]) + in_path(h, a, true, &[2, 3]) } /// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. @@ -1462,14 +1473,12 @@ pub(super) fn classes(l: &Link) -> Vec { ("convertAreaObjectToPointObject", method(l, frame_to_point)), ("convertPointObjectToAreaObject", method(l, frame_to_area)), ]); + frame.extend(threads::frame_members(l)); frame.extend( [ "lines", "insertionPoints", "textRanges", - "story", - "nextFrame", - "previousFrame", "textPath", "anchor", "antialias", @@ -1504,12 +1513,12 @@ pub(super) fn classes(l: &Link) -> Vec { ("remove", method(l, range_remove)), ]); range.extend(attr_members(l)); + range.push(threads::range_member(l)); range.extend( [ "lines", "insertionPoints", "textRanges", - "story", "kerning", "characterStyles", "paragraphStyles", @@ -1537,7 +1546,8 @@ pub(super) fn classes(l: &Link) -> Vec { chars.extend(attr_members(l)); let mut paras = named(vec![("typename", get(l, para_attrs_typename))]); paras.extend(para_members(l)); - vec![ + let stories = threads::classes(l); + let mut out = vec![ class("TextFrame", Some("PageItem"), frame, None), class("TextRange", None, range, None), part("Characters"), @@ -1586,7 +1596,9 @@ pub(super) fn classes(l: &Link) -> Vec { ]), None, ), - ] + ]; + out.extend(stories); + out } #[cfg(test)] diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs new file mode 100644 index 0000000000..ee81129944 --- /dev/null +++ b/crates/engine/src/script/dom/text/threads.rs @@ -0,0 +1,786 @@ +//! Threaded type in the script object model: a text frame's `nextFrame`, `previousFrame` and +//! `story`, `document.stories`, and each `Story` with its frames and its text, as the help pages +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - Assigning `nextFrame` links the last frame of a story to the first frame of another story, +//! whose text then flows on after it; `previousFrame` links the other way. Assigning `null` +//! breaks that link, and no text moves across it. Point type, a frame of another +//! document, the frame itself, a frame inside a story, a link that would make a loop and a hidden +//! or locked frame in either story are refused with nothing changed. Assigning the frame that is +//! already linked, or `null` where there is no link, changes nothing. +//! - A `Story` is the story of the frame it was read from as that frame is threaded now; when the +//! frame is deleted, it throws `Stale story`. +//! - `document.stories` lists one story for each type object in no thread and one for each thread, +//! in the paint order of their first frames. `index` with a string finds the first story whose +//! first frame has that name. +//! - The text of a story of two or more frames is its frames' text in thread order. Its ranges keep +//! their place through edits made through them, as a frame's ranges do, and are stale after any +//! other change to the story's text and after File › Revert. A story of one frame gives that +//! frame's own ranges. +//! - `areaText` and `pathText` with a `baseFrame` thread the new frame after it, or before it when +//! `postFix` is false; `postFix` is true when it is left out. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::rc::Rc; +use std::sync::{Arc, Weak}; + +use serde_json::json; +use vectorcraft_doc::TextKind; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, host_ref}; + +use super::super::{ + Answer, Doc, Host, Item, Link, NOT_FOUND, arg, boolean, class, current, doc_of, doc_ref, edit_item, find_doc, float, function, get, handle_of, + id_of, id_parts, in_compound, item_of, item_ref, later, method, named, num, property, text, whole, with_doc, +}; +use super::{ + ATTRS, Index, Log, Part, STALE_RANGE, frame_ids, from_script, part_spans, range_ref, read_only, text_of, this_frame, to_script, touched, + usize_of, whole_span, +}; +use crate::cmd::threads::story_of; +use crate::{DocState, Document, NodeId}; + +/// The error of a `Story` whose frame was deleted, or that came from an earlier run. +pub const STALE_STORY: &str = "Stale story"; + +/// A document's uid, the document, and the first frame of each of its stories then. +type StoryList = (u64, Weak, Rc>); + +/// The story state of one run: the text of each story of two or more frames that a range was made +/// of, by document and the frame the `Story` was read from, and the last list of stories. +#[derive(Default)] +pub(in crate::script) struct StoryState { + logs: RefCell>, + list: RefCell>, +} + +/// The frames of the story `id` is a frame of, in thread order, each once, or `id` alone. +fn frames_of(st: &DocState, id: NodeId) -> Vec { + let mut frames = story_of(&st.doc, id); + let mut seen = HashSet::new(); + frames.retain(|f| seen.insert(*f)); + if frames.len() < 2 { vec![id] } else { frames } +} + +/// The frames of the story `id` is a frame of, charged to the run. +fn charged_frames(h: &Host, st: &DocState, id: NodeId) -> std::result::Result, HostError> { + h.charge_call(st.doc.text_threads.len() as u64)?; + let frames = frames_of(st, id); + h.charge_call(frames.len() as u64)?; + Ok(frames) +} + +/// Whether type object `id` is area type or type on a path. +fn threadable(st: &DocState, id: NodeId) -> bool { + text_of(st, id).is_some_and(|t| !matches!(t.kind, TextKind::Point)) +} + +// ---- nextFrame and previousFrame ---- + +fn neighbor(h: &Host, a: &[Data], next: bool) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let frames = charged_frames(h, st, item.id)?; + let i = frames.iter().position(|f| *f == item.id); + let other = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) }); + Ok(other.map_or(Data::Null, |f| item_ref(h, st, *f))) + }) +} + +fn next_frame(h: &Host, a: &[Data]) -> Answer { + neighbor(h, a, true) +} + +fn previous_frame(h: &Host, a: &[Data]) -> Answer { + neighbor(h, a, false) +} + +/// Assigns `nextFrame` (`next`) or `previousFrame` with `text.thread.setNeighbor`. +fn set_neighbor(h: &Host, a: &[Data], next: bool) -> Answer { + let name = if next { "nextFrame" } else { "previousFrame" }; + let item = this_frame(h, a)?; + let other = match arg(a, 1) { + Data::Null => None, + d if handle_of(d, "TextFrame").is_some() => Some(item_of(h, d)?), + _ => return Err(HostError::Type(format!("{name} must be a TextFrame or null"))), + }; + if other.is_some_and(|o| o.doc.uid != item.doc.uid) { + return Err(HostError::Error(format!("{name}: the two frames are in different documents"))); + } + let now = with_doc(h, item.doc, |_, st| { + if !threadable(st, item.id) || other.is_some_and(|o| !threadable(st, o.id)) { + return Err(HostError::Error(format!("{name}: only area type and type on a path can be threaded"))); + } + let frames = charged_frames(h, st, item.id)?; + let i = frames.iter().position(|f| *f == item.id); + let current = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) }); + Ok(current.copied()) + })?; + if now == other.map(|o| o.id) { + return Ok(Data::Undefined); + } + let side = if next { "next" } else { "previous" }; + let params = json!({"id": item.id.0, "side": side, "neighbor": other.map(|o| o.id.0)}); + edit_item(h, item, "text.thread.setNeighbor", ¶ms).map_err(|e| match e { + HostError::Error(m) => HostError::Error(format!("{name}: {m}")), + e => e, + })?; + Ok(Data::Undefined) +} + +fn set_next_frame(h: &Host, a: &[Data]) -> Answer { + set_neighbor(h, a, true) +} + +fn set_previous_frame(h: &Host, a: &[Data]) -> Answer { + set_neighbor(h, a, false) +} + +/// `TextFrame.story`. +fn frame_story(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + Ok(story_ref(h, item)) +} + +/// `TextRange.story`: the story of the range's frame. +fn range_story(h: &Host, a: &[Data]) -> Answer { + let r = super::this_range(h, a)?; + super::resolve(h, r)?; + Ok(story_ref(h, r.item)) +} + +// ---- creating a frame threaded to another ---- + +/// The `baseFrame` and `postFix` arguments of `areaText` and `pathText`, checked before the frame +/// is made: the frame to thread the new one to, and whether the new one goes after it. +pub(super) fn base_frame(h: &Host, doc: Doc, base: &Data, post: &Data) -> std::result::Result, HostError> { + if matches!(base, Data::Undefined | Data::Null) { + return Ok(None); + } + if handle_of(base, "TextFrame").is_none() { + return Err(HostError::Type("baseFrame must be a TextFrame".into())); + } + let item = item_of(h, base)?; + if item.doc.uid != doc.uid { + return Err(HostError::Error("baseFrame: the frame is in another document".into())); + } + let postfix = match post { + Data::Undefined => true, + d => boolean(d, "postFix")?, + }; + with_doc(h, item.doc, |_, st| { + if !threadable(st, item.id) { + return Err(HostError::Error("baseFrame: only area type and type on a path can be threaded".into())); + } + let editable = st.doc.editable(); + if charged_frames(h, st, item.id)?.iter().any(|f| !editable(*f)) { + return Err(HostError::Error("baseFrame: a frame of its story is hidden or locked".into())); + } + Ok(()) + })?; + Ok(Some((item, postfix))) +} + +/// Refuses a `baseFrame` for a path inside a compound path before the path is turned into type: +/// `text.thread.add` does not thread type there. +pub(super) fn check_base_path(h: &Host, path: Item) -> std::result::Result<(), HostError> { + if in_compound(h, path) { + return Err(HostError::Error("baseFrame: type made from a path inside a compound path cannot be threaded".into())); + } + Ok(()) +} + +/// Threads the new frame `id` after `base`, or before it when `postfix` is false. +pub(super) fn thread_new(h: &Host, base: Item, id: NodeId, postfix: bool) -> std::result::Result<(), HostError> { + edit_item(h, base, "text.thread.add", &json!({"from": base.id.0, "to": id.0, "before": !postfix}))?; + Ok(()) +} + +// ---- Story ---- + +fn story_ref(h: &Host, item: Item) -> Data { + let [high, low] = id_parts(item.id); + host_ref("Story", &[float(h.run), float(item.doc.uid), high, low]) +} + +/// The frame the story `d` was read from, which must still be a type object. +fn story_of_data(h: &Host, d: &Data) -> std::result::Result { + let Some(handle) = handle_of(d, "Story") else { return Err(HostError::Type("this is not a Story".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Story".into())) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_STORY.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_STORY.into()))?; + match with_doc(h, doc, |_, st| text_of(st, id).is_some()) { + true => Ok(Item { doc, id }), + false => Err(HostError::Error(STALE_STORY.into())), + } +} + +fn this_story(h: &Host, a: &[Data]) -> std::result::Result { + story_of_data(h, arg(a, 0)) +} + +fn story_frames(h: &Host, a: &[Data]) -> Answer { + let story = this_story(h, a)?; + with_doc(h, story.doc, |_, st| Ok(Data::Array(charged_frames(h, st, story.id)?.iter().map(|f| item_ref(h, st, *f)).collect()))) +} + +fn story_parent(h: &Host, a: &[Data]) -> Answer { + let story = this_story(h, a)?; + Ok(doc_ref(h, story.doc.uid)) +} + +/// The story's one frame, or `None` for a story of two or more frames. +fn single(h: &Host, story: Item) -> std::result::Result, HostError> { + with_doc(h, story.doc, |_, st| { + let frames = charged_frames(h, st, story.id)?; + Ok(match frames[..] { + [one] => Some(Item { doc: story.doc, id: one }), + _ => None, + }) + }) +} + +fn story_length(h: &Host, a: &[Data]) -> Answer { + let story = this_story(h, a)?; + let (index, _) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?; + Ok(num(float(index.len() as u64))) +} + +/// A range or a collection of the whole story, as `frame_class` for a story of one frame and +/// `story_class` for a longer one. +fn story_whole(h: &Host, a: &[Data], frame_class: &str, story_class: &str) -> Answer { + let story = this_story(h, a)?; + if let Some(frame) = single(h, story)? { + let (_, r) = whole_span(h, frame)?; + return Ok(range_ref(h, frame, r.start, r.end, r.stamp, frame_class)); + } + let (index, stamp) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?; + Ok(span_ref(h, story, 0, index.len(), stamp, story_class)) +} + +fn story_text_range(h: &Host, a: &[Data]) -> Answer { + story_whole(h, a, "TextRange", "StoryRange") +} + +fn story_characters(h: &Host, a: &[Data]) -> Answer { + story_whole(h, a, "Characters", "StoryCharacters") +} + +fn story_words(h: &Host, a: &[Data]) -> Answer { + story_whole(h, a, "Words", "StoryWords") +} + +fn story_paragraphs(h: &Host, a: &[Data]) -> Answer { + story_whole(h, a, "Paragraphs", "StoryParagraphs") +} + +// ---- the text of a story of two or more frames ---- + +/// The frames of the story and the text of each, in thread order. +fn story_text(st: &DocState, frames: &[NodeId]) -> String { + frames.iter().filter_map(|f| text_of(st, *f)).flat_map(|t| t.runs.iter().map(|r| r.text.as_str())).collect() +} + +/// The story's index and its generation now, read again when its document changed. +fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc, u64), HostError> { + if text_of(st, anchor).is_none() { + return Err(HostError::Error(STALE_STORY.into())); + } + let mut logs = h.dom.text.stories.logs.borrow_mut(); + let key = (st.uid, anchor.0); + let now = Arc::as_ptr(&st.doc); + match logs.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => {} + Some(l) => { + let frames = charged_frames(h, st, anchor)?; + let text = story_text(st, &frames); + if l.reverts != st.reverts || text != l.index.text { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + l.index = Rc::new(Index::new(text)); + } + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + } + None => { + let frames = charged_frames(h, st, anchor)?; + let index = Rc::new(Index::new(story_text(st, &frames))); + logs.insert(key, Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, index, stamp: 0, floor: 0, edits: VecDeque::new() }); + } + } + let l = logs.get(&key).ok_or_else(|| HostError::Error(STALE_STORY.into()))?; + Ok((l.index.clone(), l.stamp)) +} + +/// A range of a story: the frame the story was read from, its span in UTF-16 units and the +/// generation it was made at. +#[derive(Clone, Copy)] +struct StorySpan { + story: Item, + start: usize, + end: usize, + stamp: u64, +} + +const STORY_PARTS: [(&str, Part); 3] = [("StoryCharacters", Part::Characters), ("StoryWords", Part::Words), ("StoryParagraphs", Part::Paragraphs)]; + +fn span_ref(h: &Host, story: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data { + let [high, low] = id_parts(story.id); + host_ref(class, &[float(h.run), float(story.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)]) +} + +/// The story span `d` names, when it is an object of one of `classes`. +fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result { + let handle = classes.iter().find_map(|c| handle_of(d, c)); + let Some(&[run, uid, high, low, s, e, stamp]) = handle.as_deref() else { + return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange")))); + }; + let story = story_of_data(h, &host_ref("Story", &[run, uid, high, low])).map_err(|_| HostError::Error(STALE_RANGE.into()))?; + let (Some(start), Some(end), Some(stamp)) = (usize_of(s), usize_of(e), whole(stamp)) else { return Err(HostError::Error(STALE_RANGE.into())) }; + Ok(StorySpan { story, start, end, stamp }) +} + +fn this_span(h: &Host, a: &[Data]) -> std::result::Result { + span_of(h, arg(a, 0), &["StoryRange"]) +} + +/// The span and index of `r` now. +fn resolve(h: &Host, r: StorySpan) -> std::result::Result<(Rc, usize, usize, u64), HostError> { + with_doc(h, r.story.doc, |_, st| { + let (index, stamp) = observe(h, st, r.story.id)?; + let logs = h.dom.text.stories.logs.borrow(); + let l = logs.get(&(st.uid, r.story.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + if r.stamp < l.floor || r.stamp > l.stamp { + return Err(HostError::Error(STALE_RANGE.into())); + } + let (mut s, mut e) = (r.start, r.end); + let from = l.edits.partition_point(|x| x.stamp <= r.stamp); + for x in l.edits.range(from..) { + let moved = |v: usize| v - x.removed + x.inserted; + s = if s <= x.at { + s + } else if s >= x.at + x.removed { + moved(s) + } else { + x.at + }; + // An end inside the removed text goes to the end of the new text. + e = if e < x.at || (e == x.at && x.removed > 0) { + e + } else if e >= x.at + x.removed { + moved(e) + } else { + x.at + x.inserted + }; + } + let e = e.min(index.len()); + Ok((index, s.min(e), e, stamp)) + }) +} + +/// Records an edit the model made to the story: `removed` units at `at` replaced by `inserted`. +/// When the text is not what that edit gives, every earlier range goes stale. The ranges of the +/// same story read from its other frames record the edit too, when they knew the text before it. +fn record(h: &Host, story: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { + with_doc(h, story.doc, |_, st| { + if text_of(st, story.id).is_none() { + return Err(HostError::Error(STALE_STORY.into())); + } + let frames = charged_frames(h, st, story.id)?; + let now = story_text(st, &frames); + let (a, b) = (before.byte(at, false), before.byte(at + removed, true)); + let expected = before.text.len() - (b - a) + inserted.len() == now.len() + && now.as_bytes().starts_with(&before.text.as_bytes()[..a]) + && now.as_bytes().ends_with(&before.text.as_bytes()[b..]) + && now.get(a..a + inserted.len()) == Some(inserted); + let members: HashSet = frames.iter().map(|f| f.0).collect(); + let index = Rc::new(Index::new(now)); + let inserted = inserted.encode_utf16().count(); + let mut logs = h.dom.text.stories.logs.borrow_mut(); + let mut found = false; + for (&(uid, anchor), l) in logs.iter_mut() { + if uid != st.uid || !members.contains(&anchor) { + continue; + } + let own = anchor == story.id.0; + let current = l.reverts == st.reverts; + if !own { + h.charge_call(l.index.text.len() as u64)?; + if !expected || !current || l.index.text != before.text { + continue; + } + } + found |= own; + if expected && current { + l.push(at, removed, inserted); + } else { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + } + l.index = index.clone(); + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + } + if found { Ok(()) } else { Err(HostError::Error(STALE_RANGE.into())) } + }) +} + +/// Replaces bytes `a..b` of the story's text with `insert`, a frame at a time from the end, with +/// `text.editRange`: the frames before the one an edit changes keep their text, so `a` stays in +/// place while the frames after it flow again. +fn replace(h: &Host, story: Item, a: usize, mut b: usize, insert: &str) -> std::result::Result<(), HostError> { + loop { + let spans: Vec<(NodeId, usize, usize)> = with_doc(h, story.doc, |_, st| { + if text_of(st, story.id).is_none() { + return Err(HostError::Error(STALE_STORY.into())); + } + let mut at = 0; + let spans = charged_frames(h, st, story.id)? + .into_iter() + .map(|f| { + let n: usize = text_of(st, f).map_or(0, |t| t.runs.iter().map(|r| r.text.len()).sum()); + at += n; + (f, at - n, at) + }) + .collect(); + Ok(spans) + })?; + let target = + if b > a { spans.iter().find(|(_, x, y)| *x < b && b <= *y) } else { spans.iter().find(|(_, x, y)| *x < a && a <= *y).or(spans.first()) }; + let Some(&(f, x, _)) = target else { return Err(HostError::Error(STALE_RANGE.into())) }; + let item = Item { doc: story.doc, id: f }; + if x <= a { + edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": a - x, "end": b - x, "insert": insert}))?; + return Ok(()); + } + edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": 0, "end": b - x, "insert": ""}))?; + b = x; + } +} + +fn write_contents(h: &Host, r: StorySpan, value: &Data) -> Answer { + let Data::String(v) = value else { return Err(HostError::Type("contents must be a string".into())) }; + let insert = from_script(v); + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + if index.text[a..b] == insert { + return Ok(Data::Undefined); + } + let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count()); + replace(h, r.story, a, b, &insert)?; + record(h, r.story, &index, s, e - s, &insert)?; + Ok(Data::Undefined) +} + +fn span_contents(h: &Host, a: &[Data]) -> Answer { + let (index, s, e, _) = resolve(h, this_span(h, a)?)?; + let (x, y) = (index.byte(s, false), index.byte(e, true)); + Ok(text(to_script(&index.text[x..y]))) +} + +fn span_set_contents(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_span(h, a)?, arg(a, 1)) +} + +fn span_remove(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_span(h, a)?, &text("")) +} + +fn span_start(h: &Host, a: &[Data]) -> Answer { + let (_, s, _, _) = resolve(h, this_span(h, a)?)?; + Ok(num(float(s as u64))) +} + +fn span_end(h: &Host, a: &[Data]) -> Answer { + let (_, _, e, _) = resolve(h, this_span(h, a)?)?; + Ok(num(float(e as u64))) +} + +fn span_length(h: &Host, a: &[Data]) -> Answer { + let (_, s, e, _) = resolve(h, this_span(h, a)?)?; + Ok(num(float((e - s) as u64))) +} + +fn span_story(h: &Host, a: &[Data]) -> Answer { + let r = this_span(h, a)?; + resolve(h, r)?; + Ok(story_ref(h, r.story)) +} + +fn span_paragraph_length(h: &Host, a: &[Data]) -> Answer { + let (index, s, e, _) = resolve(h, this_span(h, a)?)?; + let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x); + Ok(num(float(p as u64))) +} + +fn span_part(h: &Host, a: &[Data], class: &str) -> Answer { + let r = this_span(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(span_ref(h, r.story, s, e, stamp, class)) +} + +fn span_characters(h: &Host, a: &[Data]) -> Answer { + span_part(h, a, "StoryCharacters") +} + +fn span_words(h: &Host, a: &[Data]) -> Answer { + span_part(h, a, "StoryWords") +} + +fn span_paragraphs(h: &Host, a: &[Data]) -> Answer { + span_part(h, a, "StoryParagraphs") +} + +fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(StorySpan, Part), HostError> { + let part = STORY_PARTS.iter().find(|(c, _)| handle_of(arg(a, 0), c).is_some()).map(|(_, p)| *p); + let part = part.ok_or_else(|| HostError::Type("this is not a collection of text".into()))?; + Ok((span_of(h, arg(a, 0), &STORY_PARTS.map(|(c, _)| c))?, part)) +} + +fn part_typename(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + resolve(h, r)?; + Ok(text(match part { + Part::Characters => "Characters", + Part::Words => "Words", + Part::Paragraphs => "Paragraphs", + })) +} + +fn span_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, this_span(h, a)?)?; + Ok(text("TextRange")) +} + +fn story_typename(h: &Host, a: &[Data]) -> Answer { + this_story(h, a)?; + Ok(text("Story")) +} + +fn part_length(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + Ok(num(float(part_spans(&index, part, s, e).0.len() as u64))) +} + +fn part_parent(h: &Host, a: &[Data]) -> Answer { + let (r, _) = this_part(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(span_ref(h, r.story, s, e, stamp, "StoryRange")) +} + +fn part_at(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let (index, s, e, stamp) = resolve(h, r)?; + let (items, spans) = part_spans(&index, part, s, e); + let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) }; + let span = match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + Ok(span.map_or(Data::Undefined, |(x, y)| span_ref(h, r.story, x, y, stamp, "StoryRange"))) +} + +// ---- Stories ---- + +fn doc_stories_impl(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Stories", &[float(h.run), float(doc.uid)])) +} + +/// `document.stories`. +pub(in crate::script::dom) fn doc_stories(link: &Link) -> HostMember { + get(link, doc_stories_impl) +} + +/// The first frame of each story of the document in paint order, kept while the document is +/// unchanged. +fn heads(h: &Host, st: &DocState) -> std::result::Result>, HostError> { + if let Some((uid, doc, ids)) = &*h.dom.text.stories.list.borrow() + && *uid == st.uid + && std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc)) + { + return Ok(ids.clone()); + } + let ids = frame_ids(h, st); + h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::())?; + // A frame listed by an earlier thread belongs to that one, as `story_of` finds it. + let (mut threaded, mut first) = (HashSet::new(), HashSet::new()); + let mut seen = HashSet::new(); + for thread in &st.doc.text_threads { + let live: Vec = thread.iter().copied().filter(|f| threadable(st, *f) && seen.insert(*f)).collect(); + if live.len() >= 2 { + first.insert(live[0]); + threaded.extend(live); + } + } + let heads: Vec = ids.iter().copied().filter(|id| !threaded.contains(id) || first.contains(id)).collect(); + let heads = Rc::new(heads); + *h.dom.text.stories.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), heads.clone())); + Ok(heads) +} + +fn stories_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Stories") +} + +fn stories_length(h: &Host, a: &[Data]) -> Answer { + let doc = stories_doc(h, a)?; + let n = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.len()))?; + Ok(num(float(n as u64))) +} + +fn stories_typename(h: &Host, a: &[Data]) -> Answer { + stories_doc(h, a)?; + Ok(text("Stories")) +} + +fn stories_parent(h: &Host, a: &[Data]) -> Answer { + let doc = stories_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn stories_at(h: &Host, a: &[Data]) -> Answer { + let doc = stories_doc(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let id = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.get(i).copied()))?; + Ok(id.map_or(Data::Undefined, |id| story_ref(h, Item { doc, id }))) +} + +/// `stories.index(key)`: by number, or by the name of a story's first frame. +fn stories_index(h: &Host, a: &[Data]) -> Answer { + let doc = stories_doc(h, a)?; + match arg(a, 1) { + Data::Number(_) => match stories_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + Data::String(name) => { + let id = with_doc(h, doc, |_, st| { + let list = heads(h, st)?; + h.charge_call(list.len() as u64)?; + Ok::<_, HostError>(list.iter().copied().find(|i| st.doc.node(*i).and_then(|n| n.name.as_deref()) == Some(name.as_str()))) + })?; + id.map(|id| story_ref(h, Item { doc, id })).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + } + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +// ---- classes ---- + +/// A member of the range of a story of two or more frames that is not available yet: reading or +/// assigning it throws, after the check that the range is still there. +fn range_later(link: &Link, name: &'static str) -> (String, HostMember) { + let message = format!("TextRange.{name} is not available yet"); + let l = link.clone(); + let f: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + resolve(&h, this_span(&h, &a)?)?; + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Property { get: f.clone(), set: f }) +} + +/// The members of `TextFrame` this module adds. +pub(super) fn frame_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![ + ("nextFrame", property(l, next_frame, set_next_frame)), + ("previousFrame", property(l, previous_frame, set_previous_frame)), + ("story", get(l, frame_story)), + ]) +} + +/// `TextRange.story`. +pub(super) fn range_member(l: &Link) -> (String, HostMember) { + ("story".into(), get(l, range_story)) +} + +/// `Story`, `Stories` and the range and collections of the text of a story of two or more frames. +pub(super) fn classes(l: &Link) -> Vec { + let mut story = named(vec![ + ("typename", get(l, story_typename)), + ("parent", get(l, story_parent)), + ("length", get(l, story_length)), + ("textFrames", get(l, story_frames)), + ("textRange", get(l, story_text_range)), + ("characters", get(l, story_characters)), + ("words", get(l, story_words)), + ("paragraphs", get(l, story_paragraphs)), + ]); + story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| later(l, "Story", m))); + let mut range = named(vec![ + ("typename", get(l, span_typename)), + ("parent", get(l, span_story)), + ("story", get(l, span_story)), + ("contents", property(l, span_contents, span_set_contents)), + ("start", read_only(l, span_start, "TextRange", "start")), + ("end", read_only(l, span_end, "TextRange", "end")), + ("characterOffset", read_only(l, span_start, "TextRange", "characterOffset")), + ("length", read_only(l, span_length, "TextRange", "length")), + ("characters", get(l, span_characters)), + ("words", get(l, span_words)), + ("paragraphs", get(l, span_paragraphs)), + ("getParagraphLength", method(l, span_paragraph_length)), + ("remove", method(l, span_remove)), + ]); + range.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "characterAttributes", + "paragraphAttributes", + "kerning", + "characterStyles", + "paragraphStyles", + "textSelection", + "changeCaseTo", + "select", + "deSelect", + "duplicate", + "move", + "getTextRunLength", + "getLocalCharOverridesJSON", + "getLocalParaOverridesJSON", + ] + .into_iter() + .chain(ATTRS.iter().map(|(n, _)| *n)) + .map(|m| range_later(l, m)), + ); + let part = |name: &'static str| { + class( + name, + None, + named(vec![("typename", get(l, part_typename)), ("length", get(l, part_length)), ("parent", get(l, part_parent))]), + Some(function(l, part_at)), + ) + }; + vec![ + class("Story", None, story, None), + class("StoryRange", None, range, None), + part("StoryCharacters"), + part("StoryWords"), + part("StoryParagraphs"), + class( + "Stories", + None, + named(vec![ + ("typename", get(l, stories_typename)), + ("length", get(l, stories_length)), + ("parent", get(l, stories_parent)), + ("index", method(l, stories_index)), + ]), + Some(function(l, stories_at)), + ), + ] +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cd2a81daeb..c9326a496c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -179,6 +179,7 @@ mod script_include; mod script_io; mod script_run; mod script_text; +mod script_threads; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs new file mode 100644 index 0000000000..6d919a21d9 --- /dev/null +++ b/crates/engine/src/tests/script_threads.rs @@ -0,0 +1,596 @@ +//! Threaded type in the script object model: `nextFrame`, `previousFrame`, `story`, +//! `document.stories`, and the text of a story of several frames. + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +fn new_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +/// Area type `width` × `height` at `x` holding `text`. +fn area(s: &mut Session, x: f64, width: f64, height: f64, text: &str) -> NodeId { + let r = s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "size": 12, "area": {"width": width, "height": height}})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn plain(s: &Session, id: NodeId) -> String { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } +} + +fn threads(s: &Session) -> Vec> { + s.active().unwrap().doc.text_threads.clone() +} + +/// The text of every frame of the document's threads, in thread order. +fn story(s: &Session, frames: &[NodeId]) -> String { + frames.iter().map(|f| plain(s, *f)).collect() +} + +/// Two area frames threaded into one story whose text starts in the first, one line high, and +/// flows on into the second. +fn threaded(text: &str) -> (Session, NodeId, NodeId) { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 90.0, 18.0, text); + let b = area(&mut s, 150.0, 200.0, 200.0, ""); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(threads(&s), vec![vec![a, b]]); + (s, a, b) +} + +const STORY: &str = "alpha beta gamma\ndelta \u{1F600}"; + +#[test] +fn stories_list_one_story_for_each_thread_and_each_frame_in_none() { + let (mut s, _, _) = threaded(STORY); + area(&mut s, 400.0, 120.0, 40.0, "Alone"); + let out = log( + &mut s, + "var d = app.activeDocument, st = d.stories[0];\ + vc.log(d.stories.length); vc.log(st.typename); vc.log(st.textFrames.length);\ + vc.log(st.textFrames[0].nextFrame.previousFrame.contents === st.textFrames[0].contents);\ + vc.log(st.textFrames[1].nextFrame === null && st.textFrames[0].previousFrame === null);\ + vc.log(d.stories[1].textFrames[0].contents); vc.log(d.stories[1].textFrames.length);\ + d.textFrames.add(); vc.log(d.stories.length);\ + vc.log(d.stories.parent.typename); vc.log(st.parent.typename); vc.log(d.stories.typename);\ + vc.log(d.textFrames[2].story.textFrames[0].contents);", + ); + assert_eq!( + out, + vec![ + json!(2), + json!("Story"), + json!(2), + json!(true), + json!(true), + json!("Alone"), + json!(1), + json!(3), + json!("Document"), + json!("Document"), + json!("Stories"), + json!("Alone") + ] + ); +} + +#[test] +fn a_story_range_counts_utf16_units_across_its_frames() { + let (mut s, a, b) = threaded(STORY); + let (first, second) = (plain(&s, a), plain(&s, b)); + assert!(!first.is_empty() && !second.is_empty(), "the story flows through both frames: {first:?} {second:?}"); + assert_eq!(first.clone() + &second, STORY); + let out = log( + &mut s, + "var st = app.activeDocument.textFrames[0].story, r = st.textRange;\ + vc.log(st.length); vc.log(r.length); vc.log(r.contents); vc.log(r.typename);\ + vc.log(st.characters.length); vc.log(st.words.length); vc.log(st.paragraphs.length);\ + vc.log(st.paragraphs[0].contents); vc.log(st.words[4].contents); vc.log(st.words[4].start);\ + vc.log(r.paragraphs[1].getParagraphLength()); vc.log(r.story.length);\ + vc.log(app.activeDocument.textFrames[0].textRange.length < r.length);", + ); + assert_eq!( + out, + vec![ + json!(25), + json!(25), + json!("alpha beta gamma\rdelta \u{1F600}"), + json!("TextRange"), + json!(24), + json!(5), + json!(2), + json!("alpha beta gamma\r"), + json!("\u{1F600}"), + json!(23), + json!(8), + json!(25), + json!(true) + ] + ); +} + +/// The members a long story's range does not have yet throw that they are not available, and +/// first that a range that went stale is stale. +#[test] +fn a_story_range_names_the_members_it_does_not_have_yet() { + let (mut s, _, b) = threaded(STORY); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].story.textRange;\ + try { r.characterAttributes; } catch (e) { vc.log(String(e.message)); }\ + try { r.size = 20; } catch (e) { vc.log(String(e.message)); }\ + try { app.activeDocument.textFrames[0].story.lines; } catch (e) { vc.log(String(e.message)); }", + ); + assert_eq!( + out, + vec![ + json!("TextRange.characterAttributes is not available yet"), + json!("TextRange.size is not available yet"), + json!("Story.lines is not available yet") + ] + ); + let message = failure( + &mut s, + &format!( + "var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.characterAttributes;", + b.0 + ), + ); + assert!(message.contains("Stale text range"), "{message}"); + let message = failure( + &mut s, + &format!( + "var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.typename;", + b.0 + ), + ); + assert!(message.contains("Stale text range"), "{message}"); +} + +/// Ranges of one story read from different frames keep their places through each other's edits. +#[test] +fn story_ranges_read_from_different_frames_follow_each_others_edits() { + let (mut s, _, _) = threaded(STORY); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames, x = t[0].story.words[0], y = t[1].story.words[1];\ + x.contents = 'Q'; vc.log(y.contents); vc.log(y.start); y.contents = 'B'; vc.log(x.contents);\ + vc.log(t[1].story.textRange.contents);", + ); + assert_eq!(out, vec![json!("beta"), json!(2), json!("Q"), json!("Q B gamma\rdelta \u{1F600}")]); +} + +/// A story range that an edit covers holds the edit's new text, as a frame's range does. +#[test] +fn a_story_range_an_edit_covers_holds_the_new_text() { + let (mut s, _, _) = threaded(STORY); + let out = log( + &mut s, + "var st = app.activeDocument.textFrames[0].story, w = st.words[1], p = st.paragraphs[1];\ + st.textRange.contents = 'Z'; vc.log(w.contents); vc.log(p.contents); vc.log(w.typename); vc.log(st.words.typename);", + ); + assert_eq!(out, vec![json!("Z"), json!("Z"), json!("TextRange"), json!("Words")]); +} + +#[test] +fn a_story_edit_across_frames_reflows_in_one_undo_step() { + let (mut s, a, b) = threaded(STORY); + let before = undo_steps(&s); + let out = log( + &mut s, + "var st = app.activeDocument.textFrames[0].story, frame = app.activeDocument.textFrames[1].textRange;\ + var p = st.paragraphs[0], tail = st.paragraphs[1];\ + p.contents = 'X\\r'; vc.log(st.textRange.contents); vc.log(tail.contents); vc.log(tail.start);\ + try { frame.contents; } catch (e) { vc.log(String(e.message)); }\ + st.words[2].remove(); vc.log(st.textRange.contents);", + ); + assert_eq!(out, vec![json!("X\rdelta \u{1F600}"), json!("delta \u{1F600}"), json!(2), json!("Stale text range"), json!("X\rdelta ")]); + assert_eq!(story(&s, &[a, b]), "X\ndelta "); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(story(&s, &[a, b]), STORY); +} + +#[test] +fn a_story_range_is_stale_after_another_change_to_the_story() { + let (mut s, _, b) = threaded(STORY); + let message = failure( + &mut s, + &format!( + "var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.contents;", + b.0 + ), + ); + assert!(message.contains("Stale text range"), "{message}"); +} + +#[test] +fn a_story_range_made_before_file_revert_is_stale_even_when_the_text_is_the_same() { + let (mut s, _, _) = threaded(STORY); + let path = std::env::temp_dir().join(format!("vc-story-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].story.words[1];\ + vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\ + var st = app.activeDocument.textFrames[0].story;\ + vc.log(st.textFrames.length); vc.log(st.textRange.contents);\ + try { vc.log(r.contents); } catch (e) { vc.log(String(e.message)); }\ + vc.log(st.words[1].contents);", + ); + let _ = std::fs::remove_file(&path); + assert_eq!(out[0], json!(2), "the reverted file keeps the thread"); + assert_eq!(out[1], json!("alpha beta gamma\rdelta \u{1F600}"), "the reverted file holds the same text"); + assert!(out[2].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert_eq!(out[3], json!("beta"), "a range made after the revert reads the reverted text"); +} + +#[test] +fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 120.0, 60.0, "First story."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Second."); + let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [p.0]})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames; t[0].nextFrame = t[1];\ + vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[0].story.textRange.contents);\ + t[0].nextFrame = t[1];", + ); + assert_eq!(out, vec![json!(2), json!("First story.Second."), json!("First story.Second.")]); + assert_eq!(threads(&s), vec![vec![a, b]]); + assert_eq!(story(&s, &[a, b]), "First story.Second."); + assert_eq!(undo_steps(&s), before + 1); + assert_eq!(s.active().unwrap().selection.objects.to_vec(), vec![p]); + // previousFrame links the other way. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(threads(&s).is_empty()); + assert_eq!((plain(&s, a), plain(&s, b)), ("First story.".into(), "Second.".into())); + log(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); + assert_eq!(threads(&s), vec![vec![b, a]]); + assert_eq!(story(&s, &[b, a]), "Second.First story."); +} + +#[test] +fn null_breaks_the_link_and_each_frame_keeps_its_text() { + let (mut s, a, b) = threaded(STORY); + let (first, second) = (plain(&s, a), plain(&s, b)); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames, st = t[1].story; t[1].previousFrame = null;\ + vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[0].nextFrame);\ + t[0].nextFrame = null;", + ); + assert_eq!(out, vec![json!(2), json!(1), json!(null)]); + assert!(threads(&s).is_empty()); + assert_eq!((plain(&s, a), plain(&s, b)), (first, second)); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(threads(&s), vec![vec![a, b]]); +} + +#[test] +fn area_and_path_text_thread_the_new_frame_to_a_base_frame() { + let mut s = new_doc(); + let base = area(&mut s, 10.0, 120.0, 40.0, "Base text that is long enough to flow on into the frames made after it."); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 350, "y": 10, "width": 120, "height": 60})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 300}, {"x": 400, "y": 320}], "closed": false})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, base = d.textFrames[0];\ + var after = d.textFrames.areaText(p[1], undefined, base);\ + var first = d.textFrames.areaText(p[2], TextOrientation.HORIZONTAL, base, false);\ + var last = d.textFrames.pathText(p[3], undefined, undefined, undefined, after, true);\ + vc.log(base.story.textFrames.length); vc.log(base.previousFrame.kind); vc.log(after.nextFrame.kind); vc.log(d.stories.length);", + ); + assert_eq!(out, vec![json!(4), json!("TextType.AREATEXT"), json!("TextType.PATHTEXT"), json!(1)]); + let t = threads(&s); + assert_eq!(t.len(), 1); + assert_eq!(t[0][1], base, "the frame made with postFix false comes before the base frame: {t:?}"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn a_bad_base_frame_is_refused_before_a_frame_is_made() { + let mut s = new_doc(); + s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap(); + let count = |s: &Session| s.active().unwrap().doc.node_count(); + let (n, before) = (count(&s), undo_steps(&s)); + let d = "var d = app.activeDocument, p = d.pageItems;"; + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, d.textFrames[0]);")).contains("only area type")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, p[1]);")).contains("baseFrame must be a TextFrame")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, d.textFrames[0], 'yes');")).contains("postFix")); + assert_eq!((count(&s), undo_steps(&s)), (n, before)); +} + +/// A base frame given with a path inside a compound path is refused before the path is turned +/// into type, so a script that catches the error finds the path as it was. +#[test] +fn a_base_frame_for_a_path_in_a_compound_path_leaves_the_path() { + let mut s = new_doc(); + area(&mut s, 10.0, 120.0, 60.0, "Base."); + let r1 = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap(); + let r2 = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [r1, r2]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, p = null;\ + for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') { p = d.pageItems[i]; break; } }\ + try { d.textFrames.areaText(p, undefined, d.textFrames[0]); } catch (e) { vc.log(String(e.message)); }\ + vc.log(p.typename); vc.log(d.textFrames.length);", + ); + assert_eq!(out, vec![json!("baseFrame: type made from a path inside a compound path cannot be threaded"), json!("PathItem"), json!(1)]); + assert_eq!(undo_steps(&s), before); +} + +/// A thread of `a` and `b`, a third area frame `c`, and point type `p`; what the document holds +/// now, to check that a refused change left it alone. +fn three() -> (Session, [NodeId; 4]) { + let (mut s, a, b) = threaded(STORY); + let c = area(&mut s, 400.0, 120.0, 40.0, "Third"); + let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap()); + (s, [a, b, c, p]) +} + +fn unchanged(s: &Session, ids: &[NodeId], before: &(Vec>, Vec, usize)) { + assert_eq!((threads(s), ids.iter().map(|i| plain(s, *i)).collect::>(), undo_steps(s)), *before); +} + +fn state(s: &Session, ids: &[NodeId]) -> (Vec>, Vec, usize) { + (threads(s), ids.iter().map(|i| plain(s, *i)).collect(), undo_steps(s)) +} + +#[test] +fn a_link_to_the_frame_itself_is_refused() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[2];"); + assert!(m.contains("nextFrame") && m.contains("itself"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_link_that_makes_a_loop_is_refused() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];"); + assert!(m.contains("loop"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); + assert!(m.contains("loop"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_link_into_the_middle_of_a_story_is_refused() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];"); + assert!(m.contains("already has a previous frame"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[0];"); + assert!(m.contains("already has a next frame"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn point_type_and_other_values_cannot_be_linked() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];"); + assert!(m.contains("only area type"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];"); + assert!(m.contains("only area type"), "{m}"); + let m = failure(&mut s, "app.activeDocument.textFrames[2].nextFrame = 5;"); + assert!(m.contains("TypeError") && m.contains("TextFrame or null"), "{m}"); + let m = failure(&mut s, "app.activeDocument.textFrames[2].nextFrame = undefined;"); + assert!(m.contains("TextFrame or null"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_hidden_or_locked_frame_in_either_story_stops_a_link() { + let (mut s, ids) = three(); + log(&mut s, "app.activeDocument.textFrames[1].locked = true;"); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];"); + assert!(m.contains("hidden or locked"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].nextFrame = null;"); + assert!(m.contains("hidden or locked"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_frame_of_another_document_cannot_be_linked() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + area(&mut s, 10.0, 100.0, 40.0, "Elsewhere"); + let m = failure(&mut s, "app.documents[0].textFrames[2].nextFrame = app.documents[1].textFrames[0];"); + assert!(m.contains("different documents"), "{m}"); + let m = failure(&mut s, "app.documents[1].textFrames.areaText(app.documents[1].pageItems[0], undefined, app.documents[0].textFrames[2]);"); + assert!(m.contains("another document") || m.contains("PathItem"), "{m}"); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_deleted_frame_makes_its_story_and_links_stale() { + let (mut s, _, _) = threaded(STORY); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], st = f.story; f.remove(); st.length;"); + assert!(m.contains("Stale story"), "{m}"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], g = app.activeDocument.textFrames[1]; g.remove(); f.nextFrame = g;"); + assert!(m.contains("Stale page item"), "{m}"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], r = f.story.textRange; f.remove(); r.contents;"); + assert!(m.contains("Stale text range"), "{m}"); + // A story read from a frame that stays follows it when its link is broken. + let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[1].story; t[0].nextFrame = null; vc.log(st.textFrames.length);"); + assert_eq!(out, vec![json!(1)]); +} + +#[test] +fn stories_refuse_bad_keys_and_huge_numbers() { + let (mut s, _, _) = threaded(STORY); + let out = log( + &mut s, + "var st = app.activeDocument.stories; vc.log(st[1e300] === undefined); vc.log(st[-1] === undefined); vc.log(st[0.5] === undefined);", + ); + assert_eq!(out, vec![json!(true), json!(true), json!(true)]); + assert!(failure(&mut s, "app.activeDocument.stories.index(1e20);").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.stories.index('nobody');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.stories.index({});").contains("TypeError")); + log(&mut s, "app.activeDocument.textFrames[0].name = 'Lead';"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.stories.index('Lead').textFrames.length);"), vec![json!(2)]); +} + +#[test] +fn a_long_story_walks_to_its_end_and_refuses_a_loop() { + let mut s = new_doc(); + let ids: Vec = (0..120).map(|i| area(&mut s, f64::from(i % 12) * 45.0, 40.0, 20.0, if i == 0 { STORY } else { "" })).collect(); + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(threads(&s), vec![ids.clone()]); + let out = log( + &mut s, + "var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame) { f = f.nextFrame; n++; } \ + vc.log(n); vc.log(f.story.textFrames.length); vc.log(d.stories.length);", + ); + assert_eq!(out, vec![json!(120), json!(120), json!(1)]); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[t.length - 1].nextFrame = t[0];"); + assert!(m.contains("loop"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[0].previousFrame = t[t.length - 1];"); + assert!(m.contains("loop"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[60].nextFrame = t[30];"); + assert!(m.contains("loop"), "{m}"); + unchanged(&s, &ids, &before); +} + +/// A stored thread that lists a frame twice, as a file can, is a story that visits each frame +/// once, so a walk along `nextFrame` ends. +#[test] +fn a_thread_listing_a_frame_twice_is_walked_once() { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 120.0, 60.0, "One."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b, a]]; + let out = log( + &mut s, + "var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame && n < 10) { f = f.nextFrame; n++; } \ + vc.log(n); vc.log(d.stories[0].textFrames.length); vc.log(d.stories.length);", + ); + assert_eq!(out, vec![json!(2), json!(2), json!(1)]); + let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": null})).unwrap(); + assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]})); + assert!(threads(&s).is_empty()); +} + +/// A story and its range keep the exact id of the frame they were read from, also past 2^53. +#[test] +fn a_story_read_from_a_frame_with_a_large_id_stays_with_that_frame() { + let mut s = new_doc(); + // The second frame's id, 2^53 + 1, is not exact as a number. + let big = 1u64 << 53; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = area(&mut s, 10.0, 120.0, 60.0, "One."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); + assert_eq!((a.0, b.0), (big, big + 1)); + s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap(); + let out = log( + &mut s, + "var st = app.activeDocument.stories[0].textFrames[1].story, r = st.textRange; vc.log(r.contents);\ + st.textFrames[0].nextFrame = null; vc.log(st.textFrames.length); vc.log(st.textFrames[0].contents); vc.log(st.typename);", + ); + // The whole story flows into the first frame, so the second is empty once the link is broken. + assert_eq!(out, vec![json!("One.Two."), json!(1), json!(""), json!("Story")]); +} + +#[test] +fn set_neighbor_links_and_breaks_frames_by_id_without_a_selection() { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 120.0, 60.0, "One."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); + s.execute("select.none", &json!({})).unwrap(); + let before = undo_steps(&s); + let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap(); + assert_eq!(r, json!({"changed": true, "threads": [[a.0, b.0]]})); + let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": a.0})).unwrap(); + assert_eq!(r["changed"], json!(false)); + assert_eq!(undo_steps(&s), before + 1); + assert!(s.active().unwrap().selection.objects.is_empty()); + let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap(); + assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]})); + let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap(); + assert_eq!(r["changed"], json!(false)); + assert_eq!(undo_steps(&s), before + 2); + for bad in [ + json!({"id": a.0, "side": "up", "neighbor": b.0}), + json!({"id": a.0, "side": "next"}), + json!({"id": a.0, "side": "next", "neighbor": 999_999}), + ] { + assert!(s.execute("text.thread.setNeighbor", &bad).is_err(), "{bad}"); + } + assert_eq!(undo_steps(&s), before + 2); +} + +/// Breaking a link where a paragraph starts makes the frames after it a story whose numbered +/// paragraphs count from 1, also when that story keeps two frames. +#[test] +fn a_break_at_a_paragraph_start_numbers_the_later_story_from_one() { + let mut s = new_doc(); + let items = (1..=12).map(|i| format!("Item {i}")).collect::>().join("\n"); + let ids = [area(&mut s, 10.0, 150.0, 60.0, &items), area(&mut s, 200.0, 150.0, 60.0, ""), area(&mut s, 400.0, 150.0, 200.0, "")]; + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("text.setFormat", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "list": "number"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let numbers = |s: &Session, id: NodeId| { + let Some(NodeKind::Text(t)) = s.active().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("text") }; + assert!(!t.first_para_continues, "every frame starts a paragraph"); + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::>() + }; + let first = numbers(&s, ids[0]); + assert!(!first.is_empty() && !numbers(&s, ids[1]).is_empty(), "the first two frames hold items"); + assert_ne!(numbers(&s, ids[1]).first().map(String::as_str), Some("1.")); + let r = s.execute("text.thread.setNeighbor", &json!({"id": ids[0].0, "side": "next", "neighbor": null})).unwrap(); + assert_eq!(r, json!({"changed": true, "threads": [[ids[0].0], [ids[1].0, ids[2].0]]})); + let later = [numbers(&s, ids[1]), numbers(&s, ids[2])].concat(); + let expected: Vec = (1..=later.len()).map(|n| format!("{n}.")).collect(); + assert_eq!(later, expected, "the later story counts from 1"); + assert_eq!(numbers(&s, ids[0]), first); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index c7e7000f13..b638262389 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -90,7 +90,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames typename \ + rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= textFrames typename \ views views= width", ), ("Layer.", "prototype"), @@ -135,7 +135,7 @@ const INSIDE: &[(&str, &str)] = &[ contents contents= convertAreaObjectToPointObject convertPointObjectToAreaObject createOutline endTValue endTValue= \ insertionPoints insertionPoints= kind lines lines= matrix matrix= nextFrame nextFrame= opticalAlignment \ opticalAlignment= orientation orientation= paragraphs previousFrame previousFrame= rowCount rowCount= rowGutter \ - rowGutter= startTValue startTValue= story story= textPath textPath= textRange textRanges textRanges= textSelection \ + rowGutter= startTValue startTValue= story textPath textPath= textRange textRanges textRanges= textSelection \ textSelection= words", ), ("TextRange.", "prototype"), @@ -147,7 +147,7 @@ const INSIDE: &[(&str, &str)] = &[ getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale horizontalScale= insertionPoints \ insertionPoints= kerning kerning= leading leading= length length= lines lines= move move= paragraphAttributes \ paragraphStyles paragraphStyles= paragraphs parent remove rotation rotation= select select= size size= start start= \ - story story= strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ + story strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ tracking tracking= typename underline underline= verticalScale verticalScale= words", ), ("Characters.", "prototype"), @@ -176,6 +176,34 @@ const INSIDE: &[(&str, &str)] = &[ ("Justification.", "CENTER FULLJUSTIFY FULLJUSTIFYLASTLINECENTER FULLJUSTIFYLASTLINELEFT FULLJUSTIFYLASTLINERIGHT LEFT RIGHT"), ("TextOrientation.", "HORIZONTAL VERTICAL"), ("TextType.", "AREATEXT PATHTEXT POINTTEXT"), + ("", "Stories Story StoryCharacters StoryParagraphs StoryRange StoryWords"), + ("Stories.", "prototype"), + ("Stories.prototype.", "constructor index length parent typename"), + ("Story.", "prototype"), + ( + "Story.prototype.", + "characters constructor insertionPoints insertionPoints= length lines lines= paragraphs parent textFrames textRange \ + textRanges textRanges= textSelection textSelection= typename words", + ), + ("StoryRange.", "prototype"), + ( + "StoryRange.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \ + characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \ + contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \ + getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \ + getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \ + length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \ + paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \ + strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \ + underline underline= verticalScale verticalScale= words", + ), + ("StoryCharacters.", "prototype"), + ("StoryCharacters.prototype.", "constructor length parent typename"), + ("StoryWords.", "prototype"), + ("StoryWords.prototype.", "constructor length parent typename"), + ("StoryParagraphs.", "prototype"), + ("StoryParagraphs.prototype.", "constructor length parent typename"), ]; /// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` diff --git a/docs/gaps.md b/docs/gaps.md index 47a1680f6e..2a6e8005f9 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -807,10 +807,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, stories and threads - of type, and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open +- **Missing:** the rest of the document object model for scripts (layers, artboards, paths and the other classes) + and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames with their text ranges and - character and paragraph attributes, and the installed fonts. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + character and paragraph attributes, their links to each other and the stories they form, and the installed fonts. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index a75c5386f5..2f81d1838d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2728,9 +2728,36 @@ app through the global object `vc`, and writes to the Script Console and runs ot the auto leading. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws when `text.setRangeStyle` warns that the font is not available, or when Missing Glyph Protection keeps characters the font has no glyph for in their font, giving how many. A `TextFont` from an earlier run throws - `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and + `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.textPath` and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, `length` and `orientation` cannot be set yet. +- Threaded type (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, + https://ai-scripting.docsforadobe.dev/jsobjref/Story/, https://ai-scripting.docsforadobe.dev/jsobjref/Stories/): a + `TextFrame` has `nextFrame` and `previousFrame`, the frames after and before it in its story (`null` at either end), + and `story`; a `TextRange` has `story` too. Assigning `nextFrame` or `previousFrame` runs `text.thread.setNeighbor`: + a frame links the last frame of one story to the first frame of another, whose text flows on after the first story's + text, and `null` breaks that link, no text moving across it. `areaText(path, orientation?, baseFrame?, + postFix?)` and `pathText(path, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)` thread the new frame + after `baseFrame`, or before it when `postFix` is false, with `text.thread.add`; `startTValue` and `endTValue` are + not available yet. `Document.stories` lists the stories with `length`, `[i]` and `index(key)`. A `Story` has + `parent` (its document), `length`, `textFrames` (an array of its frames in thread order), `textRange`, `characters`, + `words` and `paragraphs`; `lines`, `insertionPoints`, `textRanges` and `textSelection` are not available yet. + VectorCraft's own rules: point type, a frame of another document, the frame itself, a frame inside a story, a link + that would make a loop and a story with a hidden or locked frame are refused with nothing changed, and assigning the + link that is already there, or `null` where there is none, runs no command. `postFix` is true when it is left out, + and a `baseFrame` given with a path inside a compound path is refused before the path is turned into type. + `Document.stories` lists one story for each type object in no thread and one for each thread, in the paint order of + their first frames, and `index` with a string finds the first story whose first frame has that name. A frame that + a stored thread lists twice is in its story once. A `Story` is + the story of the frame it was read from, as that frame is threaded now, and throws `Stale story` once that frame is + deleted. The text of a story of one frame is that frame's text, with its ranges. The text of a longer story is its + frames' text in thread order, counted in UTF-16 units: its `textRange` reads and writes across the frames, and + writing it edits the frames from the last one it reaches back to the first, inside the run's one undo step, and the + story then flows through its frames again. Such a range has `contents`, `start`, `end`, `characterOffset`, + `length`, `parent` and `story` (its story), `characters`, `words`, `paragraphs`, `getParagraphLength()` and + `remove()`; its character and paragraph attributes and the other members are not available yet. It keeps its place + through edits made through the story's ranges and throws `Stale text range` after any other change to the story's + text and after `file.revert`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -11523,6 +11550,18 @@ after it (`out`). The whole story flows into the frames before the break; the fr threaded with each other when two or more remain, and the first of them starts a paragraph. It refuses an `id` that doesn't exist, a `port` other than `in` or `out`, and a side where no frame of a thread comes before or after `id`. +`text.thread.setNeighbor {id, side: "next" | "previous", neighbor: id | null}` is what a script's `nextFrame` and +`previousFrame` assignments run, and needs no selection. With an id it links area type or type on a path `id` to +`neighbor` after it (`next`) or before it (`previous`): `id` must be the last frame of its story for `next` (the first +for `previous`) and `neighbor` the first (the last) frame of another story, and the second story's text flows on after +the first's (one undo step, Thread Text). With `null` it breaks the link on that side, and the frames on each side +form a story of their own (one undo step, Break Thread): no text moves across the break, and the frames after it flow +their own text again from their first frame, which now starts a paragraph. It refuses point type and +other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a story with a +hidden or locked frame, with nothing changed. A link that is already there, or a break where there is no link, changes +nothing and records no undo step. The selection is kept. It returns `{changed, threads}`, `threads` listing the +stories of the frames involved after the change, a story of one frame as `[id]`. + `select.same.linkBlockSeries` (Select › Same › Link Block Series) selects every frame of the threads that the selected type objects, and the type inside selected groups, are in, in thread order, and returns `{count}`. Type in no thread selects itself, and other selected objects are left out. With frames of several threads selected, it selects the frames diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6a957cad0..355a11543a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,6 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From a5690d2d35485db131a6adb6be3c9c5c3136993c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:08:05 -0800 Subject: [PATCH 19/91] Scripts: stories of one thread share their text index, and a deleted story's missing members say Stale story Stories read from different frames of one thread share one index of the story's text while the document is unchanged, instead of each keeping its own copy. A frame listed in two threads shares only with a story whose frames match. Story.lines, insertionPoints, textRanges and textSelection check the story first, so a story whose frame was deleted throws Stale story. The cross-document baseFrame test passes a rectangle of the other document and checks the error and that the rectangle stays a path. docs/mcp.md no longer says baseFrame and postFix throw, the text-frame entry in docs/target-app-parity.md no longer lists stories and threading as missing, and the M13 row in docs/roadmap.md lists text frames and stories. --- crates/engine/src/script/dom/text/threads.rs | 74 +++++++++++++++----- crates/engine/src/tests/script_threads.rs | 27 ++++++- docs/mcp.md | 4 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- 5 files changed, 84 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs index ee81129944..cfdb4119c6 100644 --- a/crates/engine/src/script/dom/text/threads.rs +++ b/crates/engine/src/script/dom/text/threads.rs @@ -34,7 +34,7 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, host_ use super::super::{ Answer, Doc, Host, Item, Link, NOT_FOUND, arg, boolean, class, current, doc_of, doc_ref, edit_item, find_doc, float, function, get, handle_of, - id_of, id_parts, in_compound, item_of, item_ref, later, method, named, num, property, text, whole, with_doc, + id_of, id_parts, in_compound, item_of, item_ref, method, named, num, property, text, whole, with_doc, }; use super::{ ATTRS, Index, Log, Part, STALE_RANGE, frame_ids, from_script, part_spans, range_ref, read_only, text_of, this_frame, to_script, touched, @@ -284,7 +284,8 @@ fn story_text(st: &DocState, frames: &[NodeId]) -> String { frames.iter().filter_map(|f| text_of(st, *f)).flat_map(|t| t.runs.iter().map(|r| r.text.as_str())).collect() } -/// The story's index and its generation now, read again when its document changed. +/// The story's index and its generation now, read again when its document changed. The stories +/// read from the frames of one story share one index of its text while the document is unchanged. fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc, u64), HostError> { if text_of(st, anchor).is_none() { return Err(HostError::Error(STALE_STORY.into())); @@ -292,24 +293,45 @@ fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc {} - Some(l) => { - let frames = charged_frames(h, st, anchor)?; - let text = story_text(st, &frames); - if l.reverts != st.reverts || text != l.index.text { - l.stamp += 1; - l.floor = l.stamp; - l.edits.clear(); - l.index = Rc::new(Index::new(text)); + let current = |l: &Log| std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts; + if !logs.get(&key).is_some_and(current) { + let frames = charged_frames(h, st, anchor)?; + // Another frame of the same story read at this state of the document has the same text; + // a frame listed in two threads can belong to another story, so its frames must match. + let mut shared = None; + if frames.len() > 1 { + h.charge_call(frames.len() as u64)?; + if let Some((f, l)) = + frames.iter().filter(|f| **f != anchor).find_map(|f| logs.get(&(st.uid, f.0)).filter(|l| current(l)).map(|l| (*f, l))) + && charged_frames(h, st, f)? == frames + { + shared = Some(l.index.clone()); } - l.doc = Arc::downgrade(&st.doc); - l.reverts = st.reverts; } - None => { - let frames = charged_frames(h, st, anchor)?; - let index = Rc::new(Index::new(story_text(st, &frames))); - logs.insert(key, Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, index, stamp: 0, floor: 0, edits: VecDeque::new() }); + let index = match shared { + Some(index) => index, + None => { + let text = story_text(st, &frames); + match logs.get(&key) { + Some(l) if l.reverts == st.reverts && l.index.text == text => l.index.clone(), + _ => Rc::new(Index::new(text)), + } + } + }; + match logs.get_mut(&key) { + Some(l) => { + if l.reverts != st.reverts || index.text != l.index.text { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + } + l.index = index; + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + } + None => { + logs.insert(key, Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, index, stamp: 0, floor: 0, edits: VecDeque::new() }); + } } } let l = logs.get(&key).ok_or_else(|| HostError::Error(STALE_STORY.into()))?; @@ -691,6 +713,20 @@ fn range_later(link: &Link, name: &'static str) -> (String, HostMember) { (name.to_string(), HostMember::Property { get: f.clone(), set: f }) } +/// A member of `Story` that is not available yet: reading or assigning it throws, after the check +/// that the story is still there. +fn story_later(link: &Link, name: &'static str) -> (String, HostMember) { + let message = format!("Story.{name} is not available yet"); + let l = link.clone(); + let f: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + this_story(&h, &a)?; + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Property { get: f.clone(), set: f }) +} + /// The members of `TextFrame` this module adds. pub(super) fn frame_members(l: &Link) -> Vec<(String, HostMember)> { named(vec![ @@ -717,7 +753,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("words", get(l, story_words)), ("paragraphs", get(l, story_paragraphs)), ]); - story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| later(l, "Story", m))); + story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| story_later(l, m))); let mut range = named(vec![ ("typename", get(l, span_typename)), ("parent", get(l, span_story)), diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs index 6d919a21d9..433cc041e7 100644 --- a/crates/engine/src/tests/script_threads.rs +++ b/crates/engine/src/tests/script_threads.rs @@ -440,10 +440,16 @@ fn a_frame_of_another_document_cannot_be_linked() { let before = state(&s, &ids); s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); area(&mut s, 10.0, 100.0, 40.0, "Elsewhere"); + s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 80, "height": 60})).unwrap(); let m = failure(&mut s, "app.documents[0].textFrames[2].nextFrame = app.documents[1].textFrames[0];"); assert!(m.contains("different documents"), "{m}"); - let m = failure(&mut s, "app.documents[1].textFrames.areaText(app.documents[1].pageItems[0], undefined, app.documents[0].textFrames[2]);"); - assert!(m.contains("another document") || m.contains("PathItem"), "{m}"); + let out = log( + &mut s, + "var d = app.documents[1], p = d.pageItems[1];\ + try { d.textFrames.areaText(p, undefined, app.documents[0].textFrames[2]); } catch (e) { vc.log(String(e.message)); }\ + vc.log(p.typename); vc.log(d.textFrames.length);", + ); + assert_eq!(out, vec![json!("baseFrame: the frame is in another document"), json!("PathItem"), json!(1)]); s.execute("document.activate", &json!({"index": 0})).unwrap(); unchanged(&s, &ids, &before); } @@ -453,6 +459,8 @@ fn a_deleted_frame_makes_its_story_and_links_stale() { let (mut s, _, _) = threaded(STORY); let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], st = f.story; f.remove(); st.length;"); assert!(m.contains("Stale story"), "{m}"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], st = f.story; f.remove(); st.lines;"); + assert!(m.contains("Stale story"), "{m}"); let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], g = app.activeDocument.textFrames[1]; g.remove(); f.nextFrame = g;"); assert!(m.contains("Stale page item"), "{m}"); let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], r = f.story.textRange; f.remove(); r.contents;"); @@ -520,6 +528,21 @@ fn a_thread_listing_a_frame_twice_is_walked_once() { assert!(threads(&s).is_empty()); } +/// When a frame is listed in two threads, a story read from a frame of the second thread reads +/// that thread's text, not the text of the story read before it from a shared frame. +#[test] +fn stories_of_threads_that_share_a_frame_keep_their_own_text() { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 120.0, 60.0, "One."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); + let c = area(&mut s, 300.0, 120.0, 60.0, "Three!"); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b], vec![b, c]]; + let out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[2].story.length);"); + let (ab, bc) = (story(&s, &[a, b]).encode_utf16().count(), story(&s, &[b, c]).encode_utf16().count()); + assert_ne!(ab, bc); + assert_eq!(out, vec![json!(ab), json!(bc)]); +} + /// A story and its range keep the exact id of the frame they were read from, also past 2^53. #[test] fn a_story_read_from_a_frame_with_a_large_id_stays_with_that_frame() { diff --git a/docs/mcp.md b/docs/mcp.md index 99d79dd67c..5db12d3918 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2692,8 +2692,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` - value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not - available yet. A `TextFrame` + value; a `startTValue` or `endTValue` that is given throws an error that says it is not available yet, and + `baseFrame` and `postFix` thread the new frame as the threaded-type paragraph below describes. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..ab191ea587 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and styles and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 355a11543a..17698d2eb6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. From cf068877825dc36c77fe28f56435202b7ab559d2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:13:38 -0800 Subject: [PATCH 20/91] Plug-ins: importers at API level 4 open type, embedded images, layers and artboards An importer whose manifest sets `api` 4 and lists `outputKinds` (any of type, image, layer and artboard) may return point type (text, font family and style, size, fill, transform), embedded RGBA images stored as PNG, top-level layers with their names, visibility, lock and objects, and named artboards that replace the one around the art. Output of a kind the manifest doesn't list is refused naming the kind. The host checks the whole output before it makes the document: limits on layers (256), artboards (100), names (256 characters, no control or text direction characters), text (1 MiB a type object, 16 MiB in all) and pixels (16,384 a side, 32 MiB of RGBA in all, checked from the sizes given before any base64 is decoded), and an image whose bytes aren't 4 x width x height. One bad entry opens nothing and leaves the open document as it was. Importers below level 4 read paths alone, as before. The host's plug-in API level goes to 4. Docs: docs/plugins.md, docs/gaps.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/importer.rs | 166 ++++++- crates/engine/src/cmd/plugin.rs | 3 + crates/engine/tests/plugin_import.rs | 143 ++++++ crates/plugins/src/import.rs | 590 ++++++++++++++++++++++- crates/plugins/src/lib.rs | 5 +- crates/plugins/src/manifest.rs | 126 ++++- crates/plugins/src/objects.rs | 21 +- crates/plugins/src/permissions.rs | 8 +- crates/ui-egui/src/dialogs/tests.rs | 1 + crates/ui-egui/src/i18n/ca.tsv | 21 + crates/ui-egui/src/i18n/cs.tsv | 21 + crates/ui-egui/src/i18n/da.tsv | 21 + crates/ui-egui/src/i18n/de.tsv | 21 + crates/ui-egui/src/i18n/el.tsv | 21 + crates/ui-egui/src/i18n/es.tsv | 21 + crates/ui-egui/src/i18n/fi.tsv | 21 + crates/ui-egui/src/i18n/fr.tsv | 21 + crates/ui-egui/src/i18n/hi.tsv | 21 + crates/ui-egui/src/i18n/hu.tsv | 21 + crates/ui-egui/src/i18n/id.tsv | 21 + crates/ui-egui/src/i18n/it.tsv | 21 + crates/ui-egui/src/i18n/ja.tsv | 21 + crates/ui-egui/src/i18n/ka.tsv | 21 + crates/ui-egui/src/i18n/ko.tsv | 21 + crates/ui-egui/src/i18n/nl.tsv | 21 + crates/ui-egui/src/i18n/pl.tsv | 21 + crates/ui-egui/src/i18n/pt-br.tsv | 21 + crates/ui-egui/src/i18n/ru.tsv | 21 + crates/ui-egui/src/i18n/sv.tsv | 21 + crates/ui-egui/src/i18n/tr.tsv | 21 + crates/ui-egui/src/i18n/uk.tsv | 21 + crates/ui-egui/src/i18n/vi.tsv | 21 + crates/ui-egui/src/i18n/zh-hans.tsv | 21 + crates/ui-egui/src/i18n/zh-hant.tsv | 21 + docs/gaps.md | 3 + docs/plugins.md | 67 ++- docs/target-app-parity.md | 1 + 37 files changed, 1614 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index 3ba6c6fa19..811043fa57 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -10,12 +10,16 @@ //! named by `path` that only an importer can read is read no further than that. Its objects become //! a new document whose artboard is their bounds, and nothing opens when the importer fails, //! declines, is cancelled or returns objects that don't pass the checks a filter's output does. +//! An importer at plug-in API level 4 may also return point type, embedded images, top-level +//! layers and artboards (its manifest's `outputKinds`): the artboards it returns replace the one +//! around the art. use std::sync::Arc; use serde_json::Value; -use vectorcraft_doc::{Document, MAX_COORD}; -use vectorcraft_geom::Rect; +use vectorcraft_doc::{CharStyle, Document, ImageObject, LAYER_COLORS, LayerColor, MAX_COORD, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_plugins::import::ImportObject; use vectorcraft_plugins::{Plugin, export, import, objects}; use super::super::{Result, bad, str_param}; @@ -135,22 +139,152 @@ pub(super) fn load(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value) -> Resu let mut doc = Document::new(1.0, 1.0); let layer = doc.layers.first().map(|l| l.id); let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(C, fx, n); - let ids = - objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?; - if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) { - board.rect = artboard_rect(bounds); + let open_err = |e: vectorcraft_plugins::Error| err(format!("can't open `{}`: {e}", file_name(name))); + let mut warnings = Vec::new(); + let (ids, artboards) = if imported.paths_only() { + let paths = imported.objects.into_iter().filter_map(|o| if let ImportObject::Path(o) = o { Some(o) } else { None }).collect(); + (objects::apply_output(&mut doc, &[], paths, layer, &admit).map_err(open_err)?, Vec::new()) + } else { + let ids = build(&mut doc, imported.objects, imported.layers, &admit, &mut warnings) + .map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?; + (ids, imported.artboards) + }; + if artboards.is_empty() { + if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) { + board.rect = artboard_rect(bounds); + } + } else { + set_artboards(&mut doc, artboards); } doc.title = file_name(name); - Ok(Loaded { - doc, - format, - warnings: imported.warnings, - restored: false, - converted: false, - preview_only: false, - editing_data: false, - native_pdf_compatible: None, - }) + warnings.splice(0..0, imported.warnings); + Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None }) +} + +/// Puts `objects`, what an importer at plug-in API level 4 returned, into `doc`, a new document of +/// one layer: in `layers`, bottom first, each holding the objects it lists in their order, or all in +/// that one layer when there are none. Paths are made as a filter's new ones are (their effects let +/// in by `admit`), type is laid out, and each image is stored in the document as a PNG of its +/// pixels. A warning for type whose font isn't there, or doesn't have its style, goes to `warnings`. +/// Returns the objects' ids in order. +fn build( + doc: &mut Document, + objects: Vec, + layers: Vec, + admit: objects::AdmitEffects, + warnings: &mut Vec, +) -> std::result::Result, String> { + let count = objects.len(); + let first = doc.layers.first().map(|l| (**l).clone()); + let first = first.unwrap_or_else(|| Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0))); + let mut owner = vec![0usize; count]; + for (li, l) in layers.iter().enumerate() { + for &k in &l.objects { + if let Some(o) = owner.get_mut(k) { + *o = li; + } + } + } + let mut members: Vec>> = vec![Vec::new(); layers.len().max(1)]; + let mut ids = Vec::with_capacity(count); + let mut fonts = std::collections::BTreeSet::new(); + for (i, o) in objects.into_iter().enumerate() { + let at = format!("objects[{i}]"); + let node = match o { + ImportObject::Path(o) => objects::new_object(doc, o, &at, admit).map_err(|e| e.to_string())?, + ImportObject::Type(t) => { + let node = type_node(doc, t); + if let NodeKind::Text(t) = &node.kind { + fonts.extend(t.runs.iter().flat_map(crate::cmd::fonts::run_fonts)); + } + node + } + ImportObject::Image(im) => image_node(doc, im).map_err(|e| e.to_string())?, + }; + ids.push(node.id); + if let Some(list) = owner.get(i).and_then(|&li| members.get_mut(li)) { + list.push(Arc::new(node)); + } + } + let built: Vec> = if layers.is_empty() { + let mut layer = first; + if let Some(children) = layer.children_mut() { + *children = members.into_iter().next().unwrap_or_default(); + } + vec![Arc::new(layer)] + } else { + layers + .into_iter() + .zip(members) + .enumerate() + .map(|(li, (l, children))| { + let mut layer = Node::layer(doc.alloc_id(), &l.name, LayerColor::Preset((li % LAYER_COLORS.len()) as u8)); + layer.visible = l.visible; + layer.locked = l.locked; + if let Some(c) = layer.children_mut() { + *c = children; + } + Arc::new(layer) + }) + .collect() + }; + doc.layers = built; + warnings.extend(crate::cmd::fonts::set_font_warning(fonts)); + Ok(ids) +} + +/// Point type `t` as a new node of `doc`, in [Normal Character Style] with the face, size and fill +/// `t` gives, laid out. +fn type_node(doc: &mut Document, t: import::OutType) -> Node { + let mut style = crate::cmd::textstyles::normal_char_style(doc); + style.font_version = None; + style.font_axes.clear(); + style.font_family = t.font_family; + match t.font_style { + Some(s) => style.font_style = s, + None => { + style.font_style = CharStyle::default().font_style; + crate::cmd::textedit::fit_font_style(&mut style); + } + } + style.size = t.font_size; + if let Some(fill) = t.fill { + style.fill = fill; + } + let mut text = TextObject::point(Point::ZERO, &t.text, style); + text.xf = t.transform; + text.para = crate::cmd::create::new_type_para(); + text.system_layout = doc.setup.system_layout; + crate::cmd::typecmd::refresh_bounds(&mut text); + let mut n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(text))); + n.name = t.name; + n +} + +/// Image `im` as a new node of `doc`, its pixels stored in `doc` as a PNG. +fn image_node(doc: &mut Document, im: import::OutImage) -> Result { + let pixels = image::RgbaImage::from_raw(im.width, im.height, im.rgba).ok_or_else(|| err("the image's pixels don't match its size"))?; + let stored = super::load::as_png(pixels, None, None)?; + let image = ImageObject { + key: stored.key.clone(), + width: stored.width, + height: stored.height, + xf: im.transform, + link: None, + placement: Default::default(), + pixels: None, + }; + doc.images.insert(stored.key, stored.blob); + let mut n = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(image))); + n.name = im.name; + Ok(n) +} + +/// Gives `doc` the artboards `boards` an importer returned, in order, in place of its one. +fn set_artboards(doc: &mut Document, boards: Vec) { + let Some(template) = doc.artboards.first().cloned() else { return }; + doc.artboards = + boards.into_iter().zip(1u32..).map(|(b, id)| vectorcraft_doc::Artboard { id, name: b.name, rect: b.rect, ..template.clone() }).collect(); } /// The artboard of art with bounds `r`: `r` within ±[`MAX_COORD`], at least 1 pt wide and high diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..f27409908f 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -101,6 +101,9 @@ pub fn describe(p: &Plugin) -> Value { if !m.inputs.is_empty() { v["inputs"] = json!(m.inputs); } + if !m.output_kinds.is_empty() { + v["outputKinds"] = json!(m.output_kinds); + } if m.paint_output { v["paintOutput"] = json!(true); } diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index 9bf9b87f0d..c8c740af8b 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -441,3 +441,146 @@ fn a_built_in_file_past_the_input_limit_still_opens() { assert_eq!(s.execute("document.open", &encoded).unwrap()["format"], "png"); let _ = std::fs::remove_dir_all(&dir); } + +/// An importer at plug-in API level 4 `id` reading `.trc` files, listing `kinds` (a JSON list) in +/// `outputKinds`, whose output is the file it is given. +fn rich_echo(s: &mut Session, id: &str, kinds: &str) -> Value { + let manifest = + format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"importer","api":4,"extensions":["trc"],"outputKinds":{kinds}}}"#); + install(s, &tpl::module(&manifest, tpl::ECHO, "", 1)) +} + +/// The pixels of a 2 × 1 image: opaque red, then half-transparent blue. +const PIXELS: [u8; 8] = [255, 0, 0, 255, 0, 0, 255, 128]; + +/// Rich importer output: type, the image of [`PIXELS`] and the rectangle of [`RECT`], with two +/// layers (the image and the rectangle in "Art", the type in the hidden, locked "Words") and two +/// artboards. +fn rich_output() -> Value { + let rect: Value = serde_json::from_str(RECT).unwrap(); + json!({ + "objects": [ + {"type": "type", "text": "Hello\nWorld", "fontFamily": "No Such Family Q9617", "fontSize": 24, + "fill": {"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}, "transform": [1, 0, 0, 1, 10, 40], "name": "Title"}, + {"type": "image", "pixelSize": [2, 1], "pixelsBase64": vectorcraft_format::base64_encode(&PIXELS), "transform": [10, 0, 0, 10, 0, 100]}, + rect["objects"][0], + ], + "layers": [{"name": "Art", "objects": [1, 2]}, {"name": "Words", "visible": false, "locked": true, "objects": [0]}], + "artboards": [{"name": "Front", "rect": [0, 0, 200, 100]}, {"name": "Back", "rect": [220, 0, 200, 100]}], + "warnings": ["from the importer"], + }) +} + +/// The active document's layers (name, shown, locked, kinds of its objects), its artboards (name +/// and rectangle), its type (text, family, size, fill) and the RGBA of its first image. +#[allow(clippy::type_complexity)] +fn structure(s: &Session) -> (Vec<(String, bool, bool, Vec<&'static str>)>, Vec<(String, [f64; 4])>, Vec<(String, String, f64, String)>, Vec) { + let d = &s.doc().unwrap().doc; + let kind = |n: &vectorcraft_doc::Node| match &n.kind { + vectorcraft_doc::NodeKind::Text(_) => "type", + vectorcraft_doc::NodeKind::Image(_) => "image", + vectorcraft_doc::NodeKind::Path { .. } => "path", + _ => "other", + }; + let layers = d + .layers + .iter() + .map(|l| (l.name.clone().unwrap_or_default(), l.visible, l.locked, l.children().unwrap().iter().map(|c| kind(c)).collect())) + .collect(); + let boards = d.artboards.iter().map(|a| (a.name.clone(), [a.rect.x0, a.rect.y0, a.rect.x1, a.rect.y1])).collect(); + let (mut types, mut pixels) = (Vec::new(), Vec::new()); + d.walk(|n| match &n.kind { + vectorcraft_doc::NodeKind::Text(t) => { + let st = &t.runs[0].style; + let text: String = t.runs.iter().map(|r| r.text.as_str()).collect(); + types.push((text, st.font_family.clone(), st.size, serde_json::to_string(&st.fill).unwrap())); + } + vectorcraft_doc::NodeKind::Image(_) if pixels.is_empty() => { + // Read back through the filter input's own decoder, not the importer's. + let o = vectorcraft_plugins::objects::encode_read_only(d, n).unwrap(); + pixels = vectorcraft_format::base64_decode(o["pixelsBase64"].as_str().unwrap()).unwrap(); + } + _ => {} + }); + (layers, boards, types, pixels) +} + +/// An importer at API level 4 that lists every output kind opens editable type, an embedded image, +/// paths, layers and artboards as it returned them; the artboards replace the one around the art, +/// a missing font is reported with the importer's warnings, and the document saves and opens again +/// in the native format with all of it. +#[test] +fn an_api_4_importer_opens_type_images_layers_and_artboards() { + let mut s = Session::new(); + let entry = rich_echo(&mut s, "test.rich", r#"["type","image","layer","artboard"]"#); + assert_eq!((&entry["api"], &entry["outputKinds"]), (&json!(4), &json!(["type", "image", "layer", "artboard"]))); + assert_eq!(entry["permissions"], json!(["import.read"])); + let r = open(&mut s, "Rich.trc", rich_output().to_string().as_bytes(), json!({})).unwrap(); + let warnings = r["warnings"].as_array().unwrap(); + assert_eq!(warnings.first(), Some(&json!("from the importer"))); + assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("No Such Family Q9617")), "{warnings:?}"); + let opened = structure(&s); + let blue = serde_json::to_string(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))).unwrap(); + assert_eq!(opened.0, [("Art".to_string(), true, false, vec!["image", "path"]), ("Words".to_string(), false, true, vec!["type"])]); + assert_eq!(opened.1, [("Front".to_string(), [0.0, 0.0, 200.0, 100.0]), ("Back".to_string(), [220.0, 0.0, 420.0, 100.0])]); + assert_eq!(opened.2, [("Hello\nWorld".to_string(), "No Such Family Q9617".to_string(), 24.0, blue)]); + assert_eq!(opened.3, PIXELS); + // The type is laid out at the place the transform gives: its first baseline starts at (10, 40). + let d = &s.doc().unwrap().doc; + let words = d.layers[1].children().unwrap()[0].clone(); + let b = d.bounds_of(&[words.id], false).unwrap(); + assert!(b.x0 >= 9.0 && b.x0 < 12.0 && b.y0 < 40.0 && b.y1 > 40.0, "{b:?}"); + + let native = fileio::encode(&s.doc().unwrap().doc, "vectorcraft", &json!({})).unwrap(); + open(&mut s, "Again.vectorcraft", &native, json!({})).unwrap(); + assert_eq!(structure(&s), opened, "saved and opened again"); +} + +/// An importer at API level 4 that lists only some kinds: output with another kind, a malformed +/// image or a bad layer opens nothing and leaves the open document as it was; a blank document of +/// artboards alone opens. +#[test] +fn rich_output_that_fails_its_checks_changes_nothing() { + let mut s = Session::new(); + rich_echo(&mut s, "test.richsome", r#"["type","image","layer"]"#); + let before = open_edited(&mut s, "test.richsome.edited"); + let mut short = rich_output(); + short["objects"][1]["pixelsBase64"] = json!(vectorcraft_format::base64_encode(&PIXELS[..4])); + let mut twice = rich_output(); + twice["layers"][1]["objects"] = json!([0, 2]); + let cases = [ + (rich_output(), "`artboard`"), + (short, "= 8 bytes"), + (twice, "exactly one layer"), + (json!({"objects": [], "layers": [{"name": "A\u{202E}B"}]}), "text direction"), + ]; + for (mut output, says) in cases { + if says != "`artboard`" { + output.as_object_mut().unwrap().remove("artboards"); + } + let e = open(&mut s, "x.trc", output.to_string().as_bytes(), json!({"importer": "plugin.test.richsome"})).unwrap_err(); + assert!(e.to_string().contains(says) && e.to_string().contains("x.trc"), "{says}: {e}"); + assert_eq!(state(&mut s), before, "{says}"); + } + rich_echo(&mut s, "test.richboards", r#"["artboard"]"#); + let blank = json!({"objects": [], "artboards": [{"name": "Only", "rect": [0, 0, 50, 60]}]}); + open(&mut s, "Blank.trc", blank.to_string().as_bytes(), json!({"importer": "plugin.test.richboards"})).unwrap(); + let (layers, boards, types, _) = structure(&s); + assert_eq!((layers.len(), layers[0].3.len(), boards, types.len()), (1, 0, vec![("Only".to_string(), [0.0, 0.0, 50.0, 60.0])], 0)); +} + +/// An importer below API level 4 reads paths alone, as it always has: type is not a path, and it +/// can't return layers. +#[test] +fn an_older_importer_reads_paths_alone() { + let mut s = Session::new(); + echo(&mut s, "test.older", r#"["tol"]"#); + let e = open(&mut s, "x.tol", rich_output().to_string().as_bytes(), json!({})).unwrap_err(); + assert!(e.to_string().contains("an importer returns `objects` and `warnings`, not `"), "{e}"); + let typed = json!({"objects": [rich_output()["objects"][0]]}); + let e = open(&mut s, "x.tol", typed.to_string().as_bytes(), json!({})).unwrap_err(); + assert!(e.to_string().contains("`type` must be \"path\" or \"compound\""), "{e}"); + assert!(s.documents().is_empty()); + open(&mut s, "Shapes.tol", RECT.as_bytes(), json!({})).unwrap(); + assert_eq!((objects(&s), artboard(&s), s.doc().unwrap().doc.layers.len()), (1, (10.0, 20.0, 110.0, 70.0), 1)); +} diff --git a/crates/plugins/src/import.rs b/crates/plugins/src/import.rs index 599470e0aa..838022ea1f 100644 --- a/crates/plugins/src/import.rs +++ b/crates/plugins/src/import.rs @@ -10,6 +10,8 @@ //! The host hands the importer the file's bytes as they are, at most [`MAX_INPUT_BYTES`] of them, //! and reads back the objects of the new document in the same form filters return them //! ([`crate::objects`]): `{"objects": [...], "warnings"?: ["…"]}`, or `{"error": "…"}` to decline. +//! An importer at plug-in API level 4 whose manifest lists `outputKinds` may also return point type +//! and embedded images in `objects`, and `layers` and `artboards` ([`decode_with`]). //! An import is one run the user asked for, so it gets an export's budget ([`crate::export::FUEL`] //! and [`crate::export::WALL_TIME_MS`]), and Cancel stops it between two slices of the budget //! ([`Error::Cancelled`]). @@ -17,9 +19,11 @@ use std::sync::Arc; use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_geom::{Affine, Rect}; -use crate::objects::{OutObject, declined, printable}; -use crate::{Error, Kind, Limits, Plugin, Result, registry}; +use crate::objects::{MAX_COORD, MAX_OBJECTS, OutObject, declined, out_err, printable}; +use crate::{Error, Kind, Limits, OutputKind, Plugin, Result, registry}; /// The largest file an importer is given, in bytes: 128 MiB, a quarter of a plug-in's memory /// limit, so the file and the objects made from it fit beside each other. @@ -64,13 +68,109 @@ pub fn for_extension(ext: &str) -> Vec> { /// What an importer returned. #[derive(Clone, Debug, PartialEq)] pub struct Imported { - /// The objects of the new document, in paint order (bottom first), checked as a filter's are. - pub objects: Vec, + /// The objects of the new document, in paint order (bottom first): paths and compound paths + /// checked as a filter's are, and type and images when the importer lists them in `outputKinds`. + pub objects: Vec, + /// The top-level layers, bottom first, each holding the objects it lists (`layers`, with + /// `outputKinds` `layer`); empty: every object goes in one layer. + pub layers: Vec, + /// The artboards (`artboards`, with `outputKinds` `artboard`); empty: one artboard around the art. + pub artboards: Vec, /// What the import left out or changed, for the user (at most /// [`crate::export::MAX_WARNINGS`]). pub warnings: Vec, } +impl Imported { + /// Whether it holds paths and compound paths alone, as an importer below API level 4 returns. + pub fn paths_only(&self) -> bool { + self.layers.is_empty() && self.artboards.is_empty() && self.objects.iter().all(|o| matches!(o, ImportObject::Path(_))) + } +} + +/// One object of an import. +#[derive(Clone, Debug, PartialEq)] +pub enum ImportObject { + /// A path or a compound path (`"type": "path"` or `"compound"`, or no `type`). + Path(OutObject), + /// Point type (`"type": "type"`). + Type(OutType), + /// An embedded image (`"type": "image"`). + Image(OutImage), +} + +/// Point type an importer returned: `{"type": "type", text, fontFamily, fontStyle?, fontSize, +/// fill?, transform?, name?}`. +#[derive(Clone, Debug, PartialEq)] +pub struct OutType { + /// Its text, a line break (`\n`) between two paragraphs. + pub text: String, + pub font_family: String, + /// `None`: the family's regular style. + pub font_style: Option, + /// In points, from [`TYPE_SIZES`]`.0` to [`TYPE_SIZES`]`.1`. + pub font_size: f64, + /// `None`: the default fill (black). + pub fill: Option, + /// Maps the type's own space (the first baseline starts at its origin) into the document. + pub transform: Affine, + pub name: Option, +} + +/// An embedded image an importer returned: `{"type": "image", pixelSize: [w, h], pixelsBase64, +/// transform?, name?}`. +#[derive(Clone, Debug, PartialEq)] +pub struct OutImage { + pub width: u32, + pub height: u32, + /// Straight RGBA, 8 bits a channel, row by row from the top: `4 × width × height` bytes. + pub rgba: Vec, + /// Maps pixel space (one unit a pixel, y down) into the document. + pub transform: Affine, + pub name: Option, +} + +/// A top-level layer an importer returned: `{name, visible?, locked?, objects: [index…]}`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OutLayer { + pub name: String, + pub visible: bool, + pub locked: bool, + /// Indexes into [`Imported::objects`], increasing: the layer's objects in paint order. + pub objects: Vec, +} + +/// An artboard an importer returned: `{name, rect: [x, y, width, height]}`. +#[derive(Clone, Debug, PartialEq)] +pub struct OutArtboard { + pub name: String, + pub rect: Rect, +} + +/// Most layers an import may return. +pub const MAX_LAYERS: usize = 256; + +/// Most artboards an import may return. +pub const MAX_ARTBOARDS: usize = 100; + +/// Longest layer, artboard, object or font name an import may return, in characters. +pub const MAX_NAME_CHARS: usize = 256; + +/// Most bytes of UTF-8 text one type object may hold. +pub const MAX_TYPE_TEXT: usize = 1 << 20; + +/// Most bytes of UTF-8 text all the type of one import may hold. +pub const MAX_TEXT_TOTAL: usize = 16 << 20; + +/// Most pixels an image may have along either side. +pub const MAX_IMAGE_SIDE: u64 = 16_384; + +/// Most bytes of RGBA all the images of one import may hold. +pub const MAX_PIXEL_BYTES: u64 = 32 << 20; + +/// The type sizes an import may give, in points (those Character panel sizes take). +pub const TYPE_SIZES: (f64, f64) = (0.1, 1296.0); + /// The file an import reads, as the importer is told in `_context`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Source<'a> { @@ -103,23 +203,57 @@ pub fn run(plugin: &Plugin, file: &[u8], params: &Value, source: Source) -> Resu let mut params = Value::Object(m.resolve_params(params)?); params["_context"] = json!({"mode": "import", "extension": source.extension, "name": source.name}); let params = serde_json::to_vec(¶ms).map_err(|e| Error::Params(e.to_string()))?; - decode(&plugin.run_limited(file, ¶ms, &limits(plugin))?) + decode_with(&plugin.run_limited(file, ¶ms, &limits(plugin))?, &m.output_kinds()) } /// An importer's output: `{"objects": [...], "warnings"?: ["…"]}`, or `{"error": "…"}` to decline /// with a message for the user. The objects are new ones (no `id`), checked as a filter's are; an /// output without any, or with keys of its own, is refused. pub fn decode(bytes: &[u8]) -> Result { + decode_with(bytes, &[]) +} + +/// [`decode`] for an importer whose manifest lists `kinds` (`outputKinds`): `objects` may also +/// hold type and images, and the output `layers` and `artboards`, of the kinds listed. Content of +/// a kind not listed is refused naming the kind. Everything is checked before anything is returned, +/// against the limits of this module, and one bad entry refuses the whole output. With `kinds` +/// listing layers or artboards, an output of no objects is an empty document when it has any. +pub fn decode_with(bytes: &[u8], kinds: &[OutputKind]) -> Result { let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?; if let Some(e) = declined(&v) { return Err(e); } - if let Some(key) = v.as_object().and_then(|o| o.keys().find(|k| !OUTPUT_KEYS.contains(&k.as_str()))) { - let key = printable(&json!(key), 64); - return Err(Error::Output(format!("an importer returns `objects` and `warnings`, not `{key}`"))); + for key in v.as_object().into_iter().flat_map(|o| o.keys()).filter(|k| !OUTPUT_KEYS.contains(&k.as_str())) { + let rich = match key.as_str() { + "layers" => Some(OutputKind::Layer), + "artboards" => Some(OutputKind::Artboard), + _ => None, + }; + match rich { + Some(kind) if kinds.contains(&kind) => {} + Some(kind) if !kinds.is_empty() => return Err(undeclared(kind)), + _ => { + let key = printable(&json!(key), 64); + return Err(Error::Output(format!("an importer returns `objects` and `warnings`, not `{key}`"))); + } + } } - let objects = crate::objects::decode(bytes)?; - if objects.is_empty() { + let (objects, layers, artboards) = if kinds.is_empty() { + let objects = crate::objects::decode(bytes)?; + (objects.into_iter().map(ImportObject::Path).collect::>(), Vec::new(), Vec::new()) + } else { + let objects = rich_objects(&v, kinds)?; + let layers = match v.get("layers") { + None => Vec::new(), + Some(l) => decode_layers(l, objects.len())?, + }; + let artboards = match v.get("artboards") { + None => Vec::new(), + Some(a) => decode_artboards(a)?, + }; + (objects, layers, artboards) + }; + if objects.is_empty() && layers.is_empty() && artboards.is_empty() { return Err(Error::Output("the importer returned no objects".into())); } let warnings = match v.get("warnings") { @@ -127,7 +261,298 @@ pub fn decode(bytes: &[u8]) -> Result { Some(Value::Array(w)) => w.iter().take(crate::export::MAX_WARNINGS).map(|w| printable(w, crate::export::MAX_WARNING_CHARS)).collect(), Some(_) => return Err(Error::Output("`warnings` must be a list of strings".into())), }; - Ok(Imported { objects, warnings }) + Ok(Imported { objects, layers, artboards, warnings }) +} + +/// The error of output holding content of `kind`, which the importer's `outputKinds` doesn't list. +fn undeclared(kind: OutputKind) -> Error { + let kind = kind.name(); + Error::Output(format!("the output holds `{kind}`, which the importer's `outputKinds` doesn't list")) +} + +/// The keys a type object may have. +const TYPE_KEYS: &[&str] = &["type", "text", "fontFamily", "fontStyle", "fontSize", "fill", "transform", "name"]; + +/// The keys an image object may have. +const IMAGE_KEYS: &[&str] = &["type", "pixelSize", "pixelsBase64", "transform", "name"]; + +/// The keys a layer may have. +const LAYER_KEYS: &[&str] = &["name", "visible", "locked", "objects"]; + +/// The keys an artboard may have. +const ARTBOARD_KEYS: &[&str] = &["name", "rect"]; + +/// The objects of output `v` of an importer listing `kinds`: paths and compound paths as a +/// filter's, type and images of the kinds listed. +fn rich_objects(v: &Value, kinds: &[OutputKind]) -> Result> { + let objects = v.get("objects").and_then(Value::as_array).ok_or_else(|| Error::Output("expected {\"objects\": [...]}".into()))?; + if objects.len() > MAX_OBJECTS { + return Err(Error::Output(format!("{} objects (limit {MAX_OBJECTS})", objects.len()))); + } + let kind_of = |o: &Value| match o.get("type").and_then(Value::as_str) { + Some("type") => Some(OutputKind::Type), + Some("image") => Some(OutputKind::Image), + _ => None, + }; + if let Some(kind) = objects.iter().filter_map(kind_of).find(|k| !kinds.contains(k)) { + return Err(undeclared(kind)); + } + check_totals(objects)?; + let mut anchors = 0; + objects + .iter() + .enumerate() + .map(|(i, o)| { + let at = format!("objects[{i}]"); + match kind_of(o) { + Some(OutputKind::Type) => decode_type(o, &at).map(ImportObject::Type), + Some(_) => decode_image(o, &at).map(ImportObject::Image), + None => crate::objects::decode_object(o, &at, &mut anchors).map(ImportObject::Path), + } + }) + .collect() +} + +/// Refuses `objects` whose type, all together, holds more than [`MAX_TEXT_TOTAL`] bytes of text, or +/// whose images, by the sizes they give, more than [`MAX_PIXEL_BYTES`] bytes of pixels, before any +/// object is read further or any pixels are decoded. +fn check_totals(objects: &[Value]) -> Result<()> { + let (mut text, mut pixel_bytes) = (0usize, 0u64); + for (i, o) in objects.iter().enumerate() { + let at = format!("objects[{i}]"); + match o.get("type").and_then(Value::as_str) { + Some("type") => { + text = text.saturating_add(o.get("text").and_then(Value::as_str).map_or(0, str::len)); + if text > MAX_TEXT_TOTAL { + return Err(out_err(&at, format!("the type holds more than {MAX_TEXT_TOTAL} bytes of text"))); + } + } + Some("image") => { + let side = |k: usize| o.get("pixelSize").and_then(|s| s.get(k)).and_then(Value::as_u64).unwrap_or(0); + let (w, h) = (side(0), side(1)); + if w > MAX_IMAGE_SIDE || h > MAX_IMAGE_SIDE { + return Err(out_err(&at, format!("{w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side)"))); + } + pixel_bytes = pixel_bytes.saturating_add(w.saturating_mul(h).saturating_mul(4)); + if pixel_bytes > MAX_PIXEL_BYTES { + return Err(out_err(&at, format!("the images hold more than {MAX_PIXEL_BYTES} bytes of pixels"))); + } + } + _ => {} + } + } + Ok(()) +} + +/// Refuses a key of JSON object `o` that isn't one of `keys`. +fn known_keys(o: &serde_json::Map, keys: &[&str], at: &str) -> Result<()> { + match o.keys().find(|k| !keys.contains(&k.as_str())) { + Some(key) => { + let key = printable(&json!(key), 64); + Err(out_err(at, format!("unknown field `{key}`"))) + } + None => Ok(()), + } +} + +/// Is `c` a character that changes the direction text is laid out in (an embedding, override, +/// isolate or mark)? +fn is_direction_mark(c: char) -> bool { + matches!(c, '\u{200E}' | '\u{200F}' | '\u{061C}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') +} + +/// The name `key` of `o` (`at` names it): 1 to [`MAX_NAME_CHARS`] characters, none of them a +/// control character or a direction mark, and not only spaces. `None` when it is left out and not +/// `required`. +fn name(o: &serde_json::Map, key: &str, required: bool, at: &str) -> Result> { + let v = match o.get(key) { + None | Some(Value::Null) if required => return Err(out_err(at, format!("missing field `{key}`"))), + None | Some(Value::Null) => return Ok(None), + Some(v) => v, + }; + let s = v.as_str().ok_or_else(|| out_err(at, format!("`{key}` must be a string")))?; + let count = s.chars().count(); + if count == 0 || count > MAX_NAME_CHARS || s.trim().is_empty() || s.chars().any(|c| c.is_control() || is_direction_mark(c)) { + return Err(out_err(at, format!("`{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters"))); + } + Ok(Some(s.to_string())) +} + +/// The affine `key` of `o` (`at` names it): six finite numbers within ±[`MAX_COORD`] that don't +/// flatten what it places. Left out, no change of place. +fn transform(o: &serde_json::Map, key: &str, at: &str) -> Result { + let Some(v) = o.get(key).filter(|v| !v.is_null()) else { return Ok(Affine::IDENTITY) }; + let wrong = || out_err(at, format!("`{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object")); + let list = v.as_array().filter(|a| a.len() == 6).ok_or_else(wrong)?; + let mut c = [0.0; 6]; + for (slot, n) in c.iter_mut().zip(list) { + *slot = n.as_f64().filter(|x| x.is_finite() && x.abs() <= MAX_COORD).ok_or_else(wrong)?; + } + let det = c[0] * c[3] - c[1] * c[2]; + if !det.is_normal() { + return Err(wrong()); + } + Ok(Affine::new(c)) +} + +/// A type object of the output (`at` names it). +fn decode_type(v: &Value, at: &str) -> Result { + let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?; + known_keys(o, TYPE_KEYS, at)?; + let text = match o.get("text") { + None | Some(Value::Null) => { + let key = "text"; + return Err(out_err(at, format!("missing field `{key}`"))); + } + Some(t) => t.as_str().ok_or_else(|| { + let key = "text"; + out_err(at, format!("`{key}` must be a string")) + })?, + }; + let len = text.len(); + if len > MAX_TYPE_TEXT { + return Err(out_err(at, format!("`text` is {len} bytes (limit {MAX_TYPE_TEXT})"))); + } + if text.chars().any(|c| c.is_control() && c != '\n' && c != '\t') { + return Err(out_err(at, "`text` must not hold control characters other than line breaks and tabs")); + } + let font_family = name(o, "fontFamily", true, at)?.unwrap_or_default(); + let font_style = name(o, "fontStyle", false, at)?; + let key = "fontSize"; + let font_size = match o.get(key) { + None | Some(Value::Null) => return Err(out_err(at, format!("missing field `{key}`"))), + Some(s) => s.as_f64().ok_or_else(|| out_err(at, format!("`{key}` must be a number")))?, + }; + let (min, max) = TYPE_SIZES; + if !(min..=max).contains(&font_size) { + let x = font_size; + return Err(out_err(at, format!("`{key}` must be between {min} and {max} (got {x})"))); + } + let fill = match o.get("fill") { + None => None, + Some(f) => { + let paint = crate::objects::decode_paint(f, &format!("{at}.fill"))?; + if matches!(paint, Paint::Pattern { .. }) { + return Err(out_err(at, "a type fill must be a color or a gradient")); + } + Some(crate::objects::unlinked(paint)) + } + }; + Ok(OutType { + text: text.to_string(), + font_family, + font_style, + font_size, + fill, + transform: transform(o, "transform", at)?, + name: name(o, "name", false, at)?, + }) +} + +/// An image object of the output (`at` names it). Its size has been checked against the limits +/// ([`check_totals`]), and its base64's length is checked against its size before anything is +/// decoded. +fn decode_image(v: &Value, at: &str) -> Result { + let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?; + known_keys(o, IMAGE_KEYS, at)?; + let size = o.get("pixelSize").and_then(Value::as_array).filter(|a| a.len() == 2).and_then(|a| { + let side = |v: &Value| v.as_u64().filter(|n| (1..=MAX_IMAGE_SIDE).contains(n)); + Some((side(a.first()?)?, side(a.get(1)?)?)) + }); + let (w, h) = size.ok_or_else(|| out_err(at, format!("`pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE}")))?; + let want = w * h * 4; + let wrong = || out_err(at, format!("`pixelsBase64` must hold 4 × width × height = {want} bytes as base64")); + let b64 = o.get("pixelsBase64").and_then(Value::as_str).ok_or_else(wrong)?; + // The length is checked first, so nothing of the wrong size is decoded. + if b64.len() as u64 != want.div_ceil(3) * 4 || craft_vectorcraft_format::base64::decoded_len(b64) != want { + return Err(wrong()); + } + let rgba = craft_vectorcraft_format::base64::decode(b64).filter(|p| p.len() as u64 == want).ok_or_else(wrong)?; + Ok(OutImage { width: w as u32, height: h as u32, rgba, transform: transform(o, "transform", at)?, name: name(o, "name", false, at)? }) +} + +/// The `layers` of the output, for `count` objects: 1 to [`MAX_LAYERS`] layers, bottom first, +/// each listing the indexes of its objects in increasing order, and every object in exactly one. +fn decode_layers(v: &Value, count: usize) -> Result> { + let key = "layers"; + let list = entries(v, key, MAX_LAYERS)?; + let mut owner: Vec = vec![false; count]; + let mut layers = Vec::with_capacity(list.len()); + for (i, l) in list.iter().enumerate() { + let at = format!("layers[{i}]"); + let o = l.as_object().ok_or_else(|| out_err(&at, format!("`{key}` must be an object")))?; + known_keys(o, LAYER_KEYS, &at)?; + let flag = |key: &str, default: bool| -> Result { + match o.get(key) { + None | Some(Value::Null) => Ok(default), + Some(v) => v.as_bool().ok_or_else(|| out_err(&at, format!("`{key}` must be true or false"))), + } + }; + let wrong = || out_err(&at, format!("`objects` must list object indexes in increasing order, each below {count}")); + let indexes = match o.get("objects") { + None | Some(Value::Null) => &[][..], + Some(v) => v.as_array().ok_or_else(wrong)?.as_slice(), + }; + let mut objects = Vec::with_capacity(indexes.len().min(count)); + for v in indexes { + let k = v.as_u64().and_then(|k| usize::try_from(k).ok()).filter(|k| *k < count).ok_or_else(wrong)?; + if objects.last().is_some_and(|last| *last >= k) { + return Err(wrong()); + } + if std::mem::replace(&mut owner[k], true) { + return Err(out_err(&at, format!("object {k} must be in exactly one layer"))); + } + objects.push(k); + } + layers.push(OutLayer { + name: name(o, "name", true, &at)?.unwrap_or_default(), + visible: flag("visible", true)?, + locked: flag("locked", false)?, + objects, + }); + } + if let Some(k) = owner.iter().position(|owned| !owned) { + return Err(out_err("layers", format!("object {k} must be in exactly one layer"))); + } + Ok(layers) +} + +/// The `artboards` of the output: 1 to [`MAX_ARTBOARDS`], each named once, their rectangles +/// within ±[`MAX_COORD`]. +fn decode_artboards(v: &Value) -> Result> { + let key = "artboards"; + let list = entries(v, key, MAX_ARTBOARDS)?; + let mut boards: Vec = Vec::with_capacity(list.len()); + for (i, a) in list.iter().enumerate() { + let at = format!("artboards[{i}]"); + let o = a.as_object().ok_or_else(|| out_err(&at, format!("`{key}` must be an object")))?; + known_keys(o, ARTBOARD_KEYS, &at)?; + let name = name(o, "name", true, &at)?.unwrap_or_default(); + if boards.iter().any(|b| b.name == name) { + let shown = printable(&json!(name), 64); + return Err(out_err(&at, format!("artboard name `{shown}` is used twice"))); + } + let wrong = || out_err(&at, format!("`rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0")); + let r = o.get("rect").and_then(Value::as_array).filter(|r| r.len() == 4).ok_or_else(wrong)?; + let n: Vec = r.iter().map(Value::as_f64).collect::>().ok_or_else(wrong)?; + let (x, y, w, h) = (n[0], n[1], n[2], n[3]); + let inside = |v: f64| v.is_finite() && v.abs() <= MAX_COORD; + if !(w > 0.0 && h > 0.0 && inside(x) && inside(y) && inside(x + w) && inside(y + h)) { + return Err(wrong()); + } + boards.push(OutArtboard { name, rect: Rect::new(x, y, x + w, y + h) }); + } + Ok(boards) +} + +/// The list `v`, the output's `key`, of 1 to `max` entries. +fn entries<'a>(v: &'a Value, key: &str, max: usize) -> Result<&'a Vec> { + let list = v.as_array().ok_or_else(|| Error::Output(format!("`{key}` must be an array")))?; + let n = list.len(); + if !(1..=max).contains(&n) { + return Err(Error::Output(format!("`{key}` must hold 1 to {max} entries (it holds {n})"))); + } + Ok(list) } #[cfg(test)] @@ -139,8 +564,9 @@ mod tests { #[test] fn output_is_the_objects_and_the_warnings_or_a_decline() { let out = decode(format!(r#"{{"objects":[{SQUARE}],"warnings":["a",2]}}"#).as_bytes()).unwrap(); + assert!(out.paths_only()); + assert!(out.objects.iter().all(|o| matches!(o, ImportObject::Path(o) if o.id.is_none() && o.path.is_some()))); assert_eq!((out.objects.len(), out.warnings), (1, vec!["a".to_string(), "2".to_string()])); - assert!(out.objects.iter().all(|o| o.id.is_none() && o.path.is_some())); assert_eq!(decode(format!(r#"{{"objects":[{SQUARE}]}}"#).as_bytes()).unwrap().warnings, Vec::::new()); assert_eq!(decode(br#"{"error": "Not a\nplot file."}"#), Err(Error::Failed("Not aplot file.".into()))); // A decline is reported as one, also with keys the host doesn't read beside it. @@ -171,6 +597,146 @@ mod tests { assert!(decode(warns.as_bytes()).unwrap_err().to_string().contains("`warnings`")); } + const ALL: &[OutputKind] = &OutputKind::ALL; + + /// A change made to [`rich`] output. + type Edit = Box; + + /// Type, an image of 2 × 1 pixels, the square, two layers and two artboards. + fn rich() -> Value { + let pixels = craft_vectorcraft_format::base64::encode(&[255, 0, 0, 255, 0, 0, 255, 128]); + json!({ + "objects": [ + {"type": "type", "text": "Hello\nWorld", "fontFamily": "Source Sans 3", "fontStyle": "Bold", "fontSize": 24, + "fill": {"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}, "transform": [1, 0, 0, 1, 10, 40], "name": "Title"}, + {"type": "image", "pixelSize": [2, 1], "pixelsBase64": pixels, "transform": [10, 0, 0, 10, 0, 100]}, + serde_json::from_str::(SQUARE).unwrap(), + ], + "layers": [{"name": "Art", "objects": [1, 2]}, {"name": "Words", "visible": false, "locked": true, "objects": [0]}], + "artboards": [{"name": "Front", "rect": [0, 0, 200, 100]}, {"name": "Back", "rect": [220, 0, 200, 100]}], + }) + } + + fn rich_with(edit: impl FnOnce(&mut Value)) -> Result { + let mut v = rich(); + edit(&mut v); + decode_with(v.to_string().as_bytes(), ALL) + } + + /// An importer listing every output kind returns type, an embedded image, paths, layers and + /// artboards, each read as it was given. + #[test] + fn each_output_kind_is_read_as_given() { + let out = decode_with(rich().to_string().as_bytes(), ALL).unwrap(); + assert!(!out.paths_only()); + let [ImportObject::Type(t), ImportObject::Image(im), ImportObject::Path(p)] = out.objects.as_slice() else { panic!("{:?}", out.objects) }; + assert_eq!( + (t.text.as_str(), t.font_family.as_str(), t.font_style.as_deref(), t.font_size), + ("Hello\nWorld", "Source Sans 3", Some("Bold"), 24.0) + ); + assert_eq!((t.transform, t.name.as_deref()), (Affine::translate((10.0, 40.0)), Some("Title"))); + assert!(matches!(t.fill, Some(Paint::Solid { .. }))); + assert_eq!((im.width, im.height, im.rgba.as_slice()), (2, 1, &[255, 0, 0, 255, 0, 0, 255, 128][..])); + assert!(p.path.is_some()); + let layers: Vec<_> = out.layers.iter().map(|l| (l.name.as_str(), l.visible, l.locked, l.objects.clone())).collect(); + assert_eq!(layers, [("Art", true, false, vec![1, 2]), ("Words", false, true, vec![0])]); + let boards: Vec<_> = out.artboards.iter().map(|a| (a.name.as_str(), a.rect)).collect(); + assert_eq!(boards, [("Front", Rect::new(0.0, 0.0, 200.0, 100.0)), ("Back", Rect::new(220.0, 0.0, 420.0, 100.0))]); + // Artboards alone are a blank document. + let blank = decode_with(br#"{"objects":[],"artboards":[{"name":"A","rect":[0,0,10,10]}]}"#, &[OutputKind::Artboard]).unwrap(); + assert_eq!((blank.objects.len(), blank.artboards.len()), (0, 1)); + } + + /// Output of a kind the manifest doesn't list is refused naming the kind; an importer listing + /// none reads paths alone, as before. + #[test] + fn a_kind_not_listed_is_refused_naming_it() { + let v = rich().to_string(); + for (kinds, named) in [ + (&[OutputKind::Image, OutputKind::Layer, OutputKind::Artboard][..], "`type`"), + (&[OutputKind::Type, OutputKind::Layer, OutputKind::Artboard][..], "`image`"), + (&[OutputKind::Type, OutputKind::Image, OutputKind::Artboard][..], "`layer`"), + (&[OutputKind::Type, OutputKind::Image, OutputKind::Layer][..], "`artboard`"), + ] { + let e = decode_with(v.as_bytes(), kinds).unwrap_err().to_string(); + assert!(e.contains(named) && e.contains("`outputKinds` doesn't list"), "{named}: {e}"); + } + let typed = r#"{"objects":[{"type":"type","text":"a","fontFamily":"x","fontSize":12}]}"#; + assert!(decode(typed.as_bytes()).unwrap_err().to_string().contains("`type` must be \"path\" or \"compound\"")); + let layered = format!(r#"{{"objects":[{SQUARE}],"layers":[{{"name":"A","objects":[0]}}]}}"#); + assert!(decode(layered.as_bytes()).unwrap_err().to_string().contains("not `layers`")); + assert!(decode(br#"{"objects":[],"artboards":[]}"#).unwrap_err().to_string().contains("not `artboards`")); + } + + /// Each limit refuses the whole output and names the limit. + #[test] + fn each_limit_is_enforced_naming_it() { + let names = |n: usize| (0..n).map(|i| json!({"name": format!("L{i}")})).collect::>(); + let cases: Vec<(Edit, String)> = vec![ + (Box::new(move |v: &mut Value| v["layers"] = json!(names(MAX_LAYERS + 1))), format!("1 to {MAX_LAYERS} entries")), + (Box::new(|v: &mut Value| v["layers"] = json!([])), "1 to".into()), + ( + Box::new(|v: &mut Value| { + v["artboards"] = json!((0..=MAX_ARTBOARDS).map(|i| json!({"name": format!("A{i}"), "rect": [0, 0, 1, 1]})).collect::>()) + }), + format!("1 to {MAX_ARTBOARDS} entries"), + ), + (Box::new(|v: &mut Value| v["objects"][0]["text"] = json!("x".repeat(MAX_TYPE_TEXT + 1))), format!("(limit {MAX_TYPE_TEXT})")), + ( + Box::new(|v: &mut Value| v["objects"][1]["pixelSize"] = json!([MAX_IMAGE_SIDE + 1, 1])), + format!("(limit {MAX_IMAGE_SIDE} pixels a side)"), + ), + (Box::new(|v: &mut Value| v["objects"][0]["fontSize"] = json!(TYPE_SIZES.1 * 2.0)), "`fontSize` must be between".into()), + ( + Box::new(|v: &mut Value| v["objects"][0]["fontFamily"] = json!("f".repeat(MAX_NAME_CHARS + 1))), + format!("1-{MAX_NAME_CHARS} characters"), + ), + ]; + for (edit, says) in cases { + let e = rich_with(edit).unwrap_err().to_string(); + assert!(e.contains(&says), "{says}: {e}"); + } + // Totals over all type and all images, found from the sizes they give before any pixels are + // decoded: these images carry no pixels at all. + let big = json!({"type": "image", "pixelSize": [MAX_IMAGE_SIDE, MAX_IMAGE_SIDE]}); + let e = decode_with(json!({"objects": [big]}).to_string().as_bytes(), ALL).unwrap_err().to_string(); + assert!(e.contains(&format!("more than {MAX_PIXEL_BYTES} bytes of pixels")), "{e}"); + let text = "t".repeat(MAX_TYPE_TEXT); + let many: Vec = (0..=MAX_TEXT_TOTAL / MAX_TYPE_TEXT).map(|_| json!({"type": "type", "text": text, "fontSize": 12})).collect(); + let e = decode_with(json!({"objects": many}).to_string().as_bytes(), ALL).unwrap_err().to_string(); + assert!(e.contains(&format!("more than {MAX_TEXT_TOTAL} bytes of text")), "{e}"); + } + + /// An image whose bytes aren't 4 × width × height, or aren't base64, is refused; so are names + /// holding control or direction characters, text holding control characters, layers that don't + /// hold each object once in order, and bad artboards. + #[test] + fn malformed_content_is_refused() { + let cases: Vec<(Edit, &str)> = vec![ + (Box::new(|v: &mut Value| v["objects"][1]["pixelsBase64"] = json!(craft_vectorcraft_format::base64::encode(&[1, 2, 3, 4]))), "= 8 bytes"), + (Box::new(|v: &mut Value| v["objects"][1]["pixelsBase64"] = json!("!!!!!!!!!!!!")), "= 8 bytes"), + (Box::new(|v: &mut Value| v["objects"][1]["pixelSize"] = json!([0, 1])), "`pixelSize`"), + (Box::new(|v: &mut Value| v["objects"][1]["linked"] = json!(true)), "unknown field `linked`"), + (Box::new(|v: &mut Value| v["objects"][0]["kind"] = json!("area")), "unknown field `kind`"), + (Box::new(|v: &mut Value| v["objects"][0]["text"] = json!("a\u{7}b")), "control characters"), + (Box::new(|v: &mut Value| v["objects"][0]["fill"] = json!({"type": "pattern", "pattern": "p"})), "objects[0]"), + (Box::new(|v: &mut Value| v["objects"][0]["transform"] = json!([0, 0, 0, 0, 0, 0])), "six finite numbers"), + (Box::new(|v: &mut Value| v["layers"][0]["name"] = json!("Art\u{202E}txt")), "text direction characters"), + (Box::new(|v: &mut Value| v["artboards"][0]["name"] = json!("A\u{0}")), "text direction characters"), + (Box::new(|v: &mut Value| v["layers"][0]["objects"] = json!([2, 1])), "increasing order"), + (Box::new(|v: &mut Value| v["layers"][0]["objects"] = json!([0, 1, 2])), "object 0 must be in exactly one layer"), + (Box::new(|v: &mut Value| v["layers"][0]["objects"] = json!([1])), "object 2 must be in exactly one layer"), + (Box::new(|v: &mut Value| v["layers"][0]["objects"] = json!([1, 2, 3])), "each below 3"), + (Box::new(|v: &mut Value| v["artboards"][1]["name"] = json!("Front")), "`Front` is used twice"), + (Box::new(|v: &mut Value| v["artboards"][0]["rect"] = json!([0, 0, 0, 10])), "width and height above 0"), + (Box::new(|v: &mut Value| v["artboards"][0]["rect"] = json!([3_999_999, 0, 10, 10])), "within ±4000000"), + ]; + for (edit, says) in cases { + let e = rich_with(edit).unwrap_err().to_string(); + assert!(e.contains(says), "{says}: {e}"); + } + } + #[test] fn warnings_are_capped_in_number_and_length() { let many: Vec = (0..crate::export::MAX_WARNINGS + 5).map(|i| format!("w{i}")).collect(); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..755f6f2bbc 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -26,7 +26,8 @@ //! time it is drawn, from an appearance stack, and at `api` 2 may paint what it returns //! ([`painted`]); an **exporter** ([`export`]) writes the whole //! document in a file format of its own; an **importer** ([`import`]) reads a file in a format of -//! its own into a new document. The process-wide [`registry`] holds the installed +//! its own into a new document, and at `api` 4 may also return type, embedded images, layers and +//! artboards ([`OutputKind`]). The process-wide [`registry`] holds the installed //! plug-ins; in [`safe_mode`] none of them loads or runs. A plug-in's parameters ([`manifest`]) come with what the host's dialogs need to show //! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A @@ -52,7 +53,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; -pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; +pub use manifest::{Budget, Command, InputKind, Kind, Manifest, OutputKind, Param, ParamSpec}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..2e10fa4671 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; -use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission}; +use crate::permissions::{self, API_LEVEL, INPUTS_API, OUTPUT_KINDS_API, PROGRESS_API, Permission}; use crate::{Error, Result}; /// Longest manifest the host reads. @@ -93,6 +93,41 @@ impl InputKind { } } +/// A kind of content an importer may return besides paths and compound paths (its manifest's +/// `outputKinds`, plug-in API level 4). Output holding a kind its manifest doesn't list is refused +/// ([`crate::import::decode_with`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum OutputKind { + /// Point type: its text, font family and style, size and fill. + Type, + /// An embedded image: its size in pixels and its RGBA pixels. + Image, + /// Top-level layers: their names, whether they show and are locked, and the objects each holds. + Layer, + /// Artboards: their names and rectangles. + Artboard, +} + +impl OutputKind { + /// Every kind, in the order the docs list them. + pub const ALL: [OutputKind; 4] = [OutputKind::Type, OutputKind::Image, OutputKind::Layer, OutputKind::Artboard]; + + /// Its name in `outputKinds`. A type or an image object's `type` in the output is this name too. + pub fn name(self) -> &'static str { + match self { + OutputKind::Type => "type", + OutputKind::Image => "image", + OutputKind::Layer => "layer", + OutputKind::Artboard => "artboard", + } + } + + /// The kind named `name`. + pub fn parse(name: &str) -> Option { + OutputKind::ALL.into_iter().find(|k| k.name() == name) + } +} + /// How much one run of a plug-in may compute. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -326,6 +361,11 @@ pub struct Manifest { /// lists them. Left out or empty, it is given paths and compound paths alone. #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")] pub inputs: Vec, + /// The kinds of content an importer returns besides paths and compound paths, by + /// [`OutputKind::name`]: only an importer at `api` 4 or later lists them. Left out or empty, it + /// returns paths and compound paths alone. + #[serde(default, rename = "outputKinds", skip_serializing_if = "Vec::is_empty", deserialize_with = "output_kind_names")] + pub output_kinds: Vec, /// Parameters in declaration (dialog) order; a JSON object `{"name": spec, …}` in the manifest. #[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")] pub params: Vec<(String, Param)>, @@ -377,6 +417,7 @@ impl Manifest { api: 1, permissions: None, inputs: Vec::new(), + output_kinds: Vec::new(), params: Vec::new(), extensions: Vec::new(), budget: Budget::Light, @@ -422,6 +463,7 @@ impl Manifest { return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}"))); } self.validate_inputs()?; + self.validate_output_kinds()?; if self.paint_output && (self.kind != Kind::Effect || self.api < 2) { return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into())); } @@ -518,6 +560,35 @@ impl Manifest { Ok(()) } + /// `outputKinds` names each [`OutputKind`] at most once, and only an importer at `api` + /// [`OUTPUT_KINDS_API`] or later lists any. + fn validate_output_kinds(&self) -> Result<()> { + if self.output_kinds.is_empty() { + return Ok(()); + } + if self.kind != Kind::Importer { + return Err(Error::Manifest("only an importer declares `outputKinds`".into())); + } + for (i, name) in self.output_kinds.iter().enumerate() { + let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD); + if OutputKind::parse(name).is_none() { + return Err(Error::Manifest(format!("`outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard"))); + } + if self.output_kinds.get(..i).is_some_and(|before| before.contains(name)) { + return Err(Error::Manifest(format!("`outputKinds` lists `{shown}` twice"))); + } + } + if self.api < OUTPUT_KINDS_API { + return Err(Error::Manifest(format!("`outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API}"))); + } + Ok(()) + } + + /// The kinds of content besides paths and compound paths an importer returns (`outputKinds`). + pub fn output_kinds(&self) -> Vec { + self.output_kinds.iter().filter_map(|n| OutputKind::parse(n)).collect() + } + /// A filter or a live effect lists at most [`MAX_COMMANDS`] commands, each with a distinct /// id, a printable label and parameters declared as the manifest's own are. A heavy filter /// lists none. The error names the command: its id, or its place in the list. @@ -733,6 +804,17 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result, D::Error> { + let wrong = || serde::de::Error::custom("`outputKinds` must be a list of kinds: type, image, layer or artboard"); + match Value::deserialize(d)? { + Value::Null => Ok(Vec::new()), + Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(), + _ => Err(wrong()), + } +} + /// Reads the `commands` list one entry at a time from the manifest itself, so each command's /// `params` keep their declaration order and a repeated parameter is refused. A malformed entry /// is an error that names it (its id when the id comes before the fault, otherwise its place in @@ -1119,7 +1201,7 @@ mod tests { (r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["progress"]}"#, "`progress` needs plug-in API level 2"), (r#"{"id":"a","name":"x","kind":"filter","permissions":["settings"]}"#, "`settings` needs plug-in API level 2"), (r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["doc.read","cache"]}"#, "`cache` needs plug-in API level 2"), - (r#"{"id":"a","name":"x","kind":"filter","api":3}"#, "`api` is 3"), + (r#"{"id":"a","name":"x","kind":"filter","api":5}"#, "`api` is 5"), (r#"{"id":"a","name":"x","kind":"filter","api":0}"#, "`api` is 0"), (r#"{"id":"a","name":"x","kind":"filter","api":-1}"#, "manifest"), ] { @@ -1128,6 +1210,46 @@ mod tests { } } + /// An importer at `api` 4 lists the kinds it returns besides paths (`outputKinds`), each once; + /// another kind of plug-in, an earlier level, an unknown kind or a repeat is refused naming + /// `outputKinds`. Left out or empty, it lists none and isn't written back. + #[test] + fn an_importer_at_api_4_lists_the_kinds_it_returns() { + let m = Manifest::parse( + br#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":["type","image","layer","artboard"]}"#, + ) + .unwrap(); + assert_eq!(m.output_kinds(), OutputKind::ALL); + assert_eq!(serde_json::to_value(&m).unwrap()["outputKinds"], json!(["type", "image", "layer", "artboard"])); + assert_eq!(m.permissions(), [Permission::ImportRead]); + for none in [ + r#"{"id":"a","name":"x","kind":"importer","extensions":["tst"]}"#, + r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":[]}"#, + r#"{"id":"a","name":"x","kind":"importer","extensions":["tst"],"outputKinds":null}"#, + ] { + let m = Manifest::parse(none.as_bytes()).unwrap(); + assert!(m.output_kinds().is_empty(), "{none}"); + assert!(serde_json::to_value(&m).unwrap().get("outputKinds").is_none(), "{none}"); + } + for (bad, says) in [ + (r#"{"id":"a","name":"x","kind":"importer","extensions":["tst"],"outputKinds":["type"]}"#, "`outputKinds` needs plug-in API level 4"), + (r#"{"id":"a","name":"x","kind":"importer","api":2,"extensions":["tst"],"outputKinds":["layer"]}"#, "give `api` 4"), + (r#"{"id":"a","name":"x","kind":"importer","api":3,"extensions":["tst"],"outputKinds":["image"]}"#, "give `api` 4"), + (r#"{"id":"a","name":"x","kind":"filter","api":4,"outputKinds":["type"]}"#, "only an importer declares `outputKinds`"), + ( + r#"{"id":"a","name":"x","kind":"exporter","api":4,"extensions":["tst"],"outputKinds":["image"]}"#, + "only an importer declares `outputKinds`", + ), + (r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":["text"]}"#, "unknown kind `text`"), + (r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":["image","image"]}"#, "lists `image` twice"), + (r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":"type"}"#, "`outputKinds` must be a list"), + (r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":[1]}"#, "`outputKinds` must be a list"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + /// A filter at `api` 2 may ask for type, images and symbol instances (`inputs`), each kind once, /// with a `permissions` list holding `doc.read`, so installing it asks for approval. Left out /// or empty, it asks for none and isn't written back. Anything else is refused naming `inputs`. diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 19a90500ce..7d6316b485 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -596,7 +596,7 @@ pub(crate) fn clamp_color(c: Color) -> Color { /// A paint from plug-in output (`null`: none), with colors, process plates, opacities and /// offsets clamped and gradient and pattern placements checked. -fn decode_paint(v: &Value, at: &str) -> Result { +pub(crate) fn decode_paint(v: &Value, at: &str) -> Result { if v.is_null() { return Ok(Paint::None); } @@ -677,7 +677,7 @@ fn opt<'a>(o: &'a serde_json::Map, key: &str) -> Option<&'a Value /// Object `v` of a plug-in's output (`at` names it in errors), its anchors added to `anchors` and /// held to [`MAX_ANCHORS`]: each key it has checked, numbers clamped into range, as [`decode`] reads /// them. -fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result { +pub(crate) fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result { let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?; let mut out = OutObject::default(); if let Some(id) = opt(o, "id") { @@ -953,7 +953,7 @@ fn paints(ap: &Appearance, fill: bool) -> Vec<&Paint> { /// `p` without swatch links: a plug-in's colours are its own, so only paints it returned /// unchanged keep theirs. A gradient stop also loses its process plates, which print only with /// a spot swatch. -fn unlinked(mut p: Paint) -> Paint { +pub(crate) fn unlinked(mut p: Paint) -> Paint { match &mut p { Paint::Solid { swatch, tint, .. } => { *swatch = None; @@ -1225,6 +1225,21 @@ impl Plan { } } +/// New object `o` of a plug-in's output (`at` names it in errors) as a node of `doc`, not yet in it: +/// a path or a compound path made as [`apply_output`] makes one, its effects admitted by `admit`. +/// An object with an `id` or without a `path` is an error. +pub fn new_object(doc: &mut Document, o: OutObject, at: &str, admit: AdmitEffects) -> Result { + if let Some(id) = o.id { + return Err(out_err(at, format!("{} is not the id of an input object", id.0))); + } + if o.path.is_none() { + return Err(out_err(at, "a new object needs a `path`")); + } + let mut n = Node::path(doc.alloc_id(), PathData::default(), Appearance::default()); + write(doc, &mut n, o, at, admit)?; + Ok(n) +} + /// Applies an object filter's output to `doc`. /// /// `inputs` are the objects the plug-in was given, in paint order ([`filter_targets`]). Output diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..664e602e51 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -15,8 +15,12 @@ use crate::{Error, Kind, Result}; /// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most /// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput` -/// ([`crate::painted`]). -pub const API_LEVEL: u32 = 2; +/// ([`crate::painted`]). Level 4 adds an importer's `outputKinds` ([`OUTPUT_KINDS_API`]). +pub const API_LEVEL: u32 = 4; + +/// The API level that adds an importer's `outputKinds` ([`crate::OutputKind`]): type, embedded +/// images, layers and artboards in what it returns ([`crate::import`]). +pub const OUTPUT_KINDS_API: u32 = 4; /// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`, /// `settings`, `cache` and `commands` permissions they need. diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4561f3dc73..e7df8a42be 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -714,6 +714,7 @@ impl PluginIntField { api: 1, permissions: None, inputs: Vec::new(), + output_kinds: Vec::new(), params: vec![("seed".into(), vectorcraft_plugins::ParamSpec::Int { min, max, default: 0 }.into())], extensions: Vec::new(), budget: Default::default(), diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..2e980762cc 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8663,6 +8663,27 @@ breakText Glyphs Glifs @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` és un efecte dinàmic: apliqueu-lo amb effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects l’importador no ha retornat cap objecte @msg an importer returns `objects` and `warnings`, not `{key}` un importador retorna `objects` i `warnings`, no `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` ha d’indicar índexs d’objectes en ordre creixent, cadascun menor que {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` inclou `{shown}` dues vegades +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` indica un tipus desconegut `{shown}`: feu servir type, image, layer o artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` requereix el nivell d’API de complements {OUTPUT_KINDS_API}: indiqueu `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` ha de ser [width, height]: dos nombres enters de l’1 al {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` ha de contenir 4 × amplada × alçada = {want} bytes en base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` ha de ser [x, y, width, height]: nombres finits dins de ±{MAX_COORD}, amb amplada i alçada més grans que 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` fa {len} bytes (límit {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` no pot contenir caràcters de control llevat de salts de línia i tabulacions +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` ha de tenir 1-{MAX_NAME_CHARS} caràcters, sense caràcters de control ni de direcció del text +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` han de ser sis nombres finits dins de ±{MAX_COORD} que no aplanin l’objecte +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` ha de contenir d’1 a {max} entrades (en conté {n}) +@msg a type fill must be a color or a gradient l’emplenament d’un text ha de ser un color o un degradat +@msg artboard name `{shown}` is used twice el nom de tauler `{shown}` s’utilitza dues vegades +@msg object {k} must be in exactly one layer l’objecte {k} ha de ser exactament en una capa +@msg only an importer declares `outputKinds` només un importador declara `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels les imatges contenen més de {MAX_PIXEL_BYTES} bytes de píxels +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list la sortida conté `{kind}`, que `outputKinds` de l’importador no inclou +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text el text conté més de {MAX_TEXT_TOTAL} bytes +@msg unknown field `{key}` camp desconegut `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} píxels (límit de {MAX_IMAGE_SIDE} píxels per costat) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads el fitxer supera els {MAX_INPUT_BYTES} bytes que llegeix un importador @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` un importador declara d’1 a {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` només un exportador o un importador declara `extensions` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..b61eb6e6e4 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8644,6 +8644,27 @@ breakText Glyphs Glyfy @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` je živý efekt: použijte ho pomocí effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects importní zásuvný modul nevrátil žádné objekty @msg an importer returns `objects` and `warnings`, not `{key}` importní zásuvný modul vrací `objects` a `warnings`, ne `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` musí uvádět indexy objektů ve vzestupném pořadí, každý menší než {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` uvádí `{shown}` dvakrát +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` uvádí neznámý druh `{shown}`: použijte type, image, layer nebo artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` vyžaduje úroveň API zásuvných modulů {OUTPUT_KINDS_API}: zadejte `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` musí být [width, height]: dvě celá čísla od 1 do {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` musí obsahovat 4 × šířka × výška = {want} bajtů v kódování base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` musí být [x, y, width, height]: konečná čísla v rozsahu ±{MAX_COORD}, šířka a výška větší než 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` má {len} bajtů (limit {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` nesmí obsahovat jiné řídicí znaky než zalomení řádků a tabulátory +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` musí mít 1-{MAX_NAME_CHARS} znaků, bez řídicích znaků a znaků směru textu +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` musí být šest konečných čísel v rozsahu ±{MAX_COORD}, která objekt nezploští +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` musí obsahovat 1 až {max} položek (obsahuje {n}) +@msg a type fill must be a color or a gradient výplň textu musí být barva nebo přechod +@msg artboard name `{shown}` is used twice název pracovní plochy `{shown}` je použit dvakrát +@msg object {k} must be in exactly one layer objekt {k} musí být právě v jedné vrstvě +@msg only an importer declares `outputKinds` `outputKinds` deklaruje pouze importní zásuvný modul +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels obrazy obsahují více než {MAX_PIXEL_BYTES} bajtů pixelů +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list výstup obsahuje `{kind}`, který `outputKinds` importního zásuvného modulu neuvádí +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text text obsahuje více než {MAX_TEXT_TOTAL} bajtů +@msg unknown field `{key}` neznámé pole `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixelů (limit {MAX_IMAGE_SIDE} pixelů na stranu) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads soubor je větší než {MAX_INPUT_BYTES} bajtů, které importní zásuvný modul čte @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` importní zásuvný modul deklaruje 1 až {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` `extensions` deklaruje jen exportní nebo importní zásuvný modul diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..4d27c64f94 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -767,6 +767,27 @@ liquify-list-end {0}, {1} {0} og {1} @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` er en live-effekt: anvend den med effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects importøren returnerede ingen objekter @msg an importer returns `objects` and `warnings`, not `{key}` en importør returnerer `objects` og `warnings`, ikke `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` skal angive objektindeks i stigende rækkefølge, hvert mindre end {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` angiver `{shown}` to gange +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` angiver en ukendt type `{shown}`: brug type, image, layer eller artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` kræver plug-in-API-niveau {OUTPUT_KINDS_API}: angiv `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` skal være [width, height]: to heltal fra 1 til {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` skal indeholde 4 × bredde × højde = {want} byte som base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` skal være [x, y, width, height]: endelige tal inden for ±{MAX_COORD}, bredde og højde over 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` er {len} byte (grænse {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` må ikke indeholde andre kontroltegn end linjeskift og tabulatorer +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` skal være 1-{MAX_NAME_CHARS} tegn uden kontroltegn eller tegn for tekstretning +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` skal være seks endelige tal inden for ±{MAX_COORD}, som ikke gør objektet fladt +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` skal indeholde 1 til {max} poster (indeholder {n}) +@msg a type fill must be a color or a gradient en tekstudfyldning skal være en farve eller en gradient +@msg artboard name `{shown}` is used twice tegnefladenavnet `{shown}` bruges to gange +@msg object {k} must be in exactly one layer objekt {k} skal ligge i præcis ét lag +@msg only an importer declares `outputKinds` kun en importør angiver `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels billederne indeholder mere end {MAX_PIXEL_BYTES} byte pixels +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list outputtet indeholder `{kind}`, som importørens `outputKinds` ikke angiver +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text teksten indeholder mere end {MAX_TEXT_TOTAL} byte +@msg unknown field `{key}` ukendt felt `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixel (grænse {MAX_IMAGE_SIDE} pixel pr. side) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads filen er større end de {MAX_INPUT_BYTES} byte, en importør læser @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` en importør angiver 1 til {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` kun en eksportør eller en importør angiver `extensions` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..d1d29163b9 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8269,6 +8269,27 @@ breakText Glyphs Glyphen @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` ist ein Live-Effekt: Wenden Sie ihn mit effect.apply {{"effect": "{_2}"}} an @msg the importer returned no objects das Import-Plug-in hat keine Objekte zurückgegeben @msg an importer returns `objects` and `warnings`, not `{key}` ein Import-Plug-in gibt `objects` und `warnings` zurück, nicht `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` muss Objektindizes in aufsteigender Reihenfolge aufführen, jeder kleiner als {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` führt `{shown}` doppelt auf +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` nennt eine unbekannte Art `{shown}`: verwenden Sie type, image, layer oder artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` erfordert Plug-in-API-Stufe {OUTPUT_KINDS_API}: geben Sie `api` {OUTPUT_KINDS_API} an +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` muss [width, height] sein: zwei ganze Zahlen von 1 bis {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` muss 4 × Breite × Höhe = {want} Byte als Base64 enthalten +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` muss [x, y, width, height] sein: endliche Zahlen innerhalb von ±{MAX_COORD}, Breite und Höhe größer als 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` ist {len} Byte groß (Grenze {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` darf außer Zeilenumbrüchen und Tabulatoren keine Steuerzeichen enthalten +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` muss 1-{MAX_NAME_CHARS} Zeichen lang sein, ohne Steuerzeichen oder Textrichtungszeichen +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` müssen sechs endliche Zahlen innerhalb von ±{MAX_COORD} sein, die das Objekt nicht flach drücken +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` muss 1 bis {max} Einträge enthalten (enthält {n}) +@msg a type fill must be a color or a gradient eine Textfläche muss eine Farbe oder ein Verlauf sein +@msg artboard name `{shown}` is used twice der Zeichenflächenname `{shown}` wird doppelt verwendet +@msg object {k} must be in exactly one layer Objekt {k} muss in genau einer Ebene liegen +@msg only an importer declares `outputKinds` nur ein Import-Plug-in deklariert `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels die Bilder enthalten mehr als {MAX_PIXEL_BYTES} Byte Pixel +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list die Ausgabe enthält `{kind}`, das `outputKinds` des Import-Plug-ins nicht aufführt +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text der Text enthält mehr als {MAX_TEXT_TOTAL} Byte +@msg unknown field `{key}` unbekanntes Feld `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} Pixel (Grenze {MAX_IMAGE_SIDE} Pixel je Seite) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads die Datei ist größer als die {MAX_INPUT_BYTES} Byte, die ein Import-Plug-in liest @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` ein Import-Plug-in gibt 1 bis {MAX_EXTENSIONS} `extensions` an @msg only an exporter or an importer declares `extensions` nur ein Export- oder Import-Plug-in gibt `extensions` an diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..21855ada39 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8635,6 +8635,27 @@ breakText Glyphs Γλύφοι @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} το `{_1}` είναι δυναμικό εφέ: εφαρμόστε το με effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects το πρόσθετο εισαγωγής δεν επέστρεψε κανένα αντικείμενο @msg an importer returns `objects` and `warnings`, not `{key}` ένα πρόσθετο εισαγωγής επιστρέφει `objects` και `warnings`, όχι `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} το `objects` πρέπει να αναφέρει δείκτες αντικειμένων σε αύξουσα σειρά, ο καθένας μικρότερος από {count} +@msg `outputKinds` lists `{shown}` twice το `outputKinds` αναφέρει το `{shown}` δύο φορές +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard το `outputKinds` ορίζει άγνωστο είδος `{shown}`: χρησιμοποιήστε type, image, layer ή artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} το `outputKinds` απαιτεί επίπεδο API προσθέτων {OUTPUT_KINDS_API}: δώστε `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} το `pixelSize` πρέπει να είναι [width, height]: δύο ακέραιοι από 1 έως {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 το `pixelsBase64` πρέπει να περιέχει 4 × πλάτος × ύψος = {want} byte σε base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 το `rect` πρέπει να είναι [x, y, width, height]: πεπερασμένοι αριθμοί εντός ±{MAX_COORD}, πλάτος και ύψος πάνω από 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) το `text` είναι {len} byte (όριο {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs το `text` δεν πρέπει να περιέχει χαρακτήρες ελέγχου εκτός από αλλαγές γραμμής και στηλοθέτες +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters το `{key}` πρέπει να έχει 1-{MAX_NAME_CHARS} χαρακτήρες, χωρίς χαρακτήρες ελέγχου ή κατεύθυνσης κειμένου +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object το `{key}` πρέπει να είναι έξι πεπερασμένοι αριθμοί εντός ±{MAX_COORD} που δεν ισοπεδώνουν το αντικείμενο +@msg `{key}` must hold 1 to {max} entries (it holds {n}) το `{key}` πρέπει να περιέχει 1 έως {max} καταχωρίσεις (περιέχει {n}) +@msg a type fill must be a color or a gradient το γέμισμα κειμένου πρέπει να είναι χρώμα ή ντεγκραντέ +@msg artboard name `{shown}` is used twice το όνομα πίνακα σχεδίασης `{shown}` χρησιμοποιείται δύο φορές +@msg object {k} must be in exactly one layer το αντικείμενο {k} πρέπει να βρίσκεται σε ακριβώς ένα επίπεδο +@msg only an importer declares `outputKinds` μόνο ένα πρόσθετο εισαγωγής δηλώνει `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels οι εικόνες περιέχουν περισσότερα από {MAX_PIXEL_BYTES} byte εικονοστοιχείων +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list η έξοδος περιέχει `{kind}`, που δεν αναφέρεται στο `outputKinds` του προσθέτου εισαγωγής +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text το κείμενο περιέχει περισσότερα από {MAX_TEXT_TOTAL} byte +@msg unknown field `{key}` άγνωστο πεδίο `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} εικονοστοιχεία (όριο {MAX_IMAGE_SIDE} εικονοστοιχεία ανά πλευρά) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads το αρχείο είναι μεγαλύτερο από τα {MAX_INPUT_BYTES} byte που διαβάζει ένα πρόσθετο εισαγωγής @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` ένα πρόσθετο εισαγωγής δηλώνει 1 έως {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` μόνο ένα πρόσθετο εξαγωγής ή εισαγωγής δηλώνει `extensions` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..bdfc398763 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8621,6 +8621,27 @@ breakText Glyphs Glifos @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` es un efecto interactivo: aplíquelo con effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects el plugin de importación no devolvió ningún objeto @msg an importer returns `objects` and `warnings`, not `{key}` un plugin de importación devuelve `objects` y `warnings`, no `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` debe incluir índices de objetos en orden creciente, cada uno menor que {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` incluye `{shown}` dos veces +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` nombra un tipo desconocido `{shown}`: use type, image, layer o artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` requiere el nivel de API de plugins {OUTPUT_KINDS_API}: indique `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` debe ser [width, height]: dos números enteros de 1 a {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` debe contener 4 × ancho × alto = {want} bytes en base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` debe ser [x, y, width, height]: números finitos dentro de ±{MAX_COORD}, con ancho y alto mayores que 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` tiene {len} bytes (límite {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` no debe contener caracteres de control salvo saltos de línea y tabulaciones +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` debe tener 1-{MAX_NAME_CHARS} caracteres, sin caracteres de control ni de dirección del texto +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` debe ser seis números finitos dentro de ±{MAX_COORD} que no aplanen el objeto +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` debe contener de 1 a {max} entradas (contiene {n}) +@msg a type fill must be a color or a gradient el relleno de un texto debe ser un color o un degradado +@msg artboard name `{shown}` is used twice el nombre de mesa de trabajo `{shown}` se usa dos veces +@msg object {k} must be in exactly one layer el objeto {k} debe estar en exactamente una capa +@msg only an importer declares `outputKinds` solo un plugin de importación declara `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels las imágenes contienen más de {MAX_PIXEL_BYTES} bytes de píxeles +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list la salida contiene `{kind}`, que `outputKinds` del plugin de importación no incluye +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text el texto contiene más de {MAX_TEXT_TOTAL} bytes +@msg unknown field `{key}` campo desconocido `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} píxeles (límite {MAX_IMAGE_SIDE} píxeles por lado) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads el archivo supera los {MAX_INPUT_BYTES} bytes que lee un plugin de importación @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` un plugin de importación declara de 1 a {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` solo un plugin de exportación o de importación declara `extensions` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..505e7d4af4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8716,6 +8716,27 @@ breakText Glyphs Merkit @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` on live-tehoste: käytä sitä komennolla effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects tuontilaajennus ei palauttanut objekteja @msg an importer returns `objects` and `warnings`, not `{key}` tuontilaajennus palauttaa `objects` ja `warnings`, ei `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects`-avaimessa on lueteltava objektien indeksit nousevassa järjestyksessä, jokainen pienempi kuin {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` luettelee kohteen `{shown}` kahdesti +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` nimeää tuntemattoman lajin `{shown}`: käytä arvoa type, image, layer tai artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` edellyttää laajennus-API:n tasoa {OUTPUT_KINDS_API}: anna `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` on oltava [width, height]: kaksi kokonaislukua väliltä 1-{MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` on sisällettävä 4 × leveys × korkeus = {want} tavua base64-muodossa +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` on oltava [x, y, width, height]: äärellisiä lukuja välillä ±{MAX_COORD}, leveys ja korkeus yli 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` on {len} tavua (raja {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` ei saa sisältää muita ohjausmerkkejä kuin rivinvaihtoja ja sarkaimia +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` on oltava 1-{MAX_NAME_CHARS} merkkiä ilman ohjausmerkkejä tai tekstin suunnan merkkejä +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` on oltava kuusi äärellistä lukua välillä ±{MAX_COORD}, jotka eivät litistä objektia +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` on sisällettävä 1-{max} merkintää (siinä on {n}) +@msg a type fill must be a color or a gradient tekstin täytön on oltava väri tai liukuväri +@msg artboard name `{shown}` is used twice piirtoalustan nimeä `{shown}` käytetään kahdesti +@msg object {k} must be in exactly one layer objektin {k} on oltava täsmälleen yhdellä tasolla +@msg only an importer declares `outputKinds` vain tuontilaajennus voi määrittää `outputKinds`-avaimen +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels kuvissa on yli {MAX_PIXEL_BYTES} tavua pikseleitä +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list tuloste sisältää lajin `{kind}`, jota tuontilaajennuksen `outputKinds` ei luettele +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text tekstissä on yli {MAX_TEXT_TOTAL} tavua +@msg unknown field `{key}` tuntematon kenttä `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pikseliä (raja {MAX_IMAGE_SIDE} pikseliä sivua kohden) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads tiedosto on suurempi kuin tuontilaajennuksen lukemat {MAX_INPUT_BYTES} tavua @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` tuontilaajennus ilmoittaa 1–{MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` vain vienti- tai tuontilaajennus ilmoittaa `extensions` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..dc578979cd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8640,6 +8640,27 @@ breakText Glyphs Glyphes @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` est un effet dynamique : appliquez-le avec effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects le module externe d’importation n’a renvoyé aucun objet @msg an importer returns `objects` and `warnings`, not `{key}` un module externe d’importation renvoie `objects` et `warnings`, pas `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` doit indiquer des indices d’objets dans l’ordre croissant, chacun inférieur à {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` mentionne `{shown}` deux fois +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` indique un type inconnu `{shown}`. Utilisez type, image, layer ou artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` nécessite le niveau d’API de module externe {OUTPUT_KINDS_API}. Indiquez `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` doit être [width, height], soit deux nombres entiers de 1 à {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` doit contenir 4 × largeur × hauteur = {want} octets en base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` doit être [x, y, width, height], soit des nombres finis compris dans ±{MAX_COORD}, largeur et hauteur supérieures à 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` fait {len} octets (limite {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` ne doit contenir aucun caractère de contrôle autre que des sauts de ligne et des tabulations +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` doit compter 1-{MAX_NAME_CHARS} caractères, sans caractère de contrôle ni de sens du texte +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` doit être six nombres finis compris dans ±{MAX_COORD} qui n’aplatissent pas l’objet +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` doit contenir de 1 à {max} entrées (il en contient {n}) +@msg a type fill must be a color or a gradient le fond d’un texte doit être une couleur ou un dégradé +@msg artboard name `{shown}` is used twice le nom de plan de travail `{shown}` est utilisé deux fois +@msg object {k} must be in exactly one layer l’objet {k} doit se trouver dans un seul calque +@msg only an importer declares `outputKinds` seul un module externe d’importation déclare `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels les images contiennent plus de {MAX_PIXEL_BYTES} octets de pixels +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list la sortie contient `{kind}`, que `outputKinds` du module externe d’importation ne mentionne pas +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text le texte contient plus de {MAX_TEXT_TOTAL} octets +@msg unknown field `{key}` champ inconnu `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixels (limite {MAX_IMAGE_SIDE} pixels par côté) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads le fichier dépasse les {MAX_INPUT_BYTES} octets qu’un module externe d’importation lit @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` un module externe d’importation déclare de 1 à {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` seul un module externe d’exportation ou d’importation déclare `extensions` diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..77bdc1a8a1 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -10101,6 +10101,27 @@ theme Appearance अपीयरेंस @msg `{_1}` is an importer: open a file with document.open {{"importer": "{_2}"}} `{_1}` एक इंपोर्टर है: document.open {{"importer": "{_2}"}} से फ़ाइल खोलें @msg the importer returned no objects इंपोर्टर ने कोई ऑब्जेक्ट नहीं लौटाया @msg an importer returns `objects` and `warnings`, not `{key}` इंपोर्टर `objects` और `warnings` लौटाता है, `{key}` नहीं +@msg `objects` must list object indexes in increasing order, each below {count} `objects` में ऑब्जेक्ट इंडेक्स बढ़ते क्रम में होने चाहिए, हर एक {count} से कम +@msg `outputKinds` lists `{shown}` twice `outputKinds` में `{shown}` दो बार सूचीबद्ध है +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` में अज्ञात प्रकार `{shown}` है: type, image, layer या artboard का उपयोग करें +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` के लिए प्लग-इन API स्तर {OUTPUT_KINDS_API} आवश्यक है: `api` {OUTPUT_KINDS_API} दें +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` [width, height] होना चाहिए: 1 से {MAX_IMAGE_SIDE} तक की दो पूर्ण संख्याएँ +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` में base64 के रूप में 4 × चौड़ाई × ऊँचाई = {want} बाइट होने चाहिए +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` [x, y, width, height] होना चाहिए: ±{MAX_COORD} के भीतर सीमित संख्याएँ, चौड़ाई और ऊँचाई 0 से अधिक +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` {len} बाइट का है (सीमा {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` में लाइन ब्रेक और टैब के अलावा कोई नियंत्रण वर्ण नहीं होना चाहिए +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` में 1-{MAX_NAME_CHARS} वर्ण होने चाहिए, नियंत्रण या टेक्स्ट दिशा वर्णों के बिना +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` ±{MAX_COORD} के भीतर छह सीमित संख्याएँ होनी चाहिए जो ऑब्जेक्ट को चपटा न करें +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` में 1 से {max} प्रविष्टियाँ होनी चाहिए (इसमें {n} हैं) +@msg a type fill must be a color or a gradient टेक्स्ट का फ़िल रंग या ग्रेडिएंट होना चाहिए +@msg artboard name `{shown}` is used twice आर्टबोर्ड नाम `{shown}` दो बार उपयोग हुआ है +@msg object {k} must be in exactly one layer ऑब्जेक्ट {k} ठीक एक लेयर में होना चाहिए +@msg only an importer declares `outputKinds` केवल इंपोर्टर `outputKinds` घोषित करता है +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels इमेज में {MAX_PIXEL_BYTES} बाइट से अधिक पिक्सेल हैं +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list आउटपुट में `{kind}` है, जिसे इंपोर्टर का `outputKinds` सूचीबद्ध नहीं करता +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text टेक्स्ट में {MAX_TEXT_TOTAL} बाइट से अधिक है +@msg unknown field `{key}` अज्ञात फ़ील्ड `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} पिक्सेल (हर तरफ़ सीमा {MAX_IMAGE_SIDE} पिक्सेल) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads फ़ाइल उन {MAX_INPUT_BYTES} बाइट्स से बड़ी है जो इंपोर्टर पढ़ता है @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` इंपोर्टर 1 से {MAX_EXTENSIONS} `extensions` घोषित करता है @msg an importer always gets an import's budget: leave `budget` out इंपोर्टर को हमेशा इंपोर्ट का बजट मिलता है: `budget` छोड़ दें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..5f5b804a4a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8630,6 +8630,27 @@ breakText Glyphs Glifák @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` élő effektus: alkalmazza az effect.apply {{"effect": "{_2}"}} paranccsal @msg the importer returned no objects az importáló bővítmény nem adott vissza objektumot @msg an importer returns `objects` and `warnings`, not `{key}` az importáló bővítmény `objects` és `warnings` értéket ad vissza, nem `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} az `objects` kulcsnak objektumindexeket kell felsorolnia növekvő sorrendben, mindegyik kisebb, mint {count} +@msg `outputKinds` lists `{shown}` twice az `outputKinds` kétszer sorolja fel ezt: `{shown}` +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard az `outputKinds` ismeretlen fajtát ad meg: `{shown}`; használja ezeket: type, image, layer vagy artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} az `outputKinds` használatához {OUTPUT_KINDS_API}. szintű bővítmény-API szükséges: adja meg az `api` {OUTPUT_KINDS_API} értéket +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} a `pixelSize` értéke [width, height] kell legyen: két egész szám 1 és {MAX_IMAGE_SIDE} között +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 a `pixelsBase64` értéknek 4 × szélesség × magasság = {want} bájtot kell tartalmaznia base64 formában +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 a `rect` értéke [x, y, width, height] kell legyen: véges számok ±{MAX_COORD} tartományban, 0-nál nagyobb szélességgel és magassággal +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) a `text` {len} bájt (korlát: {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs a `text` nem tartalmazhat vezérlőkaraktert a sortöréseken és tabulátorokon kívül +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}`: 1-{MAX_NAME_CHARS} karakter kell, vezérlő- és szövegirány-karakterek nélkül +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}`: hat véges szám kell ±{MAX_COORD} tartományban, amely nem lapítja el az objektumot +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}`: 1 és {max} közötti számú bejegyzés kell (jelenleg {n}) +@msg a type fill must be a color or a gradient a szöveg kitöltése szín vagy színátmenet lehet +@msg artboard name `{shown}` is used twice a(z) `{shown}` rajztáblanév kétszer szerepel +@msg object {k} must be in exactly one layer a(z) {k}. objektumnak pontosan egy rétegben kell lennie +@msg only an importer declares `outputKinds` `outputKinds` kulcsot csak importáló bővítmény adhat meg +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels a képek több mint {MAX_PIXEL_BYTES} bájtnyi képpontot tartalmaznak +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list a kimenet `{kind}` tartalmat hordoz, amelyet az importáló bővítmény `outputKinds` kulcsa nem sorol fel +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text a szöveg több mint {MAX_TEXT_TOTAL} bájt +@msg unknown field `{key}` ismeretlen mező: `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} képpont (oldalanként legfeljebb {MAX_IMAGE_SIDE} képpont) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads a fájl nagyobb annál a {MAX_INPUT_BYTES} bájtnál, amit egy importáló bővítmény beolvas @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` az importáló bővítmény 1–{MAX_EXTENSIONS} `extensions` értéket ad meg @msg only an exporter or an importer declares `extensions` csak exportáló vagy importáló bővítmény adhat meg `extensions` értéket diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..b83883ba62 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -648,6 +648,27 @@ @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` adalah efek langsung: terapkan dengan effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects pengimpor tidak mengembalikan objek apa pun @msg an importer returns `objects` and `warnings`, not `{key}` pengimpor mengembalikan `objects` dan `warnings`, bukan `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` harus mencantumkan indeks objek dalam urutan naik, masing-masing kurang dari {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` mencantumkan `{shown}` dua kali +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` menyebut jenis yang tidak dikenal `{shown}`: gunakan type, image, layer, atau artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` memerlukan API plug-in tingkat {OUTPUT_KINDS_API}: berikan `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` harus berupa [width, height]: dua bilangan bulat dari 1 sampai {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` harus berisi 4 × lebar × tinggi = {want} byte dalam base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` harus berupa [x, y, width, height]: bilangan hingga dalam ±{MAX_COORD}, lebar dan tinggi di atas 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` berukuran {len} byte (batas {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` tidak boleh berisi karakter kontrol selain pemisah baris dan tab +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` harus terdiri dari 1-{MAX_NAME_CHARS} karakter, tanpa karakter kontrol atau karakter arah teks +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` harus berupa enam bilangan hingga dalam ±{MAX_COORD} yang tidak memipihkan objek +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` harus berisi 1 sampai {max} entri (berisi {n}) +@msg a type fill must be a color or a gradient isian teks harus berupa warna atau gradien +@msg artboard name `{shown}` is used twice nama artboard `{shown}` digunakan dua kali +@msg object {k} must be in exactly one layer objek {k} harus berada di tepat satu lapisan +@msg only an importer declares `outputKinds` hanya pengimpor yang mendeklarasikan `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels gambar berisi lebih dari {MAX_PIXEL_BYTES} byte piksel +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list keluaran berisi `{kind}`, yang tidak dicantumkan oleh `outputKinds` pengimpor +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text teks berisi lebih dari {MAX_TEXT_TOTAL} byte +@msg unknown field `{key}` bidang tidak dikenal `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} piksel (batas {MAX_IMAGE_SIDE} piksel per sisi) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads berkas lebih besar dari {MAX_INPUT_BYTES} byte yang dibaca pengimpor @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` pengimpor mendeklarasikan 1 sampai {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` hanya pengekspor atau pengimpor yang mendeklarasikan `extensions` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..3db6189248 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8307,6 +8307,27 @@ breakText Glyphs Glifi @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` è un effetto dinamico: applicalo con effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects il plug-in di importazione non ha restituito alcun oggetto @msg an importer returns `objects` and `warnings`, not `{key}` un plug-in di importazione restituisce `objects` e `warnings`, non `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` deve elencare indici di oggetti in ordine crescente, ciascuno minore di {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` elenca `{shown}` due volte +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` indica un tipo sconosciuto `{shown}`: usa type, image, layer o artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` richiede il livello API dei plug-in {OUTPUT_KINDS_API}: indica `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` deve essere [width, height]: due numeri interi da 1 a {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` deve contenere 4 × larghezza × altezza = {want} byte in base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` deve essere [x, y, width, height]: numeri finiti entro ±{MAX_COORD}, con larghezza e altezza maggiori di 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` è di {len} byte (limite {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` non deve contenere caratteri di controllo diversi da interruzioni di riga e tabulazioni +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` deve avere 1-{MAX_NAME_CHARS} caratteri, senza caratteri di controllo o di direzione del testo +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` deve essere sei numeri finiti entro ±{MAX_COORD} che non appiattiscano l’oggetto +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` deve contenere da 1 a {max} voci (ne contiene {n}) +@msg a type fill must be a color or a gradient il riempimento di un testo deve essere un colore o una sfumatura +@msg artboard name `{shown}` is used twice il nome di tavola da disegno `{shown}` è usato due volte +@msg object {k} must be in exactly one layer l’oggetto {k} deve trovarsi in un solo livello +@msg only an importer declares `outputKinds` solo un plug-in di importazione dichiara `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels le immagini contengono più di {MAX_PIXEL_BYTES} byte di pixel +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list l’output contiene `{kind}`, che `outputKinds` del plug-in di importazione non elenca +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text il testo contiene più di {MAX_TEXT_TOTAL} byte +@msg unknown field `{key}` campo sconosciuto `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixel (limite {MAX_IMAGE_SIDE} pixel per lato) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads il file supera i {MAX_INPUT_BYTES} byte che un plug-in di importazione legge @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` un plug-in di importazione dichiara da 1 a {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` solo un plug-in di esportazione o di importazione dichiara `extensions` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..966acea9bf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -10196,6 +10196,27 @@ breakText Glyphs 字形 @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` はライブ効果です: effect.apply {{"effect": "{_2}"}} で適用してください @msg the importer returned no objects 読み込みプラグインがオブジェクトを返しませんでした @msg an importer returns `objects` and `warnings`, not `{key}` 読み込みプラグインが返すのは `objects` と `warnings` で、`{key}` ではありません +@msg `objects` must list object indexes in increasing order, each below {count} `objects` にはオブジェクトのインデックスを昇順で指定してください (各値は {count} 未満) +@msg `outputKinds` lists `{shown}` twice `outputKinds` に `{shown}` が 2 回指定されています +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` に不明な種類 `{shown}` が指定されています: type、image、layer、artboard のいずれかを使用してください +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` にはプラグイン API レベル {OUTPUT_KINDS_API} が必要です: `api` {OUTPUT_KINDS_API} を指定してください +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` は [width, height] の形式で指定してください: 1 から {MAX_IMAGE_SIDE} までの整数 2 つ +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` には 4 × 幅 × 高さ = {want} バイトを base64 で指定してください +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` は [x, y, width, height] の形式で指定してください: ±{MAX_COORD} 以内の有限の数値で、幅と高さは 0 より大きくします +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` は {len} バイトです (上限 {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` には改行とタブ以外の制御文字を含めないでください +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` は 1-{MAX_NAME_CHARS} 文字にし、制御文字や文字方向を変える文字を含めないでください +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` は ±{MAX_COORD} 以内の有限の数値 6 つで、オブジェクトをつぶさないものにしてください +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` の項目数は 1 から {max} にしてください (現在 {n}) +@msg a type fill must be a color or a gradient テキストの塗りはカラーまたはグラデーションにしてください +@msg artboard name `{shown}` is used twice アートボード名 `{shown}` が 2 回使われています +@msg object {k} must be in exactly one layer オブジェクト {k} はちょうど 1 つのレイヤーに入れてください +@msg only an importer declares `outputKinds` `outputKinds` を宣言できるのは読み込みプラグインだけです +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels 画像のピクセルが {MAX_PIXEL_BYTES} バイトを超えています +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list 出力に `{kind}` が含まれていますが、読み込みプラグインの `outputKinds` には指定されていません +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text テキストが {MAX_TEXT_TOTAL} バイトを超えています +@msg unknown field `{key}` 不明なフィールド `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} ピクセル (1 辺の上限 {MAX_IMAGE_SIDE} ピクセル) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads ファイルが読み込みプラグインの読み取る {MAX_INPUT_BYTES} バイトを超えています @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` 読み込みプラグインは `extensions` を 1~{MAX_EXTENSIONS} 個宣言します @msg only an exporter or an importer declares `extensions` `extensions` を宣言できるのは書き出しプラグインと読み込みプラグインだけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..a2507806b4 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10899,6 +10899,27 @@ font-script Japanese იაპონური @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` ცოცხალი ეფექტია: გამოიყენეთ ის effect.apply {{"effect": "{_2}"}}-ით @msg the importer returned no objects იმპორტის პლაგინმა ობიექტები არ დააბრუნა @msg an importer returns `objects` and `warnings`, not `{key}` იმპორტის პლაგინი აბრუნებს `objects`-ს და `warnings`-ს და არა `{key}`-ს +@msg `objects` must list object indexes in increasing order, each below {count} `objects`-ში ობიექტების ინდექსები ზრდადი რიგით უნდა იყოს, თითოეული {count}-ზე ნაკლები +@msg `outputKinds` lists `{shown}` twice `outputKinds`-ში `{shown}` ორჯერაა ჩამოთვლილი +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds`-ში უცნობი სახეა `{shown}`: გამოიყენეთ type, image, layer ან artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds`-ს სჭირდება პლაგინის API-ის დონე {OUTPUT_KINDS_API}: მიუთითეთ `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` უნდა იყოს [width, height]: ორი მთელი რიცხვი 1-დან {MAX_IMAGE_SIDE}-მდე +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` უნდა შეიცავდეს 4 × სიგანე × სიმაღლე = {want} ბაიტს base64-ში +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` უნდა იყოს [x, y, width, height]: სასრული რიცხვები ±{MAX_COORD}-ის ფარგლებში, სიგანე და სიმაღლე 0-ზე მეტი +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` არის {len} ბაიტი (ზღვარი {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` არ უნდა შეიცავდეს მართვის სიმბოლოებს, გარდა ხაზის გადატანისა და ტაბულაციისა +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` უნდა იყოს 1-{MAX_NAME_CHARS} სიმბოლო, მართვის და ტექსტის მიმართულების სიმბოლოების გარეშე +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` უნდა იყოს ექვსი სასრული რიცხვი ±{MAX_COORD}-ის ფარგლებში, რომლებიც ობიექტს არ აბრტყელებს +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` უნდა შეიცავდეს 1-დან {max}-მდე ჩანაწერს (შეიცავს {n}-ს) +@msg a type fill must be a color or a gradient ტექსტის შევსება უნდა იყოს ფერი ან გრადიენტი +@msg artboard name `{shown}` is used twice სამუშაო დაფის სახელი `{shown}` ორჯერაა გამოყენებული +@msg object {k} must be in exactly one layer ობიექტი {k} ზუსტად ერთ შრეში უნდა იყოს +@msg only an importer declares `outputKinds` `outputKinds`-ის გამოცხადება მხოლოდ იმპორტის პლაგინს შეუძლია +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels გამოსახულებები {MAX_PIXEL_BYTES} ბაიტზე მეტ პიქსელს შეიცავს +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list გამოტანა შეიცავს `{kind}`-ს, რომელიც იმპორტის პლაგინის `outputKinds`-ში არ არის ჩამოთვლილი +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text ტექსტი {MAX_TEXT_TOTAL} ბაიტზე მეტს შეიცავს +@msg unknown field `{key}` უცნობი ველი `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} პიქსელი (ზღვარი {MAX_IMAGE_SIDE} პიქსელი თითო მხარეს) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads ფაილი აღემატება {MAX_INPUT_BYTES} ბაიტს, რომელსაც იმპორტის პლაგინი კითხულობს @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` იმპორტის პლაგინი აცხადებს 1-დან {MAX_EXTENSIONS}-მდე `extensions`-ს @msg only an exporter or an importer declares `extensions` `extensions`-ს მხოლოდ ექსპორტის ან იმპორტის პლაგინი აცხადებს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..e67412c5aa 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8279,6 +8279,27 @@ breakText Glyphs 글리프 @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}`은(는) 라이브 효과입니다: effect.apply {{"effect": "{_2}"}}로 적용하세요 @msg the importer returned no objects 가져오기 플러그인이 개체를 반환하지 않았습니다 @msg an importer returns `objects` and `warnings`, not `{key}` 가져오기 플러그인은 `{key}`가 아닌 `objects`와 `warnings`를 반환합니다 +@msg `objects` must list object indexes in increasing order, each below {count} `objects`에는 개체 인덱스를 오름차순으로 나열해야 하며 각 값은 {count}보다 작아야 합니다 +@msg `outputKinds` lists `{shown}` twice `outputKinds`에 `{shown}`이(가) 두 번 나열되어 있습니다 +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds`에 알 수 없는 종류 `{shown}`이(가) 있습니다. type, image, layer 또는 artboard를 사용하세요 +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds`에는 플러그인 API 수준 {OUTPUT_KINDS_API}이(가) 필요합니다. `api`를 {OUTPUT_KINDS_API}(으)로 지정하세요 +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize`는 [width, height]여야 합니다. 1에서 {MAX_IMAGE_SIDE} 사이의 정수 두 개 +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64`에는 4 × 너비 × 높이 = {want}바이트가 base64로 들어 있어야 합니다 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect`는 [x, y, width, height]여야 합니다. ±{MAX_COORD} 이내의 유한한 수이며 너비와 높이는 0보다 커야 합니다 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text`가 {len}바이트입니다(한도 {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text`에는 줄 바꿈과 탭 외의 제어 문자가 없어야 합니다 +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}`은(는) 제어 문자나 텍스트 방향 문자 없이 1-{MAX_NAME_CHARS}자여야 합니다 +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}`은(는) 개체를 납작하게 만들지 않는 ±{MAX_COORD} 이내의 유한한 수 여섯 개여야 합니다 +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}`에는 1~{max}개의 항목이 있어야 합니다(현재 {n}개) +@msg a type fill must be a color or a gradient 텍스트 칠은 색상 또는 그레이디언트여야 합니다 +@msg artboard name `{shown}` is used twice 아트보드 이름 `{shown}`이(가) 두 번 사용되었습니다 +@msg object {k} must be in exactly one layer 개체 {k}은(는) 정확히 한 레이어에 있어야 합니다 +@msg only an importer declares `outputKinds` 가져오기 플러그인만 `outputKinds`를 선언할 수 있습니다 +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels 이미지의 픽셀이 {MAX_PIXEL_BYTES}바이트를 넘습니다 +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list 출력에 가져오기 플러그인의 `outputKinds`에 없는 `{kind}`이(가) 있습니다 +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text 텍스트가 {MAX_TEXT_TOTAL}바이트를 넘습니다 +@msg unknown field `{key}` 알 수 없는 필드 `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h}픽셀(한 변 한도 {MAX_IMAGE_SIDE}픽셀) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads 파일이 가져오기 플러그인이 읽는 {MAX_INPUT_BYTES}바이트보다 큽니다 @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` 가져오기 플러그인은 `extensions`를 1~{MAX_EXTENSIONS}개 선언합니다 @msg only an exporter or an importer declares `extensions` `extensions`는 내보내기 또는 가져오기 플러그인만 선언합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..d31ae44197 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -613,6 +613,27 @@ liquify-list-end {0}, {1} {0} en {1} @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` is een live-effect: pas het toe met effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects de importplug-in heeft geen objecten teruggegeven @msg an importer returns `objects` and `warnings`, not `{key}` een importplug-in geeft `objects` en `warnings` terug, niet `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` moet objectindexen in oplopende volgorde noemen, elk kleiner dan {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` noemt `{shown}` twee keer +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` noemt een onbekende soort `{shown}`: gebruik type, image, layer of artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` vereist plug-in-API-niveau {OUTPUT_KINDS_API}: geef `api` {OUTPUT_KINDS_API} op +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` moet [width, height] zijn: twee gehele getallen van 1 tot en met {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` moet 4 × breedte × hoogte = {want} bytes als base64 bevatten +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` moet [x, y, width, height] zijn: eindige getallen binnen ±{MAX_COORD}, breedte en hoogte groter dan 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` is {len} bytes (limiet {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` mag geen andere stuurtekens bevatten dan regeleinden en tabs +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` moet 1-{MAX_NAME_CHARS} tekens lang zijn, zonder stuurtekens of tekens voor de tekstrichting +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` moet uit zes eindige getallen binnen ±{MAX_COORD} bestaan die het object niet plat maken +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` moet 1 tot en met {max} items bevatten (bevat er {n}) +@msg a type fill must be a color or a gradient een tekstvulling moet een kleur of een verloop zijn +@msg artboard name `{shown}` is used twice de tekengebiednaam `{shown}` wordt twee keer gebruikt +@msg object {k} must be in exactly one layer object {k} moet in precies één laag staan +@msg only an importer declares `outputKinds` alleen een importplug-in declareert `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels de afbeeldingen bevatten meer dan {MAX_PIXEL_BYTES} bytes aan pixels +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list de uitvoer bevat `{kind}`, dat `outputKinds` van de importplug-in niet noemt +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text de tekst bevat meer dan {MAX_TEXT_TOTAL} bytes +@msg unknown field `{key}` onbekend veld `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixels (limiet {MAX_IMAGE_SIDE} pixels per zijde) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads het bestand is groter dan de {MAX_INPUT_BYTES} bytes die een importplug-in leest @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` een importplug-in declareert 1 tot {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` alleen een exportplug-in of een importplug-in declareert `extensions` diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..32cb9d38a4 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8503,6 +8503,27 @@ breakText Glyphs Glify @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` to efekt na żywo: zastosuj go za pomocą effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects wtyczka importu nie zwróciła żadnych obiektów @msg an importer returns `objects` and `warnings`, not `{key}` wtyczka importu zwraca `objects` i `warnings`, a nie `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` musi wymieniać indeksy obiektów w kolejności rosnącej, każdy mniejszy niż {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` wymienia `{shown}` dwa razy +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` podaje nieznany rodzaj `{shown}`: użyj type, image, layer lub artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` wymaga poziomu API wtyczek {OUTPUT_KINDS_API}: podaj `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` musi mieć postać [width, height]: dwie liczby całkowite od 1 do {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` musi zawierać 4 × szerokość × wysokość = {want} bajtów w base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` musi mieć postać [x, y, width, height]: liczby skończone w zakresie ±{MAX_COORD}, szerokość i wysokość większe od 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` ma {len} bajtów (limit {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` nie może zawierać znaków sterujących innych niż podziały wierszy i tabulatory +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` musi mieć 1-{MAX_NAME_CHARS} znaków, bez znaków sterujących i znaków kierunku tekstu +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` musi być sześcioma liczbami skończonymi w zakresie ±{MAX_COORD}, które nie spłaszczają obiektu +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` musi zawierać od 1 do {max} pozycji (zawiera {n}) +@msg a type fill must be a color or a gradient wypełnienie tekstu musi być kolorem lub gradientem +@msg artboard name `{shown}` is used twice nazwa obszaru kompozycji `{shown}` jest użyta dwa razy +@msg object {k} must be in exactly one layer obiekt {k} musi być w dokładnie jednej warstwie +@msg only an importer declares `outputKinds` tylko wtyczka importu deklaruje `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels obrazy zawierają więcej niż {MAX_PIXEL_BYTES} bajtów pikseli +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list wynik zawiera `{kind}`, którego nie wymienia `outputKinds` wtyczki importu +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text tekst zawiera więcej niż {MAX_TEXT_TOTAL} bajtów +@msg unknown field `{key}` nieznane pole `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pikseli (limit {MAX_IMAGE_SIDE} pikseli na bok) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads plik jest większy niż {MAX_INPUT_BYTES} bajtów, które odczytuje wtyczka importu @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` wtyczka importu deklaruje od 1 do {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` `extensions` deklaruje tylko wtyczka eksportu lub importu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..dc4ab61640 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8823,6 +8823,27 @@ swatch Yellow Green Verde-amarelado @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` é um efeito dinâmico: aplique-o com effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects o plug-in de importação não retornou nenhum objeto @msg an importer returns `objects` and `warnings`, not `{key}` um plug-in de importação retorna `objects` e `warnings`, não `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` deve listar índices de objetos em ordem crescente, cada um menor que {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` lista `{shown}` duas vezes +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` indica um tipo desconhecido `{shown}`: use type, image, layer ou artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` exige o nível de API de plug-ins {OUTPUT_KINDS_API}: informe `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` deve ser [width, height]: dois números inteiros de 1 a {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` deve conter 4 × largura × altura = {want} bytes em base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` deve ser [x, y, width, height]: números finitos dentro de ±{MAX_COORD}, com largura e altura maiores que 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` tem {len} bytes (limite {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` não deve conter caracteres de controle além de quebras de linha e tabulações +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` deve ter 1-{MAX_NAME_CHARS} caracteres, sem caracteres de controle nem de direção do texto +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` deve ser seis números finitos dentro de ±{MAX_COORD} que não achatem o objeto +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` deve conter de 1 a {max} entradas (contém {n}) +@msg a type fill must be a color or a gradient o preenchimento de um texto deve ser uma cor ou um gradiente +@msg artboard name `{shown}` is used twice o nome de mesa de trabalho `{shown}` é usado duas vezes +@msg object {k} must be in exactly one layer o objeto {k} deve estar em exatamente uma camada +@msg only an importer declares `outputKinds` somente um plug-in de importação declara `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels as imagens contêm mais de {MAX_PIXEL_BYTES} bytes de pixels +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list a saída contém `{kind}`, que `outputKinds` do plug-in de importação não lista +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text o texto contém mais de {MAX_TEXT_TOTAL} bytes +@msg unknown field `{key}` campo desconhecido `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixels (limite de {MAX_IMAGE_SIDE} pixels por lado) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads o arquivo é maior que os {MAX_INPUT_BYTES} bytes que um plug-in de importação lê @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` um plug-in de importação declara de 1 a {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` só um plug-in de exportação ou de importação declara `extensions` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..7329992d89 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8747,6 +8747,27 @@ shape Open Открытый @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` — динамический эффект: примените его с помощью effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects модуль импорта не вернул ни одного объекта @msg an importer returns `objects` and `warnings`, not `{key}` модуль импорта возвращает `objects` и `warnings`, а не `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} в `objects` должны быть индексы объектов по возрастанию, каждый меньше {count} +@msg `outputKinds` lists `{shown}` twice в `outputKinds` `{shown}` указано дважды +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard в `outputKinds` указан неизвестный вид `{shown}`: используйте type, image, layer или artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} для `outputKinds` нужен уровень API плагинов {OUTPUT_KINDS_API}: укажите `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` должно быть [width, height]: два целых числа от 1 до {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` должно содержать 4 × ширина × высота = {want} байт в base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` должно быть [x, y, width, height]: конечные числа в пределах ±{MAX_COORD}, ширина и высота больше 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` занимает {len} байт (предел {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` не должно содержать управляющих символов, кроме разрывов строк и табуляций +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` должно содержать 1-{MAX_NAME_CHARS} символов, без управляющих символов и символов направления текста +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` должно быть шестью конечными числами в пределах ±{MAX_COORD}, которые не сплющивают объект +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` должно содержать от 1 до {max} записей (содержит {n}) +@msg a type fill must be a color or a gradient заливка текста должна быть цветом или градиентом +@msg artboard name `{shown}` is used twice имя монтажной области `{shown}` использовано дважды +@msg object {k} must be in exactly one layer объект {k} должен быть ровно в одном слое +@msg only an importer declares `outputKinds` `outputKinds` может объявлять только модуль импорта +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels изображения содержат больше {MAX_PIXEL_BYTES} байт пикселей +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list вывод содержит `{kind}`, которого нет в `outputKinds` модуля импорта +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text текст занимает больше {MAX_TEXT_TOTAL} байт +@msg unknown field `{key}` неизвестное поле `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} пикселей (предел {MAX_IMAGE_SIDE} пикселей на сторону) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads файл больше {MAX_INPUT_BYTES} байт, которые читает модуль импорта @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` модуль импорта объявляет от 1 до {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` `extensions` объявляет только модуль экспорта или импорта diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..c5eeddb2d4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -10557,6 +10557,27 @@ digits Hindi Hindi @msg `{_1}` is an importer: open a file with document.open {{"importer": "{_2}"}} `{_1}` är en importfunktion: öppna en fil med document.open {{"importer": "{_2}"}} @msg the importer returned no objects importfunktionen returnerade inga objekt @msg an importer returns `objects` and `warnings`, not `{key}` en importfunktion returnerar `objects` och `warnings`, inte `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` måste ange objektindex i stigande ordning, vart och ett mindre än {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` anger `{shown}` två gånger +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` anger en okänd typ `{shown}`: använd type, image, layer eller artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` kräver plugin-API-nivå {OUTPUT_KINDS_API}: ange `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` måste vara [width, height]: två heltal från 1 till {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` måste innehålla 4 × bredd × höjd = {want} byte som base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` måste vara [x, y, width, height]: ändliga tal inom ±{MAX_COORD}, bredd och höjd över 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` är {len} byte (gräns {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` får inte innehålla andra styrtecken än radbrytningar och tabbar +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` måste vara 1-{MAX_NAME_CHARS} tecken, utan styrtecken eller textriktningstecken +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` måste vara sex ändliga tal inom ±{MAX_COORD} som inte plattar till objektet +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` måste innehålla 1 till {max} poster (innehåller {n}) +@msg a type fill must be a color or a gradient en textfyllning måste vara en färg eller en gradient +@msg artboard name `{shown}` is used twice ritytans namn `{shown}` används två gånger +@msg object {k} must be in exactly one layer objekt {k} måste ligga i exakt ett lager +@msg only an importer declares `outputKinds` bara en importfunktion anger `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels bilderna innehåller mer än {MAX_PIXEL_BYTES} byte pixlar +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list utdata innehåller `{kind}`, som importfunktionens `outputKinds` inte anger +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text texten innehåller mer än {MAX_TEXT_TOTAL} byte +@msg unknown field `{key}` okänt fält `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixlar (gräns {MAX_IMAGE_SIDE} pixlar per sida) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads filen är större än de {MAX_INPUT_BYTES} byte som en importfunktion läser @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` en importfunktion anger 1 till {MAX_EXTENSIONS} `extensions` @msg an importer always gets an import's budget: leave `budget` out en importfunktion får alltid en imports budget: utelämna `budget` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..554dfad97c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10534,6 +10534,27 @@ breakText Glyphs Glifler @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` canlı bir efekttir: effect.apply {{"effect": "{_2}"}} ile uygulayın @msg the importer returned no objects içe aktarma eklentisi hiç nesne döndürmedi @msg an importer returns `objects` and `warnings`, not `{key}` içe aktarma eklentisi `{key}` değil, `objects` ve `warnings` döndürür +@msg `objects` must list object indexes in increasing order, each below {count} `objects` nesne dizinlerini artan sırada listelemelidir; her biri {count} değerinden küçük olmalıdır +@msg `outputKinds` lists `{shown}` twice `outputKinds` `{shown}` değerini iki kez listeliyor +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` bilinmeyen bir tür belirtiyor: `{shown}`; type, image, layer veya artboard kullanın +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` için eklenti API düzeyi {OUTPUT_KINDS_API} gerekir: `api` {OUTPUT_KINDS_API} verin +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` [width, height] olmalıdır: 1 ile {MAX_IMAGE_SIDE} arasında iki tam sayı +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64`, base64 olarak 4 × genişlik × yükseklik = {want} bayt içermelidir +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` [x, y, width, height] olmalıdır: ±{MAX_COORD} içinde sonlu sayılar, genişlik ve yükseklik 0'dan büyük +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` {len} bayt (sınır {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` satır sonları ve sekmeler dışında denetim karakteri içermemelidir +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` denetim veya metin yönü karakterleri olmadan 1-{MAX_NAME_CHARS} karakter olmalıdır +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}`, nesneyi düzleştirmeyen ve ±{MAX_COORD} içinde kalan altı sonlu sayı olmalıdır +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` 1 ile {max} arasında öğe içermelidir ({n} öğe içeriyor) +@msg a type fill must be a color or a gradient metin dolgusu bir renk veya degrade olmalıdır +@msg artboard name `{shown}` is used twice çalışma yüzeyi adı `{shown}` iki kez kullanılmış +@msg object {k} must be in exactly one layer {k} nesnesi tam olarak bir katmanda olmalıdır +@msg only an importer declares `outputKinds` `outputKinds` yalnızca bir içe aktarma eklentisinde bildirilebilir +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels görüntüler {MAX_PIXEL_BYTES} bayttan fazla piksel içeriyor +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list çıktı, içe aktarma eklentisinin `outputKinds` listesinde olmayan `{kind}` içeriyor +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text metin {MAX_TEXT_TOTAL} bayttan fazla +@msg unknown field `{key}` bilinmeyen alan `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} piksel (kenar başına sınır {MAX_IMAGE_SIDE} piksel) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads dosya, içe aktarma eklentisinin okuduğu {MAX_INPUT_BYTES} bayttan büyük @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` içe aktarma eklentisi 1 ile {MAX_EXTENSIONS} arasında `extensions` bildirir @msg only an exporter or an importer declares `extensions` `extensions` yalnızca dışa veya içe aktarma eklentisi bildirir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..fb11768e94 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8289,6 +8289,27 @@ breakText Glyphs Гліфи @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` - динамічний ефект: застосуйте його за допомогою effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects модуль імпорту не повернув жодного об’єкта @msg an importer returns `objects` and `warnings`, not `{key}` модуль імпорту повертає `objects` і `warnings`, а не `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} в `objects` мають бути індекси об’єктів за зростанням, кожен менший за {count} +@msg `outputKinds` lists `{shown}` twice в `outputKinds` `{shown}` указано двічі +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard в `outputKinds` указано невідомий вид `{shown}`: використовуйте type, image, layer або artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} для `outputKinds` потрібен рівень API плагінів {OUTPUT_KINDS_API}: укажіть `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` має бути [width, height]: два цілі числа від 1 до {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` має містити 4 × ширина × висота = {want} байт у base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` має бути [x, y, width, height]: скінченні числа в межах ±{MAX_COORD}, ширина й висота більші за 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` займає {len} байт (межа {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` не має містити керівних символів, крім розривів рядків і табуляцій +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` має містити 1-{MAX_NAME_CHARS} символів, без керівних символів і символів напрямку тексту +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` має бути шістьма скінченними числами в межах ±{MAX_COORD}, які не сплющують об’єкт +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` має містити від 1 до {max} записів (містить {n}) +@msg a type fill must be a color or a gradient заливка тексту має бути кольором або градієнтом +@msg artboard name `{shown}` is used twice назву монтажної області `{shown}` використано двічі +@msg object {k} must be in exactly one layer об’єкт {k} має бути рівно в одному шарі +@msg only an importer declares `outputKinds` `outputKinds` може оголошувати лише модуль імпорту +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels зображення містять понад {MAX_PIXEL_BYTES} байт пікселів +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list вивід містить `{kind}`, якого немає в `outputKinds` модуля імпорту +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text текст займає понад {MAX_TEXT_TOTAL} байт +@msg unknown field `{key}` невідоме поле `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} пікселів (межа {MAX_IMAGE_SIDE} пікселів на сторону) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads файл більший за {MAX_INPUT_BYTES} байтів, які читає модуль імпорту @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` модуль імпорту оголошує від 1 до {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` `extensions` оголошує лише модуль експорту або імпорту diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..101eb157af 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8335,6 +8335,27 @@ breakText Glyphs Glyph @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` là hiệu ứng trực tiếp: hãy áp dụng bằng effect.apply {{"effect": "{_2}"}} @msg the importer returned no objects plug-in nhập không trả về đối tượng nào @msg an importer returns `objects` and `warnings`, not `{key}` plug-in nhập trả về `objects` và `warnings`, không phải `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` phải liệt kê chỉ mục đối tượng theo thứ tự tăng dần, mỗi chỉ mục nhỏ hơn {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` liệt kê `{shown}` hai lần +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` ghi một loại không xác định `{shown}`: hãy dùng type, image, layer hoặc artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` cần API plug-in cấp {OUTPUT_KINDS_API}: hãy đặt `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` phải là [width, height]: hai số nguyên từ 1 đến {MAX_IMAGE_SIDE} +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` phải chứa 4 × rộng × cao = {want} byte dạng base64 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` phải là [x, y, width, height]: các số hữu hạn trong khoảng ±{MAX_COORD}, chiều rộng và chiều cao lớn hơn 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` dài {len} byte (giới hạn {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` không được chứa ký tự điều khiển nào ngoài ngắt dòng và tab +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` phải dài 1-{MAX_NAME_CHARS} ký tự, không có ký tự điều khiển hay ký tự hướng văn bản +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` phải là sáu số hữu hạn trong khoảng ±{MAX_COORD} không làm dẹt đối tượng +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` phải có từ 1 đến {max} mục (hiện có {n}) +@msg a type fill must be a color or a gradient màu tô của văn bản phải là một màu hoặc một chuyển sắc +@msg artboard name `{shown}` is used twice tên bảng vẽ `{shown}` được dùng hai lần +@msg object {k} must be in exactly one layer đối tượng {k} phải nằm trong đúng một lớp +@msg only an importer declares `outputKinds` chỉ plug-in nhập mới khai báo `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels các hình ảnh chứa hơn {MAX_PIXEL_BYTES} byte điểm ảnh +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list đầu ra chứa `{kind}`, mà `outputKinds` của plug-in nhập không liệt kê +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text văn bản chứa hơn {MAX_TEXT_TOTAL} byte +@msg unknown field `{key}` trường không xác định `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} điểm ảnh (giới hạn {MAX_IMAGE_SIDE} điểm ảnh mỗi cạnh) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads tệp lớn hơn {MAX_INPUT_BYTES} byte mà plug-in nhập đọc @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` plug-in nhập khai báo từ 1 đến {MAX_EXTENSIONS} `extensions` @msg only an exporter or an importer declares `extensions` chỉ plug-in xuất hoặc nhập mới khai báo `extensions` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..87d89df070 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8513,6 +8513,27 @@ breakText Glyphs 字形 @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` 是实时效果:请用 effect.apply {{"effect": "{_2}"}} 应用 @msg the importer returned no objects 导入增效工具未返回任何对象 @msg an importer returns `objects` and `warnings`, not `{key}` 导入增效工具返回 `objects` 和 `warnings`,不是 `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` 必须按递增顺序列出对象索引,每个都小于 {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` 列出了两次 `{shown}` +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` 指定了未知类型 `{shown}`:请使用 type、image、layer 或 artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` 需要增效工具 API 级别 {OUTPUT_KINDS_API}:请指定 `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` 必须是 [width, height]:两个 1 到 {MAX_IMAGE_SIDE} 的整数 +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` 必须以 base64 形式包含 4 × 宽 × 高 = {want} 字节 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` 必须是 [x, y, width, height]:±{MAX_COORD} 以内的有限数,宽和高大于 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` 有 {len} 字节 (上限 {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` 不能包含换行符和制表符以外的控制字符 +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` 必须为 1-{MAX_NAME_CHARS} 个字符,且不含控制字符或文本方向字符 +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` 必须是 ±{MAX_COORD} 以内、不会压扁对象的六个有限数 +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` 必须包含 1 到 {max} 项 (现有 {n} 项) +@msg a type fill must be a color or a gradient 文字的填色必须是颜色或渐变 +@msg artboard name `{shown}` is used twice 画板名称 `{shown}` 使用了两次 +@msg object {k} must be in exactly one layer 对象 {k} 必须恰好位于一个图层中 +@msg only an importer declares `outputKinds` 只有导入增效工具才能声明 `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels 图像的像素超过 {MAX_PIXEL_BYTES} 字节 +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list 输出包含 `{kind}`,但导入增效工具的 `outputKinds` 没有列出它 +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text 文字超过 {MAX_TEXT_TOTAL} 字节 +@msg unknown field `{key}` 未知字段 `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} 像素 (每边上限 {MAX_IMAGE_SIDE} 像素) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads 文件超过导入增效工具读取的 {MAX_INPUT_BYTES} 字节 @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` 导入增效工具声明 1 到 {MAX_EXTENSIONS} 个 `extensions` @msg only an exporter or an importer declares `extensions` 只有导出或导入增效工具才声明 `extensions` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..8f8b5309bf 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8337,6 +8337,27 @@ breakText Glyphs 字符 @msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` 是即時效果:請用 effect.apply {{"effect": "{_2}"}} 套用 @msg the importer returned no objects 匯入增效模組未傳回任何物件 @msg an importer returns `objects` and `warnings`, not `{key}` 匯入增效模組傳回 `objects` 和 `warnings`,不是 `{key}` +@msg `objects` must list object indexes in increasing order, each below {count} `objects` 必須依遞增順序列出物件索引,每個都小於 {count} +@msg `outputKinds` lists `{shown}` twice `outputKinds` 列出了兩次 `{shown}` +@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` 指定了不明的種類 `{shown}`:請使用 type、image、layer 或 artboard +@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` 需要增效模組 API 層級 {OUTPUT_KINDS_API}:請指定 `api` {OUTPUT_KINDS_API} +@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` 必須是 [width, height]:兩個 1 到 {MAX_IMAGE_SIDE} 的整數 +@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` 必須以 base64 形式包含 4 × 寬 × 高 = {want} 位元組 +@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` 必須是 [x, y, width, height]:±{MAX_COORD} 以內的有限數,寬和高大於 0 +@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` 有 {len} 位元組 (上限 {MAX_TYPE_TEXT}) +@msg `text` must not hold control characters other than line breaks and tabs `text` 不能包含換行和定位字元以外的控制字元 +@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` 必須為 1-{MAX_NAME_CHARS} 個字元,且不含控制字元或文字方向字元 +@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` 必須是 ±{MAX_COORD} 以內、不會壓扁物件的六個有限數 +@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` 必須包含 1 到 {max} 項 (目前有 {n} 項) +@msg a type fill must be a color or a gradient 文字的填色必須是顏色或漸層 +@msg artboard name `{shown}` is used twice 工作區域名稱 `{shown}` 使用了兩次 +@msg object {k} must be in exactly one layer 物件 {k} 必須剛好位於一個圖層中 +@msg only an importer declares `outputKinds` 只有匯入增效模組才能宣告 `outputKinds` +@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels 影像的像素超過 {MAX_PIXEL_BYTES} 位元組 +@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list 輸出包含 `{kind}`,但匯入增效模組的 `outputKinds` 沒有列出 +@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text 文字超過 {MAX_TEXT_TOTAL} 位元組 +@msg unknown field `{key}` 不明的欄位 `{key}` +@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} 像素 (每邊上限 {MAX_IMAGE_SIDE} 像素) @msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads 檔案超過匯入增效模組讀取的 {MAX_INPUT_BYTES} 位元組 @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` 匯入增效模組宣告 1 到 {MAX_EXTENSIONS} 個 `extensions` @msg only an exporter or an importer declares `extensions` 只有匯出或匯入增效模組才宣告 `extensions` diff --git a/docs/gaps.md b/docs/gaps.md index 549d74f46b..fdb69df33a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -905,6 +905,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi It is given at most 128 MiB of the file and returns paths and compound paths, checked as a filter's output is, which become a new document; nothing opens when it fails, declines or is cancelled. Engine, unit and headless Open With regressions. +- **Done:** importer output kinds. An importer at plug-in API level 4 whose manifest lists `outputKinds` may also + return point type, embedded RGBA images, top-level layers and artboards; content of a kind it doesn't list, and output + past the limits on layers, artboards, text and pixels, opens nothing. Engine and unit regressions. - **Done:** exporter plug-ins (`"kind": "exporter"`). A plug-in adds a write-only file format that File › Export › Export As lists after the built-in ones and `document.export` writes (`plugin.`, or a path ending in one of its extensions). It is given the document as the native file's JSON and its parameters, with a larger budget than a diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..6501f5a359 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -17,8 +17,9 @@ There are four kinds of plug-in: laser cutters and the like. File › Export › Export As lists them after the built-in formats, and the host writes the bytes they return: a plug-in still never touches a file. - **Importers** read files in a format of their own, such as a plotter's or a cutting machine's, into a new document of - paths and compound paths. File › Open lists their files, File › Open With lists the importers by name, and the host - hands them the file's bytes. + paths and compound paths, and at API level 4 also of point type, embedded images, layers and artboards ([importer + output kinds](#importer-output-kinds)). File › Open lists their files, File › Open With lists the importers by name, + and the host hands them the file's bytes. This page is the contract for plug-in authors and the reference for the host (`crates/plugins`, the `plugin.*` commands in `crates/engine/src/cmd/plugin.rs`). @@ -27,7 +28,7 @@ in `crates/engine/src/cmd/plugin.rs`). | Command | Params | What it does | |---|---|---| -| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, commandAllowlist?, size, source, api, paintOutput?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `commandAllowlist` lists the commands it may [call](#command-calls); `paintOutput: true` marks a [painted live effect](#painted-live-effects); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `cacheBytes` is the size of its [cache](#settings-and-cache)) | +| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, commandAllowlist?, size, source, api, paintOutput?, outputKinds?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `commandAllowlist` lists the commands it may [call](#command-calls); `paintOutput: true` marks a [painted live effect](#painted-live-effects); `outputKinds` lists what an importer returns besides paths ([importer output kinds](#importer-output-kinds)); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `cacheBytes` is the size of its [cache](#settings-and-cache)) | | `plugin.info` | `{"id"}` | One plug-in: the `plugin.list` entry plus `manifest`, `defaults` and `lastError` (a live effect's last failure). | | `plugin.run` | `{"id", "params"?: {…}, "ids"?: [...]}` (plug-in params may also be top-level keys) | Runs an object filter on the selection (or `ids`; an `ids` that is not a list of object ids is an error). One undo step; the result is selected, except the objects it locked or made guides. | | `plugin.install` | `{"path": "/x/y.wasm"}` (desktop) or `{"dataBase64": "…", "name"?}`, `"replace"?: bool`, `"allowHeavy": bool = false`, `"grant"?: [permission]`, `"hash"?: "sha256 hex"` | Validates and installs a module; returns its `plugin.list` entry. The desktop app and `vectorcraft-cli` keep it in the `Plug-ins` folder next to the preferences, so it is installed again after a restart (#2541). A module with other bytes than the plug-in installed with its id, or, with none installed, one whose id has [settings and a cache](#settings-and-cache) in the `Plug-ins` folder, installs only with `replace: true`, once the user agreed; it takes that plug-in's place and gets its settings and cache. The same module installs again without `replace`, and `replace: false` refuses a module whose id is installed. A [heavy filter](#heavy-filters) installs only with `allowHeavy: true`. A plug-in whose manifest lists [permissions](#permissions) installs only when `grant` lists every one of them, unless a grant is already recorded for a module with the same SHA-256. A request's `grant` and `allowHeavy` are refused except in a session started with `vectorcraft-cli --allow-plugin-grants`. With `hash`, a module whose SHA-256 differs is refused. A module whose `commandAllowlist` lists a command no plug-in may call is refused; ids no command has are listed as `unknownCommands` ([command calls](#command-calls)). | @@ -324,10 +325,11 @@ capability model proposed for PhotoCraft plug-ins - The host enforces the grant on a filter run and a command run: without `doc.read` the filter is given no objects; without `state` its `documentData` is `null` and an output that sets it is refused; without `doc.write` an output that changes the document is refused. A refused output leaves the document as it was. -- `api` is the plug-in API level the manifest is written for: `1` (the default) or `2`, which adds the [host +- `api` is the plug-in API level the manifest is written for, `1` (the default) to `4`. Level `2` adds the [host imports](#host-imports-api-level-2), a filter's `inputs` ([reading type, images and - symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects). A higher one - is refused. `plugin.list` and `plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for + symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects). Level `3` + adds nothing to level 2 on this host. Level `4` adds an importer's [`outputKinds`](#importer-output-kinds). A higher + one is refused. `plugin.list` and `plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for are read under `doc.read`, which a filter that lists `inputs` must list in `permissions`, so installing it asks the user to grant them. A level 2 effect that declares `paintOutput` needs no other permission than `doc.read` and `effect.render`. @@ -561,6 +563,12 @@ the module's start function, in a run that isn't a filter's run on a document, o `api` 1 is refused when the module is installed, and the error names `paintOutput`. Without the key the effect returns geometry, at any level. Hosts at `api` 1 refuse the manifest for its `api`, so such an effect never draws unpainted there. +- `outputKinds` (importers at `api` 4 only): the kinds of content besides paths and compound paths the importer + returns, any of `"type"`, `"image"`, `"layer"` and `"artboard"`, each at most once (`"outputKinds": ["type", + "layer"]`). Left out, `null` or `[]`, the importer returns paths and compound paths alone, as before. An unknown, + repeated or wrongly typed entry, `outputKinds` on another kind, or below `api` 4 is refused when the plug-in is + installed, and hosts from before level 4 refuse the manifest for its `api`. It needs no permission besides + `import.read`. See [importer output kinds](#importer-output-kinds). - `extensions` (exporters and importers only, and required): 1–8 file extensions, lower-case letters and digits without the dot (`["plt"]`); the first is the one Export As gives the file. A built-in format keeps an extension both list (`svg`): `document.export` then writes the exporter's format only when asked for by its format id, and @@ -856,6 +864,48 @@ filters' object form, checked as a filter's new objects are, with warnings cappe the open's own. An output with no objects, with keys other than `objects`, `warnings` and `error`, or with an object that fails the checks opens nothing, and neither does a decline (`{"error": …}`). +#### Importer output kinds + +An importer at `api` 4 whose manifest lists [`outputKinds`](#manifest) may return more than paths. The host checks the +whole output before it makes the document, and one entry that fails a check opens nothing; the error names the entry +(`objects[2]`, `layers[0]`) and the limit or field. Content of a kind the manifest doesn't list is refused, and the +error names the kind. An importer that lists no kinds is read as before, and the keys below are errors for it. + +```json +{ + "objects": [ + {"type": "type", "text": "Hello", "fontFamily": "Source Sans 3", "fontStyle": "Bold", "fontSize": 24, + "fill": {"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}, "transform": [1, 0, 0, 1, 10, 40]}, + {"type": "image", "pixelSize": [2, 1], "pixelsBase64": "/wAA/wAA/4A=", "transform": [10, 0, 0, 10, 0, 100]}, + {"type": "path", "path": {"subpaths": [{"closed": true, "anchors": [{"p": [0, 0]}, {"p": [10, 0]}, {"p": [10, 10]}]}]}} + ], + "layers": [{"name": "Art", "objects": [1, 2]}, {"name": "Words", "visible": false, "locked": true, "objects": [0]}], + "artboards": [{"name": "Front", "rect": [0, 0, 200, 100]}, {"name": "Back", "rect": [220, 0, 200, 100]}] +} +``` + +- `"type": "type"` (kind `type`) is point type in the document's Normal Character Style with the face, size and fill + it gives: `text` (at most 1,048,576 bytes of UTF-8, a `\n` between paragraphs, no control characters other than + line breaks and tabs), `fontFamily`, `fontStyle` (left out: the family's regular style), `fontSize` (0.1–1296 pt), + `fill` (a color or a gradient, in the filters' paint form; left out: black), `transform` and `name`. The first + baseline starts at the origin of the type's own space. A font that isn't installed keeps its name, and the open + reports it as missing. All the type of one output holds at most 16,777,216 bytes of text. +- `"type": "image"` (kind `image`) is an image embedded in the document, stored as a PNG of its pixels: `pixelSize` + (width and height, 1–16,384 each), `pixelsBase64` (straight RGBA, 8 bits a channel, rows from the top, exactly 4 × + width × height bytes in padded base64), `transform` (from pixel space, one unit a pixel, into the document) and + `name`. All the images of one output hold at most 33,554,432 bytes of RGBA. The host checks both limits from the + sizes the images give, and the length of `pixelsBase64`, before it decodes any pixels. +- `transform` is six finite numbers `[a, b, c, d, e, f]` within ±4,000,000 that don't flatten the object; left out, + the identity. +- `layers` (kind `layer`): 1–256 top-level layers, bottom first. Each has a `name`, `visible` (default `true`), + `locked` (default `false`) and `objects`, the indexes of its objects in `objects` in increasing order. Every object + is in exactly one layer, and a layer may hold none. Without `layers`, every object goes in one layer. +- `artboards` (kind `artboard`): 1–100 artboards, each with a `name` used once and a `rect`, `[x, y, width, height]` + with a width and height above 0, within ±4,000,000. They replace the one artboard around the art. +- A `name` (of type, an image, a layer or an artboard) and a font's family and style are each 1–256 characters, not + only spaces, without control characters or characters that change the direction of text. +- An output whose `objects` is empty opens as a blank document when it has `layers` or `artboards`. + ## Writing a plug-in in Rust [`crates/plugins/example`](../crates/plugins/example) is a complete object filter, **Desaturate**: it moves every @@ -886,8 +936,9 @@ per change of their input, parameters or paints (results are cached), not per fr ## Not in v1 - Tool plug-ins (pointer events on the canvas, a guide line or rectangle, geometry back), panel plug-ins, and - importers that place files (File › Place reads only the built-in formats) or make type, images, layers or - artboards. + importers that place files (File › Place reads only the built-in formats) or make area type, type on a path, + nested layers or linked images (an importer at `api` 4 makes point type, embedded images, top-level layers and + artboards, see [importer output kinds](#importer-output-kinds)). - Live effects that change opacity, blending or effects (at `api` 2 one may [paint](#painted-live-effects) the pieces it returns), and filters that change type, images or symbol instances (a filter at `api` 2 reads them, see [`inputs`](#reading-type-images-and-symbols)). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..a7bd183218 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2645,6 +2645,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Exporter plug-ins (G17):** a WebAssembly plug-in of kind `exporter` adds a write-only file format. File › Export › Export As lists it after the built-in formats, with Use Artboards greyed out (the plug-in writes the whole document) and its parameters in a generated dialog once the file is picked; `document.export` writes it by its format id, `plugin.`, or by one of its extensions, and built-in formats keep theirs. The plug-in is given the native file's JSON (large images without their data) and `_context` (`mode`, `extension`, `name`), with 10 G instructions plus 4,000 per byte of input and 300 s, and Background Export's Cancel stops it between two slices of that budget. A decline or invalid output writes nothing; its warnings come back with the export's. Regressions: `crates/engine/tests/plugin_export.rs`, `crates/plugins/tests/abi.rs`, `crates/ui-egui/src/dialogs/tests_plugin_export.rs`. Scores and hours unchanged. - **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. +- **Importer output kinds (G17, VectorCraft's own contract):** an importer at plug-in API level 4 lists in its manifest's `outputKinds` which of `type`, `image`, `layer` and `artboard` it returns besides paths. Its output may then hold point type (text, font family and style, size, fill, transform), embedded RGBA images (stored as PNG in the document), top-level layers with their names, visibility, lock and objects, and named artboards that replace the one around the art; output of artboards or layers alone opens as a blank document. The host checks the whole output before it makes the document: a kind the manifest doesn't list, an image whose bytes aren't 4 × width × height, a name with control or text direction characters, or output past the limits on objects, layers, artboards, text and pixels opens nothing, and the error names the kind or the limit. Importers below level 4 read paths alone, as before. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. - **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged. From 1a21617e7394c28aafc51489ee716e0fc29dcaf2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 11:25:06 -0800 Subject: [PATCH 21/91] Scripts: text ranges take a number as contents, a new length and paragraph attributes - `contents` on a text frame or text range takes a number and writes it as `String(number)` gives it; other values still throw. - Setting a text range's `length` moves its end and leaves the text as it is (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ lists it as read/write). A value that is not a whole number from 0 to the units left in the frame throws. Each read of a member that gives a range gives a new object, so setting one range's length leaves the others alone. - A text range has the paragraph attributes as well as the character attributes, so `range.justification` reads and sets the paragraphs the range touches. - `characters`, `words` and `paragraphs` have `add(contents, relativeObject?, insertionLocation?)` and `addBefore(contents)` (https://ai-scripting.docsforadobe.dev/jsobjref/Words/), which insert the text as one `text.editRange` and give its range. An added word is kept apart from its neighbors by a space and an added paragraph by a paragraph break; an empty string runs no command. - `app.textFonts.getByName` also finds a bundled face by its PostScript name. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom/text.rs | 162 +++++++++++++++++++++++-- crates/engine/src/tests/script_text.rs | 118 +++++++++++++++++- docs/mcp.md | 22 +++- docs/target-app-parity.md | 2 +- 4 files changed, 280 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index c3ca9d1dbe..233ba56621 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -24,11 +24,17 @@ //! text. //! - The model keeps the frame's last [`MAX_EDITS`] edits; a range made before an edit that is no //! longer kept is stale. +//! - Setting a range's `length` moves its end and leaves the text as it is; each read of a member +//! that gives a range gives a new object. +//! - `add` on `characters`, `words` or `paragraphs` inserts after the collection's last item, and +//! `addBefore` before its first. An added word is kept apart from the characters next to it by a +//! space, and an added paragraph by a paragraph break. //! - A character attribute read on a range whose characters differ gives the first character's //! value; set on an empty range it changes nothing. A paragraph attribute reads the first -//! paragraph the range touches and sets every one of them. +//! paragraph the range touches and sets every one of them. A text range has the members of +//! both its `characterAttributes` and its `paragraphAttributes`. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::collections::{HashMap, VecDeque}; use std::rc::Rc; use std::sync::{Arc, Weak}; @@ -188,6 +194,10 @@ pub(in crate::script) struct TextState { /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character /// names that is not installed is added at the end. fonts: RefCell>>, + /// The number of text range objects made, which numbers the next one. + made: Cell, + /// The span of each range object, by its number, whose `length` the script set. + resized: RefCell>, } fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { @@ -320,20 +330,32 @@ fn usize_of(n: f64) -> Option { whole(n).and_then(|v| usize::try_from(v).ok()) } +/// A new object of `class` for the span `s..e` of the frame `item` at generation `stamp`. Each +/// object is numbered, so setting one range's `length` leaves every other range as it is. fn range_ref(h: &Host, item: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data { let [high, low] = id_parts(item.id); - host_ref(class, &[float(h.run), float(item.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)]) + let made = &h.dom.text.made; + made.set(made.get() + 1); + host_ref(class, &[float(h.run), float(item.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp), float(made.get())]) } /// The span `d` names, when it is an object of one of `classes`. fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result { + span_and_number(h, d, classes).map(|(span, _)| span) +} + +/// The span `d` names and the number of its object, when it is an object of one of `classes`. +fn span_and_number(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result<(Span, u64), HostError> { let handle = classes.iter().find_map(|c| handle_of(d, c)); - let Some(&[run, uid, high, low, s, e, stamp]) = handle.as_deref() else { + let Some(&[run, uid, high, low, s, e, stamp, number]) = handle.as_deref() else { return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange")))); }; let frame = item_of(h, &host_ref("TextFrame", &[run, uid, high, low])).map_err(|_| HostError::Error(STALE_RANGE.into()))?; - let (Some(start), Some(end), Some(stamp)) = (usize_of(s), usize_of(e), whole(stamp)) else { return Err(HostError::Error(STALE_RANGE.into())) }; - Ok(Span { item: frame, start, end, stamp }) + let (Some(start), Some(end), Some(stamp), Some(number)) = (usize_of(s), usize_of(e), whole(stamp), whole(number)) else { + return Err(HostError::Error(STALE_RANGE.into())); + }; + let (start, end, stamp) = h.dom.text.resized.borrow().get(&number).copied().unwrap_or((start, end, stamp)); + Ok((Span { item: frame, start, end, stamp }, number)) } /// The text frame `this` names. @@ -401,10 +423,18 @@ fn read_contents(h: &Host, r: Span) -> Answer { Ok(text(to_script(&index.text[a..b]))) } +/// The text a script gives as `contents`: a string, or a number as `String(number)` writes it. +fn contents_of(value: &Data) -> std::result::Result { + match value { + Data::String(v) => Ok(from_script(v)), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + _ => Err(HostError::Type("contents must be a string or a number".into())), + } +} + /// Replaces the text of `r` with `value`, as one `text.editRange`. fn write_contents(h: &Host, r: Span, value: &Data) -> Answer { - let Data::String(v) = value else { return Err(HostError::Type("contents must be a string".into())) }; - let insert = from_script(v); + let insert = contents_of(value)?; let (index, s, e, _) = resolve(h, r)?; let (a, b) = (index.byte(s, false), index.byte(e, true)); if index.text[a..b] == insert { @@ -562,6 +592,21 @@ fn range_length(h: &Host, a: &[Data]) -> Answer { Ok(num(float((e - s) as u64))) } +/// Setting `length` moves the range's end to that many UTF-16 units after its start; the text +/// does not change. A length that is not a whole number from 0 to the units left in the frame +/// throws. +fn range_set_length(h: &Host, a: &[Data]) -> Answer { + let (r, number) = span_and_number(h, arg(a, 0), &["TextRange"])?; + let (index, s, _, stamp) = resolve(h, r)?; + let n = super::number(arg(a, 1), "length")?; + let left = index.len() - s; + let Some(n) = usize_of(n).filter(|n| *n <= left) else { + return Err(HostError::Range(format!("length must be a whole number from 0 to {left}"))); + }; + h.dom.text.resized.borrow_mut().insert(number, (s, s + n, stamp)); + Ok(Data::Undefined) +} + /// `remove()`: deletes the range's text. fn range_remove(h: &Host, a: &[Data]) -> Answer { write_contents(h, this_range(h, a)?, &text("")) @@ -650,6 +695,85 @@ fn part_at(h: &Host, a: &[Data]) -> Answer { Ok(span.map_or(Data::Undefined, |(x, y)| range_ref(h, r.item, x, y, stamp, "TextRange"))) } +/// Where `add` puts its text: before or after the relative object. +fn text_placement(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(true), + Data::String(s) if s == "ElementPlacement.PLACEBEFORE" || s == "ElementPlacement.PLACEATBEGINNING" => Ok(false), + Data::String(s) if s == "ElementPlacement.PLACEAFTER" || s == "ElementPlacement.PLACEATEND" => Ok(true), + _ => Err(HostError::Type("insertionLocation must be PLACEBEFORE, PLACEAFTER, PLACEATBEGINNING or PLACEATEND".into())), + } +} + +/// `add(contents, relativeObject?, insertionLocation?)` and, with `before`, `addBefore(contents)`: +/// inserts `contents` after the collection's last item (`addBefore`: before its first item), or +/// before or after `relativeObject`, a text range or text frame of the same frame, as one +/// `text.editRange`. A word gets a space on each side that touches another character that is not +/// white space; a paragraph gets a paragraph break on each side that touches another paragraph. +/// → the range of `contents`. +fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { + let (r, part) = this_part(h, a)?; + let contents = contents_of(arg(a, 1))?; + let (index, s, e, _) = resolve(h, r)?; + let at = if before || matches!(arg(a, 2), Data::Undefined) { + let (items, spans) = part_spans(&index, part, s, e); + let span = |k: usize| match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + if before { + items.clone().next().and_then(span).map_or(s, |(x, _)| x) + } else { + items.clone().next_back().and_then(span).map_or(e, |(_, y)| y) + } + } else { + let rel = arg(a, 2); + let target = if handle_of(rel, "TextFrame").is_some() { + whole_span(h, item_of(h, rel)?)?.1 + } else { + span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))? + }; + if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id { + return Err(HostError::Error("relativeObject must be text of the same text frame".into())); + } + let (_, ts, te, _) = resolve(h, target)?; + if text_placement(arg(a, 3))? { te } else { ts } + }; + if contents.is_empty() { + let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; + return Ok(range_ref(h, r.item, at, at, stamp, "TextRange")); + } + let b = index.byte(at, false); + let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next()); + let (lead, trail) = match part { + Part::Characters => ("", ""), + Part::Words => { + let apart = |c: Option| c.is_some_and(|c| !c.is_whitespace()); + let lead = if apart(prev) && !contents.starts_with(char::is_whitespace) { " " } else { "" }; + let trail = if apart(next) && !contents.ends_with(char::is_whitespace) { " " } else { "" }; + (lead, trail) + } + Part::Paragraphs => ( + if prev.is_some_and(|c| c != '\n') && !contents.starts_with('\n') { "\n" } else { "" }, + if next.is_some() && !contents.ends_with('\n') { "\n" } else { "" }, + ), + }; + let insert = format!("{lead}{contents}{trail}"); + edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; + record(h, r.item, &index, at, 0, &insert)?; + let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; + let start = at + lead.encode_utf16().count(); + Ok(range_ref(h, r.item, start, start + contents.encode_utf16().count(), stamp, "TextRange")) +} + +fn part_add_after(h: &Host, a: &[Data]) -> Answer { + part_add(h, a, false) +} + +fn part_add_before(h: &Host, a: &[Data]) -> Answer { + part_add(h, a, true) +} + // ---- character attributes ---- #[derive(Clone, Copy)] @@ -1280,19 +1404,24 @@ fn fonts_at(h: &Host, a: &[Data]) -> Answer { Ok(if found { host_ref("TextFont", &[float(h.run), float(i as u64)]) } else { Data::Undefined }) } -/// `textFonts.getByName(name)`: the PostScript name, then the family and style with a space. +/// `textFonts.getByName(name)`: the PostScript name of a bundled or installed face, then the family +/// and style with a space. fn fonts_by_name(h: &Host, a: &[Data]) -> Answer { let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; if name.len() > super::MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } - let named = vectorcraft_text::FontDb::global().by_postscript_name(name); + let named = vectorcraft_text::FontDb::global().find_postscript(name).map(|f| (f.family.clone(), f.style.clone())); let i = with_fonts(h, |l| { h.charge_call(l.len() as u64)?; let by_ps = named.as_ref().and_then(|(f, s)| l.iter().position(|(lf, ls)| lf.eq_ignore_ascii_case(f) && ls.eq_ignore_ascii_case(s))); Ok::<_, HostError>(by_ps.or_else(|| l.iter().position(|(f, s)| format!("{f} {s}").eq_ignore_ascii_case(name)))) })?; - i.map(|i| host_ref("TextFont", &[float(h.run), float(i as u64)])).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + match (i, named) { + (Some(i), _) => Ok(host_ref("TextFont", &[float(h.run), float(i as u64)])), + (None, Some((family, style))) => Ok(font_ref(h, &family, &style)), + (None, None) => Err(HostError::Error(NOT_FOUND.into())), + } } fn fonts_index(h: &Host, a: &[Data]) -> Answer { @@ -1493,7 +1622,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("start", read_only(l, range_start, "TextRange", "start")), ("end", read_only(l, range_end, "TextRange", "end")), ("characterOffset", read_only(l, range_start, "TextRange", "characterOffset")), - ("length", read_only(l, range_length, "TextRange", "length")), + ("length", property(l, range_length, range_set_length)), ("characters", get(l, characters)), ("words", get(l, words)), ("paragraphs", get(l, paragraphs)), @@ -1504,6 +1633,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("remove", method(l, range_remove)), ]); range.extend(attr_members(l)); + range.extend(para_members(l)); range.extend( [ "lines", @@ -1529,7 +1659,13 @@ pub(super) fn classes(l: &Link) -> Vec { class( name, None, - named(vec![("typename", get(l, part_typename)), ("length", get(l, part_length)), ("parent", get(l, part_parent))]), + named(vec![ + ("typename", get(l, part_typename)), + ("length", get(l, part_length)), + ("parent", get(l, part_parent)), + ("add", method(l, part_add_after)), + ("addBefore", method(l, part_add_before)), + ]), Some(function(l, part_at)), ) }; diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 36dff46fa0..a357ecfe40 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -88,7 +88,19 @@ fn contents_reads_paragraph_breaks_as_r_and_accepts_every_break() { let out = log(&mut s, "var t = app.activeDocument.textFrames[0]; t.contents = 'a\\rb\\r\\nc\\nd\\u0003e'; vc.log(t.contents);"); assert_eq!(out, vec![json!("a\rb\rc\rd\u{3}e")]); assert_eq!(plain(&s, id), "a\nb\nc\nd\u{2028}e"); - assert!(failure(&mut s, "app.activeDocument.textFrames[0].contents = 5;").contains("contents must be a string")); + assert!(failure(&mut s, "app.activeDocument.textFrames[0].contents = true;").contains("contents must be a string or a number")); +} + +#[test] +fn contents_takes_a_number_as_its_text() { + let (mut s, id) = doc_with("x"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; t.contents = 7; vc.log(t.contents);\ + t.textRange.characters[0].contents = 2.5; vc.log(t.contents);", + ); + assert_eq!(out, vec![json!("7"), json!("2.5")]); + assert_eq!(plain(&s, id), "2.5"); } #[test] @@ -189,7 +201,10 @@ fn bad_attribute_values_are_refused_without_a_change() { ("r.textFont = 'Arial';", "textFont must be a TextFont"), ("r.paragraphAttributes.justification = 'LEFT';", "Justification value"), ("r.paragraphAttributes.leftIndent = 5000;", "leftIndent"), - ("r.length = 1;", "cannot be set yet"), + ("r.length = -1;", "length must be a whole number from 0 to 3"), + ("r.length = 1.5;", "length must be a whole number from 0 to 3"), + ("r.length = 4;", "length must be a whole number from 0 to 3"), + ("r.length = 'two';", "length must be a finite number"), ] { let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}")); assert!(e.contains(want), "{src}: {e}"); @@ -246,10 +261,10 @@ fn paragraph_attributes_set_the_paragraphs_a_range_touches() { &mut s, "var p = app.activeDocument.textFrames[0].paragraphs; p[0].paragraphAttributes.justification = Justification.RIGHT;\ p[0].paragraphAttributes.spaceAfter = 4;\ - vc.log([p[0].justification === undefined, p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ + vc.log([p[0].justification, p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ vc.log([p[0].paragraphAttributes.spaceAfter, p[1].paragraphAttributes.spaceAfter]);", ); - assert_eq!(out, vec![json!([true, "Justification.RIGHT", "Justification.CENTER"]), json!([4, 0])]); + assert_eq!(out, vec![json!(["Justification.RIGHT", "Justification.RIGHT", "Justification.CENTER"]), json!([4, 0])]); // The empty paragraph after a final break belongs only to an empty range at the end. let (mut s, id) = doc_with("a\n"); let out = log( @@ -431,6 +446,101 @@ fn text_fonts_list_and_assign_fonts_by_name() { assert_eq!(&set, &(family.clone(), style.clone())); } +#[test] +fn setting_a_ranges_length_moves_its_end_and_leaves_the_text() { + let (mut s, id) = doc_with("hello world"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange, w = t.words[1]; r.length = 2;\ + vc.log([r.length, r.contents, r.start, r.end, t.textRange.length]);\ + w.length = 3; vc.log([w.contents, w.start]); r.length = 0; vc.log([r.length, r.contents]);\ + t.characters[0].contents = 'J'; r.length = 5; vc.log(r.contents);", + ); + assert_eq!(out, vec![json!([2, "he", 0, 2, 11]), json!(["wor", 6]), json!([0, ""]), json!("Jello")]); + assert_eq!(plain(&s, id), "Jello world"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn collections_of_text_add_words_characters_and_paragraphs() { + let cases = [ + ("t.words.add('x')", "hello world", "hello world x", "x"), + ("t.words.addBefore('x')", "hello world", "x hello world", "x"), + ("t.words[0].words.add('x')", "hello world", "hello x world", "x"), + ("t.words.add('x', t.words[0], ElementPlacement.PLACEBEFORE)", "hello world", "x hello world", "x"), + ("t.words.add('x', t.words[1], ElementPlacement.PLACEATBEGINNING)", "hello world", "hello x world", "x"), + ("t.words.add('x', t, ElementPlacement.PLACEATEND)", "hello world", "hello world x", "x"), + ("t.words.add('x')", "hello world ", "hello world x ", "x"), + ("t.words.add('x')", "", "x", "x"), + ("t.words.add(7)", "a", "a 7", "7"), + ("t.characters.add('!')", "hi", "hi!", "!"), + ("t.characters[0].characters.add('x')", "hi", "hxi", "x"), + ("t.paragraphs.add('end')", "one\ntwo", "one\ntwo\nend", "end"), + ("t.paragraphs[0].paragraphs.add('mid')", "one\ntwo", "one\nmid\ntwo", "mid"), + ("t.paragraphs.addBefore('top')", "one", "top\none", "top"), + ]; + for (call, text, after, added) in cases { + let (mut s, id) = doc_with(text); + let before = undo_steps(&s); + let out = log(&mut s, &format!("var t = app.activeDocument.textFrames[0], n = {call}; vc.log([n.typename, n.contents]);")); + assert_eq!(out, vec![json!(["TextRange", added])], "{call} on {text:?}"); + assert_eq!(plain(&s, id), after, "{call} on {text:?}"); + assert_eq!(undo_steps(&s), before + 1, "{call} on {text:?}"); + } + // Empty contents add nothing; bad arguments throw before anything changes. + let (mut s, id) = doc_with("ab"); + s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); + let before = undo_steps(&s); + let out = log(&mut s, "var n = app.activeDocument.textFrames[1].words.add(''); vc.log([n.length, n.start]);"); + assert_eq!(out, vec![json!([0, 5])]); + for (call, want) in [ + ("t.words.add(null)", "contents must be a string or a number"), + ("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"), + ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), + ("t.words.add('x', app.activeDocument.textFrames[0])", "same text frame"), + ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), + ] { + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[1]; {call};")); + assert!(e.contains(want), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(plain(&s, id), "ab"); +} + +#[test] +fn text_fonts_find_a_bundled_face_by_its_postscript_name() { + let Some(face) = vectorcraft_text::FontDb::global().loaded_faces().into_iter().find(|f| f.family == "Source Sans 3") else { + return; // Built without the bundled fonts. + }; + let ps = face.postscript_name(); + let (mut s, _) = doc_with("abc"); + let out = log(&mut s, &format!("var f = app.textFonts.getByName('{ps}'); vc.log([f.family, f.style, f.name]);")); + assert_eq!(out, vec![json!([face.family, face.style, ps])]); +} + +#[test] +fn a_text_range_sets_the_paragraph_attributes_of_the_paragraphs_it_touches() { + let (mut s, id) = doc_with("first\nsecond\nthird"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange; r.justification = Justification.CENTER;\ + vc.log([r.justification, t.paragraphs[2].paragraphAttributes.justification]);\ + t.characters[7].leftIndent = 9; vc.log([t.paragraphs[0].leftIndent, t.paragraphs[1].leftIndent, t.paragraphs[2].leftIndent]);", + ); + assert_eq!(out, vec![json!(["Justification.CENTER", "Justification.CENTER"]), json!([0, 9, 0])]); + let justify: Vec = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (0..3).map(|i| t.para_at(i).justify).collect(), + _ => panic!("not text"), + }; + assert_eq!(justify, vec![Justify::Center; 3]); + assert_eq!(undo_steps(&s), before + 1); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.justification = 'CENTER';"); + assert!(e.contains("Justification value"), "{e}"); + assert_eq!(undo_steps(&s), before + 1); +} + #[test] fn create_outline_and_conversions_return_the_new_objects() { let (mut s, id) = doc_with("Hi"); diff --git a/docs/mcp.md b/docs/mcp.md index b837b20a5e..445018f241 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2701,7 +2701,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot `convertAreaObjectToPointObject()`. A `TextRange` (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) has `contents`, `start`, `end`, `characterOffset` (the same as `start`), `length`, `parent` (its frame), `characters`, `words`, `paragraphs`, `characterAttributes`, `paragraphAttributes`, `getParagraphLength()`, `getTextRunLength()` and - `remove()`, and the character attributes themselves. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to + `remove()`, and the character and paragraph attributes themselves. `contents` takes a string, or a number as + `String(number)` writes it. Setting `length` to a whole number from 0 to the units left in the frame moves the range's + end and leaves the text as it is. The `characters`, `words` and `paragraphs` collections + (https://ai-scripting.docsforadobe.dev/jsobjref/Words/) have `length`, `parent`, `[i]`, + `add(contents, relativeObject?, insertionLocation?)` and `addBefore(contents)`, which insert the text and give its + range, as one `text.editRange`. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to 5000 pt), `autoLeading`, `tracking` (-1000 to 10000), `baselineShift` (-1296 to 1296 pt), `horizontalScale` and `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough` and `textFont`, set with `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are @@ -2709,8 +2714,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`, `spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/) lists every style of every family in the font menu, with - `length`, `[i]`, `index(key)` and `getByName(name)`, which takes a PostScript name or the family and style joined by a - space; a `TextFont` has `name` (its PostScript name), `family` and `style`. The enumerations `TextType`, + `length`, `[i]`, `index(key)` and `getByName(name)`, which takes the PostScript name of a bundled or installed font, or + the family and style joined by a space; a `TextFont` has `name` (its PostScript name), `family` and `style`. The enumerations `TextType`, `TextOrientation` and `Justification` hold strings such as `"Justification.CENTER"`. VectorCraft's own rules: offsets and lengths count UTF-16 code units, as a JavaScript string does, and an offset inside a surrogate pair takes in its whole character; one item of `characters` is one code point. `contents` gives a @@ -2735,9 +2740,14 @@ app through the global object `vc`, and writes to the Script Console and runs ot the auto leading. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws when `text.setRangeStyle` warns that the font is not available, or when Missing Glyph Protection keeps characters the font has no glyph for in their font, giving how many. A `TextFont` from an earlier run throws - `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and - `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, `length` and - `orientation` cannot be set yet. + `Stale text font`. Each read of a member that gives a range gives a new object, so setting one range's `length` + leaves the others as they are. `add` without a relative object inserts after the collection's last item, and + `addBefore` before its first; with one, a text range or the text frame of the same frame, `PLACEBEFORE` and + `PLACEATBEGINNING` insert at its start and `PLACEAFTER`, `PLACEATEND` or no location at its end. An added word is + kept apart from the characters next to it by a space, and an added paragraph by a paragraph break; adding an empty + string runs no command. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` + and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, + `characterOffset` and `orientation` cannot be set yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6a957cad0..1eb1fe5b41 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From c0d5fddc7c41bdcf57f72457e67afbd2c360d214 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 11:40:35 -0800 Subject: [PATCH 22/91] Scripts: the host's name table lists the text ranges' paragraph attributes and the add methods --- .../tests/it/script_host_vs_scriptcheck.rs | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index b23788236e..fb505bbd2c 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -151,19 +151,21 @@ const INSIDE: &[(&str, &str)] = &[ "TextRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ - duplicate duplicate= end end= getLocalCharOverridesJSON getLocalCharOverridesJSON= getLocalParaOverridesJSON \ - getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale horizontalScale= insertionPoints \ - insertionPoints= kerning kerning= leading leading= length length= lines lines= move move= paragraphAttributes \ - paragraphStyles paragraphStyles= paragraphs parent remove rotation rotation= select select= size size= start start= \ - story story= strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ - tracking tracking= typename underline underline= verticalScale verticalScale= words", + duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \ + getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \ + horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \ + leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \ + paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \ + spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= textFont textFont= textRanges \ + textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ + verticalScale= words", ), ("Characters.", "prototype"), - ("Characters.prototype.", "constructor length parent typename"), + ("Characters.prototype.", "add addBefore constructor length parent typename"), ("Words.", "prototype"), - ("Words.prototype.", "constructor length parent typename"), + ("Words.prototype.", "add addBefore constructor length parent typename"), ("Paragraphs.", "prototype"), - ("Paragraphs.prototype.", "constructor length parent typename"), + ("Paragraphs.prototype.", "add addBefore constructor length parent typename"), ("CharacterAttributes.", "prototype"), ( "CharacterAttributes.prototype.", From 630716c81c3fc71ed7fcb04b4c14635b9d148234 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:32:57 -0800 Subject: [PATCH 23/91] Scripts: PageItem.blendingMode reads and sets an object's blending mode A page item's blendingMode gives the object's own blend mode as a BlendModes value, and assigning one sets it through object.setProps. The global BlendModes holds the 16 members the scripting constants page lists; COLORBLEND and SATURATIONBLEND set the Color and Saturation modes. Any other value throws "blendingMode needs a BlendModes value" and changes nothing. Assigning the mode the object has adds no undo step. An object in a hidden or locked layer refuses the change with "Cannot edit", as opacity does. --- crates/engine/src/script/dom.rs | 66 +++++++++++++++++-- crates/engine/src/tests/script_dom.rs | 59 +++++++++++++---- .../tests/it/script_host_vs_scriptcheck.rs | 7 +- docs/mcp.md | 19 +++--- docs/target-app-parity.md | 2 +- 5 files changed, 126 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 39c740cb2e..b94cc3efc1 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -42,11 +42,12 @@ //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. //! - Members the help pages list that are not here yet throw an error that says so. -//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an -//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change -//! nothing, even for the value the object has. The exception is `opacity` given the value the -//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps -//! another opacity it would still change the graph, so it is refused too. Its `name` and `note` +//! - Assigning `hidden`, `locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or +//! `height` to an object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` +//! and change nothing, even for the value the object has. The exception is `opacity` or +//! `blendingMode` given the value the object has when that changes nothing; on a graph's mark or +//! label whose series or kind keeps another opacity or blend mode it would still change the graph, +//! so it is refused too. Its `name` and `note` //! still change. An object that is hidden or locked itself, or is in a hidden or locked group, //! takes them. //! - `name` and `note` take a number or a Boolean as the text `String(value)` gives. @@ -60,6 +61,7 @@ use std::rc::Rc; use std::sync::Arc; use serde_json::{Value, json}; +use vectorcraft_color::BlendMode; use vectorcraft_geom::{Point, Rect}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; @@ -1600,6 +1602,56 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) } +/// The members of `BlendModes` with the blend mode each one names. +const BLEND_MODES: [(&str, BlendMode); 16] = [ + ("COLORBLEND", BlendMode::Color), + ("COLORBURN", BlendMode::ColorBurn), + ("COLORDODGE", BlendMode::ColorDodge), + ("DARKEN", BlendMode::Darken), + ("DIFFERENCE", BlendMode::Difference), + ("EXCLUSION", BlendMode::Exclusion), + ("HARDLIGHT", BlendMode::HardLight), + ("HUE", BlendMode::Hue), + ("LIGHTEN", BlendMode::Lighten), + ("LUMINOSITY", BlendMode::Luminosity), + ("MULTIPLY", BlendMode::Multiply), + ("NORMAL", BlendMode::Normal), + ("OVERLAY", BlendMode::Overlay), + ("SATURATIONBLEND", BlendMode::Saturation), + ("SCREEN", BlendMode::Screen), + ("SOFTLIGHT", BlendMode::SoftLight), +]; + +fn item_blending_mode(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| { + let name = BLEND_MODES.iter().find(|(_, m)| *m == n.blend).map_or("NORMAL", |(name, _)| name); + Ok(text(format!("BlendModes.{name}"))) + }) +} + +/// `blendingMode = BlendModes.`: the object's own blend mode, as `object.setProps` sets it. +/// The mode the object already has may be assigned while its layer is hidden or locked, unless it +/// would still replace the blend mode a graph keeps for the item's series or kind. +fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer { + let mode = match arg(a, 1) { + Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode), + _ => None, + }; + let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?; + let item = this_item(h, a)?; + let (same, keeps_other) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let same = d.node(item.id).is_some_and(|n| n.blend == mode); + let keeps_other = + crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]); + (same, keeps_other) + }); + if !same || keeps_other { + refuse_in_closed_layer(h, item)?; + } + set_props(h, a, |_| false, json!({"blend": mode.label()})) +} + fn item_selected(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)))) @@ -2077,6 +2129,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect(); + realm.define_host_object("BlendModes", blend_modes)?; let l = link; let mut application = named(vec![ ("typename", typename_of("Application")), @@ -2161,6 +2215,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("locked", property(l, item_locked, item_set_locked)), ("selected", property(l, item_selected, item_set_selected)), ("opacity", property(l, item_opacity, item_set_opacity)), + ("blendingMode", property(l, item_blending_mode, item_set_blending_mode)), ("position", property(l, item_position, item_set_position)), ("left", property(l, item_left, item_set_left)), ("top", property(l, item_top, item_set_top)), @@ -2180,7 +2235,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), page_item.extend( [ "artworkKnockout", - "blendingMode", "isIsolated", "layer", "pixelAligned", diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4e705538d9..07131a18e9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -278,6 +278,40 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(undo_steps(&s), steps + 1); } +/// `blendingMode` reads and sets the object's own blend mode as a `BlendModes` value; the mode it +/// already has adds no undo step, and any other value throws and changes nothing. +#[test] +fn blending_mode_reads_and_sets_the_objects_blend_mode() { + let (mut s, a, b) = doc(); + let blend = |s: &Session, id: NodeId| s.active().unwrap().doc.node(id).unwrap().blend; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[1]; vc.log(i.blendingMode);\ + i.blendingMode = BlendModes.MULTIPLY; vc.log(i.blendingMode);\ + vc.log([i.hasOwnProperty('blendingMode'), BlendModes.SATURATIONBLEND, BlendModes.COLORBLEND]);", + ); + assert_eq!(out[..2], [json!("BlendModes.NORMAL"), json!("BlendModes.MULTIPLY")]); + assert_eq!(out[2], json!([true, "BlendModes.SATURATIONBLEND", "BlendModes.COLORBLEND"])); + assert_ne!(blend(&s, a), blend(&s, b), "only the assigned object changed"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + let (before, steps) = (blend(&s, a), undo_steps(&s)); + log(&mut s, "var i = app.activeDocument.pageItems[1]; i.blendingMode = BlendModes.MULTIPLY; i.blendingMode = i.blendingMode;"); + assert_eq!((blend(&s, a), undo_steps(&s)), (before, steps), "the mode the object has adds no step"); + // Two modes the help page names with a suffix set the modes the Transparency panel calls Color + // and Saturation. + log(&mut s, "var p = app.activeDocument.pageItems; p[1].blendingMode = BlendModes.COLORBLEND; p[0].blendingMode = BlendModes.SATURATIONBLEND;"); + assert_eq!((blend(&s, a).label(), blend(&s, b).label()), ("Color", "Saturation")); + let (before, steps) = (blend(&s, a), undo_steps(&s)); + for value in + ["'BlendModes.SCREEN '", "'MULTIPLY'", "'Multiply'", "'BlendModes.multiply'", "'BlendModes.NOPE'", "5", "null", "ZOrderMethod.BRINGTOFRONT"] + { + let e = failure(&mut s, &format!("app.activeDocument.pageItems[1].blendingMode = {value};")); + assert!(e.contains("blendingMode needs a BlendModes value"), "{value}: {e}"); + assert_eq!((blend(&s, a), undo_steps(&s)), (before, steps), "{value}"); + } +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -876,13 +910,13 @@ fn a_startup_preset_alone_gives_its_first_size() { fn page_item_members_not_built_yet_throw_on_read_and_assignment() { let (mut s, _, _) = doc(); for source in - ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] + ["app.activeDocument.pageItems[0].isIsolated;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); // A deleted item or an earlier run's document is stale first. - let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.blendingMode;"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.isIsolated;"); assert!(e.contains("Stale page item"), "{e}"); run(&mut s, "#targetengine keep\nvar d = app.activeDocument;").unwrap(); let e = failure(&mut s, "#targetengine keep\nd.layers;"); @@ -1407,7 +1441,7 @@ fn unsupported_members_say_so() { /// A script that names each visible selected object after its place in `app.selection`, testing /// the members it uses with `hasOwnProperty` and `propertyIsEnumerable` first. A member that is not -/// available yet, such as `blendingMode`, is read only when `hasOwnProperty` reports it, so it is +/// available yet, such as `isIsolated`, is read only when `hasOwnProperty` reports it, so it is /// never read. const NAME_PICKED: &str = "\ var picked = app.selection, k = picked.length, named = 0;\ @@ -1415,7 +1449,7 @@ const NAME_PICKED: &str = "\ while (k--) {\ var obj = picked[k];\ var usable = obj.propertyIsEnumerable('name') && obj.hasOwnProperty('hidden') && !obj.hidden;\ - if (obj.hasOwnProperty('blendingMode') && obj.blendingMode) usable = false;\ + if (obj.hasOwnProperty('isIsolated') && obj.isIsolated) usable = false;\ if (usable) { obj.name = 'picked ' + k; named += 1; }\ }\ if (picked.length && named < picked.length) alert('Some objects were skipped.');"; @@ -1494,9 +1528,9 @@ fn page_items_report_their_available_members_as_their_own() { vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\ Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\ app.hasOwnProperty('activeDocument')]);\ - vc.log([p.hasOwnProperty('blendingMode'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ + vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ - vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('blendingMode')]);", + vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);", ); assert_eq!(out[0], json!([true, true, true, true, true, true, true])); // Members that are not available yet, unknown names and inherited ones are not the object's own. @@ -1625,7 +1659,7 @@ fn a_collection_read_with_a_name_gives_the_named_object() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); } -/// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or +/// `opacity`, `blendingMode`, `hidden`, `locked` and the position and size setters on an object in a hidden or /// locked layer throw and the run changes nothing, while its name and note still change; an object /// that is hidden or locked itself takes them. #[test] @@ -1645,6 +1679,7 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { // `hidden` and `locked` are refused even when the value is the one the object has. for set in [ "opacity = 50", + "blendingMode = BlendModes.MULTIPLY", "hidden = true", "hidden = false", "locked = true", @@ -1666,9 +1701,9 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { let out = log( &mut s, "var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; c.opacity = c.opacity;\ - vc.log([c.name, c.note, c.opacity]); c.name = 'closed'; c.note = '';", + c.blendingMode = c.blendingMode; vc.log([c.name, c.note, c.opacity, c.blendingMode]); c.name = 'closed'; c.note = '';", ); - assert_eq!(out, vec![json!(["renamed", "n", 100])], "{on}"); + assert_eq!(out, vec![json!(["renamed", "n", 100, "BlendModes.NORMAL"])], "{on}"); s.execute("object.setProps", &off).unwrap(); } s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); @@ -1676,9 +1711,11 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { let out = log( &mut s, "var p = app.activeDocument.pageItems; p.getByName('locked').opacity = 50; p.getByName('free').opacity = 40;\ - vc.log([p.getByName('locked').opacity, p.getByName('free').opacity]);", + p.getByName('locked').blendingMode = BlendModes.SCREEN; p.getByName('free').blendingMode = BlendModes.DARKEN;\ + vc.log([p.getByName('locked').opacity, p.getByName('free').opacity, p.getByName('locked').blendingMode,\ + p.getByName('free').blendingMode]);", ); - assert_eq!(out, vec![json!([50, 40])]); + assert_eq!(out, vec![json!([50, 40, "BlendModes.SCREEN", "BlendModes.DARKEN"])]); } /// `name` takes a number or a Boolean as the text `String` gives it, and nothing else. diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 4368ce29b7..c92729083a 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -75,7 +75,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ + "activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod", ), @@ -117,6 +117,11 @@ const INSIDE: &[(&str, &str)] = &[ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), + ( + "BlendModes.", + "COLORBLEND COLORBURN COLORDODGE DARKEN DIFFERENCE EXCLUSION HARDLIGHT HUE LIGHTEN LUMINOSITY MULTIPLY NORMAL \ + OVERLAY SATURATIONBLEND SCREEN SOFTLIGHT", + ), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), diff --git a/docs/mcp.md b/docs/mcp.md index e963a4bd42..c938b3843c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2702,7 +2702,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to - 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the + 100), `blendingMode` (the object's own blend mode as a `BlendModes` value such as `"BlendModes.MULTIPLY"` + (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/), set with `object.setProps`; `COLORBLEND` and `SATURATIONBLEND` are the Color and Saturation modes, and any other value + throws `blendingMode needs a BlendModes value`), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the visible bounds), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` @@ -2715,11 +2717,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`, - `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer - throws `Cannot edit` and changes nothing, even when the value is the one the object has, and `zOrder()` on such - an object throws `Cannot edit` too. The one exception is `opacity` given the value the object already has, which - changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity, that - value would still change the graph, so it throws `Cannot edit` as well. Its `name` and `note` still change, and an + `locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or + locked layer throws `Cannot edit` and changes nothing, even when the value is the one the object has, and + `zOrder()` on such an object throws `Cannot edit` too. The one exception is `opacity` or `blendingMode` given the + value the object already has, which changes nothing and does not throw; on a graph's mark or label whose series or + kind keeps another opacity or blend mode, that value would still change the graph, so it throws `Cannot edit` as + well. Its `name` and `note` still change, and an object that is hidden or locked itself takes all of them (VectorCraft's own rule). `move` with the object itself as the relative object and `PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` or `remove()` takes the last path out of a compound path, the compound path stays, empty, so a script that holds @@ -2729,7 +2732,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a - `RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, + `RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `BlendModes`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. `pageItems` lists the art topmost first, as the example on @@ -2770,7 +2773,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, - Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and + Document and PageItem pages list, such as `Document.layers`, `PageItem.isIsolated`, `PageItem.rotate` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. `hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b5346c5af7..5f037cf900 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1033,7 +1033,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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 263223d604293a29cfe400285244d778a575af90 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:57:54 -0800 Subject: [PATCH 24/91] Scripts: Run checks the script again before running it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the script's report has changed since the Other Script… warning opened, Run runs nothing, says so in the status bar and opens the warning again with the new report. --- crates/ui-egui/src/dialogs/script_run.rs | 31 ++++++++++++++++++++---- crates/ui-egui/src/tests/script_run.rs | 22 +++++++++++++++++ docs/mcp.md | 5 ++-- 3 files changed, 51 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 690feebd62..b7f3897931 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -15,7 +15,9 @@ //! and dialogs it needs, features only the reference app has, and its includes (at most //! [`SHOWN_INCLUDES`], then the count of the rest). It says when the script is too large to check, //! compiled or not a script, when the check failed, and when a list was cut short at its limit. -//! The listing is information: Run runs the script as before. The growth question +//! The listing is information: Run runs the script as before, after checking it again. When the +//! report has changed since the warning opened, nothing runs and the warning opens again with the +//! new report. The growth question //! (`scriptGrowth`) and the question quitting asks (`scriptClose`) have the `choice` field alone. //! //! A script's dialog (kind `scriptDialog`) has the fields `kind` (alert, confirm or prompt), @@ -522,8 +524,14 @@ pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result Result { + let path = params.get("path").and_then(Value::as_str); + let name = params.get("name").and_then(Value::as_str).or(path).map_or_else(|| "script".to_string(), vectorcraft_engine::cmd::fileio::file_name); // The script's name is the message: it is what the person reads first. let prompt = StandardPrompt::custom(name) .title(tl!("Run Script")) @@ -537,6 +545,10 @@ pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result() + && let Some(RunWarning { params, reaches: listed }) = answer.take_tag::() { - let stored = if answer.skip { app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).map(drop) } else { Ok(()) }; - if let Err(e) = stored.and_then(|()| app.run("script.run", params).map(drop)) { + // A script whose report changed while the warning was open is listed again before it runs. + let now = reaches(app, ¶ms); + let ran = if now == listed { + let stored = + if answer.skip { app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).map(drop) } else { Ok(()) }; + stored.and_then(|()| app.run("script.run", params).map(drop)) + } else { + app.status(CHANGED_SINCE_WARNING); + warn(app, params, now).map(drop) + }; + if let Err(e) = ran { app.status(e); } } diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 0f26951362..11d9a3ed0c 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -541,6 +541,28 @@ fn the_warning_lists_what_a_scripts_included_files_reach() { let _ = std::fs::remove_dir_all(&dir); } +/// A script file that changes what it reaches while its warning is open does not run on Run: the +/// warning opens again with the new report, and the next Run runs it. +#[test] +fn run_lists_a_script_again_when_it_changed_after_its_warning_opened() { + let mut app = app(); + let dir = folder("changed"); + let path = dir.join("changed.jsx"); + std::fs::write(&path, DRAW).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap(); + assert_eq!(fields(&app, KIND)["reaches"]["outside"], json!([])); + std::fs::write(&path, format!("{DRAW}\nvar s = new Socket();\n")).unwrap(); + assert!(confirm(&mut app, KIND)); + assert!(!app.session.script_running()); + assert!(is_open::(&app)); + assert_eq!(app.ui.status, script_run::CHANGED_SINCE_WARNING); + assert_eq!(fields(&app, KIND)["reaches"]["outside"][0]["id"], "network"); + assert!(confirm(&mut app, KIND)); + assert!(app.session.script_running()); + finish(&mut app); + let _ = std::fs::remove_dir_all(&dir); +} + /// A script with more includes than the warning lists gives the count of the rest. #[test] fn the_warning_counts_the_includes_it_does_not_list() { diff --git a/docs/mcp.md b/docs/mcp.md index 8ef2380bca..5cd7f9210f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2643,8 +2643,9 @@ files it opens in other apps, messages to other apps, the network, native code, app's preferences and code the checker can't read), the files and dialogs it needs, features only the reference app has, and the files its `#include` lines name (the first 20, then the count of the rest; VectorCraft's own limit). It says when the script is too large to check, compiled or not a script, when the check failed, and when a list was cut -short at its limit. The listing does not stop the run. A -script from the Scripts folder runs without the warning. +short at its limit. The listing does not stop the run. Run checks the script again, and when the report has changed +since the warning opened, nothing runs and the warning opens again with the new report. A script from the Scripts +folder runs without the warning. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and From 2b155a5de177931f7860860bb017f24cb4f5bfb0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 04:00:21 -0800 Subject: [PATCH 25/91] Scripts: the warning lists a script's needs apart from what it reaches A need such as dialogs or host features now shows on its own line, and the "Outside the document" heading appears only above what the script does outside the document. --- crates/ui-egui/src/dialogs/script_run.rs | 11 ++++++----- crates/ui-egui/src/tests/script_run.rs | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index b7f3897931..1d54f82fd6 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -592,11 +592,12 @@ fn listed(prompt: StandardPrompt, r: &Value) -> StandardPrompt { }) .collect(); let needs = list(r, "needs").iter().filter_map(Value::as_str).filter(|n| matches!(*n, "files" | "dialogs" | "hostOnly")).filter_map(need_label); - let mut lines: Vec = Vec::new(); - lines.extend(outside); - lines.extend(needs.map(str::to_string)); - if !lines.is_empty() { - lines.insert(0, crate::i18n::colon(tl!("Outside the document"))); + // The needs come first, each a sentence of its own; the heading names only what the script does + // outside the document. + let mut lines: Vec = needs.map(str::to_string).collect(); + if !outside.is_empty() { + lines.push(crate::i18n::colon(tl!("Outside the document"))); + lines.extend(outside); } let includes = list(r, "includes"); if !includes.is_empty() { diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 11d9a3ed0c..fcb0d8bbd2 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -541,6 +541,20 @@ fn the_warning_lists_what_a_scripts_included_files_reach() { let _ = std::fs::remove_dir_all(&dir); } +/// A script that opens a dialog and reaches nothing outside the document lists the need without the +/// outside-the-document heading. +#[test] +fn the_warning_lists_a_need_without_the_outside_heading() { + let mut app = app(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "var w = new Window('dialog', 'Title');", "name": "dialog.js"})).unwrap().unwrap(); + assert_eq!(fields(&app, KIND)["reaches"]["outside"], json!([])); + let texts = dialog_texts(&mut app); + assert!(texts.iter().any(|t| t == script_check::need_label("dialogs").unwrap()), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "Outside the document:"), "{texts:?}"); + cancel(&mut app, KIND); + finish(&mut app); +} + /// A script file that changes what it reaches while its warning is open does not run on Run: the /// warning opens again with the new report, and the next Run runs it. #[test] From 8ab94ba4e88cbb4804092b3a2b941f8d65d3c0cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 04:24:48 -0800 Subject: [PATCH 26/91] Scripts: format the dialog-need warning test --- crates/ui-egui/src/tests/script_run.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fcb0d8bbd2..8ffe57f766 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -546,7 +546,8 @@ fn the_warning_lists_what_a_scripts_included_files_reach() { #[test] fn the_warning_lists_a_need_without_the_outside_heading() { let mut app = app(); - menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "var w = new Window('dialog', 'Title');", "name": "dialog.js"})).unwrap().unwrap(); + let source = "var w = new Window('dialog', 'Title');"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "dialog.js"})).unwrap().unwrap(); assert_eq!(fields(&app, KIND)["reaches"]["outside"], json!([])); let texts = dialog_texts(&mut app); assert!(texts.iter().any(|t| t == script_check::need_label("dialogs").unwrap()), "{texts:?}"); From 63706325221f6072b18024fe1b857a697de48d6b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:27:12 -0800 Subject: [PATCH 27/91] Scripts: the blendingMode test catches each refused value in the script Each invalid assignment is now caught inside the script, and the mode is read right after it, so a setter that changed the mode before throwing fails the test instead of being hidden by the run's rollback. --- crates/engine/src/tests/script_dom.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 07131a18e9..ae7faace45 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -306,8 +306,19 @@ fn blending_mode_reads_and_sets_the_objects_blend_mode() { for value in ["'BlendModes.SCREEN '", "'MULTIPLY'", "'Multiply'", "'BlendModes.multiply'", "'BlendModes.NOPE'", "5", "null", "ZOrderMethod.BRINGTOFRONT"] { - let e = failure(&mut s, &format!("app.activeDocument.pageItems[1].blendingMode = {value};")); + // The error is caught in the script, so the run does not roll back and the mode read right + // after it is the one the setter left. + let out = log( + &mut s, + &format!( + "var i = app.activeDocument.pageItems[1], e = '';\ + try {{ i.blendingMode = {value}; }} catch (x) {{ e = String(x); }}\ + vc.log(e); vc.log(i.blendingMode);" + ), + ); + let e = out[0].as_str().unwrap_or_default(); assert!(e.contains("blendingMode needs a BlendModes value"), "{value}: {e}"); + assert_eq!(out[1], json!("BlendModes.COLORBLEND"), "{value}"); assert_eq!((blend(&s, a), undo_steps(&s)), (before, steps), "{value}"); } } From 5220c3ce4b29e18f132121f4007ad84489e966db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:25:40 -0800 Subject: [PATCH 28/91] Plug-ins: importer type and images past the canvas open nothing Type or an image an importer at API level 4 returns that reaches more than 4,000,000 pt from the origin is refused, as the document would drop it on the next open. plugin.list's description and docs/mcp.md name outputKinds and API level 4. --- crates/engine/src/cmd/fileio/importer.rs | 6 +++++- crates/engine/src/cmd/plugin.rs | 2 +- crates/engine/tests/plugin_import.rs | 8 +++++++- docs/mcp.md | 5 ++++- docs/plugins.md | 2 +- 5 files changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index 95a00dc4b9..c578dece5d 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -277,7 +277,8 @@ pub(super) fn load(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value) -> Resu /// that one layer when there are none. Paths are made as a filter's new ones are (their effects let /// in by `admit`), type is laid out, and each image is stored in the document as a PNG of its /// pixels. A warning for type whose font isn't there, or doesn't have its style, goes to `warnings`. -/// Returns the objects' ids in order. +/// An object that reaches more than [`MAX_COORD`] from the origin is an error. Returns the objects' +/// ids in order. fn build( doc: &mut Document, objects: Vec, @@ -312,6 +313,9 @@ fn build( } ImportObject::Image(im) => image_node(doc, im).map_err(|e| e.to_string())?, }; + if node.geometric_bounds().is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)) { + return Err(format!("plug-in output: {at}: it reaches more than {MAX_COORD} pt from the origin")); + } ids.push(node.id); if let Some(list) = owner.get(i).and_then(|&li| members.get_mut(li)) { list.push(Arc::new(node)); diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 30860199fc..3d9a3a8240 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1863,7 +1863,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), outputKinds?: [\"type\"|\"image\"|\"layer\"|\"artboard\"] (what an importer at API level 4 returns besides paths, see docs/plugins.md), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 4), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index c8c740af8b..b64dde61bf 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -537,7 +537,7 @@ fn an_api_4_importer_opens_type_images_layers_and_artboards() { } /// An importer at API level 4 that lists only some kinds: output with another kind, a malformed -/// image or a bad layer opens nothing and leaves the open document as it was; a blank document of +/// image, a bad layer, or an image or type that reaches past the canvas opens nothing and leaves the open document as it was; a blank document of /// artboards alone opens. #[test] fn rich_output_that_fails_its_checks_changes_nothing() { @@ -548,10 +548,16 @@ fn rich_output_that_fails_its_checks_changes_nothing() { short["objects"][1]["pixelsBase64"] = json!(vectorcraft_format::base64_encode(&PIXELS[..4])); let mut twice = rich_output(); twice["layers"][1]["objects"] = json!([0, 2]); + let mut wide = rich_output(); + wide["objects"][1]["transform"] = json!([4000000, 0, 0, 1, 0, 0]); + let mut far = rich_output(); + far["objects"][0]["transform"] = json!([1, 0, 0, 1, 4000000, 40]); let cases = [ (rich_output(), "`artboard`"), (short, "= 8 bytes"), (twice, "exactly one layer"), + (wide, "objects[1]: it reaches more than 4000000 pt"), + (far, "objects[0]: it reaches more than 4000000 pt"), (json!({"objects": [], "layers": [{"name": "A\u{202E}B"}]}), "text direction"), ]; for (mut output, says) in cases { diff --git a/docs/mcp.md b/docs/mcp.md index b3cea3265f..39a0afeb66 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13867,7 +13867,10 @@ with `read: true`, and `openExtensions` holds the extensions File › Open opens extension, with the installed importer that lists the extension (the one whose id sorts first, when several do). `importer` names the importer to use, which must list the file's extension, also one a built-in format reads, such as `svg`. The importer is given at most 128 MiB of the file; its objects become a new document whose artboard is -their bounds, Save then asks for a name, and `warnings` holds the importer's warnings. An importer whose manifest sets +their bounds, Save then asks for a name, and `warnings` holds the importer's warnings. An importer at plug-in API +level 4 whose manifest lists `outputKinds` (in its `plugin.list` entry) may also return point type, embedded images, +top-level layers and artboards, which replace the one around the art; output that fails a check, or an image or type +that reaches more than 4,000,000 pt from the origin, opens nothing (see docs/plugins.md). An importer whose manifest sets `place` (`place: true` in `document.formats` and `plugin.list`) also places its files: `file.place`, `file.place.info` and `file.place.queue` take `importer?: "plugin."` (one that sets `place` and lists the file's extension) and `params?`, and without `importer` a file no built-in format reads goes to the first such importer by id that lists its diff --git a/docs/plugins.md b/docs/plugins.md index 7c5155b0d1..7552a6886e 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -1105,7 +1105,7 @@ error names the kind. An importer that lists no kinds is read as before, and the `name`. All the images of one output hold at most 33,554,432 bytes of RGBA. The host checks both limits from the sizes the images give, and the length of `pixelsBase64`, before it decodes any pixels. - `transform` is six finite numbers `[a, b, c, d, e, f]` within ±4,000,000 that don't flatten the object; left out, - the identity. + the identity. Type or an image that then reaches more than 4,000,000 pt from the origin is refused. - `layers` (kind `layer`): 1–256 top-level layers, bottom first. Each has a `name`, `visible` (default `true`), `locked` (default `false`) and `objects`, the indexes of its objects in `objects` in increasing order. Every object is in exactly one layer, and a layer may hold none. Without `layers`, every object goes in one layer. From 3ac7c97f091d7b4878ba71e3de4767afa3f5f60a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:43:20 -0800 Subject: [PATCH 29/91] Scripts: graph opacity and blend checks read only the edited object's graph The checks behind `opacity` and `blendingMode` assignments, and the captures `object.setProps` runs for object opacity and blend mode, now find an object's graph series or label kind through its parents instead of walking the whole document. Assigning modes to many objects no longer costs a pass over the document for each one. A new test covers a blend mode a graph mark or axis label already has, in an open layer and in a hidden or locked one. --- crates/engine/src/cmd/graph/series.rs | 58 +++++++++++++++++++++------ crates/engine/src/tests/script_dom.rs | 46 +++++++++++++++++++++ 2 files changed, 91 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index c79f795b50..3ea811392d 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -576,23 +576,36 @@ struct ObjectOpacity { knockout_shape: bool, } +/// The series `id` belongs to when it is a graph series group or a path directly in one, as [`series_members`] finds +/// it. Looked up through its parents, with no pass over the document. +fn series_group_or_mark(doc: &Document, id: NodeId) -> Option { + let node = doc.node(id)?; + let chain = doc.ancestry(id)?; + let parent = doc.node(*chain.iter().rev().nth(1)?)?; + let in_graph = |group: &Node, graph: &Node| { + let index = group.extras().series_index.and_then(|i| usize::try_from(i).ok())?; + graph.extras().graph.as_deref().filter(|spec| index < series_count(spec)).map(|_| SeriesRef { graph: graph.id, group: group.id, index }) + }; + if let Some(r) = in_graph(node, parent) { + return Some(r); + } + // Only the paths the graph draws again, not the copy of a graph design. + if !matches!(node.kind, NodeKind::Path { .. }) { + return None; + } + in_graph(parent, doc.node(*chain.iter().rev().nth(2)?)?) +} + /// The graph, series, whether it is the series group itself (`true`) or a path directly in it, and the object -/// transparency of each of `edited` that is one of those, in order. +/// transparency of each of `edited` that is one of those, in order. Each object is looked up through its parents +/// ([`series_group_or_mark`]), so an edit of a few objects does not read the rest of the document. fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, bool, ObjectOpacity)> { - if edited.is_empty() { - return Vec::new(); - } - let members = series_members(doc); - if members.is_empty() { - return Vec::new(); - } edited .iter() .filter_map(|id| { - let r = members.get(id)?; + let r = series_group_or_mark(doc, *id)?; let group = r.group == *id; - // Only the series group and the paths the graph draws again, not the copy of a graph design. - let node = doc.node(*id).filter(|n| group || (doc.parent_of(*id) == Some(r.group) && matches!(n.kind, NodeKind::Path { .. })))?; + let node = doc.node(*id)?; let mut look = ObjectOpacity { opacity: (node.opacity < 1.0).then_some(node.opacity), blend: (node.blend != BlendMode::Normal).then_some(node.blend), @@ -675,6 +688,25 @@ fn graph_labels(doc: &Document) -> HashMap { out } +/// The graph and kind of generated label `id`, as [`graph_labels`] finds it. Only the graphs among its parent and +/// grandparent are read, with no pass over the document; `own` keeps each graph's labels read so far. +fn graph_label_of(doc: &Document, id: NodeId, own: &mut HashMap>) -> Option<(NodeId, Role)> { + if !doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) { + return None; + } + let chain = doc.ancestry(id)?; + // The nearer graph first: [`graph_labels`] visits it later, so its entry is the one kept. + for graph in chain.iter().rev().skip(1).take(2) { + let Some(n) = doc.node(*graph) else { continue }; + let Some(spec) = n.extras().graph.as_deref() else { continue }; + let labels = own.entry(*graph).or_insert_with(|| own_labels(n, spec).into_iter().collect()); + if let Some(role) = labels.get(&id) { + return Some((*graph, *role)); + } + } + None +} + /// The generated labels of graph `n` (with spec `g`) and what each shows, as [`graph_labels`] finds them. fn own_labels(n: &Node, g: &GraphSpec) -> Vec<(NodeId, Role)> { let mut out = vec![]; @@ -1725,9 +1757,9 @@ fn label_rows_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, Role, Option)> = vec![]; - for (&(g, role), n) in ids.iter().rev().filter_map(|id| Some((labels.get(id)?, doc.node(*id)?))) { + for ((g, role), n) in ids.iter().rev().filter_map(|id| Some((graph_label_of(doc, *id, &mut own)?, doc.node(*id)?))) { if !picked.iter().any(|(pg, pr, _)| *pg == g && *pr == role) { picked.push((g, role, label_rows(n))); } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ae7faace45..f535d65ebb 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -260,6 +260,52 @@ fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { assert_eq!(kept(&s), None); } +/// A blend mode a graph mark or axis label already has still replaces the blend mode another object +/// of its series or kind left on the graph, and is refused in a hidden or locked layer. +#[test] +fn a_blend_mode_a_graph_mark_or_label_already_has_replaces_the_one_the_graph_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let r = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let spec = |s: &Session| s.active().unwrap().doc.node(id).unwrap().extras().graph.as_deref().unwrap().clone(); + let kept_mark = |s: &Session| spec(s).series_paints.first().and_then(|p| p.blend); + let kept_label = |s: &Session| spec(s).label_styles.values_rows.as_ref().and_then(|r| r.paint.blend); + let graph = s.active().unwrap().doc.node(id).unwrap().clone(); + let group = graph.children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + let marks: Vec = group.children().unwrap().iter().map(|m| m.id).collect(); + let axes = graph.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Axes")).unwrap().clone(); + // The value axis numbers come first among the Axes group's labels. + let labels: Vec = axes.children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Text(_))).map(|c| c.id).collect(); + s.execute("object.setProps", &json!({"id": marks[0].0, "blend": "Multiply"})).unwrap(); + s.execute("object.setProps", &json!({"id": labels[0].0, "blend": "Screen"})).unwrap(); + let both = (Some(vectorcraft_color::BlendMode::Multiply), Some(vectorcraft_color::BlendMode::Screen)); + assert_eq!((kept_mark(&s), kept_label(&s)), both); + s.execute("object.setProps", &json!({"id": marks[1].0, "name": "mark"})).unwrap(); + s.execute("object.setProps", &json!({"id": labels[1].0, "name": "label"})).unwrap(); + let layer = s.active().unwrap().doc.layers[0].id; + for (on, off) in [ + (json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})), + (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), + ] { + s.execute("object.setProps", &on).unwrap(); + for name in ["mark", "label"] { + let steps = undo_steps(&s); + let e = failure(&mut s, &format!("var m = app.activeDocument.pageItems.getByName('{name}'); m.blendingMode = m.blendingMode;")); + assert!(e.contains("Cannot edit"), "{on} {name}: {e}"); + assert_eq!((kept_mark(&s), kept_label(&s)), both, "{on} {name}"); + assert_eq!(undo_steps(&s), steps, "{on} {name}"); + } + s.execute("object.setProps", &off).unwrap(); + } + log( + &mut s, + "var p = app.activeDocument.pageItems; p.getByName('mark').blendingMode = BlendModes.NORMAL; p.getByName('label').blendingMode = BlendModes.NORMAL;", + ); + assert_eq!((kept_mark(&s), kept_label(&s)), (None, None)); +} + /// Assigning an item the opacity it reports, rounded to four decimals, changes nothing. #[test] fn assigning_the_reported_opacity_changes_nothing() { From 9c74e2f3ba6070c758971c5bc40cc6c824071f40 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:04:58 -0800 Subject: [PATCH 30/91] Scripts: the host name table lists only the members the host defines --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 448e558c32..e12077408e 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -100,7 +100,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= textFrames textFrames= toString \ + rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= textFrames toString \ typename views views= width", ), ("Layer.", "prototype"), From 46c3e4bcff3ede242e8ed32bec591a50e9778998 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:43:17 -0800 Subject: [PATCH 31/91] Scripts: text and thread tests read frames topmost first, as pageItems lists them --- crates/engine/src/script/dom/text/threads.rs | 2 +- crates/engine/src/tests/script_text.rs | 10 +-- crates/engine/src/tests/script_threads.rs | 74 ++++++++++---------- docs/mcp.md | 4 +- 4 files changed, 45 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs index cfdb4119c6..e96282ba93 100644 --- a/crates/engine/src/script/dom/text/threads.rs +++ b/crates/engine/src/script/dom/text/threads.rs @@ -14,7 +14,7 @@ //! - A `Story` is the story of the frame it was read from as that frame is threaded now; when the //! frame is deleted, it throws `Stale story`. //! - `document.stories` lists one story for each type object in no thread and one for each thread, -//! in the paint order of their first frames. `index` with a string finds the first story whose +//! in the order of their first frames in `document.textFrames`, topmost first. `index` with a string finds the first story whose //! first frame has that name. //! - The text of a story of two or more frames is its frames' text in thread order. Its ranges keep //! their place through edits made through them, as a frame's ranges do, and are stale after any diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a357ecfe40..e711768477 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -62,7 +62,7 @@ fn text_frames_add_point_area_and_path_type() { var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ vc.log(pt.typename); vc.log(pt instanceof TextFrame && pt instanceof PageItem);\ - vc.log(d.textFrames[3].contents); vc.log(d.textFrames[9] === undefined);\ + vc.log(d.textFrames[0].contents); vc.log(d.textFrames[9] === undefined);\ vc.log(at.orientation); vc.log(d.textFrames.parent.typename);", ); assert_eq!(out[0], json!(4)); @@ -492,16 +492,16 @@ fn collections_of_text_add_words_characters_and_paragraphs() { let (mut s, id) = doc_with("ab"); s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); let before = undo_steps(&s); - let out = log(&mut s, "var n = app.activeDocument.textFrames[1].words.add(''); vc.log([n.length, n.start]);"); + let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); assert_eq!(out, vec![json!([0, 5])]); for (call, want) in [ ("t.words.add(null)", "contents must be a string or a number"), ("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"), ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), - ("t.words.add('x', app.activeDocument.textFrames[0])", "same text frame"), + ("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"), ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), ] { - let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[1]; {call};")); + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};")); assert!(e.contains(want), "{call}: {e}"); } assert_eq!(undo_steps(&s), before); @@ -586,7 +586,7 @@ fn type_made_with_a_large_id_is_the_new_type() { fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[1]);"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[0]);"); assert!(e.contains("this is not a TextFrame"), "{e}"); let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); assert!(e.contains("this is not a TextRange"), "{e}"); diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs index 433cc041e7..c8f5737dfc 100644 --- a/crates/engine/src/tests/script_threads.rs +++ b/crates/engine/src/tests/script_threads.rs @@ -73,14 +73,14 @@ fn stories_list_one_story_for_each_thread_and_each_frame_in_none() { area(&mut s, 400.0, 120.0, 40.0, "Alone"); let out = log( &mut s, - "var d = app.activeDocument, st = d.stories[0];\ + "var d = app.activeDocument, st = d.stories[1];\ vc.log(d.stories.length); vc.log(st.typename); vc.log(st.textFrames.length);\ vc.log(st.textFrames[0].nextFrame.previousFrame.contents === st.textFrames[0].contents);\ vc.log(st.textFrames[1].nextFrame === null && st.textFrames[0].previousFrame === null);\ - vc.log(d.stories[1].textFrames[0].contents); vc.log(d.stories[1].textFrames.length);\ + vc.log(d.stories[0].textFrames[0].contents); vc.log(d.stories[0].textFrames.length);\ d.textFrames.add(); vc.log(d.stories.length);\ vc.log(d.stories.parent.typename); vc.log(st.parent.typename); vc.log(d.stories.typename);\ - vc.log(d.textFrames[2].story.textFrames[0].contents);", + vc.log(d.textFrames[1].story.textFrames[0].contents);", ); assert_eq!( out, @@ -262,9 +262,9 @@ fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() { let before = undo_steps(&s); let out = log( &mut s, - "var t = app.activeDocument.textFrames; t[0].nextFrame = t[1];\ - vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[0].story.textRange.contents);\ - t[0].nextFrame = t[1];", + "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];\ + vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[2].story.textRange.contents);\ + t[2].nextFrame = t[1];", ); assert_eq!(out, vec![json!(2), json!("First story.Second."), json!("First story.Second.")]); assert_eq!(threads(&s), vec![vec![a, b]]); @@ -275,7 +275,7 @@ fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() { s.execute("edit.undo", &json!({})).unwrap(); assert!(threads(&s).is_empty()); assert_eq!((plain(&s, a), plain(&s, b)), ("First story.".into(), "Second.".into())); - log(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); + log(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[1];"); assert_eq!(threads(&s), vec![vec![b, a]]); assert_eq!(story(&s, &[b, a]), "Second.First story."); } @@ -287,9 +287,9 @@ fn null_breaks_the_link_and_each_frame_keeps_its_text() { let before = undo_steps(&s); let out = log( &mut s, - "var t = app.activeDocument.textFrames, st = t[1].story; t[1].previousFrame = null;\ - vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[0].nextFrame);\ - t[0].nextFrame = null;", + "var t = app.activeDocument.textFrames, st = t[0].story; t[0].previousFrame = null;\ + vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[1].nextFrame);\ + t[1].nextFrame = null;", ); assert_eq!(out, vec![json!(2), json!(1), json!(null)]); assert!(threads(&s).is_empty()); @@ -310,9 +310,9 @@ fn area_and_path_text_thread_the_new_frame_to_a_base_frame() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems, base = d.textFrames[0];\ - var after = d.textFrames.areaText(p[1], undefined, base);\ - var first = d.textFrames.areaText(p[2], TextOrientation.HORIZONTAL, base, false);\ - var last = d.textFrames.pathText(p[3], undefined, undefined, undefined, after, true);\ + var after = d.textFrames.areaText(p[2], undefined, base);\ + var first = d.textFrames.areaText(p[1], TextOrientation.HORIZONTAL, base, false);\ + var last = d.textFrames.pathText(p[0], undefined, undefined, undefined, after, true);\ vc.log(base.story.textFrames.length); vc.log(base.previousFrame.kind); vc.log(after.nextFrame.kind); vc.log(d.stories.length);", ); assert_eq!(out, vec![json!(4), json!("TextType.AREATEXT"), json!("TextType.PATHTEXT"), json!(1)]); @@ -330,9 +330,9 @@ fn a_bad_base_frame_is_refused_before_a_frame_is_made() { let count = |s: &Session| s.active().unwrap().doc.node_count(); let (n, before) = (count(&s), undo_steps(&s)); let d = "var d = app.activeDocument, p = d.pageItems;"; - assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, d.textFrames[0]);")).contains("only area type")); - assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, p[1]);")).contains("baseFrame must be a TextFrame")); - assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, d.textFrames[0], 'yes');")).contains("postFix")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0]);")).contains("only area type")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, p[0]);")).contains("baseFrame must be a TextFrame")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0], 'yes');")).contains("postFix")); assert_eq!((count(&s), undo_steps(&s)), (n, before)); } @@ -389,9 +389,9 @@ fn a_link_to_the_frame_itself_is_refused() { fn a_link_that_makes_a_loop_is_refused() { let (mut s, ids) = three(); let before = state(&s, &ids); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];"); assert!(m.contains("loop"), "{m}"); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];"); assert!(m.contains("loop"), "{m}"); unchanged(&s, &ids, &before); } @@ -400,9 +400,9 @@ fn a_link_that_makes_a_loop_is_refused() { fn a_link_into_the_middle_of_a_story_is_refused() { let (mut s, ids) = three(); let before = state(&s, &ids); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];"); assert!(m.contains("already has a previous frame"), "{m}"); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[0];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].previousFrame = t[3];"); assert!(m.contains("already has a next frame"), "{m}"); unchanged(&s, &ids, &before); } @@ -411,13 +411,13 @@ fn a_link_into_the_middle_of_a_story_is_refused() { fn point_type_and_other_values_cannot_be_linked() { let (mut s, ids) = three(); let before = state(&s, &ids); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];"); assert!(m.contains("only area type"), "{m}"); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); assert!(m.contains("only area type"), "{m}"); - let m = failure(&mut s, "app.activeDocument.textFrames[2].nextFrame = 5;"); + let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = 5;"); assert!(m.contains("TypeError") && m.contains("TextFrame or null"), "{m}"); - let m = failure(&mut s, "app.activeDocument.textFrames[2].nextFrame = undefined;"); + let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = undefined;"); assert!(m.contains("TextFrame or null"), "{m}"); unchanged(&s, &ids, &before); } @@ -425,11 +425,11 @@ fn point_type_and_other_values_cannot_be_linked() { #[test] fn a_hidden_or_locked_frame_in_either_story_stops_a_link() { let (mut s, ids) = three(); - log(&mut s, "app.activeDocument.textFrames[1].locked = true;"); + log(&mut s, "app.activeDocument.textFrames[2].locked = true;"); let before = state(&s, &ids); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];"); assert!(m.contains("hidden or locked"), "{m}"); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].nextFrame = null;"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].nextFrame = null;"); assert!(m.contains("hidden or locked"), "{m}"); unchanged(&s, &ids, &before); } @@ -441,12 +441,12 @@ fn a_frame_of_another_document_cannot_be_linked() { s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); area(&mut s, 10.0, 100.0, 40.0, "Elsewhere"); s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 80, "height": 60})).unwrap(); - let m = failure(&mut s, "app.documents[0].textFrames[2].nextFrame = app.documents[1].textFrames[0];"); + let m = failure(&mut s, "app.documents[0].textFrames[1].nextFrame = app.documents[1].textFrames[0];"); assert!(m.contains("different documents"), "{m}"); let out = log( &mut s, - "var d = app.documents[1], p = d.pageItems[1];\ - try { d.textFrames.areaText(p, undefined, app.documents[0].textFrames[2]); } catch (e) { vc.log(String(e.message)); }\ + "var d = app.documents[1], p = d.pageItems[0];\ + try { d.textFrames.areaText(p, undefined, app.documents[0].textFrames[1]); } catch (e) { vc.log(String(e.message)); }\ vc.log(p.typename); vc.log(d.textFrames.length);", ); assert_eq!(out, vec![json!("baseFrame: the frame is in another document"), json!("PathItem"), json!(1)]); @@ -457,16 +457,16 @@ fn a_frame_of_another_document_cannot_be_linked() { #[test] fn a_deleted_frame_makes_its_story_and_links_stale() { let (mut s, _, _) = threaded(STORY); - let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], st = f.story; f.remove(); st.length;"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.length;"); assert!(m.contains("Stale story"), "{m}"); - let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], st = f.story; f.remove(); st.lines;"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.lines;"); assert!(m.contains("Stale story"), "{m}"); - let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], g = app.activeDocument.textFrames[1]; g.remove(); f.nextFrame = g;"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], g = app.activeDocument.textFrames[0]; g.remove(); f.nextFrame = g;"); assert!(m.contains("Stale page item"), "{m}"); - let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], r = f.story.textRange; f.remove(); r.contents;"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], r = f.story.textRange; f.remove(); r.contents;"); assert!(m.contains("Stale text range"), "{m}"); // A story read from a frame that stays follows it when its link is broken. - let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[1].story; t[0].nextFrame = null; vc.log(st.textFrames.length);"); + let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[0].story; t[1].nextFrame = null; vc.log(st.textFrames.length);"); assert_eq!(out, vec![json!(1)]); } @@ -481,7 +481,7 @@ fn stories_refuse_bad_keys_and_huge_numbers() { assert!(failure(&mut s, "app.activeDocument.stories.index(1e20);").contains("Not found")); assert!(failure(&mut s, "app.activeDocument.stories.index('nobody');").contains("Not found")); assert!(failure(&mut s, "app.activeDocument.stories.index({});").contains("TypeError")); - log(&mut s, "app.activeDocument.textFrames[0].name = 'Lead';"); + log(&mut s, "app.activeDocument.textFrames[1].name = 'Lead';"); assert_eq!(log(&mut s, "vc.log(app.activeDocument.stories.index('Lead').textFrames.length);"), vec![json!(2)]); } @@ -537,7 +537,7 @@ fn stories_of_threads_that_share_a_frame_keep_their_own_text() { let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); let c = area(&mut s, 300.0, 120.0, 60.0, "Three!"); std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b], vec![b, c]]; - let out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[2].story.length);"); + let out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[0].story.length);"); let (ab, bc) = (story(&s, &[a, b]).encode_utf16().count(), story(&s, &[b, c]).encode_utf16().count()); assert_ne!(ab, bc); assert_eq!(out, vec![json!(ab), json!(bc)]); diff --git a/docs/mcp.md b/docs/mcp.md index d9ca3ba49e..772917dad0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2912,8 +2912,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot that would make a loop and a story with a hidden or locked frame are refused with nothing changed, and assigning the link that is already there, or `null` where there is none, runs no command. `postFix` is true when it is left out, and a `baseFrame` given with a path inside a compound path is refused before the path is turned into type. - `Document.stories` lists one story for each type object in no thread and one for each thread, in the paint order of - their first frames, and `index` with a string finds the first story whose first frame has that name. A frame that + `Document.stories` lists one story for each type object in no thread and one for each thread, in the order of + their first frames in `Document.textFrames`, topmost first, and `index` with a string finds the first story whose first frame has that name. A frame that a stored thread lists twice is in its story once. A `Story` is the story of the frame it was read from, as that frame is threaded now, and throws `Stale story` once that frame is deleted. The text of a story of one frame is that frame's text, with its ranges. The text of a longer story is its From 55e323ce3a1ebe68fe34eb48550adc3109b1b443 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:45:08 -0800 Subject: [PATCH 32/91] Command dialogs: restrict edits to their target document --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/command.rs | 62 +++++++++++++++++++++++-- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 5 ++ docs/target-app-parity.md | 2 + 5 files changed, 68 insertions(+), 5 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index fa2bc204f6..7394f0ea07 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -988,7 +988,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 97965e26dc..720bf3cbac 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -44,6 +44,8 @@ struct Open { preview: LivePreview, /// Set Role Swatch: the role the Swatch row was last filled for. filled_for: Option, + /// The document whose objects the dialog edits, when its caller supplies `__doc`. + doc: Option, /// Names this dialog's own open among reopenings of the same command, for its OK and Cancel. token: Arc<()>, } @@ -66,10 +68,16 @@ impl Setting { } /// Opens the parameter dialog of `command`, headed `label`, on `params` (a menu item's own values, `__params` for the -/// fixed ones and `__rowGutterLinked` for Area Type Options' linked Row Gutter). +/// fixed ones, `__rowGutterLinked` for Area Type Options' linked Row Gutter, and `__doc` for a document uid). pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut params: Map) -> Result { + let doc = match params.remove("__doc") { + None => None, + Some(value) => Some(value.as_u64().ok_or("`__doc` must be a document id")?), + }; let ctx = app.ui_ctx.clone().ok_or("no window")?; - if let Some(old) = app.command_dialog.open.take() { + if let Some(old) = app.command_dialog.open.take() + && on_document(app, &old) + { old.preview.cancel(app); } let fixed = match params.remove("__params") { @@ -104,6 +112,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par previews, preview: LivePreview::default(), filled_for: None, + doc, token, }); Ok(Value::Null) @@ -121,6 +130,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } fn step(app: &mut VectorcraftApp, open: &mut Open) { + if !on_document(app, open) { + return; + } let Some(dialogs) = app.dialogs() else { return }; let id = open.id; let seen = dialogs.with(|h| h.get_by_id::(id).map(|d| (d.fields().clone(), d.is_previewing()))); @@ -165,6 +177,9 @@ fn step(app: &mut VectorcraftApp, open: &mut Open) { /// error keeps it open with the reason under its rows. fn confirm(app: &mut VectorcraftApp, token: &Arc<()>, fields: &DialogFields) -> Result { let open = app.command_dialog.open.take_if(|o| Arc::ptr_eq(&o.token, token)).ok_or("the dialog is gone")?; + if !on_document(app, &open) { + return Ok(Value::Null); + } let params = command_params(&open.command, &open.opening, Setting::of(app)); let value = call(&open.command, &open.fixed, open.linked, form::json_of(¶ms, fields)); let result = if open.previews { @@ -185,11 +200,17 @@ fn confirm(app: &mut VectorcraftApp, token: &Arc<()>, fields: &DialogFields) -> /// Cancel: rolls back the preview of the dialog `token` names. fn cancel(app: &mut VectorcraftApp, token: &Arc<()>) { - if let Some(open) = app.command_dialog.open.take_if(|o| Arc::ptr_eq(&o.token, token)) { + if let Some(open) = app.command_dialog.open.take_if(|o| Arc::ptr_eq(&o.token, token)) + && on_document(app, &open) + { open.preview.cancel(app); } } +fn on_document(app: &VectorcraftApp, open: &Open) -> bool { + open.doc.is_none_or(|uid| app.session.active().is_some_and(|st| st.uid == uid)) +} + /// The rows of `command`'s dialog: one per value it opens with that the command takes, in `order(command)` first and /// the rest by name, Area Type Options' Text Flow last. fn command_params(command: &str, opening: &Map, setting: Setting) -> Vec { @@ -742,6 +763,41 @@ mod tests { /// The choices this dialog lists for Rasterize, Create Gradient Mesh and Repeat Options are the /// values their commands take (#8020, #7991): each one runs, and every language with complete + #[test] + fn document_scoped_dialog_confirms_only_in_its_opening_document() { + for (scoped, switch) in [(true, false), (true, true), (false, true)] { + let mut app = windowed(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let mut params = json!({"x": 10, "y": 10, "width": 20, "height": 20}).as_object().unwrap().clone(); + if scoped { + params.insert("__doc".into(), json!(app.session.active().unwrap().uid)); + } + open(&mut app, "shape.rectangle", "Rectangle", params).unwrap(); + pump(&mut app); + if switch { + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + } + answer_ok(&mut app); + assert!(app.command_dialog.open.is_none()); + assert_eq!(app.session.active().unwrap().selection.is_empty(), scoped && switch); + if switch { + assert!(app.session.set_active(0)); + assert!(app.session.active().unwrap().selection.is_empty()); + } + } + } + + #[test] + fn document_scoped_dialog_rejects_an_invalid_document_id() { + for doc in [json!(null), json!("1"), json!(-1), json!(1.5)] { + let mut app = windowed(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let params = json!({"width": 20, "height": 20, "__doc": doc}).as_object().unwrap().clone(); + assert!(open(&mut app, "shape.rectangle", "Rectangle", params).is_err(), "{doc}"); + assert!(app.command_dialog.open.is_none()); + } + } + /// menus has a row for each label. #[test] fn choice_fields_list_the_values_their_commands_take() { diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 7dcbb1d05d..b16211a756 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -989,7 +989,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/docs/mcp.md b/docs/mcp.md index 437569a1f9..c45ba8d7d1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12389,6 +12389,11 @@ the dialog on the last search, with the fields its `params` give in its place. A the wrong type is an error that leaves the dialog closed. Once it is open, `ui.dialog.confirm` with a field of the wrong type runs no action and returns the error. +For other command dialogs, `params.__doc` can supply a document uid. The dialog previews and confirms only while +that document is active. Confirming after a document switch closes the dialog without running its command. +Canceling or replacing that dialog does not cancel an interaction in another document. A supplied `__doc` must be +an unsigned integer; omitting it preserves the command dialog's existing behavior. + ## Justification options diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 043ae5c403..d20559a4c6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -32,6 +32,8 @@ ## Feature submission evidence +- Command dialogs can keep the uid of the document they edit. Their preview, confirmation, and cancellation do not change another active document. Tests cover confirmation in the original and another document, unscoped dialogs, and invalid document ids. + Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. From f64d743ffb42b6ef64ef5253a3a5ed28f16b67b2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:38:17 -0800 Subject: [PATCH 33/91] Importers: validate paths, artboards, and placed bounds --- crates/engine/src/cmd/place.rs | 5 +++- crates/engine/tests/plugin_import.rs | 25 +++++++++++----- crates/engine/tests/plugin_place.rs | 32 ++++++++++++++++++++ crates/plugins/src/import.rs | 45 ++++++++++++++++++++++++++-- docs/mcp.md | 10 +++++-- docs/plugins.md | 7 +++-- docs/target-app-parity.md | 4 +-- 7 files changed, 110 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index e787899cd2..73dc4e3603 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its objects, guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; transformed art must stay within ±4,000,000 pt on either axis, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -864,6 +864,9 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { Affine::translate(c - natural.center()) } }; + if !crate::sanity::rect_in_range(m.transform_rect_bbox(natural)) { + return Err(bad(PLACE, "placed art lies outside the canvas")); + } let parent = st.insertion_parent(); let below = st.current_layer().or_else(|| parent.and_then(|p| st.doc.layer_of(p))); let link = loaded.link.take().filter(|_| bool_or(p, "link", true)); diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index b64dde61bf..8bac66a4d3 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -472,9 +472,13 @@ fn rich_output() -> Value { } /// The active document's layers (name, shown, locked, kinds of its objects), its artboards (name -/// and rectangle), its type (text, family, size, fill) and the RGBA of its first image. +/// and rectangle), its type (text, family, size, fill), the RGBA of its first image, and the transforms +/// of its text and images. #[allow(clippy::type_complexity)] -fn structure(s: &Session) -> (Vec<(String, bool, bool, Vec<&'static str>)>, Vec<(String, [f64; 4])>, Vec<(String, String, f64, String)>, Vec) { +fn structure( + s: &Session, +) -> (Vec<(String, bool, bool, Vec<&'static str>)>, Vec<(String, [f64; 4])>, Vec<(String, String, f64, String)>, Vec, Vec<(&'static str, [f64; 6])>) +{ let d = &s.doc().unwrap().doc; let kind = |n: &vectorcraft_doc::Node| match &n.kind { vectorcraft_doc::NodeKind::Text(_) => "type", @@ -488,21 +492,25 @@ fn structure(s: &Session) -> (Vec<(String, bool, bool, Vec<&'static str>)>, Vec< .map(|l| (l.name.clone().unwrap_or_default(), l.visible, l.locked, l.children().unwrap().iter().map(|c| kind(c)).collect())) .collect(); let boards = d.artboards.iter().map(|a| (a.name.clone(), [a.rect.x0, a.rect.y0, a.rect.x1, a.rect.y1])).collect(); - let (mut types, mut pixels) = (Vec::new(), Vec::new()); + let (mut types, mut pixels, mut transforms) = (Vec::new(), Vec::new(), Vec::new()); d.walk(|n| match &n.kind { vectorcraft_doc::NodeKind::Text(t) => { + transforms.push(("type", t.xf.as_coeffs())); let st = &t.runs[0].style; let text: String = t.runs.iter().map(|r| r.text.as_str()).collect(); types.push((text, st.font_family.clone(), st.size, serde_json::to_string(&st.fill).unwrap())); } - vectorcraft_doc::NodeKind::Image(_) if pixels.is_empty() => { + vectorcraft_doc::NodeKind::Image(im) => { + transforms.push(("image", im.xf.as_coeffs())); // Read back through the filter input's own decoder, not the importer's. - let o = vectorcraft_plugins::objects::encode_read_only(d, n).unwrap(); - pixels = vectorcraft_format::base64_decode(o["pixelsBase64"].as_str().unwrap()).unwrap(); + if pixels.is_empty() { + let o = vectorcraft_plugins::objects::encode_read_only(d, n).unwrap(); + pixels = vectorcraft_format::base64_decode(o["pixelsBase64"].as_str().unwrap()).unwrap(); + } } _ => {} }); - (layers, boards, types, pixels) + (layers, boards, types, pixels, transforms) } /// An importer at API level 4 that lists every output kind opens editable type, an embedded image, @@ -525,6 +533,7 @@ fn an_api_4_importer_opens_type_images_layers_and_artboards() { assert_eq!(opened.1, [("Front".to_string(), [0.0, 0.0, 200.0, 100.0]), ("Back".to_string(), [220.0, 0.0, 420.0, 100.0])]); assert_eq!(opened.2, [("Hello\nWorld".to_string(), "No Such Family Q9617".to_string(), 24.0, blue)]); assert_eq!(opened.3, PIXELS); + assert_eq!(opened.4, [("image", [10.0, 0.0, 0.0, 10.0, 0.0, 100.0]), ("type", [1.0, 0.0, 0.0, 1.0, 10.0, 40.0])]); // The type is laid out at the place the transform gives: its first baseline starts at (10, 40). let d = &s.doc().unwrap().doc; let words = d.layers[1].children().unwrap()[0].clone(); @@ -571,7 +580,7 @@ fn rich_output_that_fails_its_checks_changes_nothing() { rich_echo(&mut s, "test.richboards", r#"["artboard"]"#); let blank = json!({"objects": [], "artboards": [{"name": "Only", "rect": [0, 0, 50, 60]}]}); open(&mut s, "Blank.trc", blank.to_string().as_bytes(), json!({"importer": "plugin.test.richboards"})).unwrap(); - let (layers, boards, types, _) = structure(&s); + let (layers, boards, types, _, _) = structure(&s); assert_eq!((layers.len(), layers[0].3.len(), boards, types.len()), (1, 0, vec![("Only".to_string(), [0.0, 0.0, 50.0, 60.0])], 0)); } diff --git a/crates/engine/tests/plugin_place.rs b/crates/engine/tests/plugin_place.rs index d164219cdb..0319595ced 100644 --- a/crates/engine/tests/plugin_place.rs +++ b/crates/engine/tests/plugin_place.rs @@ -58,6 +58,38 @@ fn state(s: &mut Session) -> (usize, usize, usize, Value) { (d.history.undo.len(), d.history.redo.len(), d.doc.layers.len(), content) } +#[test] +fn placing_importer_checks_the_transformed_bounds_before_editing() { + let image = json!({"objects": [{ + "type": "image", "pixelSize": [1, 1], "pixelsBase64": vectorcraft_format::base64_encode(&[255, 0, 0, 255]), + "transform": [20, 0, 0, 10, 0, 0], + }]}) + .to_string(); + for (index, output, half_width) in [(0, ART, 50.0), (1, image.as_str(), 10.0)] { + let mut s = with_document(); + let mut manifest: Value = serde_json::from_str(&placing(&format!("test.place.canvas{index}"), r#"["tpc"]"#)).unwrap(); + if index == 1 { + manifest["api"] = json!(4); + manifest["outputKinds"] = json!(["image"]); + } + install(&mut s, &tpl::returning(&manifest.to_string(), output)); + let importer = format!("plugin.test.place.canvas{index}"); + let before = state(&mut s); + for at in [[4_000_000.0, 400.0], [-4_000_000.0, 400.0], [400.0, 4_000_000.0], [400.0, -4_000_000.0]] { + for template in [false, true] { + assert!( + place(&mut s, "Art.tpc", b"?", json!({"at": at, "template": template, "importer": importer})).is_err(), + "{index}: {at:?}, template: {template}" + ); + assert_eq!(state(&mut s), before); + } + } + let inside = place(&mut s, "Art.tpc", b"?", json!({"at": [4_000_000.0 - half_width, 400.0], "importer": importer})); + assert!(inside.is_ok(), "{index}: {inside:?}"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.0 + 1); + } +} + /// A placed group: its name, the names of its children, and its bounds as `(x0, y0, x1, y1)`. type Placed = (Option, Vec>, (f64, f64, f64, f64)); diff --git a/crates/plugins/src/import.rs b/crates/plugins/src/import.rs index 03e853d879..97784d6b01 100644 --- a/crates/plugins/src/import.rs +++ b/crates/plugins/src/import.rs @@ -298,6 +298,17 @@ pub fn decode_with(bytes: &[u8], kinds: &[OutputKind]) -> Result { }; (objects, layers, artboards) }; + for (i, object) in objects.iter().enumerate() { + if let ImportObject::Path(path) = object { + let at = format!("objects[{i}]"); + if path.id.is_some() { + return Err(out_err(&at, "an importer returns new paths without `id`")); + } + if path.path.is_none() { + return Err(out_err(&at, "an imported path must include its geometry in `path`")); + } + } + } if objects.is_empty() && layers.is_empty() && artboards.is_empty() { return Err(Error::Output("the importer returned no objects".into())); } @@ -581,11 +592,12 @@ fn decode_artboards(v: &Value) -> Result> { let r = o.get("rect").and_then(Value::as_array).filter(|r| r.len() == 4).ok_or_else(wrong)?; let n: Vec = r.iter().map(Value::as_f64).collect::>().ok_or_else(wrong)?; let (x, y, w, h) = (n[0], n[1], n[2], n[3]); + let (x1, y1) = (x + w, y + h); let inside = |v: f64| v.is_finite() && v.abs() <= MAX_COORD; - if !(w > 0.0 && h > 0.0 && inside(x) && inside(y) && inside(x + w) && inside(y + h)) { + if !(w > 0.0 && h > 0.0 && x1 > x && y1 > y && inside(x) && inside(y) && inside(x1) && inside(y1)) { return Err(wrong()); } - boards.push(OutArtboard { name, rect: Rect::new(x, y, x + w, y + h) }); + boards.push(OutArtboard { name, rect: Rect::new(x, y, x1, y1) }); } Ok(boards) } @@ -668,6 +680,35 @@ mod tests { decode_with(v.to_string().as_bytes(), ALL) } + #[test] + fn importer_output_rejects_filter_only_path_updates() { + let square: Value = serde_json::from_str(SQUARE).unwrap(); + let mut identified = square.clone(); + identified["id"] = json!(3); + for object in [json!({"id": 3}), json!({"type": "path"}), identified] { + let output = json!({"objects": [object]}); + for kinds in [&[OutputKind::Type][..], &[][..]] { + assert!(decode_with(output.to_string().as_bytes(), kinds).is_err(), "{kinds:?}: {output}"); + } + } + let mut untyped = square.clone(); + untyped.as_object_mut().unwrap().remove("type"); + for object in [square, untyped] { + let output = json!({"objects": [object]}); + for kinds in [&[OutputKind::Type][..], &[][..]] { + assert!(decode_with(output.to_string().as_bytes(), kinds).is_ok(), "{kinds:?}: {output}"); + } + } + } + + #[test] + fn importer_output_rejects_artboards_with_collapsed_endpoints() { + for rect in [[1_000_000.0, 0.0, 1e-12, 10.0], [0.0, 1_000_000.0, 10.0, 1e-12]] { + assert!(rich_with(|v| v["artboards"][0]["rect"] = json!(rect)).is_err(), "{rect:?}"); + } + assert!(rich_with(|v| v["artboards"][0]["rect"] = json!([3_999_999.0, 3_999_999.0, 1.0, 1.0])).is_ok()); + } + /// An importer listing every output kind returns type, an embedded image, paths, layers and /// artboards, each read as it was given. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 9798427845..3c8aa304bd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13944,9 +13944,13 @@ and `file.place.queue` take `importer?: "plugin."` (one that sets `place` an `params?`, and without `importer` a file no built-in format reads goes to the first such importer by id that lists its extension. The importer is given at most 128 MiB of the file (a larger file is refused from its size, with `importer` before any of it is read or decoded, and without it after its first 64 KiB are read or decoded) -and `_context.mode` `"place"`; its objects, guides left out, are placed as one group named after the file, in the order -it returned them, as one undo step, embedded whatever `link` says (`linked: false`). `plugin.run` of an importer is -an error that names `document.open`. In the app, File › Open With lists the installed importers, and +and `_context.mode` `"place"`; its visible layers' objects, or all objects when it returns no layers, are placed +as one group named after the file, in the order it returned them, with guides omitted, as one undo step, +embedded whatever `link` says (`linked: false`). `plugin.run` of an importer is +an error that names `document.open`. Placement rejects transformed art beyond ±4,000,000 pt on either axis, +including template placement, before changing the document. An importer returns new paths with geometry and +without object IDs. An artboard's positive width and height must produce distinct finite endpoints within the canvas. +In the app, File › Open With lists the installed importers, and `file.openWith {importer, path?, params?}` opens `path`, or a file picked among the importer's extensions, with one (on the web it opens File › Open's picker) and adds it to Open Recent. With `path` the reply is `document.open`'s result; on the desktop a picked file is read off the UI thread and the reply is `{background: true, status}`, and diff --git a/docs/plugins.md b/docs/plugins.md index 631a341654..74a7b74bda 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -1243,12 +1243,15 @@ error names the kind. An importer that lists no kinds is read as before, and the `locked` (default `false`) and `objects`, the indexes of its objects in `objects` in increasing order. Every object is in exactly one layer, and a layer may hold none. Without `layers`, every object goes in one layer. - `artboards` (kind `artboard`): 1–100 artboards, each with a `name` used once and a `rect`, `[x, y, width, height]` - with a width and height above 0, within ±4,000,000. They replace the one artboard around the art. + with a width and height above 0. Each computed endpoint must differ from its origin and remain within + ±4,000,000. They replace the one artboard around the art. - A `name` (of type, an image, a layer or an artboard) and a font's family and style are each 1–256 characters, not only spaces, without control characters or characters that change the direction of text. - An output whose `objects` is empty opens as a blank document when it has `layers` or `artboards`. - To place (`_context.mode` `"place"`), the objects of the visible layers are placed in one group with their type and - images, the objects of hidden layers are left out, and `artboards` are left out. + images, the objects of hidden layers are left out, and `artboards` are left out. Without layers, all objects are + placed. Transformed art beyond ±4,000,000 pt on either axis is rejected before the edit, including template placement. +- Imported paths require `path` geometry and cannot include an `id`, at every plug-in API level. ## Writing a plug-in in Rust diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index db3cf048e3..2187c300b8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2706,8 +2706,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Exporter plug-ins (G17):** a WebAssembly plug-in of kind `exporter` adds a write-only file format. File › Export › Export As lists it after the built-in formats, with Use Artboards greyed out (the plug-in writes the whole document) and its parameters in a generated dialog once the file is picked; `document.export` writes it by its format id, `plugin.`, or by one of its extensions, and built-in formats keep theirs. The plug-in is given the native file's JSON (large images without their data) and `_context` (`mode`, `extension`, `name`), with 10 G instructions plus 4,000 per byte of input and 300 s, and Background Export's Cancel stops it between two slices of that budget. A decline or invalid output writes nothing; its warnings come back with the export's. Regressions: `crates/engine/tests/plugin_export.rs`, `crates/plugins/tests/abi.rs`, `crates/ui-egui/src/dialogs/tests_plugin_export.rs`. Scores and hours unchanged. - **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. -- **Importer output kinds (G17, VectorCraft's own contract):** an importer at plug-in API level 4 lists in its manifest's `outputKinds` which of `type`, `image`, `layer` and `artboard` it returns besides paths. Its output may then hold point type (text, font family and style, size, fill, transform), embedded RGBA images (stored as PNG in the document), top-level layers with their names, visibility, lock and objects, and named artboards that replace the one around the art; output of artboards or layers alone opens as a blank document. The host checks the whole output before it makes the document: a kind the manifest doesn't list, an image whose bytes aren't 4 × width × height, a name with control or text direction characters, or output past the limits on objects, layers, artboards, text and pixels opens nothing, and the error names the kind or the limit. Importers below level 4 read paths alone, as before. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. -- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`, and its objects are placed as one group named after the file, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. +- **Importer output kinds (G17, VectorCraft's own contract):** an importer at plug-in API level 4 lists in its manifest's `outputKinds` which of `type`, `image`, `layer` and `artboard` it returns besides paths. Its output may then hold point type (text, font family and style, size, fill, transform), embedded RGBA images (stored as PNG in the document), top-level layers with their names, visibility, lock and objects, and named artboards that replace the one around the art; output of artboards or layers alone opens as a blank document. The host checks the whole output before it makes the document: a kind the manifest doesn't list, an image whose bytes aren't 4 × width × height, a name with control or text direction characters, or output past the limits on objects, layers, artboards, text and pixels opens nothing, and the error names the kind or the limit. Imported paths require geometry and cannot name existing object IDs. Positive artboard sizes must produce distinct finite endpoints within the canvas. Importers below level 4 read paths alone, as before. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. +- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`. Its visible layers' objects, or all objects when it returns no layers, are placed as one group named after the file, with guides omitted, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. Transformed art beyond ±4,000,000 pt on either axis is rejected before an edit, including on a template layer. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. - **Plug-in int parameters as sliders (G17):** an `int` parameter with `"widget": "slider"` shows a slider over its range with its number field, in the filter, live-effect and exporter dialogs and in the Appearance panel's effect editor; the manifest is refused at install when the parameter cannot have one. Regressions: `crates/plugins/src/dialog.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`. Scores and hours unchanged. From 77f2c5f4aa7e0dd555d165ddaa69ab5a954fbc5d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:20:34 -0800 Subject: [PATCH 34/91] Clarify importer placement order and validation errors --- crates/engine/src/cmd/place.rs | 2 +- crates/engine/tests/plugin_import.rs | 2 +- docs/mcp.md | 5 +++-- docs/plugins.md | 7 ++++--- docs/target-app-parity.md | 4 ++-- 5 files changed, 11 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 73dc4e3603..2af574ef49 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; transformed art must stay within ±4,000,000 pt on either axis, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; transformed art must stay within ±4,000,000 pt on either axis, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index 8bac66a4d3..11a42a6f90 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -273,7 +273,7 @@ fn failures_open_nothing() { ("test.fail.notjson", "not json", "JSON"), ("test.fail.empty", r#"{"objects":[]}"#, "the importer returned no objects"), ("test.fail.key", r#"{"objects":[],"layers":[]}"#, "an importer returns `objects` and `warnings`, not `layers`"), - ("test.fail.id", r#"{"objects":[{"id":3}]}"#, "is not the id of an input object"), + ("test.fail.id", r#"{"objects":[{"id":3}]}"#, "an importer returns new paths without `id`"), ("test.fail.far", far, "4000000"), ("test.fail.warnings", bad_warnings.as_str(), "`warnings` must be a list of strings"), ]; diff --git a/docs/mcp.md b/docs/mcp.md index 3c8aa304bd..a6b30705a5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13945,8 +13945,9 @@ and `file.place.queue` take `importer?: "plugin."` (one that sets `place` an extension. The importer is given at most 128 MiB of the file (a larger file is refused from its size, with `importer` before any of it is read or decoded, and without it after its first 64 KiB are read or decoded) and `_context.mode` `"place"`; its visible layers' objects, or all objects when it returns no layers, are placed -as one group named after the file, in the order it returned them, with guides omitted, as one undo step, -embedded whatever `link` says (`linked: false`). `plugin.run` of an importer is +as one group named after the file. Layers are placed from bottom to top, with objects in each layer's listed order. +Without layers, objects keep their returned order. Guides are omitted. Placement records one undo step and embeds +the group whatever `link` says (`linked: false`). `plugin.run` of an importer is an error that names `document.open`. Placement rejects transformed art beyond ±4,000,000 pt on either axis, including template placement, before changing the document. An importer returns new paths with geometry and without object IDs. An artboard's positive width and height must produce distinct finite endpoints within the canvas. diff --git a/docs/plugins.md b/docs/plugins.md index 74a7b74bda..88396c2e05 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -62,9 +62,10 @@ importers that set `place`: when no built-in format reads the file, the first su extension reads it, and `"importer": "plugin."` names one, which must set `place` and list the file's extension, also one a built-in format reads. `"params"?: {…}` holds its parameters, which take their defaults when left out. The importer is given at most 128 MiB of the file and `_context.mode` `"place"`, and returns its objects as it does for -File › Open. They are placed in the open document as -one group named after the file, in the order the importer returned them, at the place, size or object `at`, `rect`, -`replace` and `template` give, as one undo step; guides are left out, and the group's box is the bounds of what the +File › Open. The visible layers' objects are placed in the open document as one group named after the file, +from the bottom layer to the top, in each layer's listed object order. Without layers, objects keep their returned +order. The group uses the place, size or object `at`, `rect`, `replace` and `template` give, as one undo step; +guides are left out, and the group's box is the bounds of what the other objects draw. The file is embedded whatever `link` says, as a format that can't be linked is, and the reply's `linked` is `false`. A decline, invalid output, a trap or Cancel places nothing and leaves the document and its undo steps as they were. An importer without `place` is not used diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2187c300b8..5b362c3606 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2705,9 +2705,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Envelope names given as another type:** `object.envelope.makeWithWarp`, `resetWithWarp` and `options` refuse a `style` or `orientation` other than text or null, such as `5`, and an `orientation` other than `horizontal` or `vertical`; `object.envelope.options` refuses such a `preserveShape`. `object.envelope.options` checks the warp keys with no envelope or only mesh envelopes selected, too. Each leaves the document, the options new envelopes get and the undo history as they were. - **Exporter plug-ins (G17):** a WebAssembly plug-in of kind `exporter` adds a write-only file format. File › Export › Export As lists it after the built-in formats, with Use Artboards greyed out (the plug-in writes the whole document) and its parameters in a generated dialog once the file is picked; `document.export` writes it by its format id, `plugin.`, or by one of its extensions, and built-in formats keep theirs. The plug-in is given the native file's JSON (large images without their data) and `_context` (`mode`, `extension`, `name`), with 10 G instructions plus 4,000 per byte of input and 300 s, and Background Export's Cancel stops it between two slices of that budget. A decline or invalid output writes nothing; its warnings come back with the export's. Regressions: `crates/engine/tests/plugin_export.rs`, `crates/plugins/tests/abi.rs`, `crates/ui-egui/src/dialogs/tests_plugin_export.rs`. Scores and hours unchanged. -- **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. +- **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document, which Save asks a name for. The document uses returned artboards when supplied; otherwise, its artboard surrounds the imported objects. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. - **Importer output kinds (G17, VectorCraft's own contract):** an importer at plug-in API level 4 lists in its manifest's `outputKinds` which of `type`, `image`, `layer` and `artboard` it returns besides paths. Its output may then hold point type (text, font family and style, size, fill, transform), embedded RGBA images (stored as PNG in the document), top-level layers with their names, visibility, lock and objects, and named artboards that replace the one around the art; output of artboards or layers alone opens as a blank document. The host checks the whole output before it makes the document: a kind the manifest doesn't list, an image whose bytes aren't 4 × width × height, a name with control or text direction characters, or output past the limits on objects, layers, artboards, text and pixels opens nothing, and the error names the kind or the limit. Imported paths require geometry and cannot name existing object IDs. Positive artboard sizes must produce distinct finite endpoints within the canvas. Importers below level 4 read paths alone, as before. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. -- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`. Its visible layers' objects, or all objects when it returns no layers, are placed as one group named after the file, with guides omitted, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. Transformed art beyond ±4,000,000 pt on either axis is rejected before an edit, including on a template layer. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. +- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`. Its visible layers' objects, or all objects when it returns no layers, are placed as one group named after the file, with guides omitted, from bottom to top by layer, preserving each layer's listed object order (returned object order without layers), at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. Transformed art beyond ±4,000,000 pt on either axis is rejected before an edit, including on a template layer. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. - **Plug-in int parameters as sliders (G17):** an `int` parameter with `"widget": "slider"` shows a slider over its range with its number field, in the filter, live-effect and exporter dialogs and in the Appearance panel's effect editor; the manifest is refused at install when the parameter cannot have one. Regressions: `crates/plugins/src/dialog.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`. Scores and hours unchanged. From 56552447e8b9d6e3006410ec171e1d1e441b7bc4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:52:34 -0800 Subject: [PATCH 35/91] Check retained placement geometry beyond crop frames --- crates/engine/src/cmd/place.rs | 33 +++++++++++++++++++++++++++-- crates/engine/tests/plugin_place.rs | 18 ++++++++++++++++ docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 4 files changed, 52 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 2af574ef49..4ede6e177b 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; transformed art must stay within ±4,000,000 pt on either axis, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -864,7 +864,36 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { Affine::translate(c - natural.center()) } }; - if !crate::sanity::rect_in_range(m.transform_rect_bbox(natural)) { + let mut retained = natural; + match &loaded.art { + Art::Vector { src, nodes, .. } => { + let symbols = src.symbol_boxes(); + for node in nodes { + node.walk(&mut |node| { + if let Some(bounds) = node.geometric_bounds_with(&symbols) { + retained = retained.union(bounds); + } + }); + } + } + Art::Image(image, _) => { + let (sx, sy) = pt_per_px(image.ppi); + retained = retained.union(Rect::new(0.0, 0.0, f64::from(image.width) * sx, f64::from(image.height) * sy)); + } + Art::Dcs(art) => { + let pixels = Rect::new(0.0, 0.0, f64::from(art.img.width), f64::from(art.img.height)); + retained = retained.union(art.xf.transform_rect_bbox(pixels)); + if let Some(clip) = &art.clip { + clip.walk(&mut |node| { + if let Some(bounds) = node.geometric_bounds() { + retained = retained.union(bounds); + } + }); + } + } + Art::Text(_) | Art::Document(..) => {} + } + if !crate::sanity::rect_in_range(m.transform_rect_bbox(retained)) { return Err(bad(PLACE, "placed art lies outside the canvas")); } let parent = st.insertion_parent(); diff --git a/crates/engine/tests/plugin_place.rs b/crates/engine/tests/plugin_place.rs index 0319595ced..c15982cd07 100644 --- a/crates/engine/tests/plugin_place.rs +++ b/crates/engine/tests/plugin_place.rs @@ -90,6 +90,24 @@ fn placing_importer_checks_the_transformed_bounds_before_editing() { } } +#[test] +fn cropped_svg_placement_checks_art_outside_its_frame_before_editing() { + let svg = br#""#; + for at in [[3_999_940.0, 400.0], [-3_999_940.0, 400.0], [400.0, 3_999_940.0], [400.0, -3_999_940.0]] { + for template in [false, true] { + let mut s = with_document(); + let before = state(&mut s); + assert!( + place(&mut s, "cropped.svg", svg, json!({"at": at, "crop": "crop", "template": template})).is_err(), + "{at:?}, template: {template}" + ); + assert_eq!(state(&mut s), before); + } + } + let mut s = with_document(); + assert!(place(&mut s, "cropped.svg", svg, json!({"at": [3_999_930.0, 400.0], "crop": "crop"})).is_ok()); +} + /// A placed group: its name, the names of its children, and its bounds as `(x0, y0, x1, y1)`. type Placed = (Option, Vec>, (f64, f64, f64, f64)); diff --git a/docs/mcp.md b/docs/mcp.md index a6b30705a5..0bf9a6b7b6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13949,7 +13949,8 @@ as one group named after the file. Layers are placed from bottom to top, with ob Without layers, objects keep their returned order. Guides are omitted. Placement records one undo step and embeds the group whatever `link` says (`linked: false`). `plugin.run` of an importer is an error that names `document.open`. Placement rejects transformed art beyond ±4,000,000 pt on either axis, -including template placement, before changing the document. An importer returns new paths with geometry and +including geometry retained outside a crop frame and template placement, before changing the document. +An importer returns new paths with geometry and without object IDs. An artboard's positive width and height must produce distinct finite endpoints within the canvas. In the app, File › Open With lists the installed importers, and `file.openWith {importer, path?, params?}` opens `path`, or a file picked among the importer's extensions, with one (on diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5b362c3606..9808f22144 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2707,7 +2707,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Exporter plug-ins (G17):** a WebAssembly plug-in of kind `exporter` adds a write-only file format. File › Export › Export As lists it after the built-in formats, with Use Artboards greyed out (the plug-in writes the whole document) and its parameters in a generated dialog once the file is picked; `document.export` writes it by its format id, `plugin.`, or by one of its extensions, and built-in formats keep theirs. The plug-in is given the native file's JSON (large images without their data) and `_context` (`mode`, `extension`, `name`), with 10 G instructions plus 4,000 per byte of input and 300 s, and Background Export's Cancel stops it between two slices of that budget. A decline or invalid output writes nothing; its warnings come back with the export's. Regressions: `crates/engine/tests/plugin_export.rs`, `crates/plugins/tests/abi.rs`, `crates/ui-egui/src/dialogs/tests_plugin_export.rs`. Scores and hours unchanged. - **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document, which Save asks a name for. The document uses returned artboards when supplied; otherwise, its artboard surrounds the imported objects. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. - **Importer output kinds (G17, VectorCraft's own contract):** an importer at plug-in API level 4 lists in its manifest's `outputKinds` which of `type`, `image`, `layer` and `artboard` it returns besides paths. Its output may then hold point type (text, font family and style, size, fill, transform), embedded RGBA images (stored as PNG in the document), top-level layers with their names, visibility, lock and objects, and named artboards that replace the one around the art; output of artboards or layers alone opens as a blank document. The host checks the whole output before it makes the document: a kind the manifest doesn't list, an image whose bytes aren't 4 × width × height, a name with control or text direction characters, or output past the limits on objects, layers, artboards, text and pixels opens nothing, and the error names the kind or the limit. Imported paths require geometry and cannot name existing object IDs. Positive artboard sizes must produce distinct finite endpoints within the canvas. Importers below level 4 read paths alone, as before. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. -- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`. Its visible layers' objects, or all objects when it returns no layers, are placed as one group named after the file, with guides omitted, from bottom to top by layer, preserving each layer's listed object order (returned object order without layers), at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. Transformed art beyond ±4,000,000 pt on either axis is rejected before an edit, including on a template layer. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. +- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`. Its visible layers' objects, or all objects when it returns no layers, are placed as one group named after the file, with guides omitted, from bottom to top by layer, preserving each layer's listed object order (returned object order without layers), at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. Transformed art beyond ±4,000,000 pt on either axis is rejected before an edit, including geometry retained outside a crop frame and placement on a template layer. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. - **Plug-in int parameters as sliders (G17):** an `int` parameter with `"widget": "slider"` shows a slider over its range with its number field, in the filter, live-effect and exporter dialogs and in the Appearance panel's effect editor; the manifest is refused at install when the parameter cannot have one. Regressions: `crates/plugins/src/dialog.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`. Scores and hours unchanged. From c71a86d8ad4100348fc3a3e8993c4fe5491afd7d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 08:25:38 -0800 Subject: [PATCH 36/91] Keep unchanged Brush Options out of document history --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/brush_options.rs | 15 ++- .../src/dialogs/brush_options/tests.rs | 96 +++++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 7 +- docs/ui-parity.md | 3 +- 6 files changed, 119 insertions(+), 6 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index f2444bc019..d0e168e4cb 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1114,7 +1114,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options only when its name or options changed; unchanged approval preserves the brush and adds no Undo", ), ( "ui.brushObjectOptions", diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index 3dbeece787..9ff3285064 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -3,8 +3,9 @@ //! Tilt, Bearing or Rotation with its Variation, over live previews of the nib and of a stroke //! (light, heavy, light pressure). Bristle Brush Options: Name (a new bristle brush name that is too //! long is refused at OK), Shape and the bristle sliders. Scatter, Art and Pattern Brush Options: see -//! [`super::brush_art_options`]. OK runs `brush.options` (strokes painted with the brush update); -//! a name another brush has, or a new bristle brush name that is too long, keeps the dialog open. +//! [`super::brush_art_options`]. A changed OK runs `brush.options` (strokes painted with the brush update); +//! accepting unchanged settings closes without an Undo step. +//! A name another brush has, or a new bristle brush name that is too long, keeps the dialog open. //! //! Fields: `__brush` (the brush's name), `__type` (`calligraphic` | `bristle` | `scatter` | `art` | //! `pattern`), `name`. @@ -183,6 +184,7 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map, object_keys: Op initial.set(OPENED, FieldValue::Json(Value::Object(opened))); initial.set(KEYS, FieldValue::Json(json!(keys))); } + let unchanged = (!object && !flag(&initial, CREATE)).then(|| (string(&initial, "name"), string(&initial, "__brush"), params(&initial))); // The canvas of the current window: the Key Color dropper samples there while the dialog is open. let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); let dialog = HostedParamDialog::new(&ctx, KIND, initial, move |fields| { @@ -202,6 +204,15 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map, object_keys: Op None if !object => return Err(tl!("Return to the original drawing to edit its brush").into()), _ => {} } + if let Some((opened_name, brush, opened_params)) = &unchanged { + let name = string(&result.fields, "name"); + // The command ignores an empty name and trims a supplied rename. + let same_name = name == *opened_name || name.trim().is_empty() || name.trim() == brush; + if same_name && params(&result.fields) == *opened_params { + // A deleted brush still reports its normal error instead of accepting a stale dialog. + return app.run("brush.get", json!({"name": brush})).map(|_| ()); + } + } ok(app, result) }) .ok_or("no window")?, diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 34e11865cf..d28d07fa44 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -9,6 +9,102 @@ fn app() -> VectorcraftApp { app } +#[test] +fn unchanged_normal_brush_approval_keeps_the_document_and_undo_history_exact() { + use crate::tests::panel_harness::Panel; + + for name in ["6 pt. Flat", "Bristle Round", "Confetti", "Arrow", "Diamonds"] { + let mut app = app(); + let params = if name == "Arrow" { json!({"width": 100.25}) } else { json!({}) }; + // Establish a saved library before testing a normal approval of an existing brush. + app.run("brush.options", json!({"name": name, "params": params})).unwrap(); + let brush = app.run("brush.get", json!({"name": name})).unwrap(); + let document = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(vec2(1200.0, 1200.0)); + panel.app().run("ui.brushOptions", json!({"name": name})).unwrap(); + panel.frame(); + panel.click("OK"); + panel.frame(); + panel.frame(); + assert!(!is_open(&panel.app()), "the unchanged {name} dialog closes normally"); + assert_eq!(panel.app().run("brush.get", json!({"name": name})).unwrap(), brush); + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc, document, "unchanged {name} approval preserves the entire stored library"); + assert_eq!(st.revision, revision); + assert_eq!(st.history.undo.len(), undo, "unchanged {name} approval adds no Undo step"); + } +} + +#[test] +fn brush_automation_approval_skips_noop_but_saves_changed_options_in_one_step() { + let mut app = app(); + app.run("brush.options", json!({"name": "Arrow", "params": {"width": 100.25}})).unwrap(); + let original = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + let undo = app.session.active().unwrap().history.undo.len(); + open(&mut app, "Arrow"); + confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc, original); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + for name in [" Arrow ", ""] { + open(&mut app, "Arrow"); + set(&mut app, json!({"name": name})); + confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc, original, "a command-equivalent name does not rewrite the brush"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + open(&mut app, "Arrow"); + set(&mut app, json!({"width": 110.25})); + confirm(&mut app).unwrap(); + assert_eq!(app.run("brush.get", json!({"name": "Arrow"})).unwrap()["width"], json!(110.25)); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, original); +} + +#[test] +fn normal_brush_rename_still_saves_and_a_deleted_brush_still_refuses_approval() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + let mut app = app(); + app.run("brush.options", json!({"name": "Arrow", "params": {}})).unwrap(); + let original = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(vec2(1200.0, 1200.0)); + panel.app().run("ui.brushOptions", json!({"name": "Arrow"})).unwrap(); + panel.frame(); + panel.click_role("Name", Role::TEXT_INPUT); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("Renamed Arrow"); + panel.key(Key::Tab, Modifiers::NONE); + panel.click("OK"); + panel.frame(); + panel.frame(); + assert!(!is_open(&panel.app())); + assert!(panel.app().run("brush.get", json!({"name": "Renamed Arrow"})).is_ok()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc, original); + + open(&mut panel.app(), "Arrow"); + panel.app().run("brush.delete", json!({"name": "Arrow"})).unwrap(); + let deleted = panel.app().session.active().unwrap().doc.clone(); + let undo = panel.app().session.active().unwrap().history.undo.len(); + assert!(confirm(&mut panel.app()).unwrap_err().contains("no brush named")); + assert!(is_open(&panel.app()), "the stale unchanged dialog reports its normal error"); + assert_eq!(panel.app().session.active().unwrap().doc, deleted); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + cancel(&mut panel.app()); +} + fn ctx(app: &VectorcraftApp) -> egui::Context { app.ui_ctx.clone().expect("the test app has a context") } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index e4d6d5d1c1..beba3e9870 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1115,7 +1115,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options only when its name or options changed; unchanged approval preserves the brush and adds no Undo", ), ( "ui.brushObjectOptions", diff --git a/docs/mcp.md b/docs/mcp.md index 808f600e69..c99fa4c7e6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,6 +1,6 @@ # VectorCraft MCP server -> **Last updated:** 2026-11-18 · **Change:** Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. +> **Last updated:** 2026-11-27 · **Change:** Brush Options: unchanged approval preserves the brush and adds no Undo; changed options save in one step; previously: Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). @@ -5446,6 +5446,10 @@ already walks Image Trace. Short agent entry points: for new art become no fill and a 0.5 pt black stroke; with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command. +For an existing brush, approving Brush Options without changing its trimmed name or options closes the dialog +without rewriting the brush, changing the document revision or adding Undo. A changed name or option is saved in +one step. A brush deleted while its dialog is open still gives an error on approval. + `brush.selectionArt {ids?|id?}` (a query) replies `{art}`: the object that `brush.new` given the same `ids` or `id`, or the same selection, takes as a new scatter or art brush's art and as a new pattern brush's side tile. Several objects become one group, and `art` is `null` when nothing is selected or `ids` name no object. In the app, the @@ -17024,6 +17028,7 @@ the error text. The interactive fallback applies only to ordinary File > Save, n | Date | Change | |---|---| +| 2026-11-27 | Brush Options: untouched approval preserves the brush, document revision and Undo; changed settings save in one step. Native UI and automation covered. Scores and estimates unchanged. | | 2026-11-18 | Production Preflight: output and artboard scope, four check summaries, clickable canvas ids, effective PPI and explicit unchecked resolution coverage. | | 2026-11-14 | Built-in Tech Circuit brush library (id `tech-circuit`): Circuit Trace, Bus Lines and Terminal Nodes; ten built-in libraries. | | 2026-11-13 | The Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides; Snap to Grid and Snap to Pixel still move its ends (#7252). | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 9b146bfcd4..82c864ef85 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (Brush Options: unchanged approval preserves the brush and adds no Undo; changed options save in one step; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -70,6 +70,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-27 | minor | Brush Options: untouched approval preserves the brush, document revision and Undo; changed settings save in one step. Native UI and automation covered. Scores and estimates unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | From 477c861f62e22dec652c2329e1452234fa824af1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 17:45:10 -0800 Subject: [PATCH 37/91] Keep parity status and revision history unchanged --- docs/ui-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 82c864ef85..7547d495c4 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (Brush Options: unchanged approval preserves the brush and adds no Undo; changed options save in one step; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -70,7 +70,6 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-27 | minor | Brush Options: untouched approval preserves the brush, document revision and Undo; changed settings save in one step. Native UI and automation covered. Scores and estimates unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | @@ -442,6 +441,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Interaction | Status | Evidence | |---|---|---| | Brush Options › Key Color eyedropper yields to one canvas click, then resumes the same draft and previous tool | done | #8284; the pick changes the dialog draft without painting or editing the document. OK applies the brush options; Cancel discards them. Escape ends the pick without sampling before a later Escape cancels the dialog. Six full-app input regressions in `crates/ui-egui/tests/brush_keycolor_modal_repro.rs` cover the actual pick, OK/reopen/Cancel, Escape, reentry, held clicks, stale releases and ordinary modal blocking. | +| Brush Options skip unchanged approval | done | Approving without editing preserves the brush, document revision and Undo history. | | Ordinary Save refused by filesystem permissions/read-only storage offers Save As | focused UI regressions passed; native acceptance pending | #6146; `io::tests_read_only_save`; same name/format suggested; unchanged format keeps options, changed format opens its Save options; Documents folder, UID-bound continuation; cancellation and automation isolation | | Selection artwork drag hovers a visible document tab to activate it, then drops editable artwork on its canvas | done | `tests_document_drag`, `edit.dropSelection`, lossless resource and one-step Undo regressions; a release over another document's tiled pane copies it there too (`canvas::panes` tests), and so does a release over a floating window drawn inside the main window (`doc_windows` tests); overflow-menu drag and floating OS windows remain separate | | A document tab dragged along the tab strip moves its document; a line marks where it goes, the current document and every document's view stay as they were, and a drag off the strip still floats it | done | #5663, [public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html); `document.move`; `tests::tab_reorder`, `chrome::tests` (drop index with floating and view tabs), `engine` `tests::document_move` | From 62f1abe5bd34b43942543d6802ab36ec324a8f93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:58:46 -0800 Subject: [PATCH 38/91] Scripts: collection reads look up names such as -1 and 1.5 The indexer hands a key that is the text of a number to the collection as a number, so pageItems["-1"] and documents["1.5"] read as positions and gave undefined, and "-1" in pageItems was false, even when getByName("-1") found the object. pageItems and documents now take only array indices as positions and look up any other number by its text as a name, giving undefined when nothing has it. index(key) still takes a number as a position. --- crates/engine/src/script/dom.rs | 70 ++++++++++++++++++++------- crates/engine/src/tests/script_dom.rs | 30 ++++++++++++ docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 4 files changed, 87 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 46ca2824d4..c61dc66b7e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -840,11 +840,19 @@ fn app_ref(_: &Host, _: &[Data]) -> Answer { Ok(host_ref("Application", &[])) } -/// `documents[i]`, and `documents["name"]` as `getByName` reads it. +/// `documents[i]`, and `documents["name"]` as `getByName` reads it. A key that is the text of a +/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is +/// looked up as that name, giving `undefined` when no document has it. fn docs_at(h: &Host, a: &[Data]) -> Answer { let s = h.session.borrow(); let at = match arg(a, 1) { - Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)), + Data::Number(n) => match position(*n) { + Some(i) => s.documents().get(i), + None => { + let name = vectorcraft_js::number_to_string(*n); + s.documents().iter().find(|d| d.title() == name) + } + }, Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) { None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())), found => found, @@ -864,10 +872,11 @@ fn docs_by_name(h: &Host, a: &[Data]) -> Answer { fn docs_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => docs_by_name(h, a), - Data::Number(_) => match docs_at(h, a)? { - Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), - d => Ok(d), - }, + Data::Number(n) => { + let s = h.session.borrow(); + let st = position(*n).and_then(|i| s.documents().get(i)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?; + Ok(doc_ref(h, st.uid)) + } _ => Err(HostError::Type("give a name or an index".into())), } } @@ -1453,27 +1462,49 @@ fn probing(a: &[Data]) -> bool { matches!(arg(a, 2), Data::Bool(true)) } -/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. +/// The position an indexer key names when it is an array index, 0 to 2^32 - 2. +fn position(n: f64) -> Option { + whole(n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) +} + +/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. A key that is the text of a +/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is +/// looked up as that name, giving `undefined` when no object has it. fn items_at(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - if let Data::String(_) = arg(a, 1) { - return match items_by_name(h, a) { + match arg(a, 1) { + Data::String(_) => match items_by_name(h, a) { Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), r => r, - }; + }, + Data::Number(n) => match position(*n) { + Some(i) => Ok(item_at(h, doc, i)), + None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { + Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), + r => r, + }, + }, + _ => Ok(Data::Undefined), } - let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; - let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +/// The object at position `i` of `pageItems`, or `undefined` past the end. +fn item_at(h: &Host, doc: Doc, i: usize) -> Data { + with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))) } fn items_by_name(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + items_named(h, doc, name) +} + +/// The first object of `pageItems` named `name`, or `Not found`. +fn items_named(h: &Host, doc: Doc, name: &str) -> Answer { with_doc(h, doc, |_, st| { let ids = page_items(h, st); h.charge_call(ids.len() as u64)?; - let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name)); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) } @@ -1481,10 +1512,13 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer { fn items_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => items_by_name(h, a), - Data::Number(_) => match items_at(h, a)? { - Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), - d => Ok(d), - }, + Data::Number(n) => { + let doc = items_doc(h, a)?; + match position(*n).map(|i| item_at(h, doc, i)) { + None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())), + Some(d) => Ok(d), + } + } _ => Err(HostError::Type("give a name or an index".into())), } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c1aa77e6a6..a8a0615354 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1753,6 +1753,36 @@ fn a_collection_read_with_a_name_gives_the_named_object() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); } +/// A collection read with a name that is the text of a number but not an array index, such as `-1` +/// or `1.5`, gives the object of that name, and `undefined` when nothing has it; array indices stay +/// positions, and `index` still takes a number as a position. +#[test] +fn a_collection_read_with_a_number_name_that_is_not_an_index_gives_the_named_object() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "NaN"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, m = [];\ + vc.log([p['-1'] === p.getByName('-1'), '-1' in p, p[-1] === p.getByName('-1'), p.NaN === p.getByName('NaN'), 'NaN' in p]);\ + vc.log([p['1.5'] === undefined, '1.5' in p, p[0].name, p['1'].name]);\ + try { p.index(-1); } catch (e) { m.push(e.message); }\ + var t = new DocumentPreset(); t.title = '1.5'; var d = app.documents.addDocument('Print', t);\ + var ds = app.documents; vc.log([ds['1.5'] === d, '1.5' in ds, ds[1.5] === d, ds['-1'] === undefined, '-1' in ds]);\ + try { ds.index(1.5); } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!( + out, + vec![ + json!([true, true, true, true, true]), + json!([true, false, "NaN", "-1"]), + json!([true, true, true, true, false]), + json!(["Not found", "Not found"]), + ] + ); +} + /// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or /// locked layer throw and the run changes nothing, while its name and note still change; an object /// that is hidden or locked itself takes them. diff --git a/docs/mcp.md b/docs/mcp.md index 1bbe49574d..2aa1994574 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2848,7 +2848,10 @@ other files through `$`: [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws `Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too - (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note` + (VectorCraft's own rule). A read with the text of a number that is not an array index, such as + `pageItems["-1"]`, `pageItems[1.5]` or `documents["NaN"]`, looks for an object of that name and gives `undefined` + when nothing has it, and `"-1" in pageItems` is true when an object has that name; `index(key)` takes a number as + a position only (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note` take a number or a Boolean as the text `String(value)` gives. `String(object)` gives `[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document ]`, `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a54102e675..8ba494f9bb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1089,7 +1089,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name (a name that is the text of a number, such as `-1` or `1.5`, included) and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 7da320875f8590ecebe06b932cc225eacfa3f098 Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Sat, 28 Nov 2026 11:14:03 +0500 Subject: [PATCH 39/91] Object Mosaic: clear the away warning on return to the original image (#9848) A refusal given while the dialog was in another drawing, or with its image unselected, now clears once the per-frame sync finds the original image again, for both OK's held refusal and Use Ratio's note. Refusals of the values themselves, and the Revert and Undo/Redo guards, stay. --- crates/ui-egui/src/dialogs/object_mosaic.rs | 75 ++++++++++++++++++++- 1 file changed, 72 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index 49f355273a..43d43d4c93 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -108,6 +108,9 @@ pub struct ObjectMosaicDialog { note: Option