From 00aeb2293edb612d0770490ccfdacd7d00cc5262 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:17:16 -0800 Subject: [PATCH 01/11] Brushes: Add original Vector Packs library --- crates/engine/src/cmd/brushlib.rs | 33 +++++++++++++++++++ crates/engine/src/tests/brushlib.rs | 28 +++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 5 +++ crates/ui-egui/src/i18n/bs.tsv | 5 +++ crates/ui-egui/src/i18n/ca.tsv | 5 +++ crates/ui-egui/src/i18n/cs.tsv | 5 +++ crates/ui-egui/src/i18n/da.tsv | 5 +++ crates/ui-egui/src/i18n/de.tsv | 5 +++ crates/ui-egui/src/i18n/el.tsv | 5 +++ crates/ui-egui/src/i18n/es.tsv | 5 +++ crates/ui-egui/src/i18n/fi.tsv | 5 +++ crates/ui-egui/src/i18n/fr.tsv | 5 +++ crates/ui-egui/src/i18n/gu.tsv | 5 +++ crates/ui-egui/src/i18n/hi.tsv | 5 +++ crates/ui-egui/src/i18n/hu.tsv | 5 +++ crates/ui-egui/src/i18n/id.tsv | 5 +++ crates/ui-egui/src/i18n/it.tsv | 5 +++ crates/ui-egui/src/i18n/ja.tsv | 5 +++ crates/ui-egui/src/i18n/ka.tsv | 5 +++ crates/ui-egui/src/i18n/ko.tsv | 5 +++ crates/ui-egui/src/i18n/nl.tsv | 5 +++ crates/ui-egui/src/i18n/pl.tsv | 5 +++ crates/ui-egui/src/i18n/pt-br.tsv | 5 +++ crates/ui-egui/src/i18n/ru.tsv | 5 +++ crates/ui-egui/src/i18n/sv.tsv | 5 +++ crates/ui-egui/src/i18n/tests.rs | 3 +- crates/ui-egui/src/i18n/tr.tsv | 5 +++ crates/ui-egui/src/i18n/uk.tsv | 5 +++ crates/ui-egui/src/i18n/vi.tsv | 5 +++ crates/ui-egui/src/i18n/zh-hans.tsv | 5 +++ crates/ui-egui/src/i18n/zh-hant.tsv | 5 +++ .../src/panels/tests_brush_libraries.rs | 9 ++++- docs/mcp.md | 4 +-- docs/target-app-parity.md | 3 +- 34 files changed, 214 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 34becd7c02..f6a149af7a 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -179,6 +179,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams }, BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media }, BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit }, + BuiltinBrushLibrary { id: "vector-packs", name: "Vector Packs", make: vector_packs }, ]; /// Built-in library `id`, made once. @@ -535,6 +536,38 @@ fn scatter_shapes() -> BrushLibrary { built("Scatter Shapes", doc, brushes) } +/// Vector Packs: four original, editable vector marks that follow the stroke color. +fn vector_packs() -> BrushLibrary { + let compass = group(vec![black(shapes::star(Point::ZERO, 10.0, 3.0, 8, 0.0)), black(shapes::ellipse(Rect::new(-1.5, -1.5, 1.5, 1.5)))]); + let sprig = group(vec![ + black(polygon(&[(-0.7, 10.0), (0.7, 10.0), (0.7, -10.0), (-0.7, -10.0)])), + black(polygon(&[(0.0, 5.0), (5.0, 2.0), (7.0, -1.0), (3.0, 0.0)])), + black(polygon(&[(0.0, 0.0), (-5.0, -3.0), (-7.0, -6.0), (-3.0, -5.0)])), + black(polygon(&[(0.0, -5.0), (5.0, -8.0), (7.0, -10.0), (3.0, -9.0)])), + ]); + let diamond = group(vec![ + black(polygon(&[(-9.0, 0.0), (-1.0, -9.0), (-1.0, -1.0)])), + black(polygon(&[(1.0, -9.0), (9.0, 0.0), (1.0, -1.0)])), + black(polygon(&[(9.0, 0.0), (1.0, 9.0), (1.0, 1.0)])), + black(polygon(&[(-1.0, 9.0), (-9.0, 0.0), (-1.0, 1.0)])), + ]); + let tide = group(vec![ + black(band(20.0, 1.2, 32, |x| -3.0 + 2.0 * (x * std::f64::consts::TAU / 20.0).sin())), + black(band(20.0, 1.2, 32, |x| 3.0 + 2.0 * (x * std::f64::consts::TAU / 20.0).sin())), + ]); + let settings = Scatter { size: (90.0, 110.0), spacing: (130.0, 160.0), colorization: Colorization::Tints, ..Default::default() }; + built( + "Vector Packs", + Document::new(100.0, 100.0), + vec![ + scatter("Compass Rose", compass, settings.clone()), + scatter("Botanical Sprig", sprig, settings.clone()), + scatter("Facet Diamond", diamond, settings.clone()), + scatter("Tide Crest", tide, settings), + ], + ) +} + /// Game Trails: art brushes for motion lines and impact streaks (original game HUD / VFX art). fn game_trails() -> BrushLibrary { let speed = { diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 4f0b739951..9741064fd7 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -116,7 +116,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "game-trails", "energy-beams", "dry-media", - "tech-circuit" + "tech-circuit", + "vector-packs" ] ); assert!(libs.iter().all(|l| l["category"] == "builtIn")); @@ -160,6 +161,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("game-trails", "art"), ("energy-beams", "art"), ("dry-media", "art"), + ("vector-packs", "scatter"), ] { let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); assert!(lib.len() >= 4, "{id}"); @@ -190,6 +192,30 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err()); } +#[test] +fn vector_packs_marks_are_editable_and_survive_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "vector-packs").unwrap(); + let names = ["Compass Rose", "Botanical Sprig", "Facet Diamond", "Tide Crest"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap(); + for b in &lib.brushes { + let BrushKind::Scatter(sc) = &b.kind else { panic!("{} is not a scatter brush", b.name) }; + assert!(art_paths(&sc.art).len() >= 2, "{} has no editable vector mark", b.name); + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &black_stroke()); + assert!(pieces.len() >= 3, "{} does not repeat along a path", b.name); + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "vector-packs", "name": b.name, "apply": true, "ids": [line]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + assert_eq!(added["applied"], json!([line])); + assert_eq!(undo_len(&s), before + 1); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + /// Every path of brush art `n`: (anchors, opacity). fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> { let mut out = vec![]; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..669cb1c880 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7237,3 +7237,8 @@ breakText Glyphs Глифи @msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Vector Packs Векторни пакети + Compass Rose Роза на компаса + Botanical Sprig Ботаническо клонче + Facet Diamond Фасетиран ромб + Tide Crest Гребен на вълна diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..81bdd1405d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7291,3 +7291,8 @@ shape Open Otvoren @msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" + Vector Packs Vektorski paketi + Compass Rose Ruža kompasa + Botanical Sprig Botanička grančica + Facet Diamond Fasetirani romb + Tide Crest Vrh vala diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..d07e375794 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8126,3 +8126,8 @@ breakText Glyphs Glifs @msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, frontisses: {hinges}, errors: {errors}, avisos: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Vector Packs Paquets vectorials + Compass Rose Rosa dels vents + Botanical Sprig Branqueta botànica + Facet Diamond Diamant facetat + Tide Crest Cresta de l'onada diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..42c881a540 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9917,3 +9917,8 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Vector Packs Vektorové balíčky + Compass Rose Směrová růžice + Botanical Sprig Botanická větvička + Facet Diamond Fazetový diamant + Tide Crest Hřeben vlny diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..06d835a21f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10025,3 +10025,8 @@ breakText Glyphs Glyffer @msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, hængsler: {hinges}, fejl: {errors}, advarsler: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" + Vector Packs Vektorpakker + Compass Rose Kompasrose + Botanical Sprig Botanisk kvist + Facet Diamond Facetteret diamant + Tide Crest Bølgetop diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..24bc021031 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9516,3 +9516,8 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Vector Packs Vektorpakete + Compass Rose Kompassrose + Botanical Sprig Botanischer Zweig + Facet Diamond Facettierter Diamant + Tide Crest Wellenkamm diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..5d0e838209 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8100,3 +8100,8 @@ breakText Glyphs Γλύφοι @msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, μεντεσέδες: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" + Vector Packs Διανυσματικά πακέτα + Compass Rose Ρόδο πυξίδας + Botanical Sprig Βοτανικό κλαδάκι + Facet Diamond Πολυεδρικό διαμάντι + Tide Crest Κορυφή κύματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..e30bbb048f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8087,3 +8087,8 @@ breakText Glyphs Glifos @msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, bisagras: {hinges}, errores: {errors}, advertencias: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Vector Packs Paquetes vectoriales + Compass Rose Rosa de los vientos + Botanical Sprig Ramita botánica + Facet Diamond Diamante facetado + Tide Crest Cresta de ola diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..59ba93d344 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8183,3 +8183,8 @@ breakText Glyphs Merkit @msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, saranat: {hinges}, virheet: {errors}, varoitukset: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" + Vector Packs Vektoripaketit + Compass Rose Kompassiruusu + Botanical Sprig Kasvinoksa + Facet Diamond Särmätty timantti + Tide Crest Aallonharja diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..794efbea4f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9902,3 +9902,8 @@ breakText Glyphs Glyphes @msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} charnière(s), {errors} erreur(s), {warnings} avertissement(s) @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution + Vector Packs Packs vectoriels + Compass Rose Rose des vents + Botanical Sprig Rameau botanique + Facet Diamond Diamant facetté + Tide Crest Crête de vague diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..74497697e1 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4987,3 +4987,8 @@ swatch [Registration] [રજિસ્ટ્રેશન] Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" + Vector Packs વેક્ટર પૅક + Compass Rose દિશાસૂચક ગુલાબ + Botanical Sprig વનસ્પતિ ડાળી + Facet Diamond પાસાદાર હીરો + Tide Crest તરંગ શિખર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..e5f8a3044a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9524,3 +9524,8 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Vector Packs वेक्टर पैक + Compass Rose दिशासूचक गुलाब + Botanical Sprig वनस्पति टहनी + Facet Diamond पहलूदार हीरा + Tide Crest लहर की चोटी diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..543534ddf0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9905,3 +9905,8 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Vector Packs Vektorcsomagok + Compass Rose Iránytűrózsa + Botanical Sprig Növényi ágacska + Facet Diamond Csiszolt gyémánt + Tide Crest Hullámhegy diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..05989c278d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7252,3 +7252,8 @@ breakText Glyphs Glif @msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" + Vector Packs Paket Vektor + Compass Rose Mawar Kompas + Botanical Sprig Ranting Botani + Facet Diamond Berlian Berfaset + Tide Crest Puncak Gelombang diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..dc015dfc61 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -9550,3 +9550,8 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Vector Packs Pacchetti vettoriali + Compass Rose Rosa dei venti + Botanical Sprig Rametto botanico + Facet Diamond Diamante sfaccettato + Tide Crest Cresta dell'onda diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..0f766d5a90 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9617,3 +9617,8 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Vector Packs ベクターパック + Compass Rose 羅針盤のバラ + Botanical Sprig 植物の小枝 + Facet Diamond 多面体ダイヤ + Tide Crest 波の頂 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..3dc49f89ed 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10285,3 +10285,8 @@ font-script Japanese იაპონური @msg A fold line is on a non-printing layer. მოკეცვის ხაზი არაბეჭდვად შრეზეა. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ანჯამები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" + Vector Packs ვექტორული პაკეტები + Compass Rose კომპასის ვარდი + Botanical Sprig ბოტანიკური ტოტი + Facet Diamond წახნაგოვანი ბრილიანტი + Tide Crest ტალღის ქედი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..7ae5a93c1e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9514,3 +9514,8 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Vector Packs 벡터 팩 + Compass Rose 나침반 장미 + Botanical Sprig 식물 가지 + Facet Diamond 패싯 다이아몬드 + Tide Crest 파도 마루 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..b9ac5ec4ca 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9953,3 +9953,8 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Vector Packs Vectorpakketten + Compass Rose Kompasroos + Botanical Sprig Botanisch takje + Facet Diamond Gefacetteerde diamant + Tide Crest Golfkam diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..b394da987b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9770,3 +9770,8 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Vector Packs Pakiety wektorowe + Compass Rose Róża wiatrów + Botanical Sprig Gałązka botaniczna + Facet Diamond Fasetowany diament + Tide Crest Grzbiet fali diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..7fb0bd696d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9988,3 +9988,8 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Vector Packs Pacotes vetoriais + Compass Rose Rosa dos ventos + Botanical Sprig Ramo botânico + Facet Diamond Diamante facetado + Tide Crest Crista da onda diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..767f811d0b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -10011,3 +10011,8 @@ shape Open Открытый @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, шарниры: {hinges}, ошибки: {errors}, предупреждения: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Vector Packs Векторные наборы + Compass Rose Роза ветров + Botanical Sprig Ботаническая ветвь + Facet Diamond Гранёный бриллиант + Tide Crest Гребень волны diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..012d7b6404 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9601,3 +9601,8 @@ digits Hindi Hindi @msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, gångjärn: {hinges}, fel: {errors}, varningar: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen + Vector Packs Vektorpaket + Compass Rose Kompassros + Botanical Sprig Botanisk kvist + Facet Diamond Fasetterad diamant + Tide Crest Vågkam diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 97fccd9167..bf6fa61a89 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -501,8 +501,9 @@ fn built_in_library_brush_names_are_in_complete_catalogs() { .flat_map(|(_, lib)| lib.brushes.iter().map(|b| b.name.clone()).collect::>()) .collect(); names.sort(); + let duplicates: Vec<&str> = names.windows(2).filter(|pair| pair[0] == pair[1]).map(|pair| pair[0].as_str()).collect(); + assert_eq!(duplicates, ["Zigzag"], "only the established Pattern Borders / Game Trails name is shared"); names.dedup(); - assert_eq!(names.len(), 46, "{names:?}"); let mut bad = vec![]; for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { let missing: Vec<&String> = names.iter().filter(|n| lang.catalog().plain(n).is_none()).collect(); diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..8a1b908cf0 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9875,3 +9875,8 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Vector Packs Vektör Paketleri + Compass Rose Pusula Gülü + Botanical Sprig Botanik Dal + Facet Diamond Fasetli Elmas + Tide Crest Dalga Tepesi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..0f713f4bcf 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9526,3 +9526,8 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Vector Packs Векторні набори + Compass Rose Роза вітрів + Botanical Sprig Ботанічна гілочка + Facet Diamond Гранований діамант + Tide Crest Гребінь хвилі diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..53bc23aca5 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7759,3 +7759,8 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" + Vector Packs Bộ cọ véc-tơ + Compass Rose Hoa la bàn + Botanical Sprig Cành cây + Facet Diamond Kim cương nhiều mặt + Tide Crest Đỉnh sóng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..f83d64189d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9758,3 +9758,8 @@ breakText Glyphs 字形 @msg A fold line is on a non-printing layer. 一条折线位于不打印的图层上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},铰链:{hinges},错误:{errors},警告:{warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 + Vector Packs 矢量画笔包 + Compass Rose 罗盘玫瑰 + Botanical Sprig 植物枝条 + Facet Diamond 切面钻石 + Tide Crest 浪尖 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..2272f5a396 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9568,3 +9568,8 @@ breakText Glyphs 字符 @msg A fold line is on a non-printing layer. 一條摺線位於不列印的圖層上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},鉸鏈:{hinges},錯誤:{errors},警告:{warnings} @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 + Vector Packs 向量筆刷包 + Compass Rose 羅盤玫瑰 + Botanical Sprig 植物枝條 + Facet Diamond 切面鑽石 + Tide Crest 浪尖 diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index 87fe34953f..5f0f853250 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -201,7 +201,8 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { json!("game-trails"), json!("energy-beams"), json!("dry-media"), - json!("tech-circuit") + json!("tech-circuit"), + json!("vector-packs") ] ); let dry = entries.iter().find(|e| under(e) && e.params["library"] == "dry-media").map(|e| e.label.as_str()); @@ -232,6 +233,12 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { click(&mut app, &ctx, "Circuit Trace", Modifiers::NONE, 2.0); assert!(has(&app, "Circuit Trace") && !has(&app, "Bus Lines")); assert_eq!(undo_len(&app), undo + 1); + let r = app.run("window.brushLibrary", json!({"library": "Vector Packs"})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("vector-packs"), Some(4))); + let undo = undo_len(&app); + click(&mut app, &ctx, "Compass Rose", Modifiers::NONE, 3.0); + assert!(has(&app, "Compass Rose") && !has(&app, "Facet Diamond")); + assert_eq!(undo_len(&app), undo + 1); // Without brushes there is nothing to save. let all: Vec = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect(); app.run("brush.delete", json!({ "names": all })).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..71e9cf24d4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5051,9 +5051,9 @@ error. ## Brush libraries -Brush libraries are read-only sets of brushes: ten generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle +Brush libraries are read-only sets of brushes: eleven generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and -Charcoal Dust art brushes, id `dry-media`, and Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`), the `.vectorcraft` files in the user library folder of the desktop app (User +Charcoal Dust art brushes, id `dry-media`, and Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, and Vector Packs with four original vector scatter marks, id `vector-packs`), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and `brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..dc0fe7f4f5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1104,9 +1104,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. + - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, Vector Packs) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. + - **Vector Packs library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Vector Packs offers Compass Rose, Botanical Sprig, Facet Diamond and Tide Crest. Each is an original editable vector mark repeated along a path as a scatter brush and tinted by the stroke color. The public page names the category but does not specify its presets. Evidence: `vector_packs_marks_are_editable_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers geometry, repetition, add/apply, undo and saving; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers the menu and panel. - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - **Brush names in library panels**: a built-in brush library's panel shows its brushes' names in the UI language, in its list rows and tooltips, and its Find field matches the name shown or the English name. This is VectorCraft's own rule. A User Defined or Other Library… library's brushes, and the document's Brushes panel, show names as they are stored. A click, a drag, Add to Brushes and `brush.addFromLibrary` still use the English name, so the brush comes into the document under that name (`built_in_library_brushes_are_listed_in_the_ui_language`, `built_in_library_brush_names_are_in_complete_catalogs`). - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection, and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. From 7174cce6c239b19a330e7ba7d24a0b4e30cfe72d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 16:32:20 -0800 Subject: [PATCH 02/11] Rerun CI From 72aae8ace7f158d4b3082f495fb097c910643c3f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 01:55:52 -0800 Subject: [PATCH 03/11] Docs: count Vector Packs in the brush library summaries The G5 entry in docs/gaps.md, the M10 row in docs/roadmap.md, both Strokes, brushes rows in docs/target-app-parity.md and the brush library row in docs/ui-parity.md now list eleven built-in brush libraries, including Vector Packs. --- docs/gaps.md | 4 ++-- docs/roadmap.md | 2 +- docs/target-app-parity.md | 4 ++-- docs/ui-parity.md | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index 304535dacb..cad6c0c28c 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -676,8 +676,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi libraries ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html)): Window › Brush Libraries and the Brushes panel's Brush Libraries Menu open each library in a library panel of - its own (ten original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes (one - bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes) and Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a + its own (eleven original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes (one + bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes) and Vector Packs (Compass Rose, Botanical Sprig, Facet Diamond and Tide Crest scatter brushes); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a click adds a brush to the document's Brushes with the patterns, symbols and other resources its art uses, as one undo step (applied to the selected paths in the same step), dragging one onto a path adds and applies it and diff --git a/docs/roadmap.md b/docs/roadmap.md index 2e9fe39fe9..2897068b5a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -170,7 +170,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | +| 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, eleven generated libraries including Vector Packs, Tech Circuit, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | 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; the script document model and batch work remain | 18–27 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 783d8e7907..afe2c572ca 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -258,7 +258,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; 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 (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (eleven generated libraries including Vector Packs, Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | @@ -527,7 +527,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill 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); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | -| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (ten generated in code including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | +| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (eleven generated in code including Vector Packs, Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e44a28165c..3a4c46350c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -457,7 +457,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves, the Gradient tool draws a vector or a Pen drag pulls out an anchor's handle; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | -| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; ten built-in libraries (original, generated in code) | +| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, Vector Packs, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; eleven built-in libraries (original, generated in code) | | Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | From a18d5de313bf940dfed84cb3e7e8e896f5ebb1b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 13:43:10 -0800 Subject: [PATCH 04/11] Brushes: keep the library test's frame times increasing The Vector Packs click runs frames at 3.0 to 3.5, so the Pressure Sensitive click now starts at 4.0 instead of 3.0. egui panics when a frame's time is earlier than the last one. --- crates/ui-egui/src/panels/tests_brush_libraries.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index f55b754afd..bd9f0e9a1b 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -244,7 +244,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("pressure-sensitive"), Some(4))); let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap(); let undo = undo_len(&app); - click(&mut app, &ctx, "Flex Ribbon", Modifiers::NONE, 3.0); + click(&mut app, &ctx, "Flex Ribbon", Modifiers::NONE, 4.0); assert!(has(&app, "Flex Ribbon") && !has(&app, "Pulse Stroke")); assert_eq!(undo_len(&app), undo + 1); assert_eq!( From 8c22c4cbe36b27228fa5f583b798181aec5299d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:20:50 -0800 Subject: [PATCH 05/11] Brushes: check Vector Packs tinting and the applied brush The Vector Packs test now renders each brush with a teal stroke and checks that every generated path is filled with that color, and after each brush.addFromLibrary call it checks that the line's stroke uses the brush. The black-stroke render still checks that each mark repeats along the path. G5's Missing entry in docs/gaps.md now counts thirteen built-in brush libraries, matching the Done entry. --- crates/engine/src/tests/brushlib.rs | 18 ++++++++++++++++++ docs/gaps.md | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 035b226bea..418c6e3ca0 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -214,11 +214,29 @@ fn vector_packs_marks_are_editable_and_survive_a_saved_library() { assert!(art_paths(&sc.art).len() >= 2, "{} has no editable vector mark", b.name); let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &black_stroke()); assert!(pieces.len() >= 3, "{} does not repeat along a path", b.name); + // The black marks take a non-black stroke color as their fill. + let teal = vectorcraft_color::Color::rgb(0.1, 0.6, 0.5); + let stroke = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(teal), 1.0); + let mut fills = vec![]; + for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &stroke) { + piece.walk(&mut |c| { + if c.path_data().is_some() { + fills.push(c.appearance.fill().map(|f| f.paint.clone())); + } + }); + } + assert!(!fills.is_empty(), "{} draws no paths", b.name); + for fill in fills { + let Some(vectorcraft_color::Paint::Solid { color, .. }) = fill else { panic!("{} draws a path without a solid fill: {fill:?}", b.name) }; + let (got, want) = (color.to_rgb(), teal.to_rgb()); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3), "{} fills {got:?}, not the stroke color {want:?}", b.name); + } let before = undo_len(&s); let added = run(&mut s, "brush.addFromLibrary", json!({"library": "vector-packs", "name": b.name, "apply": true, "ids": [line]})); assert_eq!(strs(&added["added"]), [b.name.as_str()]); assert_eq!(added["applied"], json!([line])); assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(line)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str())); } let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); diff --git a/docs/gaps.md b/docs/gaps.md index b7864ae32b..dd86ee2ff1 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -714,7 +714,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Fine Grain, Canvas Weave, Burlap Sack, Cracked Glaze, Mosaic Floor, Quilted Squares, Leaded Glass and Damp Paper, painted with the texture effects; User Defined; Other Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). -- **Missing:** more built-in brush libraries beyond the eleven shipped (and further graphic-style libraries beyond the eleven shipped, and further symbol libraries beyond Basic +- **Missing:** more built-in brush libraries beyond the thirteen shipped (and further graphic-style libraries beyond the eleven shipped, and further symbol libraries beyond Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write. - **Estimate:** 3–13 h (estimated). From 8484485a0eecb709f0e76ac23b825db06ed3f2c6 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 22:38:05 +0700 Subject: [PATCH 06/11] Brushes test: Soft Bloom's click comes after the Vector Packs click it now follows --- crates/ui-egui/src/panels/tests_brush_libraries.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index d21023c26d..63f379b0db 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -258,7 +258,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { let r = app.run("window.brushLibrary", json!({"library": "Image Brush"})).unwrap(); assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("image-brush"), Some(4))); let undo = undo_len(&app); - click(&mut app, &ctx, "Soft Bloom", Modifiers::NONE, 4.0); + click(&mut app, &ctx, "Soft Bloom", Modifiers::NONE, 5.0); assert!(has(&app, "Soft Bloom") && !has(&app, "Color Flecks")); assert_eq!(undo_len(&app), undo + 1); // Without brushes there is nothing to save. From cdcaab93016e9d749101c803e5afc8be317ba83b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 07:53:05 -0800 Subject: [PATCH 07/11] Retype: stacked lines become one area type object Part of #4934. type.retype set each line of outlined text as its own point type object, even when the lines stack as one paragraph. - Opaque, Normal lines with a solid fill or none and no stroke that follow each other in paint order, with the same group, paint, font, size, turn and tracking, each the same leading (0.25 to 3 times the size) below the one before and lined up at their starts, ends or centers, become one area type object. Its leading is Auto when Auto puts the last baseline in place, else the mean distance between the baselines, and its alignment is left, right or center. Its frame is Convert To Area Type's, now shared through typemenu::point_to_area. An untracked line of one or two glyphs takes the others' tracking. - Every object is laid out and compared with the outlines first: when area type would move a glyph the lines stay multi-line point type. When that also moves a glyph, the block ends at that glyph's line and the lines after it join again. Type whose bounds would reach past the coordinate limit stays apart. - Text Wrap objects above new area type are taken into account; when checking them on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes, the lines stay multi-line point type. text::wrap_copy_units counts that work without copying the outlines, and wrap_work no longer copies them to count. - The result's fonts entries add leading and area, and texts join an object's lines with line breaks. These rules are VectorCraft's own. Docs: docs/mcp.md (Retype several lines), docs/type-parity.md (Retype row), docs/target-app-parity.md, docs/roadmap.md (M7 row). --- crates/doc/src/text.rs | 2 +- crates/doc/src/text/wrap.rs | 44 ++- crates/engine/src/cmd/retype.rs | 370 ++++++++++++++++++++++++-- crates/engine/src/cmd/retype_tests.rs | 305 +++++++++++++++++++++ crates/engine/src/cmd/typemenu.rs | 50 ++-- docs/mcp.md | 20 ++ docs/roadmap.md | 2 +- docs/target-app-parity.md | 4 + docs/type-parity.md | 2 +- 9 files changed, 749 insertions(+), 50 deletions(-) diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index c6a9860189..107ac1dab9 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -38,7 +38,7 @@ pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList, TabAlign, TabStop, }; -pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work}; +pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_sources, wrap_work}; /// A text object. `runs` split into paragraphs at `\n`. /// diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index 15a0fbbd40..c55a973be0 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -66,10 +66,45 @@ fn collect<'a>(n: &'a Node, out: &mut Vec>) { } } +/// The anchors and subpaths [`outline`] would collect for wrap object `n`, counted without copying +/// them. +fn outline_size(n: &Node) -> (usize, usize) { + match &n.kind { + NodeKind::Path { path, guide: false, .. } => path + .subpaths + .iter() + .filter(|sp| sp.closed || sp.anchors.len() > 2) + .fold((0usize, 0usize), |(a, s), sp| (a.saturating_add(sp.anchors.len()), s.saturating_add(1))), + NodeKind::Compound { children, .. } | NodeKind::Group { children, clip: false } => children + .iter() + .filter(|c| c.visible) + .map(|c| outline_size(c)) + .fold((0, 0), |(a, s), (ca, cs)| (a.saturating_add(ca), s.saturating_add(cs))), + NodeKind::Group { children, clip: true } => children.first().map_or((0, 0), |c| outline_size(c)), + // A rectangle of the object's bounds. + _ => { + if n.geometric_bounds().is_some() { + (4, 1) + } else { + (0, 0) + } + } + } +} + /// How much [`resolve_wrap`] would copy into the wrap shapes of every area text object in `doc`: /// each wrap object's outline (its anchors, plus one for the shape) once for each area text object /// below it in its layer. pub fn wrap_work(doc: &Document) -> usize { + work(doc, false) +} + +/// [`wrap_work`], with one more for each subpath of each outline, empty ones included. +pub fn wrap_copy_units(doc: &Document) -> usize { + work(doc, true) +} + +fn work(doc: &Document, count_subpaths: bool) -> usize { let mut total = 0usize; for layer in &doc.layers { let mut items = vec![]; @@ -78,11 +113,10 @@ pub fn wrap_work(doc: &Document) -> usize { for it in items.iter().rev() { match it { Item::Wrap(n) => { - let mut pd = PathData::default(); - outline(n, &mut pd); - if !pd.is_empty() { - let anchors: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum(); - above = above.saturating_add(anchors.saturating_add(1)); + let (anchors, subpaths) = outline_size(n); + if anchors > 0 { + let subpaths = if count_subpaths { subpaths } else { 0 }; + above = above.saturating_add(anchors).saturating_add(subpaths).saturating_add(1); } } Item::Text(_) => total = total.saturating_add(above), diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 6066e47f33..45ae073129 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -11,9 +11,10 @@ //! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched //! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object //! per line of glyphs, with the first glyph's fill and stroke. A line whose glyphs are evenly spaced -//! apart takes that spacing as its tracking ([`Line::tracked`]). Shapes that match no font stay as -//! they are and are reported. Near matches (another version of the font, simplified outlines, -//! merged glyphs) and images are phase 2. +//! apart takes that spacing as its tracking ([`Line::tracked`]), and lines stacked at one leading +//! and lined up at their starts, ends or centers become one area type object ([`blocks`]). Shapes +//! that match no font stay as they are and are reported. Near matches (another version of the +//! font, simplified outlines, merged glyphs) and images are phase 2. use std::f64::consts::{PI, TAU}; use std::sync::Arc; @@ -40,7 +41,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size, tracking (1/1000 em)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches", + "{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches", has_selected_path, retype )] @@ -347,18 +348,15 @@ impl Line { /// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing, /// more space than whole spaces make); `None` when the type draws every glyph in its place. fn first_mismatch(&self, t: &TextObject) -> Option { - let lay = vectorcraft_text::layout(FontDb::global(), t); - let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()); - let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01); - for (k, m) in self.matches.iter().enumerate() { - let Some(g) = drawn.next() else { return Some(k) }; - let at = t.xf * (g.xf * Point::ORIGIN); - if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol { - return Some(k); - } - } - // Ink the outlines did not have: the last glyph is where it went wrong. - drawn.next().map(|_| self.matches.len().saturating_sub(1)) + first_mismatch(t, &self.matches, self.size()) + } + + /// Along the line, where its first glyph starts and its last glyph's advance ends, from + /// `from` (the tracking after the last glyph left out). + fn span_from(&self, from: Point) -> (f64, f64) { + let dir = self.dir(); + let last = self.matches.last().map_or(self.end, |m| m.origin + dir * (m.face.advance(m.gid) * m.scale)); + ((self.origin - from).dot(dir), (last - from).dot(dir)) } /// This line with the tracking its glyphs are spaced by, when it has at least three glyphs. @@ -564,6 +562,24 @@ fn round_tracking(t: f64) -> f64 { if (t - t.round()).abs() < 0.05 { t.round() } else { t } } +/// The first of `matches` that type `t` (at `size`) does not draw as the outlines did: another +/// glyph (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing, +/// more space than whole spaces make); `None` when the type draws every glyph in its place. +fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64) -> Option { + let lay = vectorcraft_text::layout(FontDb::global(), t); + let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()); + let tol = (size * 0.01).max(0.01); + for (k, m) in matches.iter().enumerate() { + let Some(g) = drawn.next() else { return Some(k) }; + let at = t.xf * (g.xf * Point::ORIGIN); + if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol { + return Some(k); + } + } + // Ink the outlines did not have: the last glyph is where it went wrong. + drawn.next().map(|_| matches.len().saturating_sub(1)) +} + /// `lines` checked against their own layout: a line splits where its type stops drawing the /// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`). /// The glyphs laid out are bounded by a multiple of the number of glyphs. @@ -656,6 +672,263 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) out } +/// Most units (anchors, subpaths and shapes) that Text Wrap objects may copy into the wrap shapes +/// of the area type on the layers Retype changes +/// ([`vectorcraft_doc::text::wrap_copy_units`]) when Retype checks how they flow new area type. +const MAX_WRAP_WORK: usize = 2_000_000; + +#[cfg(not(test))] +fn max_wrap_work() -> usize { + MAX_WRAP_WORK +} + +#[cfg(test)] +thread_local! { + /// [`MAX_WRAP_WORK`], lowered by tests on their own thread. + static WRAP_LIMIT: std::cell::Cell = const { std::cell::Cell::new(MAX_WRAP_WORK) }; +} + +#[cfg(test)] +fn max_wrap_work() -> usize { + WRAP_LIMIT.with(|c| c.get()) +} + +/// Lines farther apart than this many times their size do not join into one object. +const MAX_LEADING: f64 = 3.0; + +/// What Retype makes: one type object and the shapes it replaces. +struct Made { + t: TextObject, + /// For area type, the point type that also draws the glyphs in place: the type kept when + /// Text Wrap objects above it change the area type's layout. + point: Option, + /// The glyphs the type must draw, in order. + matches: Vec, + pieces: Vec, + text: String, + face: Arc, + size: f64, + tracking: f64, + /// The leading set on the type: None for Auto or a single line. + leading: Option, + opacity: f32, + blend: vectorcraft_color::BlendMode, +} + +impl Made { + fn line(l: &Line, system_layout: bool) -> Made { + Made { + t: l.text_object(system_layout), + point: None, + matches: l.matches.clone(), + pieces: l.pieces.clone(), + text: l.text.clone(), + face: l.face.clone(), + size: l.size(), + tracking: l.tracking, + leading: None, + opacity: l.opacity, + blend: l.blend, + } + } +} + +/// The alignments lines can share, in the order one is chosen: their starts, their ends, their +/// centers. +const ALIGNS: [vectorcraft_doc::Justify; 3] = [vectorcraft_doc::Justify::Left, vectorcraft_doc::Justify::Right, vectorcraft_doc::Justify::Center]; + +/// A run of lines that may become one object: lines after the first, each one leading further +/// across, in the same group, paint, transparency, font, size, turn and tracking, lined up alike. +struct Block { + lines: Vec, + /// The mean distance between baselines, from the first line's to the last line's. + leading: f64, + /// Which of [`ALIGNS`] every line so far shares. + aligns: [bool; 3], + /// The tracking of the first line that has one ([`Block::spaced`]). + tracking: Option, +} + +impl Block { + fn new(l: Line) -> Block { + let tracking = Block::spaced(&l).then_some(l.tracking); + Block { lines: vec![l], leading: 0.0, aligns: [true; 3], tracking } + } + + /// Does line `l` have a tracking of its own? A line of fewer than three glyphs that kept no + /// tracking has no gaps to measure it by ([`Line::tracked`]): it takes the block's. + fn spaced(l: &Line) -> bool { + l.pieces.len() >= 3 || l.tracking != 0.0 + } + + /// Add `l` when it continues the block; `l` back when it does not. `follows` tells whether the + /// shape `l` starts with comes right after the block's last shape, with nothing between them + /// in paint order. + fn take(&mut self, l: Line, follows: impl Fn(NodeId, NodeId) -> bool) -> Option { + let (Some(first), Some(prev)) = (self.lines.first(), self.lines.last()) else { return Some(l) }; + let (Some(a), Some(b)) = (prev.pieces.last(), l.pieces.first()) else { return Some(l) }; + let size = first.size(); + let tol = (size * 0.01).max(0.01); + let same = follows(*a, *b) + && l.parent == first.parent + && l.appearance == first.appearance + && l.opacity == first.opacity + && l.blend == first.blend + && l.face.id() == first.face.id() + && (l.scale - first.scale).abs() <= first.scale * 1e-4 + && ((l.angle - first.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5 + // The lines' estimates may differ a little; the layout check decides. + && (!Block::spaced(&l) || self.tracking.is_none_or(|t| (l.tracking - t).abs() < 1.0)) + // Lines whose ink overlaps, or a gradient spanning them, would paint otherwise as one. + && paints_as_one(first); + if !same { + return Some(l); + } + // Across the lines, down from the first line's baseline. + let across = Vec2::new(-first.angle.sin(), first.angle.cos()); + let down = (l.origin - first.origin).dot(across); + let n = self.lines.len() as f64; + // The mean distance between the baselines so far, which this line's must continue. + let leading = if self.lines.len() == 1 { down } else { self.leading }; + if !(leading > size * 0.25 && leading <= size * MAX_LEADING) || (down - n * leading).abs() > tol { + return Some(l); + } + let leading = down / n; + let (s0, e0) = first.span_from(first.origin); + let (s, e) = l.span_from(first.origin); + let fits = [(s - s0).abs() <= tol, (e - e0).abs() <= tol, ((s + e) - (s0 + e0)).abs() * 0.5 <= tol]; + let aligns = [self.aligns[0] && fits[0], self.aligns[1] && fits[1], self.aligns[2] && fits[2]]; + if !aligns.contains(&true) { + return Some(l); + } + self.leading = leading; + self.aligns = aligns; + if self.tracking.is_none() && Block::spaced(&l) { + self.tracking = Some(l.tracking); + } + self.lines.push(l); + None + } + + /// The block as one area type object when type draws every glyph in its place as area type, + /// else as one point type object when that does. When neither does, the lines before the line + /// of the first glyph the type moves are made again as a block, and the lines from that one on + /// are joined again ([`blocks`]); the first line on its own stays one object. Area type whose + /// frame would reach past [`crate::MAX_COORD`] stays point type, and point type whose bounds + /// would stays one object per line. Each try takes six times the + /// block's glyphs from `budget` (point and area type are each laid out, measured and checked); + /// without enough left, each line is one object. + fn made(self, system_layout: bool, budget: &mut usize) -> Vec { + let single = |lines: &[Line]| lines.iter().map(|l| Made::line(l, system_layout)).collect::>(); + let (Some(first), true) = (self.lines.first(), self.lines.len() > 1) else { return single(&self.lines) }; + let Some(justify) = ALIGNS.iter().zip(self.aligns).find(|(_, ok)| *ok).map(|(j, _)| *j) else { return single(&self.lines) }; + let glyphs = self.lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add); + let Some(left) = budget.checked_sub(glyphs.saturating_mul(6)) else { return single(&self.lines) }; + *budget = left; + let mut all = first.clone(); + all.tracking = self.tracking.unwrap_or(first.tracking); + all.text = self.lines.iter().map(|l| l.text.as_str()).collect::>().join("\n"); + let mut t = all.probe(system_layout); + t.para.justify = justify; + let size = first.size(); + let mut set_leading = None; + if let Some(r) = t.runs.first_mut() { + // The leading that puts the last baseline where the last line's is: Auto when Auto + // does, else the mean distance between baselines, to a thousandth of a point (as + // typed leading is) when that still puts the last baseline in place. + let gaps = self.lines.len().saturating_sub(1) as f64; + let across = Vec2::new(-first.angle.sin(), first.angle.cos()); + let span = self.lines.last().map_or(0.0, |l| (l.origin - first.origin).dot(across)); + if (t.para.effective_leading(&r.style) * gaps - span).abs() > size * 1e-4 { + let exact = span / gaps; + let rounded = (exact * 1000.0).round() / 1000.0; + let leading = if ((rounded - exact) * gaps).abs() <= size * 1e-4 { rounded } else { exact }; + r.style.leading = Some(leading); + set_leading = Some(leading); + } + } + let matches: Vec = self.lines.iter().flat_map(|l| l.matches.iter().cloned()).collect(); + // Aligned at its end or center, point type starts its first line elsewhere: the type moves + // so its first glyph is where the first outline is. + let lay = vectorcraft_text::layout(FontDb::global(), &t); + if let (Some(g), Some(m)) = (lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()), matches.first()) { + let at = t.xf * (g.xf * Point::ORIGIN); + t.xf = kurbo::Affine::translate(m.origin - at) * t.xf; + } + super::typecmd::refresh_bounds(&mut t); + if let Some(k) = first_mismatch(&t, &matches, size) { + // The line that holds glyph `k`. + let mut seen = 0usize; + let at = self.lines.iter().position(|l| { + seen = seen.saturating_add(l.pieces.len()); + k < seen + }); + let Block { mut lines, leading, aligns, .. } = self; + let rest = lines.split_off(at.unwrap_or(0).clamp(1, lines.len())); + let mut out = if lines.len() > 1 { + let tracking = lines.iter().find(|l| Block::spaced(l)).map(|l| l.tracking); + Block { lines, leading, aligns, tracking }.made(system_layout, budget) + } else { + single(&lines) + }; + // The lines of the rest followed each other in the block. + out.extend(blocks(rest, |_, _| true, system_layout, budget)); + return out; + } + // The edit is refused when an object's bounds reach past the coordinate limit. A turned + // block's box can reach a corner that none of its lines does: the lines then stay apart. + let in_range = + |t: &TextObject| Node::new(NodeId(0), NodeKind::Text(Box::new(t.clone()))).geometric_bounds().is_none_or(crate::sanity::rect_in_range); + if !in_range(&t) { + return single(&self.lines); + } + let mut area = t.clone(); + super::typemenu::point_to_area(&mut area); + let mut point = None; + if in_range(&area) && first_mismatch(&area, &matches, size).is_none() { + point = Some(std::mem::replace(&mut t, area)); + } + vec![Made { + t, + point, + matches, + pieces: self.lines.iter().flat_map(|l| l.pieces.iter().copied()).collect(), + text: all.text, + face: first.face.clone(), + size, + tracking: all.tracking, + leading: set_leading, + opacity: first.opacity, + blend: first.blend, + }] + } +} + +/// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of +/// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after +/// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`]. +fn blocks(lines: Vec, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec { + let mut out = vec![]; + let mut block: Option = None; + for l in lines { + let l = match block.as_mut() { + Some(b) => match b.take(l, &follows) { + None => continue, + Some(l) => l, + }, + None => l, + }; + if let Some(b) = block.take() { + out.extend(b.made(system_layout, budget)); + } + block = Some(Block::new(l)); + } + if let Some(b) = block { + out.extend(b.made(system_layout, budget)); + } + out +} + /// Puts parts of a line at the front of the work list, in order. trait FrontParts { fn extend_front_parts(&mut self, l: &Line, ranges: [(usize, usize); N]); @@ -855,20 +1128,29 @@ fn retype(s: &mut Session, p: &Value) -> Result { !lone }); } - (lines, unmatched, truncated) + let at: std::collections::HashMap = pieces.iter().enumerate().map(|(i, pc)| (pc.id, i)).collect(); + let follows = |a: NodeId, b: NodeId| match (at.get(&a), at.get(&b)) { + (Some(i), Some(j)) => *j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier), + _ => false, + }; + // Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room + // for small blocks. + let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256); + (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated) }; if lines.is_empty() { return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len()))); } let made = s.edit("Retype", |d, sel| { + // The layers as they were, for the Text Wrap check below. + let before = lines.iter().any(|l| l.point.is_some()).then(|| d.clone()); let mut ids = vec![]; let mut emptied = vec![]; for l in &lines { let Some(first) = l.pieces.first() else { continue }; let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?; - let t = l.text_object(system_layout); let id = d.alloc_id(); - let mut node = Node::new(id, NodeKind::Text(Box::new(t))); + let mut node = Node::new(id, NodeKind::Text(Box::new(l.t.clone()))); // The glyphs' own transparency (the group's, kept, still applies over it). node.opacity = l.opacity; node.blend = l.blend; @@ -915,17 +1197,65 @@ fn retype(s: &mut Session, p: &Value) -> Result { } } } + // Text Wrap objects above new area type flow it once the edit is done: area type they + // would move a glyph of becomes the point type that draws it in place. + if let Some(before) = &before { + // Worked out on a copy, so the edit's own Text Wrap refresh still sees every other + // area type whose wrap changes, and only on the layers this edit changed, as that + // refresh is. The copy holds only the changed layers while the work is counted; past + // the limit, the new area type is not flowed and all of it becomes its point type. + let mut probe = d.clone(); + let all = std::mem::take(&mut probe.layers); + probe.layers = all + .iter() + .enumerate() + .filter(|(i, layer)| { + // As resolve_wrap tells an unchanged layer: the same layer at its index first. + !(before.layers.get(*i).is_some_and(|b| Arc::ptr_eq(b, layer)) + || before.layers.iter().any(|b| b.id == layer.id && Arc::ptr_eq(b, layer))) + }) + .map(|(_, layer)| layer.clone()) + .collect(); + let units = vectorcraft_doc::text::wrap_copy_units(&probe); + let flowed = units <= max_wrap_work(); + probe.layers = all; + if flowed && units > 0 { + vectorcraft_doc::text::resolve_wrap(Some(before), &mut probe); + } + // With nothing to copy, no area type on those layers has a wrap shape. + for (l, id) in lines.iter().zip(&ids).filter(|_| units > 0) { + let Some(point) = &l.point else { continue }; + let Some(NodeKind::Text(t)) = probe.node(*id).map(|n| &n.kind) else { continue }; + if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size).is_none()) { + continue; + } + if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { + **t = point.clone(); + } + } + } let mut keep: Vec = roots.iter().copied().filter(|r| d.node(*r).is_some()).collect(); keep.extend(&ids); sel.set(keep); Ok(ids) })?; + let d = &s.doc()?.doc; + let area = + |id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. })); Ok(json!({ "ids": made.iter().map(|i| i.0).collect::>(), "texts": lines.iter().map(|l| l.text.clone()).collect::>(), "fonts": lines .iter() - .map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.size(), "tracking": l.tracking})) + .zip(&made) + .map(|(l, id)| json!({ + "family": l.face.family, + "style": l.face.style, + "size": l.size, + "tracking": l.tracking, + "leading": l.leading, + "area": area(id), + })) .collect::>(), "unmatched": unmatched.iter().map(|i| i.0).collect::>(), "truncated": truncated, diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index b89d8e0d78..ec98c914c0 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -568,6 +568,202 @@ fn assert_same_places(a: &TextObject, b: &TextObject) { } } +#[test] +fn several_lines_become_one_area_type_object() { + let mut s = session(); + let text = "First line\nSecond one\nThird"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["area"], json!(true), "{r}"); + assert_eq!(r["fonts"][0]["leading"], json!(null), "Auto leading gives the lines' spacing: {r}"); + let t = text_of(&s, r["ids"][0].as_u64().unwrap()); + assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. })); + assert_eq!(t.plain_text(), text); + assert_same_places(&before, &t); +} + +#[test] +fn lines_keep_their_leading_and_alignment() { + for justify in ["left", "center", "right"] { + let mut s = session(); + let text = "Wide first line\nmid\nlast one"; + let (before, r) = retyped(&mut s, json!({"x": 300, "y": 100, "text": text, "size": 20, "justify": justify}), &[json!({"leading": 31})]); + assert_eq!(r["texts"], json!([text]), "{justify}: {r}"); + assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 31.0, 1e-3), "{justify}: {r}"); + assert_eq!(r["fonts"][0]["area"], json!(true), "{justify}: {r}"); + let t = text_of(&s, r["ids"][0].as_u64().unwrap()); + assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "{justify}"); + assert_eq!(t.para.justify, before.para.justify, "{justify}"); + assert_same_places(&before, &t); + } +} + +#[test] +fn a_long_block_near_auto_leading_keeps_its_own_leading() { + // 24.001 pt is Auto's 24 pt within a ten-thousandth of the size per line, but 250 lines + // move the last one a quarter of a point. + let mut s = session(); + let text = vec!["ab"; 250].join("\n"); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 24.001})]); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len())); + assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.001, 1e-4), "{}", r["fonts"][0]); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_long_block_at_auto_leading_of_a_fractional_size_keeps_auto() { + // Auto leading of 20.002 pt is 24.0024 pt, finer than the thousandth of a point the leading + // between two lines is read to. + let mut s = session(); + // Six hundred lines: read to a thousandth, each gap would be 0.0004 pt short, and the last + // line 0.24 pt off. + let text = vec!["ab"; 600].join("\n"); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20.002}), &[]); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len())); + assert_eq!(r["fonts"][0]["leading"], json!(null), "{}", r["fonts"][0]); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_long_block_at_a_leading_finer_than_a_thousandth_keeps_it() { + // 23.9996 pt read to a thousandth is 24 pt, Auto for 20 pt type: over 600 lines the last one + // would be 0.24 pt off. + let mut s = session(); + let text = vec!["ab"; 600].join("\n"); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 23.9996})]); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len())); + assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 23.9996, 1e-6), "{}", r["fonts"][0]); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_block_whose_first_gap_is_a_little_off_stays_one_object() { + // The second line moved up 0.004 pt: its gap read alone, carried over 100 lines, would put + // the last one 0.4 pt off. + let mut s = session(); + let text = ["ab"; 100].join("\n"); + let id = s.execute("text.create", &json!({"x": 40, "y": 40, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "leading": 24.004})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let kids = children_of(&s, g); + s.execute("select.set", &json!({"ids": kids[2..4]})).unwrap(); + s.execute("object.move", &json!({"dx": 0, "dy": -0.004})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len())); + assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.004, 1e-3), "{}", r["fonts"][0]); +} + +#[test] +fn lines_whose_frame_would_pass_the_coordinate_limit_stay_point_type() { + let mut s = session(); + let text = "Wide line\nWide"; + let id = s.execute("text.create", &json!({"x": 3_999_000, "y": 100, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap(); + let right = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap().x1; + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + // The ink ends 2 pt short of the limit; Convert To Area Type's slack would reach past it. + s.execute("object.move", &json!({"dx": vectorcraft_doc::MAX_COORD - 2.0 - right, "dy": 0})).unwrap(); + let before = text_of(&s, id); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["area"], json!(false), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_line_type_cannot_join_ends_the_block_there() { + // The fourth line keeps a fraction of a unit of tracking that the others do not: joined, it + // moves, so the lines before it stay one object and the lines after it join again. + let mut s = session(); + let line = "M".repeat(40); + let text = [line.as_str(); 6].join("\n"); + let start = 3 * 41; + let (before, r) = + retyped(&mut s, json!({"x": 20, "y": 40, "text": text, "size": 20}), &[json!({"start": start, "end": start + 40, "tracking": 0.6})]); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.len(), 3, "{texts:?} {}", r["fonts"]); + assert_eq!(texts.join("\n"), text); + let places: Vec = r["ids"].as_array().unwrap().iter().flat_map(|id| glyph_places(&text_of(&s, id.as_u64().unwrap()))).collect(); + let want = glyph_places(&before); + assert_eq!(places.len(), want.len()); + for (x, y) in places.iter().zip(&want) { + assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}"); + } +} + +/// The glyphs of the outline groups `others` moved to the end of group `g`, in order, and the +/// emptied groups removed. +fn into_one_group(s: &mut Session, g: u64, others: &[u64]) { + s.edit("test", |d, _| { + for o in others { + let kids: Vec<_> = d.node(NodeId(*o)).unwrap().children().unwrap().to_vec(); + d.remove(NodeId(*o))?; + for k in kids { + let at = d.node(NodeId(g)).unwrap().children().unwrap().len(); + d.insert(Some(NodeId(g)), at, (*k).clone())?; + } + } + Ok(()) + }) + .unwrap(); +} + +#[test] +fn lines_that_do_not_stack_as_a_paragraph_stay_apart() { + let mut s = session(); + // Far apart, then lined up at nothing. + let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Top", "size": 20})); + let b = outlined(&mut s, json!({"x": 40, "y": 300, "text": "Far", "size": 20})); + let c = outlined(&mut s, json!({"x": 75, "y": 324, "text": "Askew", "size": 20})); + into_one_group(&mut s, a, &[b, c]); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Top", "Far", "Askew"]), "{r}"); + assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["area"] == json!(false)), "{r}"); +} + +#[test] +fn a_shape_between_lines_keeps_them_apart() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB\nCD", "size": 30})); + let rect = s.execute("shape.rectangle", &json!({"x": 30, "y": 60, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap(); + s.edit("test", |d, _| { + let n = d.node(NodeId(rect)).unwrap().clone(); + d.remove(NodeId(rect))?; + d.insert(Some(NodeId(g)), 2, n)?; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["AB", "CD"]), "the rectangle is painted between the lines: {r}"); +} + +#[test] +fn tracked_lines_keep_their_tracking_and_spaces() { + let mut s = session(); + let text = "SPACED OUT\nTITLE"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_short_line_takes_the_tracking_of_its_block() { + // One glyph has no gap to measure tracking by: it joins the tracked lines. + for text in ["TITLE\nB", "B\nTITLE", "TITLE\nB\nTITLE"] { + let mut s = session(); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); + } +} + #[test] fn unevenly_tracked_type_still_becomes_type() { let mut s = session(); @@ -882,3 +1078,112 @@ fn overlapping_translucent_glyphs_are_not_tracked_into_one_object() { assert_eq!(r["texts"], json!(["M", "M", "M", "M"]), "{r}"); assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["tracking"] == json!(0.0)), "{r}"); } + +#[test] +fn translucent_gradient_or_stroked_lines_stay_apart() { + for case in ["opacity", "blend", "gradient", "stroke"] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "One\nTwo", "size": 30})); + let kids = children_of(&s, g); + match case { + "gradient" => { + let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + s.execute("paint.setFill", &json!({"gradient": gradient, "ids": kids})).unwrap(); + } + "stroke" => { + s.execute("paint.setStroke", &json!({"color": "#ff0000", "ids": kids})).unwrap(); + } + _ => { + s.edit("test", |d, _| { + for k in &kids { + let n = d.node_mut(NodeId(*k)).unwrap(); + if case == "opacity" { + n.opacity = 0.5; + } else { + n.blend = vectorcraft_color::BlendMode::Multiply; + } + } + Ok(()) + }) + .unwrap(); + } + } + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["One", "Two"]), "{case}: one object would composite or fill the lines as one: {r}"); + } +} + +#[test] +fn lines_stay_point_type_past_the_text_wrap_limit_of_their_layer() { + // A Text Wrap object above the lines that moves no glyph, on their layer or on another one, + // with the limit lowered to nothing: only on their layer does it count. + for same_layer in [true, false] { + let mut s = session(); + let text = "First line\nSecond one"; + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap(); + let before = text_of(&s, id); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + if !same_layer { + // Area type below the Text Wrap object on the other layer: work there, none on this one. + s.execute("layer.new", &json!({})).unwrap(); + let other = s.execute("text.create", &json!({"x": 450, "y": 300, "text": "Other", "size": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("type.convertToAreaType", &json!({"ids": [other]})).unwrap(); + } + let rect = s.execute("shape.rectangle", &json!({"x": 500, "y": 330, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + super::WRAP_LIMIT.with(|c| c.set(0)); + let r = s.execute("type.retype", &json!({})); + super::WRAP_LIMIT.with(|c| c.set(super::MAX_WRAP_WORK)); + let r = r.unwrap(); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["area"], json!(!same_layer), "{same_layer}: {r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); + } +} + +#[test] +fn empty_subpaths_of_a_text_wrap_object_count_as_wrap_work() { + // Each one is copied into the wrap shapes of the area type below it. + let mut s = session(); + let t = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "Area", "size": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("type.convertToAreaType", &json!({"ids": [t]})).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap(); + let base = vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc); + let file_work = vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc); + s.edit("test", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(NodeId(rect)).unwrap().kind { + for _ in 0..100 { + path.subpaths.push(vectorcraft_geom::SubPath::new(vec![], true)); + } + } + Ok(()) + }) + .unwrap(); + assert!(vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc) >= base + 100); + // The count file import and the `.ai` editing copy use stays anchors and shapes only. + assert_eq!(vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc), file_work); +} + +#[test] +fn lines_under_a_text_wrap_object_stay_point_type() { + let mut s = session(); + let text = "First line\nSecond one"; + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap(); + let before = text_of(&s, id); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + // Above the outlines, over the end of both lines: area type would wrap round it. + let rect = s.execute("shape.rectangle", &json!({"x": 90, "y": 70, "width": 60, "height": 50})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["area"], json!(false), "{r}"); + let t = text_of(&s, r["ids"][0].as_u64().unwrap()); + assert!(matches!(t.kind, vectorcraft_doc::TextKind::Point)); + assert_same_places(&before, &t); +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index e9c316157f..b66a50bc19 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -634,34 +634,40 @@ fn to_area(s: &mut Session, p: &Value) -> Result { if !matches!(t.kind, TextKind::Point) { continue; } - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); - // The frame is worked out in line space, where the lines are; vertical type turns it - // into text space with the lines. - let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() }; - let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds); - // Across, the frame spans the lines as they are aligned: from their starts to their ends - // without the tracking after their last characters (`LineInfo::trailing`), not to the - // ink, which tracking can pull past an advance. Area type aligns them alike. - let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing))); - if x0.is_finite() && x1.is_finite() && x0 <= x1 { - (b.x0, b.x1) = (x0, x1); - } - // Line breaking counts that tracking: the slack holds the most of it. - let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max); - let size = t.first_style().size; - // A little slack on the right so the text doesn't rewrap. - let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0); - let slack = size * 0.5 + trailing; - let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack); - let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0))); - t.kind = TextKind::Area { frame: shapes::rectangle(frame) }; - refresh_bounds(t); + point_to_area(t); } Ok(()) })?; Ok(ids_json(&ids)) } +/// Point type `t` turned into area type in a frame around its lines, with a little slack where its +/// alignment leaves room, so the text stays where it is and does not rewrap. +pub(super) fn point_to_area(t: &mut TextObject) { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + // The frame is worked out in line space, where the lines are; vertical type turns it + // into text space with the lines. + let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() }; + let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds); + // Across, the frame spans the lines as they are aligned: from their starts to their ends + // without the tracking after their last characters (`LineInfo::trailing`), not to the + // ink, which tracking can pull past an advance. Area type aligns them alike. + let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing))); + if x0.is_finite() && x1.is_finite() && x0 <= x1 { + (b.x0, b.x1) = (x0, x1); + } + // Line breaking counts that tracking: the slack holds the most of it. + let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max); + let size = t.first_style().size; + // A little slack on the right so the text doesn't rewrap. + let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0); + let slack = size * 0.5 + trailing; + let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack); + let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0))); + t.kind = TextKind::Area { frame: shapes::rectangle(frame) }; + refresh_bounds(t); +} + /// How `slack` added to point type's lines in a frame is shared before and after them: where the /// alignment leaves room, so the text doesn't move or rewrap. fn slack_sides(justify: Justify, rtl: bool, slack: f64) -> (f64, f64) { diff --git a/docs/mcp.md b/docs/mcp.md index f0f035a261..b6295de9d9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12177,6 +12177,26 @@ tracking their own gaps give. These rules are VectorCraft's own. Each entry of t {"name":"run_command","arguments":{"command":"type.retype","params":{}}} ``` +## Retype several lines + +`type.retype` joins lines that follow each other in paint order, with the same group, paint, font, size, turn and +tracking (an untracked line of one or two glyphs takes the tracking of the others), into one type object when each +line's baseline is the same distance below the one before (between 0.25 and 3 times the size) and the lines line up at their starts, ends or centers. The object is area type with Convert To Area +Type's frame, its lines separated by line breaks, with left, right or center alignment, checked in that order. Its +leading is Auto when Auto puts the last baseline in place, else the mean distance between the baselines, to a +thousandth of a point when that still puts the last baseline in place. Lines with an opacity below 100%, a blend mode +other than Normal, a gradient or pattern fill, or a stroke stay one object per line. These rules are VectorCraft's own. + +Every joined object is laid out and compared with the outlines. When area type would not draw each glyph where its +outline was, including after Text Wrap objects above it reflow it, or when its frame would reach past the canvas's +coordinate limit, the lines become one multi-line point type object (one object per line when its bounds would reach +past that limit). When that also moves a glyph, the lines before that glyph's line stay one object, and the lines +from that line on are joined again from it. When the Text Wrap objects on the layers Retype changes would copy more +than 2,000,000 units into the wrap shapes of their area type (one for each anchor, subpath and shape, for each area +type object below them), Retype does not check the wrap and the lines become multi-line point type. Each entry of +the result's `texts` list holds an object's lines joined by `\n`, and each entry of its `fonts` list also has +`leading` (points; null for Auto leading or a single line) and `area`. + ## Retype panel `type.retypeFonts {count?}` lists the fonts whose glyphs match the selected outlined text. It compares each selected path diff --git a/docs/roadmap.md b/docs/roadmap.md index 488755ffef..8b9e0cfa0d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -181,7 +181,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; 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; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `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); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking; 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 | +| 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); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking and making stacked, aligned lines one area type object; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | 2–4 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f94e56c853..f1e15798ca 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3021,6 +3021,10 @@ The identify-fonts page has the Retype panel list ten matching fonts ordered by #4934 asks Retype to match the tracking of outlined text. `type.retype` now sets a line whose glyphs most gaps space evenly apart with that spacing as tracking, keeps gaps one space wide as word spaces when untracked type draws them, and sets negative tracking only on opaque, Normal lines with a solid fill or none and no stroke. These rules are VectorCraft's own. Each line is laid out and compared with the outlines before it is kept; a line its tracked type would move a glyph of is checked again untracked, and the glyphs after a split take the tracking their own gaps give. Tested by round trips through Create Outlines (a tracked line with a word space; uneven, tight and fractional tracking; kerned pairs in tight tracking; spaced letters that need no tracking; translucent overlapping glyphs) and by the measure's layout budget, in `crates/engine/src/cmd/retype_tests.rs`. +## Retype several lines (2026-11-19) + +#4934 asks for area text when outlined text has several lines, with its line spacing. `type.retype` now turns lines that follow each other, stack at one leading and line up at their starts, ends or centers into one area type object with that leading and left, right or center alignment. These rules are VectorCraft's own. Each object is laid out and compared with the outlines before it is kept; when area type would move a glyph, the lines become multi-line point type, and when that also would, the block ends at the line of that glyph and the lines after it join again. Tested by round trips through Create Outlines (three lines with Auto leading; set leading with left, center and right alignment; long blocks at leadings finer than a thousandth of a point; a line tracked apart from the others; tracked lines with word spaces; lines far apart or askew; a shape painted between two lines; translucent, blended, gradient and stroked lines; lines under a Text Wrap object) in `crates/engine/src/cmd/retype_tests.rs`. + ## Control bar: Paragraph section while type is selected (2026-11-06) With type selected, the Control bar shows a Paragraph: link and the Align left, Align center and Align right buttons after its Character controls, as the public documentation has the Control panel format paragraphs while the Type tool is in use, with a way to the Paragraph panel ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html)), and its alignment buttons align text as the Paragraph panel's do ([Align text](https://helpx.adobe.com/illustrator/using/align-text.html)). A button aligns the selected type (`text.setStyle {justify}`, one undo step) and the shared alignment shows selected; the link opens the Paragraph panel in a popover under it, as Character: opens the Character panel. Keeping to the three alignments that don't justify is our choice, for the bar's room; the popover has all seven. Short of room the bar leaves controls out from its right end: the inline X/Y/W/H fields, the Distribute and Align buttons, area type's vertical alignment, then these buttons and last the link, keeping room for the Transform link; on a 1536 pt bar with one point type object, the buttons show (pinned by a headless test, #5372). diff --git a/docs/type-parity.md b/docs/type-parity.md index 5e3a648745..111ee5d838 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into point text when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them; VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them), and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | 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 still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | From 7d44f644e83d1e7706d031a42b561acb2a5d76e2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 10:00:01 -0500 Subject: [PATCH 08/11] color: use shared craft-cms palette codecs with localized errors --- Cargo.lock | 10 + Cargo.toml | 1 + crates/color/Cargo.toml | 1 + crates/color/src/palette_io.rs | 531 ++++----------------------- crates/color/src/palette_io/tests.rs | 3 + 5 files changed, 91 insertions(+), 455 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 65cc426291..9acedd45bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1009,6 +1009,15 @@ dependencies = [ "ruzstd", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +dependencies = [ + "md-5", + "rayon", +] + [[package]] name = "craft-codepage" version = "0.1.0" @@ -6741,6 +6750,7 @@ dependencies = [ name = "vectorcraft-color" version = "0.24.1" dependencies = [ + "craft-cms", "kurbo 0.13.1", "moxcms", "proptest", diff --git a/Cargo.toml b/Cargo.toml index fea9cdda55..d60edf2af7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false, features = ["interpret", "write"] } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index a007ede39f..1273b5d0ad 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -9,6 +9,7 @@ description = "VectorCraft color" workspace = true [dependencies] +craft-cms = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index 9be00b4b21..b8019df4cc 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -6,6 +6,8 @@ use std::collections::{HashMap, HashSet}; +pub use craft_cms::palette::css_property; +use craft_cms::palette::{self as cms_palette, Palette, PaletteColor, PaletteError, PaletteGroup, PaletteSwatch}; use serde::{Deserialize, Serialize}; use crate::{Color, GradientKind, Paint, Swatch, SwatchGroup, SwatchLibrary}; @@ -83,18 +85,77 @@ struct NativeFile { const NATIVE_FORMAT: &str = "vcswatches"; const GPL_HEADER: &str = "GIMP Palette"; -const GPL_GROUP: &str = "# Group:"; const ASE_SIGNATURE: &[u8] = b"ASEF"; -const ASE_GROUP_START: u16 = 0xC001; -const ASE_GROUP_END: u16 = 0xC002; -const ASE_COLOR: u16 = 0x0001; -/// The most colors and groups read from one `.ase` file. -const ASE_MAX_ENTRIES: usize = 100_000; -/// The most UTF-16 code units of a name that are kept. -const ASE_MAX_NAME: usize = 1024; -const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short"; const ACB_SIGNATURE: &[u8] = b"8BCB"; -const ACB_CUT_SHORT: &str = "the color book is cut short"; +#[cfg(test)] +const ASE_GROUP_START: u16 = 0xC001; +#[cfg(test)] +const ASE_MAX_ENTRIES: usize = 100_000; + +fn color_to_cms(c: Color) -> PaletteColor { + match c { + Color::Rgb { r, g, b } => PaletteColor::Rgb { r, g, b }, + Color::Cmyk { c, m, y, k } => PaletteColor::Cmyk { c, m, y, k }, + Color::Lab { l, a, b } => PaletteColor::Lab { l, a, b }, + Color::Gray { k } => PaletteColor::Gray { k }, + } +} + +fn color_from_cms(c: PaletteColor) -> Color { + match c { + PaletteColor::Rgb { r, g, b } => Color::rgb(r, g, b), + PaletteColor::Cmyk { c, m, y, k } => Color::cmyk(c, m, y, k), + PaletteColor::Lab { l, a, b } => Color::lab(l, a, b), + PaletteColor::Gray { k } => Color::gray(k), + } +} + +fn swatches_to_cms(list: &[Swatch]) -> Vec { + list.iter() + .filter_map(|w| w.paint.color().map(|c| PaletteSwatch { name: w.name.clone(), color: color_to_cms(c), global: w.global, spot: w.spot })) + .collect() +} + +fn swatches_from_cms(list: Vec) -> Vec { + list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect() +} + +fn to_cms_palette(lib: &SwatchLibrary) -> Palette { + Palette { + name: lib.name.clone(), + swatches: swatches_to_cms(&lib.swatches), + groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches) }).collect(), + } +} + +fn from_cms_palette(p: Palette) -> SwatchLibrary { + SwatchLibrary { + name: p.name, + swatches: swatches_from_cms(p.swatches), + groups: p.groups.into_iter().map(|g| SwatchGroup { name: g.name, swatches: swatches_from_cms(g.swatches) }).collect(), + } +} + +/// Maps structured shared palette errors to VectorCraft's translatable messages. +fn palette_error(err: PaletteError) -> String { + match err { + PaletteError::UnsupportedFormat => "not a supported palette (.gpl, .ase, or .acb)".into(), + PaletteError::TruncatedAse => "the swatch exchange file is cut short".into(), + PaletteError::TruncatedAcb => "the color book is cut short".into(), + PaletteError::AseWriteEntryLimit { limit, entries } => { + format!("VectorCraft reads at most {limit} colors and groups from a swatch exchange file, and this library has {entries}") + } + PaletteError::AseReadEntryLimit { limit } => format!("the swatch exchange file holds more than {limit} colors and groups"), + PaletteError::AseBlockCount => "too many swatch exchange blocks".into(), + PaletteError::AseBlockLength => "a swatch exchange block is too long".into(), + PaletteError::AseNameLength => "a swatch exchange name is too long".into(), + PaletteError::AseVersion { major, minor } => format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"), + PaletteError::AcbVersion { version } => format!("color book version {version} isn't supported (only 1)"), + PaletteError::AcbEntryLimit { limit } => format!("the color book holds more than {limit} colors"), + PaletteError::AcbColorSpace { space } => format!("color books in color space {space} aren't supported (only RGB, CMYK and Lab)"), + PaletteError::AcbNameBytes { limit } => format!("the color book's names take more than {} MB", limit >> 20), + } +} /// Write `lib` in `format` → the file's bytes. Pattern swatches (their tiles live in a document) /// and None are left out; `.gpl` keeps solid colours only, as 8-bit RGB, and `.ase` keeps solid @@ -113,8 +174,8 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri let file = NativeFile { format: NATIVE_FORMAT.into(), version: 1, library }; serde_json::to_string_pretty(&file).unwrap_or_default() } - PaletteFormat::Gpl => write_gpl(lib), - PaletteFormat::Ase => return write_ase(lib), + PaletteFormat::Gpl => return cms_palette::write_palette_typed(&to_cms_palette(lib), cms_palette::PaletteFormat::Gpl).map_err(palette_error), + PaletteFormat::Ase => return cms_palette::write_palette_typed(&to_cms_palette(lib), cms_palette::PaletteFormat::Ase).map_err(palette_error), PaletteFormat::Css => write_css(lib, keep), }; Ok(text.into_bytes()) @@ -125,49 +186,6 @@ fn one_line(s: &str) -> String { s.split(['\n', '\r', '\t']).collect::>().join(" ").trim().to_string() } -fn write_gpl(lib: &SwatchLibrary) -> String { - let mut out = format!("{GPL_HEADER}\nName: {}\nColumns: 0\n#\n", one_line(&lib.name)); - let colors = |out: &mut String, list: &[Swatch]| { - for w in list { - if let Some(c) = w.paint.color() { - let [r, g, b, _] = c.to_rgba8(1.0); - out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(&w.name))); - } - } - }; - colors(&mut out, &lib.swatches); - for g in &lib.groups { - out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&g.name))); - colors(&mut out, &g.swatches); - } - out -} - -/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as -/// hyphens, other characters an identifier can't hold escaped with a backslash. -pub fn css_property(name: &str) -> String { - let mut out = String::from("--"); - for word in name.split_whitespace() { - if out.len() > 2 { - out.push('-'); - } - for ch in word.chars().flat_map(char::to_lowercase) { - if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() { - out.push(ch); - } else if ch.is_ascii_graphic() { - out.push('\\'); - out.push(ch); - } else { - out.push_str(&format!("\\{:x} ", ch as u32)); - } - } - } - if out.len() == 2 { - out.push_str("swatch"); - } - out -} - /// A colour as CSS (`#rrggbb`, or `#rrggbbaa` below full opacity). fn css_color(c: &Color, opacity: f32) -> String { let [r, g, b, a] = c.to_rgba8(opacity); @@ -265,108 +283,12 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String { out } -/// `.ase`, as [`read_ase`] reads it: version 1.0, the ungrouped colors, then each color group as a -/// group start (its name), its colors and a group end, also for a group without colors. A color is -/// written in its own model: RGB, CMYK and gray components from 0 to 1 (gray as a level, 1 is -/// white), Lab lightness as a fraction of 100 and a and b from −128 to 127. Components are clamped -/// to those ranges, and a component that isn't a finite number is written as 0. The color type is -/// 1 for a spot color, 0 for another global color and 2 for a process color. -/// -/// A swatch exchange file holds solid colors only: gradients, patterns and None are left out, and -/// a tint swatch is written as the color it shows, a process color without its link to its base. -/// The file has no library name ([`read_ase`] names a library after its file). More than -/// [`ASE_MAX_ENTRIES`] colors and groups is an error. -fn write_ase(lib: &SwatchLibrary) -> Result, String> { - let solid = |list: &[Swatch]| list.iter().filter(|w| w.paint.color().is_some()).count(); - let entries = solid(&lib.swatches) + lib.groups.iter().map(|g| 1 + solid(&g.swatches)).sum::(); - if entries > ASE_MAX_ENTRIES { - return Err(format!( - "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}" - )); - } - let mut body = vec![]; - let mut blocks = put_ase_colors(&mut body, &lib.swatches)?; - for g in &lib.groups { - let mut name = vec![]; - put_ase_name(&mut name, &g.name)?; - put_ase_block(&mut body, ASE_GROUP_START, &name)?; - blocks += 2 + put_ase_colors(&mut body, &g.swatches)?; - put_ase_block(&mut body, ASE_GROUP_END, &[])?; - } - let blocks = u32::try_from(blocks).map_err(|_| "too many swatch exchange blocks".to_string())?; - let mut out = ASE_SIGNATURE.to_vec(); - out.extend(1u16.to_be_bytes()); - out.extend(0u16.to_be_bytes()); - out.extend(blocks.to_be_bytes()); - out.extend(body); - Ok(out) -} - -/// The color blocks of the solid colors in `list` → how many were written. -fn put_ase_colors(out: &mut Vec, list: &[Swatch]) -> Result { - let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 }; - let mut n = 0; - for (w, color) in list.iter().filter_map(|w| Some((w, w.paint.color()?))) { - let mut body = vec![]; - put_ase_name(&mut body, &w.name)?; - let (model, values): (&[u8; 4], Vec) = match color { - Color::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]), - Color::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]), - Color::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]), - Color::Gray { k } => (b"Gray", vec![1.0 - unit(k)]), - }; - body.extend(model); - body.extend(values.iter().flat_map(|v| v.to_be_bytes())); - let kind: u16 = if w.spot { - 1 - } else if w.global { - 0 - } else { - 2 - }; - body.extend(kind.to_be_bytes()); - put_ase_block(out, ASE_COLOR, &body)?; - n += 1; - } - Ok(n) -} - -/// A block: its type, the length of its body and the body. -fn put_ase_block(out: &mut Vec, kind: u16, body: &[u8]) -> Result<(), String> { - let len = u32::try_from(body.len()).map_err(|_| "a swatch exchange block is too long".to_string())?; - out.extend(kind.to_be_bytes()); - out.extend(len.to_be_bytes()); - out.extend_from_slice(body); - Ok(()) -} - -/// A name as `.ase` stores it: a `u16` count of UTF-16 code units, the terminating zero included, -/// then the units. NUL characters are left out, and a name longer than [`ASE_MAX_NAME`] code units -/// is cut before the character that would pass that limit. -fn put_ase_name(out: &mut Vec, name: &str) -> Result<(), String> { - let mut units: Vec = vec![]; - for c in name.chars().filter(|&c| c != '\0') { - let mut buf = [0; 2]; - let encoded = c.encode_utf16(&mut buf); - if units.len() + encoded.len() > ASE_MAX_NAME { - break; - } - units.extend_from_slice(encoded); - } - units.push(0); - let count = u16::try_from(units.len()).map_err(|_| "a swatch exchange name is too long".to_string())?; - out.extend(count.to_be_bytes()); - out.extend(units.iter().flat_map(|u| u.to_be_bytes())); - Ok(()) -} - /// Read a `.vcswatches` or `.gpl` library (detected from its content). `name` names it when the /// file doesn't. pub fn read(text: &str, name: &str) -> Result { let text = text.trim_start_matches('\u{feff}').trim_start(); if text.starts_with(GPL_HEADER) { - return Ok(read_gpl(text, name)); + return cms_palette::read_palette_typed(text.as_bytes(), name).map(from_cms_palette).map_err(palette_error); } if text.starts_with('{') { let f: NativeFile = serde_json::from_str(text).map_err(|e| format!("not a swatch library: {e}"))?; @@ -391,11 +313,8 @@ pub fn sniff(text: &str) -> bool { /// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or /// `.gpl` library ([`read`]). `name` names it when the file doesn't. pub fn read_bytes(bytes: &[u8], name: &str) -> Result { - if bytes.starts_with(ASE_SIGNATURE) { - return read_ase(bytes, name); - } - if bytes.starts_with(ACB_SIGNATURE) { - return read_acb(bytes, name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e }); + if bytes.starts_with(ASE_SIGNATURE) || bytes.starts_with(ACB_SIGNATURE) { + return cms_palette::read_palette_typed(bytes, name).map(from_cms_palette).map_err(palette_error); } read(&String::from_utf8_lossy(bytes), name) } @@ -409,303 +328,5 @@ pub fn sniff_bytes(bytes: &[u8]) -> bool { || sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes))) } -/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and -/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are -/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets -/// a number ([`UniqueNames`]). -fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary { - let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; - let mut names = UniqueNames::default(); - for line in text.lines().skip(1) { - let line = line.trim(); - if let Some(g) = line.strip_prefix(GPL_GROUP) { - lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] }); - continue; - } - if let Some(n) = line.strip_prefix("Name:") { - if !n.trim().is_empty() { - lib.name = n.trim().to_string(); - } - continue; - } - // Comments, headers (`Columns: 4`) and anything else that isn't a colour are skipped. - let words: Vec<&str> = line.split_whitespace().collect(); - let rgb: Vec = words.iter().take(3).map_while(|v| v.parse().ok()).collect(); - let [r, g, b] = rgb[..] else { continue }; - let rest = words[3..].join(" "); - let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest }; - let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false }; - match lib.groups.last_mut() { - Some(grp) => grp.swatches.push(w), - None => lib.swatches.push(w), - } - } - lib -} - -/// `.ase`, from public descriptions of the format: the layout from -/// , the component ranges from -/// . After the signature come, big-endian, a `u16` major (1) and -/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and -/// the body. A group start's body is a name. A color's body is a name, a four-character model -/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16` -/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a -/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness -/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero -/// included, then the units. -/// -/// Color groups become groups: a group start inside an open group ends that group, and a group -/// left open ends with the file. Blocks of other types and colors in other models are skipped. -/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or -/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than -/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error. -fn read_ase(bytes: &[u8], fallback: &str) -> Result { - let mut data = AseData(bytes); - data.bytes(ASE_SIGNATURE.len())?; - let (major, minor) = (data.u16()?, data.u16()?); - if major != 1 { - return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)")); - } - let blocks = data.u32()?; - let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; - let mut names = UniqueNames::default(); - let (mut in_group, mut entries) = (false, 0usize); - for _ in 0..blocks { - let kind = data.u16()?; - let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX); - let mut body = AseData(data.bytes(len)?); - if matches!(kind, ASE_GROUP_START | ASE_COLOR) { - entries += 1; - if entries > ASE_MAX_ENTRIES { - return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups")); - } - } - match kind { - ASE_GROUP_START => { - lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] }); - in_group = true; - } - ASE_GROUP_END => in_group = false, - ASE_COLOR => { - let Some(mut w) = ase_swatch(&mut body)? else { continue }; - w.name = names.unique(std::mem::take(&mut w.name)); - match lib.groups.last_mut().filter(|_| in_group) { - Some(g) => g.swatches.push(w), - None => lib.swatches.push(w), - } - } - // Other blocks are skipped. - _ => {} - } - } - Ok(lib) -} - -/// `.acb` (a color book, read only), from public descriptions of the format: after the signature -/// come, big-endian, a `u16` version (1) and book id, the title, prefix, suffix and description -/// as strings, a `u16` color count, page size and page selector offset, a `u16` color space (0 -/// RGB, 2 CMYK, 7 Lab) and the colors: each a name, a six-character catalog code and its -/// components as bytes. RGB runs from 0 to 255, CMYK ink is stored inverted (255 is no ink), Lab -/// lightness is 0 to 255 for 0 to 100 and a and b are offset by 128. A string is a `u32` count of -/// UTF-16 code units, then the units; a `$$$/key=Text` string means `Text`, and `^R`, `^C` stand -/// for ® and ©. An optional `spflspot` or `spflproc` at the end says whether the colors are spot -/// or process colors (a book without it is a spot color book). -/// -/// The book's colors are named with its prefix and suffix ("PANTONE 185 C"); colors without a -/// name (the padding of a book's pages) are left out. A version other than 1, a color space other -/// than those three or more than [`ASE_MAX_ENTRIES`] colors is an error. -fn read_acb(bytes: &[u8], fallback: &str) -> Result { - let mut data = AseData(bytes); - data.bytes(ACB_SIGNATURE.len())?; - let version = data.u16()?; - if version != 1 { - return Err(format!("color book version {version} isn't supported (only 1)")); - } - let _book_id = data.u16()?; - let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?]; - let count = usize::from(data.u16()?); - if count > ASE_MAX_ENTRIES { - return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors")); - } - let (_page_size, _page_offset) = (data.u16()?, data.u16()?); - let space = data.u16()?; - let mut colors = Vec::with_capacity(count); - for _ in 0..count { - let name = data.acb_string()?; - let _code = data.bytes(6)?; - let color = match space { - 0 => { - let [r, g, b] = data.array::<3>()?; - Color::rgb8(r, g, b) - } - 2 => { - let ink = |v: u8| f32::from(255 - v) / 255.0; - let [c, m, y, k] = data.array::<4>()?; - Color::cmyk(ink(c), ink(m), ink(y), ink(k)) - } - 7 => { - let [l, a, b] = data.array::<3>()?; - Color::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0) - } - other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")), - }; - colors.push((name, color)); - } - // Spot colors unless the book says process ones. - let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice()); - let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() }; - let mut names = UniqueNames::default(); - // Every name gets the prefix and the suffix, and is kept twice (the swatch's and the set of - // names taken): a megabyte book of long affixes and many colors came to hundreds of MB. - let mut kept = 0usize; - for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) { - kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len())); - if kept > ACB_MAX_NAME_BYTES { - return Err(format!("the color book's names take more than {} MB", ACB_MAX_NAME_BYTES >> 20)); - } - let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string()); - lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot }); - } - Ok(lib) -} - -/// Most bytes a color book's full color names (with its prefix and suffix) may take, counted -/// twice as they are kept twice. -const ACB_MAX_NAME_BYTES: usize = 64 << 20; - -/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray. -/// Components are clamped to their ranges. -fn ase_swatch(body: &mut AseData) -> Result, String> { - let name = body.name()?; - let unit = |v: f32| v.clamp(0.0, 1.0); - let color = match &body.array::<4>()? { - b"RGB " => { - let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?]; - Color::rgb(unit(r), unit(g), unit(b)) - } - b"CMYK" => { - let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?]; - Color::cmyk(unit(c), unit(m), unit(y), unit(k)) - } - // Lightness is stored as a fraction of 100. Some writers store L* itself, which shows as a - // value above 1. - b"LAB " => { - let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?]; - let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 }; - Color::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0)) - } - // A gray level (1 is white); a gray color holds its ink. - b"Gray" => Color::gray(1.0 - unit(body.f32()?)), - _ => return Ok(None), - }; - // Some writers leave the color type out, which makes a process color. - let kind = if body.0.len() >= 2 { body.u16()? } else { 2 }; - // Spot colors are global. - let (global, spot) = match kind { - 0 => (true, false), - 1 => (true, true), - _ => (false, false), - }; - let name = if name.is_empty() { value_name(color) } else { name }; - Ok(Some(Swatch { name, paint: Paint::solid(color), global, spot })) -} - -/// A color's values in its own model, as new swatches are named ("C=10 M=20 Y=30 K=0", -/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30"). -fn value_name(c: Color) -> String { - let pct = |v: f32| (v * 100.0).round(); - let byte = |v: f32| (v * 255.0).round(); - match c { - Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)), - Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)), - Color::Gray { k } => format!("Gray K={}", pct(k)), - // `+ 0.0` turns a rounded -0 into 0. - Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0), - } -} - -/// `.ase` data, read field by field; reading past its end is an error. -struct AseData<'a>(&'a [u8]); - -impl<'a> AseData<'a> { - fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> { - let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?; - self.0 = rest; - Ok(head) - } - fn array(&mut self) -> Result<[u8; N], String> { - let (head, rest) = self.0.split_first_chunk::().ok_or(ASE_CUT_SHORT)?; - self.0 = rest; - Ok(*head) - } - fn u16(&mut self) -> Result { - self.array().map(u16::from_be_bytes) - } - fn u32(&mut self) -> Result { - self.array().map(u32::from_be_bytes) - } - /// A component; one that isn't a finite number reads as 0. - fn f32(&mut self) -> Result { - let v = f32::from_be_bytes(self.array()?); - Ok(if v.is_finite() { v } else { 0.0 }) - } - /// A color book string ([`read_acb`]): a `u32` count of UTF-16 code units, then the units, - /// with `$$$/key=Text` read as `Text` and `^R`, `^C` as ®, ©; at most [`ASE_MAX_NAME`] units - /// are kept. - fn acb_string(&mut self) -> Result { - let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX); - let (units, _) = self.bytes(n.checked_mul(2).ok_or(ASE_CUT_SHORT)?)?.as_chunks::<2>(); - let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); - let s = String::from_utf16_lossy(&units); - let s = match s.strip_prefix("$$$/") { - Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(), - None => s, - }; - Ok(s.replace("^R", "®").replace("^C", "©")) - } - /// A name up to its terminating zero, trimmed. A block that ends before it has no name. - fn name(&mut self) -> Result { - if self.0.is_empty() { - return Ok(String::new()); - } - let n = usize::from(self.u16()?); - let (units, _) = self.bytes(n * 2)?.as_chunks::<2>(); - let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); - Ok(String::from_utf16_lossy(&units).trim().to_string()) - } -} - -/// A group's name as a file gives it, trimmed; "Color Group" when it has none. -fn group_name(name: &str) -> String { - let name = name.trim(); - if name.is_empty() { "Color Group".into() } else { name.to_string() } -} - -/// The swatch and group names a reader has handed out. Swatches and color groups share one set of -/// names, as in a document, and a name already taken gets the first free number ("Black 2"). -#[derive(Default)] -struct UniqueNames { - taken: HashSet, - /// The last number tried for each repeated name. - last: HashMap, -} - -impl UniqueNames { - fn unique(&mut self, base: String) -> String { - if self.taken.insert(base.clone()) { - return base; - } - // Each pass tries the next number, and only finitely many names are taken. - let n = self.last.entry(base.clone()).or_insert(1); - loop { - *n += 1; - let name = format!("{base} {n}"); - if self.taken.insert(name.clone()) { - return name; - } - } - } -} - #[cfg(test)] mod tests; diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index bbbae16a53..b53a50addb 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -2,6 +2,9 @@ use super::*; use crate::{Gradient, GradientPaint, GradientStop}; use proptest::prelude::*; +const ASE_COLOR: u16 = 0x0001; +const ASE_GROUP_END: u16 = 0xC002; + #[test] fn gpl_blank_name_keeps_fallback() { let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n"; From 75813b3be880e91df3e98807d68520a67b9699c1 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 19 Nov 2026 17:09:28 +0100 Subject: [PATCH 09/11] fix: preserve palette color conversion and localization keys --- crates/color/src/palette_io.rs | 44 ++++++++++++++++++------- crates/color/src/palette_io/tests.rs | 49 ++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 12 deletions(-) diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index b8019df4cc..c14075bd2e 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -110,9 +110,22 @@ fn color_from_cms(c: PaletteColor) -> Color { } } -fn swatches_to_cms(list: &[Swatch]) -> Vec { +// GPL must retain the app-managed display conversion; ASE preserves authoring models. +fn swatches_to_cms(list: &[Swatch], rgb_only: bool) -> Vec { list.iter() - .filter_map(|w| w.paint.color().map(|c| PaletteSwatch { name: w.name.clone(), color: color_to_cms(c), global: w.global, spot: w.spot })) + .filter_map(|w| { + w.paint.color().map(|c| PaletteSwatch { + name: w.name.clone(), + color: if rgb_only { + let [r, g, b, _] = c.to_rgba8(1.0); + PaletteColor::rgb8(r, g, b) + } else { + color_to_cms(c) + }, + global: w.global, + spot: w.spot, + }) + }) .collect() } @@ -120,11 +133,11 @@ fn swatches_from_cms(list: Vec) -> Vec { list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect() } -fn to_cms_palette(lib: &SwatchLibrary) -> Palette { +fn to_cms_palette(lib: &SwatchLibrary, rgb_only: bool) -> Palette { Palette { name: lib.name.clone(), - swatches: swatches_to_cms(&lib.swatches), - groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches) }).collect(), + swatches: swatches_to_cms(&lib.swatches, rgb_only), + groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches, rgb_only) }).collect(), } } @@ -142,17 +155,20 @@ fn palette_error(err: PaletteError) -> String { PaletteError::UnsupportedFormat => "not a supported palette (.gpl, .ase, or .acb)".into(), PaletteError::TruncatedAse => "the swatch exchange file is cut short".into(), PaletteError::TruncatedAcb => "the color book is cut short".into(), - PaletteError::AseWriteEntryLimit { limit, entries } => { - format!("VectorCraft reads at most {limit} colors and groups from a swatch exchange file, and this library has {entries}") + PaletteError::AseWriteEntryLimit { limit, entries } => format!( + "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}", + ASE_MAX_ENTRIES = limit + ), + PaletteError::AseReadEntryLimit { limit } => { + format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups", ASE_MAX_ENTRIES = limit) } - PaletteError::AseReadEntryLimit { limit } => format!("the swatch exchange file holds more than {limit} colors and groups"), PaletteError::AseBlockCount => "too many swatch exchange blocks".into(), PaletteError::AseBlockLength => "a swatch exchange block is too long".into(), PaletteError::AseNameLength => "a swatch exchange name is too long".into(), PaletteError::AseVersion { major, minor } => format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"), PaletteError::AcbVersion { version } => format!("color book version {version} isn't supported (only 1)"), - PaletteError::AcbEntryLimit { limit } => format!("the color book holds more than {limit} colors"), - PaletteError::AcbColorSpace { space } => format!("color books in color space {space} aren't supported (only RGB, CMYK and Lab)"), + PaletteError::AcbEntryLimit { limit } => format!("the color book holds more than {ASE_MAX_ENTRIES} colors", ASE_MAX_ENTRIES = limit), + PaletteError::AcbColorSpace { space: other } => format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)"), PaletteError::AcbNameBytes { limit } => format!("the color book's names take more than {} MB", limit >> 20), } } @@ -174,8 +190,12 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri let file = NativeFile { format: NATIVE_FORMAT.into(), version: 1, library }; serde_json::to_string_pretty(&file).unwrap_or_default() } - PaletteFormat::Gpl => return cms_palette::write_palette_typed(&to_cms_palette(lib), cms_palette::PaletteFormat::Gpl).map_err(palette_error), - PaletteFormat::Ase => return cms_palette::write_palette_typed(&to_cms_palette(lib), cms_palette::PaletteFormat::Ase).map_err(palette_error), + PaletteFormat::Gpl => { + return cms_palette::write_palette_typed(&to_cms_palette(lib, true), cms_palette::PaletteFormat::Gpl).map_err(palette_error); + } + PaletteFormat::Ase => { + return cms_palette::write_palette_typed(&to_cms_palette(lib, false), cms_palette::PaletteFormat::Ase).map_err(palette_error); + } PaletteFormat::Css => write_css(lib, keep), }; Ok(text.into_bytes()) diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index b53a50addb..b0036b6fc6 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -703,3 +703,52 @@ proptest! { } } } + +#[test] +fn shared_gpl_adapter_uses_app_color_conversion() { + let colors = [Color::cmyk(0.2, 0.4, 0.6, 0.1), Color::lab(55.0, 30.0, -25.0), Color::gray(0.3)]; + let lib = SwatchLibrary { + name: "Managed".into(), + swatches: colors + .iter() + .enumerate() + .map(|(i, &color)| Swatch { name: format!("Color {i}"), paint: Paint::solid(color), global: false, spot: false }) + .collect(), + groups: vec![], + }; + let mut expected = String::from("GIMP Palette\nName: Managed\nColumns: 0\n#\n"); + for (i, color) in colors.iter().enumerate() { + let [r, g, b, _] = color.to_rgba8(1.0); + expected.push_str(&format!("{r:3} {g:3} {b:3}\tColor {i}\n")); + } + assert_eq!(write(&lib, PaletteFormat::Gpl).unwrap(), expected.as_bytes()); + assert!(to_cms_palette(&lib, true).swatches.iter().all(|w| matches!(w.color, PaletteColor::Rgb { .. }))); + assert!(matches!(to_cms_palette(&lib, false).swatches[0].color, PaletteColor::Cmyk { .. })); + assert!(matches!(to_cms_palette(&lib, false).swatches[1].color, PaletteColor::Lab { .. })); +} + +#[test] +fn typed_palette_errors_keep_app_wording() { + let cases = [ + (PaletteError::UnsupportedFormat, "not a supported palette (.gpl, .ase, or .acb)"), + (PaletteError::TruncatedAse, "the swatch exchange file is cut short"), + (PaletteError::TruncatedAcb, "the color book is cut short"), + ( + PaletteError::AseWriteEntryLimit { limit: 3, entries: 4 }, + "VectorCraft reads at most 3 colors and groups from a swatch exchange file, and this library has 4", + ), + (PaletteError::AseReadEntryLimit { limit: 3 }, "the swatch exchange file holds more than 3 colors and groups"), + (PaletteError::AseBlockCount, "too many swatch exchange blocks"), + (PaletteError::AseBlockLength, "a swatch exchange block is too long"), + (PaletteError::AseNameLength, "a swatch exchange name is too long"), + (PaletteError::AseVersion { major: 2, minor: 3 }, "swatch exchange version 2.3 isn't supported (only 1.x)"), + (PaletteError::AcbVersion { version: 2 }, "color book version 2 isn't supported (only 1)"), + (PaletteError::AcbEntryLimit { limit: 3 }, "the color book holds more than 3 colors"), + (PaletteError::AcbColorSpace { space: 5 }, "color books in color space 5 aren't supported (only RGB, CMYK and Lab)"), + (PaletteError::AcbNameBytes { limit: 64 << 20 }, "the color book's names take more than 64 MB"), + ]; + for (error, expected) in cases { + assert_eq!(palette_error(error), expected); + } + assert_eq!(read_bytes(b"8BCB\0\x01\0\0\0\0\0\x03\0x", "fallback").unwrap_err(), "the color book is cut short"); +} From 25dd02aa956227c52ae2df019af6142949c3c11b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 20 Nov 2026 02:20:47 +0700 Subject: [PATCH 10/11] Brushes test: open a library and pick a brush through one helper, so the panel test stays under the complexity limit --- .../src/panels/tests_brush_libraries.rs | 39 +++++++------------ 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index b3bde5b075..85e41c1894 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -63,6 +63,17 @@ fn undo_len(app: &VectorcraftApp) -> usize { app.session.doc().unwrap().history.undo.len() } +/// Opens `library` (id `id`, with `count` brushes) and clicks its brush `name` at `time`: that brush, +/// and not the library's `other` one, is added to the document in one step. +fn pick(app: &mut VectorcraftApp, ctx: &egui::Context, (library, id, count): (&str, &str, u64), (name, other): (&str, &str), time: f64) { + let r = app.run("window.brushLibrary", json!({"library": library})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some(id), Some(count))); + let undo = undo_len(app); + click(app, ctx, name, Modifiers::NONE, time); + assert!(has(app, name) && !has(app, other), "{name}"); + assert_eq!(undo_len(app), undo + 1); +} + fn has(app: &VectorcraftApp, name: &str) -> bool { vectorcraft_brush::find(&app.session.doc().unwrap().doc, name).is_some() } @@ -228,18 +239,8 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { assert!(texts.iter().any(|x| x.ends_with(t)), "{t}: {texts:?}"); } // Dry Media opens in a library panel, and a click on Chalk Grain adds it in one step. - let r = app.run("window.brushLibrary", json!({"library": "Dry Media"})).unwrap(); - assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("dry-media"), Some(4))); - let undo = undo_len(&app); - click(&mut app, &ctx, "Chalk Grain", Modifiers::NONE, 1.0); - assert!(has(&app, "Chalk Grain") && !has(&app, "Wax Crayon")); - assert_eq!(undo_len(&app), undo + 1); - let r = app.run("window.brushLibrary", json!({"library": "Tech Circuit"})).unwrap(); - assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("tech-circuit"), Some(3))); - let undo = undo_len(&app); - click(&mut app, &ctx, "Circuit Trace", Modifiers::NONE, 2.0); - assert!(has(&app, "Circuit Trace") && !has(&app, "Bus Lines")); - assert_eq!(undo_len(&app), undo + 1); + pick(&mut app, &ctx, ("Dry Media", "dry-media", 4), ("Chalk Grain", "Wax Crayon"), 1.0); + pick(&mut app, &ctx, ("Tech Circuit", "tech-circuit", 3), ("Circuit Trace", "Bus Lines"), 2.0); let r = app.run("window.brushLibrary", json!({"library": "Artistic Brushes"})).unwrap(); assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("artistic"), Some(4))); let previous = crate::i18n::current(); @@ -250,12 +251,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { click(&mut app, &ctx, "Orbit Lines", Modifiers::NONE, 3.0); assert!(has(&app, "Orbit Lines") && !has(&app, "Facet Sweep")); assert_eq!(undo_len(&app), undo + 1); - let r = app.run("window.brushLibrary", json!({"library": "Vector Packs"})).unwrap(); - assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("vector-packs"), Some(4))); - let undo = undo_len(&app); - click(&mut app, &ctx, "Compass Rose", Modifiers::NONE, 4.0); - assert!(has(&app, "Compass Rose") && !has(&app, "Facet Diamond")); - assert_eq!(undo_len(&app), undo + 1); + pick(&mut app, &ctx, ("Vector Packs", "vector-packs", 4), ("Compass Rose", "Facet Diamond"), 4.0); let r = app.run("window.brushLibrary", json!({"library": "Pressure Sensitive"})).unwrap(); assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("pressure-sensitive"), Some(4))); let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap(); @@ -278,12 +274,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some("Flat Sweep") ); - let r = app.run("window.brushLibrary", json!({"library": "Image Brush"})).unwrap(); - assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("image-brush"), Some(4))); - let undo = undo_len(&app); - click(&mut app, &ctx, "Soft Bloom", Modifiers::NONE, 7.0); - assert!(has(&app, "Soft Bloom") && !has(&app, "Color Flecks")); - assert_eq!(undo_len(&app), undo + 1); + pick(&mut app, &ctx, ("Image Brush", "image-brush", 4), ("Soft Bloom", "Color Flecks"), 7.0); // Without brushes there is nothing to save. let all: Vec = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect(); app.run("brush.delete", json!({ "names": all })).unwrap(); From 1800ca69497e9f08de780bfd75bb8a520ac7440b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 12:33:02 -0800 Subject: [PATCH 11/11] Retype: a pair of lines' glyphs takes the tracking of the lines around it, and a wrap object below all area type makes no outline A leading of exactly a quarter of the size joins lines. --- crates/doc/src/text/tests.rs | 28 +++++++++++++++++++++++ crates/doc/src/text/wrap.rs | 14 +++++++++++- crates/engine/src/cmd/retype.rs | 32 +++++++++++++++++++++++++-- crates/engine/src/cmd/retype_tests.rs | 22 ++++++++++++++++++ 4 files changed, 93 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 63b763423d..1a3229138e 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -669,6 +669,34 @@ fn area_type() -> TextObject { t } +#[test] +fn a_wrap_object_below_every_area_type_object_makes_no_outline() { + use crate::{Appearance, Document, Node, NodeKind}; + let mut d = Document::new(300.0, 300.0); + let l = d.layers[0].id; + let wrap = |d: &mut Document, r: Rect| { + let id = d.alloc_id(); + let mut n = Node::path(id, vectorcraft_geom::shapes::rectangle(r), Appearance::default_art()); + n.extras_mut().wrap = Some(TextWrap::default()); + n + }; + // Bottom to top: a wrap object, the area type, then a wrap object. + let below = wrap(&mut d, Rect::new(0.0, 0.0, 250.0, 250.0)); + d.insert(Some(l), 9, below).unwrap(); + let id = d.alloc_id(); + d.insert(Some(l), 9, Node::new(id, NodeKind::Text(Box::new(area_type())))).unwrap(); + let above = wrap(&mut d, Rect::new(60.0, 40.0, 80.0, 60.0)); + d.insert(Some(l), 9, above).unwrap(); + wrap::OUTLINES_MADE.with(|c| c.set(0)); + let mut sources = 0; + wrap_sources(&d, |_, objects, shapes| { + sources += 1; + assert_eq!((objects.len(), shapes.len()), (1, 1)); + }); + assert_eq!(sources, 1); + assert_eq!(wrap::OUTLINES_MADE.with(|c| c.get()), 1, "only the wrap object above the type is outlined"); +} + #[test] fn area_resizes_its_frame_and_keeps_its_type() { let mut t = area_type(); diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index c55a973be0..33fdcb4687 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -7,6 +7,12 @@ use vectorcraft_geom::{PathData, shapes}; use super::{TextKind, TextObject, WrapShape}; use crate::{Document, Node, NodeId, NodeKind}; +#[cfg(test)] +thread_local! { + /// How many wrap outlines [`each_text`] has made on this thread (for tests). + pub(super) static OUTLINES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Outline of a wrap object in document coordinates: its paths, or its bounds for other art. fn outline(n: &Node, out: &mut PathData) { match &n.kind { @@ -133,9 +139,15 @@ fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapS let mut items = vec![]; collect(layer, &mut items); let mut above: Vec<(&Node, WrapShape)> = vec![]; - for it in items.iter().rev() { + // A wrap object below every area text object of the layer wraps none of them: its outline is + // not made. + let first_text = items.iter().position(|it| matches!(it, Item::Text(_))); + for (i, it) in items.iter().enumerate().rev() { match it { + Item::Wrap(_) if first_text.is_none_or(|t| i < t) => {} Item::Wrap(n) => { + #[cfg(test)] + OUTLINES_MADE.with(|c| c.set(c.get() + 1)); let mut pd = PathData::default(); outline(n, &mut pd); if !pd.is_empty() { diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 6cae9c30ee..0e31d5632a 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -821,7 +821,8 @@ impl Block { let n = self.lines.len() as f64; // The mean distance between the baselines so far, which this line's must continue. let leading = if self.lines.len() == 1 { down } else { self.leading }; - if !(leading > size * 0.25 && leading <= size * MAX_LEADING) || (down - n * leading).abs() > tol { + // A quarter of the size is the least leading; the outlines' positions are rounded. + if !(leading >= size * 0.25 * (1.0 - 1e-6) && leading <= size * MAX_LEADING) || (down - n * leading).abs() > tol { return Some(l); } let leading = down / n; @@ -935,6 +936,32 @@ impl Block { } } +/// A line of two untracked glyphs has one gap, too few to measure a tracking by +/// ([`Line::tracked`]). It is set at the tracking of the nearest tracked line of the same font, +/// size and turn, so the layout check ([`verified`]) tries it as that line is set: the check falls +/// back to the line untracked, and then splits it, when the pair is not spaced so. A pair that +/// untracked type already draws in place keeps its text, and negative tracking goes only to a pair +/// that paints the same as one object ([`paints_as_one`]). +fn share_tracking(lines: &mut [Line], system_layout: bool) { + for i in 0..lines.len() { + let Some(l) = lines.get(i).filter(|l| l.pieces.len() == 2 && l.tracking == 0.0) else { continue }; + if l.first_mismatch(&l.probe(system_layout)).is_none() { + continue; + } + let like = |o: &Line| { + o.tracking != 0.0 + && o.parent == l.parent + && o.face.id() == l.face.id() + && (o.scale - l.scale).abs() <= l.scale * 1e-4 + && ((o.angle - l.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5 + }; + let nearest = lines.iter().enumerate().filter(|(_, o)| like(o)).min_by_key(|(j, _)| j.abs_diff(i)).map(|(_, o)| o.tracking); + if let Some(p) = nearest.filter(|t| *t > 0.0 || paints_as_one(l)).and_then(|t| l.respaced(0, 2, t)) { + lines[i] = p; + } + } +} + /// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of /// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after /// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`]. @@ -1147,7 +1174,8 @@ fn retype(s: &mut Session, p: &Value) -> Result { // glyphs), so every line has what its measure can take. let mut budget = lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add); - let lines = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect(); + let mut lines: Vec = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect(); + share_tracking(&mut lines, system_layout); let mut lines = verified(lines, system_layout, &mut unmatched); if pieces.len() > 1 { lines.retain(|l| { diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 9b06e3dba8..80361f1e0a 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -597,6 +597,28 @@ fn several_lines_become_one_area_type_object() { assert_same_places(&before, &t); } +#[test] +fn lines_a_quarter_of_the_size_apart_join_and_closer_ones_do_not() { + // At 20 pt, 5 pt is the least leading that joins lines. + // 4.9999999 pt is 5 pt to the rounding of the outlines' positions. + for (leading, objects) in [(5.0, 1), (4.9999999, 1), (4.9, 2)] { + let mut s = session(); + let text = "One\nTwo"; + let (_, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 20}), &[json!({"leading": leading})]); + assert_eq!(r["texts"].as_array().unwrap().len(), objects, "{leading}: {r}"); + } +} + +#[test] +fn a_two_glyph_line_takes_the_tracking_of_the_lines_around_it() { + let mut s = session(); + let text = "MMM\nMM\nMMM"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 50})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + #[test] fn lines_keep_their_leading_and_alignment() { for justify in ["left", "center", "right"] {