From 546d274e6eff61daba8934eadf884557fb3284e7 Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 07:18:04 +0000 Subject: [PATCH 01/36] .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/36] 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/36] 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/36] 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/36] 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/36] 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/36] 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/36] 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/36] 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 d82fe4e8d90b9d6a80632593fc820d009770d973 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:54:45 -0800 Subject: [PATCH 10/36] 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 11/36] 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 9c74e2f3ba6070c758971c5bc40cc6c824071f40 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:04:58 -0800 Subject: [PATCH 12/36] 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 13/36] 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 c71a86d8ad4100348fc3a3e8993c4fe5491afd7d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 08:25:38 -0800 Subject: [PATCH 14/36] 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 15/36] 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 16/36] 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 9fb14228c13a6094e15c866fc3c857c3e433c9d2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 22:54:37 -0800 Subject: [PATCH 17/36] Scripts: the cross-document thread test reads app.documents active document first app.documents now lists the active document first, so after file.new the new document is documents[0] and the document with the three frames is documents[1]. The test picks each document by that order. --- crates/engine/src/tests/script_threads.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs index c8f5737dfc..00139a4eda 100644 --- a/crates/engine/src/tests/script_threads.rs +++ b/crates/engine/src/tests/script_threads.rs @@ -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[1].nextFrame = app.documents[1].textFrames[0];"); + let m = failure(&mut s, "app.documents[1].textFrames[1].nextFrame = app.documents[0].textFrames[0];"); assert!(m.contains("different documents"), "{m}"); let out = log( &mut s, - "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)); }\ + "var d = app.documents[0], p = d.pageItems[0];\ + try { d.textFrames.areaText(p, undefined, app.documents[1].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)]); From c43ab55d18b71b31fc97e54a7f75b28e170b8ce9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:24:49 -0800 Subject: [PATCH 18/36] Docs: say only numbers outside the array-index range are read by name A key such as `1` reads position 1 of a collection, not an object named "1". The parity line now says that only numbers outside the array-index range, such as `-1` or `1.5`, are looked up by name, as `docs/mcp.md` already does. --- 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 1f0ca1869c..7a361f8e5f 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 (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: 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 key such as `1` is an array index and reads that position; only a number outside the array-index range, such as `-1` or `1.5`, is looked up 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: 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 48a0c6017e1684bc3eb820a842bcb04364f7edf6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 04:31:04 -0800 Subject: [PATCH 19/36] Three-Point Arc: join arcs to open path ends and snap to carry a path on The Three-Point Arc tool gets two options in its Tool Options: - Join to Open Path Ends (`join`, off by default; J switches it while the ends are placed): an end placed within 5 screen points of an end of an open path lands on it, and the arc is joined to that path. The path keeps its look and, when one end joins, its direction. With both ends on open path ends the two paths become one, or the path closes when both are its own ends. It is one undo step. - Snap Where the Arc Continues a Path (`tangentSnap`, on by default): in direction mode, when the direction line starts on an end of an open path, a third point near the line along which the arc carries the path on, the same way or turned back, snaps onto it, and the tool shows the line dashed. `shape.threePointArc` takes `join: true` for the same join; it picks a path in the selection first, then the front one, and in isolation mode only paths inside the isolated group. --- ROADMAP.md | 1 + crates/engine/src/cmd/create.rs | 29 ++- crates/engine/src/cmd/path.rs | 85 +++++++ crates/engine/src/tests/three_point_arc.rs | 174 +++++++++++++ crates/tools/src/settings.rs | 2 +- crates/tools/src/three_point_arc.rs | 228 ++++++++++++++++-- crates/tools/src/three_point_arc/tests.rs | 122 +++++++++- .../src/dialogs/three_point_arc_options.rs | 16 +- docs/mcp.md | 23 +- docs/target-app-parity.md | 1 + 10 files changed, 646 insertions(+), 35 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index abd6bea6bf..d40c33e9e1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -174,6 +174,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged. +- 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged. - 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 7a4a4dea07..78c066405d 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -110,7 +110,7 @@ pub fn specs() -> Vec { "Three-Point Arc", [], None, - "{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn", + "{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`), join?: bool (default false)} → {id, cx, cy, radius, sweep, joined?}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. With `join`, an end of the arc on an end of an editable open path (inside the isolated group in isolation mode) joins the arc to that path, which keeps its look and, when one end joins, its direction (a path in the selection comes first); with both ends on open path ends the second path joins too, or the path closes when both are its own ends. The result then has `joined: true` and `id` is the joined path (or its compound path). A `join` that is not true or false is an error. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn", has_doc, three_point_arc ), @@ -747,7 +747,8 @@ fn arc(s: &mut Session, p: &Value) -> Result { } /// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or -/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is. +/// leaving the end `at` names toward `toward`. With `join`, joined to the open paths whose ends +/// its ends lie on ([`super::path::join_arc`]). One undo step, named as an Arc tool drag is. fn three_point_arc(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.threePointArc"; let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]"))); @@ -774,8 +775,32 @@ fn three_point_arc(s: &mut Session, p: &Value) -> Result { } _ => return Err(bad(C, "give exactly one of `through` and `toward`")), }; + let join = match p.get("join") { + None => false, + Some(Value::Bool(on)) => *on, + Some(_) => return Err(bad(C, "`join` must be true or false")), + }; let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?; let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v)); + let ends = if join { + let st = s.doc()?; + let selected = st.selection.objects.clone(); + let find = |at| super::path::open_end_at(&st.doc, st.isolation, &selected, at); + (find(start), find(end)) + } else { + (None, None) + }; + if ends.0.is_some() || ends.1.is_some() { + let sub = path.subpaths.first().cloned().ok_or_else(|| bad(C, "no arc fits these points"))?; + let id = s.edit("Arc", |d, sel| { + let id = super::path::join_arc(d, &sub, ends.0, ends.1)?; + sel.set([id]); + Ok(id) + })?; + return Ok( + json!({ "id": id.0, "joined": true, "cx": arc.center.x, "cy": arc.center.y, "radius": arc.radius, "sweep": arc.sweep.to_degrees() }), + ); + } let look = s.new_art_look( vectorcraft_color::Paint::None, if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() }, diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 525cef316a..85d805c193 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1504,6 +1504,91 @@ fn join_pair(d: &mut Document, (a, sa): (NodeId, usize), (b, sb): (NodeId, usize Ok(compound_or_self(d, a)) } +/// An end of an open subpath of an editable path (not a guide) at `at`: the path, the subpath and +/// whether the end is the subpath's first anchor. In isolation mode (`scope`), only a path inside +/// the isolated node counts. Among several, one in or inside the selection `selected` comes first, +/// then the last in paint order. +pub(super) fn open_end_at(d: &Document, scope: Option, selected: &[NodeId], at: Point) -> Option<(NodeId, usize, bool)> { + let editable = d.editable(); + let mut found: Option<((NodeId, usize, bool), bool)> = None; + d.walk(|n| { + let NodeKind::Path { path, guide: false, .. } = &n.kind else { return }; + if !editable(n.id) { + return; + } + let chain = d.ancestry(n.id).unwrap_or_default(); + if scope.is_some_and(|s| !chain.contains(&s)) { + return; + } + let chosen = chain.iter().any(|id| selected.contains(id)); + for (si, sp) in path.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed) { + let Some((first, last)) = end_points(sp) else { continue }; + let end = if last.distance(at) < 1e-6 { + false + } else if first.distance(at) < 1e-6 { + true + } else { + continue; + }; + if found.is_none_or(|(_, was)| chosen || !was) { + found = Some(((n.id, si, end), chosen)); + } + } + }); + found.map(|(end, _)| end) +} + +/// `sp`, an open subpath whose end (its first anchor when `at_first`) lies on an end of `arc` +/// (its first anchor when `arc_at_start`), with `arc` added there: one subpath running the way +/// `sp` runs. The anchor where they meet is `sp`'s, with its handle on the arc's side taken from +/// the arc. +fn splice(sp: &SubPath, at_first: bool, arc: &SubPath, arc_at_start: bool) -> SubPath { + let mut arc = arc.clone(); + if arc_at_start == at_first { + arc.reverse(); + } + let mut out = sp.clone(); + if at_first { + let meet = arc.anchors.pop(); + if let (Some(meet), Some(first)) = (meet, out.anchors.first_mut()) { + first.h_in = meet.h_in; + } + arc.anchors.extend(out.anchors); + out.anchors = arc.anchors; + } else { + if !arc.anchors.is_empty() { + let meet = arc.anchors.remove(0); + if let Some(last) = out.anchors.last_mut() { + last.h_out = meet.h_out; + } + } + out.anchors.extend(arc.anchors); + } + out +} + +/// The arc `arc` joined to the open path ends `start` (at its first anchor) and `end` (at its +/// last), as [`open_end_at`] gives them, at least one of them. The arc joins the path at `start` +/// first, keeping that path's direction and look, and then, when `end` is an end of another open +/// subpath, that subpath joins it as Join joins two paths; when `end` is the other end of the same +/// subpath, the subpath closes. Returns what to select: the joined path, or its compound path. +pub(super) fn join_arc(d: &mut Document, arc: &SubPath, start: Option<(NodeId, usize, bool)>, end: Option<(NodeId, usize, bool)>) -> Result { + let err = || EngineError::Other("join needs open paths".into()); + let ((id, si, at_first), arc_at_start, rest) = match (start, end) { + (Some(s), e) => (s, true, e), + (None, Some(e)) => (e, false, None), + (None, None) => return Err(err()), + }; + let path = path_mut(d, id)?; + let sp = path.subpaths.get_mut(si).filter(|sp| !sp.closed && !sp.anchors.is_empty()).ok_or_else(err)?; + *sp = splice(sp, at_first, arc, arc_at_start); + match rest { + // The arc's far end is the first anchor of the joined subpath when it was added before it. + Some((other, osi, other_first)) => join_pair(d, (id, si), (other, osi), (at_first, !other_first), None), + None => Ok(compound_or_self(d, id)), + } +} + pub(super) type AnchorTargets = Vec<(NodeId, Vec<(usize, usize)>)>; pub(super) fn anchor_targets(s: &Session) -> Result { diff --git a/crates/engine/src/tests/three_point_arc.rs b/crates/engine/src/tests/three_point_arc.rs index ebd755dda7..fb34e0da6e 100644 --- a/crates/engine/src/tests/three_point_arc.rs +++ b/crates/engine/src/tests/three_point_arc.rs @@ -217,4 +217,178 @@ fn set_option_sets_the_direction_and_refuses_bad_values() { assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}"); } assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(false)); + // `join` starts off and `tangentSnap` on; both take only true or false. + assert_eq!( + (s.tool_options_of("threePointArc")["join"].clone(), s.tool_options_of("threePointArc")["tangentSnap"].clone()), + (json!(false), json!(true)) + ); + let set = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "values": {"join": true, "tangentSnap": false}})).unwrap(); + assert_eq!((set["join"].clone(), set["tangentSnap"].clone()), (json!(true), json!(false))); + for key in ["join", "tangentSnap"] { + let e = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "key": key, "value": 1})).unwrap_err(); + assert_eq!(e, format!("tool `threePointArc`: `{key}` must be true or false")); + } +} + +/// An open path drawn from SVG path data, selected. +fn open_path(s: &mut Session, d: &str) -> NodeId { + id_of(&s.execute("path.create", &json!({ "d": d })).unwrap()) +} + +/// The anchors of the first subpath of `id`, and whether it is closed. +fn anchors(s: &Session, id: NodeId) -> (Vec, bool) { + let n = node(s, id); + let sp = &n.path_data().unwrap().subpaths[0]; + (sp.anchors.iter().map(|a| a.p).collect(), sp.closed) +} + +/// With `join`, an arc starting on the last anchor of an open path is added to that path: the path +/// keeps its id and direction and now ends where the arc ends, the anchor where they meet is not +/// doubled, and it is one undo step. An arc ending on a path's first anchor is added before it. +#[test] +fn join_adds_the_arc_to_the_open_path_it_starts_on() { + let mut s = session(); + let id = open_path(&mut s, "M0 100 L100 100"); + let (undo, count) = (undo_len(&s), object_count(&s)); + let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap(); + assert_eq!((id_of(&out), out["joined"].clone(), out["radius"].as_f64()), (id, json!(true), Some(40.0)), "{out}"); + assert_eq!((undo_len(&s), object_count(&s)), (undo + 1, count)); + let (pts, closed) = anchors(&s, id); + assert!(!closed); + assert_eq!((pts.first().copied(), pts.last().copied()), (Some(Point::new(0.0, 100.0)), Some(Point::new(180.0, 100.0))), "{pts:?}"); + assert_eq!(pts.iter().filter(|p| **p == Point::new(100.0, 100.0)).count(), 1, "{pts:?}"); + assert!(farthest_from_path(&s, id, &[Point::new(140.0, 60.0), Point::new(50.0, 100.0)]) < 1e-9); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(anchors(&s, id).0, [Point::new(0.0, 100.0), Point::new(100.0, 100.0)]); + // The arc ends on the first anchor of a path running right: the path still runs right, from + // the arc's start. + let id = open_path(&mut s, "M300 100 L400 100"); + let out = s.execute(C, &json!({"start": [220, 100], "end": [300, 100], "toward": [220, 60], "join": true})).unwrap(); + assert_eq!(id_of(&out), id); + let (pts, _) = anchors(&s, id); + assert_eq!((pts.first().copied(), pts.last().copied()), (Some(Point::new(220.0, 100.0)), Some(Point::new(400.0, 100.0))), "{pts:?}"); + assert!(farthest_from_path(&s, id, &[Point::new(260.0, 60.0)]) < 1e-9); +} + +/// With both ends on ends of two open paths, the arc joins them into one path in one undo step; +/// with both ends on the two ends of one open path, the path closes. +#[test] +fn join_with_both_ends_on_open_paths_makes_one_path() { + let mut s = session(); + let a = open_path(&mut s, "M0 100 L100 100"); + let b = open_path(&mut s, "M180 100 L280 100"); + let (undo, count) = (undo_len(&s), object_count(&s)); + let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap(); + assert_eq!(id_of(&out), a); + assert_eq!((undo_len(&s), object_count(&s)), (undo + 1, count - 1)); + assert!(s.doc().unwrap().doc.node(b).is_none()); + let (pts, closed) = anchors(&s, a); + assert!(!closed); + let ends = (pts.first().copied(), pts.last().copied()); + assert!( + ends == (Some(Point::new(0.0, 100.0)), Some(Point::new(280.0, 100.0))) + || ends == (Some(Point::new(280.0, 100.0)), Some(Point::new(0.0, 100.0))), + "{pts:?}" + ); + for p in [Point::new(100.0, 100.0), Point::new(180.0, 100.0)] { + assert_eq!(pts.iter().filter(|q| **q == p).count(), 1, "{pts:?}"); + } + assert!(farthest_from_path(&s, a, &[Point::new(140.0, 60.0), Point::new(230.0, 100.0)]) < 1e-9); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((object_count(&s), anchors(&s, b).0.len()), (count, 2)); + // One path's two ends: it closes. + let id = open_path(&mut s, "M100 300 L180 300"); + let out = s.execute(C, &json!({"start": [180, 300], "end": [100, 300], "through": [140, 340], "join": true})).unwrap(); + assert_eq!(id_of(&out), id); + let (pts, closed) = anchors(&s, id); + assert!(closed, "{pts:?}"); + assert_eq!(pts.iter().filter(|q| **q == Point::new(100.0, 300.0)).count(), 1, "{pts:?}"); + assert!(farthest_from_path(&s, id, &[Point::new(140.0, 340.0), Point::new(140.0, 300.0)]) < 1e-9); +} + +/// Of two open path ends at the arc's start, `join` takes the one in the selection, and with +/// neither selected the one in front. +#[test] +fn join_prefers_the_selected_path_then_the_front_one() { + let mut s = session(); + let back = open_path(&mut s, "M0 100 L100 100"); + let front = open_path(&mut s, "M100 200 L100 100"); + for (selected, want) in [(Some(back), back), (None, front)] { + let ids: Vec = selected.iter().map(|id| id.0).collect(); + s.execute("select.set", &json!({ "ids": ids })).unwrap(); + let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap(); + assert_eq!(id_of(&out), want, "{selected:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + // In isolation mode, a path outside the isolated group is left alone. + s.execute("select.set", &json!({ "ids": [back.0] })).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({ "id": group })).unwrap(); + s.execute("select.set", &json!({ "ids": [] })).unwrap(); + let out = s.execute(C, &json!({"start": [100, 100], "end": [100, 20], "through": [60, 60], "join": true})).unwrap(); + assert_eq!(id_of(&out), back, "{out}"); + s.execute("edit.undo", &json!({})).unwrap(); + let out = s.execute(C, &json!({"start": [100, 200], "end": [180, 200], "through": [140, 160], "join": true})).unwrap(); + assert!(out.get("joined").is_none(), "{out}"); + assert_eq!(anchors(&s, front).0.len(), 2); +} + +/// Without `join`, away from open path ends, on a locked path, or on a closed path's anchor, the +/// arc is a new path; a `join` that is not true or false is an error and draws nothing. +#[test] +fn join_leaves_paths_it_cannot_join_alone() { + let mut s = session(); + let line = open_path(&mut s, "M0 100 L100 100"); + let rect = open_path(&mut s, "M200 200 L300 200 L300 300 Z"); + let arc = |s: &mut Session, start: [f64; 2], end: [f64; 2], via: [f64; 2], join: Value| { + s.execute(C, &json!({"start": start, "end": end, "through": via, "join": join})) + }; + for (start, end, via, join) in [ + ([100.0, 100.0], [180.0, 100.0], [140.0, 60.0], json!(false)), + ([100.0, 120.0], [180.0, 120.0], [140.0, 80.0], json!(true)), + ([200.0, 200.0], [120.0, 200.0], [160.0, 160.0], json!(true)), + ] { + let count = object_count(&s); + let out = arc(&mut s, start, end, via, join.clone()).unwrap(); + assert!(out.get("joined").is_none() && id_of(&out) != line && id_of(&out) != rect, "{join}: {out}"); + assert_eq!(object_count(&s), count + 1); + } + assert_eq!(anchors(&s, line).0.len(), 2); + s.execute("select.set", &json!({"ids": [line.0]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + // On the line's other end, where none of the arcs above ends. + let out = arc(&mut s, [0.0, 100.0], [0.0, 180.0], [40.0, 140.0], json!(true)).unwrap(); + assert!(out.get("joined").is_none(), "{out}"); + assert_eq!(anchors(&s, line).0.len(), 2); + let count = object_count(&s); + let e = arc(&mut s, [100.0, 300.0], [180.0, 300.0], [140.0, 260.0], json!("yes")).unwrap_err().to_string(); + assert!(e.contains("`join` must be true or false"), "{e}"); + assert_eq!(object_count(&s), count); +} + +/// With the tool's `join` option on, clicks near an open path's end place the arc's end on it and +/// the arc joins the path; with it off the arc is a path of its own, and J while the ends are +/// placed switches it on. +#[test] +fn the_tool_joins_the_arc_to_the_path_end_it_starts_near() { + let mut s = session(); + let id = open_path(&mut s, "M0 100 L100 100"); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.select_tool("threePointArc", view()).unwrap(); + let count = object_count(&s); + for p in [(100.0, 100.0), (180.0, 100.0), (140.0, 60.0)] { + click(&mut s, p.0, p.1); + } + assert_eq!((object_count(&s), anchors(&s, id).0.len()), (count + 1, 2), "off: a path of its own"); + s.execute("edit.undo", &json!({})).unwrap(); + // J after the first click, near the path's end, switches `join` on. + click(&mut s, 99.0, 100.5); + s.tool_key(ToolKey::Letter('j'), Mods::default(), view()).unwrap(); + click(&mut s, 180.0, 100.0); + click(&mut s, 140.0, 60.0); + assert_eq!(object_count(&s), count); + let (pts, _) = anchors(&s, id); + assert_eq!((pts.len() > 2, pts.last().copied()), (true, Some(Point::new(180.0, 100.0))), "{pts:?}"); + assert_eq!(s.tool_options_of("threePointArc")["join"], json!(true), "J keeps the option switched"); } diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index f9cf5f51cd..80c19c7133 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -51,7 +51,7 @@ const ROWS: &[Row] = &[ (&["mirrorCut"], None, &["axis", "keep"]), (&["puppetWarp"], None, &["showMesh", "expand"]), (&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]), - (&[crate::three_point_arc::ID], None, &["direction"]), + (&[crate::three_point_arc::ID], None, &["direction", "join", "tangentSnap"]), (&["spiral"], None, &["decay", "segments", "clockwise"]), // The grids' Tool Options: the dividers and switches the drag uses, the Default Size and // Reference Point a click's dialog opens with. diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs index 60314cbe1f..994f60cef2 100644 --- a/crates/tools/src/three_point_arc.rs +++ b/crates/tools/src/three_point_arc.rs @@ -8,6 +8,11 @@ //! the second end along the line from that end to the point, and Shift keeps the line at 45° //! steps). `direction` is set in the tool's Tool Options and kept with the preferences; `]` (with //! or without Shift) switches it while the ends are placed. Every point snaps to Smart Guides. +//! With the `join` option on (Tool Options, or J while the ends are placed), an end placed within +//! reach of an end of an open path lands on it, and the arc is joined to that path. With +//! `tangentSnap` on (the default), in direction mode, when the direction line starts at an end of +//! an open path, the third point snaps onto the line along which the arc carries on the path, the +//! same way or turned back, and the tool shows that line dashed. //! Until the third point is placed, the tool shows the arc as a dashed outline with its ends, its //! center as a small cross, the direction line in direction mode and, with Measurement Labels on, //! the radius by the pointer. Where no arc fits (the third point lies on the line through the @@ -17,9 +22,9 @@ //! the ends; a second click on the first end (a double-click) places nothing. use serde_json::{Value, json}; -use vectorcraft_doc::MAX_COORD; +use vectorcraft_doc::{MAX_COORD, NodeKind}; use vectorcraft_geom::shapes::CircularArc; -use vectorcraft_geom::{PathData, Point, Vec2}; +use vectorcraft_geom::{PathData, Point, SubPath, Vec2}; use crate::guides::{DrawSnap, Leave}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -34,6 +39,12 @@ const CROSS_PX: f64 = 4.0; const REACH_PX: f64 = 3.0; /// The label the tool shows by the pointer where no arc fits. pub const TOO_LARGE: &str = "Arc too large"; +/// How near (screen points) an end of an open path an end of the arc counts as on it, the Pen's +/// reach for the path ends it joins. +const END_PX: f64 = 5.0; +/// How near (screen points) the line along which the arc carries on an open path the third point +/// snaps onto it. +const TANGENT_PX: f64 = 5.0; /// The press in progress. #[derive(Clone, Copy, Debug, PartialEq)] @@ -47,16 +58,82 @@ enum Press { Third, } -#[derive(Default)] +/// An end of an open path under an end of the arc: where it is, and the direction a path carrying +/// on from it heads in (none for a path of one anchor). +#[derive(Clone, Copy, Debug, PartialEq)] +struct OpenEnd { + at: Point, + out: Option, +} + +/// The end of an open subpath of an editable path (not a guide) within reach of `p`. +fn open_end(cx: &ToolContext, p: Point) -> Option { + let tol = cx.tol(END_PX).max(cx.point_tol()); + let editable = cx.doc.editable(); + // The nearest end; among ends equally near, as `shape.threePointArc`'s `join` picks among the + // ends at a point: one in the selection first, then the last in paint order, and of one + // subpath's two ends its last anchor. + let mut best: Option<(OpenEnd, f64, bool)> = None; + cx.doc.walk(|n| { + let NodeKind::Path { path, guide: false, .. } = &n.kind else { return }; + if !editable(n.id) { + return; + } + // In isolation mode, only art inside the isolated node. + let chain = cx.doc.ancestry(n.id).unwrap_or_default(); + if cx.isolation.is_some_and(|s| !chain.contains(&s)) { + return; + } + let chosen = chain.iter().any(|id| cx.selection.objects.contains(id)); + for sp in path.subpaths.iter().filter(|sp| !sp.closed) { + let ends = [false, true].map(|at_first| end_of(sp, at_first)); + let near = match ends { + [Some(last), Some(first)] => Some(if last.at.distance(p) <= first.at.distance(p) { last } else { first }), + [last, first] => last.or(first), + }; + let Some(e) = near else { continue }; + let d = e.at.distance(p); + if d <= tol && best.is_none_or(|(_, bd, was)| d < bd || (d == bd && (chosen || !was))) { + best = Some((e, d, chosen)); + } + } + }); + best.map(|(e, _, _)| e) +} + +/// The end of the open subpath `sp` (its first anchor when `at_first`), with the direction a path +/// carrying on from it heads in. +fn end_of(sp: &SubPath, at_first: bool) -> Option { + let n = sp.anchors.len(); + let (end, next) = + if at_first { (sp.anchors.first()?, sp.anchors.get(1)) } else { (sp.anchors.last()?, n.checked_sub(2).and_then(|i| sp.anchors.get(i))) }; + // The path reaches the end along the first of its control points that is off the end. + let mut back = vec![if at_first { end.h_out } else { end.h_in }]; + if let Some(q) = next { + back.extend([if at_first { q.h_in } else { q.h_out }, q.p]); + } + let out = back.into_iter().map(|q| end.p - q).find(|v| v.hypot() > 0.0).map(|v| v / v.hypot()); + Some(OpenEnd { at: end.p, out }) +} + pub struct ThreePointArcTool { snap: DrawSnap, /// The third point gives the arc's direction at an end instead of a point it passes through. direction: bool, + /// An end of the arc on an end of an open path joins the arc to that path. + join: bool, + /// In direction mode, the third point snaps to where the arc carries on the open path its + /// direction line starts at, the same way or turned back. + tangent_snap: bool, start: Option, end: Option, + /// The open path ends found under the first and the second end as each was placed. + open: [Option; 2], press: Option, /// Where the pointer is, snapped: the point the next press or release places. pointer: Option, + /// The line the third point snapped to: the end it runs through and its direction. + tangent: Option<(Point, Vec2)>, /// Alt was held at the last pointer event: in direction mode, the direction is at the second end. at_end: bool, /// Where the pointer was at its last event, pressed or hovering, before snapping, and the keys @@ -64,6 +141,25 @@ pub struct ThreePointArcTool { raw: Option<(Point, Mods)>, } +impl Default for ThreePointArcTool { + fn default() -> Self { + Self { + snap: DrawSnap::default(), + direction: false, + join: false, + tangent_snap: true, + start: None, + end: None, + open: [None; 2], + press: None, + pointer: None, + tangent: None, + at_end: false, + raw: None, + } + } +} + /// The arc from `start` to `end` shaped by `third`, as `shape.threePointArc` draws it: through /// `third`, or with `direction`, heading toward `third` from `start` (or, with `at_end`, arriving /// at `end` along the line from `end` to `third`). None where no arc fits or the arc would reach @@ -81,14 +177,18 @@ pub fn arc_of(start: Point, end: Point, third: Point, direction: bool, at_end: b on_canvas.then_some((arc, path)) } -/// The command the tool runs for the arc from `start` to `end` shaped by `third`. -fn command(start: Point, end: Point, third: Point, direction: bool, at_end: bool) -> (String, Value) { +/// The command the tool runs for the arc from `start` to `end` shaped by `third`, joined to the +/// open paths at its ends with `join`. +fn command(start: Point, end: Point, third: Point, direction: bool, at_end: bool, join: bool) -> (String, Value) { let pair = |p: Point| json!([p.x, p.y]); - let params = if direction { + let mut params = if direction { json!({ "start": pair(start), "end": pair(end), "toward": pair(third), "at": if at_end { "end" } else { "start" } }) } else { json!({ "start": pair(start), "end": pair(end), "through": pair(third) }) }; + if join { + params["join"] = json!(true); + } ("shape.threePointArc".into(), params) } @@ -96,11 +196,37 @@ impl ThreePointArcTool { fn clear(&mut self) { self.start = None; self.end = None; + self.open = [None; 2]; self.press = None; self.pointer = None; + self.tangent = None; self.snap.clear(); } + /// The end `which` (0 the first, 1 the second) placed at `p`: the open path end under it is + /// noted, and with `join` on the end lands on it. + fn place(&mut self, cx: &ToolContext, which: usize, p: Point) -> Point { + let found = open_end(cx, p); + if let Some(slot) = self.open.get_mut(which) { + *slot = found; + } + match found { + Some(e) if self.join => e.at, + _ => p, + } + } + + /// The second end let go at `b`, with the first at `a`: placed, unless landing on an open path + /// end puts it on the first end, which leaves it to another try. + fn place_end(&mut self, cx: &ToolContext, a: Point, b: Point) { + let at = self.place(cx, 1, b); + if at.distance(a) > cx.tol(REACH_PX) { + self.end = Some(at); + } else { + self.open[1] = None; + } + } + /// How the point being placed keeps to the points before it: the second end to the first, and /// in direction mode the third point to the end its direction line starts from. fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { @@ -111,6 +237,28 @@ impl ThreePointArcTool { } } + /// The third point at `q`, snapped: in direction mode with `tangentSnap` on, near the line + /// along which the arc carries on the open path its direction line starts at, it moves onto + /// that line. Shift keeps the line at 45° steps instead. + fn third(&mut self, cx: &ToolContext, q: Point, mods: Mods) -> Point { + self.tangent = None; + let (Some(a), Some(b)) = (self.start, self.end) else { return q }; + if !self.direction || !self.tangent_snap || mods.shift { + return q; + } + let (o, end) = if self.at_end { (b, self.open[1]) } else { (a, self.open[0]) }; + // The direction line starts on the path's end itself, so the arc carries the path on. + let Some(OpenEnd { at, out: Some(t) }) = end.filter(|e| e.at == o) else { return q }; + let k = (q - at).dot(t); + let foot = at + t * k; + if k != 0.0 && q.distance(foot) <= cx.tol(TANGENT_PX) { + self.tangent = Some((at, t)); + foot + } else { + q + } + } + /// The pressed pointer moved to `ev`, or Shift or Alt changed: the point being placed follows /// it. A change of keys alone does not make the press a drag. fn follow(&mut self, cx: &ToolContext, ev: &PointerEvent) { @@ -122,10 +270,15 @@ impl ThreePointArcTool { let leave = Leave::segment(cx, *at, ev.mods.shift); self.pointer = Some(self.snap.drag(cx, ev.pos, Some(&leave))); } - Some(Press::End | Press::Third) => { + Some(Press::End) => { let leave = self.leave(cx, ev.mods); self.pointer = Some(self.snap.drag(cx, ev.pos, leave.as_ref())); } + Some(Press::Third) => { + let leave = self.leave(cx, ev.mods); + let q = self.snap.drag(cx, ev.pos, leave.as_ref()); + self.pointer = Some(self.third(cx, q, ev.mods)); + } None => {} } } @@ -153,7 +306,8 @@ impl Tool for ThreePointArcTool { PointerKind::Move => { self.raw = Some((ev.pos, ev.mods)); let leave = self.leave(cx, ev.mods); - self.pointer = Some(self.snap.hover(cx, ev.pos, &[], leave.as_ref())); + let q = self.snap.hover(cx, ev.pos, &[], leave.as_ref()); + self.pointer = Some(self.third(cx, q, ev.mods)); vec![] } PointerKind::Down => { @@ -161,7 +315,8 @@ impl Tool for ThreePointArcTool { let leave = self.leave(cx, ev.mods); match (self.start, self.end) { (None, _) => { - let at = self.snap.press(cx, ev.pos, &[], None); + let snapped = self.snap.press(cx, ev.pos, &[], None); + let at = self.place(cx, 0, snapped); self.start = Some(at); self.press = Some(Press::Start { at, from: ev.pos, dragged: false }); self.pointer = Some(at); @@ -177,7 +332,8 @@ impl Tool for ThreePointArcTool { self.pointer = Some(at); } (Some(_), Some(_)) => { - self.pointer = Some(self.snap.press(cx, ev.pos, &[], leave.as_ref())); + let q = self.snap.press(cx, ev.pos, &[], leave.as_ref()); + self.pointer = Some(self.third(cx, q, ev.mods)); self.press = Some(Press::Third); } } @@ -195,8 +351,8 @@ impl Tool for ThreePointArcTool { self.follow(cx, ev); } match (self.press.take(), self.start, self.pointer) { - (Some(Press::Start { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.end = Some(b), - (Some(Press::End), Some(a), Some(b)) if b.distance(a) > cx.tol(REACH_PX) => self.end = Some(b), + (Some(Press::Start { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.place_end(cx, at, b), + (Some(Press::End), Some(a), Some(b)) if b.distance(a) > cx.tol(REACH_PX) => self.place_end(cx, a, b), (Some(Press::Third), Some(a), Some(c)) => { let Some(b) = self.end else { return vec![] }; // Where no arc fits, nothing is drawn and the ends stay for another try. @@ -204,7 +360,7 @@ impl Tool for ThreePointArcTool { self.snap.clear(); return vec![]; } - let (name, params) = command(a, b, c, self.direction, self.at_end); + let (name, params) = command(a, b, c, self.direction, self.at_end, self.join); self.clear(); return vec![Action::Exec(name, params)]; } @@ -229,18 +385,40 @@ impl Tool for ThreePointArcTool { (Some(_), Some((p, mods))) => self.follow(cx, &PointerEvent::new(PointerKind::Drag, p.x, p.y).with_mods(mods)), (None, Some((p, mods))) if self.end.is_some() && self.pointer.is_some() => { let leave = self.leave(cx, mods); - self.pointer = Some(self.snap.hover(cx, p, &[], leave.as_ref())); + let q = self.snap.hover(cx, p, &[], leave.as_ref()); + self.pointer = Some(self.third(cx, q, mods)); } _ => {} } } + ToolKey::Letter('j') if self.start.is_some() => { + self.join = !self.join; + // Switched on: the ends placed on open path ends land on them, unless that would + // put one end on the other. + if self.join { + let reach = cx.tol(REACH_PX); + if let Some(e) = self.open[0] + && self.end.is_none_or(|b| b.distance(e.at) > reach) + { + self.start = Some(e.at); + if let Some(Press::Start { at, .. }) = &mut self.press { + *at = e.at; + } + } + if let (Some(a), Some(_), Some(e)) = (self.start, self.end, self.open[1]) + && a.distance(e.at) > reach + { + self.end = Some(e.at); + } + } + } _ => {} } vec![] } fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { - matches!(key, ToolKey::Escape | ToolKey::BracketRight) && self.start.is_some() + matches!(key, ToolKey::Escape | ToolKey::BracketRight | ToolKey::Letter('j')) && self.start.is_some() } /// An end placed: Escape drops it. @@ -266,6 +444,7 @@ impl Tool for ThreePointArcTool { fn hover_ended(&mut self, _cx: &ToolContext) { if self.press.is_none() { self.pointer = None; + self.tangent = None; self.snap.clear(); } } @@ -285,6 +464,11 @@ impl Tool for ThreePointArcTool { if self.direction { o.push(Overlay::Line { a: if self.at_end { b } else { a }, b: p, color, dashed: false }); } + // The line the third point snapped to, as far past its end as the pointer is. + if let Some((at, t)) = self.tangent { + let reach = t * p.distance(at); + o.push(Overlay::Line { a: at - reach, b: at + reach, color, dashed: true }); + } match self.arc() { Some((arc, path)) => { o.push(Overlay::Path { path: path.to_bezpath(), color, width: 1.0, dashed: true }); @@ -313,21 +497,23 @@ impl Tool for ThreePointArcTool { } fn options(&self) -> Value { - json!({ "direction": self.direction }) + json!({ "direction": self.direction, "join": self.join, "tangentSnap": self.tangent_snap }) } fn set_option(&mut self, key: &str, value: &Value) { - if key == "direction" - && let Some(on) = value.as_bool() - { - self.direction = on; + let Some(on) = value.as_bool() else { return }; + match key { + "direction" => self.direction = on, + "join" => self.join = on, + "tangentSnap" => self.tangent_snap = on, + _ => {} } } fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { use crate::option_check as c; match key { - "direction" => c::boolean(key, v), + "direction" | "join" | "tangentSnap" => c::boolean(key, v), _ => Err(c::unknown(key)), } } diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs index eaf269e974..1fa9451478 100644 --- a/crates/tools/src/three_point_arc/tests.rs +++ b/crates/tools/src/three_point_arc/tests.rs @@ -166,11 +166,11 @@ fn in_direction_mode_the_third_point_sets_the_tangent_at_an_end() { let mut t = ThreePointArcTool::default(); assert!(!t.claims_key(&cx, ToolKey::BracketRight), "no ends: ] is left to the app"); t.key(&cx, ToolKey::BracketRight, Mods::default()); - assert_eq!(t.options(), json!({ "direction": false })); + assert_eq!(t.options()["direction"], json!(false)); drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); assert!(t.claims_key(&cx, ToolKey::BracketRight)); t.key(&cx, ToolKey::BracketRight, Mods::default()); - assert_eq!(t.options(), json!({ "direction": true })); + assert_eq!(t.options()["direction"], json!(true)); // Straight up the page from (300, 300): the upper half circle about (340, 300). hover(&mut t, &cx, (300.0, 250.0), Mods::default()); let o = t.overlays(&cx); @@ -201,10 +201,10 @@ fn the_direction_option_takes_a_bool() { t.set_option("direction", &json!(true)); for v in [json!("false"), json!(0), json!(null)] { t.set_option("direction", &v); - assert_eq!(t.options(), json!({ "direction": true }), "{v}"); + assert_eq!(t.options()["direction"], json!(true), "{v}"); } t.set_option("direction", &json!(false)); - assert_eq!(t.options(), json!({ "direction": false })); + assert_eq!(t.options(), json!({ "direction": false, "join": false, "tangentSnap": true })); } /// `]` pressed while the third point is held down places the point as the new mode keeps it: the @@ -373,6 +373,120 @@ fn escape_history_and_a_double_click_drop_or_keep_the_ends() { assert!(!t.busy() && t.overlays(&cx).is_empty()); } +/// A document holding an open straight path from (100, 100) to (200, 100), unselected. +fn doc_with_open_line() -> vectorcraft_doc::Document { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let path = vectorcraft_geom::shapes::line(Point::new(100.0, 100.0), Point::new(200.0, 100.0)); + d.insert(Some(l), 0, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap(); + d +} + +/// The arc command's params in `acts`, its only action. +fn params_of(acts: &[Action]) -> Value { + let [Action::Exec(name, params)] = acts else { panic!("{acts:?}") }; + assert_eq!(name, "shape.threePointArc"); + params.clone() +} + +/// With `join` on, an end placed near an open path's end lands on it and the command asks for the +/// join; with it off, the end stays where it was placed and the command asks for none. J while +/// the ends are placed switches `join`, moving a placed end onto the path's end. +#[test] +fn with_join_an_end_near_an_open_path_end_lands_on_it() { + let d = doc_with_open_line(); + let (s, p) = (Selection::default(), paint()); + // Snap to Point off, so only `join` moves an end onto the path's end. + let isolated = ToolContext { smart_guides: false, snap_to_point: false, isolation: Some(vectorcraft_doc::NodeId(u64::MAX)), ..cx(&d, &s, &p) }; + let cx = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + assert!(!t.claims_key(&cx, ToolKey::Letter('j')), "no ends: J is left to the app"); + click(&mut t, &cx, (198.5, 100.5)); + click(&mut t, &cx, (280.0, 180.0)); + let off = params_of(&click(&mut t, &cx, (280.0, 100.0))); + assert_eq!((off["start"].clone(), off.get("join")), (json!([198.5, 100.5]), None), "{off}"); + t.set_option("join", &json!(true)); + click(&mut t, &cx, (198.5, 100.5)); + click(&mut t, &cx, (280.0, 180.0)); + let on = params_of(&click(&mut t, &cx, (280.0, 100.0))); + assert_eq!((on["start"].clone(), on["join"].clone()), (json!([200.0, 100.0]), json!(true)), "{on}"); + // The second end lands on the path's first end. + click(&mut t, &cx, (20.0, 180.0)); + click(&mut t, &cx, (101.5, 100.5)); + let on = params_of(&click(&mut t, &cx, (20.0, 100.0))); + assert_eq!(on["end"], json!([100.0, 100.0]), "{on}"); + // In isolation mode, a path outside the isolated node is left alone. + click(&mut t, &isolated, (198.5, 100.5)); + assert_eq!(t.start, Some(Point::new(198.5, 100.5))); + t.key(&cx, ToolKey::Escape, Mods::default()); + // Past the path's end, off its stroke, but within reach of the end. + click(&mut t, &cx, (203.5, 102.0)); + assert_eq!(t.start, Some(Point::new(200.0, 100.0))); + t.key(&cx, ToolKey::Escape, Mods::default()); + // A second end that would land on the first end is not placed, by a click or by a drag. + click(&mut t, &cx, (200.0, 100.0)); + click(&mut t, &cx, (196.0, 100.0)); + assert_eq!((t.start, t.end), (Some(Point::new(200.0, 100.0)), None)); + t.key(&cx, ToolKey::Escape, Mods::default()); + drag(&mut t, &cx, (200.0, 100.0), &[(196.0, 100.0)], Mods::default()); + assert_eq!((t.start, t.end), (Some(Point::new(200.0, 100.0)), None)); + t.key(&cx, ToolKey::Escape, Mods::default()); + // J switches `join` off and on again while the ends are placed. + t.set_option("join", &json!(false)); + click(&mut t, &cx, (198.5, 100.5)); + assert!(t.claims_key(&cx, ToolKey::Letter('j'))); + t.key(&cx, ToolKey::Letter('j'), Mods::default()); + assert_eq!((t.options()["join"].clone(), t.start), (json!(true), Some(Point::new(200.0, 100.0)))); + click(&mut t, &cx, (280.0, 180.0)); + let on = params_of(&click(&mut t, &cx, (280.0, 100.0))); + assert_eq!((on["start"].clone(), on["join"].clone()), (json!([200.0, 100.0]), json!(true)), "{on}"); +} + +/// In direction mode, with the first end on an open path's end, a third point near the line along +/// which the arc carries the path on (here the line y = 100) snaps onto it, the same way or turned +/// back, and the tool shows the line dashed; farther away, with Shift, with `tangentSnap` off, or +/// away from a path's end, the point stays where it is. +#[test] +fn in_direction_mode_the_third_point_snaps_to_carry_the_path_on() { + let d = doc_with_open_line(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + t.set_option("direction", &json!(true)); + let dashed_through = |o: &[Overlay]| { + o.iter().any(|o| matches!(o, Overlay::Line { a, b, dashed: true, .. } if (a.y - 100.0).abs() < 1e-9 && (b.y - 100.0).abs() < 1e-9 && a.midpoint(*b) == Point::new(200.0, 100.0))) + }; + for (third, want) in [((260.0, 103.0), (260.0, 100.0)), ((140.0, 97.0), (140.0, 100.0)), ((260.0, 120.0), (260.0, 120.0))] { + click(&mut t, &cx, (200.0, 100.0)); + click(&mut t, &cx, (200.0, 200.0)); + hover(&mut t, &cx, third, Mods::default()); + assert_eq!(dashed_through(&t.overlays(&cx)), third != want, "{third:?}"); + assert_eq!(params_of(&click(&mut t, &cx, third))["toward"], json!([want.0, want.1]), "{third:?}"); + } + // Shift keeps the line at 45° steps instead: the pointer just off 45° goes onto 45°. + click(&mut t, &cx, (200.0, 100.0)); + click(&mut t, &cx, (200.0, 200.0)); + let shift = Mods { shift: true, ..Mods::default() }; + let toward = params_of(&click_with(&mut t, &cx, (240.0, 63.0), shift))["toward"].clone(); + assert!((toward[0].as_f64().unwrap() - 200.0 + toward[1].as_f64().unwrap() - 100.0).abs() < 1e-9, "{toward}"); + // From an end away from the path, or with the snap off, no snap. + for (first, snap) in [((200.0, 140.0), true), ((200.0, 100.0), false)] { + t.set_option("tangentSnap", &json!(snap)); + click(&mut t, &cx, first); + click(&mut t, &cx, (200.0, 220.0)); + let toward = params_of(&click(&mut t, &cx, (260.0, first.1 + 3.0)))["toward"].clone(); + assert_eq!(toward, json!([260.0, first.1 + 3.0]), "{first:?}"); + } + // With Alt, the line from the second end, on the path's first end, carries the path on to the + // left. + t.set_option("tangentSnap", &json!(true)); + click(&mut t, &cx, (100.0, 200.0)); + click(&mut t, &cx, (100.0, 100.0)); + let alt = Mods { alt: true, ..Mods::default() }; + let acts = click_with(&mut t, &cx, (40.0, 98.0), alt); + assert_eq!((params_of(&acts)["toward"].clone(), params_of(&acts)["at"].clone()), (json!([40.0, 100.0]), json!("end"))); +} + /// The catalog lists the tool in the Line Segment tool's group, after the Arc tool, with no /// default shortcut, and `create` makes it. #[test] diff --git a/crates/ui-egui/src/dialogs/three_point_arc_options.rs b/crates/ui-egui/src/dialogs/three_point_arc_options.rs index 45f9546aa0..93facb987e 100644 --- a/crates/ui-egui/src/dialogs/three_point_arc_options.rs +++ b/crates/ui-egui/src/dialogs/three_point_arc_options.rs @@ -1,8 +1,12 @@ //! Three-Point Arc Tool Options (double-click the Three-Point Arc tool, or `tool.options`): //! Third Point Sets Direction, the tool's `direction` option. With it on, the third point gives the -//! direction the arc leaves an end in; with it off, the arc passes through the third point. OK -//! sets it with `tool.setOption {tool: "threePointArc", values: {direction}}`; it lasts across -//! tool switches and is saved with the preferences. `]` also switches it while an arc is drawn. +//! direction the arc leaves an end in; with it off, the arc passes through the third point. Snap +//! Where the Arc Continues a Path (`tangentSnap`, on by default) snaps the third point, in +//! direction mode, to where the arc carries on an open path it starts at. Join to Open Path Ends +//! (`join`) joins the arc to the open paths whose ends its ends are placed on. OK sets them with +//! `tool.setOption {tool: "threePointArc", values: {direction, tangentSnap, join}}`; they last +//! across tool switches and are saved with the preferences. `]` also switches `direction`, and J +//! `join`, while an arc is drawn. use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; @@ -17,7 +21,11 @@ pub const KIND: &str = "threePointArcOptions"; /// Open the tool's options with their current values. pub fn open(app: &mut VectorcraftApp) -> Value { - let params = vec![Param::new("direction", tl!("Third Point Sets Direction"), ParamKind::bool(false))]; + let params = vec![ + Param::new("direction", tl!("Third Point Sets Direction"), ParamKind::bool(false)), + Param::new("tangentSnap", tl!("Snap Where the Arc Continues a Path"), ParamKind::bool(true)), + Param::new("join", tl!("Join to Open Path Ends"), ParamKind::bool(false)), + ]; let options = app.session.tool_options_of(TOOL); let fields = options.as_object().map(|m| form::fields_of(¶ms, m)).unwrap_or_default(); let (title, shown) = (tool_options::title(TOOL), params.clone()); diff --git a/docs/mcp.md b/docs/mcp.md index 8cb939c506..f294fffe9b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -856,7 +856,7 @@ from −100 to 100 and is 50 when left out with `lengthX` and `lengthY`, or 100 `` `baseAlong` must be one of x, y ``), as is a `slope` outside its range; the arc is not drawn and no undo step is added. -`shape.threePointArc {start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: "start"|"end"}` draws an +`shape.threePointArc {start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: "start"|"end", join?: bool}` draws an open circular arc from `start` to `end` and selects it. With `through`, the arc passes through that point. With `toward`, the arc leaves `start` heading toward that point, so the line from `start` to the point is the arc's tangent there. With `at: "end"`, the line from `end` to the point is the tangent at `end` instead. `at` is `"start"` when left @@ -869,14 +869,31 @@ when the third point lies on the line through the ends, when the arc would reach `[x, y]`, when both or neither of `through` and `toward` are given, when `at` is anything but `"start"` or `"end"`, and when `at` is given with `through`. +With `join: true`, an end of the arc that lies on an end of an open subpath of an editable path (not a guide, and in +isolation mode inside the isolated group) joins the arc to that path, as the published arc tool documentation describes for arcs started or ended on an open path's end +(https://docs.astutegraphics.com/subscribe/arc-by-points-tool/arc-by-points-preferences). When several open path ends +lie there, one in the selection comes first, then the last in paint order. The path keeps its look, and when one end +joins, its direction: the arc is added after the path's last anchor or before its first, and the anchor where they meet +is the path's own, with the handle on the arc's side taken from the arc. When the other end of the arc lies on an end of +another open path, that path is joined on as `path.join` joins two paths; when it lies on the other end of the +same subpath, the path closes. It is one undo step, the joined path (or its compound path) is selected, and the result +is `{id, cx, cy, radius, sweep, joined: true}` with `id` the joined path. With no open path end at either end, the arc +is drawn as a new path. A `join` that is not true or false is an error. + The Three-Point Arc tool, in the Line Segment tool's group after the Arc tool, runs this command. A drag from one end to the other, or a click on each, places the ends; Shift keeps the second end at 45° steps from the first (from General › Constrain Angle). A click on a third point, or a press dragged to it, then draws the arc through it. With the tool's `direction` option on, the third point gives the direction the arc leaves the first end in; with `mods.alt`, the direction is at the second end, and Shift keeps the direction at 45° steps. Three-Point Arc Tool Options (`tool.options`, or a double-click on the tool) sets `direction` with its Third Point Sets Direction box, and -`]` (with or without Shift) switches it while the ends are placed; the option is saved with the preferences. Until the -third point is placed, the tool shows the arc as a dashed outline, its center as a small cross, the direction line in +`]` (with or without Shift) switches it while the ends are placed; the option is saved with the preferences. The +`join` option (Join to Open Path Ends in Tool Options, off by default; J switches it while the ends are placed) makes an +end placed within 5 screen points of an end of an open path land on that end (the nearest one, picked among ends equally +near as the command picks), and the tool then runs the command with +`join: true`. The `tangentSnap` option (Snap Where the Arc Continues a Path, on by default) works in direction mode: +when the direction line starts on an end of an open path, a third point within 5 screen points of the line along which +the arc carries the path on, the same way or turned back, snaps onto it, and the tool shows that line dashed. Shift +keeps the direction at 45° steps instead. Until the third point is placed, the tool shows the arc as a dashed outline, its center as a small cross, the direction line in direction mode and, with Measurement Labels on, the radius. Where no arc fits, the tool shows "Arc too large" by the pointer (nothing while the pointer is on an end), and a click there draws nothing and keeps the ends. Escape, and an edit, Undo or Redo made outside the tool, remove the ends. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 75efe3bf2e..22a9384574 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -814,6 +814,7 @@ since 2026-10-01. - **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page () describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged. - **Spirals turn as they are dragged, and along General › Constrain Angle:** a spiral dragged out with the Spiral tool turns about its center so that its outer end is at the pointer, so dragging around the center turns it, while Alt, Ctrl/Cmd, ↑/↓, Space and Escape work as before. A spiral placed from the Spiral dialog starts along the x axis turned by a Constrain Angle other than 0° or a whole turn, with its bounding box turned. `shape.spiral` takes an optional `rotation` (degrees clockwise about `cx`, `cy`); a `rotation` that is not a number is an error, and without one spirals are drawn as before. The help page () says that moving the pointer around in a curve during the drag turns the new spiral, and the help page () describes new objects being drawn along the turned axes. Putting the outer end exactly at the pointer, keeping the last direction while the pointer is within 0.01 pt of the center, and leaving a dragged spiral's direction to the pointer with Shift or a Constrain Angle are VectorCraft's own rules (tools `draw2::family::tests::spiral_drag_turns_the_spiral_to_the_pointer`; engine `a_dragged_spiral_turns_its_outer_end_to_the_pointer`, `constrain_angle_turns_a_click_made_spiral`, `spiral_rotation_turns_it_and_must_be_a_number`; UI `spiral_click_dialog_starts_along_the_constrain_angle`). Scores and hours unchanged. - **Three-Point Arc tool:** a new tool in the Line Segment tool's group, after the Arc tool, draws an open circular arc. A drag or two clicks place its ends (Shift keeps the second end at 45° steps), and a third click places a point the arc passes through. With Third Point Sets Direction on (the tool's Tool Options, or `]` while drawing), the third point gives the direction the arc leaves its first end in, or with Alt the direction at its second end. The tool previews the arc and its center, and with Measurement Labels on its radius, shows "Arc too large" where no arc fits, and draws the arc in one undo step with `shape.threePointArc {start, end, through | toward, at?}` (geom `shapes::tests::the_arc_through_a_point_passes_through_it`, `the_arc_leaving_along_a_direction_has_that_tangent`, `degenerate_points_give_no_arc`, `the_path_via_the_third_point_passes_through_it_exactly`; tools `three_point_arc::tests`; engine `tests::three_point_arc`; ui-egui `dialogs::three_point_arc_options::tests`). Scores and hours unchanged. +- **Three-Point Arc joins open paths:** with Join to Open Path Ends on (Tool Options, or J while drawing), an end of the arc placed near an end of an open path lands on it and the arc is joined to that path, which keeps its look; with both ends on open path ends the paths become one, or the path closes when both are its own ends (`shape.threePointArc {join: true}`, one undo step). In direction mode, with the direction line starting on an open path's end, Snap Where the Arc Continues a Path (on by default) snaps the third point onto the line along which the arc carries the path on, the same way or turned back (https://docs.astutegraphics.com/subscribe/arc-by-points-tool/arc-by-points-preferences; tools `three_point_arc::tests::with_join_an_end_near_an_open_path_end_lands_on_it`, `in_direction_mode_the_third_point_snaps_to_carry_the_path_on`; engine `tests::three_point_arc::join_adds_the_arc_to_the_open_path_it_starts_on`, `join_with_both_ends_on_open_paths_makes_one_path`, `join_prefers_the_selected_path_then_the_front_one`, `join_leaves_paths_it_cannot_join_alone`, `the_tool_joins_the_arc_to_the_path_end_it_starts_near`). Scores and hours unchanged. - **Shape commands refuse invalid options:** `shape.arc` refuses a `reference` that is not a whole number from 0 to 8, a `baseAlong` other than `x` or `y` (either case), null included for both, and a `slope` outside −100…100, in both of its forms; before, such a value drew the arc with reference point 0 or 8, the X axis or the nearest slope. `shape.rectangularGrid` and `shape.polarGrid` refuse a divider count that is not a whole number of at least 0; before, such a count was 5. Each error names the key, and nothing is drawn. Left-out values keep their defaults. These ranges are VectorCraft's own command rules (engine `draw2::shape_arc_rejects_an_invalid_reference_base_along_or_slope`, `draw2::shape_arc_takes_every_reference_point_and_either_base_axis`, `draw2::grid_divider_counts_reject_fractions_and_negatives`). Scores and hours unchanged. - **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged. From de8876375a759e65b83df5eb8dcd4d3fa3bf41ee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 07:57:44 -0800 Subject: [PATCH 20/36] Docs: Brush Options treats an empty name as unchanged docs/mcp.md now states that an empty name is ignored when approving Brush Options for an existing brush, as the dialog's check does. --- docs/mcp.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index c933bf1f6d..b0234e384f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5534,7 +5534,8 @@ already walks Image Trace. Short agent entry points: 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 +without rewriting the brush, changing the document revision or adding Undo. An empty name is ignored and counts +as unchanged. 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`, From 12b00a4a3720cc93d22e75d489e4d129bcad2438 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 07:58:14 -0800 Subject: [PATCH 21/36] Docs: say only numbers outside the array-index range are read by name A key such as `1` reads position 1 of a collection, not an object named "1". The parity line now says that only numbers outside the array-index range, such as `-1` or `1.5`, are looked up by name, as `docs/mcp.md` already does. --- 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 dac3e0d8da..869a0cd3b4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1101,7 +1101,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 (a key such as `1` is an array index and reads that position; only a number outside the array-index range, such as `-1` or `1.5`, is looked up 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 and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; only a number outside the array-index range, such as `-1` or `1.5`, is looked up by name. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.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 1e5aec6296894e464c760725aa5b0fd404abbc6a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 08:01:10 -0800 Subject: [PATCH 22/36] Docs: limit numeric collection names to JavaScript's own number text A key such as "1.50" is a plain name and throws Not found when nothing has it; only keys written as JavaScript writes the number, such as "1.5", give undefined. --- docs/mcp.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 4290e653db..2c84d90a66 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2867,7 +2867,8 @@ other files through `$`: `Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too (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 + when nothing has it. This applies only to the text JavaScript writes for that number: `pageItems["1.50"]` is a + plain name and throws `Not found` when nothing has it. `"-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 ]`, From 13dfdc720ae86b88bafbcbfba3ec489807695d93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 11:18:13 -0800 Subject: [PATCH 23/36] UI: a highlighted list entry applies only once it is chosen Nine list reads took the entry the arrow keys highlighted as a choice: Fold Preview's View and Inside, Define Grid's lists, the raster export options' Resolution, Background Color and Matte, the 3D and Materials rows' lists, the Separations Preview panel's lists, and the Control bar's Mirror & Cut Axis and Keep and Crop Image PPI. A highlighted entry applied at once, and Escape left it applied. These reads now take only the entry chosen with Enter or a click, as Corner and Shared Edge do since #9773. --- .../ui-egui/src/addons/packaging/preview.rs | 4 +- .../src/addons/packaging/preview/tests.rs | 34 ++++++++++++ .../ui-egui/src/dialogs/perspective_grid.rs | 5 +- crates/ui-egui/src/dialogs/png_options.rs | 4 +- crates/ui-egui/src/dialogs/revolve.rs | 5 +- crates/ui-egui/src/dialogs/tests_export.rs | 41 ++++++++++++++ .../ui-egui/src/dialogs/tests_perspective.rs | 36 +++++++++++++ crates/ui-egui/src/panels/separations.rs | 44 ++++++++++++++- crates/ui-egui/src/panels/tests_three_d.rs | 33 ++++++++++++ crates/ui-egui/src/toolbar.rs | 6 ++- crates/ui-egui/src/toolbar/tests.rs | 54 +++++++++++++++++++ 11 files changed, 254 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs index 7fde5f2f4b..5af2119835 100644 --- a/crates/ui-egui/src/addons/packaging/preview.rs +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -562,13 +562,13 @@ fn toolbar(ui: &mut Ui, words: &FoldPreviewWords, doc: &vectorcraft_engine::doc: .collect(); Row::new().wrap(true).show(ui, |ui, _| { let current = set.view().map_or("", |v| v.1); - if let Some(&id) = Select::new(words.view.clone(), Bind::given(current), &views).show(ui).value() + if let Some(&id) = Select::new(words.view.clone(), Bind::given(current), &views).show(ui).events.committed() && let Some(&(_, _, x, y)) = VIEWS.iter().find(|v| v.1 == id) { (set.rotate_x, set.rotate_y, set.pan) = (x, y, [0.0; 2]); } let inside = Select::new(words.inside.clone(), Bind::given(set.inside.clone()), &insides).placeholder(set.inside.clone()).show(ui); - if let Some(name) = inside.value() { + if let Some(name) = inside.events.committed() { set.inside.clone_from(name); } Checkbox::new(Bind::bound(&mut set.show_fold_lines)).label(words.show_fold_lines.clone()).show(ui); diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index 63f7bcc3a3..5c729aae39 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -565,3 +565,37 @@ fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() { // With no fold there is the one line that says why. assert_eq!(status(0, None, false).len(), 1); } + +/// View and Inside: an entry highlighted with the arrow keys changes no setting, Escape leaves the settings as they +/// were, and Enter applies the entry. +#[test] +fn a_highlighted_view_or_inside_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + + use crate::tests::panel_harness::Panel; + + crate::i18n::set_current(crate::i18n::Lang::EN); + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"view": "front", "inside": ""})).unwrap(); + let mut panel = Panel::new(app, show); + panel.room(vec2(520.0, 440.0)); + let settings = |panel: &Panel| panel.app().ui.fold_preview.clone(); + for name in ["View", "Inside"] { + let before = settings(&panel); + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + assert_eq!(settings(&panel), before, "a highlighted {name} entry changes no setting"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(settings(&panel), before, "Escape leaves the {name} setting as it was"); + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + assert_ne!(settings(&panel), before, "Enter applies the {name} entry"); + } + let set = settings(&panel); + assert_eq!((set.rotate_x, set.rotate_y), (0.0, 180.0), "the entry after Front is Back"); + assert!(!set.inside.is_empty(), "the entry after White is a swatch"); +} diff --git a/crates/ui-egui/src/dialogs/perspective_grid.rs b/crates/ui-egui/src/dialogs/perspective_grid.rs index f899a9d7e9..9c3dfcb00e 100644 --- a/crates/ui-egui/src/dialogs/perspective_grid.rs +++ b/crates/ui-egui/src/dialogs/perspective_grid.rs @@ -371,11 +371,12 @@ fn row(ui: &mut egui::Ui, name: &Label, salt: &str, mut body: impl FnMut(&mut eg Field::new(name.clone()).id_salt(salt).show(ui, |ui, _| body(ui)); } -/// A select of `entries` named `name` (an English label), over `value`; `set` takes a pick. +/// A select of `entries` named `name` (an English label), over `value`; `set` takes the entry chosen, not one only +/// highlighted. fn choose(ui: &mut egui::Ui, name: &str, salt: &str, entries: &[Entry], value: T, mut set: impl FnMut(T)) { let label = word(name); row(ui, &label, salt, |ui| { - if let Some(picked) = Select::new(label.clone(), Bind::given(value.clone()), entries).show(ui).value().cloned() { + if let Some(picked) = Select::new(label.clone(), Bind::given(value.clone()), entries).show(ui).events.committed().cloned() { set(picked); } }); diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 3a69a42763..cafd0f6a12 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -223,7 +223,7 @@ fn resolution_row() -> Param { let entries: Vec> = RESOLUTION_LABELS.iter().enumerate().map(|(i, label)| Entry::new(i, tl!(*label))).collect(); let (mut picked, mut typed) = (None, None); let shown = Row::new().show(ui, |ui, _| { - picked = Select::new(tl!("Resolution:"), Bind::given(preset.unwrap_or(other)), &entries).show(ui).value().copied(); + picked = Select::new(tl!("Resolution:"), Bind::given(preset.unwrap_or(other)), &entries).show(ui).events.committed().copied(); if preset.is_none() { let field = NumberField::new(tl!("Resolution:"), Bind::given(Some(ppi))) .range(1.0..=4608.0) @@ -274,7 +274,7 @@ fn color_choice( let color = (at == ids.len()).then(|| Srgba::from(Rgba::from_hex(¤t).unwrap_or(Rgba::rgb(128, 128, 128)))); let (mut picked, mut pick_color) = (None, false); let shown = Row::new().show(ui, |ui, _| { - picked = Select::new(tl!(label), Bind::given(at.max(start)), &entries).show(ui).value().copied(); + picked = Select::new(tl!(label), Bind::given(at.max(start)), &entries).show(ui).events.committed().copied(); if let Some(color) = color { pick_color = Swatch::new(tl!(label), color).show(ui).clicked; } diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 2d9c252ef3..6eab0d5404 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -130,14 +130,15 @@ fn set_value(fields: &mut DialogFields, key: &str, value: &Value) { } } -/// A select over `titles`: the index picked this pass. `at` is the shown entry (none shows a placeholder). +/// A select over `titles`: the index chosen this pass, not one only highlighted. `at` is the shown entry (none shows a +/// placeholder). fn pick(ui: &mut egui::Ui, label: &str, titles: &[String], at: Option, default: Option) -> Option { let entries: Vec> = titles.iter().enumerate().map(|(i, t)| Entry::new(i, t.clone())).collect(); let mut bind = Bind::given(at.unwrap_or(usize::MAX)); if let Some(d) = default { bind = bind.reset(d); } - Select::new(label.to_owned(), bind, &entries).id_salt(label).show(ui).value().copied() + Select::new(label.to_owned(), bind, &entries).id_salt(label).show(ui).events.committed().copied() } /// A select row of JSON `options` (value, title) for `key`. diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index f11039d48a..1a1ce7db43 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -224,6 +224,47 @@ fn png_options_name_the_pixel_size_in_the_accessibility_tree() { assert_eq!(sizes(&mut app), ["120 × 80 px"]); } +/// PNG Options' Resolution and Background Color, and PNG-8 Options' Matte: an entry highlighted with the arrow keys +/// changes no field, Escape closes the list with the dialog open and its fields as they were, and Enter applies the +/// entry. +#[test] +fn a_highlighted_raster_option_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + use vectorcraft_engine::cmd::fileio::FORMATS; + + use crate::tests::panel_harness::Panel; + + for (id, name) in [("png", "Resolution:"), ("png", "Background Color:"), ("png8", "Matte:")] { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + let format = FORMATS.iter().find(|f| f.id == id).unwrap(); + super::png_options::open(&mut panel.app(), format, json!({"format": id, "path": format!("/out/a.{id}")})); + panel.frame(); + panel.frame(); + let fields = + |panel: &Panel| on_top(&panel.app(), |h, _, at| h.open_dialogs().into_iter().find(|d| d.id == at).and_then(|d| d.fields)).flatten(); + let before = fields(&panel); + assert!(before.is_some(), "{id} options are open"); + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + assert_eq!(fields(&panel), before, "a highlighted {name} entry changes no field"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(fields(&panel), before, "Escape closes the {name} list with the fields as they were"); + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + let after = fields(&panel); + assert!(after.is_some(), "Enter in the {name} list keeps the dialog open"); + assert_ne!(after, before, "Enter applies the {name} entry"); + } +} + /// The role and name of each node of the window's accessibility tree, in a frame drawn once the dialogs have settled. fn access_names(app: &mut VectorcraftApp) -> Vec<(egui::accesskit::Role, String)> { super::tests::settle(app); diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index ce286be347..9f6d312b8f 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -223,6 +223,42 @@ fn enter(app: &mut VectorcraftApp) { frame(app); } +/// Define Grid's Type, Units and Scale: an entry highlighted with the arrow keys changes no field, Escape closes the +/// list with the dialog open and its fields as they were, and Enter applies the entry. +#[test] +fn a_highlighted_define_grid_choice_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + panel.app().run("ui.perspectiveGridDialog", json!({})).unwrap(); + panel.frame(); + panel.frame(); + let fields = |panel: &Panel| host(&panel.app(), |h| h.open_dialogs().pop().and_then(|d| d.fields)); + for name in ["Type:", "Units:", "Scale:"] { + let before = fields(&panel); + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + assert_eq!(fields(&panel), before, "a highlighted {name} entry changes no field"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(kind(&panel.app()).as_deref(), Some(super::perspective_grid::KIND), "Escape closes the list, not the dialog"); + assert_eq!(fields(&panel), before, "Escape leaves the fields as they were"); + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + assert_eq!(kind(&panel.app()).as_deref(), Some(super::perspective_grid::KIND), "Enter in the list keeps the dialog open"); + assert_ne!(fields(&panel), before, "Enter applies the {name} entry"); + } +} + #[test] fn enter_is_ok_in_define_grid_and_save_grid_as_preset() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 96d558186a..691bd720fc 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -66,7 +66,7 @@ fn check(ui: &mut Ui, label: &'static str, on: bool, enabled: bool) -> Option( ui: &mut Ui, name: &str, @@ -82,7 +82,8 @@ fn pick( if caption { Text::new(label.clone()).show(ui); } - picked = Select::new(label.clone(), Bind::given(current.clone()), &entries).enabled(enabled).id_salt(name).show(ui).value().cloned(); + picked = + Select::new(label.clone(), Bind::given(current.clone()), &entries).enabled(enabled).id_salt(name).show(ui).events.committed().cloned(); }); picked } @@ -541,6 +542,45 @@ mod tests { assert_eq!(none.params(AssignChoice::Profile, None), None, "no other profile to pick"); } + /// A profile highlighted in the Assign rows' Profile list assigns nothing, Escape leaves the document as it was, + /// and the profile chosen with Enter is assigned in one undo step. + #[test] + fn a_highlighted_profile_is_assigned_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + // Assigning a profile to the front document changes the process's active color settings. + if !crate::testing::in_own_process("panels::separations::tests::a_highlighted_profile_is_assigned_only_once_it_is_chosen") { + return; + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + app.run("edit.assignProfile", json!({"rgb": null, "cmyk": null})).unwrap(); + let row = AssignRow::of(&app.session.active().unwrap().doc); + assert!(row.others.len() >= 2, "{row:?}"); + let mut panel = Panel::new(app, show); + let state = |panel: &Panel| { + let app = panel.app(); + let st = app.session.active().unwrap(); + (vectorcraft_engine::cmd::colormgmt::doc_profiles(&st.doc), st.history.undo.len()) + }; + let before = state(&panel); + panel.click_role("Profile:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "a highlighted profile assigns nothing"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "Escape leaves the document's profiles as they were"); + panel.click_role("Profile:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + let ((rgb, _), undo) = state(&panel); + assert_eq!(rgb.as_deref(), Some(row.others[1].as_str()), "Enter assigns the chosen profile"); + assert_eq!(undo, before.1 + 1, "the choice is one undo step"); + } + /// The Assign rows follow the document's color mode: an RGB document lists the RGB working space /// and the RGB profiles and assigns its RGB profile, a CMYK document the CMYK ones, and the other /// model's profile stays as it was. diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index c253ba9747..f6b92fd209 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -237,6 +237,39 @@ fn a_drag_previews_and_records_one_undo_step_when_released() { assert_eq!(undo_len(&app), history + 1); } +/// A bevel shape highlighted with the arrow keys leaves the effect as it was, Escape closes the list with nothing +/// changed, and the shape chosen with Enter applies in one undo step. +#[test] +fn a_highlighted_bevel_shape_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let mut app = app(); + set_type(&mut app, "extrude").unwrap(); + let mut panel = Panel::new(app, show); + let state = |panel: &Panel| { + let app = panel.app(); + (effect(&app).1, undo_len(&app)) + }; + let before = state(&panel); + panel.click_role("Bevel Shape", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "a highlighted bevel shape changes nothing"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "Escape leaves the effect as it was"); + panel.click_role("Bevel Shape", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + let (params, undo) = state(&panel); + assert_ne!(params["bevel"], before.0["bevel"], "Enter applies the chosen bevel shape"); + assert_eq!(undo, before.1 + 1, "the choice is one undo step"); +} + #[test] fn a_change_reaches_each_selected_3d_effect_and_no_other_effect() { let mut app = app(); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index d90dbd96c0..093004d94e 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -599,7 +599,9 @@ pub fn control_bar_options(app: &mut VectorcraftApp, ui: &mut Ui) { let entries: Vec> = choices.iter().map(|&(value, name)| Entry::new(value, tl!(name))).collect(); let current = opts[key].as_str().and_then(|v| choices.iter().find(|(value, _)| *value == v)).map(|(value, _)| *value); let picked = Field::new(tl!(label)) - .show(ui, |ui, _| Select::new(tl!(label), Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), &entries).show(ui).value().copied()) + .show(ui, |ui, _| { + Select::new(tl!(label), Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), &entries).show(ui).events.committed().copied() + }) .inner .flatten(); if let Some(value) = picked { @@ -645,7 +647,7 @@ fn crop_options(app: &mut VectorcraftApp, ui: &mut Ui) { let label = |v: f64| crate::i18n::fmt(tl!("{n} ppi"), &[("n", &format!("{}", (v * 100.0).round() / 100.0))]); let choices: Vec> = PPI_CHOICES.iter().map(|&v| Entry::new(v, label(v)).enabled(v <= max + 1e-6)).collect(); Field::new(tl!("PPI")).show(ui, |ui, _| { - if let Some(v) = Select::new(tl!("PPI"), Bind::given(ppi), &choices).placeholder(label(ppi)).show(ui).value().copied() { + if let Some(v) = Select::new(tl!("PPI"), Bind::given(ppi), &choices).placeholder(label(ppi)).show(ui).events.committed().copied() { edits.push(("ppi", json!(v))); } // An image's own resolution above the limit (a linked image's, or one past 2400 ppi) still diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 6e2eeea570..6312f0006c 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -473,3 +473,57 @@ fn a_tool_card_shows_what_the_tool_does_and_what_its_keys_do() { app.run("prefs.set", json!({"key": "showToolTips", "value": false})).unwrap(); assert!(!card::Cards::new(&app).has(&"selection".to_string()), "tool tips off: no card"); } + +/// The Control bar's lists of the Mirror & Cut tool (Axis, Keep) and of Crop Image (PPI): an entry highlighted with the +/// arrow keys leaves the tool's options as they were, Escape closes the list with nothing changed, and the entry +/// chosen with Enter sets the option without touching the drawing. +#[test] +fn a_highlighted_control_bar_option_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role as Kind; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let png = vectorcraft_testkit::temp_dir("toolbar-crop-ppi").join("red.png"); + let image = craft_image_codecs::Image::from_raw( + 40, + 40, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [200u8, 40, 40, 255].repeat(40 * 40), + ) + .unwrap(); + let encoded = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + std::fs::write(&png, encoded).unwrap(); + for (tool, name, key) in [("mirrorCut", "Axis:", "axis"), ("mirrorCut", "Keep:", "keep"), (vectorcraft_tools::cropimage::ID, "PPI", "ppi")] { + let mut app = app_with(300, 300); + if tool == vectorcraft_tools::cropimage::ID { + app.run("file.place", json!({"path": png, "link": true, "at": [100.0, 100.0]})).unwrap(); + app.run("ui.cropImage", json!({})).unwrap(); + } else { + app.run("tool.select", json!({ "tool": tool })).unwrap(); + } + assert_eq!(app.session.tool_id(), tool); + let mut panel = Panel::new(app, control_bar_options); + let state = |panel: &Panel| { + let app = panel.app(); + let st = app.session.active().unwrap(); + (app.session.tool_options()[key].clone(), st.doc.clone(), st.history.undo.len()) + }; + let before = state(&panel); + panel.click_role(name, Kind::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "a highlighted {name} entry changes no option"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "Escape leaves {name} as it was"); + panel.click_role(name, Kind::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + let (option, doc, undo) = state(&panel); + assert_ne!(option, before.0, "Enter sets {name}"); + assert_eq!((doc, undo), (before.1, before.2), "{name} only changes the tool's options"); + } +} From d1dddd934a8042a9d50abf368b160f1337b52061 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 13:16:50 -0800 Subject: [PATCH 24/36] Direct Selection: a move by nothing leaves a live shape that needs no change live path.moveHandles with dx and dy of 0 only changes anchors that become corners (both handles listed, or `independent`). It still passed every listed handle on to the edit, so a live shape whose listed anchor needed no change was expanded to a plain path. The listed anchors that need no change are now left out, and the command returns without an edit when none is left. Follows #9921, which added path.moveHandles. --- crates/engine/src/cmd/path.rs | 5 +++-- crates/engine/tests/it/several_handles.rs | 21 ++++++++++++++++++++- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index efcd2b1e13..638517aec9 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -643,8 +643,9 @@ fn move_handles(s: &mut Session, p: &Value) -> Result { } // A move by nothing changes only the kind of anchors that become corners: those with both // handles listed, or every listed one with `independent`. + // The other anchors are left out, so a live shape that only they lie on is not expanded. if d == Vec2::ZERO { - let corners = anchors.iter().any(|(&(id, si, ai), &(inn, out))| { + anchors.retain(|&(id, si, ai), &mut (inn, out)| { (independent || (inn && out)) && doc .node(id) @@ -652,7 +653,7 @@ fn move_handles(s: &mut Session, p: &Value) -> Result { .and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) .is_some_and(|a| a.kind != AnchorKind::Corner) }); - if !corners { + if anchors.is_empty() { return ok(); } } diff --git a/crates/engine/tests/it/several_handles.rs b/crates/engine/tests/it/several_handles.rs index b45b6b16b6..7b5469c278 100644 --- a/crates/engine/tests/it/several_handles.rs +++ b/crates/engine/tests/it/several_handles.rs @@ -1,7 +1,7 @@ //! Direct Selection picks several direction handles and drags them together (`path.moveHandles`). use serde_json::{Value, json}; -use vectorcraft_doc::NodeId; +use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_engine::{Session, ViewInfo}; use vectorcraft_geom::{Anchor, AnchorKind, Point}; use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; @@ -191,3 +191,22 @@ fn move_handles_checks_its_params() { near(anchor(&s, id, 2).h_in, Point::new(305.0, 140.0)); assert_eq!(undo_len(&s), undo + 1); } + +/// A move by nothing that makes one path's smooth anchor a corner leaves a listed handle of a live +/// rectangle, which needs no change, alone: the rectangle stays live. +#[test] +fn a_move_by_nothing_leaves_a_live_shape_that_needs_no_change_live() { + let (mut s, id) = session(); + let rect = s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 100, "height": 60})).unwrap(); + let rect = NodeId(rect["id"].as_u64().unwrap()); + let live = |s: &Session| matches!(&s.doc().unwrap().doc.node(rect).unwrap().kind, NodeKind::Path { live: Some(_), .. }); + assert!(live(&s), "shape.rectangle makes a live rectangle"); + let handles = json!([ + {"id": id.0, "anchor": 1, "which": "in"}, + {"id": id.0, "anchor": 1, "which": "out"}, + {"id": rect.0, "anchor": 0, "which": "out"} + ]); + s.execute("path.moveHandles", &json!({"handles": handles, "dx": 0, "dy": 0})).unwrap(); + assert_eq!(anchor(&s, id, 1).kind, AnchorKind::Corner, "both handles listed make the smooth anchor a corner"); + assert!(live(&s), "the rectangle's listed handle needed no change, so the rectangle stays live"); +} From bca6e772f55d96dda33978e2b4026bc13c2d738f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 13:47:50 -0800 Subject: [PATCH 25/36] Tests: Cutout and Objects on Path clicks wait for the CJK font lookup The Japanese pass of gallery_cutout_setting_uses_its_localized_label and compact_objects_on_path_options_pivot_rotate_reset_and_save measures controls in one frame and clicks the saved positions in later frames. When the CJK font lookup finishes in between, the labels change width and the click can miss. Both tests now call wait_for_cjk_fonts() before measuring, as #9898 did for the Effect Gallery and Hyphenation tests. --- crates/ui-egui/src/dialogs/effect_params.rs | 2 ++ crates/ui-egui/src/dialogs/objects_on_path_options.rs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/crates/ui-egui/src/dialogs/effect_params.rs b/crates/ui-egui/src/dialogs/effect_params.rs index 10028d3c4b..fc8fd14c9d 100644 --- a/crates/ui-egui/src/dialogs/effect_params.rs +++ b/crates/ui-egui/src/dialogs/effect_params.rs @@ -313,6 +313,8 @@ mod tests { #[test] fn gallery_cutout_setting_uses_its_localized_label() { + // The Japanese pass measures Cutout in one frame and clicks it in a later one. + crate::testing::wait_for_cjk_fonts(); let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); let mut shown_labels = Vec::new(); for (language, expected) in [("en", "Levels"), ("de", "Stufen"), ("ja", "レベル数")] { diff --git a/crates/ui-egui/src/dialogs/objects_on_path_options.rs b/crates/ui-egui/src/dialogs/objects_on_path_options.rs index cfc699334e..cd1eb96f98 100644 --- a/crates/ui-egui/src/dialogs/objects_on_path_options.rs +++ b/crates/ui-egui/src/dialogs/objects_on_path_options.rs @@ -77,6 +77,8 @@ fn compact_objects_on_path_options_pivot_rotate_reset_and_save() { } const PIVOT_NAMES: [&str; 9] = ["Top Left", "Top", "Top Right", "Left", "Center", "Right", "Bottom Left", "Bottom", "Bottom Right"]; + // The Japanese pass measures the controls once and clicks them frames later. + crate::testing::wait_for_cjk_fonts(); let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); let mut untranslated = Vec::new(); for lang in ["en", "de", "fr", "ja"] { From 06c260f63742d1a1d98d052fe5c7fc142e534085 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 13:59:20 -0800 Subject: [PATCH 26/36] Render: redraw the effects on a shadowed radial or mirror repeat's copies A radial or mirror repeat with an effect of its own, such as a drop shadow, takes its bounds from the object-effects branch, which falls back to `own_box`. `own_box` measured the placed steps of a spine-aligned blend but not the rotated or reflected copies of a repeat, so moving such a repeat left the copies' geometry effects outside the redrawn area. `own_box` now unions a repeat's placed copies as #9936 does in `cull_bounds_in`. `placed_live_effect_bounds` now looks for effects below the node only: the node's own effects run on the placed whole and its callers measure them, so a repeat or blend whose only effect is its own no longer expands its copies or steps to measure them. --- crates/render/src/fx/bounds.rs | 23 ++++++++++++--------- crates/render/src/tests/changed.rs | 33 ++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 2e05fca92b..2eece1125f 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -843,12 +843,13 @@ pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) -> b.inflate(o, o) } -/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]) and a blend's to hold its -/// spine-placed keys and steps: what it draws when its object effects leave it as it is -/// (Revolve builds no art from type). +/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]), a blend's to hold its +/// spine-placed keys and steps and a radial or mirror repeat's to hold its placed copies: what it +/// draws when its object effects leave it as it is (Revolve builds no art from type). fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option { let b = match &n.kind { NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_live_effect_bounds(symbols, n)), + NodeKind::Repeat(_) => vectorcraft_geom::union_opt(n.visual_bounds_with(symbols), placed_live_effect_bounds(symbols, n)), _ => n.visual_bounds_with(symbols), }?; Some(match &n.kind { @@ -860,7 +861,8 @@ fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option { /// A radial or mirror repeat's copies or a spine-aligned blend's steps, measured after they are /// rotated or reflected. Geometry effects run on the placed shapes, so their reach on the source /// need not cover what they paint. -/// Without effects, the renderer keeps the quick bounds without evaluating the copies or steps. +/// Without effects inside it, the renderer keeps the quick bounds without evaluating the copies or +/// steps; `n`'s own effects run on the placed whole and are measured by the caller. fn placed_live_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { match &n.kind { NodeKind::Blend { spec, .. } if spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath => {} @@ -869,12 +871,13 @@ fn placed_live_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { } let mut has_effects = false; n.walk(&mut |c| { - has_effects |= has_fx(c) - || has_object_fx(c) - || match &c.kind { - NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol), - _ => false, - }; + has_effects |= !std::ptr::eq(c, n) + && (has_fx(c) + || has_object_fx(c) + || match &c.kind { + NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol), + _ => false, + }); }); if !has_effects { return None; diff --git a/crates/render/src/tests/changed.rs b/crates/render/src/tests/changed.rs index 4440c06baf..d97bfd7baf 100644 --- a/crates/render/src/tests/changed.rs +++ b/crates/render/src/tests/changed.rs @@ -227,6 +227,39 @@ fn moving_a_slanted_mirror_repeat_redraws_the_effects_on_its_reflected_copy() { } } +#[test] +fn moving_a_shadowed_radial_or_mirror_repeat_redraws_the_effects_on_its_copies() { + for radial in [true, false] { + let mut old = Document::new(110.0, 80.0); + let source_id = old.alloc_id(); + let mut source = Node::path( + source_id, + shapes::rectangle(Rect::new(47.0, 25.0, 49.0, 45.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + source.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"scaleH": 400, "scaleV": 100, "reference": 4}), + visible: true, + }); + let repeat = if radial { + vectorcraft_doc::RepeatSpec::radial(vec![Arc::new(source)], 4, Some(12.0)) + } else { + vectorcraft_doc::RepeatSpec::mirror(vec![Arc::new(source)], 45.0, 6.0) + }; + let id = old.alloc_id(); + let mut node = Node::new(id, vectorcraft_doc::NodeKind::Repeat(repeat)); + // The repeat's own effect sends its bounds through the object-effects branch. + node.appearance.effects.push(shadow()); + old.insert(Some(old.layers[0].id), 0, node).unwrap(); + let mut moved = old.clone(); + moved.node_mut(id).unwrap().transform(Affine::translate((3.0, 4.0)), false); + // A partial redraw must reproduce the whole frame, both on the move and on Undo. + area(redraw(&old, &moved)); + area(redraw(&moved, &old)); + } +} + #[test] fn adding_removing_and_restacking_change_those_objects() { let (old, [loose, _, _, _, other]) = document(); From 1ce80e6d48111e95c0334f1081d03d1401dc93b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 14:18:20 -0800 Subject: [PATCH 27/36] Paint: Invert and Complement refuse a bad target with nothing selected With nothing selected, `paint.invert` and `paint.complement` recolored the default fill or stroke before reading `target` and `aligned`, so a bad value was accepted and changed the default. They now read both before the default branch, as #8099 does for `paint.setFill` and `paint.setStroke`. --- crates/engine/src/cmd/paint.rs | 4 +++- crates/engine/src/tests/build.rs | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index b8136e8cf5..4ec75a202e 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -1986,6 +1986,8 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( Some(ids) => ids, None => super::edit::selected_roots(s)?, }; + // Read before the default is recolored, so that a bad `target` or `aligned` is refused with nothing selected too. + let item = item_target(s, p, cmd)?; if ids.is_empty() { let def = if stroke { &mut s.paint.stroke } else { &mut s.paint.fill }; let changed = super::colorcmds::map_paint(def, f); @@ -1993,7 +1995,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( s.remember_paint(&shown); return Ok(json!({ "changed": changed as usize })); } - let item = item_target(s, p, cmd)?.of_kind(s, !stroke); + let item = item.of_kind(s, !stroke); // Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has // no row for) is still an error. let targets = super::appearance::drop_design_art_rows(s, item.targets_for(s, p, !stroke)?, item, !stroke, cmd)?; diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 320d6ba70f..6ccdfad0a5 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -4046,6 +4046,26 @@ fn live_paint_bucket_refuses_a_bad_target_or_aligned() { } } +/// With nothing selected, Invert and Complement refuse a bad `target` or `aligned` and leave the +/// default fill and stroke as they are. +#[test] +fn invert_and_complement_refuse_a_bad_target_or_aligned_with_nothing_selected() { + let mut s = session(); + s.execute("paint.setFill", &json!({"color": "#336699", "defaultsOnly": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = (s.paint.fill.clone(), s.paint.stroke.clone()); + for cmd in ["paint.invert", "paint.complement"] { + for p in + [json!({"stroke": false, "target": "content"}), json!({"stroke": false, "aligned": "yes"}), json!({"stroke": true, "target": "bogus"})] + { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone()), before, "{cmd} {p}"); + } + } + s.execute("paint.invert", &json!({"stroke": false})).unwrap(); + assert_ne!(s.paint.fill, before.0, "a good call still inverts the default"); +} + /// While the Live Paint Bucket is active, each preview of a paint command in one interaction starts /// from the colors the interaction began with, so previewing a swap twice and committing swaps once. #[test] From 05d2b519987e53ab3b8d2e25871c3b2d5399c915 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 14:50:13 -0800 Subject: [PATCH 28/36] Docs: scope the numeric collection name rule to pageItems and documents Tags still returns undefined for a number that is not an array index and does not look it up by name, so the progress line names only the two collections that do, and describes the key as the text JavaScript writes for a number that is not an array index. The script guide now says that assigning to such a name is ignored outside strict mode and throws a TypeError in strict mode code or with #strict on, instead of Not found. --- docs/mcp.md | 5 +++-- docs/target-app-parity.md | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 36d400efbd..49d1aad90e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2923,7 +2923,8 @@ other files through `$`: `Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too (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. This applies only to the text JavaScript writes for that number: `pageItems["1.50"]` is a + when nothing has it; assigning to such a name is then ignored outside strict mode and throws a `TypeError` in + strict mode code or with `#strict on`, instead of `Not found`. This applies only to the text JavaScript writes for that number: `pageItems["1.50"]` is a plain name and throws `Not found` when nothing has it. `"-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 @@ -2965,7 +2966,7 @@ other files through `$`: other properties but not the methods. `Object.keys`, `Object.getOwnPropertyNames` and `Object.getOwnPropertyDescriptor` do not report any member of the class. Assigning a member that a page item, a layer, a document or the application does not have does not keep the value; it does not throw, except in - strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, as described above. Other members + strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, except for the text of a number that is not an array index, as described above. 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`. - A `Document` also has `variables`, `dataSets`, `activeDataset`, `variablesLocked`, `importVariables(file)` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b9f41b771e..77da02ba3f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1110,7 +1110,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/). A key such as `1` is an array index and reads that position; only a number outside the array-index range, such as `-1` or `1.5`, is looked up by name. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. From b6598491f5fa9c5d2e161eee5bdfdc99909b0b04 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 15:32:25 -0800 Subject: [PATCH 29/36] Canvas: a wheel pan or zoom keeps the tool's cursor until the view is still The tool host asks the canvas tool for its cursor in every pass with the pointer over the canvas. The selection tools answer by hit-testing the art under the pointer, so each frame of a wheel pan or zoom under a resting pointer walked every object. The canvas now keeps the cursor the tool last gave for the same tool and keys while the view moves, and asks again once the view has been still for HOVER_STILL_SECS, as it already does for Object Highlighting and the shown tool (#2452). --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/caches.rs | 3 ++ crates/ui-egui/src/canvas/tests.rs | 44 +++++++++++++++++++++++ crates/ui-egui/src/canvas/tool_adapter.rs | 29 ++++++++++++++- 4 files changed, 76 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index df93dc6bac..4729b05ea4 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -148,6 +148,7 @@ impl VectorcraftApp { plugin_keys: Default::default(), placed_keys: Default::default(), view_moved: None, + hover_cursor: None, hover_object: None, grab: None, carry_target: None, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6907b7ce17..1c5aa8324f 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -101,6 +101,9 @@ pub struct CanvasCache { /// The view the canvas last drew and when it last changed (egui's input time): while it moves, /// the canvas doesn't hit-test the art under the pointer ([`canvas::hover_wait`], #2452). pub view_moved: Option<(canvas::ViewKey, f64)>, + /// The cursor the active tool last gave over the canvas, with the tool and the modifier keys + /// it was for: kept while the view moves. + pub hover_cursor: Option<(&'static str, vectorcraft_tools::Mods, vectorcraft_tools::Cursor)>, /// The object the Eyedropper's click at the pointer would act on, which Object Highlighting /// outlines, with what it was found for: finding it again, which can sample a color, waits /// until one of those changes. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3f1eddb392..2ed90409d7 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6700,3 +6700,47 @@ fn a_move_stops_snapping_to_guides_hidden_during_it() { assert!((centre - xf.to_doc(near).x).abs() < 1e-4 || snaps, "{hide:?}: unsnapped, it follows the pointer: {centre}"); } } + +/// While the wheel pans the view under a resting pointer, the canvas keeps the tool's last cursor instead of asking the +/// tool for it in every frame, which hit-tests the art under the pointer each time (#2452). Once the view has been +/// still for `HOVER_STILL_SECS`, the tool is asked again. +#[test] +fn a_wheel_pan_under_a_resting_pointer_keeps_the_tool_cursor() { + let asks = || super::tool_adapter::CURSOR_ASKS.with(std::cell::Cell::get); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..20 { + let x = f64::from(i) * 15.0; + app.session.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 10, "height": 10})).unwrap(); + } + app.select_tool("selection"); + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } + let at = app.canvas_view().unwrap().rect.center(); + // The pointer comes in and rests, and the view is still: the tool gives its cursor. + for _ in 0..12 { + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + } + assert!(asks() > 0, "the tool gives the cursor over a still view"); + let wheel = |dy: f32| egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, dy), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::default(), + source: egui::MouseWheelSource::Unknown, + }; + let before = (asks(), app.canvas_view().unwrap().center); + for i in 0..10 { + app_step(&mut app, &ctx, vec![wheel(if i % 2 == 0 { -2.0 } else { 3.0 })]); + } + assert_ne!(app.canvas_view().unwrap().center, before.1, "the wheel pans the view"); + assert_eq!(asks() - before.0, 0, "no frame of the pan asks the tool for its cursor"); + // Still for longer than HOVER_STILL_SECS (egui steps 1/60 s per frame here): the tool is asked again. + let before = asks(); + for _ in 0..20 { + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + } + assert!(asks() > before, "once the view is still, the tool gives the cursor again"); +} diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index af12608aa5..cc62cc3fe6 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -18,6 +18,12 @@ use vectorcraft_tools::{Mods, PenPose, PointerEvent, PointerKind, ToolKey as Eng use super::{Ui, VectorcraftApp}; use crate::cursors::tool_cursor; +#[cfg(test)] +thread_local! { + /// How many times [`SessionTool`] asked the session for the tool's cursor on this thread. + pub(crate) static CURSOR_ASKS: Cell = const { Cell::new(0) }; +} + /// The tools that change only the view: they neither autoscroll nor take the document's presses under a modal. const VIEW_TOOLS: [&str; 3] = ["hand", "zoom", "rotateView"]; @@ -548,10 +554,31 @@ impl CanvasTool for SessionTool<'_> { // The document's overlays are shown by `overlays::show` after the host, in one list. } + /// While the view moves under the pointer, the cursor the tool last gave for the same tool and keys stays: asking + /// the tool again would hit-test the art under the pointer in every frame of a pan or zoom (#2452). fn cursor(&self, cx: &ToolContext<'_>) -> Cursor { let Some(space) = cx.space() else { return tool_cursor(vectorcraft_tools::Cursor::Arrow) }; let at = cx.pointer.map_or(Point::ZERO, |p| space.view.to_doc(p.pos)); - let c = self.app().session.cursor(at, tool_mods(cx.mods, cx.held(Key::Space)), self.view); + let mods = tool_mods(cx.mods, cx.held(Key::Space)); + let mut app = self.app(); + let wait = + super::cursor::hover_wait(&mut app.canvas.view_moved, super::ViewKey::of(&space.view), craft::ui::runtime::frame::clock(&self.ctx)); + let id = app.session.tool_id(); + let kept = app.canvas.hover_cursor.filter(|&(was, with, _)| wait.is_some() && (was, with) == (id, mods)).map(|(.., c)| c); + let c = match kept { + Some(c) => c, + None => { + #[cfg(test)] + CURSOR_ASKS.with(|n| n.set(n.get() + 1)); + let c = app.session.cursor(at, mods, self.view); + app.canvas.hover_cursor = Some((id, mods, c)); + c + } + }; + // Once the view has been still long enough, the next pass asks the tool again. + if let Some(secs) = wait { + self.ctx.request_repaint_after_secs(secs as f32); + } // PLAN: assumed the engine's own precise step is dropped (canvas-w25); the canvas's Caps Lock/preference state arrives as `cx.precise()`. tool_cursor(if cx.precise() { c.precise() } else { c }) } From 322869e87c8cfaaf909281353d65ceb0c98329c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 15:38:15 -0800 Subject: [PATCH 30/36] Tests: panel harness clicks fail on controls outside the window Panel::in_view reported a control as visible when its rect lay past the fixture's window, because the fixture's visible check clips only to the arena. A click or press then aimed at a point outside the window, hit nothing, and the test failed later on an unrelated assertion. in_view now also clips to the window (the room, at least 800 by 600 points). click, press, double and right clicks, drags, typing and click_part check that the point they aim at is inside the window and fail with a message that names the control, its rect and the window. --- crates/ui-egui/src/tests/panel_harness.rs | 100 +++++++++++++++++++--- 1 file changed, 86 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 75801d93fe..83434e98e7 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -102,9 +102,33 @@ impl Panel { self.look(name) } + /// The fixture's window in the latest frame: the room, or 800 by 600 points where the room is smaller. Dialogs and + /// menus open anywhere in it; the panel is laid out in the room. + fn window(&self) -> Rect { + self.ctx().content_rect() + } + + /// `target`, the control named `name`, once its center is in the window: a pointer aimed at a center outside the + /// window reaches no control. + fn aim(&self, name: &str, target: Target) -> Target { + let window = self.window(); + assert!( + window.contains(target.center()), + "{name:?} at {:?} has its center outside the window {window:?}, so a pointer aimed at it reaches no control", + target.rect + ); + target + } + + /// [`Panel::find`], then [`Panel::aim`]. + fn find_aimed(&mut self, name: &str) -> Target { + let target = self.find(name); + self.aim(name, target) + } + /// Clicks the control named `name`. pub(crate) fn click(&mut self, name: &str) { - let target = self.find(name); + let target = self.find_aimed(name); self.fixture.click(&target); self.after(); } @@ -114,6 +138,7 @@ impl Panel { let tree = self.fixture.tree(); let item = self.fixture.by_role(craft::ui::contract::Role::MENU_ITEM).into_iter().find(|t| tree.name_of(t.node) == Some(name)); let item = item.unwrap_or_else(|| panic!("no menu item {name:?} in {:?}", self.names())); + let item = self.aim(name, item); self.fixture.click(&item); self.after(); } @@ -135,7 +160,7 @@ impl Panel { /// [`Panel::click_role`] with `mods` held. pub(crate) fn click_role_with(&mut self, name: &str, role: craft::ui::contract::Role, mods: Modifiers) { self.frame(); - let target = self.look_role(name, role); + let target = self.aim(name, self.look_role(name, role)); self.fixture.hold(mods).click(&target).hold(Modifiers::NONE); self.after(); } @@ -149,6 +174,7 @@ impl Panel { self.fixture.by_role(role).into_iter().filter(|t| tree.name_of(t.node) == Some(name)).nth(index) }; let target = target.unwrap_or_else(|| panic!("no {role:?} named {name:?} at {index} in {:?}", self.names())); + let target = self.aim(name, target); self.fixture.click(&target); self.after(); } @@ -169,7 +195,7 @@ impl Panel { /// Clicks the control named `name` with `mods` held. pub(crate) fn click_with(&mut self, name: &str, mods: Modifiers) { - let target = self.find(name); + let target = self.find_aimed(name); self.fixture.hold(mods).click(&target).hold(Modifiers::NONE); self.after(); } @@ -187,7 +213,7 @@ impl Panel { /// Presses on the control named `name` and keeps the button down until [`Panel::release`]. pub(crate) fn press(&mut self, name: &str) { - let target = self.find(name); + let target = self.find_aimed(name); self.fixture.press(&target); self.after(); } @@ -196,7 +222,7 @@ impl Panel { /// the name (a slider beside its number box). pub(crate) fn drag_hold_role(&mut self, name: &str, role: craft::ui::contract::Role, by: Vec2) { self.frame(); - let from = self.look_role(name, role).center(); + let from = self.aim(name, self.look_role(name, role)).center(); self.drag_hold_between(from, from + by); } @@ -234,7 +260,7 @@ impl Panel { .into_iter() .flat_map(|role| self.fixture.by_role(role)) .find(|t| tree.name_of(t.node) == Some(name)); - typed.unwrap_or_else(|| self.look(name)) + self.aim(name, typed.unwrap_or_else(|| self.look(name))) } /// Types `text` into the focused field. @@ -258,13 +284,13 @@ impl Panel { /// Drags from the control named `from` to the one named `to`. pub(crate) fn drag(&mut self, from: &str, to: &str, mods: Modifiers) { - let to = self.find(to).center(); + let to = self.find_aimed(to).center(); self.drag_to(from, to, mods); } /// Drags from the control named `from` and releases at `to`. pub(crate) fn drag_to(&mut self, from: &str, to: Pos2, mods: Modifiers) { - let from = self.find(from).center(); + let from = self.find_aimed(from).center(); self.drag_between(from, to, mods); } @@ -278,7 +304,8 @@ impl Panel { /// Clicks the pointer-only part `part` (a row's thumbnail, a step arrow) of the control named `name`. pub(crate) fn click_part(&mut self, name: &str, part: impl Into, mods: Modifiers) { let (target, part) = (self.find(name), part.into()); - let at = part_rect_of_node(self.ctx(), target.node.into(), part).unwrap_or_else(|| panic!("{name:?} has no part {part:?}")).center(); + let rect = part_rect_of_node(self.ctx(), target.node.into(), part).unwrap_or_else(|| panic!("{name:?} has no part {part:?}")); + let at = self.aim(&format!("{name}'s part {part:?}"), Target { node: target.node, rect }).center(); self.fixture.hold(mods).click_at(at).hold(Modifiers::NONE); self.after(); } @@ -291,21 +318,21 @@ impl Panel { /// Two clicks on the control named `name`, close enough in time to be a double click. pub(crate) fn double_click(&mut self, name: &str) { - let target = self.find(name); + let target = self.find_aimed(name); self.fixture.click(&target).click(&target); self.after(); } /// A right click on the control named `name`. pub(crate) fn secondary_click(&mut self, name: &str) { - let at = self.find(name).center(); + let at = self.find_aimed(name).center(); self.secondary_click_at(at); } /// Right-clicks the zero-based control of `role`, including rows with identical names. pub(crate) fn secondary_click_nth(&mut self, role: craft::ui::contract::Role, index: usize) { self.frame(); - let at = self.look_nth(role, index).center(); + let at = self.aim(&format!("{role:?} at {index}"), self.look_nth(role, index)).center(); self.secondary_click_at(at); } @@ -337,9 +364,11 @@ impl Panel { tree.keys().into_iter().any(|key| tree.role_of(key) == Some(Role::STATUS) && tree.name_of(key) == Some(text)) } - /// Whether some of the control named `name` can be seen in the latest frame. + /// Whether some of the control named `name` can be seen in the latest frame: inside its arena's clip and inside the + /// window. pub(crate) fn in_view(&self, name: &str) -> bool { - self.fixture.visible(&self.look(name)).is_some() + let seen = self.fixture.visible(&self.look(name)).map(|t| t.rect.intersect(self.window())); + seen.is_some_and(|r| r.width() >= 0.0 && r.height() >= 0.0) } /// Whether the control named `name` takes input. @@ -550,3 +579,46 @@ pub(crate) fn floated(mut app: VectorcraftApp, panel: &str, lang: &str, place: P } Shown { body, nodes, names } } + +#[cfg(test)] +mod tests { + use std::panic::{AssertUnwindSafe, catch_unwind}; + + use craft::ui::buttons::Button; + use craft::ui::contract::Show as _; + use egui::{Pos2, Rect, Ui, vec2}; + use vectorcraft_engine::Session; + + use super::{Panel, ROOM}; + use crate::VectorcraftApp; + + /// A button at the top of the room and one a room's height below it, past the bottom of the window. + fn show(_: &mut VectorcraftApp, ui: &mut Ui) { + Button::new("Above").show(ui); + ui.allocate_space(vec2(100.0, ROOM.y)); + Button::new("Below").show(ui); + } + + /// The message of the panic `drive` ends with, or `None` when it returns. + fn panic_of(drive: impl FnOnce()) -> Option { + let payload = catch_unwind(AssertUnwindSafe(drive)).err()?; + payload.downcast_ref::().cloned().or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned())) + } + + #[test] + fn a_control_below_the_window_is_out_of_view_and_cannot_be_clicked_or_pressed() { + let mut panel = Panel::new(VectorcraftApp::new(Session::new(), Default::default()), show); + // The fixture's window is as tall as the room and at least 800 points wide. + let window = Rect::from_min_size(Pos2::ZERO, ROOM.max(vec2(800.0, 600.0))); + let below = panel.rect("Below"); + assert!(below.top() > window.bottom(), "the button is drawn below the window {window:?}: {below:?}"); + assert!(panel.in_view("Above"), "the button at the top is in view"); + assert!(!panel.in_view("Below"), "the button below the window is out of view: {below:?}"); + assert_eq!(panic_of(|| panel.click("Above")), None, "the button at the top takes a click"); + for (driver, message) in [("click", panic_of(|| panel.click("Below"))), ("press", panic_of(|| panel.press("Below")))] { + let message = message.unwrap_or_else(|| panic!("{driver} on the button below the window went ahead")); + let expected = format!("\"Below\" at {below:?} has its center outside the window {window:?}"); + assert!(message.starts_with(&expected), "{driver} fails naming the control, its rect and the window: {message}"); + } + } +} From c49e10268e75ecf1852e9153889da78847d02c64 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 16:06:58 -0800 Subject: [PATCH 31/36] =?UTF-8?q?Add-on=20dialogs:=20a=20draft=20from=20be?= =?UTF-8?q?fore=20File=20=E2=80=BA=20Revert=20leaves=20the=20restored=20dr?= =?UTF-8?q?awing=20alone?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shared add-on dialogs checked only the document's uid, which File › Revert keeps while it replaces the drawing. A dialog left open across a revert previewed on and applied to the restored art. They now record the revert count with the uid, stop previewing after a revert, and refuse OK with "The document was reverted. Reopen this dialog to continue.", as Vector Halftone does since #9943. --- crates/ui-egui/src/addons/dialogs.rs | 23 +++++++++++---- crates/ui-egui/src/addons/dialogs/tests.rs | 34 ++++++++++++++++++++++ 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 03f69718b9..e58443e259 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -42,13 +42,24 @@ pub(crate) struct AddonDialogs { struct Open { id: DialogId, spec: &'static Spec, - document: Option, + /// The opening document's uid and revert count: File › Revert keeps the uid but replaces the drawing. + document: Option<(u64, u64)>, } impl Open { fn on_document(self, app: &VectorcraftApp) -> bool { - self.document == app.session.active().map(|state| state.uid) + self.document == active_document(app) } + + /// Whether the active document is the opening one, reverted since the dialog opened. + fn reverted(self, app: &VectorcraftApp) -> bool { + matches!((self.document, active_document(app)), (Some((uid, reverts)), Some((now, again))) if uid == now && reverts != again) + } +} + +/// The active document's uid and revert count. +fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> { + app.session.active().map(|state| (state.uid, state.reverts)) } /// Closes the open add-on dialog without an answer and rolls its preview back. @@ -81,7 +92,7 @@ pub(crate) fn open( close_open(app); let id = dialog.id(); host.with(|h| h.open(dialog)); - app.addon_dialogs.open = Some(Open { id, spec, document: app.session.active().map(|state| state.uid) }); + app.addon_dialogs.open = Some(Open { id, spec, document: active_document(app) }); Ok(json!({ "dialog": spec.command })) } @@ -141,8 +152,10 @@ fn pump_commit(app: &mut VectorcraftApp) { app.addon_dialogs.open = None; let preview = mem::take(&mut app.addon_dialogs.preview); // The dialog is closed already, so a refusal can only go to the status line. - if !on_document { - app.status(tl!("The add-on settings apply only to the drawing where the dialog opened.").to_owned()); + if open.reverted(app) { + app.status("The document was reverted. Reopen this dialog to continue."); + } else if !on_document { + app.status("The add-on settings apply only to the drawing where the dialog opened."); } else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) { app.status(error); } diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index b7f648aa1e..679a2e2e34 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -340,6 +340,40 @@ fn an_add_on_confirmation_does_not_edit_another_drawing_before_the_pump() { assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, source_undo)); } +/// Saves the two rectangles of [`two_rects`] to a file in the returned directory, so File › Revert has a copy to restore. +fn two_saved_rects(tag: &str) -> (VectorcraftApp, vectorcraft_testkit::TempDir) { + let mut app = two_rects(); + let dir = vectorcraft_testkit::TempDir::new(tag); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + (app, dir) +} + +#[test] +fn an_add_on_draft_from_before_file_revert_leaves_the_restored_drawing_alone() { + let (mut app, _dir) = two_saved_rects("addon-revert"); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "previewed before the revert"); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let restored = app.session.doc().unwrap().doc.clone(); + let undo = undo_len(&app); + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc, restored, "the draft does not preview on the restored drawing"); + assert!(!app.session.in_interaction()); + assert!(confirm(&app, id)); + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc, restored, "OK leaves the restored drawing unchanged"); + assert_eq!(undo_len(&app), undo, "OK records no undo step"); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); +} + #[test] fn an_add_on_cancel_leaves_the_other_drawings_interaction_running() { let mut app = two_drawings(); From 48300cebe30b6b2593a92f1a817de5d4a86418d5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 16:34:40 -0800 Subject: [PATCH 32/36] Layers: the selection squares read held art from the listed rows Each frame with the Layers panel open, every row's selection square walked the art below its node to find whether it held a selected object, so a layer with 10,000 objects walked all of them in every frame. The rows now list the nodes that hold selected art in one pass over the tree when they are listed again (on each revision or selection change), and the square reads that list. --- crates/ui-egui/src/panels/layers/cells.rs | 10 +++----- crates/ui-egui/src/panels/layers/model.rs | 9 +++++++ crates/ui-egui/src/panels/layers/rows.rs | 31 +++++++++++++++++++++++ crates/ui-egui/src/panels/layers/tests.rs | 24 ++++++++++++++++++ 4 files changed, 67 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/panels/layers/cells.rs b/crates/ui-egui/src/panels/layers/cells.rs index ce0de11247..d12f248bb4 100644 --- a/crates/ui-egui/src/panels/layers/cells.rs +++ b/crates/ui-egui/src/panels/layers/cells.rs @@ -357,15 +357,11 @@ impl Component for Cells { /// The marks of node row `n`'s selection square in the panel over `tree`: whether it shows the /// full-sized square (the row is selected, or it is a layer or sublayer whose visible, unlocked art -/// is all selected), and whether it shows the small one (it holds selected art otherwise). +/// is all selected), and whether it shows the small one (it holds selected art otherwise). It reads +/// the nodes that hold selected art from the rows, which list them once per revision. pub(super) fn square_marks(tree: &DocLayers<'_>, n: &Node) -> (bool, bool) { let full = tree.is_selected(n.id) || tree.is_full(n.id); - let holds = !full && { - let mut any = false; - n.walk(&mut |c| any |= c.id != n.id && tree.is_selected(c.id)); - any - }; - (full, holds) + (full, !full && tree.holds_selected(n.id)) } /// The cells of row `row` (shown as `info`) of the panel over `tree`. diff --git a/crates/ui-egui/src/panels/layers/model.rs b/crates/ui-egui/src/panels/layers/model.rs index 57345e5040..c73794b6d0 100644 --- a/crates/ui-egui/src/panels/layers/model.rs +++ b/crates/ui-egui/src/panels/layers/model.rs @@ -193,6 +193,9 @@ pub(super) struct LayerRows { /// and not empty. #[plain_data(assume = "node ids are integers")] full: HashSet, + /// The nodes that hold a selected object below them ([`super::rows::holding`]). + #[plain_data(assume = "node ids are integers")] + holding: HashSet, /// The selected blends, in selection order. #[plain_data(assume = "node ids are integers")] blends: Vec, @@ -252,6 +255,7 @@ impl LayerRows { ruler, guide_rows, full: super::rows::full_layers(doc, &selected), + holding: super::rows::holding(doc, &selected), selected, blends: blends.collect(), root: st.isolation.and_then(|i| isolated_root(doc, i)).map(|(n, ..)| n.id), @@ -310,6 +314,11 @@ impl LayerRows { self.full.contains(&id) } + /// Whether node `id` holds a selected object below it. + pub(super) fn holds_selected(&self, id: NodeId) -> bool { + self.holding.contains(&id) + } + /// The node ids a row menu's command acts on: every highlighted row when the menu's row is one of /// them, else the row's own node. pub(super) fn targets(&self, target: &MenuTarget) -> Vec { diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 8b1ca836fe..c7f140123c 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -150,6 +150,37 @@ pub(super) fn full_layers(doc: &Document, sel: &HashSet) -> HashSet = const { std::cell::Cell::new(0) }; +} + +/// The nodes of `doc` that hold an object of `sel` below them, found in one pass over the tree: the rows whose +/// selection square shows the small mark when they are not full. +pub(super) fn holding(doc: &Document, sel: &HashSet) -> HashSet { + /// Adds `n` to `out` when an object of `sel` is below it, and returns whether `n` or one below it is in `sel`. + fn visit(n: &Node, sel: &HashSet, out: &mut HashSet) -> bool { + #[cfg(test)] + HOLDING_VISITS.with(|v| v.set(v.get() + 1)); + let mut below = false; + for c in n.children().into_iter().flatten() { + below |= visit(c, sel, out); + } + if below { + out.insert(n.id); + } + below || sel.contains(&n.id) + } + let mut out = HashSet::new(); + if !sel.is_empty() { + for n in &doc.layers { + visit(n, sel, &mut out); + } + } + out +} + /// The `layer.target` of a click with `mods` on the target circle of `id`, by the rules of a row click (#8639): plain /// targets it, Ctrl/Cmd adds it to the selection or takes it out, Shift selects the art of every row `filter` lists /// from `anchor` (the last circle clicked, else the targeted row) to it, and Shift+Ctrl/Cmd adds that art. With it, diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 2cd61e7083..5eeca21a8e 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -1328,3 +1328,27 @@ fn a_target_circle_drop_after_file_revert_leaves_the_restored_appearance_in_plac panel.drag("Target A", "Target B", Modifiers::NONE); assert_eq!(fill(&panel.app(), b), red, "a target circle drag started after the revert still moves the appearance"); } + +/// The rows find which nodes hold selected art once per revision: frames that change nothing walk no node for the +/// selection squares, and a new selection walks the tree once. +#[test] +fn idle_frames_walk_no_node_for_the_selection_squares() { + use crate::tests::panel_harness::Panel; + let visits = || super::rows::HOLDING_VISITS.with(std::cell::Cell::get); + let (mut app, [layer, sub, g, b, a, c]) = nested(); + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let mut panel = Panel::new(app, show); + panel.frame(); + assert_eq!(squares(&panel.app(), &[layer, sub, g, b, a, c]), (vec![b], vec![layer, sub, g]), "the layers and the group hold B"); + let before = visits(); + for _ in 0..10 { + panel.frame(); + } + assert_eq!(visits() - before, 0, "frames that change nothing walk no node"); + panel.app().session.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let before = visits(); + for _ in 0..5 { + panel.frame(); + } + assert!((1..=12).contains(&(visits() - before)), "a new selection walks the tree once: {}", visits() - before); +} From 7f96211081eeb1e4b0b13fd82ec2cd0c333e33bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 16:35:00 -0800 Subject: [PATCH 33/36] Docs: state the zero-offset rule for path.moveHandles The params text and docs/mcp.md now say that a move by 0, 0 changes only the anchors it makes corners, so a live shape whose listed anchors need no change stays live, and one with an anchor made a corner becomes a plain path. --- crates/engine/src/cmd/path.rs | 2 +- docs/mcp.md | 6 ++++-- docs/target-app-parity.md | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 638517aec9..78d24a20b5 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -59,7 +59,7 @@ pub fn specs() -> Vec { "Move Direction Handles", [], None, - "{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused", + "{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; a move by 0, 0 changes only the anchors it makes corners, so a live shape with no such anchor stays live and one with such an anchor becomes a plain path, and with none it changes nothing and records no undo step; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused", has_doc, move_handles ), diff --git a/docs/mcp.md b/docs/mcp.md index 32d41a1c4a..6c1eabe8c3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7968,8 +7968,10 @@ same way for a blend's spine point; without `handle` it is refused. These rules on one path or several, by the same offset as one undo step. An anchor with one handle listed places it as `path.setHandle` does, so a smooth anchor turns its other handle in line at its own length; an anchor with both handles listed moves both and becomes a corner. `independent: true` makes the anchor of every listed handle a corner and leaves -its other handle where it is. A handle listed twice moves once, and a move by 0, 0 that makes no anchor a corner leaves -the document as it is and records no undo step. An empty or missing `handles`, a `which` other than `"in"` or `"out"`, +its other handle where it is. A handle listed twice moves once. A move by 0, 0 changes only the anchors it makes corners, so a live +shape whose listed anchors need no change stays live, and a live shape with an anchor it makes a corner becomes a plain +path; when it makes no anchor a corner it leaves the document as it is +and records no undo step. An empty or missing `handles`, a `which` other than `"in"` or `"out"`, an object that is not a path, a missing subpath or anchor, a `dx` or `dy` that is missing, not a number or 1e9 pt or more in size, and an `independent` that is not true or false are refused, and the document does not change. With Direct Selection, a click on the end of a direction handle of a path picks that handle, a Shift-click adds it to the picked diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ca31fe8761..efab13e249 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1605,7 +1605,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Direct Selection (#1278):** clicking a segment picks its connection, with hollow endpoint anchors and only that curve's direction handles. Delete leaves the neighboring curves and appearance intact, opens/splits contours in one undo step, and another Delete removes the remaining selected path. A whole-path drag and deliberate anchor selection keep their existing behavior; egui frames and native control/art checked, OS mouse/visual QA pending. Where anchors of overlapping objects coincide, a click or drag takes the anchor of the selected object, also when another object lies over it (#1509, fixes #1508). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Double-clicking type (including type nested inside a group) switches to the Type tool and puts the caret at the clicked character. With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group. VectorCraft's own preference General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`, off by default, fixes #7832): on, a Direct Selection drag, an arrow-key nudge, a Move or a Transform Again of selected anchors re-maps both handles of each segment with one moved end by the turn, uniform scale and move that take its old ends to its new ends, so a segment between corner anchors keeps its shape; a segment with both ends moved, or with its ends at the same place before or after the move, moves rigidly, and a smooth anchor keeps its handles in line. The commands take an `interpolate` param that defaults to the preference, and the value used joins the journal and Transform Again. Each drag or nudge is one undo step (`a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment`, `a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step`, `a_smooth_anchor_keeps_its_handles_in_line`). - Picking several direction handles is VectorCraft's own behavior. With Direct Selection, a click on a path's direction handle picks it, a Shift-click adds or removes it without moving it, and Escape lets the picked handles go. Dragging one of two or more picked handles moves all of them, on one path or several, by the same offset in one undo step (`path.moveHandles`); an anchor with both handles picked becomes a corner, and Alt makes each moved handle's anchor a corner (`a_drag_of_one_of_two_picked_handles_moves_both_in_one_undo_step`, `shift_click_and_escape_let_picked_handles_go`, `both_handles_of_an_anchor_or_alt_make_a_corner` in `crates/engine/tests/it/several_handles.rs`). + Picking several direction handles is VectorCraft's own behavior. With Direct Selection, a click on a path's direction handle picks it, a Shift-click adds or removes it without moving it, and Escape lets the picked handles go. Dragging one of two or more picked handles moves all of them, on one path or several, by the same offset in one undo step (`path.moveHandles`); an anchor with both handles picked becomes a corner, and Alt makes each moved handle's anchor a corner; a move by 0, 0 leaves a live shape live when it makes none of its anchors a corner (`a_drag_of_one_of_two_picked_handles_moves_both_in_one_undo_step`, `shift_click_and_escape_let_picked_handles_go`, `both_handles_of_an_anchor_or_alt_make_a_corner`, `a_move_by_nothing_leaves_a_live_shape_that_needs_no_change_live` in `crates/engine/tests/it/several_handles.rs`). VectorCraft's own preference General › Delete Removes Anchor Points and Keeps Paths Joined (`deleteKeepsPathsJoined`, off by default, part of #8326): on, Delete, Backspace and Edit › Clear remove the direct-selected anchors of each path as Remove Anchor Points does, refitting the curve around each one, so a closed path stays closed and an open path stays in one piece; the next anchor along (the one before at an open path's end) is selected, so the next Delete goes on along the path. Paths with a selected segment are still cut there, objects selected whole are still deleted, and a path left with fewer than two anchors goes, in one undo step. `edit.clear` takes a `keepJoined` param that defaults to the preference, and the value used joins the journal (`with_the_preference_on_delete_keeps_a_closed_path_closed_and_selects_the_next_anchor`, `several_paths_and_an_object_selected_whole_change_in_one_undo_step`, `with_the_preference_on_delete_and_backspace_keep_the_path_joined`). VectorCraft's own preference General › Double-Click Adds Anchor Points (`doubleClickAddsAnchorPoints`, off by default, part of #8326): on, a double-click without modifier keys on a path segment with Direct Selection adds an anchor at the clicked point, keeping the curve's shape, with only the new anchor selected, in one undo step (`path.insertAnchor` with `selectAnchor`); on an anchor, a handle, a center point, a blend's spine point or a fill the double-click does what it did before, and a clipping path's segment gets the anchor (`with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_there`, `with_the_preference_on_a_double_click_in_a_group_adds_only_on_a_segment`, `with_the_preference_on_a_double_click_gives_way_to_spine_points_and_reaches_clipping_paths`, `with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_in_one_undo_step`, `the_double_click_and_delete_preferences_are_separate`). A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included). From e7bf7b789f773fc3482862d46949d9e75a85cb02 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 16:51:11 -0800 Subject: [PATCH 34/36] Scripts: Map, Set and typed array constructors read their argument through its iterator new Map, new Set, new WeakMap and new WeakSet read their argument by index (an array, a string or an object with a length), so a generator, a Map, a Set or any other iterable was a TypeError, and an array whose @@iterator was replaced was still read by index. They now read it through GetIterator and close the iterator when adding an entry throws (ECMAScript 2015, sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1). A Map or WeakMap entry that is not an object is a TypeError. The typed array constructors and %TypedArray%.from read a source with an @@iterator method through its iterator to the end before mapping it, and any other source as an array-like object (sections 22.2.1.4 and 22.2.2.1). Map.prototype[@@iterator] is entries, Set.prototype[@@iterator] is values, %TypedArray%.prototype[@@iterator] is values, and the Map, Set and array iterators inherit %IteratorPrototype%, so for-of and spread walk them. Changed behavior: an array-like object without @@iterator passed to new Set or new Map is now a TypeError, and Uint8Array.from([1, 1], f) with an f that changes the array maps the values read before f ran. --- crates/js/src/builtins/binary.rs | 126 +++++++++++++------------- crates/js/src/builtins/collections.rs | 84 ++++++----------- crates/js/src/collections_tests.rs | 92 ++++++++++++++++++- crates/js/src/iteration.rs | 49 +++++++++- crates/js/src/lib.rs | 11 ++- docs/target-app-parity.md | 2 +- 6 files changed, 229 insertions(+), 135 deletions(-) diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index 39734bb088..3ec93edc07 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -15,12 +15,13 @@ //! every buffer's bytes are checked against the heap before they are allocated. Every element //! a method visits takes a unit of fuel, and a sort's comparisons take one each. //! -//! The language has no iterators yet, so constructing from an object reads an array or an object -//! with a `length`, by index, and `%TypedArray%.from` reads those or a string, by code point. A -//! constructor given a primitive string reads it as a length. +//! Constructing from an object that is not a buffer or a typed array, and `%TypedArray%.from`, +//! read a source with an `@@iterator` method through its iterator (a string by code point), and +//! any other source as an array-like object, by index. `%TypedArray%.prototype[@@iterator]` is +//! `values`. A constructor given a primitive string reads it as a length. -use super::collections::{for_each_item, getter, length_of, new_iter, new_proto}; -use super::{arg, array, data, method, native, require_callable, to_integer}; +use super::collections::{getter, length_of, new_iter, new_proto}; +use super::{arg, array, data, method, native, new_array, require_callable, to_integer}; use crate::heap::{Class, Elem, HIDDEN, IterKind, IterSource, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, VIEW_BYTES, View, key}; use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult}; use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint32}; @@ -28,9 +29,6 @@ use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint3 /// The longest buffer, in bytes. const MAX_BUFFER: u64 = u32::MAX as u64; -/// The bytes each item a method gathers before it writes them is charged. -const ITEM_BYTES: usize = 16; - pub(super) fn install(interp: &mut Interp) -> JsResult<()> { install_array_buffer(interp)?; install_data_view(interp)?; @@ -124,6 +122,11 @@ fn install_typed_arrays(interp: &mut Interp) -> JsResult<()> { for (name, f, length) in methods { method(interp, proto, name, f, length)?; } + // `%TypedArray%.prototype[@@iterator]` is `values` (section 22.2.3.30). + if let Some(iterator) = interp.well_known(|w| &w.iterator) { + let values = interp.get_from(proto, &key("values"), &Value::Object(proto))?; + interp.define_sym(proto, iterator, crate::heap::Prop::Data { value: values, flags: HIDDEN })?; + } // `%TypedArray%.prototype.toString` is `Array.prototype.toString` (section 22.2.3.28). let array_proto = interp.intrinsics.array_proto; let to_string = interp.get_from(array_proto, &key("toString"), &Value::Object(array_proto))?; @@ -645,21 +648,59 @@ fn typed_ctor(interp: &mut Interp, args: &[Value], constructing: bool, elem: Ele } return Ok(Value::Object(ta)); } - let len = length_of(interp, o)?; - let ta = new_typed(interp, elem, len)?; - interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, &first, len))?; - Ok(Value::Object(ta)) + // Any other object is read as TypedArrayFrom reads it (section 22.2.1.4). + typed_array_from(interp, &first, None, |interp, len| new_typed(interp, elem, len)) } -/// Writes the elements `0` to `len - 1` of the array-like object `src` to the typed array `ta`, -/// each converted with ToNumber. -fn fill_from(interp: &mut Interp, ta: ObjId, src: &Value, len: u64) -> JsResult<()> { - let Value::Object(o) = src else { return Ok(()) }; +/// TypedArrayFrom (section 22.2.2.1.1): a typed array with the values of `items`, made by `make` +/// once their number is known, each value mapped with `map` (the function and its `this`) when +/// one is given and converted with ToNumber. An `items` with an `@@iterator` method is read +/// through its iterator to the end before the typed array is made. Any other value is read as +/// an array-like object, each element read, mapped and written before the next is read. +fn typed_array_from( + interp: &mut Interp, + items: &Value, + map: Option<(&Value, &Value)>, + make: impl FnOnce(&mut Interp, u64) -> JsResult, +) -> JsResult { + let using_iterator = match interp.well_known(|w| &w.iterator) { + Some(iterator) => interp.get_value_sym(items, &iterator)?, + None => Value::Undefined, + }; + let src = if using_iterator.is_nullish() { + interp.to_object(items)? + } else { + let rec = interp.get_iterator_with(items, &using_iterator)?; + interp.rooted(&[Value::Object(rec)], |interp| { + let list = new_array(interp, 0)?; + interp.rooted(&[Value::Object(list)], |interp| interp.append_values(rec, list))?; + Ok(list) + })? + }; + let src_value = Value::Object(src); + interp.rooted(std::slice::from_ref(&src_value), |interp| { + let len = length_of(interp, src)?; + let ta = make(interp, len)?; + interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, src, len, map))?; + Ok(Value::Object(ta)) + }) +} + +/// Writes the elements `0` to `len - 1` of the object `src` to the typed array `ta`, each mapped +/// with `map` when one is given and converted with ToNumber. Each element is read just before it +/// is mapped and written. +fn fill_from(interp: &mut Interp, ta: ObjId, src: ObjId, len: u64, map: Option<(&Value, &Value)>) -> JsResult<()> { let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + let src_value = Value::Object(src); for i in 0..len { interp.use_fuel()?; #[allow(clippy::cast_precision_loss)] - let v = interp.get_from(*o, &super::key_of(i as f64), src)?; + let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?; + #[allow(clippy::cast_precision_loss)] + let v = match map { + Some((f, this_arg)) => interp.call(f, this_arg, &[item, Value::Number(i as f64)])?, + None => item, + }; let n = interp.to_number(&v)?; write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); } @@ -741,54 +782,11 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe require_callable(interp, &map_fn, "the map function")?; } let this_arg = arg(args, 2); - let source = arg(args, 0); - if !matches!(source, Value::String(_)) { - // An array-like source: each element is read, mapped and written before the next is read. - let src = interp.to_object(&source)?; - let src_value = Value::Object(src); - let len = length_of(interp, src)?; + let map = mapping.then_some((&map_fn, &this_arg)); + typed_array_from(interp, &arg(args, 0), map, |interp, len| { let elem = ctor_elem(interp, &this, "from")?; - let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?; - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; - return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| { - for i in 0..len { - interp.use_fuel()?; - #[allow(clippy::cast_precision_loss)] - let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?; - #[allow(clippy::cast_precision_loss)] - let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; - let n = interp.to_number(&v)?; - write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); - } - Ok(Value::Object(ta)) - }); - } - // A string is read by code point first, as an iterable source is, and then mapped. - let mark = interp.temp_roots.len(); - let mut held = crate::interp::HeldBytes::new(interp); - let gathered = for_each_item(interp, &source, false, |interp, item| { - held.add(interp, ITEM_BYTES)?; - interp.temp_roots.push(item); - Ok(()) - }); - let result = gathered.and_then(|()| { - let items: Vec = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default(); - let elem = ctor_elem(interp, &this, "from")?; - let ta = new_typed(interp, elem, items.len() as u64)?; - interp.temp_roots.push(Value::Object(ta)); - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; - for (i, item) in items.into_iter().enumerate() { - interp.use_fuel()?; - #[allow(clippy::cast_precision_loss)] - let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; - let n = interp.to_number(&v)?; - write(interp, &view, i, n); - } - Ok(Value::Object(ta)) - }); - interp.temp_roots.truncate(mark); - drop(held); - result + new_typed(interp, elem, len) + }) } /// `%TypedArray%.of(...items)` (section 22.2.2.2). diff --git a/crates/js/src/builtins/collections.rs b/crates/js/src/builtins/collections.rs index 70da37c39c..2d9f6176d3 100644 --- a/crates/js/src/builtins/collections.rs +++ b/crates/js/src/builtins/collections.rs @@ -8,18 +8,20 @@ //! entries hold their key weakly: the collector removes an entry once its key is reachable only //! through it ([`crate::heap::Heap::collect`]), and they have no size and cannot be listed. //! -//! The language has no iterators yet, so the constructors read their argument by index: an -//! array or an object with a `length`, or a string by code point. Every entry added is checked -//! against the heap limit before it is added, and every entry visited takes a unit of fuel. +//! The constructors read their argument through its `@@iterator` method (GetIterator, section +//! 7.4.1), and close the iterator when adding an entry throws (IteratorClose, section 7.4.6). +//! `Map.prototype[@@iterator]` is `entries`, `Set.prototype[@@iterator]` is `values`, and the +//! iterators inherit from `%IteratorPrototype%`. Every entry added is checked against the heap +//! limit before it is added, and every entry visited takes a unit of fuel. -use super::{arg, constructor, create_at, key_of, method, native, new_array, require_callable}; +use super::{arg, constructor, create_at, method, native, new_array, require_callable}; use crate::heap::{ COLL_ENTRY_BYTES, CONFIGURABLE, Class, Coll, CollKey, IterKind, IterSource, IterState, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, VIEW_BYTES, WEAK_ENTRY_BYTES, WeakColl, key, string_bytes, }; use crate::interp::{Abrupt, Interp, JsResult}; use crate::string_builtins::flat_charged; -use crate::value::{Str, Value}; +use crate::value::Value; /// The ECMAScript 2015 intrinsics the built-ins make their objects with, whatever a script does /// to the globals. @@ -137,7 +139,14 @@ pub(super) fn install(interp: &mut Interp) -> JsResult<()> { getter(interp, set_proto, "get size", set_size)?; // `Set.prototype.keys` is the same function object as `values` (section 23.2.3.8). let values = interp.get_from(set_proto, &key("values"), &Value::Object(set_proto))?; - interp.define(set_proto, key("keys"), Prop::Data { value: values, flags: crate::heap::HIDDEN })?; + interp.define(set_proto, key("keys"), Prop::Data { value: values.clone(), flags: crate::heap::HIDDEN })?; + // `Map.prototype[@@iterator]` is `entries` and `Set.prototype[@@iterator]` is `values` + // (sections 23.1.3.12 and 23.2.3.11). + if let Some(iterator) = interp.well_known(|w| &w.iterator) { + let entries = interp.get_from(map_proto, &key("entries"), &Value::Object(map_proto))?; + interp.define_sym(map_proto, iterator.clone(), Prop::Data { value: entries, flags: crate::heap::HIDDEN })?; + interp.define_sym(set_proto, iterator, Prop::Data { value: values, flags: crate::heap::HIDDEN })?; + } let weak_map_proto = new_proto(interp, object_proto); interp.intrinsics.es2015.weak_map_proto = weak_map_proto; @@ -158,8 +167,12 @@ pub(super) fn install(interp: &mut Interp) -> JsResult<()> { method(interp, weak_set_proto, name, f, length)?; } + // The iterators' prototypes inherit from `%IteratorPrototype%` (sections 23.1.5.2, 23.2.5.2 + // and 22.1.5.2), whose `@@iterator` gives the iterator itself. + let iterator_proto = + interp.symbols.objects.and_then(|o| interp.heap.object(o.array_iterator_proto).and_then(|p| p.proto)).unwrap_or(object_proto); for source in [IterSource::Map, IterSource::Set, IterSource::Array] { - let proto = new_proto(interp, object_proto); + let proto = new_proto(interp, iterator_proto); let next: NativeFn = match source { IterSource::Map => map_iterator_next, IterSource::Set => set_iterator_next, @@ -209,56 +222,10 @@ pub(crate) fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { Ok(if n <= 0.0 { 0 } else { n.min(9_007_199_254_740_991.0) as u64 }) } -/// Calls `f` with each item of `list`, read by index: an object's elements up to its `length`, -/// or a string's code points. Any other value is a `TypeError`, and so is an object without a -/// `length` when `need_length` is true. Each item takes a unit of fuel. -pub(crate) fn for_each_item( - interp: &mut Interp, - list: &Value, - need_length: bool, - mut f: impl FnMut(&mut Interp, Value) -> JsResult<()>, -) -> JsResult<()> { - match list { - Value::Object(o) => { - if need_length && !interp.has_property(*o, &key("length"))? { - return Err(interp.type_error("the value is not an array, a string or an object with a length")); - } - let len = length_of(interp, *o)?; - let mut i = 0u64; - while i < len { - interp.use_fuel()?; - #[allow(clippy::cast_precision_loss)] - let item = interp.get_from(*o, &key_of(i as f64), list)?; - f(interp, item)?; - i += 1; - } - Ok(()) - } - Value::String(s) => { - let units = flat_charged(interp, s)?; - let mut i = 0; - while i < units.len() { - interp.use_fuel()?; - let width = match (units.get(i), units.get(i + 1)) { - (Some(hi), Some(lo)) if (0xD800..0xDC00).contains(hi) && (0xDC00..0xE000).contains(lo) => 2, - _ => 1, - }; - let piece = units.get(i..i + width).unwrap_or_default().to_vec(); - let bytes = string_bytes(piece.len()); - interp.reserve_heap(bytes)?; - interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); - f(interp, Value::String(Str::from_units(piece)))?; - i += width; - } - Ok(()) - } - _ => Err(interp.type_error("the value is not an array, a string or an object with a length")), - } -} - -/// Adds the items of `list` to the new collection `target` with its `adder` method, as the -/// constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` reads each item -/// as a `[key, value]` entry. +/// Adds the values the iterator of `list` gives to the new collection `target` with its `adder` +/// method, as the constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` +/// reads each value as a `[key, value]` entry, which must be an object. When reading an entry +/// or adding it throws, the iterator is closed. fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bool) -> JsResult<()> { if list.is_nullish() { return Ok(()); @@ -268,7 +235,8 @@ fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bo let add = interp.get_from(target, &key(adder), &this)?; require_callable(interp, &add, adder)?; interp.rooted(std::slice::from_ref(&add), |interp| { - for_each_item(interp, list, true, |interp, item| { + let rec = interp.get_iterator(list)?; + interp.for_each_value(rec, |interp, item| { if !pairs { return interp.call(&add, &this, &[item]).map(drop); } diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs index cbc35d3929..31230e4958 100644 --- a/crates/js/src/collections_tests.rs +++ b/crates/js/src/collections_tests.rs @@ -131,10 +131,11 @@ fn iterators_step_through_live_entries() { } #[test] -fn constructors_read_arrays_strings_and_array_likes() { +fn constructors_read_arrays_and_strings() { truth("var m = new Map([[1, 'a'], [2, 'b']]); m.size === 2 && m.get(2) === 'b'"); truth("new Set('ab\u{1F600}b').size === 3"); - truth("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'}).size === 2"); + // An object without `@@iterator` is not iterable, whatever its `length` (section 23.2.1.1). + throws("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'})", "TypeError"); truth("new Map(null).size === 0 && new Set(undefined).size === 0"); truth("Object.prototype.toString.call(new Set()) === '[object Set]' && Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'"); throws("Map()", "TypeError"); @@ -146,7 +147,8 @@ fn constructors_read_arrays_strings_and_array_likes() { truth("Uint8Array.from({}).length === 0 && new Uint8Array({}).length === 0 && DataView.length === 1 && Uint8Array.length === 3"); // `from` reads each element of an array-like source just before mapping it (section 22.2.2.1). truth("var src = {length: 2, 0: 1, 1: 1}; Uint8Array.from(src, function (v, i) { src[1] = 7; return v; }).join() === '1,7'"); - truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,14'"); + // An iterable source is read to the end before the first value is mapped (section 22.2.2.1.1). + truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,2'"); truth("Uint8Array.from('ab', function (v) { return v.charCodeAt(0); }).join() === '97,98'"); throws("Map.prototype.get.call({}, 1)", "TypeError"); throws("Object.getOwnPropertyDescriptor(Map.prototype, 'size').get.call(new Set())", "TypeError"); @@ -158,6 +160,86 @@ fn constructors_read_arrays_strings_and_array_likes() { truth("JSON.stringify(new Map([[1, 2]])) === '{}' && JSON.stringify(new Set([1])) === '{}'"); } +/// An iterable that gives `values` and counts the calls of its `return` method in `closed`. +const CLOSING: &str = "var closed = 0; function closing(values) { var i = 0; return { [Symbol.iterator]: function () { return this; }, \ + next: function () { return i < values.length ? { value: values[i++], done: false } : { done: true }; }, \ + return: function () { closed++; return {}; } }; }"; + +#[test] +fn constructors_read_their_argument_through_its_iterator() { + // GetIterator and IteratorStep (sections 23.1.1.1, 23.2.1.1, 23.3.1.1, 23.4.1.1 and 22.2.1.4). + truth("function* g() { yield 1; yield 2; yield 1; } var s = new Set(g()); s.size === 2 && s.has(2)"); + truth("function* g() { yield ['a', 1]; yield ['b', 2]; } new Map(g()).get('b') === 2"); + truth("function* g() { yield 3; yield 4; } new Uint8Array(g()).join() === '3,4' && Int16Array.from(g()).join() === '3,4'"); + truth(&format!("{CLOSING} var s = new Set(closing(['x', 'y'])); s.size === 2 && s.has('y') && closed === 0")); + truth(&format!( + "{CLOSING} var k = {{}}; var w = new WeakMap(closing([[k, 5]])); var ws = new WeakSet(closing([k])); w.get(k) === 5 && ws.has(k)" + )); + truth(&format!("{CLOSING} new Float64Array(closing([1.5, 2])).join() === '1.5,2' && closed === 0")); + // A string is read by code point, as its iterator reads it. + truth("new Set('\\uD83D\\uDE00\\uD83D\\uDE00').size === 1 && new Set('\\uD83D\\uDE00x').has('\\uD83D\\uDE00')"); + truth("var m = new Map([[1, 'a']]); Array.prototype.join.call(Uint8Array.from(m.keys())) === '1'"); + // An array is read through its `@@iterator`, not by index. + truth("var a = [1, 2]; a[Symbol.iterator] = function () { return [9][Symbol.iterator](); }; var s = new Set(a); s.has(9) && !s.has(1)"); + truth("var a = [1, 2]; a[Symbol.iterator] = function () { return [9][Symbol.iterator](); }; new Uint8Array(a).join() === '9'"); + // An object without `@@iterator` is still read by index by the typed array constructors. + truth("new Uint8Array({length: 2, 0: 1, 1: 2}).join() === '1,2'"); + throws("new Set({ [Symbol.iterator]: 1 })", "TypeError"); + throws("new Uint8Array({ [Symbol.iterator]: 1 })", "TypeError"); +} + +#[test] +fn collections_and_typed_arrays_are_iterable() { + // Sections 23.1.3.12, 23.2.3.11 and 22.2.3.30. + truth("Map.prototype[Symbol.iterator] === Map.prototype.entries && Set.prototype[Symbol.iterator] === Set.prototype.values"); + truth("var p = Object.getPrototypeOf(Int8Array.prototype); p[Symbol.iterator] === p.values"); + truth("var m = new Map([[1, 'a'], [2, 'b']]); var out = []; for (var e of m) out.push(e.join(':')); out.join() === '1:a,2:b'"); + truth("var out = []; for (var v of new Set([3, 4])) out.push(v); for (var v of new Int8Array([5])) out.push(v); out.join() === '3,4,5'"); + truth("var m = new Map([[1, 2]]); new Map(m).get(1) === 2 && new Set(new Set([7])).has(7) && new Set(new Uint8Array([8])).has(8)"); + // The iterators inherit `%IteratorPrototype%[@@iterator]` (sections 23.1.5.2, 23.2.5.2 and 22.1.5.2). + truth("var it = new Map().keys(); it[Symbol.iterator]() === it && new Set([1]).values()[Symbol.iterator]().next().value === 1"); + truth("var it = new Int8Array([6]).values(); it[Symbol.iterator]() === it && [...new Set([1, 2]).keys()].join() === '1,2'"); +} + +#[test] +fn a_map_entry_that_is_not_an_object_closes_the_iterator() { + // Section 23.1.1.1, step 10.d. + truth(&format!("{CLOSING} var caught; try {{ new Map(closing([1])); }} catch (e) {{ caught = e instanceof TypeError; }} caught && closed === 1")); + truth(&format!( + "{CLOSING} var caught; try {{ new WeakMap(closing(['k'])); }} catch (e) {{ caught = e instanceof TypeError; }} caught && closed === 1" + )); +} + +#[test] +fn an_iterator_whose_next_throws_is_not_closed() { + let src = "var closed = 0; var it = { [Symbol.iterator]: function () { return this; }, \ + next: function () { throw new RangeError('next'); }, return: function () { closed++; return {}; } };"; + for make in ["new Set(it)", "new Map(it)", "new WeakSet(it)", "new Uint8Array(it)", "Uint8Array.from(it)"] { + truth(&format!( + "{src} var caught; try {{ {make}; }} catch (e) {{ caught = e instanceof RangeError && e.message === 'next'; }} caught && closed === 0" + )); + } +} + +#[test] +fn a_throwing_adder_closes_the_iterator() { + // IteratorClose (section 7.4.6) keeps the adder's exception, even when `return` throws too. + for (ctor, adder) in [("Set", "add"), ("Map", "set"), ("WeakSet", "add"), ("WeakMap", "set")] { + let src = format!( + "{CLOSING} var o = {{}}; {ctor}.prototype.{adder} = function () {{ throw new RangeError('adder'); }}; var caught; \ + try {{ new {ctor}(closing([[o, 1], [o, 2]])); }} catch (e) {{ caught = e instanceof RangeError && e.message === 'adder'; }}" + ); + truth(&format!("{src} caught && closed === 1")); + let throwing = src.replace("closed++; return {};", "closed++; throw new TypeError('return');"); + truth(&format!("{throwing} caught && closed === 1")); + } + // A Map entry whose `0` getter throws closes the iterator as well. + truth(&format!( + "{CLOSING} var bad = {{ get 0() {{ throw new RangeError('key'); }} }}; var caught; \ + try {{ new Map(closing([bad])); }} catch (e) {{ caught = e.message === 'key'; }} caught && closed === 1" + )); +} + // ---- WeakMap and WeakSet ---- #[test] @@ -220,7 +302,9 @@ fn collections_of_millions_end_at_the_limits() { assert_eq!(limit(&heap, "var m = new Map(); for (var i = 0; ; i++) m.set(i, i);"), LimitKind::Heap); assert_eq!(limit(&heap, "var s = new Set(); for (var i = 0; ; i++) s.add('k' + i);"), LimitKind::Heap); let fuel = Limits { fuel: 100_000, ..Limits::default() }; - assert_eq!(limit(&fuel, "new Set({length: 1e15})"), LimitKind::Fuel); + let endless = "{ [Symbol.iterator]: function () { return { next: function () { return { value: 1, done: false }; } }; } }"; + assert_eq!(limit(&fuel, &format!("new Set({endless})")), LimitKind::Fuel); + assert_eq!(limit(&fuel, &format!("new Uint8Array({endless})")), LimitKind::Fuel); let m = "var m = new Map(); for (var i = 0; i < 1000; i++) m.set(i, i); m.forEach(function () { for (;;) {} });"; assert_eq!(limit(&fuel, m), LimitKind::Fuel); } diff --git a/crates/js/src/iteration.rs b/crates/js/src/iteration.rs index eac1d4abe6..c0ce093ebb 100644 --- a/crates/js/src/iteration.rs +++ b/crates/js/src/iteration.rs @@ -59,7 +59,12 @@ impl Interp { Some(_) => Value::Undefined, None => return self.walk_record(v), }; - if !self.is_callable(&method) { + self.get_iterator_with(v, &method) + } + + /// GetIterator (section 7.4.1) with `method`, the `@@iterator` method already read from `v`. + pub(crate) fn get_iterator_with(&mut self, v: &Value, method: &Value) -> JsResult { + if !self.is_callable(method) { let what = match v { Value::Undefined => "undefined", Value::Null => "null", @@ -67,7 +72,7 @@ impl Interp { }; return Err(self.type_error(&format!("{what} is not iterable"))); } - let iterator = self.call(&method, v, &[])?; + let iterator = self.call(method, v, &[])?; if !matches!(iterator, Value::Object(_)) { return Err(self.type_error("the iterator is not an object")); } @@ -187,6 +192,41 @@ impl Interp { }) } + /// Calls `f` with each value the iterator of `rec` gives, until it is done. When `f` throws, + /// the iterator is closed ([`Interp::iter_close_after_throw`]) and the exception is thrown + /// again; when a step throws, the iterator is not closed. `rec` and each value are kept + /// reachable while `f` runs. + pub(crate) fn for_each_value(&mut self, rec: ObjId, mut f: impl FnMut(&mut Self, Value) -> JsResult<()>) -> JsResult<()> { + self.rooted(&[Value::Object(rec)], |i| { + while let Some(v) = i.iter_next(rec)? { + match i.rooted(std::slice::from_ref(&v), |i| f(i, v.clone())) { + Ok(()) => {} + Err(Abrupt::Throw(reason)) => return Err(i.iter_close_after_throw(rec, reason)), + Err(other) => return Err(other), + } + } + Ok(()) + }) + } + + /// IteratorClose (section 7.4.6) with the exception `reason`: closes the iterator of `rec` + /// unless it is done, and gives back `reason` to throw, with the position it was thrown from. + /// What closing it throws is dropped, the lookup of `return` included (ECMA-262 2023 section + /// 7.4.8, steps 4 to 6); running out of fuel, heap or time is not. + pub(crate) fn iter_close_after_throw(&mut self, rec: ObjId, reason: Value) -> Abrupt { + let site = self.throw_site.clone(); + let mark = self.thrown_mark; + match self.rooted(std::slice::from_ref(&reason), |i| i.iter_close(rec)) { + Ok(()) | Err(Abrupt::Throw(_)) => { + self.throw_site = site; + self.thrown_mark = mark; + self.passing = reason.clone(); + Abrupt::Throw(reason) + } + Err(other) => other, + } + } + /// `value` → `record`. pub(crate) fn op_get_iterator(&mut self) -> JsResult<()> { let v = self.peek(0)?; @@ -227,8 +267,9 @@ impl Interp { self.append_values(rec, a) } - /// Appends the values the iterator of `rec` gives to the array `a`; both are on the stack. - fn append_values(&mut self, rec: ObjId, a: ObjId) -> JsResult<()> { + /// Appends the values the iterator of `rec` gives to the array `a`; both are on the stack or + /// otherwise kept reachable. + pub(crate) fn append_values(&mut self, rec: ObjId, a: ObjId) -> JsResult<()> { while let Some(v) = self.iter_next(rec)? { let Class::Array { length, .. } = &self.object(a)?.class else { return internal("not an array") }; let i = *length; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 346f21eb58..1f2863ed2d 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -103,10 +103,13 @@ //! entries added while it runs; `WeakMap` and `WeakSet` (23.3 and 23.4), whose entries the //! collector removes once their keys are unreachable; and `ArrayBuffer`, `DataView` and the nine //! typed arrays (24.1, 24.2 and 22.2). `keys`, `values` and `entries` give iterator objects with -//! a `next` method. Until the language has iterators, the collection constructors and -//! `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by -//! index. A typed array constructor reads an array or an object with a `length` the same way, and -//! converts a first argument that is not an object to a length. A buffer longer than the heap +//! a `next` method, and `Map`, `Set` and the typed arrays are iterable. The collection +//! constructors read their argument through its `@@iterator` method (sections 23.1.1.1 to +//! 23.4.1.1), so an object without one is a `TypeError`, and a `Map` entry that is not an object +//! is a `TypeError` too. A typed array constructor given an object that is not a buffer or a typed +//! array, and `%TypedArray%.from`, read a source with an `@@iterator` method through its iterator +//! and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1). A +//! typed array constructor converts a first argument that is not an object to a length. A buffer longer than the heap //! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated. #![forbid(unsafe_code)] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ca31fe8761..00301edd48 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1184,7 +1184,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. Until the language has iterators, the collection constructors and `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by index, and a typed array constructor reads an array or an object with a `length` the same way and converts a first argument that is not an object to a length; these rules are VectorCraft's own. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,266 of 1,514 runs pass, and the 248 others expect a configurable function `length` and a function `name` property. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. `Map`, `Set` and the typed arrays are iterable, and their iterators inherit `%IteratorPrototype%`. The collection constructors read their argument through its `@@iterator` method and close the iterator when adding an entry throws (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1), so an object without `@@iterator` is a `TypeError`, and so is a `Map` or `WeakMap` entry that is not an object. A typed array constructor given an object that is not a buffer or a typed array, and `%TypedArray%.from`, read a source with an `@@iterator` method through its iterator to the end before mapping it, and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1); a typed array constructor converts a first argument that is not an object to a length. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,266 of 1,514 runs pass, and the 248 others expect a configurable function `length` and a function `name` property. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`. - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column when known. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits the file and sets the line and column to 0. `all` and `race` preserve an input rejection's known location; calling a saved reject function from script uses that call's location. `all`, `allSettled` and `race` read `Symbol.iterator`, including user-defined iterables and overridden array iterators; string iterators keep surrogate pairs together, and objects with only a whole-number `length` reject with a `TypeError`. A failure while processing a yielded value closes the iterator with `return` when present, preserving the original exception if closing throws; a step that throws or finishes is not closed. The statics always make plain `Promise` objects (VectorCraft's own rule). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. From 7fcd28eaa571a3a2b96036518b9797f862e3088a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 16:52:01 -0800 Subject: [PATCH 35/36] Brushes: pen-driven art and pattern brushes keep the size of a short pen change With Scale or Width on a pen input, a pattern tile or art brush art was bent by checking the outline at evenly spaced positions, so a pen change that fell between two of them was drawn at the size on either side. A 10 x 4 pt tile on a 10 pt path with a pressure peak at 2.2 pt was 2 pt either side there instead of 6 pt. The bent outline is now split at the recorded pen samples where the size turns by more than the outline's tolerance, in both the fitted curves and the chords, so those samples land on anchors. Samples that keep the size on a straight course add no anchors. --- crates/brush/src/tests.rs | 77 ++++++++++++++++ crates/brush/src/warp.rs | 182 +++++++++++++++++++++++++++++++------- 2 files changed, 229 insertions(+), 30 deletions(-) diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 2a39d50010..c5d13cd0fa 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -2626,6 +2626,83 @@ fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_fal } } +/// How far from y = 0 the outlines under `nodes` reach where they cross the vertical line at `x`. +fn reach_at(nodes: &[Node], x: f64) -> f64 { + let mut reach = 0.0f64; + for n in nodes { + n.walk(&mut |c| { + for sp in c.path_data().into_iter().flat_map(|p| &p.subpaths) { + for i in 0..sp.segment_count() { + let s = sp.segment(i); + let (a, b, c, d) = (s.p0.x, s.p1.x, s.p2.x, s.p3.x); + let roots = kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (c - 2.0 * b + a), d - 3.0 * c + 3.0 * b - a); + for t in roots.into_iter().filter(|t| (-1e-9..=1.0 + 1e-9).contains(t)) { + reach = reach.max(kurbo::ParamCurve::eval(&s, t.clamp(0.0, 1.0)).y.abs()); + } + } + } + }); + } + reach +} + +/// A pattern tile whose scale follows the pen is as tall as the scale at a short peak of the +/// pressure, even where the peak falls between the positions the bent outline is checked at. +#[test] +fn pattern_brush_scale_from_the_pen_keeps_a_short_peak() { + let doc = Document::new(1.0, 1.0); + let b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(300.0)); + // One 10 × 4 pt tile on a 10 pt path: 100 % (2 pt either side) but for a peak at 2.2 pt, where + // the scale reaches 300 % (6 pt either side). + let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]); + let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 10.0, 0.0), &peak); + // At the peak 300 %, half way up it 200 %, and 100 % on either side of it. + for (x, want) in [(2.2, 6.0), (2.15, 4.0), (2.25, 4.0), (1.0, 2.0), (2.05, 2.0), (2.4, 2.0), (8.0, 2.0)] { + assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x)); + } +} + +/// An art brush whose width follows the pen is as wide as the pen gives at a short peak of the +/// pressure, even where the peak falls between the positions the bent outline is checked at. +#[test] +fn art_brush_width_from_the_pen_keeps_a_short_peak() { + let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + if let BrushKind::Art(a) = &mut b.kind { + (a.width, a.width_mode, a.width_max) = (100.0, Some(Variation::Pressure), Some(300.0)); + } + // 4 pt art on a 100 pt path: 2 pt either side but for a peak at 22 pt, where it is 6 pt. + let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]); + let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &peak); + for (x, want) in [(22.0, 6.0), (21.5, 4.0), (22.5, 4.0), (10.0, 2.0), (20.5, 2.0), (24.0, 2.0), (80.0, 2.0)] { + assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x)); + } +} + +/// A pen recording sampled many times along a straight ramp draws as many anchors as the ramp's +/// two ends do: samples that leave the scale on the same straight course are not split at. +#[test] +fn pen_samples_on_a_straight_ramp_add_no_anchors() { + let doc = Document::new(1.0, 1.0); + let bp = line(0.0, 0.0, 1000.0, 0.0); + let ramp = |n: usize| pressed((0..=n).map(|i| (i as f64 / n as f64, i as f64 / n as f64)).collect()); + let anchors = |out: &[Node]| { + let mut count = 0; + for n in out { + n.walk(&mut |c| count += c.path_data().map_or(0, |p| p.subpaths.iter().map(|s| s.anchors.len()).sum::())); + } + count + }; + let pattern = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)); + let mut art = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + if let BrushKind::Art(a) = &mut art.kind { + (a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::Pressure), Some(300.0)); + } + for b in [&pattern, &art] { + let (few, many) = (stroke_pieces(&doc, b, &bp, &ramp(1)), stroke_pieces(&doc, b, &bp, &ramp(2000))); + assert_eq!(anchors(&many), anchors(&few), "{}", b.name); + } +} + /// On a closed path, a tile that Approximate Path starts before the path's start takes the scale /// recorded at the end of the stroke there, where the tile is drawn. #[test] diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index 7ffcb472ff..3cfa54db21 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -40,23 +40,32 @@ const MASK_STEPS: usize = 32; /// through the bend to within [`fit_tol`] of `doc_tol`, the flattening tolerance in document /// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than /// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord -/// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`. -/// Text, images and symbol instances can't bend and are dropped. The art of a linked opacity mask -/// bends with the object it masks. -pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option { +/// is longer than `max_du` along x, as it always was. Both routes also split the art where it +/// crosses each of `breaks` (art x, in order), so a turn of the map there is not stepped over. +/// Stroke widths scale by `width_scale`. Text, images and symbol instances can't bend and are +/// dropped. The art of a linked opacity mask bends with the object it masks. +pub(crate) fn warp_node( + n: &Node, + f: &dyn Fn(Point) -> Point, + flat_tol: f64, + max_du: f64, + doc_tol: f64, + width_scale: f64, + breaks: &[f64], +) -> Option { let mut out = n.clone(); out.appearance.scale_strokes(width_scale); match &mut out.kind { NodeKind::Path { path, live, .. } => { *live = None; - *path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol)); + *path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol), breaks); if path.is_empty() { return None; } } NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => { let kids: Vec> = - children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale)).map(Arc::new).collect(); + children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale, breaks)).map(Arc::new).collect(); if kids.is_empty() { return None; } @@ -64,7 +73,7 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max } _ => return None, } - map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale)); + map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale, breaks)); Some(out) } @@ -80,12 +89,13 @@ fn map_mask(n: &mut Node, map: impl FnOnce(&Node) -> Option) { } /// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords -/// would, else the chords. Points `f` cannot place (not finite) are left out of the chords. -fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData { +/// would, else the chords, both split at `breaks` ([`warp_node`]). Points `f` cannot place (not +/// finite) are left out of the chords. +fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64, breaks: &[f64]) -> PathData { let mut subs = vec![]; for sp in &p.subpaths { - let Some(dense) = densified(sp, flat_tol, max_du) else { continue }; - if let Some(fit) = fitted(sp, f, fit_tol, dense.len()) { + let Some(dense) = densified(sp, flat_tol, max_du, breaks) else { continue }; + if let Some(fit) = fitted(sp, f, fit_tol, dense.len(), breaks) { subs.push(fit); continue; } @@ -98,8 +108,9 @@ fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f6 } /// `sp` flattened with `flat_tol` and its chords subdivided so none is longer than `max_du` along -/// x, in art space: the points the chord route maps. `None` below two points. -fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option> { +/// x, in art space, with a point where a chord crosses each of `breaks` (art x, in order): the +/// points the chord route maps. `None` below two points. +fn densified(sp: &SubPath, flat_tol: f64, max_du: f64, breaks: &[f64]) -> Option> { let mut bp = BezPath::new(); sp.to_bezpath_into(&mut bp); let mut pts = vec![]; @@ -118,16 +129,57 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option> { let mut dense = vec![*pts.first()?]; for (i, (&a, &b)) in pts.iter().zip(pts.iter().cycle().skip(1)).take(segs).enumerate() { let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB); + // The breaks the chord crosses, as parameters along it in order, go in among the even ones. + let mut cuts: Vec = crossed(breaks, a.x, b.x).iter().map(|&x| (x - a.x) / (b.x - a.x)).collect(); + cuts.sort_by(f64::total_cmp); + let mut cuts = cuts.into_iter().peekable(); for j in 1..=k { + let even = j as f64 / k as f64; + while let Some(t) = cuts.next_if(|&t| t < even) { + dense.push(a.lerp(b, t)); + } if sp.closed && i == segs - 1 && j == k { break; } - dense.push(a.lerp(b, j as f64 / k as f64)); + dense.push(a.lerp(b, even)); } } Some(dense) } +/// The values of `breaks` (in order) strictly between `a` and `b`, either way round. +fn crossed(breaks: &[f64], a: f64, b: f64) -> &[f64] { + let (lo, hi) = (a.min(b), a.max(b)); + let from = breaks.partition_point(|&x| x <= lo); + let to = from + breaks[from..].partition_point(|&x| x < hi); + &breaks[from..to] +} + +/// The parameters of `c` (in order, strictly between its ends) where its x is one of `breaks`; +/// `line` when `c` is a line with its handles at thirds, whose x runs evenly. +fn crossings(c: &CubicBez, line: bool, breaks: &[f64]) -> Vec { + let xs = [c.p0.x, c.p1.x, c.p2.x, c.p3.x]; + let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &x| (lo.min(x), hi.max(x))); + let inside = crossed(breaks, lo, hi); + if inside.is_empty() { + return vec![]; + } + let [a, b, cc, d] = xs; + let mut ts: Vec = vec![]; + for &x in inside { + if line { + ts.push((x - a) / (d - a)); + } else { + ts.extend(kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (cc - 2.0 * b + a), d - 3.0 * cc + 3.0 * b - a)); + } + } + // Pieces are no shorter than the step the fit reads their ends' directions over. + ts.retain(|t| t.is_finite() && *t > FIT_DT && *t < 1.0 - FIT_DT); + ts.sort_by(f64::total_cmp); + ts.dedup_by(|t, prev| *t - *prev <= FIT_DT); + ts +} + /// Times an art segment is halved at most while looking for cubics that fit it. const FIT_DEPTH: u32 = 12; /// Parameter step of the finite differences that stand in for the bend's derivative. @@ -156,7 +208,10 @@ fn fit_tol(doc_tol: f64) -> f64 { /// bend at the same parameters, so the distance measured is never less than the true one. The /// halving is our own rather than kurbo's `fit_to_bezpath`, which halves until the floats run out /// on a map that never fits; the depth and the anchor count bound this one. -fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Option { +/// +/// A segment is first split where its x crosses one of `breaks` (art x, in order), so a turn of +/// the map there lands on an anchor rather than between the checked positions. +fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize, breaks: &[f64]) -> Option { if !(tol.is_finite() && tol > 0.0) { return None; } @@ -174,7 +229,11 @@ fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Op // A line's handles sit on its ends, which stalls its parameter there; thirds keep it even. let c = if line { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c }; let at = |t: f64| Some(f(c.eval(t))).filter(|q| q.is_finite()); - fit_into(&at, (0.0, 1.0), line, tol, FIT_DEPTH, &mut bp, &mut room)?; + let mut t0 = 0.0; + for t1 in crossings(&c, line, breaks).into_iter().chain([1.0]) { + fit_into(&at, (t0, t1), line, tol, FIT_DEPTH, &mut bp, &mut room)?; + t0 = t1; + } } if sp.closed { bp.close_path(); @@ -316,6 +375,16 @@ impl AlongMap { fn max_scale(&self) -> f64 { (0..3).map(|i| self.slope(i).abs()).fold(1e-6, f64::max) } + + /// The art x (offset from the art's left edge) that [`AlongMap::at`] takes to arc length `s`, + /// when a piece with width spans it. + fn x_at(&self, s: f64) -> Option { + (0..3).find_map(|i| { + let ((x0, x1), (s0, s1)) = ((self.xs[i], self.xs[i + 1]), (self.ss[i], self.ss[i + 1])); + let spans = x1 - x0 > 1e-12 && (s1 - s0).abs() > 1e-12 && s0.min(s1) <= s && s <= s0.max(s1); + spans.then(|| x0 + (s - s0) / (s1 - s0) * (x1 - x0)) + }) + } } /// The affine that reproduces `f` over `b` to within `tol`, if one does. @@ -414,12 +483,14 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option f64) -> Option { +/// of each object in the art take the factor at the middle of the object. `marks` are the arc +/// lengths (in order) of the recorded pen samples `widen` runs in a straight line between; the art +/// is split where `widen` turns at one by more than the bent outline's tolerance ([`pen_breaks`]). +fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64, marks: &[f64]) -> Option { let cy = b.center().y; let x0 = b.x0; let f = move |p: Point| { @@ -430,7 +501,45 @@ fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, wid let art = widen_strokes(art, &factor); let scale = along.max_scale().max(cross.abs()).max(1e-6); let flat_tol = tolerance(b.height().max(b.width()) * scale) / scale; - warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs()) + // A change of `dw` in `widen` moves the art's top and bottom edges `dw × reach` across. + let reach = b.height() / 2.0 * cross.abs(); + let mut breaks: Vec = + pen_breaks(marks, along.span(), widen, fit_tol(flat_tol * scale) / reach).into_iter().filter_map(|s| along.x_at(s)).map(|x| x + x0).collect(); + breaks.sort_by(f64::total_cmp); + breaks.dedup(); + warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &breaks) +} + +/// The arc lengths among `marks` (in order) strictly within `(s0, s1)` at which the art is split: +/// those where `widen` is more than `tol` from the straight line between the ones kept on either +/// side (the span's ends to begin with), chosen by splitting at the farthest one until every +/// sample left out is within `tol` of that line. `widen` runs straight between samples, so it +/// is then within `tol` of the line between kept samples all along, and samples on a straight +/// course add no splits. +fn pen_breaks(marks: &[f64], (s0, s1): (f64, f64), widen: &dyn Fn(f64) -> f64, tol: f64) -> Vec { + if !(s1 > s0 && tol > 0.0) { + return vec![]; + } + let inside = { + let from = marks.partition_point(|&s| s <= s0); + &marks[from..from + marks[from..].partition_point(|&s| s < s1)] + }; + if inside.is_empty() { + return vec![]; + } + let pts: Vec<(f64, f64)> = std::iter::once(s0).chain(inside.iter().copied()).chain([s1]).map(|s| (s, widen(s))).collect(); + let mut keep = vec![false; pts.len()]; + let mut spans = vec![(0, pts.len() - 1)]; + while let Some((i, j)) = spans.pop() { + let ((sa, wa), (sb, wb)) = (pts[i], pts[j]); + let off = |&(s, w): &(f64, f64)| (w - if sb > sa { wa + (wb - wa) * (s - sa) / (sb - sa) } else { wa }).abs(); + let far = (i + 1..j).map(|k| (k, off(&pts[k]))).filter(|&(_, d)| d > tol).max_by(|a, b| a.1.total_cmp(&b.1)); + if let Some((k, _)) = far { + keep[k] = true; + spans.extend([(i, k), (k, j)]); + } + } + pts.iter().zip(keep).filter(|&(_, k)| k).map(|(p, _)| p.0).collect() } /// `n` with the strokes of it and of everything inside it scaled by `factor` of the object they @@ -465,8 +574,17 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> { bounds.windows(2).map(|w| (w[0], w[1])).collect() } -/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1. -fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, Rect), cross: f64, widen: &dyn Fn(f64) -> f64) -> Option { +/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1 (`marks` +/// as [`bend_widened`] takes them). +fn art_on_run( + t: &Track, + (s0, s1): (f64, f64), + a: &ArtBrush, + (art, b): (&Node, Rect), + cross: f64, + widen: &dyn Fn(f64) -> f64, + marks: &[f64], +) -> Option { let l = s1 - s0; if l <= 1e-9 { return None; @@ -489,7 +607,7 @@ fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, R } } }; - bend_widened(t, art, b, along, cross, widen) + bend_widened(t, art, b, along, cross, widen, marks) } /// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing @@ -515,9 +633,13 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5); (light + (heavy - light) * p) / width }; + let marks = match a.width_mode { + Some(m) if light != heavy && width > 0.0 => pen_marks(stroke, m, l), + _ => vec![], + }; let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] }; for run in runs { - if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen) { + if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen, &marks) { out.push(n); } } @@ -671,7 +793,7 @@ fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) if mid <= 0.0 || marks.is_none_or(even) { return tile_on(t, tile, s0, s1, mid); } - bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid) + bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid, marks.unwrap_or_default()) } /// The most side tiles a run of a pattern brush places. @@ -966,7 +1088,7 @@ fn auto_corner(t: &Track, i: usize, source: CornerSource, side: &(Node, Rect), k } let s = if tw > 1e-9 { len / tw } else { 1.0 }; let max_du = MAX_SEG / (2.0 * k * s.max(1.0)); - let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k); + let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k, &[]); // Art point → (distance along from the left edge, stretched to `len`, and offset across). let along = move |q: Point| { let (x, y) = local(q); @@ -1393,7 +1515,7 @@ mod tests { let f = |p: Point| t.map(along.at(p.x - x0), p.y - cy); let tol = tolerance(b.height().max(b.width())); let exact = traced(art, &f, 1000); - let chords: Vec = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect(); + let chords: Vec = densified(art, tol, MAX_SEG, &[]).expect("the tile flattens").into_iter().map(f).collect(); let curves = traced(sp, &|p| p, 200); let (e_curves, e_chords) = (apart(&curves, &exact), apart(&chords, &exact)); // Checked at eight points a piece, so a little room between them. @@ -1419,7 +1541,7 @@ mod tests { let allowed: usize = path .subpaths .iter() - .filter_map(|sp| densified(sp, 0.25, 1.5)) + .filter_map(|sp| densified(sp, 0.25, 1.5, &[])) .map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len()) .sum(); let finite = |n: &Node| match &n.kind { @@ -1441,7 +1563,7 @@ mod tests { calls.set(calls.get() + 1); if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) } }; - let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0); + let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0, &[]); assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get()); match (i, &out) { (3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"), @@ -1491,7 +1613,7 @@ mod tests { let mask = out.extras().mask.as_ref().expect("the mask is kept"); assert_eq!(*mask.art, stroked(1), "{name} run: an unlinked mask stays where it was"); - let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5).expect("the art is drawn"); + let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5, &[]).expect("the art is drawn"); let mask = out.extras().mask.as_ref().expect("the mask is kept"); assert_eq!(mask.art.kind, out.kind, "{name} run, widened: the mask's art bends with the art"); assert_eq!(mask.art.appearance, out.appearance, "{name} run, widened: the mask's strokes narrow with the art's"); From 4fc4cbca0b23187dd3f9bb2977626463eccf78e9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 17:00:31 -0800 Subject: [PATCH 36/36] Performance: Document::node reads the node from the lookup cache without copying its path Document::node went through index_path, which copied the node's index path out of the lookup cache into a new Vec, walked the tree to check it, and walked it again to return the node. The menus' states call it for every selected object in many of their checks, so a rebuild of the menu states with 10,000 objects selected made hundreds of thousands of copies. node now follows the place the cache has for the id once, without a copy. When the cache has no single place for it, the path is deeper than 32 levels, or the node there no longer has the id, it looks the node up as index_path does. vectorcraft_doc::path_copies counts the paths the cache copies out, for the new test. --- crates/doc/src/document.rs | 8 +++++- crates/doc/src/id_index.rs | 43 +++++++++++++++++++++++++++++++++ crates/doc/src/lib.rs | 2 +- crates/doc/src/tests/lookups.rs | 29 ++++++++++++++++++++++ 4 files changed, 80 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 3e5743aec3..dc1e082ac0 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -314,8 +314,14 @@ impl Document { self.renumber_stored_duplicates(); } - /// Find a node anywhere in the tree. + /// Find a node anywhere in the tree. With the lookup cache built, the node comes from the place the cache has for + /// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as + /// [`Document::index_path`] finds it. pub fn node(&self, id: NodeId) -> Option<&Node> { + if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) { + crate::id_index::note_path_lookup(); + return Some(n); + } self.index_path(id).and_then(|p| self.node_at(&p)) } diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index 34453234ec..0e1673580a 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -82,6 +82,7 @@ impl Paths { /// isn't in the table or it, or a node it is in, was removed. pub(crate) fn get(&self, id: &NodeId) -> Option>> { let e = (*self.table.ids.get(id)?)?; + note_path_copy(); let mut path = Vec::new(); let mut cur = e; // Each step goes to a parent entry, made before its children: at most `at.len()` steps. @@ -96,6 +97,29 @@ impl Paths { } Some(None) } + /// The node with `id` in `layers` at the place the table has for it, found without copying its index path: `None` + /// when the table does not have one place for `id`, its path is deeper than [`NODE_IN_DEPTH`], or the node there + /// does not have the id (the tree changed). The caller then looks it up as [`crate::Document::index_path`] does. + pub(crate) fn node_in<'a>(&self, layers: &'a [Arc], id: NodeId) -> Option<&'a Node> { + let mut cur = (*self.table.ids.get(&id)?)?; + let mut steps = [0u32; NODE_IN_DEPTH]; + let mut depth = 0; + loop { + let &(parent, i) = self.table.at.get(cur as usize)?; + *steps.get_mut(depth)? = self.shifted(parent, i)?; + depth += 1; + if parent == u32::MAX { + break; + } + cur = parent; + } + let mut path = steps[..depth].iter().rev(); + let mut node: &Node = layers.get(*path.next()? as usize)?; + for &i in path { + node = node.children()?.get(i as usize)?; + } + (node.id == id).then_some(node) + } /// Where the table has `id` as it was built: its parent's entry and its index among its /// siblings then; `None` when the id isn't in the table or appears more than once. pub(crate) fn table_place(&self, id: &NodeId) -> Option<(u32, u32)> { @@ -170,6 +194,25 @@ pub(crate) fn note_path_lookup() { PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1)); } +/// The deepest index path [`Paths::node_in`] follows without copying it. +const NODE_IN_DEPTH: usize = 32; + +thread_local! { + /// [`path_copies`] of this thread. + static PATH_COPIES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many index paths the lookup cache has copied out on this thread, one for each [`crate::Document::index_path`] +/// that it answered. [`crate::Document::node`] reads the node from the cache without one. +pub fn path_copies() -> u64 { + PATH_COPIES.get() +} + +/// Adds one to [`path_copies`]. +fn note_path_copy() { + PATH_COPIES.set(PATH_COPIES.get().saturating_add(1)); +} + /// The cache, shared by clones of a document (each checks every path it uses against its own tree), /// the lookups that missed it, and the nodes removed from the tree since it was built. #[derive(Default)] diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index de8bfc2875..470b0a94c4 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -24,7 +24,7 @@ mod halftone_radii; pub mod hit; mod id_index; pub mod image_quad; -pub use id_index::{path_lookups, tree_walks}; +pub use id_index::{path_copies, path_lookups, tree_walks}; pub mod inks; mod inline; pub mod intertwine; diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 295c347765..4a8f6a9d71 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -579,3 +579,32 @@ fn nearest_finder_reads_one_path_per_object() { assert_eq!(path_lookups() - lookups, 0, "lookups by id"); assert_eq!(tree_walks() - walks, 0, "walks of the tree"); } + +/// `Document::node` reads a node from the lookup cache without copying its index path, in nested groups and after +/// objects were removed, and finds what a walk finds: 10,000 objects looked up one at a time copy no path. +#[test] +fn node_lookups_copy_no_index_path() { + let (mut d, ids) = squares(10_000); + let layer = d.layers[0].id; + let mut nested = vec![]; + for g in 0..50 { + let kids: Vec> = (0..4) + .map(|_| { + let id = d.alloc_id(); + nested.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())) + }) + .collect(); + let (gid, inner) = (d.alloc_id(), d.alloc_id()); + d.insert(Some(layer), g, Node::group(gid, vec![Arc::new(Node::group(inner, kids))])).unwrap(); + } + d.remove_many(&ids[..100]).unwrap(); + d.node(layer); + let copies = path_copies(); + let found = ids[100..].iter().chain(&nested).filter(|id| d.node(**id).is_some_and(|n| n.id == **id)).count(); + assert_eq!(found, ids.len() - 100 + nested.len()); + assert_eq!(path_copies() - copies, 0, "index paths copied"); + assert!(ids[..100].iter().all(|id| d.node(*id).is_none()), "removed objects are not found"); + agree(&d, &ids[..200], "after remove_many"); + agree(&d, &nested, "nested"); +}