From f484af750228b7e0374e27dd4247e52255757cfd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 17:17:16 -0800 Subject: [PATCH 01/55] i18n: banner hem and grommet errors and the recovery failure line have rows in every complete catalog Banner Hems and Grommets' errors, including its two shared range errors, and "{saving} failed: {e}" get @msg rows in the el, es, fr, hi, ka, vi, fi, ca and da catalogs. The message scan now follows a local given to `.status(name)` to the nearest `let` of that name in the same function, so the untranslated report lists the recovery failure lines that recovery.rs builds in a local before showing them. --- crates/ui-egui/src/i18n/ca.tsv | 12 +++++ crates/ui-egui/src/i18n/da.tsv | 12 +++++ crates/ui-egui/src/i18n/el.tsv | 12 +++++ crates/ui-egui/src/i18n/es.tsv | 10 ++++ crates/ui-egui/src/i18n/fi.tsv | 12 +++++ crates/ui-egui/src/i18n/fr.tsv | 10 ++++ crates/ui-egui/src/i18n/hi.tsv | 12 +++++ crates/ui-egui/src/i18n/ka.tsv | 12 +++++ crates/ui-egui/src/i18n/tests.rs | 84 +++++++++++++++++++++++++++++++- crates/ui-egui/src/i18n/vi.tsv | 12 +++++ docs/target-app-parity.md | 1 + 11 files changed, 188 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index ab50e14a58..2e4d253cd6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7504,6 +7504,18 @@ breakText Glyphs Glifs Margin Marge Box Caixa Swatch Mostra +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` ha de ser més gran que 0 i com a màxim {MAX_DISTANCE} pt +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` ha d’estar entre 0 i {MAX_DISTANCE} pt +@msg `{key}` must be from 0.01 to 1000 pt `{key}` ha d’estar entre 0,01 i 1000 pt +@msg select the banner, or mark every artboard seleccioneu la pancarta o marqueu tots els taulers +@msg the banner has no width or height la pancarta no té amplada ni alçada +@msg the grommet inset is too large for the banner la distància dels ullets a la vora és massa gran per a la pancarta +@msg the hem is too deep for the banner la vora és massa profunda per a la pancarta +@msg the spacing makes more than {MAX_GROMMETS} grommets l’espaiat genera més de {MAX_GROMMETS} ullets +@msg there is no banner to mark no hi ha cap pancarta per marcar +@msg turn on at least one side activeu almenys un costat +@msg with no hem and no grommets there is nothing to mark sense vora ni ullets no hi ha res per marcar +@msg {saving} failed: {e} {saving} ha fallat: {e} Banner Hems and Grommets… Vores i ullets de pancarta… Banner Hems and Grommets Vores i ullets de pancarta Hem Vora diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 59ce36d15f..ba23d8a5f2 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7533,6 +7533,18 @@ breakText Glyphs Glyffer Box Ramme Swatch Farveprøve Direction Retning +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` skal være større end 0 og højst {MAX_DISTANCE} pt +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` skal være fra 0 til {MAX_DISTANCE} pt +@msg `{key}` must be from 0.01 to 1000 pt `{key}` skal være fra 0,01 til 1000 pt +@msg select the banner, or mark every artboard markér banneret, eller afmærk alle tegneflader +@msg the banner has no width or height banneret har ingen bredde eller højde +@msg the grommet inset is too large for the banner maljernes afstand fra kanten er for stor til banneret +@msg the hem is too deep for the banner sømmen er for dyb til banneret +@msg the spacing makes more than {MAX_GROMMETS} grommets mellemrummet giver mere end {MAX_GROMMETS} maljer +@msg there is no banner to mark der er intet banner at afmærke +@msg turn on at least one side slå mindst én side til +@msg with no hem and no grommets there is nothing to mark uden søm og uden maljer er der intet at afmærke +@msg {saving} failed: {e} {saving} mislykkedes: {e} Banner Hems and Grommets… Bannersømme og maljer… Banner Hems and Grommets Bannersømme og maljer Hem Søm diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a89d3c72e4..0b3b14a05b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7476,6 +7476,18 @@ breakText Glyphs Γλύφοι Margin Περιθώριο Box Πλαίσιο Swatch Δείγμα χρώματος +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt το `spacing` πρέπει να είναι μεγαλύτερο από 0 και το πολύ {MAX_DISTANCE} pt +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt το `{key}` πρέπει να είναι από 0 έως {MAX_DISTANCE} pt +@msg `{key}` must be from 0.01 to 1000 pt το `{key}` πρέπει να είναι από 0,01 έως 1000 pt +@msg select the banner, or mark every artboard επιλέξτε το πανό ή σημειώστε όλους τους πίνακες σχεδίασης +@msg the banner has no width or height το πανό δεν έχει πλάτος ή ύψος +@msg the grommet inset is too large for the banner η απόσταση των τρουκς από την άκρη είναι πολύ μεγάλη για το πανό +@msg the hem is too deep for the banner το στρίφωμα είναι πολύ βαθύ για το πανό +@msg the spacing makes more than {MAX_GROMMETS} grommets το διάστημα δημιουργεί περισσότερα από {MAX_GROMMETS} τρουκς +@msg there is no banner to mark δεν υπάρχει πανό για σήμανση +@msg turn on at least one side ενεργοποιήστε τουλάχιστον μία πλευρά +@msg with no hem and no grommets there is nothing to mark χωρίς στρίφωμα και χωρίς τρουκς δεν υπάρχει τίποτα για σήμανση +@msg {saving} failed: {e} {saving}: απέτυχε: {e} Banner Hems and Grommets… Στριφώματα και τρουκς πανό… Banner Hems and Grommets Στριφώματα και τρουκς πανό Hem Στρίφωμα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4a912f8005..c98833bb02 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7583,6 +7583,16 @@ breakText Glyphs Glifos Margin Margen Box Caja Swatch Muestra +@msg `{key}` must be from 0.01 to 1000 pt `{key}` debe estar entre 0,01 y 1000 pt +@msg select the banner, or mark every artboard seleccione la pancarta o marque todas las mesas de trabajo +@msg the banner has no width or height la pancarta no tiene anchura ni altura +@msg the grommet inset is too large for the banner la distancia de los ojales al borde es demasiado grande para la pancarta +@msg the hem is too deep for the banner el dobladillo es demasiado profundo para la pancarta +@msg the spacing makes more than {MAX_GROMMETS} grommets el espaciado genera más de {MAX_GROMMETS} ojales +@msg there is no banner to mark no hay ninguna pancarta que marcar +@msg turn on at least one side active al menos un lado +@msg with no hem and no grommets there is nothing to mark sin dobladillo ni ojales no hay nada que marcar +@msg {saving} failed: {e} {saving} falló: {e} Banner Hems and Grommets… Dobladillos y ojales de pancarta… Banner Hems and Grommets Dobladillos y ojales de pancarta Hem Dobladillo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 06499d13ea..a283b3d4fb 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7558,6 +7558,18 @@ breakText Glyphs Merkit Margin Marginaali Box Kehys Swatch Värimalli +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing`-arvon on oltava yli 0 ja enintään {MAX_DISTANCE} pt +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}`-arvon on oltava väliltä 0–{MAX_DISTANCE} pt +@msg `{key}` must be from 0.01 to 1000 pt `{key}`-arvon on oltava väliltä 0,01–1000 pt +@msg select the banner, or mark every artboard valitse banneri tai merkitse kaikki piirtoalustat +@msg the banner has no width or height bannerilla ei ole leveyttä eikä korkeutta +@msg the grommet inset is too large for the banner purjerenkaiden etäisyys reunasta on liian suuri bannerille +@msg the hem is too deep for the banner päärme on liian syvä bannerille +@msg the spacing makes more than {MAX_GROMMETS} grommets välistyksellä tulisi yli {MAX_GROMMETS} purjerengasta +@msg there is no banner to mark merkittävää banneria ei ole +@msg turn on at least one side ota käyttöön vähintään yksi sivu +@msg with no hem and no grommets there is nothing to mark ilman päärmettä ja purjerenkaita ei ole mitään merkittävää +@msg {saving} failed: {e} {saving} epäonnistui: {e} Banner Hems and Grommets… Bannerin päärmeet ja purjerenkaat… Banner Hems and Grommets Bannerin päärmeet ja purjerenkaat Hem Päärme diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 90882cf105..ae122c1302 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9322,6 +9322,16 @@ breakText Glyphs Glyphes @msg the paths are too many or too tangled to find where they cross les tracés sont trop nombreux ou trop enchevêtrés pour trouver où ils se croisent @msg the rectangle or line reaches too many paths to check le rectangle ou la ligne atteint trop de tracés pour être vérifié @msg {name} must be a number {name} doit être un nombre +@msg `{key}` must be from 0.01 to 1000 pt `{key}` doit être compris entre 0,01 et 1000 pt +@msg select the banner, or mark every artboard sélectionnez la banderole ou marquez tous les plans de travail +@msg the banner has no width or height la banderole n’a ni largeur ni hauteur +@msg the grommet inset is too large for the banner la distance des œillets au bord est trop grande pour la banderole +@msg the hem is too deep for the banner l’ourlet est trop profond pour la banderole +@msg the spacing makes more than {MAX_GROMMETS} grommets l’espacement produit plus de {MAX_GROMMETS} œillets +@msg there is no banner to mark il n’y a aucune banderole à marquer +@msg turn on at least one side activez au moins un côté +@msg with no hem and no grommets there is nothing to mark sans ourlet ni œillets, il n’y a rien à marquer +@msg {saving} failed: {e} {saving} : échec : {e} Banner Hems and Grommets… Ourlets et œillets de banderole… Banner Hems and Grommets Ourlets et œillets de banderole Hem Ourlet diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 671052e82b..118e49fe16 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8914,6 +8914,18 @@ theme Appearance अपीयरेंस Margin मार्जिन Box बॉक्स Swatch स्वॉच +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` 0 से अधिक और अधिकतम {MAX_DISTANCE} pt होना चाहिए +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` 0 से {MAX_DISTANCE} pt तक होना चाहिए +@msg `{key}` must be from 0.01 to 1000 pt `{key}` 0.01 से 1000 pt तक होना चाहिए +@msg select the banner, or mark every artboard बैनर चुनें, या हर आर्टबोर्ड को मार्क करें +@msg the banner has no width or height बैनर की कोई चौड़ाई या ऊँचाई नहीं है +@msg the grommet inset is too large for the banner बैनर के लिए किनारे से आईलेट की दूरी बहुत अधिक है +@msg the hem is too deep for the banner बैनर के लिए हेम बहुत गहरा है +@msg the spacing makes more than {MAX_GROMMETS} grommets इस स्पेसिंग से {MAX_GROMMETS} से अधिक आईलेट बनते हैं +@msg there is no banner to mark मार्क करने के लिए कोई बैनर नहीं है +@msg turn on at least one side कम से कम एक साइड चालू करें +@msg with no hem and no grommets there is nothing to mark बिना हेम और बिना आईलेट के मार्क करने के लिए कुछ नहीं है +@msg {saving} failed: {e} {saving} विफल: {e} Banner Hems and Grommets… बैनर हेम और आईलेट… Banner Hems and Grommets बैनर हेम और आईलेट Hem हेम diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8c42eafaf1..55b186a76f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7637,6 +7637,18 @@ font-script Japanese იაპონური Margin ზღვარი Box ჩარჩო Swatch ფერის ნიმუში +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` უნდა იყოს 0-ზე მეტი და არაუმეტეს {MAX_DISTANCE} pt +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` უნდა იყოს 0-დან {MAX_DISTANCE} pt-მდე +@msg `{key}` must be from 0.01 to 1000 pt `{key}` უნდა იყოს 0,01-დან 1000 pt-მდე +@msg select the banner, or mark every artboard აირჩიეთ ბანერი ან მონიშნეთ ყველა სამუშაო დაფა +@msg the banner has no width or height ბანერს არ აქვს სიგანე ან სიმაღლე +@msg the grommet inset is too large for the banner ლუვერების დაშორება კიდიდან ზედმეტად დიდია ბანერისთვის +@msg the hem is too deep for the banner ნაკეცი ზედმეტად ღრმაა ბანერისთვის +@msg the spacing makes more than {MAX_GROMMETS} grommets ამ ინტერვალით {MAX_GROMMETS}-ზე მეტი ლუვერი გამოდის +@msg there is no banner to mark მოსანიშნი ბანერი არ არის +@msg turn on at least one side ჩართეთ ერთი მხარე მაინც +@msg with no hem and no grommets there is nothing to mark ნაკეცისა და ლუვერების გარეშე მოსანიშნი არაფერია +@msg {saving} failed: {e} {saving} ვერ შესრულდა: {e} Banner Hems and Grommets… ბანერის ნაკეცები და ლუვერები… Banner Hems and Grommets ბანერის ნაკეცები და ლუვერები Hem ნაკეცი diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 7fc16807ec..9535564181 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2374,6 +2374,27 @@ fn plugin_messages_are_translated_in_every_complete_catalog() { assert!(missing.is_empty(), "{} plug-in messages have no @msg row:\n{}", missing.len(), missing.join("\n")); } +/// Banner Hems and Grommets' errors and the status of a recovery copy that failed without a folder +/// to name have an `@msg` row in every complete-message catalog. +#[test] +fn banner_and_recovery_messages_are_translated_in_every_complete_catalog() { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../engine/src/cmd/addons/cutting/banner.rs"); + let code = std::fs::read_to_string(&path).unwrap_or_default(); + let mut messages = source_messages(without_test_module(&code), &[("bad(", 1)], &std::collections::BTreeMap::new()); + assert!(messages.len() >= 11, "scan found only {} banner messages: {messages:?}", messages.len()); + let recovery = "{saving} failed: {e}"; + assert!(message_literals_in(&["ui-egui"]).contains(recovery), "the scan skips {recovery:?}"); + messages.push(recovery.to_string()); + let mut missing = vec![]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let (entries, _) = parse_entries(lang.0.source); + let rows: std::collections::BTreeSet<&str> = entries.iter().filter(|(ctx, _, _)| ctx == "@msg").map(|(_, src, _)| src.as_str()).collect(); + missing.extend(messages.iter().filter(|m| !rows.contains(m.as_str())).map(|m| format!("{code}: {m}"))); + } + assert!(missing.is_empty(), "{} banner and recovery messages have no @msg row:\n{}", missing.len(), missing.join("\n")); +} + /// Errors the plug-in host returns are translated whole in every complete-message catalog, the /// reason inside the error's kind included, and keep their numbers, JSON shapes, permission names /// and nested reasons as written. @@ -3030,6 +3051,42 @@ fn unreadable(e: impl std::fmt::Display) -> String { assert!(message_literals_in(&["engine"]).contains("Data Recovery can't keep copies in {path}: {e}")); } +/// The scan reads the values of a local that a `.status(name)` shows, from the nearest `let` of +/// that name in the same function: a `format!` string and each arm of a `match`. It skips a local +/// that no status shows, a `let` of the name in another function, and a status given a value. +#[test] +fn message_scan_reads_locals_given_to_a_status() { + let code = r#" +fn other() { + let line = format!("the other function's line: {e}"); + log(line); +} + +fn saved(app: &mut App, saving: &str, e: &str, place: Option<&str>) { + let unused = format!("a line no status shows: {e}"); + let line = format!("{saving} failed: {e}"); + app.status(line); + let line = match place { + Some(folder) => format!("Couldn't save to {folder}: {e}"), + None => "Couldn't save".to_string(), + }; + log(&line); + app.status(line); + app.status(true); +} +"#; + let want = ["{saving} failed: {e}", "Couldn't save to {folder}: {e}", "Couldn't save"]; + assert_eq!(source_messages(code, &[], &std::collections::BTreeMap::new()), want); + let ui = message_literals_in(&["ui-egui"]); + for m in [ + "{saving} failed: {e}", + "Couldn't save recovery data for {title}: {e}. Copies go to {folder}, the folder set in Preferences; to use another folder, set Preferences → File Handling → Data Recovery → Folder (recoveryFolder)", + "Couldn't save recovery data for {title}: {e}. Copies go to {folder}, the default recovery folder; to use another folder, set Preferences → File Handling → Data Recovery → Folder (recoveryFolder)", + ] { + assert!(ui.contains(m), "the scan skips {m:?}"); + } +} + /// The scan stops at a test module whose `cfg` is `test` or `all(test, …)`, and reads on past a /// declaration of a test file and a module that is not only for tests. #[test] @@ -4477,6 +4534,7 @@ fn named_const<'a>(rest: &str, consts: &'a std::collections::BTreeMap(code: &'a str, name: &str) -> Vec<&'a str> { out } +/// Where each value of a local that a `.status(name)` in `code` shows can start: the statement of +/// the nearest `let name = ` before that call in the same function (`let line = format!("…");`, +/// `let line = match place { … };`, up to its `;`), read as [`closure_returns`] reads a closure. A +/// local that no `.status(name)` shows is not read. +fn status_locals(code: &str) -> Vec<&str> { + let mut out = vec![]; + for (at, m) in code.match_indices(".status(") { + let rest = &code[at + m.len()..]; + let name = &rest[..rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len())]; + if !name.starts_with(|c: char| c.is_ascii_lowercase() || c == '_') || !rest[name.len()..].starts_with(')') { + continue; + } + let bound = format!("let {name} = "); + let nearest = code[..at].rmatch_indices(bound.as_str()).find(|&(b, _)| !code[..b].ends_with(|c: char| c.is_alphanumeric() || c == '_')); + if let Some((b, _)) = nearest + && !code[b..at].contains("fn ") + { + out.extend(closure_returns(statement(&code[b + bound.len()..]))); + } + } + out +} + /// The statement `code` starts with, up to its `;` or the bracket that closes the block it is in. fn statement(code: &str) -> &str { let (mut depth, mut chars) = (0usize, code.char_indices()); diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 16c613874c..3ffc077e69 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7134,6 +7134,18 @@ breakText Glyphs Glyph Margin Lề Box Khung Swatch Mẫu màu +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` phải lớn hơn 0 và tối đa {MAX_DISTANCE} pt +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` phải từ 0 đến {MAX_DISTANCE} pt +@msg `{key}` must be from 0.01 to 1000 pt `{key}` phải từ 0,01 đến 1000 pt +@msg select the banner, or mark every artboard hãy chọn băng rôn, hoặc đánh dấu mọi bảng vẽ +@msg the banner has no width or height băng rôn không có chiều rộng hoặc chiều cao +@msg the grommet inset is too large for the banner khoảng cách từ mép đến khoen quá lớn so với băng rôn +@msg the hem is too deep for the banner viền gấp quá sâu so với băng rôn +@msg the spacing makes more than {MAX_GROMMETS} grommets khoảng cách này tạo ra hơn {MAX_GROMMETS} khoen +@msg there is no banner to mark không có băng rôn nào để đánh dấu +@msg turn on at least one side hãy bật ít nhất một cạnh +@msg with no hem and no grommets there is nothing to mark không có viền gấp và khoen thì không có gì để đánh dấu +@msg {saving} failed: {e} {saving} thất bại: {e} Banner Hems and Grommets… Viền gấp và khoen băng rôn… Banner Hems and Grommets Viền gấp và khoen băng rôn Hem Viền gấp diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c6972468cc..e100690fae 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -921,6 +921,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Polish catalog (`crates/ui-egui/src/i18n/pl.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,439 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 46 Polish messages: 44 that open #7211, #7214, #7116, #7330 and #1931 translate, and 2 that no language has a row for. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). + - The status bar translates the errors of Object › Plug-ins › Cutting Tools › Banner Hems and Grommets… and the line for a recovery copy that fails in a store with no folder to name (`{saving} failed: {e}`) in every language that translates every message. The untranslated-strings report also lists the messages a status takes from a local variable, such as the recovery folder errors (`banner_and_recovery_messages_are_translated_in_every_complete_catalog`, `message_scan_reads_locals_given_to_a_status`). - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`). - The status bar translates the errors a script's `File` and `Folder` objects, `vc.run`, `$.evalFile`, the `$` object's properties and functions, `alert`, `confirm` and `prompt`, `vc.document` and `vc.log` raise, the limits a run can pass, and the errors of Drop Script Engine, and the line for a run that fails (a syntax error, a thrown error, a limit, a stop or an internal error, with the script's name, the line and column, the included file it is in and the files left written), in every language that translates every message. The script's name, paths, numbers, command ids and the text a script throws itself are shown as they are. A failure with no line and column, such as an error in code `eval` compiled, is shown with one colon after the script's name (`an_error_without_a_place_names_the_script_and_kind`). A message template that names a value twice matches only when both places hold the same text, so the line for a failed run is not taken for the message inside it (`a_repeated_placeholder_matches_the_same_text`). The untranslated-strings report also lists the messages the script host's `fail`, `value` and `over` helpers take and the errors the script interpreter throws, and a constant's text comes from the file or crate that declares it, so the Scripts menu's headers are not listed as messages (`script_errors_are_translated`, `script_host_errors_are_translated`, `message_scan_reads_script_interpreter_errors`, `message_scan_reads_constants_of_the_file_and_its_crate`, `message_scan_skips_test_modules_with_any_test_cfg`). From 6c787eb784a4b4c8b8ecc6137eab8426324200de Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:59:59 -0800 Subject: [PATCH 02/55] i18n: Georgian keeps one row for each banner message main now carries Georgian rows for the Banner Hems and Grommets errors and the shared distance and size range errors. Keep those rows and add only the recovery row `{saving} failed: {e}`, so the catalog has no duplicate rows for these messages. --- crates/ui-egui/src/i18n/ka.tsv | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 516595296f..999486bdae 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9865,17 +9865,6 @@ font-script Japanese იაპონური Margin ზღვარი Box ჩარჩო Swatch ფერის ნიმუში -@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` უნდა იყოს 0-ზე მეტი და არაუმეტეს {MAX_DISTANCE} pt -@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` უნდა იყოს 0-დან {MAX_DISTANCE} pt-მდე -@msg `{key}` must be from 0.01 to 1000 pt `{key}` უნდა იყოს 0,01-დან 1000 pt-მდე -@msg select the banner, or mark every artboard აირჩიეთ ბანერი ან მონიშნეთ ყველა სამუშაო დაფა -@msg the banner has no width or height ბანერს არ აქვს სიგანე ან სიმაღლე -@msg the grommet inset is too large for the banner ლუვერების დაშორება კიდიდან ზედმეტად დიდია ბანერისთვის -@msg the hem is too deep for the banner ნაკეცი ზედმეტად ღრმაა ბანერისთვის -@msg the spacing makes more than {MAX_GROMMETS} grommets ამ ინტერვალით {MAX_GROMMETS}-ზე მეტი ლუვერი გამოდის -@msg there is no banner to mark მოსანიშნი ბანერი არ არის -@msg turn on at least one side ჩართეთ ერთი მხარე მაინც -@msg with no hem and no grommets there is nothing to mark ნაკეცისა და ლუვერების გარეშე მოსანიშნი არაფერია @msg {saving} failed: {e} {saving} ვერ შესრულდა: {e} Banner Hems and Grommets… ბანერის ნაკეცები და ლუვერები… Banner Hems and Grommets ბანერის ნაკეცები და ლუვერები From d2aede7c6ecc4b575492f86c0fd88578249e6e3e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 21:44:13 -0800 Subject: [PATCH 03/55] Eyedropper: Object Highlighting outlines the object a click would act on With Smart Guides' Object Highlighting on, the Eyedropper now outlines the object under the pointer that a click there would act on, with the 1.5 px layer-color outline the selection tools draw. It follows the keys held: a plain click's source (locked and template art included, as the Eyedropper reads them), the selected gradient mesh a click recolors, the editable object an Alt-click gives the selection's attributes to, and for a Shift-click the object whose color is sampled (a blend or an envelope where its art is drawn, the art below where it leaves a gap). Empty canvas and hidden art show no outline. The tool finds that object with the same code its click uses: the click is planned once (Tool::hover_object, Session::hover_object) and the color sampler returns the object the color came from. The canvas keeps the object found until the pointer, the keys, the document, the selection or the tool's settings change, since finding it can sample a color. With Space held, a press pans the view, so no tool outlines an object under the pointer; the selection tools showed one before. --- crates/engine/src/tooling.rs | 12 +- crates/tools/src/lib.rs | 6 + crates/tools/src/xform/eyedropper.rs | 258 +++++++++++++++++++------- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/caches.rs | 4 + crates/ui-egui/src/canvas.rs | 4 +- crates/ui-egui/src/canvas/overlays.rs | 87 ++++++++- crates/ui-egui/src/canvas/tests.rs | 136 ++++++++++++++ docs/target-app-parity.md | 1 + 9 files changed, 427 insertions(+), 82 deletions(-) diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 7b1caffb7c..9642718bf7 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1,7 +1,7 @@ //! Hosting the active tool: pointer/key events → actions → commands. use serde_json::{Map, Value}; -use vectorcraft_doc::Selection; +use vectorcraft_doc::{NodeId, Selection}; use vectorcraft_geom::Point; use vectorcraft_tools::distort::perspective::widget::WidgetPlace; use vectorcraft_tools::draw2::FEEDBACK; @@ -1323,6 +1323,16 @@ impl Session { if self.precise_cursors() { c.precise() } else { c } } + /// The object a click of the active tool at `p` with `mods` would act on + /// ([`vectorcraft_tools::Tool::hover_object`]), for Smart Guides › Object Highlighting. None + /// while Cmd lends a selection tool to the press. + pub fn hover_object(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Option { + if mods.cmd && self.lender.is_none() && !self.tool_editing() && self.lent_tool(self.tool.id(), &mods).is_some() { + return None; + } + self.with_tool_cx(view, |t, cx| t.hover_object(cx, p, mods)) + } + /// General › Use Precise Cursors is on, or Caps Lock is. fn precise_cursors(&self) -> bool { self.prefs.use_precise_cursors || self.caps_lock diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 688f295478..08fba91aa3 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -305,6 +305,12 @@ pub trait Tool: Send { fn wants_rehover(&self) -> bool { false } + /// The object a click at `p` with `mods` would act on, which Smart Guides › Object + /// Highlighting outlines while the pointer rests there (the Eyedropper's source). None when a + /// click there acts on no object, or the tool does not name one. + fn hover_object(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Option { + None + } /// What the Info panel shows for the tool as it is now: the drag in progress (a move of the /// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear /// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show. diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index d45dff84ed..3448991367 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -34,6 +34,9 @@ //! Image Trace's Ignore Color eyedropper passes its bound document point to the panel, which //! samples the original image pixels and ends the pick only when a color is accepted. A miss //! stays armed; this tool changes neither paint nor selection. +//! +//! The object a click at the pointer would act on, with the keys held, is the tool's hover object +//! ([`Tool::hover_object`]), which Smart Guides › Object Highlighting outlines. use std::collections::HashSet; @@ -165,6 +168,12 @@ pub(crate) fn sample_source(cx: &ToolContext, p: Point) -> Option<(vectorcraft_d /// The visible color under `p`, including image pixels, pattern tiles, mesh colors, intermediate /// gradient colors, the steps a blend draws and an envelope's distorted contents. pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option { + sample_at(cx, p).map(|(c, _)| c) +} + +/// [`sample_color_at`] with the object of the document that gives the color: the object hit, the +/// blend or envelope whose art is sampled, or an object below them that was passed over to. +fn sample_at(cx: &ToolContext, p: Point) -> Option<(Color, NodeId)> { let (doc, opts, raster_sample) = (cx.doc, sample_options(cx), cx.raster_sample); vectorcraft_doc::depth::with_deep_stack(|| { let symbol_nodes = doc.symbols.iter().map(|s| s.art.count()).sum(); @@ -175,13 +184,13 @@ pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option { }) } -/// The color the front-most object of `doc` hit at `p` with `opts` shows there. Where a stroke +/// The color the front-most object of `doc` hit at `p` with `opts` shows there, and that object. Where a stroke /// gives no color at `p` (a gap between its pattern's tiles), the object's own fill there does; /// an object that gives none at all is passed over for the ones below it. A hit on a blend or an /// envelope, or on an object it holds, samples the art it draws ([`live_color_at`]), and where /// that art leaves `p` empty the whole blend or envelope is passed over. `levels` holds the /// scratch documents for art inside art, one for each level deeper. -fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], p: Point, opts: HitOptions) -> Option { +fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], p: Point, opts: HitOptions) -> Option<(Color, NodeId)> { let mut passed: HashSet = HashSet::new(); let mut size = None; loop { @@ -197,7 +206,7 @@ fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], let h = hit_test_visible_skipping(doc, p, opts, &|id| passed.contains(&id))?; if let Some(live) = drawn_live(doc, &h.ancestry) { if let Some(c) = live_color_at(s, levels, live, p) { - return Some(c); + return Some((c, live.id)); } if !passed.insert(live.id) { return None; @@ -208,13 +217,13 @@ fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], let n = doc.node(id)?; let on_stroke = h.kind == HitKind::Stroke; if let Some(c) = node_color_at(s, levels, n, on_stroke, p) { - return Some(c); + return Some((c, id)); } if on_stroke && fill_covers(n, p) && let Some(c) = node_color_at(s, levels, n, false, p) { - return Some(c); + return Some((c, id)); } if !passed.insert(id) { return None; @@ -464,7 +473,7 @@ fn art_color_at(s: &mut Sampler, levels: &mut [Option], art: impl Into scratch.insert(Some(layer), usize::MAX, n).ok()?; } let opts = HitOptions { scope: None, tol: 0.0, outline: false, ..s.opts }; - color_under(s, scratch, deeper, p, opts) + color_under(s, scratch, deeper, p, opts).map(|(c, _)| c) } /// Gives `n` and everything in it new ids from `doc` (pattern instances all have id 0). @@ -524,72 +533,50 @@ impl Tool for EyedropperTool { if ev.kind != PointerKind::Down { return vec![]; } - if let Some(binding) = &self.image_trace_ignore_color { - // The panel knows whether this hits an opaque source pixel. It clears the binding - // and restores the previous tool only after accepting a color, not on a miss. - return vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "point": [ev.pos.x, ev.pos.y] }))]; + let Some(click) = self.click(cx, ev.pos, ev.mods) else { return vec![] }; + match click { + Click::ImageTrace(binding) => { + // The panel knows whether this hits an opaque source pixel. It clears the binding + // and restores the previous tool only after accepting a color, not on a miss. + vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "point": [ev.pos.x, ev.pos.y] }))] + } + Click::BrushKeyColor(c, _) => { + let back = self.stop.take().unwrap_or_else(|| "selection".to_string()); + self.brush_key_color = false; + vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)] + } + Click::BackToBucket => { + self.stop = None; + vec![Action::SwitchTool("livePaintBucket".into())] + } + Click::MeshPoints(id, points, color) => { + let params = json!({ "id": id.0, "points": points, "color": color_json(&color), "keepModel": true }); + vec![Action::Exec("object.mesh.setPointColor".into(), params)] + } + Click::CopyFrom(src, how) => { + let params = match how { + Some(how) => json!({ "source": src.0, how: true }), + None => json!({ "source": src.0 }), + }; + vec![Action::Exec("appearance.copyFrom".into(), params)] + } + Click::Sample { color, meshes, stop, .. } => { + let color = color_json(&color); + if !meshes.is_empty() { + let ids: Vec = meshes.iter().map(|id| id.0).collect(); + return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stroke": false, "ids": ids }))]; + } + let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] }; + self.stop = None; + vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back)] + } } - let opts = sample_options(cx); - if self.brush_key_color { - let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; - let back = self.stop.clone().unwrap_or_else(|| "selection".to_string()); - self.brush_key_color = false; - self.stop = None; - return vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)]; - } - // A pick for a stop of the Live Paint Bucket's gradient (the default paint's) ends without - // sampling once that stop is no longer selected (a Cmd-click selected another object) or no - // longer there (another paint was chosen): the click switches back. - let bucket_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke }; - let bucket_stop = cx.gradient_stop.filter(|i| matches!(bucket_paint, Paint::Gradient(g) if *i < g.gradient.stops.len())); - if self.stop.as_deref() == Some("livePaintBucket") && bucket_stop.is_none() { - self.stop = None; - return vec![Action::SwitchTool("livePaintBucket".into())]; - } - let stop = self.stop.as_ref().zip(cx.gradient_stop); - // A plain click on a selected gradient mesh gives the fill color to the point there, else - // to the four points of the patch there. - if stop.is_none() - && !ev.mods.alt - && !ev.mods.shift - && let Paint::Solid { color, .. } = &cx.paint.fill - && let Some((id, points)) = selected_mesh_points(cx, ev.pos) - { - let params = json!({ "id": id.0, "points": points, "color": color_json(color), "keepModel": true }); - return vec![Action::Exec("object.mesh.setPointColor".into(), params)]; - } - // Reading a source is independent of its editability. Only Alt's reverse operation - // writes to the clicked object; Shift+Alt appends its appearance to the selection. - let source = if ev.mods.alt && !ev.mods.shift && stop.is_none() { - hit_test(cx.doc, ev.pos, opts).map(|h| (paint_owner(cx.doc, h.leaf), h.kind)) - } else { - sample_source(cx, ev.pos) - }; - let Some((src, _)) = source else { return vec![] }; - let Some(n) = cx.doc.node(src) else { return vec![] }; - if ev.mods.alt && stop.is_none() { - let how = if ev.mods.shift { "append" } else { "reverse" }; - return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0, how: true }))]; - } - let image = matches!(n.kind, NodeKind::Image(_)); - // Picked mesh points take only a color sampled from other art or an image: the sample goes - // to them as a fill, and to nothing else that is selected. A click on a mesh with picked - // points is handled as before. - let meshes = if stop.is_none() { picked_meshes(cx, &self.mesh_points) } else { vec![] }; - let meshes = if meshes.contains(&src) { vec![] } else { meshes }; - if !(ev.mods.shift || stop.is_some() || image || !meshes.is_empty()) { - return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0 }))]; - } - let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; - let color = color_json(&c); - if !meshes.is_empty() { - let ids: Vec = meshes.iter().map(|id| id.0).collect(); - return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stroke": false, "ids": ids }))]; - } - let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] }; - let out = vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back.clone())]; - self.stop = None; - out + } + + /// The object a click there samples, recolors or copies attributes to, as [`Self::click`] + /// finds it. + fn hover_object(&self, cx: &ToolContext, p: Point, mods: Mods) -> Option { + self.click(cx, p, mods)?.object() } /// Expose a transient text range alongside gradient-stop and brush-key sampling state. @@ -684,11 +671,92 @@ impl Tool for EyedropperTool { } } +/// What a click with the Eyedropper does, which [`EyedropperTool::pointer`] carries out. +enum Click { + /// Image Trace's Ignore Color pick: the panel samples the image with this binding. + ImageTrace(Value), + /// Brush Options › Key Color: this color, sampled from this object. + BrushKeyColor(Color, NodeId), + /// A pick for a Live Paint Bucket stop that is no longer selected switches back unsampled. + BackToBucket, + /// The fill color goes to these points of this selected gradient mesh. + MeshPoints(NodeId, Vec, Color), + /// `appearance.copyFrom` this source, with `reverse` or `append` or neither. + CopyFrom(NodeId, Option<&'static str>), + /// This color, sampled from `source`, goes to the picked points of `meshes`, else to the + /// gradient stop of `stop` (the tool to switch back to and the stop), else to the active fill + /// or stroke. + Sample { color: Color, source: NodeId, meshes: Vec, stop: Option<(String, usize)> }, +} + +impl Click { + /// The object of the document the click reads from or writes to. + fn object(&self) -> Option { + match self { + Click::ImageTrace(_) | Click::BackToBucket => None, + Click::BrushKeyColor(_, id) | Click::MeshPoints(id, ..) | Click::CopyFrom(id, _) | Click::Sample { source: id, .. } => Some(*id), + } + } +} + impl EyedropperTool { /// Is a gradient stop, Brush Key Color or Image Trace Ignore Color pick armed? fn picking(&self) -> bool { self.stop.is_some() || self.brush_key_color || self.image_trace_ignore_color.is_some() } + + /// What a click at `p` with `mods` does, or None when it does nothing. + fn click(&self, cx: &ToolContext, p: Point, mods: Mods) -> Option { + if let Some(binding) = &self.image_trace_ignore_color { + return Some(Click::ImageTrace(binding.clone())); + } + if self.brush_key_color { + let (c, source) = sample_at(cx, p)?; + return Some(Click::BrushKeyColor(c, source)); + } + // A pick for a stop of the Live Paint Bucket's gradient (the default paint's) ends without + // sampling once that stop is no longer selected (a Cmd-click selected another object) or no + // longer there (another paint was chosen): the click switches back. + let bucket_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke }; + let bucket_stop = cx.gradient_stop.filter(|i| matches!(bucket_paint, Paint::Gradient(g) if *i < g.gradient.stops.len())); + if self.stop.as_deref() == Some("livePaintBucket") && bucket_stop.is_none() { + return Some(Click::BackToBucket); + } + let stop = self.stop.clone().zip(cx.gradient_stop); + // A plain click on a selected gradient mesh gives the fill color to the point there, else + // to the four points of the patch there. + if stop.is_none() + && !mods.alt + && !mods.shift + && let Paint::Solid { color, .. } = &cx.paint.fill + && let Some((id, points)) = selected_mesh_points(cx, p) + { + return Some(Click::MeshPoints(id, points, *color)); + } + // Reading a source is independent of its editability. Only Alt's reverse operation + // writes to the clicked object; Shift+Alt appends its appearance to the selection. + let source = if mods.alt && !mods.shift && stop.is_none() { + hit_test(cx.doc, p, sample_options(cx)).map(|h| (paint_owner(cx.doc, h.leaf), h.kind)) + } else { + sample_source(cx, p) + }; + let (src, _) = source?; + let n = cx.doc.node(src)?; + if mods.alt && stop.is_none() { + return Some(Click::CopyFrom(src, Some(if mods.shift { "append" } else { "reverse" }))); + } + let image = matches!(n.kind, NodeKind::Image(_)); + // Picked mesh points take only a color sampled from other art or an image: the sample goes + // to them as a fill, and to nothing else that is selected. A click on a mesh with picked + // points is handled as before. + let meshes = if stop.is_none() { picked_meshes(cx, &self.mesh_points) } else { vec![] }; + let meshes = if meshes.contains(&src) { vec![] } else { meshes }; + if !(mods.shift || stop.is_some() || image || !meshes.is_empty()) { + return Some(Click::CopyFrom(src, None)); + } + let (color, source) = sample_at(cx, p)?; + Some(Click::Sample { color, source, meshes, stop }) + } } #[cfg(test)] @@ -1824,7 +1892,7 @@ mod tests { let opts = sample_options(&cx); let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: 1_000, exhausted: false, patterns: 0 }; let mut levels: Vec> = (0..MAX_NESTING).map(|_| None).collect(); - assert_eq!(color_under(&mut s, &d, &mut levels, Point::new(150.0, 150.0), opts).map(|c| c.to_hex()), None); + assert_eq!(color_under(&mut s, &d, &mut levels, Point::new(150.0, 150.0), opts).map(|(c, _)| c.to_hex()), None); assert!(s.exhausted); } @@ -1917,6 +1985,52 @@ mod tests { assert_eq!(sampled_hex(&below), "#00ff00"); } + /// The object the hover names for a Shift-click is the one whose color the click samples: the + /// blend where a step is drawn, and the rectangle below it in a gap between the steps. Away + /// from all art it names none. + #[test] + fn shift_hover_names_the_object_the_sample_comes_from() { + use vectorcraft_doc::live::{BlendSpacing, BlendSpec}; + use vectorcraft_geom::Rect; + let d = doc_with_live_over_green(|d| { + let red = solid_rect(d, Rect::new(300.0, 300.0, 320.0, 320.0), Color::rgb(1.0, 0.0, 0.0)); + let blue = solid_rect(d, Rect::new(400.0, 300.0, 420.0, 320.0), Color::rgb(0.0, 0.0, 1.0)); + let spec = BlendSpec { spacing: BlendSpacing::Steps(1), ..Default::default() }; + Node::new(d.alloc_id(), NodeKind::Blend { children: vec![std::sync::Arc::new(red), std::sync::Arc::new(blue)], spec: Box::new(spec) }) + }); + let ids: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + let [.., green, blend] = ids[..] else { panic!("two objects over the rectangle expected") }; + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let t = EyedropperTool::default(); + let names = |x: f64, y: f64| t.hover_object(&cx(&d, &s, &p), Point::new(x, y), shift); + assert_eq!(names(360.0, 310.0), Some(blend), "a blend step"); + assert_eq!(names(335.0, 310.0), Some(green), "a gap between the steps"); + assert_eq!(names(480.0, 480.0), None, "no art"); + } + + /// A plain click on a selected gradient mesh recolors its points, and the hover names that + /// mesh; Image Trace's Ignore Color pick, which the panel samples, names nothing. + #[test] + fn hover_names_the_selected_mesh_a_click_recolors() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mesh = d.alloc_id(); + let grid = GradientMesh::from_surface(1, 1, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE); + d.insert(Some(l), 0, Node::new(mesh, NodeKind::Mesh(grid))).unwrap(); + let p = paint(); + let mut s = Selection::default(); + s.set([mesh]); + let mut t = EyedropperTool::default(); + let at = Point::new(150.0, 150.0); + let a = t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(matches!(a.first(), Some(Action::Exec(id, _)) if id == "object.mesh.setPointColor"), "{a:?}"); + assert_eq!(t.hover_object(&cx(&d, &s, &p), at, Mods::default()), Some(mesh)); + t.set_option("imageTraceIgnoreColor", &json!({"binding": 1})); + assert_eq!(t.hover_object(&cx(&d, &s, &p), at, Mods::default()), None); + } + /// A blend of two instances of one symbol draws its steps as instances too: Shift-click on a /// step samples the symbol's art there, and where that art leaves the point empty, what lies /// below. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..320c5b0f3c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -98,6 +98,7 @@ impl VectorcraftApp { cursors: Default::default(), view_moved: None, hover_cursor: None, + hover_object: None, presented: None, opening_fit: None, panes: Default::default(), diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6e1d229023..5c8e1f3a11 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -87,6 +87,10 @@ pub struct CanvasCache { /// The cursor the active tool last gave over the canvas, with the tool and the modifier keys /// it was for: kept while the view moves. pub hover_cursor: Option<(&'static str, vectorcraft_tools::Mods, vectorcraft_tools::Cursor)>, + /// The object the Eyedropper's click at the pointer would act on, which Object Highlighting + /// outlines, with what it was found for: finding it again, which can sample a color, waits + /// until one of those changes. + pub hover_object: Option<(canvas::HoverObjectKey, Option)>, /// In Presentation Mode, the canvas rect the active artboard was last fitted to: it is fitted /// again when the rect changes (the window going full screen). pub presented: Option, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b366665d4..53a1d373f8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -61,12 +61,12 @@ use input::handle_input; use outline::KEY_OUTLINE; #[cfg(test)] use outline::{OVERLAY_MAX_ANCHORS, c32, node_outline, walk_drawn}; -pub use overlays::SharedPaths; #[cfg(test)] use overlays::selected_anchor; use overlays::{ HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, overlay_hover_text, selection_overlay, }; +pub use overlays::{HoverObjectKey, SharedPaths}; pub use panes::{Layout as TileLayout, Panes}; pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area}; pub(crate) use quick_pen_bar::quick_pen_bar_rect; @@ -1670,7 +1670,7 @@ fn selection_visuals( overlays.extend(crate::dialogs::live_paint_gaps::overlays(app)); if app.ui.view.edges && !revolve_edit { if hover_still { - hover_highlight(app, painter, xf); + hover_highlight(app, painter, xf, view_info); } selection_overlay(app, painter, xf, overlays.iter().any(|o| matches!(o, Overlay::CurvePoint { .. })), &mut marks); app.canvas.selection_marks = marks; diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b4d2d44aac..79d3195eaf 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -10,27 +10,100 @@ use super::outline::{KEY_OUTLINE, c32, node_outline, selection_hit_at, stroke_pa use super::selection_marks::{MarkOptions, SelectionMarks}; use super::{BezPath, Color32, CornerRadius, NodeKind, Overlay, Pos2, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, vec2}; -pub(super) fn hover_highlight(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { +pub(super) fn hover_highlight(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf, view: vectorcraft_engine::ViewInfo) { let Some(h) = app.hover_doc else { return }; // Smart Guides › Object Highlighting: a Smart Guides display option, so it needs them on and Snap to Grid and Pixel Preview off. if !app.ui.view.smart_guides || !app.session.prefs.object_highlighting || app.ui.view.snap_to_grid || app.ui.view.pixel_preview { return; } - if app.session.tool_busy() || !matches!(app.session.tool_id(), "selection" | "directSelection" | "groupSelection") { + if app.session.tool_busy() || !matches!(app.session.tool_id(), "selection" | "directSelection" | "groupSelection" | "eyedropper") { return; } + // With Space lending the view tools, a press pans the view and acts on no object. + let (m, space) = p.ctx().input(|i| (i.modifiers, i.key_down(egui::Key::Space))); + if super::drag::space_lends_view_tools(app, m, space) { + return; + } + let id = if app.session.tool_id() == "eyedropper" { + // The object the Eyedropper's click there samples, recolors or copies to, with the keys + // held now. A selected one is outlined too: a click on it still acts on it. + let mods = super::drag::mods(m, false); + let Some(id) = eyedropper_hover_object(app, h, mods, view) else { return }; + id + } else { + let Some(st) = app.session.active() else { return }; + let Some(hit) = selection_hit_at(app, h, xf.zoom) else { return }; + let id = if app.session.tool_id() == "selection" { hit.top_object(st.isolation) } else { hit.leaf }; + if st.selection.contains(id) { + return; + } + id + }; let Some(st) = app.session.active() else { return }; - let Some(hit) = selection_hit_at(app, h, xf.zoom) else { return }; - let id = if app.session.tool_id() == "selection" { hit.top_object(st.isolation) } else { hit.leaf }; - if st.selection.contains(id) { - return; - } if let Some(n) = st.doc.node(id).filter(|n| !too_many_anchors([*n])) { let color = c32(st.doc.layer_color(id)); stroke_path(p, &node_outline(n, &st.doc.symbol_boxes()), xf, Stroke::new(1.5, color)); } } +/// What the Eyedropper's hover object depends on: the point, the keys held, the document as it is, +/// the selection and isolation, the tool's options (an armed pick), the paint defaults and the +/// selected gradient stop, the selection tolerance, Eyedropper Options (the raster sample size), +/// whether guides show and are locked, and the view's zoom and Outline mode: everything the +/// tool's context gives a click that can change what it acts on. +#[derive(Clone, Debug, PartialEq)] +pub struct HoverObjectKey { + at: vectorcraft_geom::Point, + mods: vectorcraft_tools::Mods, + doc: (u64, u64), + selection: vectorcraft_doc::Selection, + isolation: Option, + options: serde_json::Value, + paint: vectorcraft_tools::PaintDefaults, + fill_active: bool, + stop: Option, + tolerance: f64, + eyedropper: vectorcraft_engine::EyedropperOptions, + guides: (bool, bool), + zoom: f64, + outline: bool, +} + +/// [`vectorcraft_engine::Session::hover_object`] at `at`, found again only when its +/// [`HoverObjectKey`] changes: over an image, or with Shift held, finding it samples a color. +fn eyedropper_hover_object( + app: &mut VectorcraftApp, + at: vectorcraft_geom::Point, + mods: vectorcraft_tools::Mods, + view: vectorcraft_engine::ViewInfo, +) -> Option { + let st = app.session.active()?; + let key = HoverObjectKey { + at, + mods, + doc: (st.uid, st.revision), + selection: st.selection.clone(), + isolation: st.isolation, + options: app.session.tool_options(), + paint: app.session.paint.clone(), + fill_active: app.session.fill_active, + stop: app.session.selected_stop(), + tolerance: app.session.prefs.selection_tolerance, + eyedropper: app.session.prefs.eyedropper, + guides: (view.guides, app.session.guides_locked()), + zoom: view.zoom, + outline: view.outline, + }; + if let Some((k, id)) = &app.canvas.hover_object + && *k == key + { + return *id; + } + let id = app.session.hover_object(at, mods, view); + app.canvas.hover_object = Some((key, id)); + id +} + /// Draw Inside (Shift+D): while the mode lasts, a dotted open rectangle round the corners of the /// object drawn into, selected or not (#4319). pub(super) fn draw_inside_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..1a714ccfe6 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6096,6 +6096,142 @@ fn object_highlighting_preference_hides_the_hover_outline() { assert_eq!(outlines(&mut app), 0, "Smart Guides off"); } +/// The screen points of the 1.5 px hover outlines in `color` that one frame with `held` keys down +/// draws, the pointer where the last frame left it. +fn hover_outline_points(app: &mut VectorcraftApp, ctx: &egui::Context, color: Color32, held: egui::Modifiers) -> Vec { + fn flat(s: Shape, out: &mut Vec) { + match s { + Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)), + s => out.push(s), + } + } + app.canvas.selection_marks = Default::default(); + let events = vec![egui::Event::ModifiersChanged(held)]; + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + // The art's raster lands in some frame when the render worker is done with it. + out.textures_delta.clear(); + let mut shapes = vec![]; + out.shapes.into_iter().for_each(|c| flat(c.shape, &mut shapes)); + let solid = egui::epaint::ColorMode::Solid(color); + let mut at = vec![]; + for s in shapes { + if let Shape::Path(ps) = s + && ps.stroke.width == 1.5 + && ps.stroke.color == solid + { + at.extend(ps.points); + } + } + at +} + +/// The screen box around `points`. +fn screen_box(points: &[Pos2]) -> egui::Rect { + points.iter().fold(egui::Rect::NOTHING, |r, p| r.union(egui::Rect::from_min_max(*p, *p))) +} + +/// Whether two screen boxes agree to within a pixel. +fn same_box(a: egui::Rect, b: egui::Rect) -> bool { + (a.min - b.min).length() < 1.0 && (a.max - b.max).length() < 1.0 +} + +/// With the Eyedropper, Smart Guides › Object Highlighting outlines the object under the pointer +/// as the selection tools do (1.5 px in its layer color), and nothing over empty canvas. +#[test] +fn eyedropper_hover_outlines_the_object_under_the_pointer() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("eyedropper"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let color = c32(app.session.active().unwrap().doc.layer_color(vectorcraft_doc::NodeId(id))); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(Point::new(150.0, 150.0)))]); + let at = hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE); + let rect = egui::Rect::from_two_pos(xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(200.0, 200.0))); + assert!(!at.is_empty() && same_box(screen_box(&at), rect), "the rectangle under the pointer is outlined: {:?}", screen_box(&at)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(Point::new(300.0, 50.0)))]); + assert!(hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE).is_empty(), "nothing over empty canvas"); + // Space lends the view tools: a press pans, so no object is outlined, with any tool. + let space = |pressed| egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + for tool in ["eyedropper", "selection"] { + app.select_tool(tool); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(Point::new(150.0, 150.0)))]); + assert!(!hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE).is_empty(), "{tool}: outlined"); + frame(&mut app, &ctx, vec![space(true)]); + assert!(hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE).is_empty(), "{tool}: Space held"); + frame(&mut app, &ctx, vec![space(false)]); + assert!(!hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE).is_empty(), "{tool}: Space let go"); + } +} + +/// The Eyedropper's hover outline follows Smart Guides › Object Highlighting. +#[test] +fn eyedropper_hover_outline_follows_object_highlighting() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("eyedropper"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let color = c32(app.session.active().unwrap().doc.layer_color(vectorcraft_doc::NodeId(id))); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(Point::new(150.0, 150.0)))]); + app.session.execute("prefs.set", &json!({"key": "objectHighlighting", "value": false})).unwrap(); + assert!(hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE).is_empty(), "the option off"); + app.session.execute("prefs.set", &json!({"key": "objectHighlighting", "value": true})).unwrap(); + assert!(!hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE).is_empty(), "the option on"); +} + +/// The Eyedropper outlines the object its click there then acts on: the front object a plain +/// click copies attributes from, a locked one included (the Eyedropper reads locked art), and with +/// Alt the unlocked object below it that an Alt-click gives the selection's attributes to. +#[test] +fn eyedropper_hover_outline_is_the_object_the_click_acts_on() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let rect = |app: &mut VectorcraftApp, x: f64, y: f64, size: f64, color: &str| { + let id = app.session.execute("shape.rectangle", &json!({"x": x, "y": y, "width": size, "height": size})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("paint.setFill", &json!({"ids": [id], "color": color})).unwrap(); + id + }; + let back = rect(&mut app, 100.0, 100.0, 100.0, "#0000ff"); + let front = rect(&mut app, 150.0, 150.0, 100.0, "#ff0000"); + let target = rect(&mut app, 20.0, 20.0, 40.0, "#00ff00"); + app.session.execute("select.set", &json!({"ids": [target]})).unwrap(); + app.select_tool("eyedropper"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let color = c32(app.session.active().unwrap().doc.layer_color(vectorcraft_doc::NodeId(front))); + let boxed = |x: f64, y: f64, size: f64| egui::Rect::from_two_pos(xf.to_screen(Point::new(x, y)), xf.to_screen(Point::new(x + size, y + size))); + let fill = |app: &VectorcraftApp, id: u64| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint(); + let over = xf.to_screen(Point::new(175.0, 175.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(over)]); + let at = hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE); + assert!(same_box(screen_box(&at), boxed(150.0, 150.0, 100.0)), "the front rectangle is outlined: {:?}", screen_box(&at)); + click_at(&mut app, &ctx, over); + assert_eq!(fill(&app, target), fill(&app, front), "the click copied the outlined rectangle's fill"); + + app.session.execute("object.lock", &json!({"ids": [front]})).unwrap(); + app.session.execute("select.set", &json!({"ids": [target]})).unwrap(); + app.session.execute("paint.setFill", &json!({"ids": [target], "color": "#00ff00"})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(over)]); + let at = hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE); + assert!(same_box(screen_box(&at), boxed(150.0, 150.0, 100.0)), "the locked front rectangle is still the source: {:?}", screen_box(&at)); + let at = hover_outline_points(&mut app, &ctx, color, egui::Modifiers::ALT); + assert!(same_box(screen_box(&at), boxed(100.0, 100.0, 100.0)), "with Alt, the unlocked rectangle below: {:?}", screen_box(&at)); + let button = |pressed| egui::Event::PointerButton { pos: over, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; + frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::ALT), button(true)]); + frame(&mut app, &ctx, vec![button(false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + assert_eq!(fill(&app, back), fill(&app, target), "the Alt-click gave the outlined rectangle the selection's fill"); + assert_ne!(fill(&app, front), fill(&app, target)); +} + /// Hide Corner Widget for angles greater than (#394): a rectangle's 90° corners lose their /// widgets below 90°. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..143f215fcd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2015,6 +2015,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pasting into hex color fields:** in the hex fields of the Color Picker, Swatch Options, Recolor Artwork, the Color panel, Document Setup, Duotone, Color Themes and Perspective Grid, a click or keyboard focus selects the digits. A pasted code of six digits, with or without `#`, replaces them wherever the caret is. A pasted code of three digits also replaces them, unless the paste holds only those digits and exactly three digits stay; those digits then edit the text in place. A press on another field commits the text as Tab and Enter do. As VectorCraft's own rule, a paste that is not a color leaves the field as it was. Tests: `a_hex_code_pasted_into_the_hex_field_replaces_its_digits` in `crates/ui-egui/src/dialogs/tests.rs`, `define_grid_takes_a_three_digit_color` in `crates/ui-egui/src/dialogs/tests_perspective.rs` and `a_paste_into_a_hex_field_replaces_or_edits_its_digits` in `crates/ui-egui/src/tests/numfields.rs`. - **Color Picker layout (#2008):** a centered draggable header, equal-width actions above aligned HSB/RGB/Hex and Lab/CMYK fields, compact field and slider, and warnings below the preview. No horizontal scrolling; narrow windows stack the sections with vertical scrolling. Tests in `dialogs/color_picker.rs` cover actual pointer/key input, typed values before OK/Enter, Cancel/Escape rollback, one Undo step, mode-size stability, warnings and layout at two UI scales. The screen sampler sits above the field and the upstream two-grid Tab order is retained. AccessKit regressions check the action names and each channel slider's displayed value, units and range. German and enlarged English UI renders were reviewed locally; no reference images are shipped. This is a layout improvement, with no change to scores or remaining-hour estimates. - **Eyedropper sources (#1251):** ordinary and Shift clicks, Shift+Alt appearance append, raster pixels and gradient-stop sampling can read visible locked/template art and sources outside isolation. Sampling leaves the source and selection intact; Alt reverse still uses editable hits, and hidden art stays excluded. Engine/tool/hit regressions cover the editing boundary, color models and one-step Undo/Redo. The general object/image workflow is described in [public HelpX](https://helpx.adobe.com/illustrator/using/tool-techniques/eyedropper-tool.html); the lock/isolation expectations come from the user report and these regressions, without a new full-parity measurement. + - **Eyedropper hover outline:** as VectorCraft's own behavior, with Smart Guides › Object Highlighting on, the Eyedropper outlines the object a click at the pointer would act on, in the selection tools' 1.5 px layer-color outline: the source a click copies from (locked and template art included), the selected gradient mesh a click recolors, the object below a locked one that an Alt-click gives the selection's attributes to, and for a Shift-click the object whose color is sampled (a blend or envelope where its art is drawn, the art below where it leaves a gap). A selected object is outlined too. Empty canvas, hidden art and a Cmd-click that borrows a selection tool show no outline, and with the Eyedropper or a selection tool, Space held for the view tools hides the outline. Tests: `crates/ui-egui/src/canvas/tests.rs`, `crates/tools/src/xform/eyedropper.rs`. - **Eyedropper colors in a CMYK document (#2276):** a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's pixel or an RGB color given to `paint.setFill`, `paint.setStroke`, `paint.sampleColor` or `swatch.new {color}` (hex input and gradient stops included) is separated through the color settings' CMYK working space and intent, as Document Color Mode converts it. With the default Generic CMYK, RGB 83/170/223 separates to C62 M19 Y0 K0, where the profile-free formula gave C63 M24 Y0 K13. - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). The ICC profile written for it (embedded in exports) gives the paper as its media white point, and its colorimetric Lab → CMYK table is the inverse of its CMYK → Lab table, without black-point compensation; the perceptual and saturation tables keep compensation. From a321546b4a36c406345f38d519c47d4dcd05018b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:40:50 -0800 Subject: [PATCH 04/55] Links: the Location row in Link Info has a button that shows the file in its folder Link Info's Location row gets a folder button, Show in Folder, that runs links.reveal with the id of the image Link Info shows, so the system's file manager opens that file's folder. The button is off while the file is missing and when no file manager is available (the web build). An embedded image has no Location row and no button. The help page describes a folder icon on this row that opens the file's folder: https://helpx.adobe.com/illustrator/using/links-info.html The button's name and its off state are VectorCraft's own. --- crates/ui-egui/src/panels/doc_info.rs | 6 +++ crates/ui-egui/src/panels/links.rs | 20 +++++--- crates/ui-egui/src/panels/tests_links.rs | 64 ++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 4 files changed, 85 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index ed6bdcdaab..83e45e4151 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -22,10 +22,16 @@ struct Cache { /// A `label: value` row. `label` is shown as given: translate an interface label first, a name /// stays as it is. pub(crate) fn row(ui: &mut Ui, label: &str, value: String) { + row_with(ui, label, value, |_| {}); +} + +/// A [`row`] with `end` drawn at its right end, after the value. +pub(crate) fn row_with(ui: &mut Ui, label: &str, value: String, end: impl FnOnce(&mut Ui)) { let t = Tokens::get(ui.ctx()); ui.horizontal(|ui| { ui.label(egui::RichText::new(label).size(12.0).color(t.text_dim)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + end(ui); // Long values (paths) are cut to the panel's width; hovering shows them whole. ui.add(egui::Label::new(egui::RichText::new(value).size(12.0).color(t.text)).truncate()); }); diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 4c491efb6b..a3962ade38 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -3,7 +3,8 @@ //! its image, Ctrl/Cmd-click adds or removes it, and Shift-click selects the images of the rows //! from the last row clicked without Shift to it (with Ctrl/Cmd, adds them); the buttons Relink, //! Go To, Update and Edit Original act on the selected rows (Relink through its dialog, with the -//! Replace choice: `ui.relinkDialog`); Link Info shows the details of the first. The flyout adds Relink to Folder, Find in Folder (Find Linked Files: +//! Replace choice: `ui.relinkDialog`); Link Info shows the details of the first, with a Show in +//! Folder button on its Location row. The flyout adds Relink to Folder, Find in Folder (Find Linked Files: //! `ui.findLinksInFolder`), Embed / Unembed, Placement Options, Select Linked / Embedded / Missing / //! Modified (`addon.select.byLinkStatus`, Shift adds), Show filters, Sort, Copy Info (the selected //! rows' file names to the clipboard: `links.copyInfo`), thumbnail size, Show in Folder and Show DCS Transparency Interactions (a warning on the rows of images placed @@ -721,7 +722,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } if o.info { let units = app.session.general_unit(); - link_info(ui, cache.info.as_ref().map(|(_, i)| i), units); + link_info(app, ui, cache.info.as_ref().map(|(id, i)| (*id, i)), units); } let sel = selected_rows(&cache.list, &selected); let modified = ids(&sel, |r| status_is(r, "modified") || r["preview"] == true && !status_is(r, "missing")); @@ -876,10 +877,10 @@ pub(crate) fn date_label(ms: u64) -> String { format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02} UTC") } -/// The Link Info section: the details of `info` (`links.info`), or a hint. -fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { +/// The Link Info section: the details of `info` (`links.info` of image `id`), or a hint. +fn link_info(app: &mut VectorcraftApp, ui: &mut Ui, info: Option<(u64, &Value)>, units: vectorcraft_doc::Unit) { widgets::divider(ui); - let Some(i) = info else { + let Some((id, i)) = info else { widgets::dim_label(ui, tl!("Select an image to see its Link Info.")); return; }; @@ -896,7 +897,14 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { row(ui, tl!("Format"), i["format"].as_str().unwrap_or_default().into()); row(ui, tl!("Color Space"), i["colorMode"].as_str().unwrap_or_default().into()); if let Some(l) = i["location"].as_str() { - row(ui, tl!("Location"), l.into()); + // Show in Folder for the image shown here: off while its file is missing and without a + // file manager (the web). + let can_reveal = i["path"].is_string() && i["status"] != "missing" && app.services.reveal.is_some(); + super::doc_info::row_with(ui, tl!("Location"), l.into(), |ui| { + if widgets::icon_button_enabled(ui, "folder-open", tl!("Show in Folder"), false, can_reveal, 18.0).clicked() { + crate::menus::invoke(app, "links.reveal", json!({ "id": id })); + } + }); } // A placed document has no resolution: its rows are left out. for (label, k) in [(tl!("PPI"), "ppi"), (tl!("Effective PPI"), "effectivePpi")] { diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 85a26e557a..1494b75925 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -558,6 +558,70 @@ fn edit_original_and_show_in_folder_hand_the_file_to_the_system() { assert!(app.run("links.editOriginal", json!({"id": linked})).is_err()); } +/// Frames of the panel in a fresh context (Link Info read anew), the pointer clicking the middle of +/// the button that screen readers name `name` → whether that button was on, or `None` when it was +/// not drawn. +fn click_panel_button(app: &mut VectorcraftApp, name: &str) -> Option { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), ..Default::default() }, |ui| super::links::show(app, ui)); + out.textures_delta.clear(); + out + }; + frame(app, vec![]); + let out = frame(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = &nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::Button && n.label() == Some(name))?.1; + let on = !node.is_disabled(); + let b = node.bounds().expect("bounds"); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(app, vec![egui::Event::PointerMoved(at)]); + frame(app, vec![button(true)]); + frame(app, vec![button(false)]); + Some(on) +} + +/// The Location row of Link Info has a Show in Folder button that shows the file of the image Link +/// Info shows. An embedded image has no Location row; the button is off while the file is missing +/// and without a file manager (the web). +#[test] +fn link_infos_location_row_shows_the_file_in_its_folder() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let dir = Folder::new("location-reveal"); + let (mut app, linked, embedded) = app(&dir); + let other = dir.file("other.png", &png(30, 20)); + let other = app.run("file.place", json!({"path": other, "at": [50, 50]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("select.set", json!({"ids": [embedded]})).unwrap(); + let revealed: Rc>> = Rc::default(); + let r = revealed.clone(); + app.services.reveal = Some(Box::new(move |p: &str| { + r.borrow_mut().push(p.to_string()); + Ok(()) + })); + let path = |app: &mut VectorcraftApp, id: u64| app.run("links.info", json!({"id": id})).unwrap()["path"].as_str().unwrap().to_string(); + let (linked_path, other_path) = (path(&mut app, linked), path(&mut app, other)); + // An embedded image has no file to show. + assert_eq!(click_panel_button(&mut app, "Show in Folder"), None); + app.run("select.set", json!({"ids": [linked]})).unwrap(); + assert_eq!(click_panel_button(&mut app, "Show in Folder"), Some(true)); + app.run("select.set", json!({"ids": [other]})).unwrap(); + assert_eq!(click_panel_button(&mut app, "Show in Folder"), Some(true)); + assert_eq!(*revealed.borrow(), [linked_path, other_path.clone()]); + // A missing file: the row stays, the button is off. + std::fs::remove_file(&other_path).unwrap(); + assert_eq!(click_panel_button(&mut app, "Show in Folder"), Some(false)); + // Without a file manager (the web): off. + app.run("select.set", json!({"ids": [linked]})).unwrap(); + app.services.reveal = None; + assert_eq!(click_panel_button(&mut app, "Show in Folder"), Some(false)); + assert_eq!(revealed.borrow().len(), 2, "nothing more was shown"); +} + /// #5236: with Preferences › File Handling › Use System Defaults for Edit Original off, Edit /// Original opens a raster image in the app that made it, PhotoCraft, and falls back to the /// system's default app when PhotoCraft isn't installed or the file isn't a raster image. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..86edfe41d6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1387,6 +1387,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. The Links panel provides an item right-click context menu on link rows offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Separator, and Embed Image / Unembed…. Right-clicking an unselected row selects that row first; right-clicking a row that is already part of a multi-selection preserves the multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. + The Location row of the Links panel's Link Info has a folder button, Show in Folder, that opens the folder of the file Link Info shows in the system's file manager (`links.reveal {id}` with that image's id); the help page describes a folder icon on this row ([Links information](https://helpx.adobe.com/illustrator/using/links-info.html)). The button's name and its off state while the file is missing or no file manager is available (the web build) are VectorCraft's own. Tests: `panels::tests_links::link_infos_location_row_shows_the_file_in_its_folder`. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345). When a clip group, a layer with a clipping mask or a single object in one is isolated, the Selection, Direct Selection and Group Selection tools also select the art that the mask hides, by a click or a marquee, and a drag from that art moves it (#3748). In isolation mode the canvas Unlock submenu also lists that art when it is locked. Outside isolation mode a click selects clipped art only inside the mask. A marquee selects a Shaper Group only when it reaches the art the group shows, not the original shapes kept under it, and Direct Selection's clicks and marquee do not select those shapes' anchor points. In Construction mode a marquee selects the original shapes, and Direct Selection selects their anchor points. From 7703c42c31d4be27ba9a09e712a84eb969488adc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:08:28 -0800 Subject: [PATCH 05/55] OpenType: Proportional Metrics in the panel menu with the East Asian options With Show East Asian Options on, the OpenType panel menu has a Proportional Metrics item before H or V Style. The help page (https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) lists it among the OpenType panel options that this setting shows. The item sets the proportionalMetrics character attribute that the Character panel menu's item sets (palt in horizontal type, vpal in vertical type), through text.setFormat for selected type and text.setRangeStyle while the Type tool edits text. It is checked when every character it changes has the attribute, read like H or V Style and Roman Italics (at a caret, every character of the text), and a click turns it on for all of them, or off when checked, in one undo step. It is disabled with no type selected. Its place in the menu and the check rule are VectorCraft's own. Docs: docs/target-app-parity.md, docs/type-parity.md, docs/mcp.md. --- crates/ui-egui/src/panels/opentype.rs | 124 ++++++++++++++++++++++++-- docs/mcp.md | 5 +- docs/target-app-parity.md | 1 + docs/type-parity.md | 1 + 4 files changed, 125 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 4cfcb27e89..e52c852afb 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -1,7 +1,8 @@ //! OpenType panel: per-character OpenType features (ligatures, alternates, swashes, small caps, //! ordinals, fractions, figure style, position, stylistic sets from the panel or its menu, and with -//! the East Asian options the menu's H or V Style and Roman Italics) for the selected text (every -//! frame of each selected threaded story) or the Type tool's selected characters. +//! the East Asian options the menu's Proportional Metrics, H or V Style and Roman Italics) for the +//! selected text (every frame of each selected threaded story) or the Type tool's selected +//! characters. use egui::Ui; use serde_json::json; @@ -123,19 +124,24 @@ fn shown_figure(app: &VectorcraftApp) -> Option { /// threaded story, the command styles all the text ([`run_features`]), so every character of it /// counts, as in [`edit`]. fn shown_flag(app: &VectorcraftApp, flag: Flag) -> Option { - let on = |s: &CharStyle| flag.get(&OtFeatures::from_tags(s.features.iter().map(String::as_str))); + shown(app, |s| flag.get(&OtFeatures::from_tags(s.features.iter().map(String::as_str)))) +} + +/// Whether `on` holds for every character a menu item changes (`Some(true)`), for none of them +/// (`Some(false)`), or only for some (`None`), read as [`shown_flag`] reads a feature. +fn shown(app: &VectorcraftApp, on: impl Fn(&CharStyle) -> bool) -> Option { if let Some(mut runs) = whole_text_runs(app) { // A run with no text, such as an empty frame's, counts only when no run has text. if runs.iter().any(|r| !r.text.is_empty()) { runs.retain(|r| !r.text.is_empty()); } let Some(first) = runs.first() else { - return shared(app, on); + return shared(app, &on); }; let v = on(&first.style); return runs.iter().all(|r| on(&r.style) == v).then_some(v); } - shared(app, on) + shared(app, &on) } /// The runs the panel's commands style as a whole while the Type tool edits text: those of every @@ -378,6 +384,14 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if app.session.prefs.show_east_asian_options { ui.separator(); // Checked when every character it changes has it; chosen then, it turns it off. + // Proportional Metrics: full-width glyphs on the font's proportional widths (`palt`, `vpal`), + // the character attribute the Character panel menu's item sets. + let proportional = shown(app, |s| s.proportional_metrics) == Some(true); + if menu_item(ui, tl!("Proportional Metrics"), has, proportional) + && let Err(e) = super::character::run_format(app, json!({"proportionalMetrics": !proportional})) + { + app.ui.status = e; + } for (label, flag) in east_asian_items() { let on = shown_flag(app, flag) == Some(true); if menu_item(ui, label, has, on) { @@ -957,4 +971,104 @@ mod tests { assert!(runs.iter().all(|(_, f)| !f.as_array().is_some_and(|f| f.iter().any(|x| x == tag))), "{label}: {runs:?}"); } } + + /// The text, Proportional Metrics and features of each run of `id`. + fn metrics_runs(app: &VectorcraftApp, id: &Value) -> Vec<(String, bool, Vec)> { + let Some(id) = id.as_u64() else { panic!("no id: {id}") }; + match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.proportional_metrics, r.style.features.clone())).collect(), + _ => panic!("not text"), + } + } + + /// The drawn text and rect of the panel menu's `label` item. + fn menu_row(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) -> (String, egui::Rect) { + let texts = super::super::tests_appearance::frame_events(ctx, app, vec![], menu); + texts.into_iter().find(|(t, _)| t.trim_start_matches(['✓', ' ']) == label).unwrap_or_else(|| panic!("{label} missing")) + } + + /// Proportional Metrics is in the panel menu with the East Asian options only, before H or V + /// Style, and with no type selected it is disabled: a click changes nothing. + #[test] + fn proportional_metrics_shows_with_the_east_asian_options() { + let mut app = selected_text(); + assert!(!crate::tests_labels::painted_text(&mut app, menu).contains("Proportional Metrics")); + app.session.prefs.show_east_asian_options = true; + let text = crate::tests_labels::painted_text(&mut app, menu); + let (Some(metrics), Some(kana)) = (text.find("Proportional Metrics"), text.find("H or V Style")) else { panic!("{text}") }; + assert!(metrics < kana, "{text}"); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + let ctx = egui::Context::default(); + let (text, at) = menu_row(&ctx, &mut app, "Proportional Metrics"); + assert!(!text.starts_with('✓'), "{text:?}"); + let undo = undo_steps(&app); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert_eq!(undo_steps(&app), undo, "no text: nothing changes"); + } + + /// With the Type tool's characters only partly set, Proportional Metrics shows unchecked; + /// chosen, it turns on for every selected character in one undo step, each run keeping its + /// features, and shows checked; chosen again, it turns off in one undo step. + #[test] + fn proportional_metrics_turns_on_and_off_for_a_mixed_range() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.prefs.show_east_asian_options = true; + app.session.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "かなAB"})).unwrap()["id"].clone(); + let first = json!({"id": id, "start": 0, "end": 3, "features": ["smcp"], "proportionalMetrics": true}); + app.session.execute("text.setRangeStyle", &first).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + // "かなAB" is 8 bytes. + app.session.set_tool_option("select", &json!({"start": 0, "end": 8})); + let ctx = egui::Context::default(); + let (text, at) = menu_row(&ctx, &mut app, "Proportional Metrics"); + assert!(!text.starts_with('✓'), "{text:?}"); + let undo = undo_steps(&app); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert_eq!(undo_steps(&app), undo + 1); + let runs = metrics_runs(&app, &id); + assert!(runs.iter().all(|(_, on, _)| *on), "{runs:?}"); + assert_eq!(runs.iter().map(|(t, _, f)| (t.as_str(), f.clone())).collect::>(), [("か", vec!["smcp".to_string()]), ("なAB", vec![])]); + let (text, at) = menu_row(&ctx, &mut app, "Proportional Metrics"); + assert!(text.starts_with('✓'), "{text:?}"); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert_eq!(undo_steps(&app), undo + 2); + let runs = metrics_runs(&app, &id); + assert!(runs.iter().all(|(_, on, f)| !*on && (f.is_empty() || *f == ["smcp"])), "{runs:?}"); + } + + /// With the Selection tool, Proportional Metrics turns on for the whole selected object. At a + /// Type tool caret after a character that has it while the rest of the text does not, the item + /// reads every character the command styles at a caret (all of them): it shows unchecked, and + /// choosing it turns it on for the whole text. + #[test] + fn proportional_metrics_reaches_a_selected_object_and_the_text_at_a_caret() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.prefs.show_east_asian_options = true; + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "かなAB"})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let ctx = egui::Context::default(); + let at = menu_row(&ctx, &mut app, "Proportional Metrics").1; + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert!(metrics_runs(&app, &id).iter().all(|(_, on, _)| *on), "{:?}", metrics_runs(&app, &id)); + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.prefs.show_east_asian_options = true; + app.session.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "かなAB"})).unwrap()["id"].clone(); + app.session.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 3, "proportionalMetrics": true})).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + // The caret after "か", whose style the next typed character takes. + app.session.set_tool_option("select", &json!({"start": 3, "end": 3})); + assert_eq!(text_editing(&app).map(|(_, a, b)| (a, b)), Some((3, 3))); + let ctx = egui::Context::default(); + let (text, at) = menu_row(&ctx, &mut app, "Proportional Metrics"); + assert!(!text.starts_with('✓'), "{text:?}"); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + let runs = metrics_runs(&app, &id); + assert!(runs.iter().all(|(_, on, _)| *on), "{runs:?}"); + } } diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..d7322cd219 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12405,7 +12405,10 @@ a font without vertical metrics keeps its cells. Line-end Punctuation Half Width punctuation `palt` or `vpal` re-spaced (the opening bracket at a line's start, consecutive punctuation, the closing mark at a line's end); punctuation left full width is trimmed as before. With automatic kerning the font's kerning for the re-spaced glyphs comes too: `apkn` with `palt`, and `vkrn` and `vapk` with `vpal` (vertical type is otherwise -not kerned). Off by default and saved only when on. One undo step. +not kerned). Off by default and saved only when on. One undo step. With Show East Asian Options on, the Character +panel menu and the OpenType panel menu ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)) +each have a Proportional Metrics item that sends this attribute; the OpenType panel's item is checked when every +character it changes has it. ```json {"name":"run_command","arguments":{"command":"text.setFormat","params":{"proportionalMetrics":true}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..676106a205 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1765,6 +1765,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu shows the first selected character's font's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft design choice. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). The OpenType panel menu has a Stylistic Sets submenu after Reset OpenType Features, with the same sets, labels and checks as the panel's Stylistic Sets button; a set chosen there turns on or off for the characters the panel acts on in one undo step, keeping their other features, and the submenu is disabled with no text selected or when the font offers no sets. The 2019 user guide ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) has stylistic sets chosen from the OpenType panel menu. The submenu's place in the menu is VectorCraft's own. Tests: `panels::opentype::tests::the_panel_menu_stylistic_sets_submenu_turns_sets_on_and_off`. With Show East Asian Options on, the OpenType panel menu has H or V Style and Roman Italics, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes. H or V Style sets the feature tag `hkna`, which draws kana with the forms the font makes for horizontal type, and with `vkna` for vertical type in vertical type; Roman Italics sets `ital`, the font's italic forms of half-width alphanumerics ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). Each is checked when every selected character has it and turns it on or off for all of them in one undo step; character styles carry both in OpenType Features. Tests: `panels::opentype::tests::kana_style_and_roman_italics_turn_on_and_off`, `features::tests::kana_style_and_roman_italics_are_kept_and_shaped`. + With Show East Asian Options on, the OpenType panel menu also has Proportional Metrics, before H or V Style; [the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) lists it among the OpenType panel options that this setting shows. It sets the `proportionalMetrics` character attribute that the Character panel menu's item sets (`palt` in horizontal type, `vpal` in vertical type), through `text.setFormat` for selected type and `text.setRangeStyle` while the Type tool edits text. It is checked when every character it changes has the attribute (at a Type tool caret, every character of the text), and choosing it turns the attribute on for all of them, or off when it is checked, in one undo step, keeping their other attributes; with no type selected it is disabled. Its place in the menu and the check rule are VectorCraft's own. Tests: `panels::opentype::tests::proportional_metrics_turns_on_and_off_for_a_mixed_range`, `panels::opentype::tests::proportional_metrics_reaches_a_selected_object_and_the_text_at_a_caret`. `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). diff --git a/docs/type-parity.md b/docs/type-parity.md index 111ee5d838..6855ba364b 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -35,6 +35,7 @@ against Illustrator's public documentation; **estimated** unless noted. | OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges and Alternates for Current Selection, the selected character's alternate glyphs from the font's `GSUB` table. A double-click applies the OpenType feature that draws a variant to that character alone, or uses a glyph choice when no supported feature draws it; see the Glyphs panel row below for Entire Font and the joining limits. A grid cell whose glyph has alternates shows a triangle in its lower right corner; a click on it opens a pop-up of that glyph and its alternates in the font's order, and a pick inserts the character at the caret drawn with that glyph, or draws the selected character with it, in one undo step; in Entire Font a glyph no character maps has the triangle too, and a pick goes on the selected character as a double-click on that glyph's cell does ([CS6 reference, Glyphs panel overview](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=373)); the triangle's size and the pop-up's eight columns and six rows are VectorCraft's own (`panels::glyphs` tests `a_cells_corner_triangle_opens_its_alternates_and_a_pick_inserts_one`, `a_pick_replaces_the_selected_character_and_says_why_when_it_cannot`, `a_pick_that_cannot_be_drawn_leaves_the_text_as_it_was`, `an_unencoded_glyphs_corner_triangle_applies_its_alternates_to_the_selection`; `has_alternates_follows_the_listed_substitutions` in the text crate) | | Glyphs panel: alternates as OpenType feature values, unencoded glyphs | done | #5514, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Show › Alternates For Current Selection; replace the selected character by double-clicking the glyph). A character-style feature takes a value (`"salt=2"`, the font's alternate number; `ss01`–`ss20`, `swsh`, `titl` and `aalt` too) in `features` and `featureChanges`, in SVG `font-feature-settings` (`"salt" 2`) and in native files as the plain string. Show › Entire Font applies an unencoded glyph the same way when it is an alternate of the selected character in its word, applies one no feature reaches (`A.salt` in a font with no `salt`) to the selected character as a glyph choice (it may not join), and dims the others with the reason in the tooltip (e.g. `yehfarsi.fina.alt2 belongs to ی (U+06CC) at the end of a word; your selection is ي (U+064A)`); an Arabic presentation form picked there inserts its letter so the word joins. Runs that differ only in their features shape as one piece of text, each run's features over its own characters, so a variant on one letter of an Arabic word keeps its neighbours' initial, medial and final forms and the letters still touch. The panel lists the alternates of the glyph the shaper makes for the selected character in its word (a medial letter shows medial variants), and a double-click applies the OpenType feature that draws the variant (`salt=N` or `ssNN`) to that character alone, in one undo step (`text.setRangeStyle`); a variant no feature reaches falls back to a replacement glyph (`text.setGlyphAlternate`), which its tooltip says may not join. Show › Entire Font also lists the glyphs no character maps, with their name or `gid N` and the feature that gives them. The text crate reads each face's `GSUB` once (alternate sets, single substitutions, the feature that reaches a glyph). Not done: alternates reached through contextual or ligature lookups, and features of the font that the style has no tag for (`cv01`–`cv99`, `hist`). Evidence: `tests::glyph_alternates` in the text crate (a fixture font with a medial teh at `salt=1` to `3`, the neighbours' forms, no gap; Kufi Murabba PIIIX when it is installed), `features::tests::feature_values_are_parsed_validated_and_shaped`, `tests::textedit::feature_values_are_set_replaced_and_saved`, the `panels::glyphs` tests. | | OpenType panel menu: H or V Style, Roman Italics | done | With Show East Asian Options, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes: H or V Style is the character feature `hkna` (kana in the font's horizontal forms, shaped as `vkna` in vertical type) and Roman Italics is `ital` (the font's italic half-width alphanumerics), set with `text.setStyle` / `text.setRangeStyle {features, featureChanges}`, on or off only, and in Character Style Options › OpenType Features ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). | +| OpenType panel menu: Proportional Metrics | done | With Show East Asian Options, before H or V Style ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) lists it among the OpenType panel options): the `proportionalMetrics` character attribute of `text.setFormat` / `text.setRangeStyle`, as the Character panel menu's item sets it. | | Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice); Show Similar Fonts: the ≈ button on a family's row lists the families that look like it first ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)), by VectorCraft's own measure of PANOSE, weight, width, heights, average width and italic angle, same script first, a family sharing none of these numbers with it last in its group (VectorCraft's own rule), and the ≈ chip under the filters clears it (`text.similarFonts`; evidence: `font_menu::tests::show_similar_fonts_orders_the_list_by_likeness`, `tests::similar::families_are_ordered_by_likeness`, `tests::similar::a_family_without_numbers_comes_after_the_measured_ones`). | | Missing glyphs set in an installed font made for their script (Thai, Lao, Khmer, Myanmar first; then any font that has them) | done | Thai: Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai, TLWG | | Full font-name matching (OpenType name ID 4) | done | #1258: loaded/cataloged faces and Missing Fonts searches; localized names and variable default faces; Windows font-service QA pending | From 5c46288a71f8b13c7706722f61a6de670a99a3c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:34:06 -0800 Subject: [PATCH 06/55] i18n: file pickers name Tracing presets, Action sets and Composite fonts in every language The Edit > Tracing Presets... Import and Export pickers and the save panel showed the Tracing presets, Action sets and Composite fonts file types in English in every language: no catalog had a row for them. Each catalog now has a file-filter row for the three, made from its own Tracing Presets, Action Set and Composite Fonts terms, and the Gujarati catalog gains its missing Perspective grid presets row. The Hindi file-filter block also names Export presets as a noun instead of as an instruction, and All readable files in the plain plural form. save_panel_file_types_are_in_complete_catalogs checks that every complete catalog translates each file type in the save panel's list. --- crates/ui-egui/src/i18n/bg.tsv | 3 +++ crates/ui-egui/src/i18n/bs.tsv | 3 +++ crates/ui-egui/src/i18n/ca.tsv | 3 +++ crates/ui-egui/src/i18n/cs.tsv | 3 +++ crates/ui-egui/src/i18n/da.tsv | 3 +++ crates/ui-egui/src/i18n/de.tsv | 3 +++ crates/ui-egui/src/i18n/el.tsv | 3 +++ crates/ui-egui/src/i18n/es.tsv | 3 +++ crates/ui-egui/src/i18n/fi.tsv | 3 +++ crates/ui-egui/src/i18n/fr.tsv | 3 +++ crates/ui-egui/src/i18n/gu.tsv | 4 ++++ crates/ui-egui/src/i18n/hi.tsv | 7 +++++-- crates/ui-egui/src/i18n/hu.tsv | 3 +++ crates/ui-egui/src/i18n/id.tsv | 3 +++ crates/ui-egui/src/i18n/it.tsv | 3 +++ crates/ui-egui/src/i18n/ja.tsv | 3 +++ crates/ui-egui/src/i18n/ka.tsv | 3 +++ crates/ui-egui/src/i18n/ko.tsv | 3 +++ crates/ui-egui/src/i18n/nl.tsv | 3 +++ crates/ui-egui/src/i18n/pl.tsv | 3 +++ crates/ui-egui/src/i18n/pt-br.tsv | 3 +++ crates/ui-egui/src/i18n/ru.tsv | 3 +++ crates/ui-egui/src/i18n/sv.tsv | 3 +++ crates/ui-egui/src/i18n/tests.rs | 19 +++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 3 +++ crates/ui-egui/src/i18n/uk.tsv | 3 +++ crates/ui-egui/src/i18n/vi.tsv | 3 +++ crates/ui-egui/src/i18n/zh-hans.tsv | 3 +++ crates/ui-egui/src/i18n/zh-hant.tsv | 3 +++ crates/ui-egui/src/io.rs | 2 ++ crates/ui-egui/src/io/save.rs | 2 +- docs/target-app-parity.md | 1 + 32 files changed, 110 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..5f48190518 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6281,6 +6281,9 @@ file-filter Flattener presets Предварителни настройки за file-filter PDF presets Предварителни настройки за PDF file-filter PDF-compatible .ai Съвместими с PDF .ai файлове file-filter Print presets Предварителни настройки за печат +file-filter Tracing presets Предварителни настройки за трасиране +file-filter Action sets Набори от действия +file-filter Composite fonts Съставни шрифтове file-filter Preferences Настройки file-filter Export presets Набори за експортиране file-filter SVG Compressed Компресиран SVG diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..8830d178c0 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6303,6 +6303,9 @@ file-filter Swatch libraries Biblioteke uzoraka boja file-filter Flattener presets Predlošci spljoštavanja file-filter PDF presets PDF predlošci file-filter Print presets Predlošci štampanja +file-filter Tracing presets Predlošci praćenja +file-filter Action sets Skupovi akcija +file-filter Composite fonts Kompozitni fontovi file-filter Preferences Postavke file-filter Export presets Predlošci izvoza file-filter SVG Compressed Komprimirani SVG diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..6db8daca9a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7922,6 +7922,9 @@ file-filter Flattener presets Preajustos de l’aplanador file-filter PDF presets Preajustos de PDF file-filter PDF-compatible .ai .ai compatible amb PDF file-filter Print presets Preajustos d’impressió +file-filter Tracing presets Preajustos de traçat +file-filter Action sets Conjunts d’accions +file-filter Composite fonts Tipus de lletra compostos file-filter Preferences Preferències file-filter Export presets Preajustos d’exportació file-filter SVG Compressed SVG comprimit diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..4d5dd966a8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6774,6 +6774,9 @@ file-filter Swatch libraries Knihovny vzorníků file-filter Flattener presets Přednastavení sloučení průhlednosti file-filter PDF presets Přednastavení PDF file-filter Print presets Přednastavení tisku +file-filter Tracing presets Přednastavení vektorizace +file-filter Action sets Sady akcí +file-filter Composite fonts Složená písma file-filter Preferences Předvolby file-filter Export presets Přednastavení exportu file-filter SVG Compressed Komprimované SVG diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..96b85320bc 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -8816,6 +8816,9 @@ file-filter Swatch libraries Farveprøvebiblioteker file-filter Flattener presets Flattener-forudindstillinger file-filter PDF presets PDF-forudindstillinger file-filter Print presets Printforudindstillinger +file-filter Tracing presets Vektoriseringsforudindstillinger +file-filter Action sets Handlingssæt +file-filter Composite fonts Sammensatte skrifttyper file-filter Preferences Præferencer file-filter Export presets Eksportforudindstillinger file-filter SVG Compressed Komprimeret SVG diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..e8db515b66 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1461,6 +1461,9 @@ file-filter Swatch libraries Farbfeldbibliotheken file-filter Flattener presets Reduzierungsvorgaben file-filter PDF presets PDF-Vorgaben file-filter Print presets Druckvorgaben +file-filter Tracing presets Nachzeichnervorgaben +file-filter Action sets Aktionssätze +file-filter Composite fonts Zusammengesetzte Schriften file-filter Preferences Voreinstellungen file-filter Export presets Exportvorgaben file-filter SVG Compressed SVG komprimiert diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..772fa55ef9 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3210,6 +3210,9 @@ file-filter Flattener presets Προεπιλογές ισοπέδωσης file-filter PDF presets Προεπιλογές PDF file-filter PDF-compatible .ai .ai συμβατό με PDF file-filter Print presets Προεπιλογές εκτύπωσης +file-filter Tracing presets Προεπιλογές ανίχνευσης περιγραμμάτων +file-filter Action sets Σύνολα ενεργειών +file-filter Composite fonts Σύνθετες γραμματοσειρές file-filter Preferences Προτιμήσεις file-filter Export presets Προκαθορισμένα εξαγωγής file-filter SVG Compressed Συμπιεσμένο SVG diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..5ccafd0b62 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6674,6 +6674,9 @@ file-filter Swatch libraries Bibliotecas de muestras file-filter Flattener presets Preajustes del acoplador file-filter PDF presets Preajustes de PDF file-filter Print presets Preajustes de impresión +file-filter Tracing presets Preajustes de calco +file-filter Action sets Conjuntos de acciones +file-filter Composite fonts Fuentes compuestas file-filter Preferences Preferencias file-filter Export presets Ajustes de exportación file-filter SVG Compressed SVG comprimido diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..6a8e09877a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6676,6 +6676,9 @@ file-filter Swatch libraries Värimallikirjastot file-filter Flattener presets Litistyksen esiasetukset file-filter PDF presets PDF-esiasetukset file-filter Print presets Tulostuksen esiasetukset +file-filter Tracing presets Jäljityksen esiasetukset +file-filter Action sets Toimintosarjat +file-filter Composite fonts Yhdistelmäfontit file-filter Preferences Asetukset file-filter Export presets Vientiesiasetukset file-filter SVG Compressed Pakattu SVG diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..f3dbafa3dc 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6938,6 +6938,9 @@ file-filter Flattener presets Paramètres prédéfinis d’aplatissement file-filter PDF presets Paramètres prédéfinis PDF file-filter PDF-compatible .ai .ai compatible PDF file-filter Print presets Paramètres prédéfinis d’impression +file-filter Tracing presets Paramètres prédéfinis de vectorisation +file-filter Action sets Jeux de scripts +file-filter Composite fonts Polices composites file-filter Preferences Préférences file-filter Export presets Paramètres prédéfinis d’export file-filter SVG Compressed SVG compressé diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..95f53182c6 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -5262,16 +5262,20 @@ antiAlias Sharp શાર્પ anchor Points: પોઇન્ટ્સ: diagnostics render રેન્ડર diagnostics ui ઇન્ટરફેસ +file-filter Action sets ઍક્શન સેટ file-filter All placeable files પ્લેસ કરી શકાય તેવી બધી ફાઇલો file-filter All readable files વાંચી શકાય તેવી બધી ફાઇલો +file-filter Composite fonts કમ્પોઝિટ ફોન્ટ્સ file-filter Export presets એક્સપોર્ટ પ્રીસેટ્સ file-filter Flattener presets ફ્લેટનર પ્રીસેટ્સ file-filter PDF presets PDF પ્રીસેટ્સ file-filter PDF-compatible .ai PDF-સુસંગત .ai +file-filter Perspective grid presets પરસ્પેક્ટિવ ગ્રિડ પ્રીસેટ્સ file-filter Print presets પ્રિન્ટ પ્રીસેટ્સ file-filter SVG Compressed સંકુચિત SVG file-filter Swatch libraries સ્વેચ લાઇબ્રેરીઓ file-filter Templates ટેમ્પ્લેટ્સ +file-filter Tracing presets ટ્રેસિંગ પ્રીસેટ્સ file-filter VectorCraft Template VectorCraft ટેમ્પ્લેટ gradient-kind Radial રેડિયલ lighting Light લાઇટ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..c7e9cd65b4 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9986,9 +9986,11 @@ effect Points पॉइंट्स effect Regular सामान्य effect Soft सॉफ़्ट effect Vertical लंबवत +file-filter Action sets एक्शन सेट्स file-filter All placeable files सभी प्लेसेबल फ़ाइलें -file-filter All readable files सभी पठनीय फ़ाइलों -file-filter Export presets प्रीसेट्स एक्सपोर्ट करें +file-filter All readable files सभी पठनीय फ़ाइलें +file-filter Composite fonts कंपोज़िट फ़ॉन्ट +file-filter Export presets एक्सपोर्ट प्रीसेट्स file-filter Flattener presets फ़्लैटनर प्रीसेट्स file-filter PDF presets PDF प्रीसेट्स file-filter PDF-compatible .ai PDF-संगत .ai @@ -9997,6 +9999,7 @@ file-filter Preferences प्रेफ़रेंसेज़ file-filter SVG Compressed SVG संपीड़ित file-filter Swatch libraries स्वॉच लाइब्रेरीज़ file-filter Templates टेम्पलेट्स +file-filter Tracing presets ट्रेसिंग प्रीसेट्स file-filter VectorCraft Template वेक्टर क्राफ्ट टेम्पलेट font-script Japanese जापानी font-technology Variable वेरिएबल diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..9b75e5abd8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1802,6 +1802,9 @@ file-filter Swatch libraries Színminta-könyvtárak file-filter Flattener presets Lapítási előbeállítások file-filter PDF presets PDF-előbeállítások file-filter Print presets Nyomtatási előbeállítások +file-filter Tracing presets Vektorizálási előbeállítások +file-filter Action sets Műveletkészletek +file-filter Composite fonts Összetett betűtípusok file-filter Preferences Beállítások file-filter Export presets Exportálási előbeállítások file-filter SVG Compressed Tömörített SVG diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..8ced48ea64 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6610,6 +6610,9 @@ file-filter Swatch libraries Pustaka swatch file-filter Flattener presets Preset perata file-filter PDF presets Preset PDF file-filter Print presets Preset cetak +file-filter Tracing presets Preset penelusuran +file-filter Action sets Set tindakan +file-filter Composite fonts Font komposit file-filter Preferences Preferensi file-filter Export presets Preset ekspor file-filter SVG Compressed SVG terkompresi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..db8e846458 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1498,6 +1498,9 @@ file-filter Swatch libraries Librerie campioni file-filter Flattener presets Preset di appiattimento file-filter PDF presets Preset PDF file-filter Print presets Preset di stampa +file-filter Tracing presets Preset di ricalco +file-filter Action sets Set di azioni +file-filter Composite fonts Font compositi file-filter Preferences Preferenze file-filter Export presets Predefiniti di esportazione file-filter SVG Compressed SVG compresso diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..da2dc81781 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4345,6 +4345,9 @@ file-filter Swatch libraries スウォッチライブラリ file-filter Flattener presets 分割・統合プリセット file-filter PDF presets PDF プリセット file-filter Print presets プリントプリセット +file-filter Tracing presets トレースプリセット +file-filter Action sets アクションセット +file-filter Composite fonts 合成フォント file-filter Preferences 環境設定 file-filter Export presets 書き出しプリセット file-filter SVG Compressed SVG 圧縮 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..41c647bc9a 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8279,6 +8279,9 @@ file-filter Swatch libraries ფერის ნიმუშების ბი file-filter Flattener presets გაბრტყელების პრესეტები file-filter PDF presets PDF-ის პრესეტები file-filter Print presets ბეჭდვის პრესეტები +file-filter Tracing presets ვექტორიზაციის პრესეტები +file-filter Action sets მოქმედებების ნაკრებები +file-filter Composite fonts კომპოზიტური შრიფტები file-filter Preferences პარამეტრები file-filter Export presets ექსპორტის პრესეტები file-filter SVG Compressed შეკუმშული SVG diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..bcb6e13a65 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4335,6 +4335,9 @@ file-filter Swatch libraries 견본 라이브러리 file-filter Flattener presets 병합 프리셋 file-filter PDF presets PDF 프리셋 file-filter Print presets 인쇄 프리셋 +file-filter Tracing presets 추적 프리셋 +file-filter Action sets 액션 세트 +file-filter Composite fonts 합성 글꼴 file-filter Preferences 환경 설정 file-filter Export presets 내보내기 사전 설정 file-filter SVG Compressed 압축된 SVG diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..c41f0adfcd 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8524,6 +8524,9 @@ file-filter Swatch libraries Stalenbibliotheken file-filter Flattener presets Afvlakvoorinstellingen file-filter PDF presets PDF-voorinstellingen file-filter Print presets Afdrukvoorinstellingen +file-filter Tracing presets Traceervoorinstellingen +file-filter Action sets Actiesets +file-filter Composite fonts Samengestelde lettertypen file-filter Preferences Voorkeuren file-filter Export presets Exportvoorinstellingen file-filter SVG Compressed Gecomprimeerde SVG diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..db8c8fd322 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6603,6 +6603,9 @@ file-filter Swatch libraries Biblioteki próbek file-filter Flattener presets Ustawienia spłaszczania file-filter PDF presets Ustawienia PDF file-filter Print presets Ustawienia drukowania +file-filter Tracing presets Ustawienia obrysu +file-filter Action sets Zestawy operacji +file-filter Composite fonts Fonty złożone file-filter Preferences Preferencje file-filter Export presets Ustawienia eksportu file-filter SVG Compressed SVG skompresowany diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..81441c5e35 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6653,6 +6653,9 @@ file-filter Swatch libraries Bibliotecas de amostras file-filter Flattener presets Predefinidos de achatamento file-filter PDF presets Predefinidos de PDF file-filter Print presets Predefinidos de impressão +file-filter Tracing presets Predefinições de vetorização +file-filter Action sets Conjuntos de ações +file-filter Composite fonts Fontes compostas file-filter Preferences Preferências file-filter Export presets Predefinições de exportação file-filter SVG Compressed SVG Compactado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..5e456ce18b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1483,6 +1483,9 @@ file-filter Swatch libraries Библиотеки образцов file-filter Flattener presets Наборы объединения file-filter PDF presets Наборы PDF file-filter Print presets Наборы печати +file-filter Tracing presets Наборы трассировки +file-filter Action sets Наборы действий +file-filter Composite fonts Составные шрифты file-filter Preferences Настройки file-filter Export presets Наборы настроек экспорта file-filter SVG Compressed Сжатый SVG diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..0eb2b60e7f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6849,6 +6849,9 @@ file-filter Flattener presets Förinställningar för plattning file-filter PDF presets PDF-förinställningar file-filter PDF-compatible .ai PDF-kompatibel .ai file-filter Print presets Utskriftsförinställningar +file-filter Tracing presets Förinställningar för vektorisering +file-filter Action sets Åtgärdsuppsättningar +file-filter Composite fonts Sammansatta typsnitt file-filter Preferences Inställningar file-filter Export presets Exportförinställningar file-filter SVG Compressed SVG komprimerad diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..fa7d72b1f5 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -7439,6 +7439,22 @@ fn render_site_labels_fall_back_to_english() { } } +/// Every file type the save panel shows for a file that is not a document format has a +/// file-filter or plain row in each complete catalog. CSS and PostScript are format names and +/// stay in English. +#[test] +fn save_panel_file_types_are_in_complete_catalogs() { + let mut missing = vec![]; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for (label, _) in crate::io::FILE_TYPES.iter().filter(|(label, _)| !["CSS", "PostScript"].contains(label)) { + if lang.catalog().contextual("file-filter", label).is_none() && lang.catalog().plain(label).is_none() { + missing.push(format!("{} {label}", lang.code)); + } + } + } + assert!(missing.is_empty(), "{missing:?}"); +} + /// (context, English source) of the labels [`untranslated_report`] lists for a language without /// their rows: the file dialogs' filter names, the status bar's timings, New Document's preset /// name, the contributor tooltips, the gradient kind in a swatch's description, the printer mark @@ -7450,6 +7466,9 @@ const RENDER_SITE_ROWS: &[(&str, &str)] = &[ ("file-filter", "Flattener presets"), ("file-filter", "PDF presets"), ("file-filter", "Print presets"), + ("file-filter", "Tracing presets"), + ("file-filter", "Action sets"), + ("file-filter", "Composite fonts"), ("file-filter", "Export presets"), ("file-filter", "SVG Compressed"), ("file-filter", "PDF-compatible .ai"), diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..2f81ffefa8 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6694,8 +6694,10 @@ effect Horizontal Yatay effect Points Noktalar effect Regular Düzenli effect Vertical Dikey +file-filter Action sets Eylem setleri file-filter All placeable files Yerleştirilebilir tüm dosyalar file-filter All readable files Okunabilir tüm dosyalar +file-filter Composite fonts Bileşik fontlar file-filter Export presets Dışa aktarma önayarları file-filter Flattener presets Düzleştirici önayarları file-filter PDF presets PDF önayarları @@ -6705,6 +6707,7 @@ file-filter Preferences Tercihler file-filter SVG Compressed Sıkıştırılmış SVG file-filter Swatch libraries Renk örneği kitaplıkları file-filter Templates Şablonlar +file-filter Tracing presets İzleme önayarları file-filter VectorCraft Template VectorCraft Şablonu gradient-kind Radial Radyal mark-style Japanese Japon diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..d4cb488f55 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1492,6 +1492,9 @@ file-filter Swatch libraries Бібліотеки зразків file-filter Flattener presets Набори зведення file-filter PDF presets Набори PDF file-filter Print presets Набори друку +file-filter Tracing presets Набори трасування +file-filter Action sets Набори дій +file-filter Composite fonts Складені шрифти file-filter Preferences Налаштування file-filter Export presets Набори параметрів експорту file-filter SVG Compressed Стиснутий SVG diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..745153720c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1714,6 +1714,9 @@ file-filter Swatch libraries Thư viện mẫu màu file-filter Flattener presets Thiết lập sẵn làm phẳng file-filter PDF presets Thiết lập sẵn PDF file-filter Print presets Thiết lập sẵn in +file-filter Tracing presets Thiết lập sẵn vector hóa +file-filter Action sets Bộ hành động +file-filter Composite fonts Phông chữ tổ hợp file-filter Preferences Tùy chọn file-filter Export presets Cài đặt sẵn xuất file-filter SVG Compressed SVG nén diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..56fb240b6d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1426,6 +1426,9 @@ file-filter Swatch libraries 色板库 file-filter Flattener presets 拼合预设 file-filter PDF presets PDF 预设 file-filter Print presets 打印预设 +file-filter Tracing presets 描摹预设 +file-filter Action sets 动作组 +file-filter Composite fonts 复合字体 file-filter Preferences 首选项 file-filter Export presets 导出预设 file-filter SVG Compressed 压缩 SVG diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..c3a7aa53fe 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1462,6 +1462,9 @@ file-filter Swatch libraries 色票資料庫 file-filter Flattener presets 平面化預設集 file-filter PDF presets PDF 預設集 file-filter Print presets 列印預設集 +file-filter Tracing presets 描圖預設集 +file-filter Action sets 動作組 +file-filter Composite fonts 複合字體 file-filter Preferences 偏好設定 file-filter Export presets 轉存預設集 file-filter SVG Compressed 壓縮 SVG diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index 73dd82dd02..b3c72096e2 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -35,6 +35,8 @@ pub use open::{ }; #[cfg(test)] pub(crate) use open::{open_file, opened_with_notes}; +#[cfg(test)] +pub(crate) use save::FILE_TYPES; pub(crate) use save::save_current; pub use save::{ SAVE_CANCELED, ask_format_options, ask_pdf_options, cancel_saves, hide_saves, remember_active_artboard, remember_view, save, save_pdf, diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index aa4b565c07..bb10d77a66 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -144,7 +144,7 @@ pub(super) fn suggested(app: &VectorcraftApp, ext: &str) -> (String, Option Date: Fri, 20 Nov 2026 15:57:31 -0800 Subject: [PATCH 07/55] Links: test Show in Folder with two images selected With two images selected, Link Info shows the first selected one, while the list puts the other (on top) first. The test clicks Show in Folder in that state and checks that only the file of the image Link Info shows is handed to the file manager. --- crates/ui-egui/src/panels/tests_links.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 1494b75925..47f4dc173a 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -611,15 +611,21 @@ fn link_infos_location_row_shows_the_file_in_its_folder() { assert_eq!(click_panel_button(&mut app, "Show in Folder"), Some(true)); app.run("select.set", json!({"ids": [other]})).unwrap(); assert_eq!(click_panel_button(&mut app, "Show in Folder"), Some(true)); - assert_eq!(*revealed.borrow(), [linked_path, other_path.clone()]); + assert_eq!(*revealed.borrow(), [linked_path.clone(), other_path.clone()]); + // Both images selected: Link Info shows the first selected, `linked`, while the list has `other` + // (on top) first. Only the file of the image Link Info shows is handed over. + app.run("select.set", json!({"ids": [linked, other]})).unwrap(); + assert_eq!(click_panel_button(&mut app, "Show in Folder"), Some(true)); + assert_eq!(*revealed.borrow(), [linked_path.clone(), other_path.clone(), linked_path]); // A missing file: the row stays, the button is off. + app.run("select.set", json!({"ids": [other]})).unwrap(); std::fs::remove_file(&other_path).unwrap(); assert_eq!(click_panel_button(&mut app, "Show in Folder"), Some(false)); // Without a file manager (the web): off. app.run("select.set", json!({"ids": [linked]})).unwrap(); app.services.reveal = None; assert_eq!(click_panel_button(&mut app, "Show in Folder"), Some(false)); - assert_eq!(revealed.borrow().len(), 2, "nothing more was shown"); + assert_eq!(revealed.borrow().len(), 3, "nothing more was shown"); } /// #5236: with Preferences › File Handling › Use System Defaults for Edit Original off, Edit From 0ddd5539ad1d35e56cbf72e1162daec542de948c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:58:55 -0800 Subject: [PATCH 08/55] Transform: Polygon Properties' Sides row has a 3 to 20 slider beside the field The Sides field of Polygon Properties (Transform panel, the Properties panel's Transform section and the task bar's Shape Properties) gets a slider after it over 3 to 20 sides, as the help page describes (https://helpx.adobe.com/illustrator/using/live-shapes.html); the field still takes 3 to 1000. - A drag previews the count through object.setLiveShape {sides} and its release adds one undo step, none when it ends at its starting count. Escape during the drag puts the count back. A click or an arrow key on the rail sets the count in one undo step. - A count above 20 shows the handle at the rail's right end; the field and screen readers show the real count until the rail moves. - A drag whose rows stop being drawn keeps its preview as one undo step at the end of that frame. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/panels/transform.rs | 106 ++++++++- crates/ui-egui/src/panels/transform/tests.rs | 217 +++++++++++++++++++ docs/target-app-parity.md | 1 + 4 files changed, 319 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..455f6a8337 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -654,6 +654,7 @@ impl VectorcraftApp { crate::toasts::show(self, &ctx); // After every panel had its chance to draw in this pass. crate::panels::three_d::end_stale_drag(self, &ctx); + panels::transform::end_stale_sides_drag(self, &ctx); if self.custom_titlebar { titlebar::resize_zones(ui); } diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 42e0dba358..70b9dd030d 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -588,9 +588,9 @@ fn pie_link(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// A live polygon's Polygon Properties (Transform and Properties panels): its side count, angle -/// (counterclockwise), corner type and radius, radius (centre to vertex) and side length, and Make -/// Sides Equal, which an uneven scale enables. +/// A live polygon's Polygon Properties (Transform and Properties panels): its side count (a field +/// and [`sides_slider`]), angle (counterclockwise), corner type and radius, radius (center to +/// vertex) and side length, and Make Sides Equal, which an uneven scale enables. pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, id: &str) { let LiveShape::Polygon { sides, .. } = live else { return }; let (units, fw) = (app.session.general_unit(), super::field_width(ui)); @@ -603,9 +603,12 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live let mut set = None; egui::Grid::new((id, "grid")).num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { widgets::dim_label(ui, tl!("Sides:")); - if let Some(s) = widgets::range_field_named(ui, (id, "sides"), Some(tl!("Sides:")), f64::from(*sides), 3.0..=1000.0, "", 0, fw) { - set = Some(("sides", json!(s as u64))); - } + ui.horizontal(|ui| { + if let Some(s) = widgets::range_field_named(ui, (id, "sides"), Some(tl!("Sides:")), f64::from(*sides), 3.0..=1000.0, "", 0, fw) { + set = Some(("sides", json!(s as u64))); + } + sides_slider(app, ui, id, *sides, fw); + }); ui.end_row(); widgets::dim_label(ui, tl!("Angle:")); if let Some(a) = widgets::mixed_field_named(ui, (id, "angle"), Some(tl!("Angle:")), angle, "°", 1, fw) { @@ -641,6 +644,97 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live } } +/// The side counts the Sides slider of Polygon Properties spans; the field beside it takes 3 to +/// 1,000. +pub(crate) const SIDES_SLIDER: std::ops::RangeInclusive = 3.0..=20.0; + +/// A drag on a Sides slider in progress: the rows it is in, whether Escape canceled it (the rest +/// of it is ignored until the button is up), and the main window's pass the rail was last drawn in. +#[derive(Clone, Debug, PartialEq)] +struct SidesDrag { + rows: String, + canceled: bool, + pass: u64, +} + +/// Panel state key of the [`SidesDrag`] in progress. +const SIDES_DRAG: &str = "polygon-sides-drag"; + +/// The main window's pass in progress, which a floating window's panel also marks its drag with. +fn root_pass(ctx: &egui::Context) -> u64 { + ctx.cumulative_pass_nr_for(egui::ViewportId::ROOT) +} + +/// Keeps the count a Sides slider drag previewed as one undo step when its rail was not drawn in +/// this pass (the task bar's popover or the panel closed during the drag), so no preview stays open +/// into a later pass; a drag Escape canceled only ends. The app runs this at the end of every +/// pass, after the panels. +pub(crate) fn end_stale_sides_drag(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(drag) = pstate::>(ctx, SIDES_DRAG) else { return }; + if drag.pass == root_pass(ctx) { + return; + } + if !drag.canceled && app.session.in_interaction() { + if let Err(e) = app.session.commit_interaction() { + app.ui.status = e.to_string(); + } + app.sync_views(); + } + set_pstate(ctx, SIDES_DRAG, None::); +} + +/// The Sides slider of Polygon Properties (rows `id`), `width` wide, for a polygon of `sides` +/// sides. A drag, a press on the rail included, previews the side count and its release records +/// one undo step; Escape during the drag puts the polygon back as it was and ignores the rest of +/// the drag. A key step sets the count at once. A count past 20 shows at the rail's right end and +/// stays until the rail moves. Screen readers get the count the field shows. +fn sides_slider(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, sides: u32, width: f32) { + let t = Tokens::get(ui.ctx()); + let (lo, hi) = (*SIDES_SLIDER.start(), *SIDES_SLIDER.end()); + let n = f64::from(sides); + let shown = widgets::SliderValue::field(n, SIDES_SLIDER, "", 0); + let at = ((n.clamp(lo, hi) - lo) / (hi - lo)) as f32; + let (dragged, phase, keyed) = widgets::color_slider_stepped(ui, (id, "sides-slider"), tl!("Sides:"), Some(shown), at, width, &|_| t.input_border); + let ctx = ui.ctx().clone(); + let held = pstate::>(&ctx, SIDES_DRAG).filter(|d| d.rows == id); + let down = ui.input(|i| i.pointer.any_down()); + let pass = root_pass(&ctx); + // `None` leaves another rows' drag as it is. + let mut next = None; + if let Some(d) = held.as_ref().filter(|d| d.canceled) { + next = Some(down.then(|| SidesDrag { pass, ..d.clone() })); + } else if held.is_some() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + if let Err(e) = app.session.cancel_interaction() { + app.ui.status = e.to_string(); + } + app.sync_views(); + next = Some(down.then(|| SidesDrag { rows: id.to_string(), canceled: true, pass })); + } else if let Some(x) = dragged { + let count = (lo + f64::from(x) * (hi - lo)).round(); + super::live_run(app, "Live Shape Properties", "object.setLiveShape", json!({ "sides": count as u64 }), phase); + next = Some((phase == widgets::Live::Dragging).then(|| SidesDrag { rows: id.to_string(), canceled: false, pass })); + } else if let Some(k) = keyed.map(f64::round).filter(|k| *k != n) { + app.run("object.setLiveShape", json!({ "sides": k as u64 })).ok(); + } else if let Some(d) = held { + if down { + next = Some(Some(SidesDrag { pass, ..d })); + } else { + // The button is up but the rail reported no release: keep the preview as a release + // on the rail would. + if app.session.in_interaction() { + if let Err(e) = app.session.commit_interaction() { + app.ui.status = e.to_string(); + } + app.sync_views(); + } + next = Some(None); + } + } + if let Some(next) = next { + set_pstate(&ctx, SIDES_DRAG, next); + } +} + /// The Control bar's underlined "Transform" link: a click toggles the Transform panel in a /// popover under it, as the Stroke link does with the Stroke panel. pub fn link(app: &mut VectorcraftApp, ui: &mut Ui) { diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index 75ae9f2594..5ee1311e80 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -1305,3 +1305,220 @@ fn a_frame_after_a_shape_shows_the_transform_panel() { assert_eq!(texts.iter().any(|t| t == heading), on, "on: {on}, {texts:?}"); } } + +/// The selected live polygon's side count. +fn polygon_sides(app: &VectorcraftApp) -> u32 { + match &first_selected(app).unwrap().kind { + NodeKind::Path { live: Some(l), .. } => match **l { + LiveShape::Polygon { sides, .. } => sides, + ref k => panic!("{k:?}"), + }, + k => panic!("{k:?}"), + } +} + +/// The Shape Properties rows of the contextual task bar's popover for the selected live shape. +fn task_bar_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui) { + let n = first_selected(app).unwrap(); + if let NodeKind::Path { live: Some(live), .. } = &n.kind { + let live = live.clone(); + live_shape_rows(app, ui, &n, &live, "task-bar-shape", true); + } +} + +/// A headless harness drawing `draw` with a live hexagon selected, its side count then set to +/// `sides`, after its first frames. +fn polygon_harness(sides: u32, draw: fn(&mut VectorcraftApp, &mut Ui)) -> egui_kittest::Harness<'static, VectorcraftApp> { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.polygon", json!({"cx": 150, "cy": 150, "radius": 50, "sides": 6})).unwrap(); + if sides != 6 { + app.run("object.setLiveShape", json!({ "sides": sides })).unwrap(); + } + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(320.0, 900.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + draw(app, ui); + }, + app, + ); + h.run_steps(3); + h +} + +/// Where on the Sides slider's rail a press picks `count` sides. +fn sides_rail_at(h: &egui_kittest::Harness<'_, VectorcraftApp>, count: f64) -> egui::Pos2 { + use egui_kittest::kittest::Queryable; + let r = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Sides:").rect(); + let (lo, hi) = (*SIDES_SLIDER.start(), *SIDES_SLIDER.end()); + egui::pos2(r.left() + 4.0 + ((count - lo) / (hi - lo)) as f32 * (r.width() - 8.0), r.center().y) +} + +/// Press the primary button at `from` and move to `to` in four frames, keeping it down. +fn sides_press_and_move(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, from: egui::Pos2, to: egui::Pos2) { + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + for i in 1..=4 { + h.event(egui::Event::PointerMoved(from + (to - from) * (i as f32 / 4.0))); + h.run_steps(1); + } +} + +/// Release the primary button at `at`. +fn sides_release(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, at: egui::Pos2) { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(2); +} + +/// Polygon Properties' Sides row has a slider beside its field, in the Transform panel, the +/// Properties panel's Transform section and the task bar's Shape Properties: screen readers get it +/// as a slider named Sides with the side count over 3 to 20. +#[test] +fn polygon_sides_slider_is_shared_by_transform_and_properties() { + use egui_kittest::kittest::{NodeT, Queryable}; + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section, task_bar_shape_rows] { + let h = polygon_harness(6, draw); + let slider = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Sides:"); + let node = slider.accesskit_node(); + assert_eq!(node.numeric_value(), Some(6.0)); + assert_eq!(node.min_numeric_value(), Some(3.0)); + assert_eq!(node.max_numeric_value(), Some(20.0)); + let field = h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Sides:"); + assert_eq!(field.value().as_deref(), Some("6")); + assert!(slider.rect().left() >= field.rect().right(), "the slider follows the field on its row"); + assert!((slider.rect().center().y - field.rect().center().y).abs() < 6.0, "one row"); + } +} + +/// A count past the slider's 20, typed or set by a command, stays as it is while the panel is +/// drawn: the field and screen readers show it, and the rail's handle sits at its right end. A +/// press on the rail then sets a count from 3 to 20 in one undo step, and an arrow key steps it by +/// one in one undo step. +#[test] +fn polygon_sides_above_slider_range_remain_editable() { + use egui_kittest::kittest::{NodeT, Queryable}; + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let mut h = polygon_harness(50, show); + let (depth, revision) = (undo(h.state()), h.state().session.active().unwrap().revision); + h.run_steps(3); + assert_eq!(polygon_sides(h.state()), 50); + assert_eq!(undo(h.state()), depth); + assert_eq!(h.state().session.active().unwrap().revision, revision, "drawing the slider leaves the document as it is"); + let slider = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Sides:"); + let node = slider.accesskit_node(); + assert_eq!(node.numeric_value(), Some(50.0)); + assert_eq!(node.max_numeric_value(), Some(50.0)); + assert_eq!(h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Sides:").value().as_deref(), Some("50")); + let at = sides_rail_at(&h, 12.0); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(1); + assert_eq!(polygon_sides(h.state()), 12); + assert_eq!(undo(h.state()), depth + 1, "a press on the rail is one undo step"); + h.key_press(egui::Key::ArrowRight); + h.run_steps(2); + assert_eq!(polygon_sides(h.state()), 13); + assert_eq!(undo(h.state()), depth + 2, "a key step is one undo step"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(polygon_sides(h.state()), 12); +} + +/// A drag on the Sides slider previews the side count and its release records one undo step, +/// which Undo takes back. Escape during a drag puts the polygon back and ignores the rest of the +/// drag, and a drag that ends at the count it started from records nothing. +#[test] +fn polygon_sides_slider_drag_is_one_undo_step() { + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let mut h = polygon_harness(6, show); + let depth = undo(h.state()); + let (six, fifteen, ten) = (sides_rail_at(&h, 6.0), sides_rail_at(&h, 15.0), sides_rail_at(&h, 10.0)); + sides_press_and_move(&mut h, six, fifteen); + assert!(h.state().session.in_interaction(), "the drag is in progress"); + assert_eq!(polygon_sides(h.state()), 15, "the drag previews the count"); + assert_eq!(undo(h.state()), depth); + sides_release(&mut h, fifteen); + assert!(!h.state().session.in_interaction()); + assert_eq!(polygon_sides(h.state()), 15); + assert_eq!(undo(h.state()), depth + 1, "the whole drag is one undo step"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(polygon_sides(h.state()), 6); + // Escape cancels the drag; the rest of it changes nothing. + sides_press_and_move(&mut h, six, fifteen); + assert_eq!(polygon_sides(h.state()), 15); + h.key_press(egui::Key::Escape); + h.run_steps(1); + assert!(!h.state().session.in_interaction(), "Escape ends the drag"); + assert_eq!(polygon_sides(h.state()), 6, "Escape puts the count back"); + h.event(egui::Event::PointerMoved(ten)); + h.run_steps(1); + sides_release(&mut h, ten); + assert_eq!(polygon_sides(h.state()), 6); + assert_eq!(undo(h.state()), depth, "a canceled drag records no undo step"); + // Back where it started: no undo step. + sides_press_and_move(&mut h, six, fifteen); + sides_press_and_move_back(&mut h, fifteen, six); + sides_release(&mut h, six); + assert_eq!(polygon_sides(h.state()), 6); + assert_eq!(undo(h.state()), depth, "a drag back to its start records no undo step"); +} + +/// A Sides drag whose rows stop being drawn (the task bar's popover closed under it) keeps the +/// count it previewed as one undo step at the end of that pass, as the app ends it; the release +/// and the rows drawn again change nothing more. +#[test] +fn polygon_sides_slider_drag_released_unseen_is_kept() { + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.polygon", json!({"cx": 150, "cy": 150, "radius": 50, "sides": 6})).unwrap(); + let depth = undo(&app); + let shown = std::rc::Rc::new(std::cell::Cell::new(true)); + let drawn = shown.clone(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(320.0, 900.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + if drawn.get() { + show(app, ui); + } + end_stale_sides_drag(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + let (six, fifteen) = (sides_rail_at(&h, 6.0), sides_rail_at(&h, 15.0)); + sides_press_and_move(&mut h, six, fifteen); + assert!(h.state().session.in_interaction()); + assert_eq!(polygon_sides(h.state()), 15); + shown.set(false); + h.run_steps(1); + assert!(!h.state().session.in_interaction(), "the drag ends with the pass that did not draw it"); + assert_eq!(polygon_sides(h.state()), 15); + assert_eq!(undo(h.state()), depth + 1, "one undo step"); + sides_release(&mut h, fifteen); + shown.set(true); + h.run_steps(2); + assert_eq!(polygon_sides(h.state()), 15); + assert_eq!(undo(h.state()), depth + 1); +} + +/// Move from `from` to `to` in four frames with the primary button still down. +fn sides_press_and_move_back(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, from: egui::Pos2, to: egui::Pos2) { + for i in 1..=4 { + h.event(egui::Event::PointerMoved(from + (to - from) * (i as f32 / 4.0))); + h.run_steps(1); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..40d395e75a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1494,6 +1494,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). + - **Polygon side slider:** Polygon Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Sides slider after the Sides field, over 3 to 20 sides. [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) gives the slider that range and leaves larger counts, up to 1000, to the typed field, which still takes 3 to 1000. A drag previews the count through `object.setLiveShape {sides}`; its release adds one undo step when the count changed and none when it ends where it began, and Escape during the drag puts the count back and ignores the rest of it. A click on the rail or an arrow key on it sets the count in one undo step. A count above 20 shows the handle at the rail's right end, and screen readers and the field show the real count, until the rail moves. The slider's place, the rule for counts above 20 and the undo steps are VectorCraft's own (`polygon_sides_slider_is_shared_by_transform_and_properties`, `polygon_sides_above_slider_range_remain_editable`, `polygon_sides_slider_drag_is_one_undo_step`, `polygon_sides_slider_drag_released_unseen_is_kept`). - **Hide/Show Shape Widgets:** with the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool, the Control bar shows a Hide Shape Widgets button, which reads Show Shape Widgets while the widgets are hidden (`view.shapeWidgets {on?}`). [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) describes this Control panel button, offered with any live shape drawing tool, as switching the on-canvas widgets of selected shapes off and on. While they are hidden, a selected live rectangle's or polygon's corner widgets, a live ellipse's pie widgets and a live polygon's side widget are not drawn, and the Selection tool and those shape tools do not answer a press, a double-click or the cursor on their place (a shape tool draws from there). The bounding box and its handles, the center point and Direct Selection's corner widgets (View › Hide Corner Widget) stay as they are. The setting is on by default, kept with the interface state across sessions and tool switches, and adds no undo step. Its scope beyond the shape tools, its default and what it leaves shown are VectorCraft's own rules (tests `hidden_shape_widgets_leave_the_bounding_box`, `the_shape_tools_control_bar_hides_and_shows_the_shape_widgets`, `shape_widgets_command_toggles_and_takes_on`, `hidden_shape_widgets_do_not_answer_a_shape_tool` and `hidden_shape_widgets_leave_direct_selections_corners`). - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - **Anchor Point tool, Alt-drag on a handle:** with the Anchor Point tool chosen, dragging a direction handle with Alt (Option) held links it with the opposite handle and makes the anchor smooth, on a path and on a selected blend's spine, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/create-smooth-paths-with-the-smooth-tool.html) describes; a drag without Alt still moves one handle on its own (`path.setHandle` and `object.blend.spine.moveAnchor` with `link`). VectorCraft's own rules: the opposite handle keeps its length; a retracted one is pulled out to the dragged handle's length where a segment leaves the anchor on its side and stays retracted at an open end; Shift with Alt keeps the 45° steps; an Alt-click still retracts the handle; the Pen with Alt keeps moving a handle on its own. Tests: `anchor_point_alt_drag_links_*` in `crates/tools/src/draw2/anchor/tests.rs`, `a_linked_handle_makes_the_anchor_smooth` in `crates/engine/src/tests/anchor_edit_work.rs`, `a_linked_spine_handle_makes_the_point_smooth` in `crates/engine/src/tests/blendspine.rs`. From 8d0a50ffa0bff71fe9a8a6994af2fd19ef835c22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:10:38 -0800 Subject: [PATCH 09/55] Type: Show Hidden Characters and Auto Spell Check list the type once per revision Both overlays visited every object of the document in every frame to find its type. They now draw from one list of the active document's text objects, kept for the document's uid and revision, so a frame that changes nothing visits only the type. An edit, Undo, Redo or a switch to another document makes a new list, and the canvas drops the list while it draws neither overlay. Show Hidden Characters no longer draws marks over type in a hidden group or layer, which the canvas does not draw. Auto Spell Check already left such type out. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/caches.rs | 4 + crates/ui-egui/src/canvas.rs | 17 +- crates/ui-egui/src/canvas/tests.rs | 192 +++++++++++++++++++++ crates/ui-egui/src/canvas/tool_overlays.rs | 87 +++++++--- docs/target-app-parity.md | 3 +- docs/type-parity.md | 2 +- 7 files changed, 272 insertions(+), 34 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..458da81741 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -85,6 +85,7 @@ impl VectorcraftApp { find_font: None, hidden_chars: Default::default(), spelling: Default::default(), + text_nodes: Default::default(), selection_marks: Default::default(), shared_paths: Default::default(), selection_box: None, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6e1d229023..01b0a2b6f7 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -52,6 +52,10 @@ pub struct CanvasCache { /// The words Edit › Spelling › Auto Spell Check underlined on each text object in the last /// frame; dropped while it is off. pub spelling: canvas::SpellingMarks, + /// The active document's text objects for (document uid, revision), which Show Hidden + /// Characters and Auto Spell Check draw over. A frame that draws neither drops them + /// ([`canvas::show`]). + pub text_nodes: canvas::TextNodes, /// The selected objects' outlines, anchors and handles as drawn in the last frame. A frame that /// does not draw them drops them ([`canvas::show`]). pub selection_marks: canvas::SelectionMarks, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b366665d4..128af6f67f 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -80,7 +80,7 @@ pub(crate) use task_bar::{bar_action_name, chip_paints, images_with_other_art, t pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type}; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; -pub use tool_overlays::{HiddenChars, SpellingMarks}; +pub use tool_overlays::{HiddenChars, SpellingMarks, TextNodes}; use tool_overlays::{ grid_repeat_overlay, hidden_chars_overlay, live_paint_gap_overlays, mirror_axis_overlay, nine_slice_overlay, original_path_overlay, print_tiling_overlay, radial_repeat_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays, @@ -249,6 +249,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // that does not draw the overlay drops them, for example with the option off, with the edges // hidden, on the Home screen or with no document open. let hidden_chars = std::mem::take(&mut app.canvas.hidden_chars); + // The text objects those marks and Auto Spell Check's lines are drawn over. Likewise, a frame + // that draws neither drops them. + let text_nodes = std::mem::take(&mut app.canvas.text_nodes); // The selection's kept marks. Likewise, a frame that does not draw them drops them. let selection_marks = std::mem::take(&mut app.canvas.selection_marks); // The meshes of the tools' shared paths. Likewise, a frame that does not draw the tools' @@ -431,7 +434,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } original_path_overlay(app, &painter, &xf); - let overlays = selection_visuals(app, &painter, &xf, (hidden_chars, selection_marks, hover_still), revolve_edit, view_info); + let overlays = selection_visuals(app, &painter, &xf, (hidden_chars, text_nodes, selection_marks, hover_still), revolve_edit, view_info); draw_overlays(&painter, &xf, &overlays, &t, HandleLook::of(&app.session.prefs), &mut shared_paths); app.canvas.shared_paths = shared_paths; crate::panels::tabs::paint_stop_guide(app, &painter, &xf); @@ -1652,10 +1655,16 @@ fn selection_visuals( app: &mut VectorcraftApp, painter: &egui::Painter, xf: &Xf, - (hidden_chars, mut marks, hover_still): (HiddenChars, SelectionMarks, bool), + (hidden_chars, text_nodes, mut marks, hover_still): (HiddenChars, TextNodes, SelectionMarks, bool), revolve_edit: bool, view_info: vectorcraft_engine::ViewInfo, ) -> Vec { + // Show Hidden Characters (with the edges shown) and Auto Spell Check draw over the same text + // objects: their list is kept while either is drawn. + let draws_hidden_chars = app.ui.view.edges && !revolve_edit && app.ui.view.hidden_chars; + if draws_hidden_chars || (app.ui.view.auto_spell_check && !revolve_edit) { + app.canvas.text_nodes = text_nodes; + } // View → Hide Gradient Annotator hides the Gradient tool's annotator. let mut overlays = if !revolve_edit && (app.session.tool_id() != "gradient" || app.ui.view.gradient_annotator) { app.session.overlays(view_info) @@ -1688,7 +1697,7 @@ fn selection_visuals( if app.ui.view.live_paint_gaps { overlays.extend(live_paint_gap_overlays(app)); } - if app.ui.view.hidden_chars { + if draws_hidden_chars { app.canvas.hidden_chars = hidden_chars; hidden_chars_overlay(app, painter, xf); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..4c98f2df4e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -7530,9 +7530,11 @@ fn show_hidden_characters_off_releases_the_text_nodes() { after.inputs == inputs && std::sync::Arc::ptr_eq(&after.marks[&id].1, &marks) }); assert!(kept, "a frame keeps the marks of the frame before"); + assert!(app.canvas.text_nodes.list.is_some(), "the list of the text objects is kept"); app.run("type.hiddenCharacters", json!({})).unwrap(); assert!(hidden_char_marks(&mut app, &ctx).is_empty(), "off"); assert!(app.canvas.hidden_chars.marks.is_empty(), "no node is kept"); + assert!(app.canvas.text_nodes.list.is_none(), "no list of the text objects is kept"); app.run("type.hiddenCharacters", json!({})).unwrap(); assert_eq!(hidden_char_marks(&mut app, &ctx), on, "on again: the same marks"); } @@ -7556,9 +7558,199 @@ fn show_hidden_characters_releases_the_text_nodes_of_a_closed_document() { app.session.execute("file.close", &json!({})).unwrap(); assert!(hidden_char_marks(&mut app, &ctx).is_empty(), "the Home screen"); assert!(app.canvas.hidden_chars.marks.is_empty(), "no node of the closed document is kept"); + assert!(app.canvas.text_nodes.list.is_none(), "no list of the closed document's text objects is kept"); assert_eq!(open(&mut app), first, "the same type in a new document"); } +/// `paths` small rectangles and three point type objects with hidden characters and words no +/// dictionary knows: the first on the first layer, the second in a group on that layer and the +/// third on a second layer. Returns the type objects, the group, the second layer and a view. +fn type_among_paths(paths: usize) -> (VectorcraftApp, [vectorcraft_doc::NodeId; 3], vectorcraft_doc::NodeId, vectorcraft_doc::NodeId, Xf) { + use std::sync::Arc; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = |v: serde_json::Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + let path = id(app.session.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 5, "height": 5})).unwrap()); + { + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let template = doc.node(path).unwrap().clone(); + let more: Vec<_> = (1..paths) + .map(|_| { + let mut p = template.clone(); + p.id = doc.alloc_id(); + Arc::new(p) + }) + .collect(); + Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().extend(more); + doc.drop_lookup_cache(); + } + let text = + |app: &mut VectorcraftApp, y: u32, text: &str| id(app.session.execute("text.create", &json!({"x": 20, "y": y, "text": text})).unwrap()); + let a = text(&mut app, 40, "one\ttwo\u{00A0}the\nthree\u{2028}four"); + let b = text(&mut app, 110, "Qzvbtrw the\u{2003}cat"); + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let group = id(app.session.execute("object.group", &json!({})).unwrap()); + let layer = id(app.session.execute("layer.new", &json!({})).unwrap()); + let c = text(&mut app, 180, "Zvqtrbx the\u{202F}cat\n"); + assert_eq!(app.session.active().unwrap().doc.layers.iter().find(|l| l.id == layer).and_then(|l| l.children()).map(|c| c.len()), Some(1)); + let xf = Xf { rect: egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), zoom: 1.0, center: Point::new(200.0, 150.0), rot: 0.0 }; + (app, [a, b, c], group, layer, xf) +} + +/// The list of text objects Show Hidden Characters and Auto Spell Check last drew over. +fn listed_type(app: &VectorcraftApp) -> super::tool_overlays::TextList { + app.canvas.text_nodes.list.as_ref().map(|(_, l)| l.clone()).unwrap() +} + +/// Show Hidden Characters and Auto Spell Check find the type among the document's other objects +/// once for each revision, in one list both draw from: frames that change nothing draw from the +/// same list, and draw the marks and lines a frame drawing from a new list draws. The list holds +/// the visible type in the order the overlays drew it before they shared it. +#[test] +fn hidden_characters_and_auto_spell_check_share_one_list_of_the_type() { + let (mut app, ids, _, _, xf) = type_among_paths(2_000); + let ctx = egui::Context::default(); + // Each visible text object in `Document::walk` order, with no group or layer hidden. + let mut walked = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)) && n.visible { + walked.push(n.id); + } + }); + assert_eq!(walked.len(), 3); + let marks = hidden_chars(&mut app, &ctx, &xf); + let list = listed_type(&app); + assert_eq!(list.iter().filter(|t| t.shown).map(|t| t.node.id).collect::>(), walked); + assert!(list.iter().all(|t| ids.contains(&t.node.id)), "only type"); + let lines = spelling_lines(&mut app, &ctx, &xf); + assert_eq!(lines.len(), 2, "{lines:?}"); + assert!(std::sync::Arc::ptr_eq(&list, &listed_type(&app)), "Auto Spell Check draws from the same list"); + for _ in 0..3 { + assert_eq!(hidden_chars(&mut app, &ctx, &xf), marks); + assert_eq!(spelling_lines(&mut app, &ctx, &xf), lines); + assert!(std::sync::Arc::ptr_eq(&list, &listed_type(&app)), "a frame that changes nothing lists no type"); + } + app.canvas.text_nodes = TextNodes::default(); + app.canvas.hidden_chars = HiddenChars::default(); + app.canvas.spelling = SpellingMarks::default(); + assert_eq!(hidden_chars(&mut app, &ctx, &xf), marks, "the marks drawn from a new list"); + assert_eq!(spelling_lines(&mut app, &ctx, &xf), lines, "the lines drawn from a new list"); + assert!(!std::sync::Arc::ptr_eq(&list, &listed_type(&app))); +} + +/// The list follows the document: a new text object, an edit, Undo, Redo and a switch to another +/// document each list the type again, and the marks are those of the type the document holds. +#[test] +fn the_list_of_type_follows_edits_undo_redo_and_the_active_document() { + use std::sync::Arc; + let (mut app, ids, _, _, xf) = type_among_paths(50); + let ctx = egui::Context::default(); + // Each listed object's id and node. + let nodes = |app: &VectorcraftApp| listed_type(app).iter().map(|t| (t.node.id, Arc::as_ptr(&t.node))).collect::>(); + hidden_chars(&mut app, &ctx, &xf); + let first = nodes(&app); + assert_eq!(first.len(), 3); + let added = + vectorcraft_doc::NodeId(app.session.execute("text.create", &json!({"x": 200, "y": 40, "text": "g h"})).unwrap()["id"].as_u64().unwrap()); + hidden_chars(&mut app, &ctx, &xf); + let with_new = nodes(&app); + assert_eq!(with_new.len(), 4); + assert!(with_new.iter().any(|(id, _)| *id == added), "the new object"); + assert!(app.canvas.hidden_chars.marks.contains_key(&added), "has marks"); + app.session.execute("text.setText", &json!({"id": ids[0].0, "text": "x\ty"})).unwrap(); + hidden_chars(&mut app, &ctx, &xf); + let edited = nodes(&app); + let node_of = |list: &[(vectorcraft_doc::NodeId, *const vectorcraft_doc::Node)], id| list.iter().find(|(i, _)| *i == id).map(|(_, n)| *n); + assert_ne!(node_of(&edited, ids[0]), node_of(&with_new, ids[0]), "the edited object's new node"); + assert_eq!(node_of(&edited, ids[1]), node_of(&with_new, ids[1]), "the others' nodes"); + assert_eq!(app.canvas.hidden_chars.marks[&ids[0]].1.chars.len(), 1, "the marks of the edited text: one tab"); + app.session.execute("edit.undo", &json!({})).unwrap(); + hidden_chars(&mut app, &ctx, &xf); + assert_eq!(nodes(&app), with_new, "Undo"); + assert_eq!(app.canvas.hidden_chars.marks[&ids[0]].1.chars.len(), 2, "the marks of the text before: a tab and a nonbreaking space"); + app.session.execute("edit.redo", &json!({})).unwrap(); + hidden_chars(&mut app, &ctx, &xf); + assert_eq!(nodes(&app), edited, "Redo"); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + assert!(hidden_chars(&mut app, &ctx, &xf).is_empty(), "another document: none of the first one's marks"); + assert!(nodes(&app).is_empty() && app.canvas.hidden_chars.marks.is_empty()); + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + hidden_chars(&mut app, &ctx, &xf); + assert_eq!(nodes(&app), edited, "back to the first document"); +} + +/// Neither overlay draws over type that the canvas does not draw: a hidden text object, or one in +/// a hidden group or layer. Shown again, its marks and lines come back. +#[test] +fn hidden_characters_and_auto_spell_check_leave_out_type_in_hidden_groups_and_layers() { + let (mut app, [a, b, c], group, layer, xf) = type_among_paths(10); + let ctx = egui::Context::default(); + let drawn = |app: &mut VectorcraftApp| { + let marks = hidden_chars(app, &ctx, &xf).len(); + let lines = spelling_lines(app, &ctx, &xf).len(); + let mut ids: Vec<_> = app.canvas.hidden_chars.marks.keys().copied().collect(); + ids.sort(); + let mut spelled: Vec<_> = app.canvas.spelling.lines.keys().copied().collect(); + spelled.sort(); + (ids, spelled, marks, lines) + }; + let all = drawn(&mut app); + assert_eq!((all.0.clone(), all.1.clone(), all.3), (vec![a, b, c], vec![a, b, c], 2)); + app.session.execute("object.setProps", &json!({"ids": [group.0], "visible": false})).unwrap(); + let (ids, spelled, marks, lines) = drawn(&mut app); + assert_eq!((ids, spelled, lines), (vec![a, c], vec![a, c], 1), "a hidden group"); + assert!(marks < all.2, "fewer marks: {marks} of {}", all.2); + assert!(listed_type(&app).iter().any(|t| t.node.id == b && !t.shown), "listed, not shown"); + app.session.execute("object.setProps", &json!({"ids": [group.0], "visible": true})).unwrap(); + assert_eq!(drawn(&mut app), all, "the group shown again"); + app.session.execute("layer.setProps", &json!({"id": layer.0, "visible": false})).unwrap(); + let (ids, spelled, _, lines) = drawn(&mut app); + assert_eq!((ids, spelled, lines), (vec![a, b], vec![a, b], 1), "a hidden layer"); + app.session.execute("layer.setProps", &json!({"id": layer.0, "visible": true})).unwrap(); + assert_eq!(drawn(&mut app), all, "the layer shown again"); + app.session.execute("object.setProps", &json!({"ids": [a.0], "visible": false})).unwrap(); + let (ids, spelled, _, _) = drawn(&mut app); + assert_eq!((ids, spelled), (vec![b, c], vec![b, c]), "a hidden text object"); + app.session.execute("object.setProps", &json!({"ids": [a.0], "visible": true})).unwrap(); + assert_eq!(drawn(&mut app), all, "the text object shown again"); +} + +/// An ignored diagnostic for the overlays' cost on a document of many paths and a little type: +/// frames of both overlays drawing from the kept list, and frames that list the type again each +/// time. There is no timing threshold; run on an idle machine and compare the printed cases. +#[test] +#[ignore = "manual performance diagnostic; no stable timing threshold"] +fn type_overlays_on_many_paths_diagnostic() { + use std::time::Instant; + const FRAMES: usize = 50; + for paths in [10_000, 100_000] { + let (mut app, _, _, _, xf) = type_among_paths(paths); + let ctx = egui::Context::default(); + let both = |app: &mut VectorcraftApp| { + hidden_chars(app, &ctx, &xf); + spelling_lines(app, &ctx, &xf); + }; + both(&mut app); + let t = Instant::now(); + for _ in 0..FRAMES { + both(&mut app); + } + let kept = t.elapsed(); + let t = Instant::now(); + for _ in 0..FRAMES { + app.canvas.text_nodes = TextNodes::default(); + both(&mut app); + } + let listed = t.elapsed(); + eprintln!( + "{paths} paths: {:?} a frame from the kept list, {:?} a frame listing the type again", + kept / FRAMES as u32, + listed / FRAMES as u32 + ); + } +} + /// General › Zoom with Mouse Wheel (#394), through the control channel's `ui.wheel`: off, /// the wheel scrolls and Cmd-wheel scrolls sideways (Scroll Sideways with Cmd/Ctrl + Wheel is on /// by default); on, the wheel zooms about the pointer, Shift-wheel diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index 958872d6b0..81215d883b 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -22,21 +22,13 @@ pub(super) fn hidden_chars_overlay(app: &mut VectorcraftApp, p: &egui::Painter, last.clear(); kept.inputs = inputs; } - // `walk` visits each node's `Arc` in the order `Document::walk` visits the nodes (depth first, - // in paint order). - fn walk(nodes: &[std::sync::Arc], f: &mut impl FnMut(&std::sync::Arc)) { - for n in nodes { - f(n); - if let Some(children) = n.children() { - walk(children, f); - } - } - } - walk(&st.doc.layers, &mut |n| { - let NodeKind::Text(tx) = &n.kind else { return }; + // Leaving out hidden objects and what is inside hidden groups and layers, as the canvas does. + for t in text_nodes(&mut app.canvas.text_nodes, st).iter().filter(|t| t.shown) { + let n = &t.node; + let NodeKind::Text(tx) = &n.kind else { continue }; // The box round the object's corners on screen, turned with the view. - if !n.visible || n.geometric_bounds().is_none_or(|b| !egui::Rect::from_points(&xf.quad(b)).intersects(clip)) { - return; + if n.geometric_bounds().is_none_or(|b| !egui::Rect::from_points(&xf.quad(b)).intersects(clip)) { + continue; } let marks = match last.remove(&n.id) { Some((was, marks)) if std::sync::Arc::ptr_eq(&was, n) => marks, @@ -62,7 +54,53 @@ pub(super) fn hidden_chars_overlay(app: &mut VectorcraftApp, p: &egui::Painter, p.text(xf.to_screen(at), align, glyph, font.clone(), color); } kept.marks.insert(n.id, (n.clone(), marks)); - }); + } +} + +/// One text object of the active document ([`TextNodes`]). +pub(super) struct TextNode { + pub(super) node: std::sync::Arc, + /// The object and every group and layer that holds it are visible: the canvas draws it. + pub(super) shown: bool, +} + +/// The text objects of the active document, for (document uid, revision): Show Hidden Characters +/// and Auto Spell Check draw over them every frame ([`crate::CanvasCache::text_nodes`]). A frame +/// that draws neither drops them ([`super::show`]). +#[derive(Default)] +pub struct TextNodes { + pub(super) list: Option<((u64, u64), TextList)>, +} + +/// The text objects of a document, in paint order ([`TextNodes`]). +pub(super) type TextList = std::sync::Arc>; + +/// The text objects of `st`'s document in the order `Document::walk` visits the nodes (depth +/// first, in paint order), hidden ones included. `kept` holds the list while the document and its +/// revision are those it was made for. +pub(super) fn text_nodes(kept: &mut TextNodes, st: &vectorcraft_engine::DocState) -> TextList { + let key = (st.uid, st.revision); + if let Some((k, list)) = &kept.list + && *k == key + { + return list.clone(); + } + fn walk(nodes: &[std::sync::Arc], shown: bool, out: &mut Vec) { + for n in nodes { + let shown = shown && n.visible; + if matches!(n.kind, NodeKind::Text(_)) { + out.push(TextNode { node: n.clone(), shown }); + } + if let Some(children) = n.children() { + walk(children, shown, out); + } + } + } + let mut list = Vec::new(); + walk(&st.doc.layers, true, &mut list); + let list = std::sync::Arc::new(list); + kept.list = Some((key, list.clone())); + list } /// `v` scaled to length 1, or `or` when `v` has no length. @@ -265,19 +303,12 @@ pub(super) fn spelling_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: kept.inputs = Some(inputs); } let stroke = Stroke::new(1.0, Color32::from_rgb(0xe0, 0x20, 0x20)); - // Depth first in paint order, leaving out hidden objects and what is inside them. - fn walk(nodes: &[std::sync::Arc], f: &mut impl FnMut(&std::sync::Arc)) { - for n in nodes.iter().filter(|n| n.visible) { - f(n); - if let Some(children) = n.children() { - walk(children, f); - } - } - } - walk(&st.doc.layers, &mut |n| { - let NodeKind::Text(tx) = &n.kind else { return }; + // Leaving out hidden objects and what is inside hidden groups and layers. + for t in text_nodes(&mut app.canvas.text_nodes, st).iter().filter(|t| t.shown) { + let n = &t.node; + let NodeKind::Text(tx) = &n.kind else { continue }; if !auto_spell_checks(n) || n.geometric_bounds().is_none_or(|b| !egui::Rect::from_points(&xf.quad(b)).intersects(clip)) { - return; + continue; } let lines = match last.remove(&n.id) { Some((was, lines)) if std::sync::Arc::ptr_eq(&was, n) => lines, @@ -287,7 +318,7 @@ pub(super) fn spelling_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: wavy_line(p, xf.to_screen(a), xf.to_screen(b), stroke); } kept.lines.insert(n.id, (n.clone(), lines)); - }); + } } /// Whether Auto Spell Check marks `n`'s words: not with an effect shown (the Appearance panel's diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..5ce1ca2497 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -840,7 +840,7 @@ since 2026-10-01. - **Justification… on type on a path:** each paragraph's Desired Word Spacing, Letter Spacing and Glyph Scaling set its glyphs on type on a path as on point and area type, so the text after a wider gap starts further along the path, alignment and overflow use the spaced length, and a list marker keeps its width. Minimum and Maximum are not used on a path, and vertical type is not glyph scaled. SVG export writes such type as outlines with a warning. Tests `tests::justify::type_on_a_path_takes_desired_spacing_and_scaling`, `type_on_a_path_is_aligned_and_fitted_at_desired_spacing`, `vertical_type_and_list_markers_on_a_path_are_not_glyph_scaled` and the SVG test `text_layout::justification_spacing_on_a_path_is_outlined`. Public reference: the help page (). - **Letter spacing and Full Justify between shaped clusters:** Desired Letter Spacing on any line, the letter spacing range of a justified line, and Single Word Justification's Full Justify add space only between shaped clusters, in horizontal, right-to-left and vertical type, so a combining mark stays on its letter and a Devanagari syllable's glyphs stay together. They add no space next to a zero-width format control (a soft hyphen, a bidi mark, embedding, override or isolate, a zero-width space, a joiner or non-joiner, a word joiner, a variation selector, a tag, the byte order mark), so a word wrapped in an override still reaches both edges of a justified line, and a Kinsoku push-in counts no gap at one either. A zero-width space is a line break opportunity but not a word separator ([CSS Text Level 3](https://www.w3.org/TR/css-text-3/#word-separator) does not list it), so a justified line gives it no share of its room. Desired Letter Spacing between the letters on either side of a zero-width space goes after the zero-width space, so a line that breaks there ends at its last letter, and the line breaker does not measure a gap after it. A line that Full Justify spreads and that ends in a drawn hyphen puts the same gap between its last letter and the hyphen. The cluster boundary is VectorCraft's own rule, based on the typographic character unit of [CSS Text Level 3](https://www.w3.org/TR/css-text-3/#typographic-character-unit). Tests `tests::justify::single_word_full_justify_keeps_combining_mark_with_base`, `desired_and_fitted_letter_spacing_skip_shaped_cluster`, `rtl_single_word_cluster_gap_follows_drawn_order`, `vertical_single_word_cluster_gap_follows_drawn_order`, `single_word_full_justify_keeps_conjunct_cluster`, `desired_letter_spacing_skips_bidi_format_controls`, `letter_spacing_and_full_justify_skip_joiners_and_soft_hyphens`, `format_controls_are_the_zero_width_default_ignorables`, `zero_width_space_takes_no_word_space_room`, `desired_letter_spacing_ends_a_line_broken_at_a_zero_width_space_without_a_gap`, `single_word_full_justify_spreads_up_to_the_drawn_hyphen` and `layout::wrapping_tests::kinsoku_shori_type_counts_no_gap_at_a_format_control`. Public reference: the help page (). - **Justified lines with tabs:** a tab is not a word space, so a justified area type line no longer gives it a share of its room that no glyph draws. On a justified line with a tab, the text up to the last tab keeps its spacing, each tab keeps its stop and its leader stays in its gap, and the text after the last tab takes the room (word spaces first, then letter spacing, glyph scaling and the gaps between its letters), so the line ends on the far edge. A tab separates two words, so Single Word Justification does not align a word-tab-word line. Right-to-left lines take the text drawn after the last tab drawn, and vertical lines work down the column. Spreading the room after the last tab is VectorCraft's own rule. Tests `tests::justify::a_justified_line_with_a_tab_spreads_the_text_after_it_to_the_edge`, `a_justified_tab_keeps_its_leader_inside_its_gap`, `a_justified_word_tab_word_line_reaches_the_edge`, `the_last_line_with_a_tab_fills_the_measure_only_with_justify_all`, `a_justified_line_takes_its_room_after_its_last_tab`, `a_justified_vertical_line_with_a_tab_reaches_the_end_of_its_column`, `a_justified_right_to_left_line_with_a_tab_spans_its_measure` and `justified_point_type_with_a_tab_keeps_its_width`. Public reference: the help pages (, ). -- **Show Hidden Characters marks every character that prints no ink:** [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/insert-white-space-and-break-characters.html) lists the characters that Type › Show Hidden Characters makes visible: paragraph returns, forced line breaks, tabs, spaces, nonbreaking spaces, discretionary hyphens and the end of the text. Besides the dot over a space, ¶ at a paragraph's end and # at the story's end, the canvas draws an arrow across each tab's advance to its stop, a ring over a nonbreaking space (U+00A0) and a smaller one over a narrow nonbreaking space (U+202F), a short tick over the spaces of a set width (U+2000 to U+200A, U+205F, U+3000), ¬ at a discretionary hyphen (U+00AD) whether or not the line breaks there, and a bent arrow after a line that a forced line break (U+2028) ends, which gets no ¶. The marks follow the baseline of vertical type and of type on a path, ¶ goes at the left end of a right-to-left line, and type on a path gets # after its last character when the path shows all of its text. The shapes of the marks, and marking U+202F and the spaces of a set width, are VectorCraft's own rules. The marks are drawn only on the canvas and are not saved or exported. Tests: `canvas::tests::hidden_characters_mark_tabs_nonbreaking_spaces_and_discretionary_hyphens`, `hidden_characters_mark_forced_line_breaks`, `hidden_characters_mark_a_discretionary_hyphen_at_a_break_once`, `hidden_characters_follow_vertical_type`, `hidden_characters_end_a_right_to_left_line_at_its_left`, `hidden_characters_mark_type_on_a_path` and `show_hidden_characters_draws_every_kind_of_mark`. +- **Show Hidden Characters marks every character that prints no ink:** [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/insert-white-space-and-break-characters.html) lists the characters that Type › Show Hidden Characters makes visible: paragraph returns, forced line breaks, tabs, spaces, nonbreaking spaces, discretionary hyphens and the end of the text. Besides the dot over a space, ¶ at a paragraph's end and # at the story's end, the canvas draws an arrow across each tab's advance to its stop, a ring over a nonbreaking space (U+00A0) and a smaller one over a narrow nonbreaking space (U+202F), a short tick over the spaces of a set width (U+2000 to U+200A, U+205F, U+3000), ¬ at a discretionary hyphen (U+00AD) whether or not the line breaks there, and a bent arrow after a line that a forced line break (U+2028) ends, which gets no ¶. The marks follow the baseline of vertical type and of type on a path, ¶ goes at the left end of a right-to-left line, and type on a path gets # after its last character when the path shows all of its text. The shapes of the marks, and marking U+202F and the spaces of a set width, are VectorCraft's own rules. The marks are drawn only on the canvas and are not saved or exported. Type that the canvas does not draw, because it or a group or layer holding it is hidden, gets no marks; this is VectorCraft's own rule. Tests: `canvas::tests::hidden_characters_mark_tabs_nonbreaking_spaces_and_discretionary_hyphens`, `hidden_characters_and_auto_spell_check_leave_out_type_in_hidden_groups_and_layers`, `hidden_characters_mark_forced_line_breaks`, `hidden_characters_mark_a_discretionary_hyphen_at_a_break_once`, `hidden_characters_follow_vertical_type`, `hidden_characters_end_a_right_to_left_line_at_its_left`, `hidden_characters_mark_type_on_a_path` and `show_hidden_characters_draws_every_kind_of_mark`. - **The text style panel menus' Duplicate and Delete:** in the Character Styles and Paragraph Styles panel menus, Duplicate highlights the copy, as Create New Style highlights the new style, and Delete leaves no style highlighted, as the Delete button does, so Duplicate, Clear Overrides, Redefine and Style Options are disabled until another style is clicked. A highlighted style that is renamed in Style Options or deleted by a command is no longer highlighted either. The tests `panels::text_styles::tests::panel_menu_duplicate_and_delete_update_the_highlighted_style` and `a_highlighted_style_that_is_no_longer_listed_is_not_highlighted` cover this. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Item context menus in the Character Styles and Paragraph Styles panels:** right-clicking a style row displays a context menu ({Kind} Style Options…, Duplicate {Kind} Style, Delete {Kind} Style, Redefine {Kind} Style, Clear Overrides). Right-clicking an unselected row highlights it before displaying the menu; right-clicking an item in an existing multi-selection preserves the selection. Style Options and Delete are disabled for the built-in Normal style; Redefine is enabled when active text has styling; Clear Overrides is enabled when text is selected. Duplicate creates ` copy` and highlights it; Delete removes non-Normal styles in one undo step. Tests `panels::text_styles::tests::right_click_context_menu_in_character_styles_panel`, `right_click_context_menu_in_paragraph_styles_panel`, `right_click_context_menu_normal_style_disables_options_and_delete`, and `right_click_context_menu_preserves_multiselection`. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Names of new styles and symbols:** `charStyle.new` and `paraStyle.new` trim the white space around the name they are given, as `charStyle.rename` and `paraStyle.rename` do, and refuse a name that is then empty; Duplicate names its copy from the trimmed name. `symbol.new` and `symbol.duplicate` trim the name as Symbol Options does, and `library.use` adds a library's text style under its trimmed name. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). @@ -2507,6 +2507,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A subpath keeps its anchors in chunks of up to 256 anchors, and the versions of a path share the chunks they have not changed. Editing one anchor copies only the chunk that holds it, so its undo step keeps that chunk instead of a copy of every anchor; adding or deleting an anchor copies the chunk it is in and rebuilds the subpath's table of chunks. When the renderer looks for the anchors that moved, it compares only the chunks the edit copied. Moving one anchor of a selected open path of 10,000 or 200,000 anchors (`path.moveAnchor`, `path.setHandle`, `path.moveAnchors` or a nudge) keeps at most 48 KiB in the undo step and in the redo step, where it kept a copy of every anchor at 56 bytes each (counted in the engine's tests). Files are written and read as before, each subpath's anchors as one list. Opening a document keeps the layouts it makes for its type objects, up to 128 MiB, and the first frame uses them instead of laying those objects out again. It does not keep a layout with bitmap or color glyphs or a text object with a gradient. The frame uses a layout only for a text object equal to the one laid out, and only while the fonts and the hyphenation exceptions have not changed. It uses each layout once. The renderer drops the rest when a frame that used one ends, and all of them after eight frames that use none. The frames of a threaded story are laid out while the file is read, and the first frame lays them out again. The pixels are the same. On Windows at 1600 × 1200, in medians of seven interleaved rounds of a local example, counted in the main thread's CPU cycles because other builds were running: with 5,000 point type objects in view the first frame takes 409 million cycles instead of 894 million and the open 816 million instead of 665 million, so the two together take 1,225 million instead of 1,559 million; with one area type object of 500 paragraphs the first frame takes 697 million instead of 1,193 million and the open 535 million instead of 568 million. Type › Show Hidden Characters keeps the marks it places on each text object from one frame to the next. The canvas lays a text object out again when an edit changes it or its threaded story, or when the last frame that showed the marks did not draw it, and it lays out all type in view again when the fonts or the hyphenation exceptions change. With 1,000 two-line labels in view, drawing the marks takes 0.8 ms per frame in a release build instead of 19.7 ms. + Show Hidden Characters and Auto Spell Check find the document's text objects among its other objects once for each change to the document, in one list that both draw from, instead of visiting every object in every frame. An edit, Undo, Redo or a switch to another document makes a new list, and the canvas drops the list while it draws neither overlay. With a Type tool active, the in and out ports of the selected area type and type on a path, and the highlight of a selected story's other frames after Select All, use each frame's layout from the last frame instead of laying the frame out again. A frame is laid out again when its text object changes, or when the fonts or the hyphenation exceptions change. With 200 selected area type frames of about 400 characters, one of them being edited, the Type tool's overlays take 0.27 ms per frame instead of 121 ms; with a 5-frame story selected they take 0.016 ms instead of 2.0 ms (release build on Linux, medians of seven runs, measured while other builds were running). A selection with more than 100,000 points to outline shows its bounds instead of each object's outline and anchors. Paths count their anchors. Area type and type on a path count the anchors of their frame or path, and point type counts six: its box's corners and the ends of its baseline marker. Images, symbol instances, placed documents, and area type or type on a path in perspective count the four corners of their box, and gradient meshes and envelopes count their points and the ends of their mesh lines. The hover highlight leaves out an object past that count, and such an object shows its bounds as the key object. With 32,768 type objects, images, symbol instances, gradient meshes or envelopes selected, the selection's outlines and anchors add fewer than 100 vertices to the canvas's mesh (#2460). The canvas keeps the selected objects' outlines, anchors and handles from one frame to the next as one mesh. It builds an object's marks again when the object, its layer color or its selected anchors change. A pan moves the kept outlines and handles and places the anchor squares again. Each subpath and handle gets its triangles the first time it is in view. A frame with a new zoom or rotation draws the marks one shape at a time and keeps nothing, and the next frame at that view builds them. The pixels are the same, apart from two small differences: a kept outline's corner of exactly 90 degrees in a rotated view can keep its miter or cut corner after a pan, and kept vertices can move by rounding errors. On Windows at 1440 × 900, in a release build, with 2,000 selected circles of 50 anchors each in 10 fill colors, an idle frame takes 12.8 ms instead of 59.9 ms with the Selection tool and 29.8 ms instead of 192.1 ms with Direct Selection (medians of five runs). A frame during a zoom takes about what it did: 86.7 ms instead of 80.0 ms with the Selection tool. diff --git a/docs/type-parity.md b/docs/type-parity.md index 111ee5d838..7f142cb60f 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -50,7 +50,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Roman Hanging Punctuation | done | Paragraph panel menu › Roman Hanging Punctuation, `text.setFormat {romanHangingPunctuation}` (#2756): per paragraph, Optical Margin Alignment's punctuation and amounts without the letters; paragraph styles carry it. Evidence: `tests::roman_hanging_punctuation_hangs_punctuation_but_not_letters`, `typecmd::area_tests::roman_hanging_punctuation_is_set_per_paragraph_and_saved_only_when_on` | | Hyphenation… and Justification… options | done | Eleven Indian languages use attributed patterns and preserve syllables in both composers (#4947). Hyphenation… (`ui.hyphenation`, `text.setFormat`) sets each paragraph's Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone (Single-line Composer only) and Hyphenate Capitalized Words, and paragraph styles carry them (#2310). Justification… (`ui.justification`, `text.setFormat`, #2755) sets Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired, Maximum), Auto Leading and Single Word Justification; Desired applies to every line, justified lines and the Every-line Composer use the ranges. Vertical type isn't glyph scaled. Auto Leading also sets the Leading the Character panel shows for Auto type, the leading Alt+↑/↓ (`type.step`) steps from, per paragraph, and the lines Fill with Placeholder Text counts. Evidence: `crates/text/src/tests/justify.rs`, `dialogs::justification::tests`, `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading` | | Tab stops and leaders; Tabs panel | partial | Tabs panel and stops with leaders in the model (`text.tabs.set`); a stop drags from where the press landed (#1458); leaders fill the tab's gap, repeated on a grid so they line up from line to line (#1877); Ctrl-dragging a stop (Command on macOS) moves all the stops together; in right-aligned area type the text before a line's last tab sits at its stops, from the left edge, and the text after it against the right edge, as Illustrator's own layout in a user's `.ai` sets a price list (evidence: `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`; centred lines are still aligned as a whole); in justified area type the text up to a line's last tab keeps its spacing and its tabs their stops, and the text after the last tab takes the line's room to the far edge, VectorCraft's own rule (evidence: `tests::justify::a_justified_line_with_a_tab_spreads_the_text_after_it_to_the_edge` and the other tab tests in `crates/text/src/tests/justify.rs`) | -| Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters`: marks spaces, tabs, nonbreaking and narrow nonbreaking spaces, the spaces of a set width, discretionary hyphens, forced line breaks, paragraph ends and the story's end, in horizontal, vertical and right-to-left type and on a path; the mark shapes are VectorCraft's own. Evidence: `canvas::tests::hidden_characters_*` | +| Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters`: marks spaces, tabs, nonbreaking and narrow nonbreaking spaces, the spaces of a set width, discretionary hyphens, forced line breaks, paragraph ends and the story's end, in horizontal, vertical and right-to-left type and on a path, and none on type in a hidden group or layer; the mark shapes are VectorCraft's own. Evidence: `canvas::tests::hidden_characters_*` | | Spell check (Check Spelling, Auto Spell Check, custom dictionary) | done | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The modal Check Spelling dialog is done: Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in sentence context ("Not in Dictionary"), a list of suggestions with double-click or selection to replace ("Change to" field), and action buttons: Ignore, Ignore All, Change (one-step Undo/Redo via `text.editRange`), Change All (batched across occurrences in a single undo step), Add to Dictionary (`text.spelling.addWord`), Done and Cancel, with keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close). Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog), `crates/ui-egui/src/dialogs/check_spelling.rs` (the Check Spelling dialog). | | Smart Punctuation, Change Case, Find & Replace | done | Type › Smart Punctuation… opens a dialog with the ff, fi, ffi and ff, fl, ffl ligatures, Smart Quotes, Smart Spaces, En, Em Dashes, Ellipses and Expert Fractions, Replace In and Report Results, which lists the count of each replacement; ligatures and fractions are written only where the font has a glyph for them. Evidence: `tests::menucmds::smart_punctuation_ligatures_spaces_and_fractions_are_counted`, `smart_punctuation_skips_ligatures_and_fractions_the_font_lacks`, `smart_spaces_keeps_one_space_after_a_period`, `dialogs::smart_punctuation::tests::menu_item_opens_the_dialog_and_ok_reports_the_counts` | | 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 | From 1e18a7e9fc77ff4deba2f45139ea248723ded7b2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:31:59 -0800 Subject: [PATCH 10/55] i18n: Indonesian translates the banner hem and grommet errors and the save failure Indonesian joined the complete-message languages on main, so it needs the twelve banner and recovery rows the other complete catalogs carry. --- crates/ui-egui/src/i18n/id.tsv | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..7e066a4494 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8579,6 +8579,18 @@ breakText Glyphs Glif Box Kotak Swatch Sampel warna Direction Arah +@msg `spacing` must be more than 0 and at most {MAX_DISTANCE} pt `spacing` harus lebih dari 0 dan paling besar {MAX_DISTANCE} pt +@msg `{key}` must be from 0 to {MAX_DISTANCE} pt `{key}` harus dari 0 sampai {MAX_DISTANCE} pt +@msg `{key}` must be from 0.01 to 1000 pt `{key}` harus dari 0,01 sampai 1000 pt +@msg select the banner, or mark every artboard seleksi spanduk, atau tandai setiap artboard +@msg the banner has no width or height spanduk tidak memiliki lebar atau tinggi +@msg the grommet inset is too large for the banner jarak mata ayam dari tepi terlalu besar untuk spanduk +@msg the hem is too deep for the banner lipatan terlalu dalam untuk spanduk +@msg the spacing makes more than {MAX_GROMMETS} grommets spasi ini menghasilkan lebih dari {MAX_GROMMETS} mata ayam +@msg there is no banner to mark tidak ada spanduk untuk ditandai +@msg turn on at least one side aktifkan setidaknya satu sisi +@msg with no hem and no grommets there is nothing to mark tanpa lipatan dan tanpa mata ayam tidak ada yang perlu ditandai +@msg {saving} failed: {e} {saving} gagal: {e} Banner Hems and Grommets… Lipatan dan Mata Ayam Spanduk… Banner Hems and Grommets Lipatan dan Mata Ayam Spanduk Hem Lipatan From 8c738353e5db35e9dc043c045f09b539c95ae209 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:50:13 -0800 Subject: [PATCH 11/55] Width Point Edit: OK and Delete act only on the stroke and the paired points it opened on - OK and Delete on several width points are refused when a selected point became, or stopped being, one half of a discontinuous point since the dialog opened, for example after a point was added at its place. Before, Delete removed only the selected half and left the new one, and OK edited only the selected half. - OK and Delete are refused when `ui.dialog.set` changed `id`, `index`, `outIndex` or `indices` after the dialog opened. Before, a changed `id` sent the edit or the removal to another stroke whose width points matched. --- crates/ui-egui/src/dialogs/width_point.rs | 44 ++++++++++-- .../ui-egui/src/dialogs/width_point/tests.rs | 67 +++++++++++++++++++ docs/control-protocol.md | 4 +- docs/mcp.md | 5 +- 4 files changed, 113 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/width_point.rs b/crates/ui-egui/src/dialogs/width_point.rs index 56caf05845..65d5680671 100644 --- a/crates/ui-egui/src/dialogs/width_point.rs +++ b/crates/ui-egui/src/dialogs/width_point.rs @@ -32,7 +32,9 @@ //! `outSide2`, `outTotalWidth` and `outLinked`. //! //! OK and Delete on existing points, one or several, are refused when those points changed since -//! the dialog opened or another document is active. +//! the dialog opened (their place, their widths, or which of them pair as a discontinuous point) or +//! another document is active. OK and Delete are also refused when `id`, `index`, `outIndex` or +//! `indices` no longer holds the value it had when the dialog opened. use egui::vec2; use serde_json::{Value, json}; @@ -65,6 +67,10 @@ const DOC: &str = "__doc"; /// The place and side widths `[t, left, right]` (points) of the existing point the one-point dialog /// opened on, and of the outgoing half of a discontinuous point. const AT: &str = "__at"; +/// The values of [`TARGET_KEYS`] when the dialog opened. +const TARGET: &str = "__target"; +/// The fields that name the stroke and the points OK and Delete act on. +const TARGET_KEYS: [&str; 4] = ["id", "index", "outIndex", "indices"]; /// The fields of each set of side widths of several points: Side 1, Side 2, Total Width and the /// link, for the incoming set and the outgoing set. @@ -296,6 +302,14 @@ fn pairs(points: &[(f64, f64, f64)]) -> Vec> { .collect() } +/// The sets of side widths that edit width point `i`, `[incoming, outgoing]`, with the points +/// paired as `pairs` pairs them: an outgoing half is not edited by the incoming set, and an +/// incoming half not by the outgoing set. +fn sets(pairs: &[Option], i: usize) -> [bool; 2] { + let outgoing = i.checked_sub(1).is_some_and(|a| pairs[a] == Some(i)); + [!outgoing, pairs[i].is_none()] +} + /// The width points `indices` of `id` names, each discontinuous point's two halves together. fn target(app: &VectorcraftApp, id: u64, indices: &Value) -> Result { const NONE: &str = "no such width point"; @@ -326,7 +340,7 @@ fn target(app: &VectorcraftApp, id: u64, indices: &Value) -> Result Value { + json!(TARGET_KEYS.map(|key| d.fields.get(key).cloned().unwrap_or(Value::Null))) +} + /// Open Width Point Edit for `index`, or a prospective point at fraction `t` without an index /// (`{id, index?, t?, adjustAdjoining?}`), or for several existing points (`{id, indices, /// adjustAdjoining?}`). Opening only samples the stroke: confirmation creates the point. @@ -409,7 +429,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { fields[key] = value; } } - app.ui.dialog = Some(Dialog::new(KIND, fields)); + let mut d = Dialog::new(KIND, fields); + d.fields.insert(TARGET.into(), targets(&d)); + app.ui.dialog = Some(d); Ok(Value::Null) } @@ -547,6 +569,12 @@ fn same_document(app: &VectorcraftApp, d: &Dialog) -> Result<(), String> { } } +/// Whether the dialog still names the stroke and points it opened on: `ui.dialog.set` can set +/// `id`, `index`, `outIndex` and `indices`, and OK and Delete refuse any other value. +fn same_target(d: &Dialog) -> Result<(), String> { + if d.fields.get(TARGET) == Some(&targets(d)) { Ok(()) } else { Err("no such width point".into()) } +} + /// `id`'s width profile and the stroke's half weight, when the points `open` are still where and as /// wide as when the dialog opened, exactly. fn opened_profile(app: &VectorcraftApp, id: u64, open: &[Entry]) -> Result<(WidthProfile, f64), String> { @@ -567,6 +595,12 @@ fn opened_profile(app: &VectorcraftApp, id: u64, open: &[Entry]) -> Result<(Widt return Err(NONE.into()); } } + // Each point is still a continuous point or the same half of a discontinuous one: a point added + // at the place of one would leave it changing only one half. + let pairs = pairs(&profile.points); + if open.iter().any(|o| o.sets != sets(&pairs, o.index)) { + return Err(NONE.into()); + } Ok((profile, half)) } @@ -636,6 +670,7 @@ fn confirm_several(app: &mut VectorcraftApp, d: &Dialog) -> Result = open.iter().map(|e| e.index).collect(); @@ -677,8 +712,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { app.ui.dialog = None; return Ok(Value::Null); } - // OK and Delete act only on the document and the points the dialog opened on. + // OK and Delete act only on the document, the stroke and the points the dialog opened on. same_document(app, d)?; + same_target(d)?; if let Some(index) = index.as_u64().and_then(|i| usize::try_from(i).ok()) { unchanged_point(app, d, index, out.as_ref().and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()))?; } diff --git a/crates/ui-egui/src/dialogs/width_point/tests.rs b/crates/ui-egui/src/dialogs/width_point/tests.rs index 0653c5fb19..ddaec66c1a 100644 --- a/crates/ui-egui/src/dialogs/width_point/tests.rs +++ b/crates/ui-egui/src/dialogs/width_point/tests.rs @@ -1047,3 +1047,70 @@ fn one_point_refuses_a_change_since_the_dialog_opened() { assert_eq!(app.session.doc().unwrap().doc, paired, "{field}"); } } + +#[test] +fn several_points_refuse_a_change_in_which_points_pair() { + // A point added at a selected point's place, after it, pairs with it; a third point at a + // discontinuous point's place unpairs its halves. The selected points keep their index, place + // and widths. + let cases = [ + ( + three_app as fn() -> (VectorcraftApp, u64), + json!([1, 3]), + json!([[0, 1, 1], [0.25, 0.8, 0.4], [0.5, 0.8, 0.8], [0.75, 0.4, 1.2], [0.75, 0.3, 0.3], [1, 1, 1]]), + ), + (pair_app, json!([0, 1]), json!([[0, 1, 1], [0.5, 0.8, 0.8], [0.5, 0.4, 1.2], [0.5, 0.3, 0.3], [1, 1, 1]])), + ]; + for (make, indices, points) in cases { + for field in ["side2", "discard"] { + let (mut app, id) = make(); + app.run("ui.widthPointEdit", json!({"id": id, "indices": indices})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key(OPEN), "{indices}"); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": points})).unwrap(); + let changed = app.session.doc().unwrap().doc.clone(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert(field.into(), if field == "discard" { json!(true) } else { json!(5) }); + assert!(super::super::confirm(&mut app).is_err(), "{indices} {field}"); + assert_eq!(app.session.doc().unwrap().doc, changed, "{indices} {field}"); + } + } +} + +#[test] +fn ok_and_delete_refuse_another_stroke_or_point_set_into_the_dialog() { + let set = |app: &mut VectorcraftApp, field: &str, value: Value| { + let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": field, "value": value})); + let crate::control::Outcome::Done(r) = crate::control::handle(app, &egui::Context::default(), &req) else { + panic!("expected an immediate reply") + }; + assert_eq!(r["ok"], json!(true), "{field}: {r}"); + }; + // `field` set to `value` on the dialog opened with `opened`, then `action` and OK. + let cases = [ + (json!({"indices": [1, 3]}), "id", None, "side1"), + (json!({"indices": [1, 3]}), "id", None, "discard"), + (json!({"indices": [1, 3]}), "indices", Some(json!([1, 2])), "side1"), + (json!({"index": 2}), "id", None, "side1"), + (json!({"index": 2}), "id", None, "discard"), + (json!({"index": 2}), "index", Some(json!(1)), "discard"), + (json!({"t": 0.4}), "id", None, "side1"), + ]; + for (opened, field, value, action) in cases { + let (mut app, id) = three_app(); + // Another stroke in the document with the same weight and width points. + let other = app.run("shape.line", json!({"x1": 100, "y1": 250, "x2": 300, "y2": 250})).unwrap()["id"].as_u64().unwrap(); + app.run("stroke.set", json!({"ids": [other], "weight": 10})).unwrap(); + let profile = json!([[0, 1, 1], [0.25, 0.8, 0.4], [0.5, 0.8, 0.8], [0.75, 0.4, 1.2], [1, 1, 1]]); + app.run("stroke.widthProfile.set", json!({"ids": [other], "points": profile})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let mut p = opened.clone(); + p["id"] = json!(id); + app.run("ui.widthPointEdit", p).unwrap(); + set(&mut app, field, value.unwrap_or(json!(other))); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert(action.into(), if action == "discard" { json!(true) } else { json!(5) }); + assert!(super::super::confirm(&mut app).is_err(), "{opened} {field} {action}"); + assert_eq!(app.session.doc().unwrap().doc, before, "{opened} {field} {action}"); + assert!(app.ui.dialog.is_some(), "{opened} {field} {action}"); + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dafab93a58..c8b9137af3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -656,7 +656,9 @@ as it was; `totalWidth` scales each point's own two sides to that total; a null `stroke.widthPoint.remove {id, indices}`. With `adjustAdjoining`, each changed point changes the nearest unselected point at another place before and after it in proportion to its change since the dialog opened; a point next to two changed points takes both changes. These rules for several points are VectorCraft's own. Confirm and Delete on existing -points, one or several, are refused when those points changed since the dialog opened or another document is active. +points, one or several, are refused when those points changed since the dialog opened (their place, their widths, or +which of them pair as a discontinuous point) or another document is active. Confirm and Delete are also refused when +`ui.dialog.set` changed `id`, `index`, `outIndex` or `indices` from the value it had when the dialog opened. Corners: double-clicking a Live Corners widget with the Selection or Direct Selection tool, or `ui.corners {id?, corners?}`, opens the `corners` dialog for a path's corners (the Direct-Selected ones, else every corner; fields `id`, diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..422dbd4e5e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8611,8 +8611,9 @@ turn it off to keep each point's other side), and Total Width scales each point' one `stroke.widthProfile.set` (one undo step, none when nothing changed), and Delete removes them all; with a discontinuous point among them, Incoming and Outgoing edit its two halves and both edit the continuous points. Malformed or out-of-range `indices`, or more than one of `index`, `indices` and `t`, are errors that open no dialog. OK -and Delete on existing points are refused when those points changed since the dialog opened or another document is -active. +and Delete on existing points are refused when those points changed since the dialog opened (their place, their widths, +or which of them pair as a discontinuous point) or another document is active. OK and Delete are also refused when +`id`, `index`, `outIndex` or `indices` no longer holds the value it had when the dialog opened. `document.inspect` reports a path's `strokeOptions.widthPoints` (`[t, left, right]`, factors of half the weight; null for a uniform stroke). `stroke.widthPoint.remove {id, index | indices}` deletes points; `stroke.widthProfile.set {ids, points}` replaces them all, as dragging several Shift-selected points with the Width tool does in one undo step. From 76127a13b685dd434f5c9d45f108cfc7dffe6cad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:54:49 -0800 Subject: [PATCH 12/55] Canvas: Color Settings and a reloaded profile render the art again Edit > Color Settings, a profile in use loaded again under its name, a removed profile and a change to the document's assigned profiles only raise the documents' revisions. The art and the render options stay the same, so the canvas kept the frame drawn through the previous color conversion. The canvas's frame key now holds the active color settings and the loaded profiles' generation, so a change to either renders the frame again through the new conversion. --- crates/ui-egui/src/caches.rs | 5 ++ crates/ui-egui/src/canvas.rs | 1 + crates/ui-egui/src/canvas/tests.rs | 91 ++++++++++++++++++++++++++++++ 3 files changed, 97 insertions(+) diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6e1d229023..ec50e4c8a4 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -225,6 +225,11 @@ pub struct CacheKey { /// The paper under the art that translucent art is blended with before the conversion /// ([`crate::display_profile::convert_over`]). None without a display profile, and in Outline. pub backdrop: Option>, + /// The active color settings ([`vectorcraft_color::cms::active_settings`]) and the loaded + /// profiles' generation ([`vectorcraft_color::cms::profiles_generation`]) the frame's colors + /// were converted with: Edit › Color Settings, a profile loaded again under its name or removed, + /// and the front document's assigned profiles change them without changing the document. + pub color: (vectorcraft_color::cms::ColorSettings, u64), } impl CacheKey { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b366665d4..f9a49a3e18 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -923,6 +923,7 @@ fn cache_key( // Preferences › Performance › Use Monitor Profile for Canvas. display: app.display_profile.key(app.session.prefs.monitor_profile_display), backdrop: backdrop(app, st, app.outline_view()), + color: (vectorcraft_color::cms::active_settings(), vectorcraft_color::cms::profiles_generation()), } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..fa9a6b813e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4801,6 +4801,97 @@ fn appearance_of_black_on_screen_shows_pure_black_as_rgb_black() { assert!(near(middle(&mut app).expect("re-rendered"), accurate), "accurate again"); } +/// A change of the color settings, and a profile in use loaded again under its name, re-render the +/// canvas through the new conversion. They raise the documents' revisions but leave the art as it +/// is, so [`changed_pixels`] finds no part of the frame shown that changed: the frame's +/// key holds the color settings and the loaded profiles' generation. A frame with nothing changed +/// renders nothing. +#[test] +fn color_settings_and_a_reloaded_profile_render_the_canvas_again() { + const CHILD: &str = "VECTORCRAFT_TEST_CANVAS_COLOR_SETTINGS"; + if std::env::var_os(CHILD).is_none() { + // Color settings and loaded profiles are process-wide: change them in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "canvas::tests::color_settings_and_a_reloaded_profile_render_the_canvas_again", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated canvas color test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + use vectorcraft_color::cms; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + app.canvas.worker_started = true; // render on this thread + // Larger than the view: the middle of the art's raster is its fill. + let id = app.run("shape.rectangle", json!({"x": -5000, "y": -5000, "width": 10000, "height": 10000})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [id], "color": {"c": 60, "m": 10, "y": 80, "k": 0}})).unwrap(); + let ctx = egui::Context::default(); + // The middle pixel of the art's raster uploaded by one frame, None when it was not re-rendered. + let middle = |app: &mut VectorcraftApp| -> Option<[u8; 4]> { + let (_, mut delta) = frame_output(app, &ctx); + let art = app.canvas.texture.as_ref().unwrap().id(); + let px = delta.set.iter().find(|e| e.0.eq(&art)).and_then(|e| e.1.last()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + let [w, h] = img.size; + img.pixels[h / 2 * w + w / 2].to_array() + }); + delta.clear(); + px + }; + let ink = vectorcraft_color::Color::cmyk(0.6, 0.1, 0.8, 0.0); + let through = |cmyk: &str| { + let c = cms::Cms::new(&cms::ColorSettings { cmyk: cmyk.into(), ..cms::working_settings() }).unwrap().display_rgb(&ink); + c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) + }; + let near = |a: [u8; 4], b: [u8; 3]| a[..3].iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 3); + let (generic, device) = (through(cms::GENERIC_CMYK), through(cms::DEVICE_CMYK)); + assert!(!near([generic[0], generic[1], generic[2], 255], device), "the two CMYK spaces draw the ink differently: {generic:?}, {device:?}"); + + let first = middle(&mut app).expect("the first frame renders the art"); + assert!(near(first, generic), "through the working CMYK space: {first:?}, not {generic:?}"); + assert_eq!(middle(&mut app), None, "nothing changed: no re-render"); + app.run("edit.colorSettings", json!({"cmyk": cms::DEVICE_CMYK})).unwrap(); + let shown = middle(&mut app).expect("Color Settings re-render the canvas"); + assert!(near(shown, device), "through the new working CMYK space: {shown:?}, not {device:?}"); + assert_eq!(middle(&mut app), None, "nothing changed since: no re-render"); + app.run("edit.colorSettings", json!({"cmyk": cms::GENERIC_CMYK})).unwrap(); + assert!(near(middle(&mut app).expect("re-rendered"), generic), "back to the first working space"); + + // A built-in CMYK profile's file renamed `name`: padded with spaces, which names drop. + let renamed = |builtin: &str, name: &str| { + let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + let mut bytes = cms::icc_bytes(builtin).unwrap().to_vec(); + let (from, to) = (utf16(builtin), utf16(&format!("{name: Date: Fri, 20 Nov 2026 17:40:52 -0800 Subject: [PATCH 13/55] OpenType: menu check marks skip empty frames of selected stories With the Selection tool, the panel menu's Proportional Metrics, H or V Style and Roman Italics read every run of the selected stories, including an empty frame's run. An empty frame without the setting made the item show unchecked while every character had it, and choosing it then turned the setting on instead of off. A run with no text now counts only when no run has text, as at a Type tool caret. --- crates/ui-egui/src/panels/opentype.rs | 57 ++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index e52c852afb..05fb6f671e 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -122,7 +122,8 @@ fn shown_figure(app: &VectorcraftApp) -> Option { /// Whether `flag` is on for every character a toggle changes (`Some(true)`), for none of them /// (`Some(false)`), or only for some (`None`). At a Type tool caret, and after Select All in a /// threaded story, the command styles all the text ([`run_features`]), so every character of it -/// counts, as in [`edit`]. +/// counts, as in [`edit`]. There, and with the Selection tool, a run with no text (an empty +/// frame's) counts only when no run has text. fn shown_flag(app: &VectorcraftApp, flag: Flag) -> Option { shown(app, |s| flag.get(&OtFeatures::from_tags(s.features.iter().map(String::as_str)))) } @@ -130,7 +131,13 @@ fn shown_flag(app: &VectorcraftApp, flag: Flag) -> Option { /// Whether `on` holds for every character a menu item changes (`Some(true)`), for none of them /// (`Some(false)`), or only for some (`None`), read as [`shown_flag`] reads a feature. fn shown(app: &VectorcraftApp, on: impl Fn(&CharStyle) -> bool) -> Option { - if let Some(mut runs) = whole_text_runs(app) { + let runs = match whole_text_runs(app) { + Some(runs) => Some(runs), + // With the Selection tool: every run of every frame of the selected stories. + None if text_editing(app).is_none() => Some(super::character::selected_story_texts(app).into_iter().flat_map(|t| t.runs.iter()).collect()), + None => None, + }; + if let Some(mut runs) = runs { // A run with no text, such as an empty frame's, counts only when no run has text. if runs.iter().any(|r| !r.text.is_empty()) { runs.retain(|r| !r.text.is_empty()); @@ -1071,4 +1078,50 @@ mod tests { let runs = metrics_runs(&app, &id); assert!(runs.iter().all(|(_, on, _)| *on), "{runs:?}"); } + + /// With the Selection tool on a threaded story whose second frame is empty, the East Asian + /// items read only the characters: with the text set and the empty frame's run not, each item + /// shows checked, and choosing it turns the setting off for the text. + #[test] + fn east_asian_items_skip_an_empty_frame_of_a_selected_story() { + type Set = fn(&mut CharStyle, bool); + type Get = fn(&CharStyle) -> bool; + let items: [(&str, Set, Get); 3] = [ + ("Proportional Metrics", |s, on| s.proportional_metrics = on, |s| s.proportional_metrics), + ("H or V Style", |s, on| s.features = if on { vec!["hkna".into()] } else { vec![] }, |s| s.features.iter().any(|f| f == "hkna")), + ("Roman Italics", |s, on| s.features = if on { vec!["ital".into()] } else { vec![] }, |s| s.features.iter().any(|f| f == "ital")), + ]; + for (label, set, get) in items { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.prefs.show_east_asian_options = true; + app.run("file.new", json!({"width": 600, "height": 300})).unwrap(); + let area = json!({"x": 10, "y": 10, "text": "かなAB", "size": 12, "area": {"width": 150, "height": 60}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("shape.rectangle", json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("text.thread.create", json!({})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + assert_eq!(super::super::character::selected_story_texts(&app).len(), 2, "{label}"); + for (id, on) in [(a, true), (b, false)] { + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let Some(NodeKind::Text(t)) = doc.node_mut(NodeId(id)).map(|n| &mut n.kind) else { panic!("no frame {id}") }; + for r in &mut t.runs { + set(&mut r.style, on); + } + } + let empty = match &app.session.active().unwrap().doc.node(NodeId(b)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().filter(|r| r.text.is_empty()).count(), + _ => panic!("{label}: not text"), + }; + assert!(empty > 0, "{label}: the empty frame has no run"); + let ctx = egui::Context::default(); + let (text, at) = menu_row(&ctx, &mut app, label); + assert!(text.starts_with('✓'), "{label}: {text:?}"); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + match &app.session.active().unwrap().doc.node(NodeId(a)).unwrap().kind { + NodeKind::Text(t) => assert!(t.runs.iter().all(|r| !get(&r.style)), "{label}"), + _ => panic!("{label}: not text"), + } + } + } } From 4cf72518e1b48edd0383791b979a0f21b973a2e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:37:40 -0800 Subject: [PATCH 14/55] i18n: the message scan skips a status local bound in a block that has ended status_locals took the nearest `let name = ` before a `.status(name)` call, even when that `let` was in an inner block that closed before the call. For `let note = "Outer"; { let note = "Inner"; log(note); } app.status(note);` the untranslated-strings report listed "Inner" and missed "Outer". The scan now skips a binding whose block a `}` closes before the call. Braces inside string and character literals are skipped with quoted_end, the helper without_comments already uses. message_scan_reads_locals_given_to_a_status covers the shadowing case and a status local followed by brace literals. --- crates/ui-egui/src/i18n/tests.rs | 55 ++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 5cbbe4cf11..1add793f4e 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -4931,8 +4931,9 @@ fn unreadable(e: impl std::fmt::Display) -> String { } /// The scan reads the values of a local that a `.status(name)` shows, from the nearest `let` of -/// that name in the same function: a `format!` string and each arm of a `match`. It skips a local -/// that no status shows, a `let` of the name in another function, and a status given a value. +/// that name in the same function whose block is still open at the call: a `format!` string and +/// each arm of a `match`. It skips a local that no status shows, a `let` of the name in another +/// function or in a block that ended before the call, and a status given a value. #[test] fn message_scan_reads_locals_given_to_a_status() { let code = r#" @@ -4953,8 +4954,24 @@ fn saved(app: &mut App, saving: &str, e: &str, place: Option<&str>) { app.status(line); app.status(true); } + +fn scoped(app: &mut App) { + let note = "Outer message"; + { + let note = "Inner message"; + log(note); + } + app.status(note); +} + +fn braced(app: &mut App) { + let tip = "Kept open"; + log("}", '}', '\'', '\\'); + // } + app.status(tip); +} "#; - let want = ["{saving} failed: {e}", "Couldn't save to {folder}: {e}", "Couldn't save"]; + let want = ["{saving} failed: {e}", "Couldn't save to {folder}: {e}", "Couldn't save", "Outer message", "Kept open"]; assert_eq!(source_messages(code, &[], &std::collections::BTreeMap::new()), want); let ui = message_literals_in(&["ui-egui"]); for m in [ @@ -7230,9 +7247,12 @@ fn handler_returns<'a>(code: &'a str, name: &str) -> Vec<&'a str> { } /// Where each value of a local that a `.status(name)` in `code` shows can start: the statement of -/// the nearest `let name = ` before that call in the same function (`let line = format!("…");`, -/// `let line = match place { … };`, up to its `;`), read as [`closure_returns`] reads a closure. A -/// local that no `.status(name)` shows is not read. +/// the nearest `let name = ` before that call in the same function whose block is still open at +/// the call (`let line = format!("…");`, `let line = match place { … };`, up to its `;`), read as +/// [`closure_returns`] reads a closure. A `let` in a block that a `}` closes before the call is +/// skipped; a brace inside a string or character literal ([`quoted_end`]) does not open or close a +/// block. `code` comes from [`source_messages`] with its comments removed ([`without_comments`]), so +/// a brace in a comment is not seen. A local that no `.status(name)` shows is not read. fn status_locals(code: &str) -> Vec<&str> { let mut out = vec![]; for (at, m) in code.match_indices(".status(") { @@ -7242,7 +7262,28 @@ fn status_locals(code: &str) -> Vec<&str> { continue; } let bound = format!("let {name} = "); - let nearest = code[..at].rmatch_indices(bound.as_str()).find(|&(b, _)| !code[..b].ends_with(|c: char| c.is_alphanumeric() || c == '_')); + let open_at_call = |b: usize| { + let (mut depth, mut i) = (0usize, b); + while let Some(c) = code.get(i..at).and_then(|s| s.chars().next()) { + if let Some(end) = (c == '"' || c == '\'').then(|| quoted_end(code, i)).flatten() { + i = end; + continue; + } + match c { + '{' => depth += 1, + '}' => match depth.checked_sub(1) { + Some(d) => depth = d, + None => return false, + }, + _ => {} + } + i += c.len_utf8(); + } + true + }; + let nearest = code[..at] + .rmatch_indices(bound.as_str()) + .find(|&(b, _)| !code[..b].ends_with(|c: char| c.is_alphanumeric() || c == '_') && open_at_call(b)); if let Some((b, _)) = nearest && !code[b..at].contains("fn ") { From 8d4f9e4f35cd21ca46d93c7c5e52e05c7ffef150 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:22:29 -0800 Subject: [PATCH 15/55] Color Settings: a background open whose profile question is gone finishes off the UI thread A file read off the UI thread that waits behind another file's profile question, and has no question any more once Color Settings change, now does the rest of its read (policies, linked files, type) off the UI thread, as an answered file does, instead of on the UI thread. It opens at once when no thread can start, and a failure is reported once. A profile question that comes while another dialog is open (a paste waiting for its Swatch Conflict answer, say) now waits until that dialog closes instead of replacing it and canceling the paste. Follows #7733. --- crates/engine/src/cmd/fileio/load.rs | 7 ++ .../ui-egui/src/dialogs/profile_mismatch.rs | 67 +++++++++---------- .../src/dialogs/profile_mismatch/tests.rs | 42 ++++++++++++ crates/ui-egui/src/opening.rs | 13 +++- crates/ui-egui/src/opening/tests.rs | 20 +++++- 5 files changed, 111 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index cedda4844a..85a221a838 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -845,6 +845,13 @@ impl ReadFile { r } + /// Is part of the read still to do ([`Self::finish_read`]): the policies and the color mode of a + /// file that stopped for its profile question, or the linked files and the type of an answered + /// one? + pub fn read_left(&self) -> bool { + self.rest.is_some() || self.links_left.is_some() + } + /// The rest of [`read_for_open_asking`], once: the color management policies with the profile /// answer (or as the policy says without one), the color mode `colorMode` asks for, the linked /// files and the type. The app runs it off the UI thread once the question is answered. diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs index a0f447277e..47f97b77dd 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -87,28 +87,24 @@ fn paste_choices() -> [(&'static str, &'static str); 2] { /// Open `file`, read for File › Open from `path`, as `document.open` does, unless Edit › Color /// Settings asks about its profile ([`ReadFile::ask`]): then the dialog asks first, and the result -/// is `{dialog}`. A file read while another one's question is open waits for its own question -/// until that one is answered (`{dialog, queued: true}`). Opened, the views follow and the file +/// is `{dialog}`. A file read while another one's question, or another dialog, is open waits for +/// its own question until that one closes (`{dialog, queued: true}`). Opened, the views follow and the file /// goes on the recent files ([`crate::io::opened`]). `background`: the file was read off the UI /// thread, and the rest of its read after an answer is done there too. pub fn open_or_ask(app: &mut VectorcraftApp, file: ReadFile, path: Option, background: bool) -> Result { ask_or_open(app, PendingOpen { file, path, scope: ScopeHandle::capture(), background }) } -/// [`open_or_ask`] for a file that has its scope already. +/// [`open_or_ask`] for a file that has its scope already. While another dialog is open (a paste +/// waiting for its Swatch Conflict answer, say), the question waits for it to close too. fn ask_or_open(app: &mut VectorcraftApp, mut pending: PendingOpen) -> Result { let Some(q) = pending.file.ask() else { - let PendingOpen { file, path, scope, .. } = pending; - return scope.run(|| { - let r = fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())?; - crate::io::opened(app, &r); - if let Some(p) = &path { - crate::io::note_recent(app, p); - } - Ok(r) - }); + // The question is gone (or there was none): a file read off the UI thread does the rest of + // its read there, as an answered one does. + let scope = pending.scope.clone(); + return open_now(app, pending, scope); }; - if app.pending_profile_open.is_some() { + if app.pending_profile_open.is_some() || app.ui.dialog.is_some() { app.queued_profile_opens.push_back(pending); return Ok(json!({ "dialog": OPEN_KIND, "queued": true })); } @@ -222,33 +218,36 @@ fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { /// off the UI thread does the rest of its read (its linked files and type) there too /// ([`crate::opening::finish_answered`]). fn open_pending(app: &mut VectorcraftApp, pending: PendingOpen, scope: ScopeHandle) -> DialogResult { + let name = pending.file.name(); + let r = open_now(app, pending, scope); + if let Err(e) = &r { + crate::io::report_open_error(app, &name, e); + } + r +} + +/// Open `pending` under `scope` without reporting a failure. A file read off the UI thread with part +/// of its read left ([`ReadFile::read_left`]) does that part there ([`crate::opening::finish_answered`]) +/// → `{background: true, status}`; when no thread can start, it opens at once. +fn open_now(app: &mut VectorcraftApp, pending: PendingOpen, scope: ScopeHandle) -> Result { let PendingOpen { file, path, background, .. } = pending; - let name = file.name(); let file = match &path { - Some(p) if background && crate::opening::available() => match crate::opening::finish_answered(app, p, file, scope.clone()) { - Ok(r) => return Ok(r), - Err(Some(file)) => *file, - Err(None) => { - let e = "the file stopped being read (please report this bug)".to_string(); - crate::io::report_open_error(app, &name, &e); - return Err(e); + Some(p) if background && file.read_left() && crate::opening::available() => { + match crate::opening::finish_answered(app, p, file, scope.clone()) { + Ok(r) => return Ok(r), + Err(Some(file)) => *file, + Err(None) => return Err("the file stopped being read (please report this bug)".to_string()), } - }, + } _ => file, }; - scope.run(|| match fileio::open_read(&mut app.session, file) { - Ok(r) => { - crate::io::opened(app, &r); - if let Some(p) = &path { - crate::io::note_recent(app, p); - } - Ok(r) - } - Err(e) => { - let e = e.to_string(); - crate::io::report_open_error(app, &name, &e); - Err(e) + scope.run(|| { + let r = fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())?; + crate::io::opened(app, &r); + if let Some(p) = &path { + crate::io::note_recent(app, p); } + Ok(r) }) } diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index 358c6f428e..0bd7cc82e2 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -132,6 +132,46 @@ fn files_opened_together_ask_in_turn(app: &mut VectorcraftApp, tagged: &[u8]) { assert!(app.ui.dialog.is_none() && app.pending_profile_open.is_none()); } +/// A file opened while another dialog is open (a message here) waits for it to close and then asks +/// its question; the other dialog stays. `tagged` asks with the settings in force. +fn a_question_waits_for_an_open_dialog(app: &mut VectorcraftApp, tagged: &[u8]) { + let docs = app.session.documents().len(); + crate::dialogs::confirm::tell(app, "Waiting", ""); + let r = crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND, "queued": true })); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind != OPEN_KIND), "the message stays"); + assert!(app.pending_profile_open.is_none()); + super::super::cancel(app); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) && app.pending_profile_open.is_some(), "then it asks"); + super::super::confirm(app).unwrap(); + assert_eq!(app.session.documents().len(), docs + 1); +} + +/// A file read off the UI thread waits for another file's question, and Color Settings change so +/// that it has none any more: once the first question closes, the rest of its read is done off the +/// UI thread too, and it opens when that is done. `tagged` asks with the settings in force, which +/// Ask When Opening for a mismatch is one of. +fn a_background_open_whose_question_is_gone_finishes_off_the_ui_thread(app: &mut VectorcraftApp, tagged: &[u8]) { + let docs = app.session.documents().len(); + assert_eq!(crate::io::open_bytes(app, "first.vectorcraft", tagged, None).unwrap(), json!({ "dialog": OPEN_KIND })); + let path = "/tmp/background.vectorcraft".to_string(); + let file = fileio::read_for_open_asking("background.vectorcraft", tagged, Some(path.clone()), &json!({}), false, false, true).unwrap(); + assert!(file.read_left()); + let r = open_or_ask(app, file, Some(path.clone()), true).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND, "queued": true })); + app.run("edit.colorSettings", json!({"askMismatchOpen": false})).unwrap(); + crate::opening::tests::with_threads(|| { + super::super::cancel(app); + assert!(app.queued_profile_opens.is_empty()); + assert_eq!(app.opening.pending.len(), 1, "read off the UI thread"); + assert_eq!(app.session.documents().len(), docs, "not open before its read is done"); + crate::opening::tests::open_ready(app); + }); + assert_eq!(app.session.documents().len(), docs + 1); + assert_eq!(app.ui.recent_files.first(), Some(&path)); + app.run("edit.colorSettings", json!({"askMismatchOpen": true})).unwrap(); +} + /// Color Settings change the open question while it is open: OK asks the question as it is now /// (another working space) instead of opening, and opens by the policy once there is no question /// (the working space is the file's profile). `tagged` (Wide Gamut RGB) asks with the settings in @@ -339,6 +379,8 @@ fn opening_and_pasting_ask_about_profiles() { open_confirmed_under_roots(&mut app, &tagged); links_read_under_the_roots_of_the_open(&mut app); files_opened_together_ask_in_turn(&mut app, &tagged); + a_question_waits_for_an_open_dialog(&mut app, &tagged); + a_background_open_whose_question_is_gone_finishes_off_the_ui_thread(&mut app, &tagged); // Missing Profiles: Ask When Opening, and a choice the file refuses. app.run("edit.colorSettings", json!({"askMismatchOpen": false, "askMissingOpen": true, "rgbPolicy": "preserveEmbedded"})).unwrap(); diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 5b4c8619ee..5467de0aae 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -59,9 +59,16 @@ pub fn long_operation_busy(app: &VectorcraftApp) -> bool { } /// Does opening happen off the UI thread here? Not on wasm (no threads), in unit tests (they look -/// at the document right after asking for it), or with `VECTORCRAFT_SYNC_OPEN` set. +/// at the document right after asking for it, unless one turns it on: [`tests::with_threads`]), or +/// with `VECTORCRAFT_SYNC_OPEN` set. +#[cfg(not(test))] pub fn available() -> bool { - !(cfg!(target_arch = "wasm32") || cfg!(test) || std::env::var_os("VECTORCRAFT_SYNC_OPEN").is_some()) + !(cfg!(target_arch = "wasm32") || std::env::var_os("VECTORCRAFT_SYNC_OPEN").is_some()) +} + +#[cfg(test)] +pub fn available() -> bool { + tests::threads_on() } /// Decode `bytes`, the file at `path`, read its linked files and lay out its type on a thread of its @@ -278,4 +285,4 @@ fn finish(app: &mut VectorcraftApp, path: &str, r: Result) { } #[cfg(test)] -mod tests; +pub(crate) mod tests; diff --git a/crates/ui-egui/src/opening/tests.rs b/crates/ui-egui/src/opening/tests.rs index 43fe46e217..a1884da5b1 100644 --- a/crates/ui-egui/src/opening/tests.rs +++ b/crates/ui-egui/src/opening/tests.rs @@ -44,8 +44,26 @@ fn wait_read(app: &mut VectorcraftApp) { } } +std::thread_local! { + /// Opening happens off the UI thread in this test ([`with_threads`]). + static THREADS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Is opening off the UI thread turned on for this test ([`available`])? +pub(crate) fn threads_on() -> bool { + THREADS.with(std::cell::Cell::get) +} + +/// Run `f` with opening off the UI thread, as on the desktop. +pub(crate) fn with_threads(f: impl FnOnce() -> R) -> R { + THREADS.with(|t| t.set(true)); + let r = f(); + THREADS.with(|t| t.set(false)); + r +} + /// Wait until every file being opened has been read, then open the files that may open now. -fn open_ready(app: &mut VectorcraftApp) { +pub(crate) fn open_ready(app: &mut VectorcraftApp) { wait_read(app); poll(app); } From 15b4898f853d2b06a152fa85f18bd7459b13b7ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:24:36 -0800 Subject: [PATCH 16/55] Canvas: a new working CMYK space renders a Working CMYK proof again MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A proof of the working CMYK space converts through the working color settings. With a profile assigned to the document in place of the working CMYK space, Edit › Color Settings changes the working settings while the active settings stay the same, and the canvas kept showing the proof through the previous working space. - The canvas's frame key also holds the working color settings (`cms::working_settings`). - The test now requires a re-render after `edit.assignProfile`, and checks that a new working CMYK space re-renders a Working CMYK proof while the active settings stay the same. --- crates/ui-egui/src/caches.rs | 13 ++++++++----- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/tests.rs | 16 +++++++++++++++- 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index ec50e4c8a4..244f69f9df 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -225,11 +225,14 @@ pub struct CacheKey { /// The paper under the art that translucent art is blended with before the conversion /// ([`crate::display_profile::convert_over`]). None without a display profile, and in Outline. pub backdrop: Option>, - /// The active color settings ([`vectorcraft_color::cms::active_settings`]) and the loaded - /// profiles' generation ([`vectorcraft_color::cms::profiles_generation`]) the frame's colors - /// were converted with: Edit › Color Settings, a profile loaded again under its name or removed, - /// and the front document's assigned profiles change them without changing the document. - pub color: (vectorcraft_color::cms::ColorSettings, u64), + /// The active color settings ([`vectorcraft_color::cms::active_settings`]), the working color + /// settings ([`vectorcraft_color::cms::working_settings`]) and the loaded profiles' generation + /// ([`vectorcraft_color::cms::profiles_generation`]) the frame's colors were converted with: + /// Edit › Color Settings, a profile loaded again under its name or removed, and the front + /// document's assigned profiles change them without changing the document. A proof of the + /// working CMYK space converts through the working settings, which can change while the active + /// settings stay the same. + pub color: (vectorcraft_color::cms::ColorSettings, vectorcraft_color::cms::ColorSettings, u64), } impl CacheKey { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f9a49a3e18..dc422b125c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -923,7 +923,7 @@ fn cache_key( // Preferences › Performance › Use Monitor Profile for Canvas. display: app.display_profile.key(app.session.prefs.monitor_profile_display), backdrop: backdrop(app, st, app.outline_view()), - color: (vectorcraft_color::cms::active_settings(), vectorcraft_color::cms::profiles_generation()), + color: (vectorcraft_color::cms::active_settings(), vectorcraft_color::cms::working_settings(), vectorcraft_color::cms::profiles_generation()), } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index fa9a6b813e..c80546d29c 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4882,7 +4882,7 @@ fn color_settings_and_a_reloaded_profile_render_the_canvas_again() { }; load(&mut app, cms::GENERIC_CMYK); app.run("edit.assignProfile", json!({"cmyk": name})).unwrap(); - let assigned = middle(&mut app).unwrap_or(first); + let assigned = middle(&mut app).expect("assigning a profile re-renders the canvas"); assert!(near(assigned, generic), "through the assigned copy of the working space: {assigned:?}, not {generic:?}"); assert_eq!(middle(&mut app), None, "nothing changed: no re-render"); // The same name, the settings as they were: only the profile's file is new. @@ -4890,6 +4890,20 @@ fn color_settings_and_a_reloaded_profile_render_the_canvas_again() { let reloaded = middle(&mut app).expect("the profile loaded again re-renders the canvas"); assert!(near(reloaded, device), "through the profile's new file: {reloaded:?}, not {device:?}"); assert_eq!(middle(&mut app), None, "nothing changed since: no re-render"); + + // A proof of the working CMYK space converts through the working settings. With the document's + // assigned profile in place of the working CMYK space, a new working CMYK space leaves the + // active settings as they were and changes only the proof. + app.run("view.proofSetup", json!({"target": "workingCmyk"})).unwrap(); + app.run("view.proofColors", json!({"on": true})).unwrap(); + let proofed = middle(&mut app).expect("Proof Colors re-renders the canvas"); + assert_eq!(middle(&mut app), None, "nothing changed: no re-render"); + let active = cms::active_settings(); + app.run("edit.colorSettings", json!({"cmyk": cms::DEVICE_CMYK})).unwrap(); + let reproofed = middle(&mut app).expect("a new working CMYK space re-renders the proof"); + assert_eq!(cms::active_settings(), active, "the assigned profile keeps the active settings"); + assert!(!near(reproofed, [proofed[0], proofed[1], proofed[2]]), "the proof through the new working CMYK space: {reproofed:?}, not {proofed:?}"); + assert_eq!(middle(&mut app), None, "nothing changed since: no re-render"); } /// Guides & Grid › Show Pixel Grid (Above 600% Zoom) (#394): in Pixel Preview at 600% zoom and From 3c0bdfbd43fde9400d0ea427934cad53f2145856 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:48:18 -0800 Subject: [PATCH 17/55] i18n: the message scan reads character literals and fn inside strings The scan of status locals checked for a function boundary with a plain search for `fn `, so a local whose string held `fn ` was skipped. It now looks for `fn ` outside string and character literals. `statement`, `closure_returns`, `skip_args` and `without_strings` read the `"` of a character literal such as `'"'` as the start of a string, so a `match` arm on `'"'` hid the arms after it. They now skip character literals with `quoted_end`, which leaves a lifetime alone. --- crates/ui-egui/src/i18n/tests.rs | 81 ++++++++++++++++++++++++++++---- 1 file changed, 71 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 1add793f4e..e82a573df6 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -4932,8 +4932,9 @@ fn unreadable(e: impl std::fmt::Display) -> String { /// The scan reads the values of a local that a `.status(name)` shows, from the nearest `let` of /// that name in the same function whose block is still open at the call: a `format!` string and -/// each arm of a `match`. It skips a local that no status shows, a `let` of the name in another -/// function or in a block that ended before the call, and a status given a value. +/// each arm of a `match`, a `'"'` arm included. It reads a local whose string holds `fn `. It +/// skips a local that no status shows, a `let` of the name in another function or in a block that +/// ended before the call, and a status given a value. #[test] fn message_scan_reads_locals_given_to_a_status() { let code = r#" @@ -4970,8 +4971,30 @@ fn braced(app: &mut App) { // } app.status(tip); } + +fn named(app: &mut App) { + let line = "Invalid fn declaration"; + app.status(line); +} + +fn quoted(app: &mut App, quote: char) { + let line = match quote { + '"' => "Double quote", + _ => "Other quote", + }; + app.status(line); +} "#; - let want = ["{saving} failed: {e}", "Couldn't save to {folder}: {e}", "Couldn't save", "Outer message", "Kept open"]; + let want = [ + "{saving} failed: {e}", + "Couldn't save to {folder}: {e}", + "Couldn't save", + "Outer message", + "Kept open", + "Invalid fn declaration", + "Double quote", + "Other quote", + ]; assert_eq!(source_messages(code, &[], &std::collections::BTreeMap::new()), want); let ui = message_literals_in(&["ui-egui"]); for m in [ @@ -7201,6 +7224,7 @@ fn skip_args(args: &str, n: usize) -> Option<&str> { match c { '(' | '[' | '{' => depth += 1, ')' | ']' | '}' => depth = depth.checked_sub(1)?, + '\'' => skip_char_literal(args, at, &mut chars), '"' => loop { match chars.next()?.1 { '\\' => { @@ -7285,7 +7309,7 @@ fn status_locals(code: &str) -> Vec<&str> { .rmatch_indices(bound.as_str()) .find(|&(b, _)| !code[..b].ends_with(|c: char| c.is_alphanumeric() || c == '_') && open_at_call(b)); if let Some((b, _)) = nearest - && !code[b..at].contains("fn ") + && !declares_fn(&code[b..at]) { out.extend(closure_returns(statement(&code[b + bound.len()..]))); } @@ -7293,7 +7317,35 @@ fn status_locals(code: &str) -> Vec<&str> { out } +/// Whether `code` holds the keyword `fn ` outside its string and character literals +/// ([`quoted_end`]). +fn declares_fn(code: &str) -> bool { + let mut i = 0; + while let Some(c) = code[i..].chars().next() { + if let Some(end) = (c == '"' || c == '\'').then(|| quoted_end(code, i)).flatten() { + i = end; + continue; + } + if code[i..].starts_with("fn ") && !code[..i].ends_with(|c: char| c.is_alphanumeric() || c == '_') { + return true; + } + i += c.len_utf8(); + } + false +} + +/// Moves `chars`, just past the `'` at `text[at]`, to the end of the character literal it opens +/// ([`quoted_end`]); a lifetime's `'` leaves it where it is. +fn skip_char_literal(text: &str, at: usize, chars: &mut std::str::CharIndices) { + if let Some(end) = quoted_end(text, at) { + for _ in text[at + 1..end].chars() { + chars.next(); + } + } +} + /// The statement `code` starts with, up to its `;` or the bracket that closes the block it is in. +/// A bracket, `;` or `"` inside a character literal (`'"'`) is skipped. fn statement(code: &str) -> &str { let (mut depth, mut chars) = (0usize, code.char_indices()); while let Some((at, c)) = chars.next() { @@ -7304,6 +7356,7 @@ fn statement(code: &str) -> &str { None => return &code[..at], }, ';' if depth == 0 => return &code[..at], + '\'' => skip_char_literal(code, at, &mut chars), '"' => loop { match chars.next() { Some((_, '\\')) => { @@ -7328,7 +7381,8 @@ fn statement(code: &str) -> &str { /// only when the local's name is used, outside a string literal and a `format!`, in a value the closure returns /// (`let why = if … { format!("…") } else { … }; Error(why)`), and not when the local only goes /// elsewhere (`let level = if … { "warning" } else { "error" }; log(level);`). A `return` counts -/// wherever it is, except inside a closure the body holds (`unwrap_or_else(|| return …)`). +/// wherever it is, except inside a closure the body holds (`unwrap_or_else(|| return …)`). A +/// character literal (`'"'`, `'{'`) is skipped, so it does not open a string or a block. fn closure_returns(body: &str) -> Vec<&str> { let ident = |c: char| c.is_alphanumeric() || c == '_'; // The name a `let` statement starting at `at` binds (empty for a pattern), if it is one. @@ -7387,6 +7441,7 @@ fn closure_returns(body: &str) -> Vec<&str> { { found.push((&body[at + "return".len()..], None, true)); } + '\'' => skip_char_literal(body, at, &mut chars), '"' => loop { match chars.next() { Some((_, '\\')) => { @@ -7441,14 +7496,20 @@ fn without_format_args(code: &str) -> String { out } -/// `code` with the text of its string literals removed, the quotes kept. +/// `code` with the text of its string literals removed, the quotes kept. A character literal +/// (`'"'`) stays as it is. fn without_strings(code: &str) -> String { - let (mut out, mut chars) = (String::new(), code.chars()); - while let Some(c) = chars.next() { + let (mut out, mut chars) = (String::new(), code.char_indices()); + while let Some((at, c)) = chars.next() { out.push(c); - if c == '"' { + if c == '\'' + && let Some(end) = quoted_end(code, at) + { + out.push_str(&code[at + 1..end]); + skip_char_literal(code, at, &mut chars); + } else if c == '"' { loop { - match chars.next() { + match chars.next().map(|(_, c)| c) { Some('\\') => { chars.next(); } From d03a34977a60685244fee6eae02afb4f0f4c01e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:40:40 -0800 Subject: [PATCH 18/55] Canvas: a worker frame of other color settings is not shown The render worker converts colors with the settings in force while it renders, and the frame it returns carries the key captured when it was asked for. A change of the color settings during the render could store the new settings' colors under the old key, and a return to the old settings then matched that key and kept the frame. The canvas now drops a worker frame whose color key is not the current one and asks for the frame again. --- crates/ui-egui/src/canvas.rs | 15 ++++++++-- crates/ui-egui/src/canvas/tests.rs | 46 ++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index dc422b125c..2803558a11 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -923,10 +923,16 @@ fn cache_key( // Preferences › Performance › Use Monitor Profile for Canvas. display: app.display_profile.key(app.session.prefs.monitor_profile_display), backdrop: backdrop(app, st, app.outline_view()), - color: (vectorcraft_color::cms::active_settings(), vectorcraft_color::cms::working_settings(), vectorcraft_color::cms::profiles_generation()), + color: color_key(), } } +/// [`CacheKey::color`] now: the active color settings, the working color settings and the loaded +/// profiles' generation. +fn color_key() -> (vectorcraft_color::cms::ColorSettings, vectorcraft_color::cms::ColorSettings, u64) { + (vectorcraft_color::cms::active_settings(), vectorcraft_color::cms::working_settings(), vectorcraft_color::cms::profiles_generation()) +} + /// [`CacheKey::plugins`] of document `st`, one of the documents open in `session`. `keys` holds each /// document's value and the plug-in revision it was checked at, so a document is looked through only /// once after each change of the plug-in revision. @@ -1053,10 +1059,13 @@ fn poll_worker(app: &mut VectorcraftApp, ui: &Ui, key_doc: usize) { /// Upload frame `done` from the render worker when it is of document `key_doc` and not older than /// the frame shown. This prevents canvas freezes during continuous edits (drags, arrow nudges, MCP -/// command bursts) while ensuring obsolete out-of-order frames are dropped. +/// command bursts) while ensuring obsolete out-of-order frames are dropped. A frame whose color key +/// ([`CacheKey::color`]) is not the current one is dropped too: the worker converted its colors +/// with the settings in force while it rendered, which may not be the ones in its key, and the next +/// frame renders again with the current ones. fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate::render_worker::Done, key_doc: usize) { let not_older = app.canvas.key.as_ref().filter(|k| k.doc == done.key.doc).is_none_or(|k| done.key.revision >= k.revision); - if done.key.doc != key_doc || !not_older { + if done.key.doc != key_doc || !not_older || done.key.color != color_key() { return; } upload(app, ctx, done.img, done.key.pixel.is_some()); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index c80546d29c..a6ea9defbd 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4906,6 +4906,52 @@ fn color_settings_and_a_reloaded_profile_render_the_canvas_again() { assert_eq!(middle(&mut app), None, "nothing changed since: no re-render"); } +/// A frame from the render worker whose color key is not the current one is not shown, and the +/// canvas asks for the frame again. The worker converts colors with the settings in force while it +/// renders, so a frame asked for before a change of the color settings may hold colors of the new +/// settings under the old key, and a return to the old settings would keep it. +#[test] +fn a_worker_frame_of_other_color_settings_is_not_shown() { + keeping_color_settings(a_worker_frame_of_other_color_settings); +} + +fn a_worker_frame_of_other_color_settings() { + use vectorcraft_color::cms; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.canvas.worker_started = true; + let (worker, jobs, done_tx) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(worker); + let ctx = egui::Context::default(); + let frame = |app: &mut VectorcraftApp| { + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), time: Some(1.0), ..Default::default() }; + ctx.run_ui(raw, |ui| show(app, ui)).textures_delta.clear(); + }; + frame(&mut app); + done_tx.send(finished(&jobs.try_recv().expect("the first frame"))).unwrap(); + frame(&mut app); + let first = app.canvas.key.clone().expect("the first frame is shown"); + + // A pan's frame goes to the worker, and the color settings change before it is finished. + app.view_mut().unwrap().center.x += 5.0; + frame(&mut app); + let pan = jobs.try_recv().expect("the pan's frame goes to the worker"); + let settings = cms::ColorSettings { cmyk: cms::DEVICE_CMYK.into(), ..cms::active_settings() }; + assert_ne!(settings, cms::active_settings(), "other color settings"); + cms::with_active(std::sync::Arc::new(cms::Cms::new(&settings).unwrap()), || { + done_tx.send(finished(&pan)).unwrap(); + frame(&mut app); + assert_eq!(app.canvas.key.as_ref(), Some(&first), "the pan's frame, of other color settings, is not shown"); + let again = jobs.try_recv().expect("the pan's frame is asked for with the current color settings"); + assert_ne!(again.key.color, pan.key.color); + }); + // Back to the settings in the pan's key: the pan's frame is asked for again. + frame(&mut app); + let back = jobs.try_recv().expect("the pan's frame is asked for again"); + assert_eq!(back.key, pan.key); +} + /// Guides & Grid › Show Pixel Grid (Above 600% Zoom) (#394): in Pixel Preview at 600% zoom and /// above, a line at every document pixel over the art; none below 600%, out of Pixel Preview, /// or with the option off. From 822987115cd056db3d620686803960c371c90b99 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:58:46 -0800 Subject: [PATCH 19/55] Transform: a Sides slider drag that ends early takes no more input until release - A drag whose rows stop being drawn still keeps its preview as one undo step, and the rest of it is ignored while the button stays down, also when the rows are drawn again before the release. An Escape in the pass whose rows are not drawn (one that closes the task bar's popover) puts the count back instead. - A drag during which another document comes to the front ends there; the rest of it changes neither document. - The Escape that cancels a drag is the slider's: the tool, isolation mode and a command bound to Escape do not take it (shortcuts::handle, through transform::sides_drag_held). --- crates/ui-egui/src/panels/transform.rs | 44 ++++++-- crates/ui-egui/src/panels/transform/tests.rs | 109 +++++++++++++++++++ crates/ui-egui/src/shortcuts.rs | 13 ++- docs/target-app-parity.md | 2 +- 4 files changed, 152 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 70b9dd030d..8f95f7659b 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -648,11 +648,14 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live /// 1,000. pub(crate) const SIDES_SLIDER: std::ops::RangeInclusive = 3.0..=20.0; -/// A drag on a Sides slider in progress: the rows it is in, whether Escape canceled it (the rest -/// of it is ignored until the button is up), and the main window's pass the rail was last drawn in. +/// A drag on a Sides slider in progress: the rows it is in, the document it edits (its `uid`), +/// whether it ended early (Escape canceled it, its rows went undrawn or another document came to +/// the front; the rest of it is ignored until the button is up), and the main window's pass the +/// rail was last drawn in. #[derive(Clone, Debug, PartialEq)] struct SidesDrag { rows: String, + doc: Option, canceled: bool, pass: u64, } @@ -665,22 +668,38 @@ fn root_pass(ctx: &egui::Context) -> u64 { ctx.cumulative_pass_nr_for(egui::ViewportId::ROOT) } +/// Is a Sides slider drag in progress, or one that ended early with its button still down? The +/// shortcuts then leave Escape to the slider. +pub(crate) fn sides_drag_held(ctx: &egui::Context) -> bool { + pstate::>(ctx, SIDES_DRAG).is_some() +} + /// Keeps the count a Sides slider drag previewed as one undo step when its rail was not drawn in /// this pass (the task bar's popover or the panel closed during the drag), so no preview stays open -/// into a later pass; a drag Escape canceled only ends. The app runs this at the end of every -/// pass, after the panels. +/// into a later pass; with an Escape in this pass it puts the count back instead, and a drag that +/// already ended early only ends. While the button stays down, the +/// rest of the drag is ignored, also when its rows are drawn again. The app runs this at the end +/// of every pass, after the panels. pub(crate) fn end_stale_sides_drag(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(drag) = pstate::>(ctx, SIDES_DRAG) else { return }; if drag.pass == root_pass(ctx) { return; } - if !drag.canceled && app.session.in_interaction() { - if let Err(e) = app.session.commit_interaction() { + let front = app.session.active().map(|d| d.uid); + if !drag.canceled && drag.doc == front && app.session.in_interaction() { + // An Escape in this pass (one that closed the task bar's popover) cancels the drag, as it + // does on a drawn rail; the shortcuts leave it to the slider. + let escaped = ctx.input(|i| { + i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, modifiers, .. } if modifiers.is_none())) + }); + let ended = if escaped { app.session.cancel_interaction() } else { app.session.commit_interaction() }; + if let Err(e) = ended { app.ui.status = e.to_string(); } app.sync_views(); } - set_pstate(ctx, SIDES_DRAG, None::); + let down = ctx.input(|i| i.pointer.any_down()); + set_pstate(ctx, SIDES_DRAG, down.then_some(SidesDrag { canceled: true, ..drag })); } /// The Sides slider of Polygon Properties (rows `id`), `width` wide, for a polygon of `sides` @@ -699,20 +718,23 @@ fn sides_slider(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, sides: u32, wid let held = pstate::>(&ctx, SIDES_DRAG).filter(|d| d.rows == id); let down = ui.input(|i| i.pointer.any_down()); let pass = root_pass(&ctx); + let doc = app.session.active().map(|d| d.uid); // `None` leaves another rows' drag as it is. let mut next = None; - if let Some(d) = held.as_ref().filter(|d| d.canceled) { - next = Some(down.then(|| SidesDrag { pass, ..d.clone() })); + // A switch to another document canceled the drag's preview there; the rest of the drag is + // ignored, as after Escape. + if let Some(d) = held.as_ref().filter(|d| d.canceled || d.doc != doc) { + next = Some(down.then(|| SidesDrag { canceled: true, pass, ..d.clone() })); } else if held.is_some() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { if let Err(e) = app.session.cancel_interaction() { app.ui.status = e.to_string(); } app.sync_views(); - next = Some(down.then(|| SidesDrag { rows: id.to_string(), canceled: true, pass })); + next = Some(down.then(|| SidesDrag { rows: id.to_string(), doc, canceled: true, pass })); } else if let Some(x) = dragged { let count = (lo + f64::from(x) * (hi - lo)).round(); super::live_run(app, "Live Shape Properties", "object.setLiveShape", json!({ "sides": count as u64 }), phase); - next = Some((phase == widgets::Live::Dragging).then(|| SidesDrag { rows: id.to_string(), canceled: false, pass })); + next = Some((phase == widgets::Live::Dragging).then(|| SidesDrag { rows: id.to_string(), doc, canceled: false, pass })); } else if let Some(k) = keyed.map(f64::round).filter(|k| *k != n) { app.run("object.setLiveShape", json!({ "sides": k as u64 })).ok(); } else if let Some(d) = held { diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index 5ee1311e80..cd9cdd8eb1 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -1513,6 +1513,115 @@ fn polygon_sides_slider_drag_released_unseen_is_kept() { h.run_steps(2); assert_eq!(polygon_sides(h.state()), 15); assert_eq!(undo(h.state()), depth + 1); + // Rows drawn again while the button is still down: the rest of that drag changes nothing. + let (fifteen, ten) = (sides_rail_at(&h, 15.0), sides_rail_at(&h, 10.0)); + sides_press_and_move(&mut h, fifteen, ten); + assert_eq!(polygon_sides(h.state()), 10); + shown.set(false); + h.run_steps(1); + assert_eq!(undo(h.state()), depth + 2, "the drag ends with the pass that did not draw it"); + shown.set(true); + h.run_steps(1); + sides_press_and_move_back(&mut h, ten, fifteen); + sides_release(&mut h, fifteen); + assert!(!h.state().session.in_interaction()); + assert_eq!(polygon_sides(h.state()), 10, "the rows drawn again before the release take no more of the drag"); + assert_eq!(undo(h.state()), depth + 2); +} + +/// An Escape in the pass whose rows are not drawn (an Escape that closes the task bar's popover) +/// puts the count a Sides drag previewed back instead of keeping it, and adds no undo step. +#[test] +fn polygon_sides_slider_drag_escaped_unseen_is_canceled() { + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.polygon", json!({"cx": 150, "cy": 150, "radius": 50, "sides": 6})).unwrap(); + let depth = undo(&app); + let shown = std::rc::Rc::new(std::cell::Cell::new(true)); + let drawn = shown.clone(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(320.0, 900.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + if drawn.get() { + show(app, ui); + } + end_stale_sides_drag(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + let (six, fifteen) = (sides_rail_at(&h, 6.0), sides_rail_at(&h, 15.0)); + sides_press_and_move(&mut h, six, fifteen); + assert_eq!(polygon_sides(h.state()), 15); + shown.set(false); + h.key_press(egui::Key::Escape); + h.run_steps(1); + assert!(!h.state().session.in_interaction()); + assert_eq!(polygon_sides(h.state()), 6, "Escape puts the count back"); + assert_eq!(undo(h.state()), depth, "and records no undo step"); + shown.set(true); + h.run_steps(1); + sides_release(&mut h, fifteen); + assert_eq!(polygon_sides(h.state()), 6); + assert_eq!(undo(h.state()), depth); +} + +/// A Sides drag in progress when another document comes to the front (which cancels the drag's +/// preview) changes neither document with the rest of the drag. +#[test] +fn polygon_sides_slider_drag_ends_with_a_document_switch() { + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let mut h = polygon_harness(6, show); + h.state_mut().run("file.new", json!({"width": 300, "height": 300})).unwrap(); + h.state_mut().run("shape.polygon", json!({"cx": 150, "cy": 150, "radius": 50, "sides": 6})).unwrap(); + h.run_steps(2); + let depths = (undo(h.state()), { + crate::chrome::show_document(h.state_mut(), 0); + let d = undo(h.state()); + crate::chrome::show_document(h.state_mut(), 1); + d + }); + h.run_steps(2); + let (six, fifteen, ten) = (sides_rail_at(&h, 6.0), sides_rail_at(&h, 15.0), sides_rail_at(&h, 10.0)); + sides_press_and_move(&mut h, six, fifteen); + assert_eq!(polygon_sides(h.state()), 15); + crate::chrome::show_document(h.state_mut(), 0); + h.run_steps(1); + sides_press_and_move_back(&mut h, fifteen, ten); + sides_release(&mut h, ten); + assert!(!h.state().session.in_interaction()); + assert_eq!((polygon_sides(h.state()), undo(h.state())), (6, depths.1), "the document now in front stays as it was"); + crate::chrome::show_document(h.state_mut(), 1); + assert_eq!((polygon_sides(h.state()), undo(h.state())), (6, depths.0), "the switch put the other document back"); +} + +/// An Escape that cancels a Sides drag in isolation mode ends only the drag: isolation mode stays. +#[test] +fn polygon_sides_slider_escape_keeps_isolation_mode() { + let mut h = polygon_harness(6, |app, ui| { + crate::shortcuts::handle(app, ui.ctx()); + show(app, ui); + }); + for (cmd, p) in [("object.group", json!({})), ("object.isolate", json!({})), ("select.all", json!({}))] { + h.state_mut().run(cmd, p).unwrap(); + } + h.run_steps(2); + let isolated = |app: &VectorcraftApp| app.session.active().unwrap().isolation.is_some(); + assert!(isolated(h.state())); + let (six, fifteen) = (sides_rail_at(&h, 6.0), sides_rail_at(&h, 15.0)); + sides_press_and_move(&mut h, six, fifteen); + assert_eq!(polygon_sides(h.state()), 15); + h.key_press(egui::Key::Escape); + h.run_steps(1); + assert_eq!(polygon_sides(h.state()), 6, "Escape cancels the drag"); + assert!(isolated(h.state()), "and isolation mode stays"); + sides_release(&mut h, fifteen); + assert!(isolated(h.state())); } /// Move from `from` to `to` in four frames with the primary button still down. diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 462adb62d2..f37a6e13de 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -279,7 +279,10 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { // Escape that cancels a ruler-origin drag or floating Tools move skips the tool and later Escape actions, // and so do its repeats while it is held. let escape_ended_gesture = escape_ended_gesture(ctx); - let escape_held_by_drag = crate::canvas::dragging(ctx) || escape_ended_gesture; + // Escape during a drag on Polygon Properties' Sides slider is the slider's (it cancels the + // drag), so neither the tool nor the later Escape actions take it. + let sides_drag = crate::panels::transform::sides_drag_held(ctx); + let escape_held_by_drag = crate::canvas::dragging(ctx) || escape_ended_gesture || sides_drag; let typing = ctx.egui_wants_keyboard_input(); // Escape closes Edit Toolbar's drawer first (egui drops a drag from it on Escape already). if app.ui.tools_drawer && !typing && !escape_held_by_drag && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { @@ -302,7 +305,7 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { if (text || !busy) && ctx.input(|i| runs_a_command(i, k, text)) { continue; } - if k == Key::Escape && escape_ended_gesture { + if k == Key::Escape && (escape_ended_gesture || sides_drag) { continue; } // A key the tool claims (Esc with a loaded place cursor) is only the tool's. @@ -400,8 +403,10 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { let row_key = |chord: &craft_keymap::Chord| { rows_keys && chord.is_plain() && !chord.mods.shift && matches!(chord.key, craft_keymap::Key::Delete | craft_keymap::Key::Backspace) }; - // An Escape that ended a ruler-origin drag or floating Tools move runs no command bound to it. - let gesture_escape = |chord: &craft_keymap::Chord| escape_ended_gesture && chord.is_plain() && chord.key == craft_keymap::Key::Escape; + // An Escape that ended a ruler-origin drag or floating Tools move, or that a Sides slider drag + // takes, runs no command bound to it. + let gesture_escape = + |chord: &craft_keymap::Chord| (escape_ended_gesture || sides_drag) && chord.is_plain() && chord.key == craft_keymap::Key::Escape; // A Copy or Cut left to the labels runs neither command from the keymap. let labels_clip = |hit: &Hit| to_labels && matches!(hit.command.id.as_str(), "edit.copy" | "edit.cut"); let hits = dispatch(app, ctx, |hit| { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40d395e75a..efa910cebc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1494,7 +1494,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). - - **Polygon side slider:** Polygon Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Sides slider after the Sides field, over 3 to 20 sides. [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) gives the slider that range and leaves larger counts, up to 1000, to the typed field, which still takes 3 to 1000. A drag previews the count through `object.setLiveShape {sides}`; its release adds one undo step when the count changed and none when it ends where it began, and Escape during the drag puts the count back and ignores the rest of it. A click on the rail or an arrow key on it sets the count in one undo step. A count above 20 shows the handle at the rail's right end, and screen readers and the field show the real count, until the rail moves. The slider's place, the rule for counts above 20 and the undo steps are VectorCraft's own (`polygon_sides_slider_is_shared_by_transform_and_properties`, `polygon_sides_above_slider_range_remain_editable`, `polygon_sides_slider_drag_is_one_undo_step`, `polygon_sides_slider_drag_released_unseen_is_kept`). + - **Polygon side slider:** Polygon Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Sides slider after the Sides field, over 3 to 20 sides. [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) gives the slider that range and leaves larger counts, up to 1000, to the typed field, which still takes 3 to 1000. A drag previews the count through `object.setLiveShape {sides}`; its release adds one undo step when the count changed and none when it ends where it began, and Escape during the drag puts the count back and ignores the rest of it without leaving isolation mode or running a command bound to Escape. A drag whose rows stop being drawn keeps its preview as one undo step (an Escape in that pass puts the count back instead), and a drag during which another document comes to the front leaves both documents as they were; in both cases the rest of the drag is ignored until the button is released. A click on the rail or an arrow key on it sets the count in one undo step. A count above 20 shows the handle at the rail's right end, and screen readers and the field show the real count, until the rail moves. The slider's place, the rule for counts above 20 and the undo steps are VectorCraft's own (`polygon_sides_slider_is_shared_by_transform_and_properties`, `polygon_sides_above_slider_range_remain_editable`, `polygon_sides_slider_drag_is_one_undo_step`, `polygon_sides_slider_drag_released_unseen_is_kept`, `polygon_sides_slider_drag_escaped_unseen_is_canceled`, `polygon_sides_slider_drag_ends_with_a_document_switch`, `polygon_sides_slider_escape_keeps_isolation_mode`). - **Hide/Show Shape Widgets:** with the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool, the Control bar shows a Hide Shape Widgets button, which reads Show Shape Widgets while the widgets are hidden (`view.shapeWidgets {on?}`). [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) describes this Control panel button, offered with any live shape drawing tool, as switching the on-canvas widgets of selected shapes off and on. While they are hidden, a selected live rectangle's or polygon's corner widgets, a live ellipse's pie widgets and a live polygon's side widget are not drawn, and the Selection tool and those shape tools do not answer a press, a double-click or the cursor on their place (a shape tool draws from there). The bounding box and its handles, the center point and Direct Selection's corner widgets (View › Hide Corner Widget) stay as they are. The setting is on by default, kept with the interface state across sessions and tool switches, and adds no undo step. Its scope beyond the shape tools, its default and what it leaves shown are VectorCraft's own rules (tests `hidden_shape_widgets_leave_the_bounding_box`, `the_shape_tools_control_bar_hides_and_shows_the_shape_widgets`, `shape_widgets_command_toggles_and_takes_on`, `hidden_shape_widgets_do_not_answer_a_shape_tool` and `hidden_shape_widgets_leave_direct_selections_corners`). - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - **Anchor Point tool, Alt-drag on a handle:** with the Anchor Point tool chosen, dragging a direction handle with Alt (Option) held links it with the opposite handle and makes the anchor smooth, on a path and on a selected blend's spine, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/create-smooth-paths-with-the-smooth-tool.html) describes; a drag without Alt still moves one handle on its own (`path.setHandle` and `object.blend.spine.moveAnchor` with `link`). VectorCraft's own rules: the opposite handle keeps its length; a retracted one is pulled out to the dragged handle's length where a segment leaves the anchor on its side and stays retracted at an open end; Shift with Alt keeps the 45° steps; an Alt-click still retracts the handle; the Pen with Alt keeps moving a handle on its own. Tests: `anchor_point_alt_drag_links_*` in `crates/tools/src/draw2/anchor/tests.rs`, `a_linked_handle_makes_the_anchor_smooth` in `crates/engine/src/tests/anchor_edit_work.rs`, `a_linked_spine_handle_makes_the_point_smooth` in `crates/engine/src/tests/blendspine.rs`. From 05762dba5b17b18118bc61b1d0d8386f4c1f0763 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:45:39 -0800 Subject: [PATCH 20/55] Eyedropper: Cmd hover outlines what the lent selection tool selects With Cmd held, a click with the Eyedropper selects with the selection tool lent to it. The hover outline is now that tool's outline: the object under the pointer, or none when that object is already selected. Before, Cmd hid the outline. While the pointer rests, the canvas compares the state its cached outline was found for with the current state field by field. It copies the selection, the paint defaults and the tool's options into a new key only when some part of that state changed. The progress-doc line states the Alt case as the front editable object (the one below when locked art covers it) and names the tests. New tests cover a selected object, Cmd, hidden art, an armed Ignore Color pick, Shift over a blend on the canvas, and Shift over an envelope. --- crates/tools/src/xform/eyedropper.rs | 25 +++++++++++ crates/ui-egui/src/canvas.rs | 3 +- crates/ui-egui/src/canvas/overlays.rs | 57 +++++++++++++++++++----- crates/ui-egui/src/canvas/tests.rs | 64 +++++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 5 files changed, 139 insertions(+), 12 deletions(-) diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 3448991367..0eb5008fc8 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -2009,6 +2009,31 @@ mod tests { assert_eq!(names(480.0, 480.0), None, "no art"); } + /// For a Shift-click on an envelope, the hover names the envelope where its distorted contents + /// are drawn, and the rectangle below where they leave the point empty. + #[test] + fn shift_hover_names_the_envelope_where_its_art_is_drawn() { + use vectorcraft_geom::{Affine, Rect}; + let d = doc_with_live_over_green(|d| { + let red = solid_rect(d, Rect::new(300.0, 300.0, 420.0, 320.0), Color::rgb(1.0, 0.0, 0.0)); + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + let content = vec![std::sync::Arc::new(red)]; + let options = Default::default(); + Node::new( + d.alloc_id(), + NodeKind::Envelope { content, kind: Box::new(kind), fidelity: 50.0, editing: false, options, frame: Box::new(Affine::IDENTITY) }, + ) + }); + let ids: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + let [.., green, envelope] = ids[..] else { panic!("two objects over the rectangle expected") }; + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let t = EyedropperTool::default(); + let names = |x: f64, y: f64| t.hover_object(&cx(&d, &s, &p), Point::new(x, y), shift); + assert_eq!(names(360.0, 310.0), Some(envelope), "the distorted contents"); + assert_eq!(names(360.0, 332.0), Some(green), "a point the contents leave empty"); + } + /// A plain click on a selected gradient mesh recolors its points, and the hover names that /// mesh; Image Trace's Ignore Color pick, which the panel samples, names nothing. #[test] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 53a1d373f8..c1eaf41980 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -61,12 +61,13 @@ use input::handle_input; use outline::KEY_OUTLINE; #[cfg(test)] use outline::{OVERLAY_MAX_ANCHORS, c32, node_outline, walk_drawn}; +pub use overlays::HoverObjectKey; +pub use overlays::SharedPaths; #[cfg(test)] use overlays::selected_anchor; use overlays::{ HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, overlay_hover_text, selection_overlay, }; -pub use overlays::{HoverObjectKey, SharedPaths}; pub use panes::{Layout as TileLayout, Panes}; pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area}; pub(crate) use quick_pen_bar::quick_pen_bar_rect; diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 79d3195eaf..736bfb999e 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -19,21 +19,25 @@ pub(super) fn hover_highlight(app: &mut VectorcraftApp, p: &egui::Painter, xf: & if app.session.tool_busy() || !matches!(app.session.tool_id(), "selection" | "directSelection" | "groupSelection" | "eyedropper") { return; } - // With Space lending the view tools, a press pans the view and acts on no object. let (m, space) = p.ctx().input(|i| (i.modifiers, i.key_down(egui::Key::Space))); + let mods = super::drag::mods(m, false); + // With Space lending the view tools, a press pans the view and acts on no object. if super::drag::space_lends_view_tools(app, m, space) { return; } - let id = if app.session.tool_id() == "eyedropper" { + // With the Eyedropper, Cmd lends a selection tool, whose click acts on what that tool outlines. + let eyedropper = app.session.tool_id() == "eyedropper"; + let lent = if eyedropper && !app.session.tool_editing() { app.session.lent_tool_id(&mods) } else { None }; + let id = if eyedropper && lent.is_none() { // The object the Eyedropper's click there samples, recolors or copies to, with the keys // held now. A selected one is outlined too: a click on it still acts on it. - let mods = super::drag::mods(m, false); let Some(id) = eyedropper_hover_object(app, h, mods, view) else { return }; id } else { + let tool = lent.unwrap_or(app.session.tool_id()); let Some(st) = app.session.active() else { return }; let Some(hit) = selection_hit_at(app, h, xf.zoom) else { return }; - let id = if app.session.tool_id() == "selection" { hit.top_object(st.isolation) } else { hit.leaf }; + let id = if tool == "selection" { hit.top_object(st.isolation) } else { hit.leaf }; if st.selection.contains(id) { return; } @@ -70,7 +74,9 @@ pub struct HoverObjectKey { } /// [`vectorcraft_engine::Session::hover_object`] at `at`, found again only when its -/// [`HoverObjectKey`] changes: over an image, or with Shift held, finding it samples a color. +/// [`HoverObjectKey`] changes: over an image, or with Shift held, finding it samples a color. The +/// cached key is compared field by field, the cheap fields first, and the key is copied only +/// when it changed. fn eyedropper_hover_object( app: &mut VectorcraftApp, at: vectorcraft_geom::Point, @@ -78,6 +84,42 @@ fn eyedropper_hover_object( view: vectorcraft_engine::ViewInfo, ) -> Option { let st = app.session.active()?; + let s = &app.session; + let cached = app.canvas.hover_object.as_ref().filter(|(k, _)| { + let HoverObjectKey { + at: k_at, + mods: k_mods, + doc, + selection, + isolation, + options, + paint, + fill_active, + stop, + tolerance, + eyedropper, + guides, + zoom, + outline, + } = k; + *k_at == at + && *k_mods == mods + && *doc == (st.uid, st.revision) + && *isolation == st.isolation + && *fill_active == s.fill_active + && *stop == s.selected_stop() + && *tolerance == s.prefs.selection_tolerance + && *eyedropper == s.prefs.eyedropper + && *guides == (view.guides, s.guides_locked()) + && *zoom == view.zoom + && *outline == view.outline + && *selection == st.selection + && *paint == s.paint + && *options == s.tool_options() + }); + if let Some((_, id)) = cached { + return *id; + } let key = HoverObjectKey { at, mods, @@ -94,11 +136,6 @@ fn eyedropper_hover_object( zoom: view.zoom, outline: view.outline, }; - if let Some((k, id)) = &app.canvas.hover_object - && *k == key - { - return *id; - } let id = app.session.hover_object(at, mods, view); app.canvas.hover_object = Some((key, id)); id diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 1a714ccfe6..c17f11629a 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6168,6 +6168,70 @@ fn eyedropper_hover_outlines_the_object_under_the_pointer() { } } +/// The Eyedropper outlines a selected object too, since its click still acts on it. With Cmd held, +/// a click selects with the selection tool lent to it, so the outline is that tool's: none on a +/// selected object, and the object under the pointer otherwise. Hiding the object under the +/// pointer, or arming Image Trace's Ignore Color pick (which acts on no object), removes the +/// outline without the pointer moving. +#[test] +fn eyedropper_hover_outline_follows_the_selection_cmd_and_the_document() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("eyedropper"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let color = c32(app.session.active().unwrap().doc.layer_color(vectorcraft_doc::NodeId(id))); + let rect = egui::Rect::from_two_pos(xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(200.0, 200.0))); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(Point::new(150.0, 150.0)))]); + assert!(app.session.active().unwrap().selection.contains(vectorcraft_doc::NodeId(id))); + let at = hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE); + assert!(!at.is_empty() && same_box(screen_box(&at), rect), "a selected object: {:?}", screen_box(&at)); + assert!(hover_outline_points(&mut app, &ctx, color, egui::Modifiers::COMMAND).is_empty(), "Cmd over a selected object"); + app.session.execute("select.none", &json!({})).unwrap(); + let at = hover_outline_points(&mut app, &ctx, color, egui::Modifiers::COMMAND); + assert!(!at.is_empty() && same_box(screen_box(&at), rect), "Cmd over an unselected object: {:?}", screen_box(&at)); + assert!(!hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE).is_empty(), "Cmd let go"); + app.session.set_tool_option("imageTraceIgnoreColor", &json!({"binding": 1})); + assert!(hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE).is_empty(), "an armed Ignore Color pick"); + app.session.set_tool_option("imageTraceIgnoreColor", &serde_json::Value::Null); + assert!(!hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE).is_empty(), "the pick disarmed"); + app.session.execute("object.hide", &json!({"ids": [id]})).unwrap(); + assert!(hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE).is_empty(), "hidden art"); +} + +/// For a Shift-click the Eyedropper outlines the object whose color the click samples: the blend +/// where one of its steps is drawn, and the rectangle below it in a gap between the steps. +#[test] +fn eyedropper_shift_hover_outlines_the_object_sampled() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let rect = |app: &mut VectorcraftApp, x: f64, y: f64, w: f64, h: f64, color: &str| { + let id = app.session.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("paint.setFill", &json!({"ids": [id], "color": color})).unwrap(); + id + }; + let back = rect(&mut app, 20.0, 50.0, 360.0, 150.0, "#00ff00"); + let a = rect(&mut app, 100.0, 100.0, 20.0, 20.0, "#ff0000"); + let b = rect(&mut app, 200.0, 100.0, 20.0, 20.0, "#0000ff"); + app.session.execute("object.blend.make", &json!({"ids": [a, b], "steps": 1})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("eyedropper"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let color = c32(app.session.active().unwrap().doc.layer_color(vectorcraft_doc::NodeId(back))); + let boxed = |x0: f64, y0: f64, x1: f64, y1: f64| egui::Rect::from_two_pos(xf.to_screen(Point::new(x0, y0)), xf.to_screen(Point::new(x1, y1))); + // One step, halfway: (150, 100) to (170, 120). + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(Point::new(160.0, 110.0)))]); + let at = hover_outline_points(&mut app, &ctx, color, egui::Modifiers::SHIFT); + assert!(!at.is_empty() && same_box(screen_box(&at), boxed(100.0, 100.0, 220.0, 120.0)), "a blend step: {:?}", screen_box(&at)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(Point::new(135.0, 110.0)))]); + let at = hover_outline_points(&mut app, &ctx, color, egui::Modifiers::SHIFT); + assert!(!at.is_empty() && same_box(screen_box(&at), boxed(20.0, 50.0, 380.0, 200.0)), "a gap between the steps: {:?}", screen_box(&at)); +} + /// The Eyedropper's hover outline follows Smart Guides › Object Highlighting. #[test] fn eyedropper_hover_outline_follows_object_highlighting() { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 143f215fcd..a061ec8a59 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2015,7 +2015,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pasting into hex color fields:** in the hex fields of the Color Picker, Swatch Options, Recolor Artwork, the Color panel, Document Setup, Duotone, Color Themes and Perspective Grid, a click or keyboard focus selects the digits. A pasted code of six digits, with or without `#`, replaces them wherever the caret is. A pasted code of three digits also replaces them, unless the paste holds only those digits and exactly three digits stay; those digits then edit the text in place. A press on another field commits the text as Tab and Enter do. As VectorCraft's own rule, a paste that is not a color leaves the field as it was. Tests: `a_hex_code_pasted_into_the_hex_field_replaces_its_digits` in `crates/ui-egui/src/dialogs/tests.rs`, `define_grid_takes_a_three_digit_color` in `crates/ui-egui/src/dialogs/tests_perspective.rs` and `a_paste_into_a_hex_field_replaces_or_edits_its_digits` in `crates/ui-egui/src/tests/numfields.rs`. - **Color Picker layout (#2008):** a centered draggable header, equal-width actions above aligned HSB/RGB/Hex and Lab/CMYK fields, compact field and slider, and warnings below the preview. No horizontal scrolling; narrow windows stack the sections with vertical scrolling. Tests in `dialogs/color_picker.rs` cover actual pointer/key input, typed values before OK/Enter, Cancel/Escape rollback, one Undo step, mode-size stability, warnings and layout at two UI scales. The screen sampler sits above the field and the upstream two-grid Tab order is retained. AccessKit regressions check the action names and each channel slider's displayed value, units and range. German and enlarged English UI renders were reviewed locally; no reference images are shipped. This is a layout improvement, with no change to scores or remaining-hour estimates. - **Eyedropper sources (#1251):** ordinary and Shift clicks, Shift+Alt appearance append, raster pixels and gradient-stop sampling can read visible locked/template art and sources outside isolation. Sampling leaves the source and selection intact; Alt reverse still uses editable hits, and hidden art stays excluded. Engine/tool/hit regressions cover the editing boundary, color models and one-step Undo/Redo. The general object/image workflow is described in [public HelpX](https://helpx.adobe.com/illustrator/using/tool-techniques/eyedropper-tool.html); the lock/isolation expectations come from the user report and these regressions, without a new full-parity measurement. - - **Eyedropper hover outline:** as VectorCraft's own behavior, with Smart Guides › Object Highlighting on, the Eyedropper outlines the object a click at the pointer would act on, in the selection tools' 1.5 px layer-color outline: the source a click copies from (locked and template art included), the selected gradient mesh a click recolors, the object below a locked one that an Alt-click gives the selection's attributes to, and for a Shift-click the object whose color is sampled (a blend or envelope where its art is drawn, the art below where it leaves a gap). A selected object is outlined too. Empty canvas, hidden art and a Cmd-click that borrows a selection tool show no outline, and with the Eyedropper or a selection tool, Space held for the view tools hides the outline. Tests: `crates/ui-egui/src/canvas/tests.rs`, `crates/tools/src/xform/eyedropper.rs`. + - **Eyedropper hover outline:** as VectorCraft's own behavior, with Smart Guides › Object Highlighting on, the Eyedropper outlines the object a click at the pointer would act on, in the selection tools' 1.5 px layer-color outline: the source a click copies from (locked and template art included), the selected gradient mesh a click recolors, the front editable object an Alt-click gives the selection's attributes to (the one below when locked art covers it), and for a Shift-click the object whose color is sampled (a blend or envelope where its art is drawn, the art below where it leaves a gap). A selected object is outlined too. With Cmd held, a click selects with the selection tool lent to the Eyedropper, and the outline is that tool's. Empty canvas and hidden art show no outline, and with the Eyedropper or a selection tool, Space held for the view tools hides the outline. Tests: `eyedropper_hover_outlines_the_object_under_the_pointer`, `eyedropper_hover_outline_follows_object_highlighting`, `eyedropper_hover_outline_is_the_object_the_click_acts_on`, `eyedropper_hover_outline_follows_the_selection_cmd_and_the_document` and `eyedropper_shift_hover_outlines_the_object_sampled` in `crates/ui-egui/src/canvas/tests.rs`, and `shift_hover_names_the_object_the_sample_comes_from`, `shift_hover_names_the_envelope_where_its_art_is_drawn` and `hover_names_the_selected_mesh_a_click_recolors` in `crates/tools/src/xform/eyedropper.rs`. - **Eyedropper colors in a CMYK document (#2276):** a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's pixel or an RGB color given to `paint.setFill`, `paint.setStroke`, `paint.sampleColor` or `swatch.new {color}` (hex input and gradient stops included) is separated through the color settings' CMYK working space and intent, as Document Color Mode converts it. With the default Generic CMYK, RGB 83/170/223 separates to C62 M19 Y0 K0, where the profile-free formula gave C63 M24 Y0 K13. - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). The ICC profile written for it (embedded in exports) gives the paper as its media white point, and its colorimetric Lab → CMYK table is the inverse of its CMYK → Lab table, without black-point compensation; the perceptual and saturation tables keep compensation. From 91bfcc7455a794c1c42da64bd8ffef0535e2b17c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:04:25 -0800 Subject: [PATCH 21/55] Eyedropper: count a blend's steps before sampling it; hover skips a selected group member Before the Eyedropper evaluates a blend to sample its color, it now counts the steps of every blend the art holds against the work left. When the steps alone exceed it, the blend is not evaluated and the sample gives no color. Hover runs this lookup on every pointer move with Shift held. The Selection tool's hover outline, and the one it shows when lent to the Eyedropper with Cmd, now outlines nothing over a selected group member, where a press keeps the selection. It uses the same rule as the press (select::selected_under_in). Tests: blend_steps_count_before_the_blend_is_evaluated and selection_hover_outline_skips_a_selected_group_member. --- crates/tools/src/select.rs | 15 ++++++-- crates/tools/src/xform/eyedropper.rs | 54 ++++++++++++++++++++++++++- crates/ui-egui/src/canvas/overlays.rs | 9 ++++- crates/ui-egui/src/canvas/tests.rs | 25 +++++++++++++ docs/target-app-parity.md | 2 +- 5 files changed, 98 insertions(+), 7 deletions(-) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index fc18a978e6..0ccb8499ed 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -1473,15 +1473,22 @@ fn object_behind(cx: &ToolContext, p: Point) -> Option { /// member with only some anchors or segments selected does not count: the press selects `top`. /// A member with every anchor selected (as `select.anchors` and `select.key` leave a path) counts. fn selected_under(cx: &ToolContext, h: &Hit, top: NodeId) -> Option { - if cx.selection.contains(top) { + selected_under_in(cx.doc, cx.selection, h, top) +} + +/// [`selected_under`] in `doc` with `selection`: the selected object a Selection tool press on +/// `h` lands on, where `top` is the object the press would select. The canvas's hover outline +/// outlines nothing where this finds an object. +pub fn selected_under_in(doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection, h: &Hit, top: NodeId) -> Option { + if selection.contains(top) { return Some(top); } let every_anchor = |id: NodeId| { - cx.selection + selection .partial(id) - .is_none_or(|picked| cx.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.anchors().all(|(s, i, _)| picked.contains(&(s, i))))) + .is_none_or(|picked| doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.anchors().all(|(s, i, _)| picked.contains(&(s, i))))) }; - let whole = |id: NodeId| cx.selection.contains(id) && every_anchor(id) && !cx.selection.segments.contains_key(&id); + let whole = |id: NodeId| selection.contains(id) && every_anchor(id) && !selection.segments.contains_key(&id); let below = h.ancestry.iter().position(|id| *id == top).map_or(&[][..], |i| h.ancestry.get(i..).unwrap_or_default()); below.iter().copied().chain(std::iter::once(h.leaf)).find(|id| whole(*id)) } diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 0eb5008fc8..38a6b8cf58 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -249,14 +249,31 @@ fn drawn_live<'d>(doc: &'d Document, ancestry: &[NodeId]) -> Option<&'d Node> { /// The color the art blend or envelope `n` draws shows at `p`, sampled as [`art_color_at`] samples /// art: a blend's keys and steps, an envelope's distorted contents, symbol instances in them by /// their symbols' art. Evaluating it counts the objects it holds, and the art made counts its -/// objects. +/// objects. When less work is left than the steps of its blends make, it is not evaluated. fn live_color_at(s: &mut Sampler, levels: &mut [Option], n: &Node, p: Point) -> Option { + let steps = blend_steps_in(n); + if s.work < steps { + // Too little work is left for the steps the blends make. + s.spend(steps)?; + } s.spend(n.count())?; let art = vectorcraft_effects::expand_live_deep(Some(s.doc), n); s.spend(art.count())?; art_color_at(s, levels, [art], p) } +/// The steps the blends in `n` and its subtree make between their keys, at the least: a blend +/// inside another blend's keys is counted once, not once for each step that copies it. +fn blend_steps_in(n: &Node) -> usize { + let mut steps = 0usize; + n.walk(&mut |c| { + if let NodeKind::Blend { children, spec } = &c.kind { + steps = vectorcraft_doc::blend::blend_steps(children, spec).into_iter().fold(steps, usize::saturating_add); + } + }); + steps +} + /// The color `n` shows at `p`: an image's pixels, a mesh's interpolated patch color, a symbol /// instance's art, or the color of its fill (or its stroke, when the stroke was hit or there is no /// fill) there. Images, symbols and patterns are looked up in the sampled document. @@ -2009,6 +2026,41 @@ mod tests { assert_eq!(names(480.0, 480.0), None, "no art"); } + /// A blend's steps count as work before it is evaluated: the steps of every blend it holds + /// are counted, and with less work left than that the sample gives no color. + #[test] + fn blend_steps_count_before_the_blend_is_evaluated() { + use vectorcraft_doc::Document; + use vectorcraft_doc::live::{BlendSpacing, BlendSpec}; + use vectorcraft_geom::Rect; + let blend = |d: &mut Document, steps: u32| { + let red = solid_rect(d, Rect::new(300.0, 300.0, 320.0, 320.0), Color::rgb(1.0, 0.0, 0.0)); + let blue = solid_rect(d, Rect::new(400.0, 300.0, 420.0, 320.0), Color::rgb(0.0, 0.0, 1.0)); + let spec = BlendSpec { spacing: BlendSpacing::Steps(steps), ..Default::default() }; + Node::new(d.alloc_id(), NodeKind::Blend { children: vec![std::sync::Arc::new(red), std::sync::Arc::new(blue)], spec: Box::new(spec) }) + }; + let mut scratch = Document::new(500.0, 500.0); + let (big, small) = (blend(&mut scratch, 1000), blend(&mut scratch, 3)); + let rect = solid_rect(&mut scratch, Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb(0.0, 1.0, 0.0)); + assert_eq!(blend_steps_in(&big), 1000); + assert_eq!(blend_steps_in(&rect), 0); + let group = + Node::new(scratch.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(big), std::sync::Arc::new(small)], clip: false }); + assert_eq!(blend_steps_in(&group), 1003, "every blend in the group"); + + let d = doc_with_live_over_green(|d| blend(d, 1000)); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let opts = sample_options(&cx); + let mut levels: Vec> = (0..MAX_NESTING).map(|_| None).collect(); + let at = Point::new(360.0, 310.0); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: 900, exhausted: false, patterns: 0 }; + assert_eq!(color_under(&mut s, &d, &mut levels, at, opts).map(|(c, _)| c.to_hex()), None); + assert!(s.exhausted, "less work left than the blend's 1,000 steps"); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: MAX_WORK, exhausted: false, patterns: 0 }; + assert!(color_under(&mut s, &d, &mut levels, at, opts).is_some(), "a step is drawn at the point"); + } + /// For a Shift-click on an envelope, the hover names the envelope where its distorted contents /// are drawn, and the rectangle below where they leave the point empty. #[test] diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 736bfb999e..351f3b070e 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -38,7 +38,14 @@ pub(super) fn hover_highlight(app: &mut VectorcraftApp, p: &egui::Painter, xf: & let Some(st) = app.session.active() else { return }; let Some(hit) = selection_hit_at(app, h, xf.zoom) else { return }; let id = if tool == "selection" { hit.top_object(st.isolation) } else { hit.leaf }; - if st.selection.contains(id) { + // A Selection tool press on selected art inside `id`, such as a group member picked with + // Group Selection, keeps the selection and selects nothing new. + let kept = if tool == "selection" { + vectorcraft_tools::select::selected_under_in(&st.doc, &st.selection, &hit, id).is_some() + } else { + st.selection.contains(id) + }; + if kept { return; } id diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index c17f11629a..534dbc5562 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6201,6 +6201,31 @@ fn eyedropper_hover_outline_follows_the_selection_cmd_and_the_document() { assert!(hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE).is_empty(), "hidden art"); } +/// With a group member selected (as Group Selection leaves it), the Selection tool outlines +/// nothing over that member, where a press keeps the selection, and the group over its other +/// member, where a press selects the group. +#[test] +fn selection_hover_outline_skips_a_selected_group_member() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let b = app.session.execute("shape.rectangle", &json!({"x": 200, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + app.session.execute("object.group", &json!({})).unwrap(); + app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + app.select_tool("selection"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let color = c32(app.session.active().unwrap().doc.layer_color(vectorcraft_doc::NodeId(a))); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(Point::new(125.0, 125.0)))]); + assert!(hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE).is_empty(), "the selected member"); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(Point::new(225.0, 125.0)))]); + let group = egui::Rect::from_two_pos(xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(250.0, 150.0))); + let at = hover_outline_points(&mut app, &ctx, color, egui::Modifiers::NONE); + assert!(!at.is_empty() && same_box(screen_box(&at), group), "the other member: {:?}", screen_box(&at)); +} + /// For a Shift-click the Eyedropper outlines the object whose color the click samples: the blend /// where one of its steps is drawn, and the rectangle below it in a gap between the steps. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a061ec8a59..eaa809b5f2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2015,7 +2015,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pasting into hex color fields:** in the hex fields of the Color Picker, Swatch Options, Recolor Artwork, the Color panel, Document Setup, Duotone, Color Themes and Perspective Grid, a click or keyboard focus selects the digits. A pasted code of six digits, with or without `#`, replaces them wherever the caret is. A pasted code of three digits also replaces them, unless the paste holds only those digits and exactly three digits stay; those digits then edit the text in place. A press on another field commits the text as Tab and Enter do. As VectorCraft's own rule, a paste that is not a color leaves the field as it was. Tests: `a_hex_code_pasted_into_the_hex_field_replaces_its_digits` in `crates/ui-egui/src/dialogs/tests.rs`, `define_grid_takes_a_three_digit_color` in `crates/ui-egui/src/dialogs/tests_perspective.rs` and `a_paste_into_a_hex_field_replaces_or_edits_its_digits` in `crates/ui-egui/src/tests/numfields.rs`. - **Color Picker layout (#2008):** a centered draggable header, equal-width actions above aligned HSB/RGB/Hex and Lab/CMYK fields, compact field and slider, and warnings below the preview. No horizontal scrolling; narrow windows stack the sections with vertical scrolling. Tests in `dialogs/color_picker.rs` cover actual pointer/key input, typed values before OK/Enter, Cancel/Escape rollback, one Undo step, mode-size stability, warnings and layout at two UI scales. The screen sampler sits above the field and the upstream two-grid Tab order is retained. AccessKit regressions check the action names and each channel slider's displayed value, units and range. German and enlarged English UI renders were reviewed locally; no reference images are shipped. This is a layout improvement, with no change to scores or remaining-hour estimates. - **Eyedropper sources (#1251):** ordinary and Shift clicks, Shift+Alt appearance append, raster pixels and gradient-stop sampling can read visible locked/template art and sources outside isolation. Sampling leaves the source and selection intact; Alt reverse still uses editable hits, and hidden art stays excluded. Engine/tool/hit regressions cover the editing boundary, color models and one-step Undo/Redo. The general object/image workflow is described in [public HelpX](https://helpx.adobe.com/illustrator/using/tool-techniques/eyedropper-tool.html); the lock/isolation expectations come from the user report and these regressions, without a new full-parity measurement. - - **Eyedropper hover outline:** as VectorCraft's own behavior, with Smart Guides › Object Highlighting on, the Eyedropper outlines the object a click at the pointer would act on, in the selection tools' 1.5 px layer-color outline: the source a click copies from (locked and template art included), the selected gradient mesh a click recolors, the front editable object an Alt-click gives the selection's attributes to (the one below when locked art covers it), and for a Shift-click the object whose color is sampled (a blend or envelope where its art is drawn, the art below where it leaves a gap). A selected object is outlined too. With Cmd held, a click selects with the selection tool lent to the Eyedropper, and the outline is that tool's. Empty canvas and hidden art show no outline, and with the Eyedropper or a selection tool, Space held for the view tools hides the outline. Tests: `eyedropper_hover_outlines_the_object_under_the_pointer`, `eyedropper_hover_outline_follows_object_highlighting`, `eyedropper_hover_outline_is_the_object_the_click_acts_on`, `eyedropper_hover_outline_follows_the_selection_cmd_and_the_document` and `eyedropper_shift_hover_outlines_the_object_sampled` in `crates/ui-egui/src/canvas/tests.rs`, and `shift_hover_names_the_object_the_sample_comes_from`, `shift_hover_names_the_envelope_where_its_art_is_drawn` and `hover_names_the_selected_mesh_a_click_recolors` in `crates/tools/src/xform/eyedropper.rs`. + - **Eyedropper hover outline:** as VectorCraft's own behavior, with Smart Guides › Object Highlighting on, the Eyedropper outlines the object a click at the pointer would act on, in the selection tools' 1.5 px layer-color outline: the source a click copies from (locked and template art included), the selected gradient mesh a click recolors, the front editable object an Alt-click gives the selection's attributes to (the one below when locked art covers it), and for a Shift-click the object whose color is sampled (a blend or envelope where its art is drawn, the art below where it leaves a gap). A selected object is outlined too. With Cmd held, a click selects with the selection tool lent to the Eyedropper, and the outline is that tool's. The Selection tool's outline, lent or not, leaves out a group whose selected member is under the pointer, where a press keeps the selection. Finding a Shift-click's sample counts a blend's steps before the blend is evaluated. Empty canvas and hidden art show no outline, and with the Eyedropper or a selection tool, Space held for the view tools hides the outline. Tests: `eyedropper_hover_outlines_the_object_under_the_pointer`, `eyedropper_hover_outline_follows_object_highlighting`, `eyedropper_hover_outline_is_the_object_the_click_acts_on`, `eyedropper_hover_outline_follows_the_selection_cmd_and_the_document`, `selection_hover_outline_skips_a_selected_group_member` and `eyedropper_shift_hover_outlines_the_object_sampled` in `crates/ui-egui/src/canvas/tests.rs`, and `shift_hover_names_the_object_the_sample_comes_from`, `shift_hover_names_the_envelope_where_its_art_is_drawn`, `hover_names_the_selected_mesh_a_click_recolors` and `blend_steps_count_before_the_blend_is_evaluated` in `crates/tools/src/xform/eyedropper.rs`. - **Eyedropper colors in a CMYK document (#2276):** a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's pixel or an RGB color given to `paint.setFill`, `paint.setStroke`, `paint.sampleColor` or `swatch.new {color}` (hex input and gradient stops included) is separated through the color settings' CMYK working space and intent, as Document Color Mode converts it. With the default Generic CMYK, RGB 83/170/223 separates to C62 M19 Y0 K0, where the profile-free formula gave C63 M24 Y0 K13. - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). The ICC profile written for it (embedded in exports) gives the paper as its media white point, and its colorimetric Lab → CMYK table is the inverse of its CMYK → Lab table, without black-point compensation; the perceptual and saturation tables keep compensation. From a935af00151607b160fa477bc6d903aaa5c0c9d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:34:42 -0800 Subject: [PATCH 22/55] Eyedropper: count the steps that copy a nested blend before sampling it Each step of a blend whose keys are blends is a copy of one of them, which makes its own steps when drawn. The work check before a blend is evaluated now counts those steps too, with the same count the blend uses to fit its steps (`vectorcraft_doc::blend::blend_steps_made`), so a nested blend with more steps than the work left is not evaluated. Tests check that the blend is not evaluated when the work left is too little, for a plain blend and for an outer blend of nested blends. --- crates/doc/src/blend.rs | 7 +++ crates/tools/src/xform/eyedropper.rs | 74 ++++++++++++++++++++++------ 2 files changed, 65 insertions(+), 16 deletions(-) diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 02458af8c5..64545d1bcf 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -2186,6 +2186,13 @@ pub fn blend_steps(keys: &[Arc], spec: &BlendSpec) -> Vec { StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0 } +/// Most steps the blends in `n` and its subtree make in all when drawn: a step that copies a +/// blend counts that blend's steps again, and each instance of a repeat counts its source's +/// steps again. Objects that are not blend steps count 0. +pub fn blend_steps_made(n: &Node) -> usize { + StepCount::default().node(n, false) +} + /// Does each pair of `keys` blended with `spec` ask for the same number of steps /// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and, /// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)? diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 38a6b8cf58..0c63f2f21c 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -249,29 +249,26 @@ fn drawn_live<'d>(doc: &'d Document, ancestry: &[NodeId]) -> Option<&'d Node> { /// The color the art blend or envelope `n` draws shows at `p`, sampled as [`art_color_at`] samples /// art: a blend's keys and steps, an envelope's distorted contents, symbol instances in them by /// their symbols' art. Evaluating it counts the objects it holds, and the art made counts its -/// objects. When less work is left than the steps of its blends make, it is not evaluated. +/// objects. When less work is left than the steps of its blends make in all, the steps that copy +/// a nested blend included ([`vectorcraft_doc::blend::blend_steps_made`]), it is not evaluated. fn live_color_at(s: &mut Sampler, levels: &mut [Option], n: &Node, p: Point) -> Option { - let steps = blend_steps_in(n); + let steps = vectorcraft_doc::blend::blend_steps_made(n); if s.work < steps { // Too little work is left for the steps the blends make. s.spend(steps)?; } s.spend(n.count())?; + #[cfg(test)] + EXPANSIONS.with(|e| e.set(e.get() + 1)); let art = vectorcraft_effects::expand_live_deep(Some(s.doc), n); s.spend(art.count())?; art_color_at(s, levels, [art], p) } -/// The steps the blends in `n` and its subtree make between their keys, at the least: a blend -/// inside another blend's keys is counted once, not once for each step that copies it. -fn blend_steps_in(n: &Node) -> usize { - let mut steps = 0usize; - n.walk(&mut |c| { - if let NodeKind::Blend { children, spec } = &c.kind { - steps = vectorcraft_doc::blend::blend_steps(children, spec).into_iter().fold(steps, usize::saturating_add); - } - }); - steps +#[cfg(test)] +thread_local! { + /// The blends and envelopes [`live_color_at`] has evaluated on this thread. + static EXPANSIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The color `n` shows at `p`: an image's pixels, a mesh's interpolated patch color, a symbol @@ -2027,10 +2024,12 @@ mod tests { } /// A blend's steps count as work before it is evaluated: the steps of every blend it holds - /// are counted, and with less work left than that the sample gives no color. + /// are counted, and with less work left than that the sample gives no color and the blend is + /// not evaluated. #[test] fn blend_steps_count_before_the_blend_is_evaluated() { use vectorcraft_doc::Document; + use vectorcraft_doc::blend::blend_steps_made; use vectorcraft_doc::live::{BlendSpacing, BlendSpec}; use vectorcraft_geom::Rect; let blend = |d: &mut Document, steps: u32| { @@ -2042,11 +2041,11 @@ mod tests { let mut scratch = Document::new(500.0, 500.0); let (big, small) = (blend(&mut scratch, 1000), blend(&mut scratch, 3)); let rect = solid_rect(&mut scratch, Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb(0.0, 1.0, 0.0)); - assert_eq!(blend_steps_in(&big), 1000); - assert_eq!(blend_steps_in(&rect), 0); + assert_eq!(blend_steps_made(&big), 1000); + assert_eq!(blend_steps_made(&rect), 0); let group = Node::new(scratch.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(big), std::sync::Arc::new(small)], clip: false }); - assert_eq!(blend_steps_in(&group), 1003, "every blend in the group"); + assert_eq!(blend_steps_made(&group), 1003, "every blend in the group"); let d = doc_with_live_over_green(|d| blend(d, 1000)); let (sel, p) = (Selection::default(), paint()); @@ -2054,11 +2053,54 @@ mod tests { let opts = sample_options(&cx); let mut levels: Vec> = (0..MAX_NESTING).map(|_| None).collect(); let at = Point::new(360.0, 310.0); + let evaluated = || EXPANSIONS.with(std::cell::Cell::get); + let before = evaluated(); let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: 900, exhausted: false, patterns: 0 }; assert_eq!(color_under(&mut s, &d, &mut levels, at, opts).map(|(c, _)| c.to_hex()), None); assert!(s.exhausted, "less work left than the blend's 1,000 steps"); + assert_eq!(evaluated(), before, "the blend is not evaluated"); let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: MAX_WORK, exhausted: false, patterns: 0 }; assert!(color_under(&mut s, &d, &mut levels, at, opts).is_some(), "a step is drawn at the point"); + assert!(evaluated() > before, "with enough work the blend is evaluated"); + } + + /// Each step of a blend whose keys are blends is a copy of one of them, so the steps it makes + /// in all count before it is evaluated: an outer blend of 20 steps between two blends of 100 + /// steps makes more than 2,000, though its blends have 220 steps between their own keys. + #[test] + fn steps_that_copy_a_nested_blend_count_before_it_is_evaluated() { + use vectorcraft_doc::Document; + use vectorcraft_doc::live::{BlendSpacing, BlendSpec}; + use vectorcraft_geom::Rect; + let blend = |d: &mut Document, keys: Vec, steps: u32| { + let spec = BlendSpec { spacing: BlendSpacing::Steps(steps), ..Default::default() }; + Node::new(d.alloc_id(), NodeKind::Blend { children: keys.into_iter().map(std::sync::Arc::new).collect(), spec: Box::new(spec) }) + }; + let inner = |d: &mut Document, y: f64| { + let red = solid_rect(d, Rect::new(300.0, y, 320.0, y + 10.0), Color::rgb(1.0, 0.0, 0.0)); + let blue = solid_rect(d, Rect::new(400.0, y, 420.0, y + 10.0), Color::rgb(0.0, 0.0, 1.0)); + blend(d, vec![red, blue], 100) + }; + let d = doc_with_live_over_green(|d| { + let (a, b) = (inner(d, 300.0), inner(d, 330.0)); + blend(d, vec![a, b], 20) + }); + let outer = d.layers[0].children().unwrap().last().unwrap(); + assert!(vectorcraft_doc::blend::blend_steps_made(outer) > 2_000, "the copies' steps count"); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let opts = sample_options(&cx); + let mut levels: Vec> = (0..MAX_NESTING).map(|_| None).collect(); + let at = Point::new(310.0, 305.0); + let evaluated = || EXPANSIONS.with(std::cell::Cell::get); + let before = evaluated(); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: 1_000, exhausted: false, patterns: 0 }; + assert_eq!(color_under(&mut s, &d, &mut levels, at, opts).map(|(c, _)| c.to_hex()), None); + assert!(s.exhausted, "less work left than the steps the outer blend makes"); + assert_eq!(evaluated(), before, "the outer blend is not evaluated"); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: MAX_WORK, exhausted: false, patterns: 0 }; + assert!(color_under(&mut s, &d, &mut levels, at, opts).is_some(), "a key is drawn at the point"); + assert!(evaluated() > before, "with enough work the outer blend is evaluated"); } /// For a Shift-click on an envelope, the hover names the envelope where its distorted contents From cc3a8775adb6a60831275c07a3821c15291e91cb Mon Sep 17 00:00:00 2001 From: Zaxaerith Date: Sat, 21 Nov 2026 18:46:43 +0800 Subject: [PATCH 23/55] docs(cli): correct artboard color export help (#8850) --- crates/engine/src/cmd/layer.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 73c92877e9..5ccc441ddd 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -156,7 +156,7 @@ pub fn specs() -> Vec { "Artboard Options…", ["Window", "Artboards"], None, - "{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes", + "{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on. Supported artboard exports and printing include it by default. Set `includeArtboardFill: false` on the export or print command to omit it. Selection exports, exports of non-artboard regions, and unsupported formats omit the background) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes", has_doc, artboard_set ), From 1b29256601c465fdbd1d1a2043fab3c6039165bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:14:06 -0800 Subject: [PATCH 24/55] Plug-ins: stored and folder plug-ins load on worker threads while the window shows At launch the desktop app loaded every stored plug-in and every module in the Additional Plug-ins Folder on the UI thread before the window appeared, one after the other. A slow or panicking module held up or ended startup. - crates/plugins/src/loader.rs (new): `Loads` runs load jobs on up to four threads. Each job runs inside `catch_unwind`; a panic or a load that takes 10 s or longer fails that job alone, and the others go on. Outcomes come back in job order. - registry::FolderLoad and store::StoredLoad list in one step, load on the workers and install in file-name order. A module whose id was installed or removed in another window while it loaded is skipped. - The desktop app loads in the background only during launch; frames install the finished loads. Plug-in commands, commands that edit, exports, control requests and files opened at launch wait for the loads first; view commands and queries do not. - The launch marker names every plug-in still loading, not only the oldest. After a launch that stopped during the loads, the Safe Mode choice lists all of them, and Disable Listed Plug-ins and Continue turns them all off. `plugin.safeMode` adds `pendingItems`. A module whose load panicked is no longer named. Docs: docs/plugins.md, docs/mcp.md. --- apps/vectorcraft/src/app.rs | 13 +- apps/vectorcraft/src/main.rs | 6 + apps/vectorcraft/src/tests.rs | 3 +- crates/engine/src/cmd/plugin.rs | 303 ++++++++-- crates/engine/src/command_sets.rs | 8 + crates/engine/src/file_access.rs | 35 +- crates/engine/src/lib.rs | 7 +- crates/engine/src/session/documents.rs | 2 + crates/engine/src/session/execute.rs | 7 + crates/engine/src/store.rs | 481 ++++++++++++++-- crates/engine/src/tests/plugins.rs | 283 ++++++++++ crates/engine/tests/plugin_safe_mode.rs | 2 +- crates/plugins/src/effect.rs | 10 +- crates/plugins/src/lib.rs | 1 + crates/plugins/src/loader.rs | 717 ++++++++++++++++++++++++ crates/plugins/src/registry.rs | 546 ++++++++++++++++-- crates/plugins/src/safe_mode.rs | 261 ++++++--- crates/ui-egui/src/app.rs | 12 + crates/ui-egui/src/app/control.rs | 9 + crates/ui-egui/src/dialogs/safe_mode.rs | 101 ++-- crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/io/export.rs | 2 + crates/ui-egui/src/io/open.rs | 2 + crates/ui-egui/src/menus/invoke.rs | 6 + crates/ui-egui/src/opening.rs | 2 + crates/ui-egui/src/state.rs | 5 +- crates/ui-egui/tests/safe_mode.rs | 43 +- docs/mcp.md | 9 +- docs/plugins.md | 13 + 53 files changed, 2701 insertions(+), 288 deletions(-) create mode 100644 crates/plugins/src/loader.rs diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index a40eb0c92f..3d5ed72143 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -122,6 +122,9 @@ impl eframe::App for App { // screen first (`quit_windows`). #[cfg(not(any(target_os = "macos", windows)))] super::quit_windows::before_teardown(self.winit_window.as_deref()); + // Plug-ins still loading end before the launch marker does (the macOS exit below skips + // dropping the app). + self.app.session.cancel_plugin_loads(); end_before_teardown(self.frames); } } @@ -186,8 +189,9 @@ impl App { // dialog is open: what asked for it runs again on its document when it answers. They also // wait for the choice about a stopped plug-in, so they open after the plug-ins it loads, as // do the command line's files held back for it. Files later launches handed over before the - // choice ended in Safe Mode open in a new app with plug-ins. - if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) { + // choice ended in Safe Mode open in a new app with plug-ins. They wait while plug-ins load + // as well, since a plug-in may be what reads them. + if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) && !self.app.session.plugins_loading() { let held = std::mem::take(&mut self.held_files); #[cfg(target_os = "macos")] let files = open_documents::take(); @@ -252,9 +256,10 @@ pub(crate) fn bring_window_forward(ctx: &egui::Context) { } /// Open the command line's `files` now, or, while the choice about a stopped plug-in is up -/// ([`safe_mode::choosing`]), return them to open once it is made, with the plug-ins it loads. +/// ([`safe_mode::choosing`]) or plug-ins are still loading (a plug-in may be what reads one), +/// return them to open once it is made and they have loaded. pub(crate) fn open_or_hold(app: &mut VectorcraftApp, files: Vec) -> Vec { - if safe_mode::choosing(app) { + if safe_mode::choosing(app) || app.session.plugins_loading() { return files; } open_files(app, files); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 29cb56bdfa..081ce9a6b8 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -548,6 +548,9 @@ fn main() -> std::process::ExitCode { // preferences (none for runs without preferences), and Safe Mode. let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch"))); let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag); + // The launch's loads of the stored plug-ins and the plug-ins folder go on on worker + // threads while the window shows; the frames install them as they finish. + session.load_plugins_in_background(true); prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); @@ -560,6 +563,9 @@ fn main() -> std::process::ExitCode { app.set_startup_update_check(true); load_prefs(&mut app, saved); safe_mode::after_start(&mut app, stopped); + // Loads started later (a preference change, the end of Safe Mode) are waited for, + // after the launch's own. + app.session.load_plugins_in_background(false); // The saved PDF presets live in their own folder (also read by vectorcraft-cli), // which takes over from the copy the preferences file used to hold. prefs_dir::attach_pdf_preset_store(&mut app.session); diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index 54fa01da03..2accab70cf 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -55,7 +55,8 @@ fn command_line_files_wait_for_the_choice_about_a_stopped_plug_in() { ..Default::default() }; let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), services); - app.ui.stopped_plugin = Some(serde_json::json!({"id": "test.held", "name": "Held"})); + let held = serde_json::json!({"id": "test.held", "name": "Held"}); + app.ui.stopped_plugin = Some(serde_json::json!({"item": held, "items": [held]})); assert_eq!(open_or_hold(&mut app, files.clone()), files, "held while the choice is up"); assert!(read.borrow().is_empty(), "nothing opened before the choice"); app.ui.stopped_plugin = None; diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..f34f8cdfa8 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -51,7 +51,7 @@ use vectorcraft_doc::{Effect, Node}; use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode}; use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or}; -use crate::store::StoreTurn; +use crate::store::{PluginLoad, StoreTurn}; use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission}; @@ -704,9 +704,10 @@ thread_local! { } /// Held by `plugin.install` from its first read of the grant until the store holds what it -/// installed, and throughout by `plugin.remove`, by loads of the stored plug-ins -/// ([`Session::load_stored_plugins`]) and by loads of a plug-ins folder: these run one after the -/// other across sessions. +/// installed, throughout by `plugin.remove`, and while the loads of the stored plug-ins +/// ([`Session::load_stored_plugins`]) and of a plug-ins folder install what they loaded: these run +/// one after the other across sessions. It is not held while the modules load, so a session's +/// plug-in commands don't wait for another session's loads. static PLUGIN_CHANGES: Mutex<()> = Mutex::new(()); /// Takes [`PLUGIN_CHANGES`], waiting while another session holds it. @@ -724,6 +725,21 @@ pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> { } } +/// Takes [`PLUGIN_CHANGES`] when no other session holds it, without waiting. +pub(crate) fn try_hold_plugin_changes() -> Option> { + match PLUGIN_CHANGES.try_lock() { + Ok(held) => Some(held), + Err(std::sync::TryLockError::Poisoned(e)) => Some(e.into_inner()), + Err(std::sync::TryLockError::WouldBlock) => None, + } +} + +/// Tests: whether [`PLUGIN_CHANGES`] could be taken now. +#[cfg(test)] +pub(crate) fn plugin_changes_free() -> bool { + !matches!(PLUGIN_CHANGES.try_lock(), Err(std::sync::TryLockError::WouldBlock)) +} + /// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an /// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget /// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this @@ -973,31 +989,57 @@ fn load_path(_: &str) -> Result<(Plugin, Vec)> { Err(EngineError::Other("installing from a path is not available on the web; pass the module as `dataBase64`".into())) } -/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, and what -/// happened. -static FOLDER: Mutex, Value)>> = Mutex::new(None); +/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, what +/// happened, and the load whose report it is ([`FOLDER_LOADS`]; 0: a `plugin.reload`). +type FolderRecord = (String, Option, Value, u64); + +/// The [`FolderRecord`] of the plug-in folder last loaded. +static FOLDER: Mutex> = Mutex::new(None); + +/// The number of the last folder load [`sync_prefs`] started, which it keeps in [`FOLDER`] while +/// that load runs, so only that load replaces or clears the record. +static FOLDER_LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// Loads the Additional Plug-ins Folder preference (`*.wasm`) when it is set and it, or the /// session's plug-in store, has changed since the last load. Runs whenever preferences are applied -/// (startup, `prefs.set`). Native only. -pub(crate) fn sync_prefs(s: &Session) { - let folder = s.prefs.plugins_folder.trim(); +/// (startup, `prefs.set`). With [`Session::load_plugins_in_background`] on, it returns while the +/// modules load, and `plugin.list` reports the folder as loading until they are installed. Off, it +/// returns once the folder's plug-ins are installed, also while another session is still loading +/// the same folder. Native only. +pub(crate) fn sync_prefs(s: &mut Session) { + let folder = s.prefs.plugins_folder.trim().to_string(); // In Safe Mode nothing loads, and the folder is loaded once it ends ([`load_prefs_folder`]). if folder.is_empty() || safe_mode::active() { return; } - let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner()); - if last.as_ref().is_some_and(|(f, store, _)| f == folder && *store == s.plugin_dir) { + // This session's own load of the folder, still running, is waited for unless loads go on in the + // background. + if s.plugin_loads.iter().any(|l| matches!(l, PluginLoad::Folder(f) if f.loads(&folder, &s.plugin_dir))) { + if !s.plugin_loads_in_background { + s.finish_plugin_loads(); + } return; } - *last = Some((folder.to_string(), s.plugin_dir.clone(), load_folder(s, folder))); + let token = { + let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + // A folder another session is still loading is loaded here too: that load may end with its + // session, and this one returns once its own plug-ins are installed. + if last.as_ref().is_some_and(|(f, store, r, _)| *f == folder && *store == s.plugin_dir && r["loading"] != true) { + return; + } + let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + *last = Some((folder.clone(), s.plugin_dir.clone(), json!({"folder": folder, "loading": true}), token)); + token + }; + let load = start_folder(s, &folder, Some(token)); + s.queue_plugin_load(PluginLoad::Folder(load)); } /// The Additional Plug-ins Folder preference was cleared from `old`: when `old` is the folder last /// loaded, it is forgotten, so setting the preference to it again loads it again. pub(crate) fn forget_prefs_folder(old: &str) { let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner()); - if last.as_ref().is_some_and(|(f, _, _)| f == old.trim()) { + if last.as_ref().is_some_and(|(f, _, _, _)| f == old.trim()) { *last = None; } } @@ -1017,42 +1059,199 @@ pub fn load_prefs_folder(s: &mut Session) { sync_prefs(s); } -/// Loads the plug-ins in `folder`, those that list permissions only when `s` has them granted -/// ([`Session::plugin_approved`], with the store's grants read once) → its report; saves the -/// disabled list when loading changed it. +/// The modules of a folder loading ([`registry::FolderLoad`]); the web build has none. #[cfg(not(target_arch = "wasm32"))] -fn load_folder(s: &Session, folder: &str) -> Value { - if let Err(e) = crate::file_access::check_read(folder) { - return json!({"folder": folder, "error": e}); - } - // A file in it may be a link to one elsewhere. - let allow = |f: &std::path::Path| match f.to_str() { - Some(f) => crate::file_access::check_read(f), - // A lossy name would check another file than the one loaded. - None if crate::file_access::current().is_none() => Ok(()), - None => Err(format!("automation path rejected: {} isn't valid text", f.display())), - }; - // A `plugin.install` in another session or process finishes writing the store first. When the - // store can't be locked, the folder still loads, and the store isn't written. - let _held = hold_plugin_changes(); - let turn = s.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld()); - match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) { - Ok(r) => { - for id in &r.loaded { - s.attach_plugin_storage(&turn, id); - } - if r.disabled_changed { - s.store_disabled_plugins_in(&turn); - } - json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::>(), "leftOut": r.left_out}) +type FolderModules = registry::FolderLoad; +#[cfg(target_arch = "wasm32")] +type FolderModules = std::convert::Infallible; + +/// A load of the plug-ins in a folder ([`start_folder`]), which [`install_folder`] installs as the +/// modules load and [`end_folder`] ends. +pub(crate) struct FolderPending { + folder: String, + /// The plug-in store whose grants it loads with. + store: Option, + /// The load's number in [`FOLDER`] when [`end_folder`] keeps its report as the folder last + /// loaded ([`sync_prefs`]). + record: Option, + /// The modules loading, or the report of a folder that can't be loaded; `None` once ended. + load: Option>, + /// Whether the modules not installed yet were dropped ([`FolderPending::cancel`]). + canceled: bool, +} + +impl FolderPending { + /// Whether every module has been installed or reported. + pub(crate) fn done(&self) -> bool { + match &self.load { + #[cfg(not(target_arch = "wasm32"))] + Some(Ok(load)) => load.done(), + #[cfg(target_arch = "wasm32")] + Some(Ok(never)) => match *never {}, + Some(Err(_)) | None => true, } - Err(e) => json!({"folder": folder, "error": e.to_string()}), + } + + /// Starts the modules loading, unless they started already. + pub(crate) fn start(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(Ok(load)) = &mut self.load { + load.start(); + } + } + + /// The installs and removals its modules are checked against (`None`: the folder couldn't be + /// listed, or the load ended). + pub(crate) fn changes(&self) -> Option<®istry::LoadChanges> { + match &self.load { + #[cfg(not(target_arch = "wasm32"))] + Some(Ok(load)) => Some(load.changes()), + #[cfg(target_arch = "wasm32")] + Some(Ok(never)) => match *never {}, + Some(Err(_)) | None => None, + } + } + + /// [`FolderPending::changes`], to adopt an earlier load's. + pub(crate) fn changes_mut(&mut self) -> Option<&mut registry::LoadChanges> { + match &mut self.load { + #[cfg(not(target_arch = "wasm32"))] + Some(Ok(load)) => Some(load.changes_mut()), + #[cfg(target_arch = "wasm32")] + Some(Ok(never)) => match *never {}, + Some(Err(_)) | None => None, + } + } + + /// Whether something can be installed or reported now, without waiting. + pub(crate) fn ready(&mut self) -> bool { + match &mut self.load { + #[cfg(not(target_arch = "wasm32"))] + Some(Ok(load)) => load.ready(), + #[cfg(target_arch = "wasm32")] + Some(Ok(never)) => match *never {}, + Some(Err(_)) | None => true, + } + } + + /// Waits until the next module in file-name order has loaded or failed. + pub(crate) fn wait(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(Ok(load)) = &mut self.load { + load.wait(); + } + } + + /// Drops the modules not installed yet, leaving it [`FolderPending::done`]; [`end_folder`] + /// then keeps no report as the folder last loaded. + pub(crate) fn cancel(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(Ok(load)) = &mut self.load { + load.cancel(); + } + self.canceled = true; + } + + /// Whether it is a load of `folder` with the plug-in store `store`. + pub(crate) fn loads(&self, folder: &str, store: &Option) -> bool { + self.folder == folder && self.store == *store } } +impl Drop for FolderPending { + /// A load dropped before it ended (its session closed) leaves no folder reported as loading, so + /// the next session that applies the preference loads it. + fn drop(&mut self) { + if let Some(token) = self.record.filter(|_| self.load.is_some()) { + let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + if last.as_ref().is_some_and(|(_, _, _, t)| *t == token) { + *last = None; + } + } + } +} + +/// Starts loading the plug-ins in `folder` on worker threads ([`registry::FolderLoad`]); `record`: +/// the load's number in [`FOLDER`], whose record [`end_folder`] replaces with the report. +#[cfg(not(target_arch = "wasm32"))] +fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending { + let pending = |load| FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, load: Some(load), canceled: false }; + if let Err(e) = crate::file_access::check_read(folder) { + return pending(Err(json!({"folder": folder, "error": e}))); + } + // A file in it may be a link to one elsewhere. Each file is checked again on its worker + // thread, in the scope in force here (the automation roots and the script gate). + let scope = crate::file_access::ScopeHandle::capture(); + let allow = move |f: &std::path::Path| { + scope.clone().run(|| match f.to_str() { + Some(f) => crate::file_access::check_read(f), + // A lossy name would check another file than the one loaded. + None if crate::file_access::current().is_none() => Ok(()), + None => Err(format!("automation path rejected: {} isn't valid text", f.display())), + }) + }; + // The modules start loading once the loads queued before them are done. + pending(registry::FolderLoad::list(std::path::Path::new(folder), allow).map_err(|e| json!({"folder": folder, "error": e.to_string()}))) +} + #[cfg(target_arch = "wasm32")] -fn load_folder(_: &Session, folder: &str) -> Value { - json!({"folder": folder, "error": "plug-in folders are not available on the web"}) +fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending { + let load = Err(json!({"folder": folder, "error": "plug-in folders are not available on the web"})); + FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, load: Some(load), canceled: false } +} + +/// Installs what `load` has loaded so far, in file-name order up to the first module still +/// loading, without waiting: those that list permissions only when `s` has them granted +/// ([`Session::plugin_approved`], with the store's grants read once). Runs while +/// [`hold_plugin_changes`] and `turn` are held, so a `plugin.install` in another session or process +/// finishes writing the store first; when the store can't be locked, the folder still installs, +/// and the store isn't written. +pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &StoreTurn) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(Ok(load)) = &mut load.load + && !load.done() + { + for id in load.install_ready(s.plugin_folder_approver()) { + s.attach_plugin_storage(turn, &id); + } + } + #[cfg(target_arch = "wasm32")] + let _ = (s, load, turn); +} + +/// Ends `load` once [`FolderPending::done`], while [`hold_plugin_changes`] and `turn` are held, so +/// the grants of ids whose module lists no permissions are forgotten while no `plugin.install` can +/// record one for another module → its report; saves the disabled list when loading changed it. +pub(crate) fn end_folder(s: &mut Session, mut load: FolderPending, turn: &StoreTurn) -> Value { + let report = match load.load.take() { + #[cfg(not(target_arch = "wasm32"))] + Some(Ok(modules)) => { + let r = modules.finish(); + if r.disabled_changed { + s.store_disabled_plugins_in(turn); + } + json!({"folder": load.folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::>(), "leftOut": r.left_out}) + } + #[cfg(target_arch = "wasm32")] + Some(Ok(never)) => match never {}, + Some(Err(report)) => report, + None => Value::Null, + }; + if let Some(token) = load.record { + let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + // A later load, or a `plugin.reload`, replaced it meanwhile. A canceled load leaves no + // folder reported, so the next session that applies the preference loads it. + if last.as_ref().is_some_and(|(_, _, _, t)| *t == token) { + *last = if load.canceled { None } else { Some((load.folder.clone(), load.store.clone(), report.clone(), token)) }; + } + } + report +} + +/// Loads the plug-ins in `folder` and installs them, waiting for every module → the report. +fn load_folder_now(s: &mut Session, folder: &str) -> Value { + let load = start_folder(s, folder, None); + s.finish_plugin_load(PluginLoad::Folder(load)) } fn reload(s: &mut Session, p: &Value) -> Result { @@ -1064,11 +1263,13 @@ fn reload(s: &mut Session, p: &Value) -> Result { if folder.is_empty() { return Err(bad(C, "no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder")); } - let report = load_folder(s, &folder); + // Loads started earlier install first, so this one's plug-ins replace theirs. + s.finish_plugin_loads(); + let report = load_folder_now(s, &folder); if let Some(e) = report.get("error").and_then(Value::as_str) { return Err(EngineError::Other(e.to_string())); } - *FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = Some((folder, s.plugin_dir.clone(), report.clone())); + *FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = Some((folder, s.plugin_dir.clone(), report.clone(), 0)); Ok(report) } @@ -1117,7 +1318,7 @@ fn shown_report(mut report: Value) -> Value { } fn list(_: &mut Session, _: &Value) -> Result { - let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| shown_report(r.clone())); + let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r, _)| shown_report(r.clone())); let disabled: Vec = safe_mode::disabled().iter().map(shown_item).collect(); Ok( json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}), @@ -1125,13 +1326,15 @@ fn list(_: &mut Session, _: &Value) -> Result { } /// `plugin.safeMode`: whether Safe Mode is on and why, the plug-ins disabled for the next launch, -/// and the plug-in the last launch was loading when it stopped while the user hasn't chosen yet. +/// and the plug-ins the last launch was loading when it stopped while the user hasn't chosen yet. fn safe_mode_state(_: &mut Session, _: &Value) -> Result { + let pending: Vec = safe_mode::previous().iter().map(shown_item).collect(); Ok(json!({ "active": safe_mode::active(), "source": safe_mode::source().map(safe_mode::Source::name), "disabled": safe_mode::disabled().iter().map(shown_item).collect::>(), - "pendingItem": safe_mode::previous().map(|i| shown_item(&i)), + "pendingItem": pending.first(), + "pendingItems": pending, })) } @@ -1342,7 +1545,7 @@ pub fn specs() -> Vec { "Safe Mode", [], None, - "{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command", + "{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the first of pendingItems), pendingItems: [{id, file, name, label}] (the plug-ins the last launch was loading when it stopped, oldest first, until the user chooses; any of them, or none, may be what stopped it)}. Safe Mode is chosen at launch, never by a command", always, safe_mode_state ), diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 69194eba00..1346dc40c5 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -125,6 +125,14 @@ pub fn waits_for_tool_edit(id: &str) -> bool { find_command(id).is_some_and(|spec| spec.journal || WAIT_FOR_TOOL_EDIT.contains(&id)) } +/// Does command `id` first install the plug-ins still loading on other threads +/// ([`crate::Session::finish_plugin_loads`])? Plug-in commands do, a plug-in's own commands +/// included, and so does every command that waits for a tool edit ([`waits_for_tool_edit`]); +/// queries that only read, and view commands, go ahead while the plug-ins load. +pub fn waits_for_plugin_loads(id: &str) -> bool { + id.starts_with(vectorcraft_plugins::PREFIX) || waits_for_tool_edit(id) +} + /// Journaled commands that write a file and change nothing in the document: with an object of a /// dynamic symbol instance's art selected, they read the instance as queries do /// ([`crate::Session::execute`]). diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..31baf206fe 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -226,15 +226,26 @@ fn with_gate_reads_exempt(exempt: bool, f: impl FnOnce() -> T) -> T { f() } +/// `scope`, or for a thread without one, the `process` roots in force now (none: unconfined). +fn resolved(scope: Option, process: Option<&Arc>) -> Scope { + scope.unwrap_or_else(|| match process { + Some(r) => Scope::Confined(r.clone()), + None => Scope::Unconfined, + }) +} + /// This thread's scope, with the gate of the script command it runs, to carry to work it hands to /// another thread ([`ScopeHandle::run`]). #[derive(Clone, Debug)] pub struct ScopeHandle(Option, Option>, bool); impl ScopeHandle { - /// The scope of the calling thread. + /// The scope of the calling thread. A thread with no scope of its own takes the process's + /// roots as they are now ([`confine_process`]), so work captured before the process is confined + /// stays unconfined on the thread that runs it. pub fn capture() -> Self { - Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) + let scope = resolved(SCOPE.with(|s| s.borrow().clone()), PROCESS.get()); + Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) } /// Run `f` in the captured scope. @@ -1156,6 +1167,26 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A scope captured on a thread without one keeps the process's roots as they were then: work + /// captured before the process was confined stays unconfined, and work captured after is + /// confined. + #[test] + fn a_captured_scope_keeps_the_process_roots_of_its_time() { + let (base, roots) = folders("captured"); + let outside = s(base.join("outside/secret.svg")); + let before = ScopeHandle(Some(resolved(None, None)), None, false); + let after = ScopeHandle(Some(resolved(None, Some(&roots))), None, false); + confine(Some(&roots), || { + assert_eq!(before.run(|| check_read(&outside)), Ok(()), "captured before the roots were in force"); + }); + assert!(after.run(|| check_read(&outside)).is_err(), "captured while the roots were in force"); + // No test confines the process, so a thread without a scope captures an unconfined one, + // which roots put in force later don't narrow. + let captured = std::thread::spawn(ScopeHandle::capture).join().unwrap(); + assert!(matches!(captured.0, Some(Scope::Unconfined)), "{captured:?}"); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn device_names() { for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL ", "COM¹", "Lpt²", "lpt³.txt"] { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..65c2e02e37 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -189,6 +189,11 @@ pub struct Session { /// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process /// ([`Session::attach_plugin_store`]). plugin_dir: Option, + /// Plug-in loads running on worker threads, oldest first ([`Session::poll_plugin_loads`]). + plugin_loads: std::collections::VecDeque, + /// Whether the loads of the stored plug-ins and of the plug-ins folder go on after the call + /// that starts them ([`Session::load_plugins_in_background`]). + plugin_loads_in_background: bool, /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option, @@ -431,7 +436,7 @@ mod session; pub(crate) use command_sets::SELECTS_GIVEN_IDS; #[cfg(test)] use command_sets::given_ids; -pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit}; +pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit}; pub use doc_state::{DocState, OpenRows, RecalledSelection}; pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY}; #[cfg(test)] diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..4caf28f40c 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -99,6 +99,8 @@ impl Session { profile_dir: None, color_settings_file: None, plugin_dir: None, + plugin_loads: Default::default(), + plugin_loads_in_background: false, scripts_dir: None, metadata_templates_dir: None, new_doc_profile_dir: None, diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..ec43871b0a 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -59,6 +59,13 @@ impl Session { /// Execute a command by id. This is THE entry point for every frontend. pub fn execute(&mut self, id: &str, params: &Value) -> Result { + // Plug-ins still loading on other threads ([`Session::load_plugins_in_background`]) are + // installed before a plug-in command, its own commands included, and before a command that + // may edit, as they would have been before the window showed; a step of a batch waits for + // the plug-ins an earlier step started loading. + if self.plugins_loading() && crate::waits_for_plugin_loads(id) { + self.finish_plugin_loads(); + } let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?; // A clipboard import is a query that replaces the clipboard, which the end of a run sets too. if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 9c555d82f7..aafe8ae1bc 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -35,14 +35,16 @@ //! The files are untrusted input like any other: sizes and counts are capped, a file that does not //! parse is skipped with a log record, and every write is atomic. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::io::Read; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::SystemTime; +use serde_json::Value; use vectorcraft_pdf::{PdfPreset, builtin_preset}; +use vectorcraft_plugins::loader::{Job, Loads}; use vectorcraft_plugins::permissions::GrantToken; use vectorcraft_plugins::safe_mode; use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError}; @@ -187,6 +189,123 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result> { Ok(bytes) } +/// Plug-ins loading on worker threads, which [`Session::poll_plugin_loads`] and +/// [`Session::finish_plugin_loads`] install. +pub(crate) enum PluginLoad { + /// The plug-in store's ([`Session::load_stored_plugins`]). + Stored(StoredLoad), + /// The Additional Plug-ins Folder's ([`crate::cmd::plugin::sync_prefs`]). + Folder(crate::cmd::plugin::FolderPending), +} + +impl PluginLoad { + /// Starts the modules loading, unless they started already. + fn start(&mut self) { + match self { + PluginLoad::Stored(load) => load.loads.begin(), + PluginLoad::Folder(load) => load.start(), + } + } + + /// The installs and removals it checks its modules against (`None`: a folder that couldn't be + /// listed, or one ended already). + fn changes(&self) -> Option<&vectorcraft_plugins::registry::LoadChanges> { + match self { + PluginLoad::Stored(load) => Some(&load.changes), + PluginLoad::Folder(load) => load.changes(), + } + } + + /// [`PluginLoad::changes`], to adopt an earlier load's. + fn changes_mut(&mut self) -> Option<&mut vectorcraft_plugins::registry::LoadChanges> { + match self { + PluginLoad::Stored(load) => Some(&mut load.changes), + PluginLoad::Folder(load) => load.changes_mut(), + } + } + + /// Whether every module has been installed or skipped. + fn done(&self) -> bool { + match self { + PluginLoad::Stored(load) => load.next == load.files.len(), + PluginLoad::Folder(load) => load.done(), + } + } + + /// Whether something can be installed or ended now, without waiting. + fn ready(&mut self) -> bool { + match self { + PluginLoad::Stored(load) => load.next == load.files.len() || !load.loaded.is_empty() || load.loads.next_ready(), + PluginLoad::Folder(load) => load.ready(), + } + } + + /// Waits until [`PluginLoad::ready`], starting the modules loading first ([`PluginLoad::start`]). + fn wait(&mut self) { + self.start(); + match self { + PluginLoad::Stored(load) if load.loaded.is_empty() && load.next < load.files.len() => load.loads.wait_next(), + PluginLoad::Stored(_) => {} + PluginLoad::Folder(load) => load.wait(), + } + } + + /// Drops the modules not installed yet ([`Session::cancel_plugin_loads`]), leaving it + /// [`PluginLoad::done`] with what it installed. + fn cancel(&mut self) { + match self { + PluginLoad::Stored(load) => { + load.loads = Loads::deferred(Vec::new()); + load.loaded.clear(); + load.next = load.files.len(); + } + PluginLoad::Folder(load) => load.cancel(), + } + } + + /// Whether installing it takes the plug-in store's own turn, making the store folder (a + /// folder's plug-ins keep their settings and cache there), rather than one that goes ahead + /// without a store folder. + fn creates_store(&self) -> bool { + matches!(self, PluginLoad::Folder(_)) + } +} + +/// The stored plug-ins loading from the plug-in store `dir`. +pub(crate) struct StoredLoad { + dir: PathBuf, + /// Each file, with its stamp when it was listed ([`file_stamp`]; `None`: it couldn't be read). + files: Vec<(PathBuf, Option)>, + loads: Loads, + /// Outcomes taken from `loads` and not installed yet, in order. + loaded: VecDeque>, + /// The next file to install. + next: usize, + /// The store's grants this load removed, by id, because the module stored for the id lists no + /// permissions: a later file holding a module with that id that the grant covers still loads, + /// and the grant goes back to the store. + retired: BTreeMap, + /// Installs and removals elsewhere since the store was listed, which a module loaded before + /// them doesn't undo. + changes: vectorcraft_plugins::registry::LoadChanges, +} + +/// Tests: what runs before a stored module is read, given its path. +#[cfg(test)] +type StoredHook = Arc; + +/// Tests: runs on the worker thread before the stored module at the path it is given is read. +#[cfg(test)] +pub(crate) static BEFORE_STORED_LOAD: Mutex> = Mutex::new(None); + +#[cfg(test)] +fn before_stored_load(path: &Path) { + let hook = BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(hook) = hook { + hook(path); + } +} + /// What a file over its cap is told (a detail after the file's name, in the log or an error). fn too_large(max: u64) -> String { format!("larger than {max} bytes") @@ -230,8 +349,7 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> { /// replaced or removed, so that every window locks the same file. #[cfg(not(target_arch = "wasm32"))] fn lock_store(dir: &Path) -> std::io::Result { - std::fs::create_dir_all(dir)?; - let file = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))?; + let file = open_store_lock(dir)?; match file.try_lock() { Ok(()) => return Ok(file), Err(std::fs::TryLockError::WouldBlock) => {} @@ -245,6 +363,30 @@ fn lock_store(dir: &Path) -> std::io::Result { Ok(file) } +/// [`DISABLED_LOCK`] in `dir`, opened (and made, with the folder) but not locked. +#[cfg(not(target_arch = "wasm32"))] +fn open_store_lock(dir: &Path) -> std::io::Result { + std::fs::create_dir_all(dir)?; + std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK)) +} + +/// [`lock_store`] without waiting: `None` while another window or process holds the lock. +#[cfg(not(target_arch = "wasm32"))] +fn try_lock_store(dir: &Path) -> std::io::Result> { + let file = open_store_lock(dir)?; + match file.try_lock() { + Ok(()) => Ok(Some(file)), + Err(std::fs::TryLockError::WouldBlock) => Ok(None), + Err(std::fs::TryLockError::Error(e)) => Err(e), + } +} + +/// The browser has no folders to keep anything in. +#[cfg(target_arch = "wasm32")] +fn try_lock_store(_: &Path) -> std::io::Result> { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) +} + /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] fn lock_store(_: &Path) -> std::io::Result { @@ -445,48 +587,50 @@ impl Session { } /// Keep the plug-ins this session installs in `dir`, take the disabled plug-ins saved there - /// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]). + /// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]). Loads + /// still running from an earlier call are finished first. pub fn attach_plugin_store(&mut self, dir: PathBuf) { - let path = dir.join(DISABLED_FILE); + self.finish_plugin_loads(); self.plugin_dir = Some(dir); - // A `plugin.install` in another session or process writes the store before this reads it. - let _held = crate::cmd::plugin::hold_plugin_changes(); - let turn = self.plugin_store_turn_for_load(); - let disabled = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default(); - safe_mode::set_disabled(disabled); - self.load_stored_plugins_in(&turn); + self.start_stored_plugins(true); } /// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user - /// disabled (matched by file name, which is made from the id). The launch marker names each - /// file while it loads. A module that doesn't load, and one that lists permissions the grants - /// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and - /// stays in the folder with its grant. A grant for an id whose stored module lists no - /// permissions is forgotten; one that can't be removed from the grants file doesn't count for - /// any session in the process attached to the folder until the file can be written for the id - /// ([`Session::ignore_stored_grant`]). The folder is read and changed in one turn on it - /// ([`Session::plugin_store_turn_for_load`]). + /// disabled (matched by file name, which is made from the id). The modules load on worker + /// threads ([`vectorcraft_plugins::loader`]) and install in file-name order, whatever order + /// their loads finish in; the launch marker names each file while it loads. A module that + /// doesn't load (its load panicked or didn't finish in time included), one that changed or + /// went away while it loaded, and one that lists permissions the grants there don't grant that + /// very module ([`grant_covers`]), is skipped with a log record, and stays in the folder with + /// its grant. A grant for an id whose stored module lists no permissions is forgotten; one that + /// can't be removed from the grants file doesn't count for any session in the process attached + /// to the folder until the file can be written for the id ([`Session::ignore_stored_grant`]). + /// The folder is listed, and what loaded is installed and the folder changed, in turns on it + /// ([`Session::plugin_store_turn_for_load`]); the modules load between them. With + /// [`Session::load_plugins_in_background`] on, this returns while the modules load. pub fn load_stored_plugins(&mut self) { - if self.plugin_dir.is_none() || safe_mode::active() { - return; - } - // A `plugin.install` in another session or process writes the store before this reads it. - let _held = crate::cmd::plugin::hold_plugin_changes(); - let turn = self.plugin_store_turn_for_load(); - self.load_stored_plugins_in(&turn); + self.start_stored_plugins(false); } - /// [`Session::load_stored_plugins`] in `turn`, while [`crate::cmd::plugin::hold_plugin_changes`] - /// is held. - fn load_stored_plugins_in(&mut self, turn: &StoreTurn) { + /// [`Session::load_stored_plugins`]; `disabled`: first take the disabled plug-ins saved in the + /// folder ([`DISABLED_FILE`]). + fn start_stored_plugins(&mut self, disabled: bool) { let Some(dir) = self.plugin_dir.clone() else { return }; + // A `plugin.install` in another session or process writes the store before this lists it. + let held = crate::cmd::plugin::hold_plugin_changes(); + let turn = self.plugin_store_turn_for_load(); + if disabled { + let path = dir.join(DISABLED_FILE); + let saved = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default(); + safe_mode::set_disabled(saved); + } if safe_mode::active() { return; } - let grants = self.counted_grants(&dir); let limits = vectorcraft_plugins::Limits::default(); let mut left = MAX_PLUGIN_STORE; - let mut asks_nothing = BTreeSet::new(); + let mut files = Vec::new(); + let mut jobs = Vec::new(); for path in list_files(&dir, PLUGIN_EXT) { if left == 0 { log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together"); @@ -499,24 +643,96 @@ impl Session { log::info!("skipping the stored plug-in {}: disabled", path.display()); continue; } - let token = safe_mode::loading(&item); - let loaded = read_capped(&path, (limits.max_module_bytes as u64).min(left)).and_then(|bytes| { - left -= bytes.len() as u64; - vectorcraft_plugins::Plugin::load(&bytes, limits.clone()).map_err(|e| e.to_string()) - }); - safe_mode::loaded(token); + // Each file takes its listed length from what the files before it left of the total, + // and its load reads no more than that. + let cap = (limits.max_module_bytes as u64).min(left); + let stamp = file_stamp(&path); + let len = match &stamp { + Ok(Some((len, _))) if *len <= cap => *len, + Ok(Some(_)) => { + log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(cap)); + continue; + } + Ok(None) => continue, + Err(e) => { + log::warn!("skipping the stored plug-in {}: {e}", path.display()); + continue; + } + }; + // A file this process may not read takes nothing from the total, as one that couldn't + // be read didn't when the files were read one after the other. + #[cfg(not(target_arch = "wasm32"))] + if let Err(e) = vectorcraft_plugins::registry::may_read(&path) { + log::warn!("skipping the stored plug-in {}: {e}", path.display()); + continue; + } + left -= len; + let (read, limits) = (path.clone(), limits.clone()); + jobs.push(Job::new(Some(item), move || { + #[cfg(test)] + before_stored_load(&read); + let bytes = read_capped(&read, len).map_err(vectorcraft_plugins::Error::Io)?; + vectorcraft_plugins::Plugin::load(&bytes, limits) + })); + files.push((path, stamp.ok())); + } + // A change made after the listing, while `held` no longer stops one, is made elsewhere. + let mut changes = vectorcraft_plugins::registry::LoadChanges::default(); + changes.start(); + // The modules load after the turn, once the loads queued before them are done. + drop((turn, held)); + let load = StoredLoad { dir, files, loads: Loads::deferred(jobs), loaded: VecDeque::new(), next: 0, retired: BTreeMap::new(), changes }; + self.queue_plugin_load(PluginLoad::Stored(load)); + } + + /// Installs what the stored plug-ins' `load` has loaded so far, in file-name order up to the + /// first module still loading, without waiting ([`Session::load_stored_plugins`]), while + /// [`crate::cmd::plugin::hold_plugin_changes`] and `turn` are held. + fn install_stored_plugins(&mut self, load: &mut StoredLoad, turn: &StoreTurn) { + load.loaded.extend(load.loads.ready()); + if load.loaded.is_empty() { + return; + } + let dir = load.dir.clone(); + let mut grants = self.counted_grants(&dir); + while let (Some(loaded), Some((path, stamp))) = (load.loaded.pop_front(), load.files.get(load.next)) { + load.next += 1; + load.loads.release(1); + if file_stamp(path).ok() != *stamp { + log::warn!("skipping the stored plug-in {}: it changed or went away while it loaded", path.display()); + continue; + } match loaded { + // A file replaced by one of the same length within the clock's resolution keeps its + // stamp: its content is compared too. + Ok(plugin) if !holds_module(path, stamp.flatten().map_or(0, |(len, _)| len), plugin.hash()) => { + log::warn!("skipping the stored plug-in {}: it changed or went away while it loaded", path.display()); + } + Ok(plugin) if load.changes.superseded(plugin.id()) => { + log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED); + } // Only this store's grants count: one given elsewhere in the process doesn't let a // module stored here load. Ok(plugin) if plugin.manifest().asks_permissions() => { let m = plugin.manifest(); - match grants.get(&m.id).filter(|g| grant_covers(g, &plugin)) { + let stored = grants.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned(); + let back = stored.is_none().then(|| load.retired.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned()).flatten(); + match stored.or(back.clone()) { Some(g) => { - asks_nothing.remove(&m.id); + // A grant this load removed for an earlier file with the id goes back. + if back.is_some() { + load.retired.remove(&m.id); + if self.store_grant_in(turn, &m.id, Some(g.clone())) { + grants.insert(m.id.clone(), g.clone()); + } else { + log::warn!("couldn't put back the grant for the stored plug-in {}", path.display()); + } + } vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone())); vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id, turn)); - if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); + match vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) { + Ok(p) => load.changes.installed(&p), + Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()), } } None => { @@ -525,29 +741,178 @@ impl Session { } } Ok(plugin) => { - asks_nothing.insert(plugin.id().to_string()); - vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id(), turn)); - if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); + let id = plugin.id().to_string(); + vectorcraft_plugins::registry::set_storage(&id, plugin_storage(Some(&dir), &id, turn)); + match vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) { + Ok(p) => load.changes.installed(&p), + Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()), + } + // In the same turn: the grants for the id stop counting, the process's and the + // store's, so no session sees the earlier module as approved. + vectorcraft_plugins::registry::revoke(&id); + if let Some(g) = grants.remove(&id) { + load.retired.insert(id.clone(), g); + } + if self.holds_plugin_grant(&id) { + let writes = self.grant_writes(); + if !self.store_grant_in(turn, &id, None) && self.holds_plugin_grant(&id) { + self.ignore_stored_grant(&id, writes); + } } } Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()), } } - let kept = read_grants(&dir); - for id in &asks_nothing { - vectorcraft_plugins::registry::revoke(id); - let named = match &kept { - Ok(file) => file.names(id), - Err(e) => e.unread, + } + + /// Whether the loads of the stored plug-ins and of the Additional Plug-ins Folder go on after + /// the call that starts them ([`Session::attach_plugin_store`], [`Session::load_stored_plugins`], + /// preferences that set the folder): the app turns it on for its launch so that its window + /// shows while they load, installs what loaded with [`Session::poll_plugin_loads`] as its + /// frames go by, and turns it off once the launch's loads have started. Off (the default), + /// those calls return once what loaded is installed, the loads still running from before + /// included. + pub fn load_plugins_in_background(&mut self, on: bool) { + self.plugin_loads_in_background = on; + } + + /// Installs what the plug-in loads have loaded so far, in the order the loads started and each + /// load's file-name order, up to the first module still loading, without waiting → whether + /// some are still loading. A load starts once the loads before it are done. When another + /// session or process is changing the plug-ins or the store, nothing installs until a later + /// call. + pub fn poll_plugin_loads(&mut self) -> bool { + while let Some(mut next) = self.plugin_loads.pop_front() { + next.start(); + if !next.ready() { + self.plugin_loads.push_front(next); + return true; + } + let Some((held, turn)) = self.plugin_install_turn_now(next.creates_store()) else { + self.plugin_loads.push_front(next); + return true; }; - if named { - let writes = self.grant_writes(); - if !self.store_grant_in(turn, id, None) && self.holds_plugin_grant(id) { - self.ignore_stored_grant(id, writes); + self.install_plugin_load(&mut next, &turn); + if !next.done() { + self.plugin_loads.push_front(next); + return true; + } + self.end_plugin_load(next, &turn); + drop((turn, held)); + } + false + } + + /// Waits for every plug-in load still running and installs what they loaded, in the order the + /// loads started. Plug-in commands, and commands that may edit, call it first + /// ([`Session::execute`]). + pub fn finish_plugin_loads(&mut self) { + while let Some(next) = self.plugin_loads.pop_front() { + self.finish_plugin_load(next); + } + } + + /// Ends the plug-in loads still running without installing more of what they load: the app + /// calls it as it quits. Modules not started are dropped, and the ones running are given until + /// their deadline, so the launch marker is not left naming a plug-in that was loading. Each load + /// then ends as one that finished does for what it installed, in turns on the store: the grant + /// for an id whose installed module lists no permissions is forgotten. + pub fn cancel_plugin_loads(&mut self) { + while let Some(mut load) = self.plugin_loads.pop_front() { + load.cancel(); + let held = crate::cmd::plugin::hold_plugin_changes(); + let turn = self.plugin_install_turn(load.creates_store()); + self.end_plugin_load(load, &turn); + drop((turn, held)); + } + } + + /// Waits for `load`'s modules and installs them as they load, in turns on the store, then + /// ends it → its report (a folder's; `null` for the stored plug-ins). + pub(crate) fn finish_plugin_load(&mut self, mut load: PluginLoad) -> Value { + load.start(); + loop { + load.wait(); + let held = crate::cmd::plugin::hold_plugin_changes(); + let turn = self.plugin_install_turn(load.creates_store()); + self.install_plugin_load(&mut load, &turn); + if load.done() { + let report = self.end_plugin_load(load, &turn); + drop((turn, held)); + return report; + } + } + } + + /// A turn on the store for installing what a load loaded, taken after + /// [`crate::cmd::plugin::hold_plugin_changes`]: the folder's own turn + /// ([`Session::plugin_store_turn`]) when `create`, else one that goes ahead without a store + /// folder ([`Session::plugin_store_turn_for_load`]). One that can't be locked goes ahead + /// unheld. + fn plugin_install_turn(&self, create: bool) -> StoreTurn { + if create { self.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld()) } else { self.plugin_store_turn_for_load() } + } + + /// [`crate::cmd::plugin::hold_plugin_changes`] and [`Session::plugin_install_turn`] without + /// waiting: `None` while another session holds the one or another window or process the other. + fn plugin_install_turn_now(&self, create: bool) -> Option<(MutexGuard<'static, ()>, StoreTurn)> { + let held = crate::cmd::plugin::try_hold_plugin_changes()?; + let turn = match self.plugin_dir.as_deref() { + Some(dir) if create || dir.is_dir() => match try_lock_store(dir) { + Ok(Some(file)) => StoreTurn { lock: Some(file) }, + Ok(None) => return None, + Err(e) => { + log::warn!("can't lock {}: {e}", dir.join(DISABLED_LOCK).display()); + StoreTurn::unheld() + } + }, + _ => StoreTurn::unheld(), + }; + Some((held, turn)) + } + + /// Whether plug-ins are still loading on worker threads ([`Session::load_plugins_in_background`]). + pub fn plugins_loading(&self) -> bool { + !self.plugin_loads.is_empty() + } + + /// Keeps `load` to install after the loads started before it; without + /// [`Session::load_plugins_in_background`], waits for them all and installs what they loaded. + pub(crate) fn queue_plugin_load(&mut self, load: PluginLoad) { + self.plugin_loads.push_back(load); + // The first load starts now; one queued after it starts once those before it are done. + if let [only] = self.plugin_loads.make_contiguous() { + only.start(); + } + if !self.plugin_loads_in_background { + self.finish_plugin_loads(); + } + } + + /// Installs what `load` has loaded so far, without waiting, in `turn`. + fn install_plugin_load(&mut self, load: &mut PluginLoad, turn: &StoreTurn) { + match load { + PluginLoad::Stored(load) => self.install_stored_plugins(load, turn), + PluginLoad::Folder(load) => crate::cmd::plugin::install_folder(self, load, turn), + } + } + + /// Ends `load` once [`PluginLoad::done`], in `turn` → its report (a folder's). + fn end_plugin_load(&mut self, load: PluginLoad, turn: &StoreTurn) -> Value { + // The loads queued after it count what it installed as their own: one of theirs replaces + // it, as it would have with the loads run one after the other. + if let Some(ended) = load.changes() { + for later in &mut self.plugin_loads { + if let Some(changes) = later.changes_mut() { + changes.adopt(ended); } } } + match load { + // A stored load's grants were settled as each module installed. + PluginLoad::Stored(_) => Value::Null, + PluginLoad::Folder(load) => crate::cmd::plugin::end_folder(self, load, turn), + } } /// Take a turn on the attached plug-in store ([`StoreTurn`]), waiting while another window or @@ -1070,6 +1435,12 @@ fn plugin_storage(dir: Option<&Path>, id: &str, turn: &StoreTurn) -> Option; +/// Does the file at `path` hold, in its first `len` bytes and no more, the module whose SHA-256 is +/// `hash`? +fn holds_module(path: &Path, len: u64, hash: &str) -> bool { + read_capped(path, len).is_ok_and(|bytes| vectorcraft_plugins::permissions::sha256_hex(&bytes) == hash) +} + /// The stamp of the file at `path`. fn file_stamp(path: &Path) -> Result { match std::fs::metadata(path) { diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..a8368dc7c2 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -1986,6 +1986,289 @@ fn installed_plugins_are_kept_in_the_store() { assert!(vectorcraft_plugins::registry::get(id).is_none()); } +/// Held by the tests that set [`crate::store::BEFORE_STORED_LOAD`]. +static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// A stored module's load waits on its worker thread until the test lets it go +/// ([`crate::store::BEFORE_STORED_LOAD`]). The hook is cleared when this is dropped. +struct HeldLoad { + _lock: std::sync::MutexGuard<'static, ()>, + entered: std::sync::Arc, + go: std::sync::Arc, + gave_up: std::sync::Arc, +} + +impl HeldLoad { + /// Holds the load of the file at `path`. A load the test never lets go gives up after a + /// million yields (so a test of code that waits for it ends) and says so in `gave_up`. + fn new(path: std::path::PathBuf) -> HeldLoad { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()); + let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false))); + let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone()); + *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| { + if p != path { + return; + } + e.store(true, Ordering::SeqCst); + if !(0..1_000_000).any(|_| { + std::thread::yield_now(); + g.load(Ordering::SeqCst) + }) { + q.store(true, Ordering::SeqCst); + } + })); + HeldLoad { _lock: lock, entered, go, gave_up } + } + + fn entered(&self) -> bool { + self.entered.load(std::sync::atomic::Ordering::SeqCst) + } + + fn release(&self) { + self.go.store(true, std::sync::atomic::Ordering::SeqCst); + } + + fn gave_up(&self) -> bool { + self.gave_up.load(std::sync::atomic::Ordering::SeqCst) + } +} + +impl Drop for HeldLoad { + fn drop(&mut self) { + self.release(); + *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None; + } +} + +/// A store holding the module of a filter `id` in `.wasm`. +fn store_with(name: &str, id: &str) -> (crate::tests_links::Folder, std::path::PathBuf) { + let folder = crate::tests_links::Folder::new(name); + let path = folder.0.join(format!("{id}.wasm")); + std::fs::create_dir_all(&folder.0).unwrap(); + std::fs::write(&path, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + (folder, path) +} + +/// With loads in the background, attaching a plug-in store returns while a stored module is +/// still loading: the plug-in installs once its load is done, at the next plug-in command. +#[test] +fn a_store_attached_with_background_loads_returns_before_its_plugins_load() { + let id = "test.engine.background"; + let (folder, path) = store_with("plugin-background", id); + let held = HeldLoad::new(path); + let mut s = session(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + let returned_while_loading = !held.gave_up(); + while !held.entered() { + std::thread::yield_now(); + } + assert!(returned_while_loading, "attaching the store waited for the module to load"); + assert!(vectorcraft_plugins::registry::get(id).is_none(), "nothing installs before its load is done"); + assert!(s.poll_plugin_loads(), "still loading"); + held.release(); + let listed = run(&mut s, "plugin.list", json!({})); + assert!(listed.to_string().contains(id), "plugin.list waits for the load and lists it: {listed}"); + assert!(!s.poll_plugin_loads()); + assert!(vectorcraft_plugins::registry::remove(id)); +} + +/// Stored files that can't be opened take nothing from the bytes the stored plug-ins may read +/// together: a module after 512 MiB of them still installs. +#[cfg(unix)] +#[test] +fn unreadable_stored_files_leave_the_store_budget_to_the_others() { + use std::os::unix::fs::PermissionsExt; + let id = "test.engine.budget.after"; + let (folder, _) = store_with("plugin-budget-unreadable", id); + let per_file = vectorcraft_plugins::Limits::default().max_module_bytes as u64; + let locked: Vec<_> = (0..crate::store::MAX_PLUGIN_STORE.div_ceil(per_file)) + .map(|n| { + // Sparse files sorted before the module, each as long as a module may be. + let path = folder.0.join(format!("a{n:03}.wasm")); + std::fs::File::create(&path).unwrap().set_len(per_file).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap(); + path + }) + .collect(); + // A process that may read any file (root) opens them all: nothing to check. + if std::fs::File::open(&locked[0]).is_ok() { + return; + } + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let installed = vectorcraft_plugins::registry::get(id).is_some(); + for path in &locked { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + assert!(installed, "the files that couldn't be opened used up the store's bytes"); + assert!(vectorcraft_plugins::registry::remove(id)); +} + +/// A folder listed while the stored plug-ins still load, in the same session, replaces a stored +/// plug-in with a module of the same id once it loads, as it does when the loads run one after the +/// other: what an earlier load of the session installed doesn't count as a change made elsewhere. +#[test] +fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.queued.same"; + let (store, stored) = store_with("plugin-queued-store", id); + let (folder, from_folder) = store_with("plugin-queued-folder", id); + let held = HeldLoad::new(stored); + let mut s = session(); + s.load_plugins_in_background(true); + s.attach_plugin_store(store.0.clone()); + while !held.entered() { + std::thread::yield_now(); + } + s.prefs.plugins_folder = folder.0.display().to_string(); + crate::cmd::plugin::sync_prefs(&mut s); + held.release(); + s.finish_plugin_loads(); + let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string)); + assert!(vectorcraft_plugins::registry::remove(id)); + assert_eq!(source.as_deref(), Some(from_folder.display().to_string().as_str()), "the folder's module replaces the stored one"); +} + +/// A query that only reads runs while the stored plug-ins load in the background, and doesn't +/// wait for them; a plug-in command does. +#[test] +fn a_query_runs_while_the_plugins_load() { + let id = "test.engine.background.query"; + let (folder, path) = store_with("plugin-background-query", id); + let held = HeldLoad::new(path); + let mut s = session(); + run(&mut s, "file.new", json!({})); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + while !held.entered() { + std::thread::yield_now(); + } + run(&mut s, "document.info", json!({})); + let waited = held.gave_up() || !s.plugins_loading(); + held.release(); + assert!(!waited, "document.info waited for the plug-ins to load"); + assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info")); + s.finish_plugin_loads(); + assert!(vectorcraft_plugins::registry::remove(id)); +} + +/// The stored plug-ins load without holding the lock that `plugin.install` and `plugin.remove` +/// take, so another session's plug-in changes don't wait for them. +#[test] +fn stored_plugins_load_without_holding_the_plugin_changes_lock() { + let id = "test.engine.unlocked"; + let (folder, path) = store_with("plugin-unlocked", id); + let held = HeldLoad::new(path); + let mut s = session(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + while !held.entered() && !held.gave_up() { + std::thread::yield_now(); + } + // Other tests take the lock for a moment; the load holding it would hold it throughout (a + // tenth of the yields the held load waits before it gives up). + let free = (0..100_000).any(|_| { + std::thread::yield_now(); + crate::cmd::plugin::plugin_changes_free() + }); + held.release(); + s.finish_plugin_loads(); + assert!(free, "the lock was held while the module loaded"); + assert!(vectorcraft_plugins::registry::remove(id)); +} + +/// Loads canceled as the app quits still end for what they installed: a stored module listing no +/// permissions that installed before a later one finished loading has its id's grant forgotten, +/// in the process and in `grants.json`, and the module still loading doesn't install. +#[test] +fn canceled_loads_forget_the_grants_of_what_they_installed() { + use vectorcraft_plugins::permissions::sha256_hex; + let (first, later) = ("test.engine.cancel.a", "test.engine.cancel.b"); + let (folder, _) = store_with("plugin-cancel", first); + let held_path = folder.0.join(format!("{later}.wasm")); + std::fs::write(&held_path, wat::parse_str(tpl::returning(&tpl::manifest(later, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + let empty = json!({"objects": []}); + let approved = asking(first, r#"["doc.read"]"#, &empty); + let grants = folder.0.join("grants.json"); + let entry = json!([{"id": first, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]); + std::fs::write(&grants, serde_json::to_vec(&entry).unwrap()).unwrap(); + let held = HeldLoad::new(held_path); + let mut s = session(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + while vectorcraft_plugins::registry::get(first).is_none() && !held.gave_up() { + s.poll_plugin_loads(); + std::thread::yield_now(); + } + assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads"); + s.cancel_plugin_loads(); + // The file goes once it holds no grant. + let listed: Vec = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default(); + assert!(listed.iter().all(|e| e["id"] != first), "{listed:?}"); + assert!(vectorcraft_plugins::registry::granted(first).is_none()); + assert!(vectorcraft_plugins::registry::get(later).is_none(), "the module still loading doesn't install"); + assert!(!s.plugins_loading()); + drop(held); + assert!(vectorcraft_plugins::registry::remove(first)); +} + +/// The grants for a stored module that lists no permissions stop counting when it installs, in the +/// same turn, while a later module of the load is still loading. +#[test] +fn a_stored_module_without_permissions_ends_its_grant_when_it_installs() { + use vectorcraft_plugins::permissions::sha256_hex; + let (first, later) = ("test.engine.retire.a", "test.engine.retire.b"); + let (folder, _) = store_with("plugin-retire", first); + let held_path = folder.0.join(format!("{later}.wasm")); + std::fs::write(&held_path, wat::parse_str(tpl::returning(&tpl::manifest(later, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap(); + let empty = json!({"objects": []}); + let approved = asking(first, r#"["doc.read"]"#, &empty); + let grants = folder.0.join("grants.json"); + let entry = json!([{"id": first, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]); + std::fs::write(&grants, serde_json::to_vec(&entry).unwrap()).unwrap(); + let held = HeldLoad::new(held_path); + let mut s = session(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + while vectorcraft_plugins::registry::get(first).is_none() && !held.gave_up() { + s.poll_plugin_loads(); + std::thread::yield_now(); + } + assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads"); + assert!(s.plugins_loading(), "the second module is still loading"); + let listed: Vec = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default(); + assert!(listed.iter().all(|e| e["id"] != first), "{listed:?}"); + assert!(vectorcraft_plugins::registry::granted(first).is_none()); + drop(held); + s.finish_plugin_loads(); + assert!(vectorcraft_plugins::registry::remove(first)); + assert!(vectorcraft_plugins::registry::remove(later)); +} + +/// A session that waits for its loads and sets the plug-ins folder another session is still +/// loading in the background loads the folder itself: its plug-in is installed when `prefs.set` +/// returns, and the other session's load, when it installs, counts the same module as loaded. +#[test] +fn a_folder_another_session_is_loading_is_loaded_by_a_session_that_waits() { + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let id = "test.engine.sharedfolder"; + let (folder, _) = store_with("plugin-shared-folder", id); + let path = folder.0.display().to_string(); + let mut background = session(); + background.load_plugins_in_background(true); + run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": path}})); + assert!(background.plugins_loading(), "the folder loads in the background"); + let mut waits = session(); + run(&mut waits, "prefs.set", json!({"values": {"pluginsFolder": path}})); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "prefs.set returned before the folder's plug-in installed"); + let report = run(&mut background, "plugin.list", json!({})); + assert!(!background.plugins_loading()); + assert!(vectorcraft_plugins::registry::remove(id), "{report}"); +} + /// A heavy test filter `id` that counts `steps` down, then adds a triangle named "Plug-in". fn heavy(id: &str, steps: u64) -> Vec { let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","budget":"heavy"}}"#); diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index a469e68f20..32901ffb6a 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -90,7 +90,7 @@ fn a_disabled_plug_in_stays_installed_and_loads_again_once_enabled_at_the_next_l let list = s.execute("plugin.list", &json!({})).unwrap(); assert_eq!((list["safeMode"].clone(), list["disabled"][0]["id"].clone()), (json!(false), json!("test.sm.x"))); let state = s.execute("plugin.safeMode", &json!({})).unwrap(); - assert_eq!(state, json!({"active": false, "source": null, "pendingItem": null, "disabled": state["disabled"].clone()})); + assert_eq!(state, json!({"active": false, "source": null, "pendingItem": null, "pendingItems": [], "disabled": state["disabled"].clone()})); assert_eq!(state["disabled"].as_array().map(Vec::len), Some(1)); s.execute("plugin.setEnabled", &json!({"id": "test.sm.x", "enabled": true})).unwrap(); diff --git a/crates/plugins/src/effect.rs b/crates/plugins/src/effect.rs index 02b212cb23..1f478353fa 100644 --- a/crates/plugins/src/effect.rs +++ b/crates/plugins/src/effect.rs @@ -807,7 +807,7 @@ mod tests { crate::safe_mode::set_active(None); let dir = std::env::temp_dir().join(format!("vc-effect-overlap-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); - assert_eq!(crate::safe_mode::begin_launch(&dir), None); + assert_eq!(crate::safe_mode::begin_launch(&dir), []); let marker = || { let files = std::fs::read_dir(&dir).unwrap().filter_map(|e| Some(e.ok()?.path())); let json = files.filter(|p| p.extension().is_some_and(|x| x == "json")).collect::>(); @@ -816,8 +816,8 @@ mod tests { }; let src = crate::wat::returning(&crate::wat::manifest("test.effect.overlap", "effect", "{}"), r#"{"objects":[]}"#); let plugin = registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()).unwrap(); - let named = Some(crate::safe_mode::Item::of(&plugin)); - assert_eq!(marker(), None); + let named = vec![crate::safe_mode::Item::of(&plugin)]; + assert_eq!(marker(), []); assert!(begin_run(&plugin), "the first run is guarded"); assert!(begin_run(&plugin), "a run that starts while the first is running is guarded"); @@ -829,9 +829,9 @@ mod tests { end_run(plugin.serial(), true); assert_eq!(marker(), named, "the third run is still running"); end_run(plugin.serial(), false); - assert_eq!(marker(), None, "no run is running"); + assert_eq!(marker(), [], "no run is running"); assert!(!begin_run(&plugin), "later runs aren't guarded"); - assert_eq!(marker(), None); + assert_eq!(marker(), []); crate::safe_mode::end_launch(); crate::safe_mode::forget_previous(); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..8a0e089181 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -40,6 +40,7 @@ pub mod effect; pub mod export; pub mod host; pub mod import; +pub mod loader; pub mod manifest; pub mod objects; pub mod painted; diff --git a/crates/plugins/src/loader.rs b/crates/plugins/src/loader.rs new file mode 100644 index 0000000000..f38f00f07e --- /dev/null +++ b/crates/plugins/src/loader.rs @@ -0,0 +1,717 @@ +//! Loads plug-ins on worker threads. +//! +//! [`Loads::start`] hands its jobs to a pool of at most [`MAX_WORKERS`] threads and returns at +//! once. The web build has no threads, so there it runs the jobs one after the other before it +//! returns. Each job runs inside a panic boundary: a job that panics fails with [`Error::Failed`], +//! and the launch marker stops naming its item ([`crate::safe_mode::loading`]), as when it loads. +//! A job that takes [`LOAD_DEADLINE`] or longer fails too, and the marker names its item until its +//! thread returns; while it is still running, its thread is left to finish on its own, and another worker +//! takes the jobs after it, up to twice as many threads as were started. While +//! [`MAX_STUCK_THREADS`] threads in the process still run jobs past their deadline, no load starts +//! a thread. When no thread is left to take them, the jobs not started fail. +//! +//! The caller takes the outcomes in the order of the jobs, whatever order they finish in +//! ([`Loads::ready`]), so it installs them in the same order on every launch. A job starts only +//! while fewer than twice the workers' count of outcomes before it are waiting to be taken or are +//! still held by the caller ([`Loads::release`]), so the loaded modules held at once stay bounded +//! however many jobs there are. + +use std::collections::VecDeque; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard}; +use std::time::Duration; + +use web_time::Instant; + +use crate::safe_mode::{self, Item}; +use crate::{Error, Result}; + +/// The most worker threads one [`Loads`] starts, besides those that replace a worker whose job +/// passed [`LOAD_DEADLINE`]. +pub const MAX_WORKERS: usize = 4; + +/// How long one job may take; one that takes longer fails as not finished. +pub const LOAD_DEADLINE: Duration = Duration::from_secs(10); + +/// How often a wait looks at the deadlines while no job finishes. +const TICK: Duration = Duration::from_millis(50); + +/// The most loader threads in the process still running a job past its deadline. While that many +/// are, no [`Loads`] starts another thread, so loads started again and again on files whose reads +/// never return don't pile up threads. +pub const MAX_STUCK_THREADS: usize = 2 * MAX_WORKERS; + +/// Loader threads in the process running a job past its deadline, across every [`Loads`]. +static STUCK_THREADS: AtomicUsize = AtomicUsize::new(0); + +/// One plug-in to load: the item the launch marker names while it loads, and the work, which runs +/// on a worker thread. +pub struct Job { + pub item: Option, + pub work: Box Result + Send>, +} + +impl Job { + pub fn new(item: Option, work: impl FnOnce() -> Result + Send + 'static) -> Self { + Job { item, work: Box::new(work) } + } +} + +/// The time since a fixed start, for the deadlines. +type Clock = Arc Duration + Send + Sync>; + +/// A job's outcome as its worker sends it: the job, its result and how long it took. +type Done = (usize, Result, Duration); + +/// What the workers and [`Loads`] share. +struct State { + /// The jobs not started yet, in order. + queue: VecDeque<(usize, Job)>, + /// When each job started, and whether it has finished or passed its deadline. + started: Vec>, + finished: Vec, + expired: Vec, + /// Jobs whose index is below this may start. + limit: usize, + /// Worker threads alive, and how many of them run a job past its deadline. + workers: usize, + stuck: usize, +} + +struct Pool { + state: Mutex>, + /// Told when a job may start, or when the queue is emptied. + wake: Condvar, +} + +impl Pool { + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } +} + +/// Counts a worker as alive until its thread ends, however it ends. +struct Alive(Arc>); + +impl Drop for Alive { + fn drop(&mut self) { + self.0.lock().workers -= 1; + } +} + +/// Jobs loading on worker threads ([`Loads::start`]). +pub struct Loads { + pool: Arc>, + results: Mutex>>, + send: Sender>, + outcomes: Vec>>, + /// The outcomes before this one were taken ([`Loads::ready`]). + next: usize, + /// Of those, the ones the caller is done with ([`Loads::release`]). + released: usize, + /// How many jobs past `next` may start. + window: usize, + clock: Clock, + deadline: Duration, + /// The workers [`Loads::begin`] starts, and whether it has. + workers: usize, + begun: bool, + /// The process's count of stuck loader threads ([`STUCK_THREADS`]), and its most. + stuck_threads: &'static AtomicUsize, + max_stuck: usize, + /// Tests: no thread can be started from now on. + #[cfg(test)] + refuse_threads: bool, +} + +impl Loads { + /// Starts `jobs` on `min(available parallelism, MAX_WORKERS)` threads. + pub fn start(jobs: Vec>) -> Self { + let mut loads = Self::deferred(jobs); + loads.begin(); + loads + } + + /// `jobs` to start on `min(available parallelism, MAX_WORKERS)` threads once [`Loads::begin`] + /// is called (or something waits for them). + pub fn deferred(jobs: Vec>) -> Self { + Self::deferred_on(jobs, std::thread::available_parallelism().map_or(1, |n| n.get()).min(MAX_WORKERS)) + } + + /// [`Loads::deferred`] on `workers` threads (at least one). + pub(crate) fn deferred_on(jobs: Vec>, workers: usize) -> Self { + let origin = Instant::now(); + Self::with(jobs, workers, LOAD_DEADLINE, Arc::new(move || origin.elapsed())) + } + + /// Starts the jobs, unless they started already. + pub fn begin(&mut self) { + if self.begun { + return; + } + self.begun = true; + if cfg!(target_arch = "wasm32") { + // The web build has no threads: each job runs here, in order. + let jobs: Vec<_> = self.pool.lock().queue.drain(..).collect(); + for (i, job) in jobs { + // A job can't be stopped here, but one that took past its deadline fails as on + // the desktop. + let at = (self.clock)(); + let r = run_job(job); + let took = (self.clock)().saturating_sub(at); + self.record((i, r, took)); + } + } else { + for _ in 0..self.workers.min(self.outcomes.len()) { + self.spawn_worker(); + } + } + } + + #[cfg(test)] + fn start_with(jobs: Vec>, workers: usize, deadline: Duration, clock: Clock) -> Self { + let mut loads = Self::with(jobs, workers, deadline, clock); + loads.begin(); + loads + } + + fn with(jobs: Vec>, workers: usize, deadline: Duration, clock: Clock) -> Self { + let n = jobs.len(); + let workers = workers.max(1); + let window = workers * 2; + let state = State { + queue: jobs.into_iter().enumerate().collect(), + started: vec![None; n], + finished: vec![false; n], + expired: vec![false; n], + limit: window, + workers: 0, + stuck: 0, + }; + let (send, results) = mpsc::channel(); + Loads { + pool: Arc::new(Pool { state: Mutex::new(state), wake: Condvar::new() }), + results: Mutex::new(results), + send, + outcomes: (0..n).map(|_| None).collect(), + next: 0, + released: 0, + window, + clock, + deadline, + workers, + begun: false, + stuck_threads: &STUCK_THREADS, + max_stuck: MAX_STUCK_THREADS, + #[cfg(test)] + refuse_threads: false, + } + } + + /// Starts a thread that takes jobs until none are left → whether it started. + fn spawn_worker(&self) -> bool { + #[cfg(test)] + if self.refuse_threads { + return false; + } + if self.stuck_threads.load(Ordering::SeqCst) >= self.max_stuck { + log::warn!("not starting a thread to load plug-ins: {} loader threads are still running loads past their deadline", self.max_stuck); + return false; + } + let pool = self.pool.clone(); + let send = self.send.clone(); + let clock = self.clock.clone(); + let target = self.workers; + let stuck_threads = self.stuck_threads; + self.pool.lock().workers += 1; + let spawned = std::thread::Builder::new().name("plug-in loader".into()).spawn(move || { + let alive = Alive(pool); + loop { + let (i, job, at) = { + let mut s = alive.0.lock(); + loop { + match s.queue.front() { + None => return, + Some((i, _)) if *i < s.limit => break, + Some(_) => s = alive.0.wake.wait(s).unwrap_or_else(|e| e.into_inner()), + } + } + let Some((i, job)) = s.queue.pop_front() else { return }; + let at = clock(); + s.started[i] = Some(at); + (i, job, at) + }; + let r = run_job(job); + let took = clock().saturating_sub(at); + // A worker whose job passed its deadline and was replaced ends once the job + // returns, unless the workers able to take jobs are fewer than started. + let retire = { + let mut s = alive.0.lock(); + s.finished[i] = true; + s.expired[i] && { + s.stuck -= 1; + stuck_threads.fetch_sub(1, Ordering::SeqCst); + s.workers - s.stuck > target + } + }; + let _ = send.send((i, r, took)); + if retire { + return; + } + } + }); + if let Err(e) = spawned { + self.pool.lock().workers -= 1; + log::warn!("can't start a thread to load plug-ins: {e}"); + return false; + } + true + } + + /// Takes the outcomes that came in and fails the jobs past their deadline → whether every job + /// has its outcome. + pub fn poll(&mut self) -> bool { + loop { + let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).try_recv(); + let Ok(done) = next else { break }; + self.record(done); + } + self.expire(); + self.outcomes.iter().all(Option::is_some) + } + + /// The outcomes not taken yet that come in order from the last one taken, without waiting + /// ([`Loads::poll`] first). The jobs after them start as the caller releases them + /// ([`Loads::release`]). + pub fn ready(&mut self) -> Vec> { + self.poll(); + let mut out = Vec::new(); + while let Some(o) = self.outcomes.get_mut(self.next).and_then(Option::take) { + out.push(o); + self.next += 1; + } + out + } + + /// The caller is done with `n` more of the outcomes it took (installed or dropped them): as + /// many more jobs may start, so the outcomes held, here and by the caller, stay at most twice + /// the workers' count. + pub fn release(&mut self, n: usize) { + let released = (self.released + n).min(self.next); + if released != self.released { + self.released = released; + self.pool.lock().limit = released + self.window; + self.pool.wake.notify_all(); + } + } + + /// Whether every outcome has been taken. + pub fn taken(&self) -> bool { + self.next == self.outcomes.len() + } + + /// Whether the next outcome in order can be taken ([`Loads::ready`]). + pub fn next_ready(&mut self) -> bool { + self.poll(); + self.outcomes.get(self.next).is_some_and(Option::is_some) + } + + /// Waits until the next outcome in order can be taken, or every one has been. Jobs that have + /// not been started are started first ([`Loads::begin`]). + pub fn wait_next(&mut self) { + self.begin(); + while !self.taken() && !self.next_ready() { + let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv_timeout(TICK); + match next { + Ok(done) => self.record(done), + Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => {} + } + } + } + + /// Waits for every outcome → those not taken yet, in the order of the jobs. + pub fn wait(mut self) -> Vec> { + let mut out = Vec::new(); + while !self.taken() { + self.wait_next(); + let ready = self.ready(); + self.release(ready.len()); + out.extend(ready); + } + out + } + + fn record(&mut self, (i, r, took): Done) { + let r = if took >= self.deadline { Err(self.too_long()) } else { r }; + // An outcome that comes after the job failed past its deadline is dropped. + if let Some(slot @ None) = self.outcomes.get_mut(i) { + *slot = Some(r); + } + } + + fn too_long(&self) -> Error { + let secs = self.deadline.as_secs(); + Error::Failed(format!("did not finish loading within {secs} s")) + } + + /// Fails the jobs still running past their deadline, starting a worker in place of each one's + /// while the threads alive are fewer than twice the workers started. When no worker is left to + /// take the jobs not started (none could be made, or every one is stuck), those fail too, and + /// so does a job whose worker ended without an outcome. + fn expire(&mut self) { + if !self.begun { + return; + } + let now = (self.clock)(); + let mut expired = Vec::new(); + { + let mut s = self.pool.lock(); + for i in 0..self.outcomes.len() { + let late = s.started[i].is_some_and(|at| now.saturating_sub(at) >= self.deadline); + if late && !s.finished[i] && !s.expired[i] && self.outcomes[i].is_none() { + s.expired[i] = true; + s.stuck += 1; + self.stuck_threads.fetch_add(1, Ordering::SeqCst); + expired.push(i); + } + } + } + for i in &expired { + self.outcomes[*i] = Some(Err(self.too_long())); + } + for _ in &expired { + let room = { + let s = self.pool.lock(); + !s.queue.is_empty() && s.workers < 2 * self.workers + }; + if !room || !self.spawn_worker() { + break; + } + } + let stranded = { + let s = self.pool.lock(); + s.workers <= s.stuck + }; + if stranded && !self.outcomes.iter().all(Option::is_some) { + // What the last workers sent before they ended counts. + loop { + let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).try_recv(); + let Ok(done) = next else { break }; + self.record(done); + } + self.pool.lock().queue.clear(); + for o in self.outcomes.iter_mut().filter(|o| o.is_none()) { + *o = Some(Err(Error::Failed("no thread was left to load it".into()))); + } + } + } +} + +impl Drop for Loads { + /// Jobs not started yet are dropped; the running ones are given until their deadline, so the + /// launch marker is not left naming a plug-in that was still loading when the app quit. + fn drop(&mut self) { + self.pool.lock().queue.clear(); + self.pool.wake.notify_all(); + loop { + let running = { + let s = self.pool.lock(); + let now = (self.clock)(); + (0..self.outcomes.len()) + .any(|i| !s.finished[i] && !s.expired[i] && s.started[i].is_some_and(|at| now.saturating_sub(at) < self.deadline)) + }; + if !running { + break; + } + let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv_timeout(TICK); + if let Ok(done) = next { + self.record(done); + } + } + // A job still running past its deadline leaves its thread stuck, and the thread counts + // against the process's stuck threads until the job returns. + let mut s = self.pool.lock(); + for i in 0..self.outcomes.len() { + if s.started[i].is_some() && !s.finished[i] && !s.expired[i] { + s.expired[i] = true; + s.stuck += 1; + self.stuck_threads.fetch_add(1, Ordering::SeqCst); + } + } + } +} + +/// Runs `job` inside a panic boundary, with the launch marker naming its item while it runs. +fn run_job(job: Job) -> Result { + let token = job.item.as_ref().map(safe_mode::loading); + let result = catch_unwind(AssertUnwindSafe(job.work)); + if let Some(t) = token { + safe_mode::loaded(t); + } + match result { + Ok(r) => r, + Err(panic) => { + let what = panic.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| panic.downcast_ref::().cloned()); + Err(match what { + Some(what) => Error::Failed(format!("panicked while loading: {what}")), + None => Error::Failed("panicked while loading".into()), + }) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::AtomicU64; + use std::sync::mpsc::sync_channel; + + /// A clock the test moves. + fn manual() -> (Arc, Clock) { + let ms = Arc::new(AtomicU64::new(0)); + let read = ms.clone(); + (ms, Arc::new(move || Duration::from_millis(read.load(Ordering::SeqCst)))) + } + + /// A job that says it started on `started`, then waits for `go` and returns `v`. + fn held(v: u32, started: mpsc::SyncSender, go: Receiver<()>) -> Job { + Job::new(None, move || { + let _ = started.send(v); + let _ = go.recv(); + Ok(v) + }) + } + + /// Polls `loads` until `done` says so, at most a million times. + fn poll_until(loads: &mut Loads, mut done: impl FnMut(&mut Loads) -> bool) -> bool { + (0..1_000_000).any(|_| { + std::thread::yield_now(); + loads.poll(); + done(loads) + }) + } + + /// The outcomes come back in the order of the jobs when they finish in the reverse order. + #[test] + fn outcomes_keep_the_order_of_the_jobs() { + let (started, starts) = sync_channel(3); + let mut go = Vec::new(); + let mut jobs = Vec::new(); + for v in 0..3 { + let (tx, rx) = mpsc::channel(); + go.push(tx); + jobs.push(held(v, started.clone(), rx)); + } + let (_, clock) = manual(); + let mut loads = Loads::start_with(jobs, 3, LOAD_DEADLINE, clock); + for _ in 0..3 { + starts.recv().unwrap(); + } + // Each job is let go only once the one after it has finished. + let mut finished = Vec::new(); + for v in (0..3).rev() { + go[v].send(()).unwrap(); + let done = loads.results.lock().unwrap().recv().unwrap(); + finished.push(done.0); + loads.record(done); + } + assert_eq!(finished, vec![2, 1, 0], "they finished in reverse"); + assert_eq!(loads.wait().into_iter().map(|r| r.unwrap()).collect::>(), vec![0, 1, 2]); + } + + /// A job that panics fails with the panic's message, and the others load. + #[test] + fn a_job_that_panics_fails_alone() { + let jobs: Vec> = vec![Job::new(None, || Ok(1)), Job::new(None, || panic!("broken module")), Job::new(None, || Ok(3))]; + let (_, clock) = manual(); + let out = Loads::start_with(jobs, 2, LOAD_DEADLINE, clock).wait(); + assert_eq!(out[0], Ok(1)); + assert!(matches!(&out[1], Err(Error::Failed(m)) if m.contains("panicked") && m.contains("broken module")), "{:?}", out[1]); + assert_eq!(out[2], Ok(3)); + } + + /// With one worker, a job that never finishes fails at its deadline, and the job after it + /// still loads, on the worker that takes its place. + #[test] + fn a_job_that_hangs_fails_at_its_deadline_and_the_rest_load() { + let (started, starts) = sync_channel(2); + let (go, held_until) = mpsc::channel(); + let jobs = vec![held(0, started.clone(), held_until), Job::new(None, || Ok(1))]; + let (ms, clock) = manual(); + let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock); + assert_eq!(starts.recv().unwrap(), 0); + assert!(!loads.poll(), "the first job is still running and the second waits for a worker"); + ms.store(10_000, Ordering::SeqCst); + let done = poll_until(&mut loads, |l| l.outcomes.iter().all(Option::is_some)); + go.send(()).unwrap(); + assert!(done, "the job after the one that hangs never got its outcome"); + let out = loads.wait(); + assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]); + assert_eq!(out[1], Ok(1)); + } + + /// Workers that replace stuck ones stop at twice the workers started: with one worker and two + /// jobs that never finish, the third job fails instead of a third thread taking it. + #[test] + fn replacements_stop_at_twice_the_workers() { + let (started, starts) = sync_channel(3); + let (go0, held0) = mpsc::channel(); + let (go1, held1) = mpsc::channel(); + let jobs = vec![held(0, started.clone(), held0), held(1, started, held1), Job::new(None, || Ok(2))]; + let (ms, clock) = manual(); + let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock); + assert_eq!(starts.recv().unwrap(), 0); + ms.store(10_000, Ordering::SeqCst); + loads.poll(); + assert_eq!(starts.recv().unwrap(), 1, "a worker took the place of the stuck one"); + ms.store(20_000, Ordering::SeqCst); + let done = loads.poll(); + go0.send(()).unwrap(); + go1.send(()).unwrap(); + assert!(done, "every job has its outcome"); + let out = loads.wait(); + assert!(matches!(&out[2], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[2]); + } + + /// A job that finished but took longer than the deadline fails, however soon it is looked at. + #[test] + fn a_job_that_took_too_long_fails_when_it_is_taken() { + let (ms, clock) = manual(); + let moved = ms.clone(); + let jobs = vec![Job::new(None, move || { + moved.store(10_000, Ordering::SeqCst); + Ok(1u32) + })]; + let out = Loads::start_with(jobs, 1, Duration::from_secs(10), clock).wait(); + assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]); + } + + /// Only twice the workers' count of jobs past the last outcome taken start: the next one waits + /// until an outcome is taken. + #[test] + fn jobs_past_the_window_wait_until_outcomes_are_taken() { + let ran = Arc::new(AtomicUsize::new(0)); + let jobs: Vec> = (0..5) + .map(|v| { + let ran = ran.clone(); + Job::new(None, move || { + ran.fetch_add(1, Ordering::SeqCst); + Ok(v) + }) + }) + .collect(); + let (_, clock) = manual(); + let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock); + assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded"); + let early = ran.load(Ordering::SeqCst); + assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]); + assert_eq!(early, 2, "the third job waited for the first outcomes to be taken"); + assert!(!poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() > 0), "taken but not released"); + assert_eq!(ran.load(Ordering::SeqCst), 2, "the third job waits until the caller is done with the first outcomes"); + loads.release(2); + assert_eq!(loads.wait(), vec![Ok(2), Ok(3), Ok(4)]); + } + + /// When no worker can take the jobs left, because the only one is stuck past its deadline and + /// no thread takes its place, those jobs fail instead of being waited for. + #[test] + fn jobs_no_worker_can_take_fail() { + let (started, starts) = sync_channel(1); + let (go, held_until) = mpsc::channel(); + let jobs = vec![held(0, started, held_until), Job::new(None, || Ok(1))]; + let (ms, clock) = manual(); + let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock); + starts.recv().unwrap(); + loads.refuse_threads = true; + ms.store(10_000, Ordering::SeqCst); + let done = loads.poll(); + go.send(()).unwrap(); + assert!(done, "every job has its outcome"); + let out = loads.wait(); + assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]); + assert!(matches!(&out[1], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[1]); + } + + /// A thread stuck past its deadline counts against later loads until its job returns: with + /// room for one stuck thread in the process, the load after one that left a thread stuck + /// starts no thread and fails its job, and once the stuck job returns a load runs again. + #[test] + fn stuck_threads_count_across_loads_until_they_end() { + let stuck: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0))); + let make = |jobs: Vec>, clock: Clock| { + let mut loads = Loads::with(jobs, 1, Duration::from_secs(10), clock); + loads.stuck_threads = stuck; + loads.max_stuck = 1; + loads.begin(); + loads + }; + let (started, starts) = sync_channel(1); + let (go, held_until) = mpsc::channel(); + let (ms, clock) = manual(); + let mut first = make(vec![held(0, started, held_until)], clock); + starts.recv().unwrap(); + ms.store(10_000, Ordering::SeqCst); + assert!(first.poll(), "the stuck job failed at its deadline"); + drop(first); + let (_, clock) = manual(); + let out = make(vec![Job::new(None, || Ok(1))], clock.clone()).wait(); + assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[0]); + go.send(()).unwrap(); + assert!((0..1_000_000).any(|_| { + std::thread::yield_now(); + stuck.load(Ordering::SeqCst) == 0 + })); + assert_eq!(make(vec![Job::new(None, || Ok(2))], clock).wait(), vec![Ok(2)]); + } + + /// A load dropped while a job runs past its deadline, before anything looked at the job, still + /// counts the job's thread as stuck until the job returns. + #[test] + fn a_dropped_load_counts_a_job_past_its_deadline_as_stuck() { + let stuck: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0))); + let (started, starts) = sync_channel(1); + let (go, held_until) = mpsc::channel(); + let (ms, clock) = manual(); + let mut loads = Loads::with(vec![held(0, started, held_until)], 1, Duration::from_secs(10), clock); + loads.stuck_threads = stuck; + loads.begin(); + starts.recv().unwrap(); + ms.store(10_000, Ordering::SeqCst); + drop(loads); + assert_eq!(stuck.load(Ordering::SeqCst), 1, "the stuck thread counts"); + go.send(()).unwrap(); + assert!((0..1_000_000).any(|_| { + std::thread::yield_now(); + stuck.load(Ordering::SeqCst) == 0 + })); + } + + /// The launch marker names an item while its job runs, and stops naming it when the job + /// returns, a job that panicked included. + #[test] + fn a_job_names_its_item_until_it_returns_even_when_it_panics() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let ok = Item::file("test-loader-ok.wasm"); + let bad = Item::file("test-loader-panics.wasm"); + let named = |item: &Item| crate::safe_mode::still_loading().iter().any(|i| i.same(item)); + let (ok2, bad2) = (ok.clone(), bad.clone()); + let bad_named = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let seen = bad_named.clone(); + let jobs: Vec> = vec![ + Job::new(Some(ok.clone()), move || Ok(named(&ok2))), + Job::new(Some(bad.clone()), move || { + seen.store(named(&bad2), Ordering::SeqCst); + panic!("x") + }), + ]; + let (_, clock) = manual(); + let outcomes = Loads::start_with(jobs, 2, LOAD_DEADLINE, clock).wait(); + assert!(matches!(outcomes.first(), Some(Ok(true))), "named while it runs"); + assert!(bad_named.load(Ordering::SeqCst), "named while it runs, before it panics"); + assert!(matches!(outcomes.get(1), Some(Err(Error::Failed(m))) if m.contains("panicked while loading")), "the panic is the job's failure"); + let running = crate::safe_mode::still_loading(); + assert!(!running.iter().any(|i| i.same(&bad) || i.same(&ok)), "{running:?}"); + } +} diff --git a/crates/plugins/src/registry.rs b/crates/plugins/src/registry.rs index 6d20452ce6..3d84d8a6f7 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -77,11 +77,69 @@ pub fn install(mut plugin: Plugin) -> Result> { return Err(Error::NeedsApproval(crate::permissions::names(&plugin.manifest().permissions()).join(", "))); } plugin.set_serial(REVISION.fetch_add(1, Ordering::Relaxed) + 1); + note_change(plugin.id(), plugin.serial()); let p = Arc::new(plugin); plugins.insert(p.id().to_string(), p.clone()); Ok(p) } +/// The [`revision`] of each id's last install or removal ([`changed_since`]). +static CHANGED: RwLock> = RwLock::new(BTreeMap::new()); + +/// Records that `id` was installed or removed at revision `rev`; called while the plug-ins' write +/// lock is held. +fn note_change(id: &str, rev: u64) { + CHANGED.write().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), rev); +} + +/// Whether plug-in `id` was installed or removed after [`revision`] gave `rev`. +pub fn changed_since(id: &str, rev: u64) -> bool { + CHANGED.read().unwrap_or_else(|e| e.into_inner()).get(id).is_some_and(|&r| r > rev) +} + +/// What a load that installs plug-ins one by one has to check, so that a module it loaded before +/// another session installed or removed the same id doesn't undo that change: the [`revision`] when +/// the load listed its files, and the revision of each id it, or a load of the same session that +/// ended before it, installed. +#[derive(Debug, Default)] +pub struct LoadChanges { + since: Option, + own: BTreeMap, +} + +impl LoadChanges { + /// Marks the load as started now, unless it started already. A load calls it as it lists its + /// files, so a change made between the listing and the loads counts as one made elsewhere. + pub fn start(&mut self) { + self.since.get_or_insert_with(revision); + } + + /// Whether `id` was installed or removed since the load started, other than by the load itself + /// or a load it [adopted](LoadChanges::adopt). + pub fn superseded(&self, id: &str) -> bool { + self.since.is_some_and(|since| changed_since(id, since.max(self.own.get(id).copied().unwrap_or(0)))) + } + + /// Records that the load installed `plugin`. + pub fn installed(&mut self, plugin: &Plugin) { + self.own.insert(plugin.id().to_string(), plugin.serial()); + } + + /// Counts what `earlier`, a load of the same session queued before this one that has ended, + /// installed as this load's own: a module this load installs after it then replaces it, as it + /// would have with the loads run one after the other. + pub fn adopt(&mut self, earlier: &LoadChanges) { + for (id, &serial) in &earlier.own { + let own = self.own.entry(id.clone()).or_default(); + *own = (*own).max(serial); + } + } +} + +/// What a load reports for a module it skips because the plug-in under its id was installed or +/// removed elsewhere while it loaded ([`LoadChanges`]). +pub const SUPERSEDED: &str = "skipped: the plug-in with its id was installed or removed elsewhere while it loaded"; + /// What [`install_checked`] does to the grant recorded for the plug-in's id. pub enum GrantUpdate { /// Records this grant, replacing an earlier one for the id ([`grant`]). @@ -128,6 +186,7 @@ pub fn install_checked( } } plugin.set_serial(REVISION.fetch_add(1, Ordering::Relaxed) + 1); + note_change(&id, plugin.serial()); let p = Arc::new(plugin); plugins.insert(id, p.clone()); Ok(p) @@ -154,7 +213,7 @@ pub fn remove(id: &str) -> bool { let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner()); let gone = plugins.remove(id).is_some(); if gone { - REVISION.fetch_add(1, Ordering::Relaxed); + note_change(id, REVISION.fetch_add(1, Ordering::Relaxed) + 1); } gone } @@ -224,6 +283,19 @@ fn open_module(path: &std::path::Path) -> std::io::Result { open.open(path) } +/// Whether this process may read the file at `path`, checked against its permissions without +/// opening it. On Unix the check uses the effective user and group; elsewhere it passes. +#[cfg(all(unix, not(target_arch = "wasm32")))] +pub fn may_read(path: &std::path::Path) -> std::io::Result<()> { + rustix::fs::accessat(rustix::fs::CWD, path, rustix::fs::Access::READ_OK, rustix::fs::AtFlags::EACCESS).map_err(std::io::Error::from) +} + +/// [`may_read`] off Unix: it passes, and a file that can't be read fails when its load reads it. +#[cfg(all(not(unix), not(target_arch = "wasm32")))] +pub fn may_read(_path: &std::path::Path) -> std::io::Result<()> { + Ok(()) +} + /// The most `.wasm` files one [`load_folder`] reads. #[cfg(not(target_arch = "wasm32"))] const MAX_FOLDER_FILES: usize = 1000; @@ -272,9 +344,11 @@ pub struct FolderReport { /// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first /// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything /// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it -/// ([`load_file`]). A bad module is reported and skipped, the others still load; so is a heavy one -/// ([`crate::Budget::Heavy`]), which installs only once the user agrees, and one that lists -/// permissions the user has not granted this very module ([`approved`]). +/// ([`load_file`]). The modules load on worker threads ([`FolderLoad`]) and install in file-name +/// order. A bad module is reported and skipped, the others still load; so is one whose load panics +/// or doesn't finish in time ([`crate::loader`]), a heavy one ([`crate::Budget::Heavy`]), which +/// installs only once the user agrees, and one that lists permissions the user has not granted this +/// very module ([`approved`]). #[cfg(not(target_arch = "wasm32"))] pub fn load_folder(dir: &std::path::Path) -> Result { load_folder_where(dir, |_| Ok(()), approved) @@ -291,54 +365,233 @@ pub fn load_folder(dir: &std::path::Path) -> Result { #[cfg(not(target_arch = "wasm32"))] pub fn load_folder_where( dir: &std::path::Path, - allow: impl Fn(&std::path::Path) -> std::result::Result<(), String>, + allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, approve: impl Fn(&Plugin) -> bool, ) -> Result { - use crate::safe_mode::{self, Item}; - safe_mode::check()?; - let (files, left_out) = folder_files(dir)?; - let mut report = FolderReport { left_out, ..FolderReport::default() }; - for f in files { - if let Err(why) = allow(&f) { - report.failed.push((f.display().to_string(), why)); - continue; + let mut load = FolderLoad::begin(dir, allow)?; + while !load.done() { + load.wait(); + load.install_ready(&approve); + } + Ok(load.finish()) +} + +/// Tests: what runs before a folder module loads, given its path. +#[cfg(all(test, not(target_arch = "wasm32")))] +type FileHook = std::sync::Arc; + +/// Tests: runs on the worker thread before the module at the path it is given loads. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) static BEFORE_FOLDER_FILE: Mutex> = Mutex::new(None); + +/// A [`load_folder_where`] whose modules load on worker threads ([`crate::loader`]) while the +/// caller goes on: [`FolderLoad::begin`] lists the folder and starts the loads, +/// [`FolderLoad::install_ready`] installs what loaded so far in file-name order, whatever order the +/// loads finish in, and [`FolderLoad::finish`] ends the load once [`FolderLoad::done`]. A module +/// whose load panics or doesn't finish in time is reported as failed, and the others still install. +#[cfg(not(target_arch = "wasm32"))] +pub struct FolderLoad { + /// Each file in file-name order, with why it was refused before loading, if it was. + files: Vec<(std::path::PathBuf, Option)>, + loads: crate::loader::Loads, + /// Outcomes taken from `loads` and not installed yet, in order. + loaded: std::collections::VecDeque>, + /// The next file to install or report. + next: usize, + report: FolderReport, + /// Installs and removals elsewhere since the folder was listed, which a module loaded before + /// them doesn't undo. + changes: LoadChanges, +} + +#[cfg(not(target_arch = "wasm32"))] +impl FolderLoad { + /// Lists `dir` and starts loading the files `allow` accepts and the user didn't disable. Each + /// file is checked with `allow` again on its worker thread, right before it is read. In Safe + /// Mode nothing loads ([`Error::SafeMode`]); an error listing the folder is returned. + pub fn begin( + dir: &std::path::Path, + allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, + ) -> Result { + let mut load = Self::list_on(dir, allow, None)?; + load.start(); + Ok(load) + } + + /// [`FolderLoad::begin`] without starting the loads: [`FolderLoad::start`] starts them, and + /// so does waiting for them. + pub fn list( + dir: &std::path::Path, + allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, + ) -> Result { + Self::list_on(dir, allow, None) + } + + /// Starts the loads, unless they started already. + pub fn start(&mut self) { + self.changes.start(); + self.loads.begin(); + } + + /// [`FolderLoad::list`] for `workers` threads (`None`: as many as [`crate::loader::Loads::start`] + /// starts). + fn list_on( + dir: &std::path::Path, + allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static, + workers: Option, + ) -> Result { + use crate::loader::{Job, Loads}; + use crate::safe_mode::{self, Item}; + safe_mode::check()?; + let (found, left_out) = folder_files(dir)?; + let allow = std::sync::Arc::new(allow); + let mut files = Vec::with_capacity(found.len()); + let mut jobs = Vec::new(); + for f in found { + let item = Item::file(f.display().to_string()); + let refused = match allow(&f) { + Err(why) => Some(why), + Ok(()) if safe_mode::skipped(&item) => Some(DISABLED.to_string()), + Ok(()) => None, + }; + if refused.is_none() { + let (path, allow) = (f.clone(), allow.clone()); + jobs.push(Job::new(Some(item), move || { + allow(&path).map_err(Error::Io)?; + #[cfg(test)] + { + let hook = BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(hook) = hook { + hook(&path); + } + } + load_file(&path, Limits::default()) + })); + } + files.push((f, refused)); } - let item = Item::file(f.display().to_string()); - if safe_mode::skipped(&item) { - report.failed.push((f.display().to_string(), DISABLED.into())); - continue; - } - let token = safe_mode::loading(&item); - let loaded = load_file(&f, Limits::default()); - safe_mode::loaded(token); - match loaded { - Ok(p) if safe_mode::skipped(&Item::of(&p)) => { - report.disabled_changed |= safe_mode::disable_file_of(&Item::of(&p)); - report.failed.push((f.display().to_string(), DISABLED.into())); - } - // A heavy plug-in installs once the user agrees, which loading a folder doesn't ask. - Ok(p) if p.manifest().budget == crate::Budget::Heavy => { - report.failed.push((f.display().to_string(), "asks for a heavy budget, which the user allows when installing it on its own".into())); - } - Ok(p) if p.manifest().asks_permissions() && !approve(&p) => { - let asked = crate::permissions::names(&p.manifest().permissions()).join(", "); - report.failed.push((f.display().to_string(), Error::NeedsApproval(asked).to_string())); - } - // `approve` only narrows what installs: `install` still refuses a module that no - // recorded grant covers. - Ok(p) => match install(p) { - Ok(p) => report.loaded.push(p.id().to_string()), - Err(e) => report.failed.push((f.display().to_string(), e.to_string())), - }, - Err(e) => report.failed.push((f.display().to_string(), e.to_string())), + let loads = match workers { + Some(n) => Loads::deferred_on(jobs, n), + None => Loads::deferred(jobs), + }; + let report = FolderReport { left_out, ..FolderReport::default() }; + let mut changes = LoadChanges::default(); + changes.start(); + Ok(FolderLoad { files, loads, loaded: Default::default(), next: 0, report, changes }) + } + + /// The installs and removals the load checks its modules against ([`LoadChanges`]). + pub fn changes(&self) -> &LoadChanges { + &self.changes + } + + /// [`FolderLoad::changes`], to [adopt](LoadChanges::adopt) an earlier load's. + pub fn changes_mut(&mut self) -> &mut LoadChanges { + &mut self.changes + } + + /// Whether every file has been installed or reported. + pub fn done(&self) -> bool { + self.next == self.files.len() + } + + /// Whether [`FolderLoad::install_ready`] has something to install or report now, without + /// waiting (or nothing is left). + pub fn ready(&mut self) -> bool { + match self.files.get(self.next) { + None => true, + Some((_, Some(_))) => true, + Some((_, None)) => !self.loaded.is_empty() || self.loads.next_ready(), } } - for id in &report.loaded { - if get(id).is_some_and(|p| !p.manifest().asks_permissions()) { - revoke(id); + + /// Waits until [`FolderLoad::ready`], starting the loads first ([`FolderLoad::start`]). + pub fn wait(&mut self) { + self.start(); + while !self.ready() && !self.loads.taken() { + self.loads.wait_next(); } } - Ok(report) + + /// Installs the plug-ins that loaded, and reports the files that failed, in file-name order up + /// to the first file still loading, as [`load_folder_where`] does: those that list permissions + /// only when `approve` accepts them and a recorded grant covers them → the ids it installed. + pub fn install_ready(&mut self, approve: impl Fn(&Plugin) -> bool) -> Vec { + use crate::safe_mode::{self, Item}; + self.loaded.extend(self.loads.ready()); + let mut installed = Vec::new(); + while let Some((f, refused)) = self.files.get(self.next) { + let name = f.display().to_string(); + if let Some(why) = refused { + self.report.failed.push((name, why.clone())); + self.next += 1; + continue; + } + let Some(loaded) = self.loaded.pop_front() else { break }; + self.loads.release(1); + self.next += 1; + let report = &mut self.report; + match loaded { + Ok(p) if safe_mode::skipped(&Item::of(&p)) => { + report.disabled_changed |= safe_mode::disable_file_of(&Item::of(&p)); + report.failed.push((name, DISABLED.into())); + } + // A heavy plug-in installs once the user agrees, which loading a folder doesn't ask. + Ok(p) if p.manifest().budget == crate::Budget::Heavy => { + report.failed.push((name, "asks for a heavy budget, which the user allows when installing it on its own".into())); + } + // The very module installed elsewhere meanwhile (another session loading the same + // folder) counts as loaded. `approve` may record a grant, so it is asked only for + // that module: a module another session replaced or removed changes no grant. + Ok(p) if self.changes.superseded(p.id()) => match get(p.id()) { + Some(q) if q.hash() == p.hash() && (!p.manifest().asks_permissions() || approve(&p)) => report.loaded.push(p.id().to_string()), + Some(q) if q.hash() == p.hash() => { + let asked = crate::permissions::names(&p.manifest().permissions()).join(", "); + report.failed.push((name, Error::NeedsApproval(asked).to_string())); + } + _ => report.failed.push((name, SUPERSEDED.into())), + }, + Ok(p) if p.manifest().asks_permissions() && !approve(&p) => { + let asked = crate::permissions::names(&p.manifest().permissions()).join(", "); + report.failed.push((name, Error::NeedsApproval(asked).to_string())); + } + // `approve` only narrows what installs: `install` still refuses a module that no + // recorded grant covers. + Ok(p) => match install(p) { + Ok(p) => { + self.changes.installed(&p); + report.loaded.push(p.id().to_string()); + installed.push(p.id().to_string()); + } + Err(e) => report.failed.push((name, e.to_string())), + }, + Err(e) => report.failed.push((name, e.to_string())), + } + } + installed + } + + /// Drops the loads not taken yet: jobs not started don't start, and running ones are given + /// until their deadline ([`crate::loader::Loads`]). What was installed stays, and the load is + /// [`FolderLoad::done`]. + pub fn cancel(&mut self) { + self.loads = crate::loader::Loads::deferred(Vec::new()); + self.loaded.clear(); + self.next = self.files.len(); + } + + /// Ends the load → its report. When the module the load installed under an id lists no + /// permissions and is still installed, the process's grant for that id is forgotten. Files not + /// installed or reported yet ([`FolderLoad::done`] false) are left out. + pub fn finish(self) -> FolderReport { + let FolderLoad { report, changes, .. } = self; + for id in &report.loaded { + if get(id).is_some_and(|p| changes.own.get(id) == Some(&p.serial()) && !p.manifest().asks_permissions()) { + revoke(id); + } + } + report + } } #[cfg(test)] @@ -618,4 +871,207 @@ mod tests { let first: Vec = (0..MAX_FOLDER_FILES).map(|i| dir.join(format!("{i:05}.wasm")).display().to_string()).collect(); assert_eq!(tried, first, "the first files by name, in that order"); } + + /// Clears [`BEFORE_FOLDER_FILE`] when a test ends, failed or not. + #[cfg(not(target_arch = "wasm32"))] + struct Hooked; + + #[cfg(not(target_arch = "wasm32"))] + impl Hooked { + fn set(hook: impl Fn(&std::path::Path) + Send + Sync + 'static) -> Hooked { + *BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(hook)); + Hooked + } + } + + #[cfg(not(target_arch = "wasm32"))] + impl Drop for Hooked { + fn drop(&mut self) { + *BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + } + + /// The plug-ins of a folder install in file-name order, and take their revisions in that order, + /// when the first file's load finishes after the others. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_installs_in_file_name_order_whatever_order_the_loads_finish_in() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + let dir = test_dir("order"); + let ids = ["test.registry.order.a", "test.registry.order.b", "test.registry.order.c"]; + for (n, id) in ["a", "b", "c"].iter().zip(ids) { + std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 11)).unwrap(); + } + let first = dir.join("a.wasm"); + let (go, a_waits) = std::sync::mpsc::channel::<()>(); + let a_waits = Mutex::new(a_waits); + let seen = std::sync::Arc::new(Mutex::new(Vec::new())); + let held = first.clone(); + let saw = seen.clone(); + let _hook = Hooked::set(move |p| { + saw.lock().unwrap_or_else(|e| e.into_inner()).push(p.to_path_buf()); + if p == held { + let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv(); + } + }); + // Two workers, so the other files load while the first one waits. + let loading = std::thread::spawn({ + let dir = dir.clone(); + move || { + let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2))?; + load.start(); + while !load.done() { + load.wait(); + load.install_ready(|_| false); + } + Ok::<_, Error>(load.finish()) + } + }); + // The other two files load on the other worker while the first one waits: their loads have + // started (the hook saw them) and ended (the launch marker list no longer has them). + let all = ["a", "b", "c"].map(|n| dir.join(format!("{n}.wasm"))); + let finished = |p: &std::path::Path| { + let item = crate::safe_mode::Item::file(p.display().to_string()); + seen.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|s| s == p) && !crate::safe_mode::still_loading().iter().any(|i| i.same(&item)) + }; + while !(seen.lock().unwrap_or_else(|e| e.into_inner()).contains(&first) && finished(&all[1]) && finished(&all[2])) { + std::thread::yield_now(); + } + assert!(ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded"); + go.send(()).unwrap(); + let r = loading.join().unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + let r = r.unwrap(); + assert_eq!(r.loaded, ids.to_vec(), "{r:?}"); + let serials: Vec = ids.iter().map(|id| get(id).unwrap().serial()).collect(); + assert!(serials.windows(2).all(|w| w[0] < w[1]), "installed in file-name order: {serials:?}"); + for id in ids { + assert!(remove(id)); + } + } + + /// A folder module that loaded before something else installed or removed the same id, while + /// an earlier file still loaded, doesn't undo that change: it is reported as skipped, and the + /// plug-in installed meanwhile stays, as does the removal. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_module_doesnt_undo_a_change_made_while_it_waited() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + let dir = test_dir("superseded"); + let ids = ["test.registry.superseded.a", "test.registry.superseded.b", "test.registry.superseded.c"]; + // b's file asks for a permission: asking whether it may install could record a grant. + for (n, id) in ["a", "b", "c"].iter().zip(ids) { + let asks = (*n == "b").then_some(r#"["doc.read"]"#); + std::fs::write(dir.join(format!("{n}.wasm")), module(id, asks, 13)).unwrap(); + } + install_bytes(&module(ids[2], None, 14)).unwrap(); + let first = dir.join("a.wasm"); + let (go, a_waits) = std::sync::mpsc::channel::<()>(); + let a_waits = Mutex::new(a_waits); + let (reached, a_reached) = std::sync::mpsc::channel::<()>(); + let held = first.clone(); + let _hook = Hooked::set(move |p| { + if p == held { + let _ = reached.send(()); + let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv(); + } + }); + let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap(); + load.start(); + a_reached.recv().unwrap(); + // Elsewhere, while the first file still loads: `b` is installed and `c` removed. + let theirs = install_bytes(&module(ids[1], None, 15)).unwrap().serial(); + assert!(remove(ids[2])); + go.send(()).unwrap(); + let asked = Mutex::new(Vec::new()); + while !load.done() { + load.wait(); + load.install_ready(|p| { + asked.lock().unwrap_or_else(|e| e.into_inner()).push(p.id().to_string()); + false + }); + } + let r = load.finish(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(r.loaded, vec![ids[0]], "{r:?}"); + assert!(r.failed.iter().all(|(_, why)| why == SUPERSEDED) && r.failed.len() == 2, "{r:?}"); + assert!(asked.lock().unwrap_or_else(|e| e.into_inner()).is_empty(), "no grant is asked for a superseded module"); + assert_eq!(get(ids[1]).map(|p| p.serial()), Some(theirs), "the plug-in installed meanwhile stays"); + assert!(get(ids[2]).is_none(), "the removal stays"); + for id in &ids[..2] { + assert!(remove(id)); + } + } + + /// A plug-in installed elsewhere after the folder was listed and before its loads started + /// stays: the folder's module with its id is skipped. One a load of the same session installed + /// before it ([`LoadChanges::adopt`]) is replaced. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_module_doesnt_undo_a_change_made_before_its_loads_started() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + let dir = test_dir("superseded-listed"); + let ids = ["test.registry.listed.a", "test.registry.listed.b"]; + for (n, id) in ["a", "b"].iter().zip(ids) { + std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 13)).unwrap(); + } + let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap(); + // Before the loads start: another session installs `a`, and an earlier load of this + // session installs `b`. + let theirs = install_bytes(&module(ids[0], None, 14)).unwrap().serial(); + let mut earlier = LoadChanges::default(); + earlier.start(); + earlier.installed(&install_bytes(&module(ids[1], None, 15)).unwrap()); + load.changes_mut().adopt(&earlier); + load.start(); + while !load.done() { + load.wait(); + load.install_ready(|_| false); + } + let r = load.finish(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(r.loaded, vec![ids[1]], "{r:?}"); + assert!(r.failed.iter().all(|(_, why)| why == SUPERSEDED) && r.failed.len() == 1, "{r:?}"); + assert_eq!(get(ids[0]).map(|p| p.serial()), Some(theirs), "the plug-in installed elsewhere stays"); + for id in ids { + assert!(remove(id)); + } + } + + /// A folder whose second module panics while it loads reports it as failed and installs the + /// others. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_module_that_panics_while_loading_fails_alone() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + let dir = test_dir("panics"); + let ids = ["test.registry.panics.a", "test.registry.panics.b", "test.registry.panics.c"]; + for (n, id) in ["a", "b", "c"].iter().zip(ids) { + std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 12)).unwrap(); + } + let broken = dir.join("b.wasm"); + let hooked = broken.clone(); + let hook = Hooked::set(move |p| { + if p == hooked { + panic!("a defect while loading"); + } + }); + let r = load_folder_where(&dir, |_| Ok(()), |_| false); + drop(hook); + std::fs::remove_dir_all(&dir).unwrap(); + let item = crate::safe_mode::Item::file(broken.display().to_string()); + let marked = crate::safe_mode::still_loading().iter().any(|i| i.same(&item)); + let r = r.unwrap(); + assert_eq!(r.loaded, vec![ids[0], ids[2]], "{r:?}"); + assert_eq!(r.failed.len(), 1, "{r:?}"); + assert!(r.failed[0].0 == broken.display().to_string() && r.failed[0].1.contains("panicked"), "{r:?}"); + assert!(!marked, "the launch marker stops naming the module whose load failed"); + for id in [ids[0], ids[2]] { + assert!(remove(id)); + } + } } diff --git a/crates/plugins/src/safe_mode.rs b/crates/plugins/src/safe_mode.rs index efa853d763..7c7be98d1c 100644 --- a/crates/plugins/src/safe_mode.rs +++ b/crates/plugins/src/safe_mode.rs @@ -14,16 +14,16 @@ //! //! **Launch marker** (native builds): a small file in a folder the app picks, written before the //! stored plug-ins load, updated before and after each module load and each live effect's first -//! evaluation (and each evaluation that starts while one of those is running) to name the oldest -//! item still loading (several threads can load at once), and removed -//! when the app quits ([`begin_launch`], [`loading`], [`loaded`], [`end_launch`]). A launch that -//! ends while an item is still loading (a panic the app caught while a plug-in loaded) keeps its -//! marker naming that item. A marker left behind by a -//! launch that is no longer running names the item that was loading when it stopped, which may or -//! may not be what stopped it. Until the user -//! chooses what to do about that item ([`forget_previous`]), the next launch's marker names it too -//! and stays when that launch quits, so a launch that asks nothing (`--safe-mode`) or one closed in -//! Safe Mode leaves the choice to the launch after it. Each launch has +//! evaluation (and each evaluation that starts while one of those is running) to name every item +//! still loading, oldest first (several threads can load at once; at most [`MAX_MARKER_ITEMS`]), +//! and removed when the app quits ([`begin_launch`], [`loading`], [`loaded`], [`end_launch`]). A +//! launch that ends while an item is still loading (a panic the app caught outside a load job +//! while a plug-in loaded) keeps its marker naming that item. A marker left behind by a launch +//! that is no longer running names the items that were loading when it stopped; any one of them, +//! or none, may be what stopped it. Until the user chooses what to do about those items +//! ([`forget_previous`]), the next launch's marker names them too and stays when that launch +//! quits, so a launch that asks nothing (`--safe-mode`) or one closed in Safe Mode leaves the +//! choice to the launch after it. Each launch has //! its own marker and holds a lock on a file beside it, so a launch that is still running (a second //! window) is never taken for one that stopped. A marker that is missing, empty, unreadable, //! malformed, larger than [`MAX_MARKER_BYTES`] or of another version names nothing. @@ -41,8 +41,11 @@ const MAX_FIELD_CHARS: usize = 1024; /// The most bytes one stored item takes in JSON: three fields of [`MAX_FIELD_CHARS`] characters, /// each written in at most 6 bytes (`\u001f`), plus keys, quotes and indentation. const MAX_ITEM_JSON_BYTES: usize = 3 * MAX_FIELD_CHARS * 6 + 256; -/// The largest launch marker read, in bytes: room for one stored item. -pub const MAX_MARKER_BYTES: u64 = (MAX_ITEM_JSON_BYTES + 256) as u64; +/// The most items a launch marker names. +pub const MAX_MARKER_ITEMS: usize = 16; +/// The largest launch marker read, in bytes: room for [`MAX_MARKER_ITEMS`] stored items, and the +/// first of them again as `item`. +pub const MAX_MARKER_BYTES: u64 = ((MAX_MARKER_ITEMS + 1) * MAX_ITEM_JSON_BYTES + 256) as u64; /// The longest name an item is shown with, in characters (longer ones end with "…"). pub const MAX_NAME_CHARS: usize = 64; /// The most disabled items kept. @@ -413,18 +416,19 @@ pub fn read_disabled_file(bytes: &[u8]) -> Option> { ) } -/// The item the launch before this one was loading when it stopped, once [`begin_launch`] read it. -static PREVIOUS: Mutex> = Mutex::new(None); +/// The items the launch before this one was loading when it stopped, once [`begin_launch`] read +/// them. +static PREVIOUS: Mutex> = Mutex::new(Vec::new()); -/// The item the launch before this one was loading when it stopped ([`begin_launch`]); `None` once -/// the user chose what to do about it ([`forget_previous`]). -pub fn previous() -> Option { +/// The items the launch before this one was loading when it stopped, oldest first +/// ([`begin_launch`]); none once the user chose what to do about them ([`forget_previous`]). +pub fn previous() -> Vec { PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()).clone() } -/// The user chose what to do about [`previous`]: this launch's marker stops naming it. +/// The user chose what to do about [`previous`]: this launch's marker stops naming them. pub fn forget_previous() { - *PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()) = None; + PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()).clear(); refresh(); } @@ -437,9 +441,19 @@ struct Running { #[cfg(not(target_arch = "wasm32"))] impl Running { - /// The item this launch's marker names: the oldest item still loading, else [`previous`]. - fn pending(&self) -> Option { - self.items.first().map(|(_, i)| i.clone()).or_else(previous) + /// The items this launch's marker names: the items still loading, oldest first, each plug-in + /// once, at most [`MAX_MARKER_ITEMS`]; with none loading, [`previous`]. + fn pending(&self) -> Vec { + let mut items: Vec = Vec::new(); + for (_, item) in &self.items { + if items.len() == MAX_MARKER_ITEMS { + break; + } + if !items.iter().any(|i| i.same(item)) { + items.push(item.clone()); + } + } + if items.is_empty() { previous() } else { items } } } @@ -450,22 +464,33 @@ static LOADING: Mutex = Mutex::new(Running { next: 0, items: Vec::new() #[derive(Debug)] pub struct Loading(u64); -/// Writes this launch's marker naming the item [`Running::pending`] gives, while holding the lock +/// Writes this launch's marker naming the items [`Running::pending`] gives, while holding the lock /// on the items still loading, so two threads' writes land in the order of their changes. fn refresh() { #[cfg(not(target_arch = "wasm32"))] - marker::write(LOADING.lock().unwrap_or_else(|e| e.into_inner()).pending().as_ref()); + marker::write(&LOADING.lock().unwrap_or_else(|e| e.into_inner()).pending()); } -/// The marker's content naming `item`, cut as a stored item is (none: nothing is loading). +/// The marker's content naming `items` (none: nothing is loading), each cut as a stored item is, +/// at most [`MAX_MARKER_ITEMS`]: the first as `item`, and all of them as `items` when there are +/// several. #[cfg(not(target_arch = "wasm32"))] -fn marker_bytes(item: Option<&Item>) -> Vec { - let item = item.cloned().and_then(Item::bounded); - serde_json::to_vec(&json!({"format": MARKER_FORMAT, "version": MARKER_VERSION, "item": item})).unwrap_or_default() +fn marker_bytes(items: &[Item]) -> Vec { + let items: Vec = items.iter().cloned().filter_map(Item::bounded).take(MAX_MARKER_ITEMS).collect(); + let mut v = json!({"format": MARKER_FORMAT, "version": MARKER_VERSION, "item": items.first()}); + if items.len() > 1 { + v["items"] = json!(items); + } + serde_json::to_vec(&v).unwrap_or_default() } -/// The item a marker's content names; `None` when it names none or isn't a marker of this version. -pub fn parse_marker(bytes: &[u8]) -> Option { +/// The items a marker's content names, oldest first: its `items` when it has them, else its +/// `item`; none when it names none or isn't a marker of this version. +pub fn parse_marker(bytes: &[u8]) -> Vec { + read_marker(bytes).unwrap_or_default() +} + +fn read_marker(bytes: &[u8]) -> Option> { if bytes.len() as u64 > MAX_MARKER_BYTES { return None; } @@ -473,31 +498,44 @@ pub fn parse_marker(bytes: &[u8]) -> Option { if v["format"] != MARKER_FORMAT || v["version"] != MARKER_VERSION { return None; } - serde_json::from_value::(v.get("item").filter(|i| i.is_object())?.clone()).ok()?.bounded() + let item = |i: &Value| serde_json::from_value::(i.clone()).ok()?.bounded(); + let mut items: Vec = Vec::new(); + for i in v["items"].as_array().into_iter().flatten().filter(|i| i.is_object()) { + if items.len() == MAX_MARKER_ITEMS { + break; + } + if let Some(i) = item(i).filter(|i| !items.iter().any(|e| e.same(i))) { + items.push(i); + } + } + if items.is_empty() { + items.extend(v.get("item").filter(|i| i.is_object()).and_then(item)); + } + Some(items) } #[cfg(not(target_arch = "wasm32"))] pub use marker::{begin_launch, end_launch}; -/// Adds `item` to the items still loading and writes this launch's marker naming the oldest of -/// them (no marker: only the list changes) → the [`Loading`] to give to [`loaded`] when it is done. +/// Adds `item` to the items still loading and writes this launch's marker naming them (no marker: +/// only the list changes) → the [`Loading`] to give to [`loaded`] when it is done. pub fn loading(item: &Item) -> Loading { let mut running = LOADING.lock().unwrap_or_else(|e| e.into_inner()); let token = running.next; running.next = running.next.wrapping_add(1); running.items.push((token, item.clone())); #[cfg(not(target_arch = "wasm32"))] - marker::write(running.pending().as_ref()); + marker::write(&running.pending()); Loading(token) } /// Removes the item `token` names from the items still loading and writes this launch's marker -/// naming the oldest one left; with none left, the item of [`previous`] or nothing. +/// naming the ones left; with none left, the items of [`previous`] or nothing. pub fn loaded(token: Loading) { let mut running = LOADING.lock().unwrap_or_else(|e| e.into_inner()); running.items.retain(|(t, _)| *t != token.0); #[cfg(not(target_arch = "wasm32"))] - marker::write(running.pending().as_ref()); + marker::write(&running.pending()); } #[cfg(not(target_arch = "wasm32"))] @@ -551,12 +589,12 @@ mod marker { (bytes.len() as u64 <= MAX_MARKER_BYTES).then_some(bytes) } - /// Starts this launch's marker in `dir` → the item a launch that is no longer running was - /// loading when it stopped, if one was (its marker is then removed, and this launch's marker - /// names the item until [`super::forget_previous`]). A folder that can't be written leaves this - /// launch without a marker; it still starts. - pub fn begin_launch(dir: &Path) -> Option { - let mut previous = None; + /// Starts this launch's marker in `dir` → the items a launch that is no longer running was + /// loading when it stopped, if it was loading any (its marker is then removed, and this + /// launch's marker names the items until [`super::forget_previous`]). A folder that can't be + /// written leaves this launch without a marker; it still starts. + pub fn begin_launch(dir: &Path) -> Vec { + let mut previous = Vec::new(); let mut tokens: Vec = std::fs::read_dir(dir) .into_iter() .flatten() @@ -569,8 +607,8 @@ mod marker { if running(dir, &token) { continue; } - if previous.is_none() { - previous = read(&json_path(dir, &token)).as_deref().and_then(parse_marker); + if previous.is_empty() { + previous = read(&json_path(dir, &token)).as_deref().map(parse_marker).unwrap_or_default(); } for path in [json_path(dir, &token), tmp_path(dir, &token), lock_path(dir, &token)] { let _ = std::fs::remove_file(path); @@ -588,32 +626,32 @@ mod marker { previous } - /// Replaces this launch's marker with one naming `item`: written to a temporary file first, + /// Replaces this launch's marker with one naming `items`: written to a temporary file first, /// then renamed over the marker, so a reader finds the old marker or the new one. A write that /// fails leaves the marker as it was. - pub(super) fn write(item: Option<&Item>) { + pub(super) fn write(items: &[Item]) { let current = CURRENT.lock().unwrap_or_else(|e| e.into_inner()); let Some(c) = current.as_ref() else { return }; let tmp = tmp_path(&c.dir, &c.token); let _ = File::create(&tmp) - .and_then(|mut f| f.write_all(&marker_bytes(item)).and_then(|()| f.sync_all())) + .and_then(|mut f| f.write_all(&marker_bytes(items)).and_then(|()| f.sync_all())) .and_then(|()| std::fs::rename(&tmp, json_path(&c.dir, &c.token))); } /// Removes this launch's marker: the app is quitting normally. While an item is still loading - /// ([`super::loading`] without [`super::loaded`]), the marker stays, naming the oldest one; - /// otherwise, while the user has not chosen what to do about [`super::previous`], the marker - /// stays, naming that, so the next launch asks. + /// ([`super::loading`] without [`super::loaded`]), the marker stays, naming the items still + /// loading; otherwise, while the user has not chosen what to do about [`super::previous`], the + /// marker stays, naming those, so the next launch asks. pub fn end_launch() { let running = LOADING.lock().unwrap_or_else(|e| e.into_inner()); let pending = running.pending(); - if pending.is_some() { - write(pending.as_ref()); + if !pending.is_empty() { + write(&pending); } let Some(c) = CURRENT.lock().unwrap_or_else(|e| e.into_inner()).take() else { return }; let Current { dir, token, _lock } = c; drop(_lock); - let marker = pending.is_none().then(|| json_path(&dir, &token)); + let marker = pending.is_empty().then(|| json_path(&dir, &token)); for path in marker.into_iter().chain([tmp_path(&dir, &token), lock_path(&dir, &token)]) { let _ = std::fs::remove_file(path); } @@ -629,6 +667,12 @@ mod marker { #[cfg(test)] pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(()); +/// Tests: the items still loading, oldest first. +#[cfg(test)] +pub(crate) fn still_loading() -> Vec { + LOADING.lock().unwrap_or_else(|e| e.into_inner()).items.iter().map(|(_, i)| i.clone()).collect() +} + #[cfg(test)] mod tests { use super::*; @@ -683,11 +727,18 @@ mod tests { assert_eq!(Item::file("C:\\Plug-ins\\x.wasm").label(), "x.wasm"); } + /// The items the marker at `path` names. + fn marker_at(path: &std::path::Path) -> Vec { + std::fs::read(path).ok().as_deref().map(parse_marker).unwrap_or_default() + } + #[test] fn only_a_marker_of_this_version_names_an_item() { let item = Item { id: Some("org.example.x".into()), file: Some("/p/x.wasm".into()), name: None }; - assert_eq!(parse_marker(&marker_bytes(Some(&item))), Some(item)); - assert_eq!(parse_marker(&marker_bytes(None)), None, "nothing was loading"); + assert_eq!(parse_marker(&marker_bytes(std::slice::from_ref(&item))), std::slice::from_ref(&item)); + assert_eq!(parse_marker(&marker_bytes(&[])), [], "nothing was loading"); + // A marker naming one item has no `items`, as before markers named several. + assert!(!String::from_utf8(marker_bytes(std::slice::from_ref(&item))).unwrap().contains("\"items\"")); for bad in [ &b""[..], b"{", @@ -698,13 +749,28 @@ mod tests { br#"{"format":"vectorcraft-launch","version":1,"item":{}}"#, br#"{"format":"vectorcraft-launch","version":1,"item":{"id":"x""#, ] { - assert_eq!(parse_marker(bad), None, "{}", String::from_utf8_lossy(bad)); + assert_eq!(parse_marker(bad), [], "{}", String::from_utf8_lossy(bad)); } let mut big = format!(r#"{{"format":"vectorcraft-launch","version":1,"item":{{"id":"{}"}}}}"#, "y".repeat(MAX_MARKER_BYTES as usize)).into_bytes(); - assert_eq!(parse_marker(&big), None, "larger than the limit"); + assert_eq!(parse_marker(&big), [], "larger than the limit"); big.truncate(10); - assert_eq!(parse_marker(&big), None, "cut short"); + assert_eq!(parse_marker(&big), [], "cut short"); + } + + #[test] + fn a_marker_names_every_item_up_to_its_limit() { + let field = |i: usize, tag: &str| format!("{tag}{i:04}{}", "\u{1}".repeat(MAX_FIELD_CHARS)); + let items: Vec = + (0..MAX_MARKER_ITEMS + 3).map(|i| Item { id: Some(field(i, "i")), file: Some(field(i, "f")), name: Some(field(i, "n")) }).collect(); + let bytes = marker_bytes(&items); + assert!(bytes.len() as u64 <= MAX_MARKER_BYTES, "{} bytes", bytes.len()); + let read = parse_marker(&bytes); + assert_eq!(read.len(), MAX_MARKER_ITEMS); + assert!(read.iter().zip(&items).all(|(r, i)| r.same(i)), "oldest first"); + // A marker whose `items` names nothing readable falls back to its `item`. + let x = br#"{"format":"vectorcraft-launch","version":1,"item":{"id":"x"},"items":[{},"y"]}"#; + assert_eq!(parse_marker(x), [Item { id: Some("x".into()), ..Item::default() }]); } #[test] @@ -714,23 +780,23 @@ mod tests { // A launch that stopped while loading x: its marker without a held lock, and a stray // temporary file from a write it didn't finish. let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) }; - std::fs::write(dir.join("launch-1-a.json"), marker_bytes(Some(&x))).unwrap(); + std::fs::write(dir.join("launch-1-a.json"), marker_bytes(std::slice::from_ref(&x))).unwrap(); std::fs::write(dir.join("launch-1-a.json.tmp"), b"{\"format\":\"vectorcr").unwrap(); - assert_eq!(begin_launch(&dir), Some(x.clone())); - assert_eq!(previous(), Some(x.clone())); + assert_eq!(begin_launch(&dir), std::slice::from_ref(&x)); + assert_eq!(previous(), std::slice::from_ref(&x)); assert!(!dir.join("launch-1-a.json").exists() && !dir.join("launch-1-a.json.tmp").exists(), "read once"); let mine = marker::path_of_current().unwrap(); - assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), Some(x.clone()), "named until the user chooses"); + assert_eq!(marker_at(&mine), std::slice::from_ref(&x), "named until the user chooses"); forget_previous(); - assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), None); + assert_eq!(marker_at(&mine), []); let token = loading(&x); - assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), Some(x.clone())); + assert_eq!(marker_at(&mine), std::slice::from_ref(&x)); assert!(!mine.with_extension("json.tmp").exists(), "the temporary file is renamed over the marker"); loaded(token); - assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), None); + assert_eq!(marker_at(&mine), []); end_launch(); assert!(!mine.exists(), "a normal quit removes the marker"); - assert_eq!(begin_launch(&dir), None, "nothing left behind"); + assert_eq!(begin_launch(&dir), [], "nothing left behind"); end_launch(); forget_previous(); let _ = std::fs::remove_dir_all(&dir); @@ -741,13 +807,13 @@ mod tests { let _f = fresh(); let dir = temp_dir("pending"); let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) }; - std::fs::write(dir.join("launch-1-a.json"), marker_bytes(Some(&x))).unwrap(); - assert_eq!(begin_launch(&dir), Some(x.clone())); + std::fs::write(dir.join("launch-1-a.json"), marker_bytes(std::slice::from_ref(&x))).unwrap(); + assert_eq!(begin_launch(&dir), std::slice::from_ref(&x)); end_launch(); - assert_eq!(begin_launch(&dir), Some(x.clone()), "asked again"); + assert_eq!(begin_launch(&dir), std::slice::from_ref(&x), "asked again"); forget_previous(); end_launch(); - assert_eq!(begin_launch(&dir), None, "once the user chose"); + assert_eq!(begin_launch(&dir), [], "once the user chose"); end_launch(); let _ = std::fs::remove_dir_all(&dir); } @@ -757,15 +823,15 @@ mod tests { let _f = fresh(); let dir = temp_dir("ends-loading"); let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) }; - assert_eq!(begin_launch(&dir), None); + assert_eq!(begin_launch(&dir), []); let token = loading(&x); // A panic the app caught while x loaded: the app quits without `loaded`. end_launch(); loaded(token); - assert_eq!(begin_launch(&dir), Some(x.clone()), "the next launch asks"); + assert_eq!(begin_launch(&dir), std::slice::from_ref(&x), "the next launch asks"); forget_previous(); end_launch(); - assert_eq!(begin_launch(&dir), None); + assert_eq!(begin_launch(&dir), []); end_launch(); let _ = std::fs::remove_dir_all(&dir); } @@ -776,22 +842,49 @@ mod tests { let dir = temp_dir("two-loading"); let a = Item { id: Some("org.example.a".into()), file: None, name: Some("A".into()) }; let b = Item { id: Some("org.example.b".into()), file: None, name: Some("B".into()) }; - assert_eq!(begin_launch(&dir), None); + assert_eq!(begin_launch(&dir), []); let mine = marker::path_of_current().unwrap(); - let marker = || std::fs::read(&mine).ok().as_deref().and_then(parse_marker); // Two threads run their plug-ins' first evaluations at once. let ta = loading(&a); let tb = loading(&b); - assert_eq!(marker(), Some(a.clone()), "the oldest item still loading"); + assert_eq!(marker_at(&mine), [a.clone(), b.clone()], "both items still loading, oldest first"); loaded(ta); - assert_eq!(marker(), Some(b.clone()), "b is still loading"); + assert_eq!(marker_at(&mine), std::slice::from_ref(&b), "b is still loading"); // The app stops while b loads. end_launch(); loaded(tb); - assert_eq!(begin_launch(&dir), Some(b.clone()), "the next launch offers b"); + assert_eq!(begin_launch(&dir), std::slice::from_ref(&b), "the next launch offers b"); forget_previous(); end_launch(); - assert_eq!(begin_launch(&dir), None); + assert_eq!(begin_launch(&dir), []); + end_launch(); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A launch that stops while two plug-ins load offers both at the next launch, until the user + /// chooses, however many launches that takes. + #[test] + fn a_launch_that_stops_while_two_plug_ins_load_offers_both() { + let _f = fresh(); + let dir = temp_dir("two-stopped"); + let a = Item { id: Some("org.example.a".into()), file: None, name: Some("A".into()) }; + let b = Item { id: Some("org.example.b".into()), file: None, name: Some("B".into()) }; + assert_eq!(begin_launch(&dir), []); + let ta = loading(&a); + let tb = loading(&b); + // The same plug-in loading twice is named once. + let ta2 = loading(&a); + end_launch(); + for t in [ta, tb, ta2] { + loaded(t); + } + assert_eq!(begin_launch(&dir), [a.clone(), b.clone()], "the next launch offers both"); + assert_eq!(previous(), [a.clone(), b.clone()]); + end_launch(); + assert_eq!(begin_launch(&dir), [a.clone(), b.clone()], "asked again"); + forget_previous(); + end_launch(); + assert_eq!(begin_launch(&dir), []); end_launch(); let _ = std::fs::remove_dir_all(&dir); } @@ -802,11 +895,11 @@ mod tests { let dir = temp_dir("long-path"); // Each character written as 6 or 2 bytes, so the item is far larger in JSON than in characters. let long = format!("C:\\{}\\x.wasm", "\u{1}é".repeat(700)); - assert_eq!(begin_launch(&dir), None); + assert_eq!(begin_launch(&dir), []); let token = loading(&Item::file(long.clone())); end_launch(); loaded(token); - let stopped = begin_launch(&dir).expect("the marker names the module"); + let stopped = begin_launch(&dir).into_iter().next().expect("the marker names the module"); assert!(stopped.same(&Item::file(long.clone())), "the stored item matches the full path"); disable(stopped); assert!(skipped(&Item::file(long.clone())), "Disable and Continue skips it"); @@ -891,14 +984,14 @@ mod tests { let _f = fresh(); let dir = temp_dir("running"); let x = Item { id: Some("org.example.x".into()), file: None, name: None }; - std::fs::write(dir.join("launch-9-b.json"), marker_bytes(Some(&x))).unwrap(); + std::fs::write(dir.join("launch-9-b.json"), marker_bytes(std::slice::from_ref(&x))).unwrap(); let lock = std::fs::File::create(dir.join("launch-9-b.lock")).unwrap(); lock.try_lock().unwrap(); - assert_eq!(begin_launch(&dir), None, "that launch is still running"); + assert_eq!(begin_launch(&dir), [], "that launch is still running"); assert!(dir.join("launch-9-b.json").exists()); end_launch(); drop(lock); - assert_eq!(begin_launch(&dir), Some(x), "once it stopped"); + assert_eq!(begin_launch(&dir), [x], "once it stopped"); end_launch(); forget_previous(); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..fd78584fa3 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -434,6 +434,18 @@ impl VectorcraftApp { crate::chrome::sync_window_title(self, ctx); crate::chrome::sync_fullscreen(self, ctx); self.drain_control(ctx); + // Plug-ins loading on other threads since launch install as their loads finish; until then + // the host keeps coming back to look again, and once more when the last one installs, for + // what waits for them. They install after the control requests are drained, so the frame + // after the last one opens the files held for them (the desktop app does that before this + // pass) before a control request waiting for them runs. + if self.session.plugins_loading() { + if self.session.poll_plugin_loads() { + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + } else { + ctx.request_repaint(); + } + } self.answer_pointer_replies(ctx); // An egui `PasteImage` with a rich system clipboard: run the paste command now, once. It // goes through `run`, whose `edit.paste` branch calls `adopt_system_clipboard` (which clears diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 5ef64dfa3f..87f04c0044 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -33,6 +33,15 @@ impl VectorcraftApp { ctx.request_repaint(); break; } + // An automation request sees every plug-in the launch loads: what it reads or writes + // (rendered artwork, file formats, effect lists) would otherwise depend on timing. It + // waits in the queue while the frames install them, so the window keeps drawing; one + // its caller gave up meanwhile is dropped below. + if self.session.plugins_loading() && !req.given_up() { + self.deferred_control = Some(req); + ctx.request_repaint(); + break; + } // Its caller stopped waiting (the app was busy or its window not drawn for too long) // and was told it won't run: an edit applied now would come from nowhere (#1725). if !req.claim() { diff --git a/crates/ui-egui/src/dialogs/safe_mode.rs b/crates/ui-egui/src/dialogs/safe_mode.rs index b26711c741..64cd7bb30e 100644 --- a/crates/ui-egui/src/dialogs/safe_mode.rs +++ b/crates/ui-egui/src/dialogs/safe_mode.rs @@ -11,8 +11,9 @@ use crate::VectorcraftApp; use crate::state::Dialog; use crate::theme::Tokens; -/// Dialog kind of the choice after a launch that stopped. Fields: `item` (`{id, file, name, label}`) -/// and `normal` (Start Normally instead of Disable and Continue). Cancel starts in Safe Mode. +/// Dialog kind of the choice after a launch that stopped. Fields: `items` (`[{id, file, name, +/// label}]`, the plug-ins that were loading, oldest first), `item` (the first of them) and +/// `normal` (Start Normally instead of Disable and Continue). Cancel starts in Safe Mode. pub const STOPPED: &str = "pluginStopped"; /// Dialog kind of Help › Safe Mode. Fields: `items` (`[{id, file, name, label, enable}]`, the @@ -21,17 +22,17 @@ pub const KIND: &str = "safeMode"; /// Before any plug-in loads (desktop): starts this launch's marker in `marker_dir` (none: no /// marker), and turns Safe Mode on for `--safe-mode` (`flag`), or until the user chooses after a -/// launch that stopped while a plug-in was loading → that plug-in, for [`after_start`]. With `flag` -/// nothing is asked, and the plug-in stays pending (`plugin.safeMode`'s `pendingItem`): the next -/// launch asks about it. +/// launch that stopped while plug-ins were loading → those plug-ins, for [`after_start`]. With +/// `flag` nothing is asked, and the plug-ins stay pending (`plugin.safeMode`'s `pendingItems`): the +/// next launch asks about them. #[cfg(not(target_arch = "wasm32"))] -pub fn begin_launch(marker_dir: Option<&std::path::Path>, flag: bool) -> Option { - let stopped = marker_dir.and_then(safe_mode::begin_launch); +pub fn begin_launch(marker_dir: Option<&std::path::Path>, flag: bool) -> Vec { + let stopped = marker_dir.map(safe_mode::begin_launch).unwrap_or_default(); if flag { safe_mode::set_active(Some(safe_mode::Source::Flag)); - return None; + return Vec::new(); } - if stopped.is_some() { + if !stopped.is_empty() { safe_mode::set_active(Some(safe_mode::Source::Startup)); } stopped @@ -45,29 +46,30 @@ pub fn end_launch() { /// Once the app is made: the choice about `stopped` ([`begin_launch`]), or in Safe Mode a status /// line saying so. -pub fn after_start(app: &mut VectorcraftApp, stopped: Option) { - match stopped { - Some(item) => ask_about_stopped(app, &item), - None if safe_mode::active() => app.status(vectorcraft_plugins::Error::SafeMode.to_string()), - None => {} +pub fn after_start(app: &mut VectorcraftApp, stopped: Vec) { + if !stopped.is_empty() { + ask_about_stopped(app, &stopped); + } else if safe_mode::active() { + app.status(vectorcraft_plugins::Error::SafeMode.to_string()); } } -/// Ask what to do about `item`, the plug-in the last launch was loading when it stopped. Safe Mode -/// is on until the user chooses. A dialog that takes the choice's place leaves it waiting: it opens -/// again once no dialog is open ([`reopen`]). -pub fn ask_about_stopped(app: &mut VectorcraftApp, item: &Item) { - let item = item.to_json(); - app.ui.stopped_plugin = Some(item.clone()); - app.ui.dialog = Some(Dialog::new(STOPPED, json!({ "item": item }))); +/// Ask what to do about `items`, the plug-ins the last launch was loading when it stopped. Safe +/// Mode is on until the user chooses. A dialog that takes the choice's place leaves it waiting: it +/// opens again once no dialog is open ([`reopen`]). +pub fn ask_about_stopped(app: &mut VectorcraftApp, items: &[Item]) { + let items: Vec = items.iter().map(Item::to_json).collect(); + let fields = json!({ "item": items.first(), "items": items }); + app.ui.stopped_plugin = Some(fields.clone()); + app.ui.dialog = Some(Dialog::new(STOPPED, fields)); } /// With no dialog open, the choice about a stopped plug-in that another dialog replaced opens again. pub(super) fn reopen(app: &mut VectorcraftApp) { if app.ui.dialog.is_none() - && let Some(item) = app.ui.stopped_plugin.clone() + && let Some(fields) = app.ui.stopped_plugin.clone() { - app.ui.dialog = Some(Dialog::new(STOPPED, json!({ "item": item }))); + app.ui.dialog = Some(Dialog::new(STOPPED, fields)); } } @@ -94,14 +96,33 @@ fn item_of(v: &Value) -> Item { Item { id: s("id"), file: s("file"), name: s("name") } } +/// The items the choice's fields name: its `items`, else its `item`. +fn stopped_items(fields: &serde_json::Map) -> Vec { + match fields.get("items").and_then(Value::as_array).filter(|i| !i.is_empty()) { + Some(items) => items.iter().map(item_of).collect(), + None => fields.get("item").filter(|i| i.is_object()).map(item_of).into_iter().collect(), + } +} + +/// How many plug-ins the waiting choice names. +fn stopped_count(app: &VectorcraftApp) -> usize { + app.ui.stopped_plugin.as_ref().and_then(Value::as_object).map_or(0, |f| stopped_items(f).len()) +} + /// The choice's Disable and Continue (OK) or Start Normally: Safe Mode ends and the plug-ins load, -/// without the stopped one for Disable and Continue (kept off for later launches too). +/// without the stopped ones for Disable and Continue (kept off for later launches too). fn confirm_stopped(app: &mut VectorcraftApp, d: &Dialog) -> Result { app.ui.dialog = None; app.ui.stopped_plugin = None; - let item = item_of(d.fields.get("item").unwrap_or(&Value::Null)); - // When the disabled plug-in can't be saved for the next launch, that launch asks again. - let saved = d.bool("normal") || (safe_mode::disable(item) && app.session.store_disabled_plugins()); + // When a disabled plug-in can't be saved for the next launch, that launch asks again. Every + // listed plug-in is turned off for this launch, whether or not the one before it was saved. + let saved = d.bool("normal") || { + let mut all = true; + for item in stopped_items(&d.fields) { + all &= safe_mode::disable(item); + } + all && app.session.store_disabled_plugins() + }; if saved { safe_mode::forget_previous(); } else { @@ -164,16 +185,32 @@ pub(super) const STOPPED_SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Safe Mode").into(), body: |_, ui, d| { let t = Tokens::get(ui.ctx()); - let name = item_of(d.fields.get("item").unwrap_or(&Value::Null)).label(); - let text = crate::i18n::fmt( - tl!("The last launch of VectorCraft stopped while the plug-in {name} was loading. It may not be what stopped it."), - &[("name", &name)], + let items = stopped_items(&d.fields); + if let [item] = items.as_slice() { + let text = crate::i18n::fmt( + tl!("The last launch of VectorCraft stopped while the plug-in {name} was loading. It may not be what stopped it."), + &[("name", &item.label())], + ); + ui.label(egui::RichText::new(text).color(t.text)); + return false; + } + ui.label( + egui::RichText::new(tl!( + "The last launch of VectorCraft stopped while these plug-ins were loading. Any one of them, or none, may be what stopped it." + )) + .color(t.text), ); - ui.label(egui::RichText::new(text).color(t.text)); + ui.add_space(6.0); + egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| { + for item in &items { + ui.label(egui::RichText::new(item.label()).color(t.text)); + } + }); false }, confirm: confirm_stopped, ok: Some("Disable and Continue"), + ok_label: Some(|app| if stopped_count(app) > 1 { "Disable Listed Plug-ins and Continue" } else { "Disable and Continue" }), cancel: Some("Start in Safe Mode"), alternate: Some(("Start Normally", "normal")), min_width: 380.0, diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..ceb32a262d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7723,6 +7723,10 @@ variable-list-end {0}, {1} {0} i {1} @msg vc_alloc returned 0 (out of memory) vc_alloc ha retornat 0 (sense memòria) @msg vc_alloc returned a block outside memory vc_alloc ha retornat un bloc fora de la memòria @msg vc_run returned error code {packed} vc_run ha retornat el codi d’error {packed} +@msg did not finish loading within {secs} s no ha acabat de carregar-se en {secs} s +@msg no thread was left to load it no ha quedat cap fil per carregar-lo +@msg panicked while loading ha fallat inesperadament en carregar-se +@msg panicked while loading: {what} ha fallat inesperadament en carregar-se: {what} @msg {_1} is not a file {_1} no és un fitxer @msg {_1} is {_2} bytes (limit {_3}) {_1} té {_2} bytes (límit {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} objectes (límit {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..0062ee8b1c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7334,6 +7334,10 @@ axis Y Axis osa Y @msg vc_alloc returned 0 (out of memory) vc_alloc vrátila 0 (nedostatek paměti) @msg vc_alloc returned a block outside memory vc_alloc vrátila blok mimo paměť @msg vc_run returned error code {packed} vc_run vrátila chybový kód {packed} +@msg did not finish loading within {secs} s nedokončil načítání do {secs} s +@msg no thread was left to load it nezbylo žádné vlákno, které by ho načetlo +@msg panicked while loading při načítání došlo k panice +@msg panicked while loading: {what} při načítání došlo k panice: {what} @msg {_1} is not a file {_1} není soubor @msg {_1} is {_2} bytes (limit {_3}) {_1} má {_2} bajtů (limit {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} objektů (limit {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..a3218b05fc 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -564,6 +564,10 @@ liquify-list-end {0}, {1} {0} og {1} @msg vc_alloc returned 0 (out of memory) vc_alloc returnerede 0 (ikke mere hukommelse) @msg vc_alloc returned a block outside memory vc_alloc returnerede en blok uden for hukommelsen @msg vc_run returned error code {packed} vc_run returnerede fejlkoden {packed} +@msg did not finish loading within {secs} s blev ikke færdig med at indlæse inden for {secs} s +@msg no thread was left to load it der var ingen tråd tilbage til at indlæse den +@msg panicked while loading gik ned under indlæsningen +@msg panicked while loading: {what} gik ned under indlæsningen: {what} @msg {_1} is not a file {_1} er ikke en fil @msg {_1} is {_2} bytes (limit {_3}) {_1} fylder {_2} byte (grænse {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} objekter (grænse {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..df249b18a3 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6917,6 +6917,10 @@ axis Y Axis Y-Achse @msg vc_alloc returned 0 (out of memory) vc_alloc hat 0 zurückgegeben (kein Speicher mehr) @msg vc_alloc returned a block outside memory vc_alloc hat einen Block außerhalb des Speichers zurückgegeben @msg vc_run returned error code {packed} vc_run hat den Fehlercode {packed} zurückgegeben +@msg did not finish loading within {secs} s wurde nicht innerhalb von {secs} s fertig geladen +@msg no thread was left to load it es war kein Thread mehr frei, um es zu laden +@msg panicked while loading ist beim Laden abgestürzt +@msg panicked while loading: {what} ist beim Laden abgestürzt: {what} @msg {_1} is not a file {_1} ist keine Datei @msg {_1} is {_2} bytes (limit {_3}) {_1} ist {_2} Byte groß (Grenze {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} Objekte (Grenze {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..f5fdf14278 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7323,6 +7323,10 @@ axis Y Axis Άξονας Y @msg vc_alloc returned 0 (out of memory) η vc_alloc επέστρεψε 0 (η μνήμη εξαντλήθηκε) @msg vc_alloc returned a block outside memory η vc_alloc επέστρεψε ένα μπλοκ εκτός μνήμης @msg vc_run returned error code {packed} η vc_run επέστρεψε τον κωδικό σφάλματος {packed} +@msg did not finish loading within {secs} s δεν ολοκλήρωσε τη φόρτωση μέσα σε {secs} s +@msg no thread was left to load it δεν έμεινε νήμα για να το φορτώσει +@msg panicked while loading κατέρρευσε κατά τη φόρτωση +@msg panicked while loading: {what} κατέρρευσε κατά τη φόρτωση: {what} @msg {_1} is not a file το {_1} δεν είναι αρχείο @msg {_1} is {_2} bytes (limit {_3}) το {_1} έχει {_2} byte (όριο {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} αντικείμενα (όριο {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..2966e0b8f8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7309,6 +7309,10 @@ axis Y Axis Eje Y @msg vc_alloc returned 0 (out of memory) vc_alloc devolvió 0 (sin memoria) @msg vc_alloc returned a block outside memory vc_alloc devolvió un bloque fuera de la memoria @msg vc_run returned error code {packed} vc_run devolvió el código de error {packed} +@msg did not finish loading within {secs} s no terminó de cargarse en {secs} s +@msg no thread was left to load it no quedó ningún hilo para cargarlo +@msg panicked while loading falló de forma inesperada al cargarse +@msg panicked while loading: {what} falló de forma inesperada al cargarse: {what} @msg {_1} is not a file {_1} no es un archivo @msg {_1} is {_2} bytes (limit {_3}) {_1} ocupa {_2} bytes (límite {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} objetos (límite {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..293b719ccf 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7400,6 +7400,10 @@ axis Y Axis Y-akseli @msg vc_alloc returned 0 (out of memory) vc_alloc palautti 0 (muisti loppui) @msg vc_alloc returned a block outside memory vc_alloc palautti lohkon muistin ulkopuolelta @msg vc_run returned error code {packed} vc_run palautti virhekoodin {packed} +@msg did not finish loading within {secs} s ei latautunut loppuun {secs} sekunnissa +@msg no thread was left to load it sen lataamiseen ei jäänyt yhtään säiettä +@msg panicked while loading kaatui latauksen aikana +@msg panicked while loading: {what} kaatui latauksen aikana: {what} @msg {_1} is not a file {_1} ei ole tiedosto @msg {_1} is {_2} bytes (limit {_3}) {_1} on {_2} tavua (raja {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} objektia (raja {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..279816abc8 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7330,6 +7330,10 @@ axis Y Axis Axe Y @msg vc_alloc returned 0 (out of memory) vc_alloc a renvoyé 0 (mémoire épuisée) @msg vc_alloc returned a block outside memory vc_alloc a renvoyé un bloc hors de la mémoire @msg vc_run returned error code {packed} vc_run a renvoyé le code d’erreur {packed} +@msg did not finish loading within {secs} s n’a pas fini de se charger en {secs} s +@msg no thread was left to load it aucun fil d’exécution n’était libre pour le charger +@msg panicked while loading a planté pendant le chargement +@msg panicked while loading: {what} a planté pendant le chargement ({what}) @msg {_1} is not a file {_1} n’est pas un fichier @msg {_1} is {_2} bytes (limit {_3}) {_1} fait {_2} octets (limite {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} objets (limite {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..e2c23a2e4c 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9787,6 +9787,10 @@ variable-list-end {0}, {1} {0} और {1} @msg vc_alloc returned 0 (out of memory) vc_alloc ने 0 लौटाया (मेमोरी खत्म) @msg vc_alloc returned a block outside memory vc_alloc ने मेमोरी के बाहर का ब्लॉक लौटाया @msg vc_run returned error code {packed} vc_run ने त्रुटि कोड {packed} लौटाया +@msg did not finish loading within {secs} s {secs} सेकंड के भीतर लोड होना पूरा नहीं हुआ +@msg no thread was left to load it इसे लोड करने के लिए कोई थ्रेड नहीं बचा +@msg panicked while loading लोड होते समय क्रैश हो गया +@msg panicked while loading: {what} लोड होते समय क्रैश हो गया: {what} @msg VectorCraft doesn't search other apps' or the system's folders: {path} वेक्टर क्रेफ्ट अन्य एप्लिकेशन या सिस्टम के फ़ोल्डर्स की खोज नहीं करता है: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} वेक्टर क्रेफ्ट उपयोगकर्ताओं में साझा या सार्वजनिक फ़ोल्डर की खोज नहीं करता है: {path} @msg VectorCraft failed to start: {e} वेक्टर क्रेफ्ट शुरू करने में विफल रहा: {e} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..bc02c85e91 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7319,6 +7319,10 @@ axis Y Axis Y tengely @msg vc_alloc returned 0 (out of memory) a vc_alloc 0-t adott vissza (elfogyott a memória) @msg vc_alloc returned a block outside memory a vc_alloc a memórián kívüli blokkot adott vissza @msg vc_run returned error code {packed} a vc_run {packed} hibakódot adott vissza +@msg did not finish loading within {secs} s nem töltődött be {secs} másodpercen belül +@msg no thread was left to load it nem maradt szál a betöltéséhez +@msg panicked while loading összeomlott betöltés közben +@msg panicked while loading: {what} összeomlott betöltés közben: {what} @msg {_1} is not a file nem fájl: {_1} @msg {_1} is {_2} bytes (limit {_3}) {_1}: {_2} bájt (korlát: {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} objektum (korlát: {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..4d763e814f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -447,6 +447,10 @@ @msg vc_alloc returned 0 (out of memory) vc_alloc mengembalikan 0 (memori habis) @msg vc_alloc returned a block outside memory vc_alloc mengembalikan blok di luar memori @msg vc_run returned error code {packed} vc_run mengembalikan kode galat {packed} +@msg did not finish loading within {secs} s tidak selesai dimuat dalam {secs} detik +@msg no thread was left to load it tidak ada utas tersisa untuk memuatnya +@msg panicked while loading mogok saat dimuat +@msg panicked while loading: {what} mogok saat dimuat: {what} @msg {_1} is not a file {_1} bukan berkas @msg {_1} is {_2} bytes (limit {_3}) {_1} berukuran {_2} byte (batas {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} objek (batas {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..1194da4f02 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6956,6 +6956,10 @@ axis Y Axis Asse Y @msg vc_alloc returned 0 (out of memory) vc_alloc ha restituito 0 (memoria esaurita) @msg vc_alloc returned a block outside memory vc_alloc ha restituito un blocco fuori dalla memoria @msg vc_run returned error code {packed} vc_run ha restituito il codice di errore {packed} +@msg did not finish loading within {secs} s non ha finito di caricarsi entro {secs} s +@msg no thread was left to load it non è rimasto alcun thread per caricarlo +@msg panicked while loading si è arrestato in modo anomalo durante il caricamento +@msg panicked while loading: {what} si è arrestato in modo anomalo durante il caricamento: {what} @msg {_1} is not a file {_1} non è un file @msg {_1} is {_2} bytes (limit {_3}) {_1} occupa {_2} byte (limite {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} oggetti (limite {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..9238c8edfa 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7031,6 +7031,10 @@ axis Y Axis Y 軸 @msg vc_alloc returned 0 (out of memory) vc_alloc が 0 を返しました (メモリ不足) @msg vc_alloc returned a block outside memory vc_alloc がメモリの外のブロックを返しました @msg vc_run returned error code {packed} vc_run がエラーコード {packed} を返しました +@msg did not finish loading within {secs} s {secs} 秒以内に読み込みが完了しませんでした +@msg no thread was left to load it 読み込むためのスレッドが残っていませんでした +@msg panicked while loading 読み込み中にパニックが発生しました +@msg panicked while loading: {what} 読み込み中にパニックが発生しました: {what} @msg {_1} is not a file {_1} はファイルではありません @msg {_1} is {_2} bytes (limit {_3}) {_1} は {_2} バイトです (上限 {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) オブジェクトが {_1} 個あります (上限 {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..1dc0906c4e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9436,6 +9436,10 @@ axis Y Axis Y ღერძი @msg vc_alloc returned 0 (out of memory) vc_alloc-მა დააბრუნა 0 (მეხსიერება ამოიწურა) @msg vc_alloc returned a block outside memory vc_alloc-მა დააბრუნა ბლოკი მეხსიერების გარეთ @msg vc_run returned error code {packed} vc_run-მა დააბრუნა შეცდომის კოდი {packed} +@msg did not finish loading within {secs} s ჩატვირთვა {secs} წამში არ დასრულდა +@msg no thread was left to load it მის ჩასატვირთად ნაკადი აღარ დარჩა +@msg panicked while loading ჩატვირთვისას ავარიულად შეწყდა +@msg panicked while loading: {what} ჩატვირთვისას ავარიულად შეწყდა: {what} @msg {_1} is not a file {_1} ფაილი არ არის @msg {_1} is {_2} bytes (limit {_3}) {_1} {_2} ბაიტია (ლიმიტი {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} ობიექტი (ლიმიტი {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..56aa08ba9f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6928,6 +6928,10 @@ axis Y Axis Y축 @msg vc_alloc returned 0 (out of memory) vc_alloc이 0을 반환했습니다(메모리 부족) @msg vc_alloc returned a block outside memory vc_alloc이 메모리 밖의 블록을 반환했습니다 @msg vc_run returned error code {packed} vc_run이 오류 코드 {packed}을(를) 반환했습니다 +@msg did not finish loading within {secs} s {secs}초 안에 로드를 마치지 못했습니다 +@msg no thread was left to load it 로드할 스레드가 남아 있지 않았습니다 +@msg panicked while loading 로드하는 중에 비정상 종료되었습니다 +@msg panicked while loading: {what} 로드하는 중에 비정상 종료되었습니다: {what} @msg {_1} is not a file {_1}은(는) 파일이 아닙니다 @msg {_1} is {_2} bytes (limit {_3}) {_1}이(가) {_2}바이트입니다(한도 {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) 개체 {_1}개(한도 {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..783f500219 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -411,6 +411,10 @@ liquify-list-end {0}, {1} {0} en {1} @msg vc_alloc returned 0 (out of memory) vc_alloc gaf 0 terug (onvoldoende geheugen) @msg vc_alloc returned a block outside memory vc_alloc gaf een blok buiten het geheugen terug @msg vc_run returned error code {packed} vc_run gaf foutcode {packed} terug +@msg did not finish loading within {secs} s was niet binnen {secs} s klaar met laden +@msg no thread was left to load it er was geen thread meer over om het te laden +@msg panicked while loading is tijdens het laden gecrasht +@msg panicked while loading: {what} is tijdens het laden gecrasht: {what} @msg {_1} is not a file {_1} is geen bestand @msg {_1} is {_2} bytes (limit {_3}) {_1} is {_2} bytes (limiet {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} objecten (limiet {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..397a53e9e6 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7189,6 +7189,10 @@ axis Y Axis Oś Y @msg vc_alloc returned 0 (out of memory) vc_alloc zwróciła 0 (brak pamięci) @msg vc_alloc returned a block outside memory vc_alloc zwróciła blok poza pamięcią @msg vc_run returned error code {packed} vc_run zwróciła kod błędu {packed} +@msg did not finish loading within {secs} s nie zakończył wczytywania w ciągu {secs} s +@msg no thread was left to load it nie został żaden wątek, który mógłby go wczytać +@msg panicked while loading uległ awarii podczas wczytywania +@msg panicked while loading: {what} uległ awarii podczas wczytywania: {what} @msg {_1} is not a file {_1} nie jest plikiem @msg {_1} is {_2} bytes (limit {_3}) {_1} ma {_2} bajtów (limit {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} obiektów (limit {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..b72cdb27ae 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7233,6 +7233,10 @@ axis Y Axis Eixo Y @msg vc_alloc returned 0 (out of memory) vc_alloc retornou 0 (sem memória) @msg vc_alloc returned a block outside memory vc_alloc retornou um bloco fora da memória @msg vc_run returned error code {packed} vc_run retornou o código de erro {packed} +@msg did not finish loading within {secs} s não terminou de carregar em {secs} s +@msg no thread was left to load it não restou nenhuma thread para carregá-lo +@msg panicked while loading falhou inesperadamente ao carregar +@msg panicked while loading: {what} falhou inesperadamente ao carregar: {what} @msg {_1} is not a file {_1} não é um arquivo @msg {_1} is {_2} bytes (limit {_3}) {_1} tem {_2} bytes (limite {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} objetos (limite {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..ac3229de3c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6955,6 +6955,10 @@ axis Y Axis Ось Y @msg vc_alloc returned 0 (out of memory) vc_alloc вернула 0 (нехватка памяти) @msg vc_alloc returned a block outside memory vc_alloc вернула блок вне памяти @msg vc_run returned error code {packed} vc_run вернула код ошибки {packed} +@msg did not finish loading within {secs} s не завершил загрузку за {secs} с +@msg no thread was left to load it не осталось потока, чтобы его загрузить +@msg panicked while loading аварийно завершился при загрузке +@msg panicked while loading: {what} аварийно завершился при загрузке: {what} @msg {_1} is not a file {_1} не является файлом @msg {_1} is {_2} bytes (limit {_3}) {_1} занимает {_2} байт (предел {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) объектов: {_1} (предел {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..bc99b69b0d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -10099,6 +10099,10 @@ digits Hindi Hindi @msg vc_alloc returned 0 (out of memory) vc_alloc returnerade 0 (slut på minne) @msg vc_alloc returned a block outside memory vc_alloc returnerade ett block utanför minnet @msg vc_run returned error code {packed} vc_run returnerade felkoden {packed} +@msg did not finish loading within {secs} s blev inte färdigläst inom {secs} s +@msg no thread was left to load it ingen tråd fanns kvar som kunde läsa in den +@msg panicked while loading kraschade under inläsningen +@msg panicked while loading: {what} kraschade under inläsningen: {what} @msg view is required view krävs @msg view must be one of {_1} view måste vara något av {_1} @msg warpStyle can only edit an applied Warp effect warpStyle kan bara redigera en tillämpad Förvräng-effekt diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..7a6a658d0b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7406,6 +7406,10 @@ axis Y Axis Y ekseni @msg vc_alloc returned 0 (out of memory) vc_alloc 0 döndürdü (bellek yetersiz) @msg vc_alloc returned a block outside memory vc_alloc bellek dışında bir blok döndürdü @msg vc_run returned error code {packed} vc_run {packed} hata kodunu döndürdü +@msg did not finish loading within {secs} s {secs} sn içinde yüklenmeyi bitirmedi +@msg no thread was left to load it onu yükleyecek iş parçacığı kalmadı +@msg panicked while loading yüklenirken çöktü +@msg panicked while loading: {what} yüklenirken çöktü: {what} @msg {_1} is not a file {_1} bir dosya değil @msg {_1} is {_2} bytes (limit {_3}) {_1} {_2} bayt (sınır {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} nesne (sınır {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..fc7707bc0c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6938,6 +6938,10 @@ axis Y Axis Вісь Y @msg vc_alloc returned 0 (out of memory) vc_alloc повернула 0 (бракує пам’яті) @msg vc_alloc returned a block outside memory vc_alloc повернула блок поза пам’яттю @msg vc_run returned error code {packed} vc_run повернула код помилки {packed} +@msg did not finish loading within {secs} s не завершив завантаження за {secs} с +@msg no thread was left to load it не залишилося потоку, щоб його завантажити +@msg panicked while loading аварійно завершився під час завантаження +@msg panicked while loading: {what} аварійно завершився під час завантаження: {what} @msg {_1} is not a file {_1} не є файлом @msg {_1} is {_2} bytes (limit {_3}) {_1} займає {_2} байтів (межа {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) об’єктів: {_1} (межа {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..5412659c05 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6984,6 +6984,10 @@ axis Y Axis Trục Y @msg vc_alloc returned 0 (out of memory) vc_alloc trả về 0 (hết bộ nhớ) @msg vc_alloc returned a block outside memory vc_alloc trả về một khối nằm ngoài bộ nhớ @msg vc_run returned error code {packed} vc_run trả về mã lỗi {packed} +@msg did not finish loading within {secs} s không tải xong trong vòng {secs} giây +@msg no thread was left to load it không còn luồng nào để tải nó +@msg panicked while loading gặp sự cố khi đang tải +@msg panicked while loading: {what} gặp sự cố khi đang tải: {what} @msg {_1} is not a file {_1} không phải là tệp @msg {_1} is {_2} bytes (limit {_3}) {_1} có {_2} byte (giới hạn {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} đối tượng (giới hạn {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..874555f6aa 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7166,6 +7166,10 @@ axis Y Axis Y 轴 @msg vc_alloc returned 0 (out of memory) vc_alloc 返回了 0(内存不足) @msg vc_alloc returned a block outside memory vc_alloc 返回了内存之外的块 @msg vc_run returned error code {packed} vc_run 返回了错误代码 {packed} +@msg did not finish loading within {secs} s 未在 {secs} 秒内完成加载 +@msg no thread was left to load it 没有剩余的线程来加载它 +@msg panicked while loading 加载时崩溃 +@msg panicked while loading: {what} 加载时崩溃:{what} @msg {_1} is not a file {_1} 不是文件 @msg {_1} is {_2} bytes (limit {_3}) {_1} 为 {_2} 字节(上限 {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} 个对象(上限 {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..7184b246ae 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6987,6 +6987,10 @@ axis Y Axis Y 軸 @msg vc_alloc returned 0 (out of memory) vc_alloc 傳回了 0(記憶體不足) @msg vc_alloc returned a block outside memory vc_alloc 傳回了記憶體之外的區塊 @msg vc_run returned error code {packed} vc_run 傳回了錯誤代碼 {packed} +@msg did not finish loading within {secs} s 未在 {secs} 秒內完成載入 +@msg no thread was left to load it 沒有剩餘的執行緒可以載入它 +@msg panicked while loading 載入時當機 +@msg panicked while loading: {what} 載入時當機:{what} @msg {_1} is not a file {_1} 不是檔案 @msg {_1} is {_2} bytes (limit {_3}) {_1} 為 {_2} 位元組(上限 {_3}) @msg {_1} objects (limit {MAX_OBJECTS}) {_1} 個物件(上限 {MAX_OBJECTS}) diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index bacfd0f554..a646d55383 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -70,6 +70,8 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option Result { // Automation confined to some folders reaches no file outside them, open in a tab or not. vectorcraft_engine::file_access::check_read(path)?; + // A plug-in still loading may be the importer that reads the file, or what installs it. + app.session.finish_plugin_loads(); // File › Open, Open Recent, the Home screen, a drop and the Finder all focus a document that // is already open, or still being read, instead of opening a second copy. While a dialog or // a drag acts on the active document, its tab comes to the front once that ends diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 7186f0707d..040f4cbcd9 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -175,6 +175,12 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) { // (Recolor Artwork), opens on the art as the gesture left it. let r = app.session.finish_tool_edit(); crate::canvas::apply_requests(app, r); + // So do the plug-ins the launch is still loading, for a command chosen meanwhile that the + // engine holds until they install (a plug-in's own command, one that may edit); view commands + // and queries go ahead. + if vectorcraft_engine::waits_for_plugin_loads(id) { + app.session.finish_plugin_loads(); + } // A shortcut or a palette pick on a filter plug-in does nothing while its menu item is dimmed. if id == "plugin.dialog" && !enabled(app, id) { return; diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 5b4c8619ee..714e241f86 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -73,6 +73,8 @@ pub fn start(app: &mut VectorcraftApp, path: &str, bytes: Vec) -> Result, params: Value) -> Result> { + // A plug-in still loading may be the importer that reads the file. + app.session.finish_plugin_loads(); let (tx, done) = channel(); let bytes = Arc::new(bytes); let (name, file) = (path.to_string(), bytes.clone()); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f8bce4e088..039311d63c 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -894,8 +894,9 @@ pub struct UiState { /// place, [`crate::dialogs::settle`] puts the document back at the front of `pending_fonts`. #[serde(skip)] pub fonts_dialog: Option, - /// The plug-in (`{id, file, name, label}`) the last launch was loading when it stopped, while - /// the user has not chosen what to do about it. When another dialog takes the choice's place, + /// The fields of the choice about the plug-ins the last launch was loading when it stopped + /// (`{item, items}`, each `{id, file, name, label}`), while the user has not chosen what to do + /// about them. When another dialog takes the choice's place, /// [`crate::dialogs::settle`] opens the choice again once no dialog is open. #[serde(skip)] pub stopped_plugin: Option, diff --git a/crates/ui-egui/tests/safe_mode.rs b/crates/ui-egui/tests/safe_mode.rs index 246352e469..76bab86dca 100644 --- a/crates/ui-egui/tests/safe_mode.rs +++ b/crates/ui-egui/tests/safe_mode.rs @@ -137,6 +137,45 @@ fn disable_and_continue_loads_every_plug_in_but_the_one_that_was_loading() { let _ = std::fs::remove_dir_all(&dir); } +/// A marker left by a launch that stopped while the stored plug-ins x and y were both loading. +fn stopped_while_loading_both(launch: &Path, dir: &Path) { + let file = |tag: &str| { + let p = std::fs::read_dir(dir).unwrap().flatten().map(|e| e.path()).find(|p| p.to_string_lossy().contains(tag)).unwrap(); + json!({"file": p.display().to_string()}) + }; + let (x, y) = (file("test_ui_x"), file("test_ui_y")); + let marker = json!({"format": "vectorcraft-launch", "version": 1, "item": x, "items": [x, y]}); + std::fs::create_dir_all(launch).unwrap(); + std::fs::write(launch.join("launch-1-dead.json"), marker.to_string()).unwrap(); +} + +#[test] +fn a_launch_that_stopped_while_two_plug_ins_loaded_offers_to_disable_both() { + let _f = fresh(); + let dir = store_with_two("both"); + let launch_dir = dir.join("Launch"); + stopped_while_loading_both(&launch_dir, &dir); + let mut app = launch(&dir, &launch_dir, false); + assert_eq!(kind(&app), Some(ui::STOPPED)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["items"].as_array().map(Vec::len), Some(2), "both are listed"); + let state = app.run("plugin.safeMode", json!({})).unwrap(); + assert_eq!(state["pendingItems"].as_array().map(Vec::len), Some(2), "{state}"); + assert_eq!(state["pendingItem"], state["pendingItems"][0]); + frame(&mut app); + // Start in Safe Mode leaves both to the next launch. + dialogs::cancel(&mut app); + ui::end_launch(); + safe_mode::set_active(None); + let mut app = launch(&dir, &launch_dir, false); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["items"].as_array().map(Vec::len), Some(2), "both asked again"); + dialogs::confirm(&mut app).unwrap(); + assert!(!safe_mode::active() && safe_mode::previous().is_empty()); + assert!(registry::get("test.ui.x").is_none() && registry::get("test.ui.y").is_none(), "both are off"); + assert_eq!(safe_mode::disabled().len(), 2, "both kept off at later launches"); + done(&launch_dir); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn start_normally_loads_everything_and_start_in_safe_mode_loads_nothing() { let _f = fresh(); @@ -180,7 +219,7 @@ fn a_disabled_list_that_cannot_be_saved_says_so() { let mut app = launch(&dir, &launch_dir, false); dialogs::confirm(&mut app).unwrap(); assert_eq!(app.ui.status, unsaved, "Disable and Continue"); - assert!(safe_mode::previous().is_some(), "the next launch asks again"); + assert!(!safe_mode::previous().is_empty(), "the next launch asks again"); assert!(registry::get("test.ui.x").is_none(), "this launch still skips it"); app.ui.status.clear(); app.run("help.safeMode", json!({})).unwrap(); @@ -275,7 +314,7 @@ fn a_safe_mode_flag_launch_leaves_the_stopped_plug_in_to_the_next_launch() { stopped_while_loading_x(&launch_dir, &dir); let app = launch(&dir, &launch_dir, true); assert!(kind(&app).is_none() && registry::list().is_empty(), "--safe-mode asks nothing"); - assert!(safe_mode::previous().is_some(), "the plug-in is still pending"); + assert!(!safe_mode::previous().is_empty(), "the plug-in is still pending"); ui::end_launch(); safe_mode::set_active(None); diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..a7bea5799e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -301,7 +301,7 @@ the suite) keep the agent to the folders you give it: outside the read roots, also those the person or an earlier request put there. In `plugin.list`, the plug-in folder last loaded is `null` in `folder.folder`, and a failed file in `folder.failed` and a plug-in's `source` (also in `plugin.info`) are named by their file name, in the errors too. A plug-in turned off for the next - launch (`disabled`, and `pendingItem` in `plugin.safeMode`) has a file outside the read roots named by its file + launch (`disabled`, and `pendingItem` and `pendingItems` in `plugin.safeMode`) has a file outside the read roots named by its file name. `plugin.setEnabled {file}` takes that name, and a plug-in's `source` name, when no other listed file has it. In `file.recovery.list` and `file.recovery.restore`, a document's original file in `path` is `null`, and so is the recovery folder in `location` (`file.recovery.save` @@ -13264,8 +13264,9 @@ commands, `ids` left out or null means the selection, and an `ids` that is not a Safe Mode starts VectorCraft without plug-ins: `vectorcraft --safe-mode`, `vectorcraft-cli --safe-mode `, or the choice the desktop app offers when the last launch stopped while a plug-in was loading (Disable and Continue, Start -Normally, Start in Safe Mode). It names that plug-in without saying it caused the stop. Until the user picks Disable and -Continue or Start Normally, the next launch asks again, also after a `--safe-mode` launch, which asks nothing. +Normally, Start in Safe Mode). It names that plug-in without saying it caused the stop. When several plug-ins were +loading at once, it lists all of them, and Disable Listed Plug-ins and Continue turns off every one. Until the user picks +Disable and Continue or Start Normally, the next launch asks again, also after a `--safe-mode` launch, which asks nothing. `vectorcraft --safe-mode` opens its files in a window of its own, and on Windows and Linux a file opened from the file manager while the app is in Safe Mode starts a window with plug-ins. Files given on the command line, or opened from the file manager while the choice is up, open after the user picks. On Windows and Linux, when the choice is Start in Safe @@ -13278,7 +13279,7 @@ error and changes nothing when an object it would expand holds such an effect, i plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. `vectorcraft` rejects an option it does not know (such as `--safe-mod`) instead of opening it as a file; `--` before a file name that starts with `-` opens it. The web build keeps no installed plug-ins from one page load to the next and has no launch marker, so it never offers the choice. `plugin.safeMode` returns `{active, source, disabled, -pendingItem}`; a command does not turn Safe Mode on or off. `plugin.setEnabled {id | file, enabled}` turns a plug-in on or +pendingItem, pendingItems}` (`pendingItems` lists every plug-in the choice names, and `pendingItem` is the first); a command does not turn Safe Mode on or off. `plugin.setEnabled {id | file, enabled}` turns a plug-in on or off for the next launch, as Help › Safe Mode's Enable on Re-launch does; it does not load, unload or uninstall anything now, and `plugin.install` of a disabled plug-in turns it on. Turning a plug-in on by `id` or by installing it also turns on the file it is stored in, which names it when it stopped a launch while loading; when the new version can't be saved diff --git a/docs/plugins.md b/docs/plugins.md index 7e6dd26185..81e7f56af0 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -113,6 +113,19 @@ most 1,000 `.wasm` files, the first ones by file name (VectorCraft's own limit); (`leftOut`). An entry that is not a regular file, such as a subfolder or a named pipe with a `.wasm` name, is listed in the report and skipped, and the load does not wait on a named pipe. +**Loading.** On the desktop, the plug-ins in the `Plug-ins` folder and the Additional Plug-ins Folder load on up to four +worker threads and install in file-name order, whatever order their loads finish in; at most eight loaded modules wait +to be installed at once. When the desktop app starts, its window shows while they load, and they install as their loads +finish. Plug-in commands, commands that edit a document, exports, control-channel requests and files opened at launch +wait for them first; view commands and queries chosen from a menu do not. Until then a live effect whose plug-in is still loading is drawn as if it weren't +there, and another window's `plugin.list` reports the folder as `{"folder", "loading": true}`. A folder set later in +Preferences, `vectorcraft-cli` and `plugin.reload` wait for the loads before they go on. A module whose load panics, +or whose load takes 10 s or longer (VectorCraft's own limit), is reported as failed or skipped with a log record, and +the others install. The launch marker names every module still loading, so when the app stops during the loads, the +next launch's Safe Mode choice lists all of them. A module whose load panicked or failed is no longer named; one past +its 10 s limit is named until its load returns. A module is also skipped when the plug-in with its id was installed or removed in another window while it loaded. The +web build loads one module at a time. + Plug-ins are installed **per process**, not per document. Documents store a live effect as an ordinary effect record (`{"id": "plugin.", "params": {…}}`): while the plug-in is installed it is drawn, exported and expanded; without it the object is drawn as if the effect weren't there, and the record is kept for when the plug-in comes back. From 48e38cdd624ac7175eed197f65fd29050810d18c Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Sun, 22 Nov 2026 12:40:37 +0500 Subject: [PATCH 25/55] docs: ROADMAP Upcoming names G11's remaining bugs (#8314) Shape Builder regions (#937) and Asset Export borders (#983, #1037) are fixed; the item now names what docs/roadmap.md keeps (#864's unit preference, #885) with its 6-13 h estimate. --- ROADMAP.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 90a6100167..83c2ab14c2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-22 · **Change:** minor (Upcoming: G11 names what is left (#864's unit preference, #885), not the fixed Shape Builder regions and Asset Export borders, with docs/roadmap.md's 6–13 h, #8314; previously: G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -119,7 +119,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap 1. **Interaction-fidelity pass** (G1), tool by tool from [ui-parity.md](docs/ui-parity.md): 60–90 h. 2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h. 3. **Launch and stability on real machines** (G10): 20–35 h. -4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h. +4. **Core-tool correctness** (G11: the unit preference reverting to points, #864, SVG export units fixed; a Transform effect in a fill's or stroke's own effects, #885; Shape Builder regions and Asset Export borders are fixed): 6–13 h. 5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2). ## Progress log @@ -249,6 +249,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. Headline numbers unchanged. | | 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. | From 194cd7972b50696c2228040c30290f2606703588 Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Sun, 22 Nov 2026 12:47:12 +0500 Subject: [PATCH 26/55] docs: Essentials row names Shape Builder's remaining depth (#8314) --- ROADMAP.md | 6 +++--- docs/target-app-parity.md | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 83c2ab14c2..ccb24094d0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-22 · **Change:** minor (Upcoming: G11 names what is left (#864's unit preference, #885), not the fixed Shape Builder regions and Asset Export borders, with docs/roadmap.md's 6–13 h, #8314; previously: G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-22 · **Change:** minor (Upcoming: G11 names what is left (#864's unit preference, #885), not the fixed Shape Builder regions and Asset Export borders, with docs/roadmap.md's 6–13 h, and the Essentials row names Shape Builder's remaining depth, #8314; previously: G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -35,7 +35,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). |---|---:|---:|---:|---| | **Full Illustrator** (ready for real work; decides the stage) | **~62%** (57–67%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (50–85 h) and ecosystem | | **Mainstream illustrator** | **~65%** (60–70%) | **~230–380 h** | ~65–110 h | the interaction-fidelity pass (60–90 h), hardening and QA (30–50 h), stability (20–35 h), performance budgets (15–25 h), `.ai` exchange (10–20 h), the remaining depth of the everyday areas | -| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder regions (4–8 h), UI polish | +| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish | Hours are Opus 5.5 agent wall-clock hours, calibrated from this repo's merged-PR timestamps (e.g. 0.7–1.2 h per Photoshop-style filter, ~0.8 h per medium feature); see [calibration](docs/target-app-parity.md#calibration). @@ -249,7 +249,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| -| 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. Headline numbers unchanged. | +| 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (confirming #937's fix on the reporter's file). Headline numbers unchanged. | | 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..a746618801 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-22 · **Change:** minor (Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -77,6 +77,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-22 | minor | Essentials readiness row: the Shape Builder item names what its 4–8 h still covers, confirming #937's fix on the reporter's file (the reproduced case is fixed), #8314. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel row context menus (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance); right-clicking an unselected row targets that row first. Headless regressions: `panels::tests_appearance`. Scores and estimates unchanged. | @@ -349,7 +350,7 @@ review parallelize less and need humans. |---|---:|---:|---:|---| | **Full Illustrator** (ready for real work; decides the stage) | **~62%** (57–67%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (24–40 h), advanced type (20–28 h), generative AI (30–60 h), localization (55–90 h) and ecosystem | | **Mainstream illustrator** | **~65%** (60–70%) | **~230–380 h** | ~65–110 h | the interaction-fidelity pass (60–90 h), hardening and QA (30–50 h), stability (20–35 h), performance budgets (15–25 h), `.ai` exchange (10–20 h), the remaining depth of the everyday areas | -| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder regions (4–8 h), UI polish | +| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish | ### Full Illustrator: additive weighted sum over the dimensions @@ -3176,6 +3177,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-22 | minor | Essentials readiness row: the Shape Builder item names what its 4–8 h still covers, confirming #937's fix on the reporter's file (the reproduced case is fixed), #8314. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | Guides, grids, smart guides, snapping, rulers: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out their Show/Hide items; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged. | From 460678d341ac73567aed53363c2b0873a03e61c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:02:00 -0800 Subject: [PATCH 27/55] Plug-ins: filters and plug-in commands read the document's settings, artboards, layers and swatches without a selection A filter, or a live effect with commands, at plug-in API level 3 lists `context` (settings, artboards, layers, swatches) with `doc.read` in its permissions. Each filter or command run is then given those parts of the active document in `_context.document`, whether or not anything is selected: the document's name without its folder, color mode, units, active artboard size, bleed and raster effects resolution; every artboard's id, index, name, rectangle and whether it is active; every layer and sublayer with its parent, depth, name, visibility, lock, template, color and whether it is current; and every swatch as swatch.list lists it. It holds no path, object or write handle, and live-effect drawing, exporters and importers get none. More than 10,000 rows or 4 MiB of them fail the run before the plug-in starts, with the document unchanged, and each row takes 1,000 instructions from the run's budget. The install prompt names the wider read. API_LEVEL is now 3, so older hosts refuse such a manifest. plugin.list and plugin.info give `context`, and their params text names it and API level 3. The plug-in fuzz tests add hostile `context` manifests, installed and run with and without a selection. Docs: docs/plugins.md (Document information), docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/plugin.rs | 33 ++++- crates/engine/src/cmd/plugin/context.rs | 147 +++++++++++++++++++++ crates/engine/src/cmd/swatch.rs | 24 +++- crates/engine/src/tests/plugins.rs | 162 ++++++++++++++++++++++++ crates/engine/tests/plugin_fuzz.rs | 71 +++++++++++ crates/plugins/src/lib.rs | 2 +- crates/plugins/src/manifest.rs | 135 +++++++++++++++++++- crates/plugins/src/permissions.rs | 11 +- crates/ui-egui/src/dialogs/tests.rs | 1 + crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/io/open.rs | 12 +- docs/mcp.md | 11 +- docs/plugins.md | 74 +++++++++-- docs/target-app-parity.md | 1 + 41 files changed, 757 insertions(+), 30 deletions(-) create mode 100644 crates/engine/src/cmd/plugin/context.rs diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..fad852e14f 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -43,6 +43,11 @@ //! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type, //! images or symbol instances of those kinds, to read only: its output must return each of them //! unchanged ([`objects::decode_output_with`]). +//! +//! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is +//! also given the parts of the active document it names in `_context.document`, whether or not +//! anything is selected: the settings, artboards, layers and swatches, as plain values +//! ([`context`]). use std::sync::{Arc, Mutex, RwLock}; @@ -55,6 +60,9 @@ use crate::store::StoreTurn; use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission}; +mod context; +pub use context::{CONTEXT_FUEL_PER_ITEM, MAX_CONTEXT_BYTES, MAX_CONTEXT_ITEMS}; + /// What a plug-in error looks like to the user. A run the caller cancelled changed nothing. fn err(e: vectorcraft_plugins::Error) -> EngineError { match e { @@ -101,6 +109,9 @@ pub fn describe(p: &Plugin) -> Value { if !m.inputs.is_empty() { v["inputs"] = json!(m.inputs); } + if !m.context.is_empty() { + v["context"] = json!(m.context); + } if m.paint_output { v["paintOutput"] = json!(true); } @@ -242,15 +253,25 @@ impl FilterRun { params["_context"]["mode"] = json!("command"); params["_context"]["command"] = json!(cmd.id); } + // The parts of the document its manifest asks for (`context`), selection or not. Each row + // costs the run [`context::CONTEXT_FUEL_PER_ITEM`] instructions. + let sections = m.context_sections(); + let mut charged = 0; + if !sections.is_empty() && may.contains(&Permission::DocRead) { + let given = context::document_context(st, §ions, c)?; + params["_context"]["document"] = given.value; + charged = (given.items as u64).saturating_mul(context::CONTEXT_FUEL_PER_ITEM); + } let params = serde_json::to_vec(¶ms).map_err(|e| bad(c, e.to_string()))?; // The input and the parameters may use half the plug-in's memory together. let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len()); let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?; let document = (st.uid, st.revision); - let limits = match s.prefs.plugin_instruction_budget { + let mut limits = match s.prefs.plugin_instruction_budget { crate::PluginBudget::Normal => plugin.limits().clone(), crate::PluginBudget::Large => plugin.large_limits(), }; + limits.fuel_base = limits.fuel_base.saturating_sub(charged); Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits }) } @@ -284,11 +305,17 @@ impl FilterRun { } /// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when - /// it was made. + /// it was made, less what its document context costs. pub fn limits(&self) -> &vectorcraft_plugins::Limits { &self.limits } + /// The parameters it hands the plug-in, `_context` included. + #[cfg(test)] + pub(crate) fn params_json(&self) -> Value { + serde_json::from_slice(&self.params).unwrap_or(Value::Null) + } + /// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the /// session ([`FilterRun::run_with_calls`]). pub fn calls(&self) -> bool { @@ -1270,7 +1297,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), diff --git a/crates/engine/src/cmd/plugin/context.rs b/crates/engine/src/cmd/plugin/context.rs new file mode 100644 index 0000000000..2078828eba --- /dev/null +++ b/crates/engine/src/cmd/plugin/context.rs @@ -0,0 +1,147 @@ +//! A plug-in run's document context (`_context.document`): the parts of the active document its +//! manifest's `context` asks for ([`ContextSection`]), read when the run is prepared, with or +//! without a selection. It holds plain values only: names, flags, rectangles and colors, never an +//! object, a file path or a link target. + +use serde_json::{Value, json}; +use vectorcraft_doc::{ColorMode, LayerColor, Node, NodeKind}; +use vectorcraft_plugins::ContextSection; + +use super::super::{Result, bad}; +use crate::DocState; + +/// Most rows (artboards, layers and sublayers, and swatches together) a document context holds. +pub const MAX_CONTEXT_ITEMS: usize = 10_000; + +/// Most bytes the rows of a document context take as JSON. +pub const MAX_CONTEXT_BYTES: usize = 4 * 1024 * 1024; + +/// Instructions each row costs: they come off the run's instruction budget. +pub const CONTEXT_FUEL_PER_ITEM: u64 = 1_000; + +/// A document context, and the rows it holds. +pub(super) struct DocumentContext { + pub value: Value, + pub items: usize, +} + +/// The document context of `sections` for a run of command `c` on `st`: `{revision}` and a key +/// for each section asked for. A document with more than [`MAX_CONTEXT_ITEMS`] rows in them, or +/// rows of more than [`MAX_CONTEXT_BYTES`], is an error, before any row is made in the first case. +pub(super) fn document_context(st: &DocState, sections: &[ContextSection], c: &str) -> Result { + let d = &st.doc; + let layers = if sections.contains(&ContextSection::Layers) { layer_rows(d) } else { Vec::new() }; + let swatches = || super::super::swatch::listed_swatches(d, true, d.swatch_groups.iter().collect()); + let mut items = 0; + for s in sections { + items += match s { + ContextSection::Settings => 0, + ContextSection::Artboards => d.artboards.len(), + ContextSection::Layers => layers.len(), + ContextSection::Swatches => swatches().count(), + }; + } + let too_large = || { + bad( + c, + format!( + "the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes" + ), + ) + }; + if items > MAX_CONTEXT_ITEMS { + return Err(too_large()); + } + let mut bytes = 0usize; + let mut row = |v: Value| -> Result { + bytes = bytes.saturating_add(serde_json::to_vec(&v).map_or(usize::MAX, |b| b.len() + 1)); + if bytes > MAX_CONTEXT_BYTES { Err(too_large()) } else { Ok(v) } + }; + let active = active_artboard(st); + let mut out = json!({"revision": st.revision}); + for s in sections { + let value = match s { + ContextSection::Settings => { + let board = active.and_then(|i| d.artboards.get(i)); + row(json!({ + "name": st.title(), + "colorMode": match d.color_mode { + ColorMode::Rgb => "rgb", + ColorMode::Cmyk => "cmyk", + }, + "units": d.units.label(), + "width": board.map(|a| a.rect.width()), + "height": board.map(|a| a.rect.height()), + "bleed": d.setup.bleed, + "rasterEffectsPpi": d.raster_ppi(), + "activeArtboard": board.map(|a| a.id), + }))? + } + ContextSection::Artboards => { + let rows = d.artboards.iter().enumerate().map(|(i, a)| { + let r = a.rect; + row(json!({"id": a.id, "index": i, "name": a.name, "rect": [r.x0, r.y0, r.x1, r.y1], "active": active == Some(i)})) + }); + Value::Array(rows.collect::>()?) + } + ContextSection::Layers => { + let rows = layers.iter().map(|l| { + let n = l.node; + row(json!({ + "id": n.id.0, "parentId": l.parent, "depth": l.depth, "name": n.display_name(), + "visible": n.visible, "locked": n.locked, "template": l.template, "color": l.color.label_text(), + "sublayers": l.sublayers, "current": st.active_layer == Some(n.id), + })) + }); + Value::Array(rows.collect::>()?) + } + ContextSection::Swatches => { + let rows = swatches().map(|(w, g)| row(super::super::swatch::swatch_json(w, g))); + Value::Array(rows.collect::>()?) + } + }; + out[s.name()] = value; + } + Ok(DocumentContext { value: out, items }) +} + +/// Is `n` a layer or sublayer? +fn is_layer(n: &Node) -> bool { + matches!(n.kind, NodeKind::Layer { .. }) +} + +/// A layer or sublayer, where it is in the layer tree, and what its row reports besides the +/// node's own name and flags. +struct LayerRow<'a> { + node: &'a Node, + /// Its parent layer's id; `None` for a top-level layer. + parent: Option, + /// 0 for a top-level layer, 1 for its sublayers, and so on. + depth: usize, + color: LayerColor, + template: bool, + /// The sublayers it holds directly. + sublayers: usize, +} + +/// Every layer and sublayer of `d`, depth first in document order (bottom first within each +/// parent). The walk keeps its own stack, so deep nesting can't overflow the thread's. +fn layer_rows(d: &vectorcraft_doc::Document) -> Vec> { + let mut out = Vec::new(); + let mut stack: Vec<(&Node, Option, usize)> = d.layers.iter().rev().map(|l| (l.as_ref(), None, 0)).collect(); + while let Some((node, parent, depth)) = stack.pop() { + let NodeKind::Layer { color, template, children, .. } = &node.kind else { continue }; + let sublayers = children.iter().filter(|c| is_layer(c)).count(); + stack.extend(children.iter().rev().filter(|c| is_layer(c)).map(|c| (c.as_ref(), Some(node.id.0), depth + 1))); + out.push(LayerRow { node, parent, depth, color: *color, template: *template, sublayers }); + } + out +} + +/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no +/// longer has it, the artboard the document opened on, else the first; `None` with no artboards. +fn active_artboard(st: &DocState) -> Option { + let d = &st.doc; + let at = |id: Option| id.and_then(|id| d.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(d.opened_artboard)).or((!d.artboards.is_empty()).then_some(0)) +} diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 511352b9a5..78f3a88b1e 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -1012,18 +1012,28 @@ fn swatch_list(s: &mut Session, p: &Value) -> Result { Some(g) => vec![d.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| bad("swatch.list", format!("no colour group `{g}`")))?], None => d.swatch_groups.iter().collect(), }; - // The built-in Registration swatch lists after None, as the panel shows it. - let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count(); - let (specials, rest) = d.swatches.split_at(none); - let all = specials.iter().chain([vectorcraft_color::swatch::registration()]).chain(rest); - let ungrouped = all.filter(|_| only.is_none()).map(|w| swatch_json(w, None)); - let grouped = groups.iter().flat_map(|g| g.swatches.iter().map(|w| swatch_json(w, Some(&g.name)))); - let swatches: Vec = ungrouped.chain(grouped).collect(); + let swatches: Vec = listed_swatches(d, only.is_none(), groups.clone()).map(|(w, g)| swatch_json(w, g)).collect(); let groups: Vec = groups.iter().map(|g| json!({"name": g.name, "swatches": g.swatches.iter().map(|w| &w.name).collect::>()})).collect(); Ok(json!({"swatches": swatches, "groups": groups})) } +/// The swatches `swatch.list` lists, in its order, each with the name of the colour group it is +/// in: with `ungrouped`, the swatches outside groups (the built-in Registration swatch after None, +/// as the panel shows it), then those of `groups`. +pub(super) fn listed_swatches<'a>( + d: &'a Document, + ungrouped: bool, + groups: Vec<&'a SwatchGroup>, +) -> impl Iterator)> + 'a { + let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count(); + let (specials, rest) = d.swatches.split_at(none); + let all = specials.iter().chain([vectorcraft_color::swatch::registration()]).chain(rest); + let ungrouped = all.filter(move |_| ungrouped).map(|w| (w, None)); + let grouped = groups.into_iter().flat_map(|g| g.swatches.iter().map(move |w| (w, Some(g.name.as_str())))); + ungrouped.chain(grouped) +} + fn swatch_sort(s: &mut Session, _: &Value) -> Result { s.edit("Sort Swatches", |d, _| { // [None] and other bracketed specials stay first, like the reference app. diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..a498049cc3 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -3858,6 +3858,168 @@ fn read_only_kind_field_and_omission_refuse_without_undo() { assert!(e.contains("`inputs` needs `api` 2"), "{e}"); } +/// The manifest of a filter at `api` 3 with id `id` that asks for the document information +/// `context` (a JSON list), with `doc.read` and `doc.write`, and `rest` (keys after a comma, or +/// nothing). +fn context_manifest(id: &str, context: &str, rest: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"context":{context}{rest}}}"#) +} + +/// Installs `src` granted `doc.read` and `doc.write`, in place of any module with its id. +fn install_reading(s: &mut Session, src: &str) -> Value { + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})) +} + +/// A filter at `api` 3 whose manifest lists `context` is given the document's settings, artboards, +/// layers and swatches in `_context.document` with nothing selected: plain values, hidden and +/// locked layers with their flags, the active artboard and the current layer marked, and the +/// document's name without its folder. A filter that doesn't list `context` is given none, and one +/// that lists it without `doc.read` or below `api` 3 doesn't install. +#[test] +fn an_unselected_filter_reads_the_document_context_it_asks_for() { + use cmd::plugin::FilterRun; + let mut s = session(); + run(&mut s, "artboard.new", json!({"x": 500, "y": 0, "width": 100, "height": 50})); + let hidden = run(&mut s, "layer.new", json!({"name": "Hidden", "visible": false}))["id"].as_u64().unwrap(); + let locked = run(&mut s, "layer.newSublayer", json!({"parent": hidden, "name": "Locked", "locked": true}))["id"].as_u64().unwrap(); + run(&mut s, "layer.setCurrent", json!({"id": locked})); + run(&mut s, "swatch.new", json!({"name": "Tone", "color": "#ff0000", "global": true})); + run(&mut s, "select.none", json!({})); + s.doc_mut().unwrap().path = Some("/private/folder/Poster.vectorcraft".into()); + let second = s.doc().unwrap().doc.artboards[1].id; + s.doc_mut().unwrap().active_artboard = Some(second); + let id = "test.engine.context"; + let all = r#"["settings","artboards","layers","swatches"]"#; + let installed = install_reading(&mut s, &tpl::returning(&context_manifest(id, all, ""), r#"{"objects":[]}"#)); + assert_eq!(installed["context"], json!(["settings", "artboards", "layers", "swatches"])); + let swatches = run(&mut s, "swatch.list", json!({}))["swatches"].clone(); + assert!(s.doc().unwrap().selection.objects.is_empty()); + let given = FilterRun::prepare(&s, &json!({"id": id})).unwrap().params_json()["_context"]["document"].clone(); + let st = s.doc().unwrap(); + let d = &st.doc; + assert_eq!(given["revision"], json!(st.revision)); + let board = &d.artboards[1]; + let settings = json!({ + "name": "Poster.vectorcraft", "colorMode": "rgb", "units": d.units.label(), "width": board.rect.width(), + "height": board.rect.height(), "bleed": d.setup.bleed, "rasterEffectsPpi": d.raster_ppi(), "activeArtboard": second, + }); + assert_eq!(given["settings"], settings); + let boards: Vec = d + .artboards + .iter() + .enumerate() + .map(|(i, a)| json!({"id": a.id, "index": i, "name": a.name, "rect": [a.rect.x0, a.rect.y0, a.rect.x1, a.rect.y1], "active": i == 1})) + .collect(); + assert_eq!((boards.len(), &given["artboards"]), (2, &json!(boards))); + let layers = given["layers"].as_array().unwrap(); + let rows: Vec<(String, u64, bool, bool, bool)> = layers + .iter() + .map(|l| { + (l["name"].as_str().unwrap().to_string(), l["depth"].as_u64().unwrap(), l["visible"] == true, l["locked"] == true, l["current"] == true) + }) + .collect(); + let bottom = d.layers[0].display_name(); + assert_eq!(rows, [(bottom, 0, true, false, false), ("Hidden".into(), 0, false, false, false), ("Locked".into(), 1, true, true, true)]); + assert_eq!((&layers[0]["parentId"], &layers[1]["sublayers"], &layers[2]["parentId"]), (&Value::Null, &json!(1), &json!(hidden))); + assert_eq!((&layers[1]["id"], &layers[2]["id"]), (&json!(hidden), &json!(locked))); + assert_eq!(given["swatches"], swatches, "as swatch.list lists them"); + assert!(given["swatches"].as_array().unwrap().iter().any(|w| w["name"] == "Tone" && w["global"] == true)); + assert!(!given.to_string().contains("/private/folder"), "no path: {given}"); + // Only the sections asked for. + let some = "test.engine.context.some"; + install_reading(&mut s, &tpl::returning(&context_manifest(some, r#"["layers"]"#, ""), r#"{"objects":[]}"#)); + let given = FilterRun::prepare(&s, &json!({"id": some})).unwrap().params_json()["_context"]["document"].clone(); + let keys: Vec<&String> = given.as_object().unwrap().keys().collect(); + assert_eq!(keys.len(), 2, "{keys:?}"); + assert!(given.get("layers").is_some() && given.get("revision").is_some()); + // A filter without `context` is given none. + let legacy = "test.engine.context.legacy"; + install_reading(&mut s, &tpl::returning(&tpl::manifest(legacy, "filter", "{}"), r#"{"objects":[]}"#)); + assert!(FilterRun::prepare(&s, &json!({"id": legacy})).unwrap().params_json()["_context"].get("document").is_none()); + // Without `doc.read`, or below `api` 3, it doesn't install. + let needs = "`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`"; + for manifest in [ + format!(r#"{{"id":"{some}","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"context":["layers"]}}"#), + format!(r#"{{"id":"{some}","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"context":["layers"]}}"#), + ] { + let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()); + let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})).unwrap_err(); + assert!(e.to_string().contains(needs), "{manifest}: {e}"); + } +} + +/// A plug-in command, of a filter or of a live effect, whose manifest lists `context` is given it +/// too, with nothing selected. +#[test] +fn a_plugin_command_reads_the_document_context_without_a_selection() { + let mut s = session(); + let made = json!({"objects": [{"path": triangle(), "name": "Saw layers"}]}).to_string(); + for (id, kind, permissions) in [ + ("test.engine.context.command", "filter", r#"["doc.read","doc.write"]"#), + ("test.engine.context.effectcommand", "effect", r#"["doc.read","doc.write","effect.render"]"#), + ] { + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","kind":"{kind}","api":3,"permissions":{permissions},"context":["layers"],"commands":[{{"id":"look","label":"Look"}}]}}"# + ); + let src = tpl::when_given_else(&manifest, tpl::Given::Params, r#""layers":["#, &made, r#"{"objects":[]}"#); + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + let grant: Vec = serde_json::from_str(permissions).unwrap(); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": grant, "replace": true})); + run(&mut s, "select.none", json!({})); + let ids = run(&mut s, &format!("plugin.{id}.look"), json!({}))["ids"].clone(); + assert_eq!(ids.as_array().map(Vec::len), Some(1), "{kind}: {ids}"); + assert_eq!(node(&s, NodeId(ids[0].as_u64().unwrap())).name.as_deref(), Some("Saw layers"), "{kind}"); + } +} + +/// A document context holds at most [`cmd::plugin::MAX_CONTEXT_ITEMS`] rows in +/// [`cmd::plugin::MAX_CONTEXT_BYTES`] bytes: past either, the run fails before the plug-in starts, +/// with the document and undo history as they were. Each row comes off the run's instruction +/// budget. +#[test] +fn the_document_context_is_capped_and_its_rows_cost_instructions() { + use cmd::plugin::{CONTEXT_FUEL_PER_ITEM, FilterRun, MAX_CONTEXT_BYTES, MAX_CONTEXT_ITEMS}; + let mut s = session(); + let id = "test.engine.context.cap"; + install_reading(&mut s, &tpl::returning(&context_manifest(id, r#"["swatches"]"#, ""), r#"{"objects":[]}"#)); + let p = json!({"id": id}); + let listed = run(&mut s, "swatch.list", json!({}))["swatches"].as_array().unwrap().len(); + let add = |s: &mut Session, n: usize| { + s.edit("Set up", |d, _| { + let base = d.swatches.last().unwrap().clone(); + let at = d.swatches.len(); + d.swatches.extend((at..at + n).map(|i| vectorcraft_color::Swatch { name: format!("Many {i}"), ..base.clone() })); + Ok(()) + }) + .unwrap(); + }; + add(&mut s, MAX_CONTEXT_ITEMS - listed); + let full = FilterRun::prepare(&s, &p).unwrap(); + assert_eq!(full.params_json()["_context"]["document"]["swatches"].as_array().map(Vec::len), Some(MAX_CONTEXT_ITEMS)); + assert_eq!(full.limits().fuel_base, full.plugin().limits().fuel_base - MAX_CONTEXT_ITEMS as u64 * CONTEXT_FUEL_PER_ITEM); + let too_large = "the document information the plug-in asks for is too large to hand over"; + add(&mut s, 1); + let refused = |s: &mut Session| { + let Err(e) = FilterRun::prepare(s, &p) else { panic!("prepared past the cap") }; + assert!(e.to_string().contains(too_large), "{e}"); + let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute("plugin.run", &p).unwrap_err().to_string(); + assert!(e.contains(too_large), "{e}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo)); + }; + refused(&mut s); + // A few rows past the byte cap are refused as well. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + s.edit("Set up", |d, _| { + d.swatches.last_mut().unwrap().name = "n".repeat(MAX_CONTEXT_BYTES); + Ok(()) + }) + .unwrap(); + refused(&mut s); +} + /// A run past its memory budget fails before the plug-in starts, with the document and undo /// history as they were: a read-only object whose other fields don't fit, a path and a compound /// path that don't fit, and parameters past the input's half of the cap, with objects selected or diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 35f29a2a25..519efdaf43 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -882,6 +882,77 @@ proptest! { vectorcraft_plugins::registry::revoke("fuzz.inputs"); } + /// Manifests with a hostile `context` (unknown, repeated and oddly cased sections, long lists, + /// junk of every type) with any `api`, kind and permissions parse to an error or to a filter, or + /// a live effect with commands, at `api` 3 or later asking for each section once, whose + /// `permissions` list `doc.read` so that installing it asks for approval. One that installs and + /// echoes its input, with or without a selection, leaves the document as it was, and it still + /// renders. + #[test] + fn hostile_manifest_context_never_crash( + kind in prop::sample::select(vec!["filter", "effect", "exporter"]), + commands in any::(), + names in prop::collection::vec(prop::sample::select(vec!["settings", "artboards", "layers", "swatches", "Layers", "document", ""]), 0..6), + long in prop::option::weighted(0.1, 5usize..300), + context in prop::option::weighted(0.8, prop_oneof![Just(Value::Null), arb_junk()]), + api in prop_oneof![2 => Just(json!(3)), 1 => Just(json!(2)), 1 => Just(json!(4)), 1 => arb_junk()], + permissions in prop_oneof![Just(Value::Null), Just(json!([])), Just(json!(["doc.read", "doc.write"])), Just(json!(["doc.read", "effect.render"])), Just(json!(["doc.write"]))], + select in any::(), + ) { + let mut m = json!({"id": "fuzz.context", "name": "Context", "kind": kind, "api": api}); + if kind == "exporter" { + m["extensions"] = json!(["fz"]); + } + if commands { + m["commands"] = json!([{"id": "c", "label": "C"}]); + } + if !permissions.is_null() { + m["permissions"] = permissions; + } + m["context"] = match (context, long) { + (_, Some(n)) => json!(vec!["layers"; n]), + (Some(Value::Null) | None, None) => json!(names), + (Some(junk), None) => junk, + }; + let text = m.to_string(); + let parsed = catch_quiet(|| vectorcraft_plugins::Manifest::parse(text.as_bytes())); + let parsed = parsed.map_err(|msg| TestCaseError::fail(format!("panicked on {text}: {msg}")))?; + if let Ok(man) = &parsed { + let sections = man.context_sections(); + prop_assert_eq!(sections.len(), man.context.len(), "{}", text); + prop_assert!(sections.iter().enumerate().all(|(i, k)| !sections[..i].contains(k)), "{}", text); + let kind_ok = man.kind == Kind::Filter || (man.kind == Kind::Effect && !man.commands.is_empty()); + prop_assert!(sections.is_empty() || (kind_ok && man.api >= 3), "{}", text); + let reads = man.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == "doc.read")); + prop_assert!(sections.is_empty() || (man.asks_permissions() && reads), "{}", text); + } + let mut s = rich_session(); + s.allow_plugin_grants_from_requests(); + let module = wat::parse_str(tpl::module(&text, tpl::ECHO, "", 1)).unwrap(); + let data = vectorcraft_format::base64_encode(&module); + let grant = json!(["doc.read", "doc.write", "state", "effect.render", "export.write"]); + let before = s.doc().unwrap().doc.clone(); + let r = catch_quiet(|| { + let installed = s.execute("plugin.install", &json!({"dataBase64": data, "grant": grant})).is_ok(); + let _ = s.execute(if select { "select.all" } else { "select.none" }, &json!({})); + let ran = installed && s.execute("plugin.run", &json!({"id": "fuzz.context"})).is_ok(); + if installed { + for c in s.commands().into_iter().filter(|c| c.id.starts_with("plugin.fuzz.context.")) { + let _ = s.execute(c.id, &json!({})); + } + } + (installed, ran) + }); + let (installed, ran) = r.map_err(|msg| TestCaseError::fail(format!("panicked running {text}: {msg}")))?; + prop_assert!(!installed || parsed.is_ok(), "a manifest that doesn't parse installed: {}", text); + if ran { + prop_assert!(s.doc().unwrap().doc.layers == before.layers, "an echo changed the document: {}", text); + } + renders(&s, &text)?; + vectorcraft_plugins::registry::remove("fuzz.context"); + vectorcraft_plugins::registry::revoke("fuzz.context"); + } + /// A plug-in that calls the storage imports with hostile keys (`..`, separators, device names, /// control characters, too long), values, lengths up to about 1 MiB and pointers in and out of /// its memory runs to an output, or on a small budget to its instruction budget, never a panic; diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..5ee30395e8 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -52,7 +52,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; -pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; +pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, Param, ParamSpec}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..10caefddac 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; -use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission}; +use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission}; use crate::{Error, Result}; /// Longest manifest the host reads. @@ -93,6 +93,45 @@ impl InputKind { } } +/// A part of the active document a filter or a plug-in command asks to be given in +/// `_context.document`, with or without a selection (its manifest's `context`, plug-in API level 3): +/// plain values to read, never objects. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ContextSection { + /// The document's name (never its path), color mode, units, the active artboard's size, the + /// bleed and the raster effects resolution. + Settings, + /// Every artboard's id, name and rectangle, and which one is active. + Artboards, + /// Every layer and sublayer: name, visibility, lock, nesting, and which one is current. + Layers, + /// Every swatch, as `swatch.list` lists it. + Swatches, +} + +impl ContextSection { + /// Every section, in the order the docs list them. + pub const ALL: [ContextSection; 4] = [ContextSection::Settings, ContextSection::Artboards, ContextSection::Layers, ContextSection::Swatches]; + + /// Its name in `context`, which is also its key in `_context.document`. + pub fn name(self) -> &'static str { + match self { + ContextSection::Settings => "settings", + ContextSection::Artboards => "artboards", + ContextSection::Layers => "layers", + ContextSection::Swatches => "swatches", + } + } + + /// The section named `name`. + pub fn parse(name: &str) -> Option { + ContextSection::ALL.into_iter().find(|s| s.name() == name) + } +} + +/// The error of a `context` that is not a list of distinct section names. +const CONTEXT_LIST: &str = "`context` must list distinct sections: settings, artboards, layers or swatches"; + /// How much one run of a plug-in may compute. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -326,6 +365,12 @@ pub struct Manifest { /// lists them. Left out or empty, it is given paths and compound paths alone. #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")] pub inputs: Vec, + /// The parts of the document a run is given in `_context.document`, by + /// [`ContextSection::name`]: only a filter, or a live effect with `commands` (for its command + /// runs), at `api` 3 or later whose `permissions` list `doc.read` lists them. Left out or empty, + /// a run is given none. + #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "context_names")] + pub context: Vec, /// Parameters in declaration (dialog) order; a JSON object `{"name": spec, …}` in the manifest. #[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")] pub params: Vec<(String, Param)>, @@ -377,6 +422,7 @@ impl Manifest { api: 1, permissions: None, inputs: Vec::new(), + context: Vec::new(), params: Vec::new(), extensions: Vec::new(), budget: Budget::Light, @@ -422,6 +468,7 @@ impl Manifest { return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}"))); } self.validate_inputs()?; + self.validate_context()?; if self.paint_output && (self.kind != Kind::Effect || self.api < 2) { return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into())); } @@ -518,6 +565,33 @@ impl Manifest { Ok(()) } + /// `context` names each [`ContextSection`] at most once, and only a filter, or a live effect + /// with commands, at `api` 3 or later lists any, with a `permissions` list that holds + /// `doc.read`: installing it then asks the user to grant it ([`Manifest::asks_permissions`]). + fn validate_context(&self) -> Result<()> { + if self.context.is_empty() { + return Ok(()); + } + for (i, name) in self.context.iter().enumerate() { + if ContextSection::parse(name).is_none() || self.context.get(..i).is_some_and(|before| before.contains(name)) { + return Err(Error::Manifest(CONTEXT_LIST.into())); + } + } + let runs = self.kind == Kind::Filter || (self.kind == Kind::Effect && !self.commands.is_empty()); + let reads = self.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == Permission::DocRead.name())); + if !runs || self.api < CONTEXT_API || !reads { + return Err(Error::Manifest( + "`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`".into(), + )); + } + Ok(()) + } + + /// The parts of the document it asks to be given (`context`). + pub fn context_sections(&self) -> Vec { + self.context.iter().filter_map(|n| ContextSection::parse(n)).collect() + } + /// A filter or a live effect lists at most [`MAX_COMMANDS`] commands, each with a distinct /// id, a printable label and parameters declared as the manifest's own are. A heavy filter /// lists none. The error names the command: its id, or its place in the list. @@ -733,6 +807,18 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result, D::Error> { + match Value::deserialize(d)? { + Value::Null => Ok(Vec::new()), + Value::Array(names) => { + names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(serde::de::Error::custom(CONTEXT_LIST)) }).collect() + } + _ => Err(serde::de::Error::custom(CONTEXT_LIST)), + } +} + /// Reads the `commands` list one entry at a time from the manifest itself, so each command's /// `params` keep their declaration order and a repeated parameter is refused. A malformed entry /// is an error that names it (its id when the id comes before the fault, otherwise its place in @@ -1119,7 +1205,7 @@ mod tests { (r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["progress"]}"#, "`progress` needs plug-in API level 2"), (r#"{"id":"a","name":"x","kind":"filter","permissions":["settings"]}"#, "`settings` needs plug-in API level 2"), (r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["doc.read","cache"]}"#, "`cache` needs plug-in API level 2"), - (r#"{"id":"a","name":"x","kind":"filter","api":3}"#, "`api` is 3"), + (r#"{"id":"a","name":"x","kind":"filter","api":4}"#, "`api` is 4; this host implements plug-in API levels 1 to 3"), (r#"{"id":"a","name":"x","kind":"filter","api":0}"#, "`api` is 0"), (r#"{"id":"a","name":"x","kind":"filter","api":-1}"#, "manifest"), ] { @@ -1175,6 +1261,51 @@ mod tests { assert!(Manifest::parse(long.as_bytes()).unwrap_err().to_string().contains("twice")); } + /// A filter, or a live effect with commands, at `api` 3 may ask for parts of the document + /// (`context`), each once, with a `permissions` list holding `doc.read`, so installing it asks + /// for approval. Left out or empty, it asks for none and isn't written back. Anything else is + /// refused naming `context`. + #[test] + fn a_level_3_plugin_lists_the_document_context_it_reads() { + let m = Manifest::parse( + br#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["settings","artboards","layers","swatches"]}"#, + ) + .unwrap(); + assert_eq!(m.context_sections(), ContextSection::ALL); + assert!(m.asks_permissions()); + assert_eq!(serde_json::to_value(&m).unwrap()["context"], json!(["settings", "artboards", "layers", "swatches"])); + let effect = br#"{"id":"a","name":"x","kind":"effect","api":3,"permissions":["doc.read","effect.render"],"context":["layers"],"commands":[{"id":"c","label":"C"}]}"#; + assert_eq!(Manifest::parse(effect).unwrap().context_sections(), [ContextSection::Layers]); + for none in [r#"{"id":"a","name":"x","kind":"filter","context":[]}"#, r#"{"id":"a","name":"x","kind":"filter","api":3,"context":null}"#] { + let m = Manifest::parse(none.as_bytes()).unwrap(); + assert!(m.context_sections().is_empty(), "{none}"); + assert!(serde_json::to_value(&m).unwrap().get("context").is_none(), "{none}"); + } + let list = "`context` must list distinct sections"; + let needs = "`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`"; + for (bad, says) in [ + (r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["paths"]}"#, list), + (r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["Layers"]}"#, list), + (r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":["layers","layers"]}"#, list), + (r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":"layers"}"#, list), + (r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":[1]}"#, list), + (r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"context":{"layers":true}}"#, list), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"context":["layers"]}"#, needs), + (r#"{"id":"a","name":"x","kind":"filter","permissions":["doc.read"],"context":["layers"]}"#, needs), + (r#"{"id":"a","name":"x","kind":"filter","api":3,"context":["layers"]}"#, needs), + (r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"context":["layers"]}"#, needs), + (r#"{"id":"a","name":"x","kind":"effect","api":3,"permissions":["doc.read","effect.render"],"context":["layers"]}"#, needs), + ( + r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"api":3,"permissions":["doc.read","export.write"],"context":["layers"]}"#, + needs, + ), + (r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"api":3,"permissions":["import.read"],"context":["layers"]}"#, needs), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + /// A live effect at `api` 2 may declare `"paintOutput": true`, and only that value; any other /// kind or level, and `false`, `null` or another type, is refused naming the key. Without the /// key, at any level, the effect returns geometry only. diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..7d2a3452c8 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -15,8 +15,8 @@ use crate::{Error, Kind, Result}; /// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most /// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput` -/// ([`crate::painted`]). -pub const API_LEVEL: u32 = 2; +/// ([`crate::painted`]); level 3 adds a manifest's `context` ([`CONTEXT_API`]). +pub const API_LEVEL: u32 = 3; /// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`, /// `settings`, `cache` and `commands` permissions they need. @@ -25,6 +25,10 @@ pub const PROGRESS_API: u32 = 2; /// The API level that adds a filter's `inputs` ([`crate::InputKind`]). pub const INPUTS_API: u32 = 2; +/// The API level that adds a manifest's `context` ([`crate::ContextSection`]): the document's +/// settings, artboards, layers and swatches, given to a run with or without a selection. +pub const CONTEXT_API: u32 = 3; + /// Most permissions a manifest may list. pub const MAX_PERMISSIONS: usize = 16; @@ -42,7 +46,8 @@ pub const RESERVED: &[&str] = &["ui.panel", "ui.tool"]; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub enum Permission { /// Read the objects the host hands it: a filter's selected paths, the object a live effect is - /// on, the document an exporter writes. + /// on, the document an exporter writes; and the document information a manifest's `context` + /// asks for ([`crate::ContextSection`]). #[serde(rename = "doc.read")] DocRead, /// Change, add and delete objects (a filter's output), as one undo step. diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4561f3dc73..b39314befa 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -714,6 +714,7 @@ impl PluginIntField { api: 1, permissions: None, inputs: Vec::new(), + context: Vec::new(), params: vec![("seed".into(), vectorcraft_plugins::ParamSpec::Int { min, max, default: 0 }.into())], extensions: Vec::new(), budget: Default::default(), diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..946a160dbf 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6683,6 +6683,7 @@ axis Y Axis Y ос Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Автоматизация поиска инсталирането на тази приставка. За да я инсталирате, изберете Обект › Приставки › Инсталиране на приставка… сами. File SHA-256: {hash} SHA-256 на файла: {hash} Read the objects it is given Четене на обектите, които получава + Read the objects it is given, and the document's settings, artboards, layers and swatches Четене на обектите, които получава, както и на настройките, работните области, слоевете и образците на документа Change, add and delete objects in the document Промяна, добавяне и изтриване на обекти в документа Keep data of its own with the document Съхраняване на собствени данни в документа Change how the objects its effect is applied to are drawn Промяна на начина, по който се рисуват обектите, към които е приложен ефектът му diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..559cb7ec59 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6711,6 +6711,7 @@ axis Y Axis Y osa @msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees „{name}” je drugi modul od dodatka s ID-om {_1} i dobio bi postavke i predmemoriju sačuvane za njega: instalirajte ga s `replace: true` kada korisnik pristane File SHA-256: {hash} SHA-256 datoteke: {hash} Read the objects it is given Čitati objekte koje dobije + Read the objects it is given, and the document's settings, artboards, layers and swatches Čitati objekte koje dobije, kao i postavke, radne ploče, slojeve i uzorke boja dokumenta Change, add and delete objects in the document Mijenjati, dodavati i brisati objekte u dokumentu Keep data of its own with the document Čuvati vlastite podatke uz dokument Change how the objects its effect is applied to are drawn Mijenjati kako se crtaju objekti na koje je primijenjen njegov efekt diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..7ed90f1685 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7875,6 +7875,10 @@ variable-list-end {0}, {1} {0} i {1} @msg `inputs` lists `{shown}` twice `inputs` inclou `{shown}` dues vegades @msg `inputs` needs `api` 2 or later `inputs` requereix `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requereix el permís `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Llegir els objectes que rep, i la configuració, els taulers, les capes i les mostres del document +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` ha de llistar seccions diferents: settings, artboards, layers o swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` és per a un filtre, o un efecte dinàmic amb `commands`, amb `api` 3 o posterior i el permís `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes la informació del document que demana el complement és massa gran per passar-la: com a màxim {MAX_CONTEXT_ITEMS} taulers, capes i mostres en {MAX_CONTEXT_BYTES} bytes @msg memory budget (object {_1} needs {size} bytes of input, {left} left) pressupost de memòria (l’objecte {_1} necessita {size} bytes d’entrada, en queden {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) pressupost d’objectes (més de {MAX_OBJECTS} objectes de només lectura) @msg instruction budget pressupost d’instruccions diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..721c70d0a6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7485,6 +7485,10 @@ axis Y Axis osa Y @msg `inputs` lists `{shown}` twice `inputs` uvádí `{shown}` dvakrát @msg `inputs` needs `api` 2 or later `inputs` vyžaduje `api` 2 nebo vyšší @msg `inputs` needs the permission `doc.read` `inputs` vyžaduje oprávnění `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Číst objekty, které dostane, a nastavení, pracovní plochy, vrstvy a vzorky dokumentu +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` musí uvádět různé oddíly: settings, artboards, layers nebo swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` je pro filtr nebo živý efekt s `commands`, s `api` 3 nebo vyšším a s oprávněním `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes informace o dokumentu, které zásuvný modul požaduje, jsou příliš velké na předání: nejvýše {MAX_CONTEXT_ITEMS} pracovních ploch, vrstev a vzorků v {MAX_CONTEXT_BYTES} bajtech @msg memory budget (object {_1} needs {size} bytes of input, {left} left) rozpočet paměti (objekt {_1} potřebuje {size} bajtů vstupu, zbývá {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) rozpočet objektů (více než {MAX_OBJECTS} objektů jen pro čtení) @msg instruction budget rozpočet instrukcí diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..1790edd287 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -697,6 +697,10 @@ liquify-list-end {0}, {1} {0} og {1} @msg `inputs` lists `{shown}` twice `inputs` angiver `{shown}` to gange @msg `inputs` needs `api` 2 or later `inputs` kræver `api` 2 eller nyere @msg `inputs` needs the permission `doc.read` `inputs` kræver tilladelsen `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Læse de objekter, den får, og dokumentets indstillinger, tegneflader, lag og farveprøver +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` skal angive forskellige afsnit: settings, artboards, layers eller swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` er til et filter eller en live-effekt med `commands`, ved `api` 3 eller senere og med tilladelsen `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes de dokumentoplysninger, som plug-in'et beder om, er for store til at blive overdraget: højst {MAX_CONTEXT_ITEMS} tegneflader, lag og farveprøver i {MAX_CONTEXT_BYTES} byte @msg memory budget (object {_1} needs {size} bytes of input, {left} left) hukommelsesbudget (objekt {_1} kræver {size} byte input, {left} tilbage) @msg object budget (more than {MAX_OBJECTS} read-only objects) objektbudget (mere end {MAX_OBJECTS} skrivebeskyttede objekter) @msg instruction budget instruktionsbudget diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..c5c6dd522a 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7068,6 +7068,10 @@ axis Y Axis Y-Achse @msg `inputs` lists `{shown}` twice `inputs` führt `{shown}` doppelt auf @msg `inputs` needs `api` 2 or later `inputs` erfordert `api` 2 oder höher @msg `inputs` needs the permission `doc.read` `inputs` erfordert die Berechtigung `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Die Objekte lesen, die es erhält, sowie die Einstellungen, Zeichenflächen, Ebenen und Farbfelder des Dokuments +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` muss verschiedene Abschnitte aufführen: settings, artboards, layers oder swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` gilt für einen Filter oder einen Live-Effekt mit `commands`, mit `api` 3 oder höher und der Berechtigung `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes die Dokumentinformationen, die das Plug-in anfordert, sind zu groß zum Übergeben: höchstens {MAX_CONTEXT_ITEMS} Zeichenflächen, Ebenen und Farbfelder in {MAX_CONTEXT_BYTES} Byte @msg memory budget (object {_1} needs {size} bytes of input, {left} left) Speicherbudget (Objekt {_1} benötigt {size} Byte Eingabe, {left} verbleiben) @msg object budget (more than {MAX_OBJECTS} read-only objects) Objektbudget (mehr als {MAX_OBJECTS} schreibgeschützte Objekte) @msg instruction budget Anweisungsbudget diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..e6900b1d7c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7475,6 +7475,10 @@ axis Y Axis Άξονας Y @msg `inputs` lists `{shown}` twice το `inputs` αναφέρει το `{shown}` δύο φορές @msg `inputs` needs `api` 2 or later το `inputs` απαιτεί `api` 2 ή νεότερο @msg `inputs` needs the permission `doc.read` το `inputs` απαιτεί το δικαίωμα `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Ανάγνωση των αντικειμένων που του δίνονται, καθώς και των ρυθμίσεων, των πινάκων σχεδίασης, των επιπέδων και των δειγμάτων χρωμάτων του εγγράφου +@msg `context` must list distinct sections: settings, artboards, layers or swatches το `context` πρέπει να απαριθμεί διαφορετικές ενότητες: settings, artboards, layers ή swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` το `context` ισχύει για φίλτρο ή ζωντανό εφέ με `commands`, με `api` 3 ή νεότερο και το δικαίωμα `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes οι πληροφορίες εγγράφου που ζητά το πρόσθετο είναι πολύ μεγάλες για να παραδοθούν: το πολύ {MAX_CONTEXT_ITEMS} πίνακες σχεδίασης, επίπεδα και δείγματα χρωμάτων σε {MAX_CONTEXT_BYTES} byte @msg memory budget (object {_1} needs {size} bytes of input, {left} left) προϋπολογισμός μνήμης (το αντικείμενο {_1} χρειάζεται {size} byte εισόδου, απομένουν {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) προϋπολογισμός αντικειμένων (περισσότερα από {MAX_OBJECTS} αντικείμενα μόνο για ανάγνωση) @msg instruction budget προϋπολογισμός εντολών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..e7dc633d7e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7461,6 +7461,10 @@ axis Y Axis Eje Y @msg `inputs` lists `{shown}` twice `inputs` incluye `{shown}` dos veces @msg `inputs` needs `api` 2 or later `inputs` requiere `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requiere el permiso `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Leer los objetos que recibe, y los ajustes, las mesas de trabajo, las capas y las muestras del documento +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` debe enumerar secciones distintas: settings, artboards, layers o swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` es para un filtro, o un efecto dinámico con `commands`, con `api` 3 o posterior y el permiso `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes la información del documento que pide el plugin es demasiado grande para entregarla: como máximo {MAX_CONTEXT_ITEMS} mesas de trabajo, capas y muestras en {MAX_CONTEXT_BYTES} bytes @msg memory budget (object {_1} needs {size} bytes of input, {left} left) presupuesto de memoria (el objeto {_1} necesita {size} bytes de entrada, quedan {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) presupuesto de objetos (más de {MAX_OBJECTS} objetos de solo lectura) @msg instruction budget presupuesto de instrucciones diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..46389e1158 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7552,6 +7552,10 @@ axis Y Axis Y-akseli @msg `inputs` lists `{shown}` twice `inputs` luettelee kohteen `{shown}` kahdesti @msg `inputs` needs `api` 2 or later `inputs` edellyttää `api`-tasoa 2 tai uudempaa @msg `inputs` needs the permission `doc.read` `inputs` edellyttää käyttöoikeutta `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Lukea sille annetut objektit sekä asiakirjan asetukset, piirtoalustat, tasot ja värimallit +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context`-avaimen on lueteltava eri osiot: settings, artboards, layers tai swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` on suodattimelle tai reaaliaikaiselle tehosteelle, jolla on `commands`, tasolla `api` 3 tai uudempi ja käyttöoikeudella `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes laajennuksen pyytämät asiakirjan tiedot ovat liian suuret luovutettaviksi: enintään {MAX_CONTEXT_ITEMS} piirtoalustaa, tasoa ja värimallia {MAX_CONTEXT_BYTES} tavussa @msg memory budget (object {_1} needs {size} bytes of input, {left} left) muistibudjetti (objekti {_1} tarvitsee {size} tavua syötettä, jäljellä {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) objektibudjetti (yli {MAX_OBJECTS} vain luku -objektia) @msg instruction budget käskybudjetti diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..56bf714d14 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7482,6 +7482,10 @@ axis Y Axis Axe Y @msg `inputs` lists `{shown}` twice `inputs` mentionne `{shown}` deux fois @msg `inputs` needs `api` 2 or later `inputs` nécessite `api` 2 ou plus @msg `inputs` needs the permission `doc.read` `inputs` nécessite l’autorisation `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Lire les objets qui lui sont transmis, ainsi que les paramètres, les plans de travail, les calques et les nuances du document +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` doit lister des sections distinctes parmi settings, artboards, layers et swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` est réservé à un filtre, ou à un effet dynamique avec `commands`, avec `api` 3 ou plus et l’autorisation `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes les informations du document que demande le module externe sont trop volumineuses pour être transmises (au plus {MAX_CONTEXT_ITEMS} plans de travail, calques et nuances en {MAX_CONTEXT_BYTES} octets) @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget mémoire (l’objet {_1} nécessite {size} octets d’entrée, il en reste {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) budget d’objets (plus de {MAX_OBJECTS} objets en lecture seule) @msg instruction budget budget d’instructions diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..a70039342d 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3070,6 +3070,7 @@ Read Shortcut Set File શોર્ટકટ સેટ ફાઇલ વાંચો Read files you open in its format and make documents from them તમે ખોલો તે ફાઇલોને તેના ફોર્મેટમાં વાંચો અને તેમાંથી દસ્તાવેજ બનાવો Read the objects it is given આપેલી ઑબ્જેક્ટ્સ વાંચો + Read the objects it is given, and the document's settings, artboards, layers and swatches આપેલી ઑબ્જેક્ટ્સ અને દસ્તાવેજની સેટિંગ્સ, આર્ટબોર્ડ, લેયર્સ અને સ્વેચ વાંચો Reading the file… ફાઇલ વાંચી રહ્યું છે… Reads or sets environment variables એન્વાયર્નમેન્ટ વેરીએબલ વાંચે કે સેટ કરે છે Ready તૈયાર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..b34eed754f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6669,6 +6669,10 @@ arrowhead Feather पंख @msg `inputs` lists `{shown}` twice `inputs` में `{shown}` दो बार सूचीबद्ध है @msg `inputs` needs `api` 2 or later `inputs` के लिए `api` 2 या बाद का स्तर आवश्यक है @msg `inputs` needs the permission `doc.read` `inputs` के लिए अनुमति `doc.read` आवश्यक है + Read the objects it is given, and the document's settings, artboards, layers and swatches उसे दिए गए ऑब्जेक्ट्स, और डॉक्यूमेंट की सेटिंग्स, आर्टबोर्ड्स, लेयर्स और स्वॉचेस पढ़ना +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` में अलग-अलग सेक्शन होने चाहिए: settings, artboards, layers या swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` केवल फ़िल्टर, या `commands` वाले लाइव इफ़ेक्ट के लिए है, `api` 3 या उसके बाद और अनुमति `doc.read` के साथ +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes प्लग-इन जो डॉक्यूमेंट जानकारी माँगता है वह सौंपने के लिए बहुत बड़ी है: {MAX_CONTEXT_BYTES} बाइट्स में अधिकतम {MAX_CONTEXT_ITEMS} आर्टबोर्ड्स, लेयर्स और स्वॉचेस @msg memory budget (object {_1} needs {size} bytes of input, {left} left) मेमोरी बजट (ऑब्जेक्ट {_1} को इनपुट के {size} बाइट चाहिए, {left} शेष हैं) @msg object budget (more than {MAX_OBJECTS} read-only objects) ऑब्जेक्ट बजट ({MAX_OBJECTS} से अधिक केवल-पठन ऑब्जेक्ट) @msg the plug-in's grant can't be removed from the plug-in store प्लग-इन की अनुमति प्लग-इन स्टोर से हटाई नहीं जा सकती diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..f3407d6e4d 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7470,6 +7470,10 @@ axis Y Axis Y tengely @msg `inputs` lists `{shown}` twice az `inputs` kétszer sorolja fel ezt: `{shown}` @msg `inputs` needs `api` 2 or later az `inputs` használatához `api` 2 vagy újabb szükséges @msg `inputs` needs the permission `doc.read` az `inputs` használatához a(z) `doc.read` engedély szükséges + Read the objects it is given, and the document's settings, artboards, layers and swatches Olvashatja a kapott objektumokat, valamint a dokumentum beállításait, rajztábláit, rétegeit és színmintáit +@msg `context` must list distinct sections: settings, artboards, layers or swatches a `context` csak különböző szakaszokat sorolhat fel: settings, artboards, layers vagy swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` a `context` szűrőhöz vagy `commands` kulccsal rendelkező élő effektushoz való, `api` 3 vagy újabb mellett, a(z) `doc.read` engedéllyel +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes a bővítmény által kért dokumentumadatok túl nagyok az átadáshoz: legfeljebb {MAX_CONTEXT_ITEMS} rajztábla, réteg és színminta {MAX_CONTEXT_BYTES} bájtban @msg memory budget (object {_1} needs {size} bytes of input, {left} left) memóriakeret (a(z) {_1} objektumnak {size} bájt bemenet kell, {left} maradt) @msg object budget (more than {MAX_OBJECTS} read-only objects) objektumkeret (több mint {MAX_OBJECTS} csak olvasható objektum) @msg instruction budget utasításkeret diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..3e16bc37f7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -579,6 +579,10 @@ @msg `inputs` lists `{shown}` twice `inputs` mencantumkan `{shown}` dua kali @msg `inputs` needs `api` 2 or later `inputs` memerlukan `api` 2 atau lebih baru @msg `inputs` needs the permission `doc.read` `inputs` memerlukan izin `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Membaca objek yang diberikan kepadanya, serta pengaturan, artboard, lapisan, dan sampel warna dokumen +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` harus mencantumkan bagian yang berbeda: settings, artboards, layers, atau swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` untuk filter, atau efek langsung dengan `commands`, pada `api` 3 atau lebih baru dengan izin `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes informasi dokumen yang diminta plug-in terlalu besar untuk diserahkan: paling banyak {MAX_CONTEXT_ITEMS} artboard, lapisan, dan sampel warna dalam {MAX_CONTEXT_BYTES} byte @msg memory budget (object {_1} needs {size} bytes of input, {left} left) anggaran memori (objek {_1} memerlukan {size} byte masukan, tersisa {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) anggaran objek (lebih dari {MAX_OBJECTS} objek baca-saja) @msg instruction budget anggaran instruksi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..932c3e6b06 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7107,6 +7107,10 @@ axis Y Axis Asse Y @msg `inputs` lists `{shown}` twice `inputs` elenca `{shown}` due volte @msg `inputs` needs `api` 2 or later `inputs` richiede `api` 2 o successivo @msg `inputs` needs the permission `doc.read` `inputs` richiede l’autorizzazione `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Leggere gli oggetti che riceve, e le impostazioni, le tavole da disegno, i livelli e i campioni del documento +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` deve elencare sezioni distinte: settings, artboards, layers o swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` vale per un filtro, o un effetto dinamico con `commands`, con `api` 3 o successiva e l’autorizzazione `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes le informazioni sul documento chieste dal plug-in sono troppo grandi per essere passate: al massimo {MAX_CONTEXT_ITEMS} tavole da disegno, livelli e campioni in {MAX_CONTEXT_BYTES} byte @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget di memoria (l’oggetto {_1} richiede {size} byte di input, ne restano {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) budget di oggetti (più di {MAX_OBJECTS} oggetti di sola lettura) @msg instruction budget budget di istruzioni diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..d747c0f091 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7182,6 +7182,10 @@ axis Y Axis Y 軸 @msg `inputs` lists `{shown}` twice `inputs` に `{shown}` が 2 回指定されています @msg `inputs` needs `api` 2 or later `inputs` には `api` 2 以上が必要です @msg `inputs` needs the permission `doc.read` `inputs` には権限 `doc.read` が必要です + Read the objects it is given, and the document's settings, artboards, layers and swatches 渡されたオブジェクトと、ドキュメントの設定、アートボード、レイヤー、スウォッチの読み取り +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` には重複しないセクションを指定してください: settings、artboards、layers、swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` は、`api` 3 以降で権限 `doc.read` を持つフィルターまたは `commands` のあるライブ効果専用です +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes プラグインが求めるドキュメント情報が大きすぎて渡せません: アートボード、レイヤー、スウォッチは合わせて {MAX_CONTEXT_ITEMS} 個、{MAX_CONTEXT_BYTES} バイトまでです @msg memory budget (object {_1} needs {size} bytes of input, {left} left) メモリ予算 (オブジェクト {_1} には {size} バイトの入力が必要ですが、残りは {left} です) @msg object budget (more than {MAX_OBJECTS} read-only objects) オブジェクト予算 ({MAX_OBJECTS} 個を超える読み取り専用オブジェクト) @msg instruction budget 命令予算 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..461780c0fd 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9588,6 +9588,10 @@ axis Y Axis Y ღერძი @msg `inputs` lists `{shown}` twice `inputs`-ში `{shown}` ორჯერაა ჩამოთვლილი @msg `inputs` needs `api` 2 or later `inputs`-ს სჭირდება `api` 2 ან უფრო ახალი @msg `inputs` needs the permission `doc.read` `inputs`-ს სჭირდება ნებართვა `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches მიღებული ობიექტების და დოკუმენტის პარამეტრების, სამუშაო დაფების, შრეებისა და ფერის ნიმუშების წაკითხვა +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context`-ში განსხვავებული სექციები უნდა იყოს: settings, artboards, layers ან swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` განკუთვნილია ფილტრისთვის ან `commands`-ის მქონე ცოცხალი ეფექტისთვის, `api` 3-ზე ან უფრო ახალზე, ნებართვით `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes პლაგინის მიერ მოთხოვნილი დოკუმენტის ინფორმაცია ზედმეტად დიდია გადასაცემად: მაქსიმუმ {MAX_CONTEXT_ITEMS} სამუშაო დაფა, შრე და ფერის ნიმუში {MAX_CONTEXT_BYTES} ბაიტში @msg memory budget (object {_1} needs {size} bytes of input, {left} left) მეხსიერების ბიუჯეტი (ობიექტს {_1} სჭირდება შეყვანის {size} ბაიტი, დარჩენილია {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) ობიექტების ბიუჯეტი ({MAX_OBJECTS}-ზე მეტი მხოლოდ წასაკითხი ობიექტი) @msg instruction budget ინსტრუქციების ბიუჯეტი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..5790315032 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7079,6 +7079,10 @@ axis Y Axis Y축 @msg `inputs` lists `{shown}` twice `inputs`에 `{shown}`이(가) 두 번 나열되어 있습니다 @msg `inputs` needs `api` 2 or later `inputs`에는 `api` 2 이상이 필요합니다 @msg `inputs` needs the permission `doc.read` `inputs`에는 `doc.read` 권한이 필요합니다 + Read the objects it is given, and the document's settings, artboards, layers and swatches 전달받은 개체와 문서의 설정, 아트보드, 레이어, 견본 읽기 +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context`에는 서로 다른 섹션을 나열해야 합니다: settings, artboards, layers 또는 swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context`는 `api` 3 이상이고 `doc.read` 권한이 있는 필터 또는 `commands`가 있는 라이브 효과에만 쓸 수 있습니다 +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes 플러그인이 요청한 문서 정보가 너무 커서 넘길 수 없습니다: 아트보드, 레이어, 견본은 {MAX_CONTEXT_BYTES}바이트 안에서 최대 {MAX_CONTEXT_ITEMS}개입니다 @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 메모리 예산(개체 {_1}에 입력 {size}바이트가 필요하지만 {left}바이트 남음) @msg object budget (more than {MAX_OBJECTS} read-only objects) 개체 예산(읽기 전용 개체 {MAX_OBJECTS}개 초과) @msg instruction budget 명령어 예산 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..465ca7fca0 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -543,6 +543,10 @@ liquify-list-end {0}, {1} {0} en {1} @msg `inputs` lists `{shown}` twice `inputs` noemt `{shown}` twee keer @msg `inputs` needs `api` 2 or later `inputs` vereist `api` 2 of hoger @msg `inputs` needs the permission `doc.read` `inputs` vereist de machtiging `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches De objecten lezen die het krijgt, en de instellingen, tekengebieden, lagen en stalen van het document +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` moet verschillende secties noemen: settings, artboards, layers of swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` is voor een filter, of een live-effect met `commands`, bij `api` 3 of later en met de machtiging `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes de documentgegevens die de plug-in vraagt zijn te groot om door te geven: hoogstens {MAX_CONTEXT_ITEMS} tekengebieden, lagen en stalen in {MAX_CONTEXT_BYTES} bytes @msg memory budget (object {_1} needs {size} bytes of input, {left} left) geheugenbudget (object {_1} heeft {size} bytes invoer nodig, {left} over) @msg object budget (more than {MAX_OBJECTS} read-only objects) objectbudget (meer dan {MAX_OBJECTS} alleen-lezen objecten) @msg instruction budget instructiebudget diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..3def56d8e2 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7340,6 +7340,10 @@ axis Y Axis Oś Y @msg `inputs` lists `{shown}` twice `inputs` wymienia `{shown}` dwa razy @msg `inputs` needs `api` 2 or later `inputs` wymaga `api` 2 lub nowszego @msg `inputs` needs the permission `doc.read` `inputs` wymaga uprawnienia `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Odczytywać obiekty, które otrzymuje, oraz ustawienia, obszary kompozycji, warstwy i próbki dokumentu +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` musi wymieniać różne sekcje: settings, artboards, layers lub swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` dotyczy filtra albo efektu na żywo z `commands`, z `api` 3 lub nowszym i z uprawnieniem `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes informacje o dokumencie, o które prosi wtyczka, są zbyt duże, aby je przekazać: najwyżej {MAX_CONTEXT_ITEMS} obszarów kompozycji, warstw i próbek w {MAX_CONTEXT_BYTES} bajtach @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budżet pamięci (obiekt {_1} wymaga {size} bajtów danych wejściowych, pozostało {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) budżet obiektów (ponad {MAX_OBJECTS} obiektów tylko do odczytu) @msg instruction budget budżet instrukcji diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..e4ff196410 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7384,6 +7384,10 @@ axis Y Axis Eixo Y @msg `inputs` lists `{shown}` twice `inputs` lista `{shown}` duas vezes @msg `inputs` needs `api` 2 or later `inputs` exige `api` 2 ou posterior @msg `inputs` needs the permission `doc.read` `inputs` exige a permissão `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Ler os objetos que recebe, e as configurações, as mesas de trabalho, as camadas e as amostras do documento +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` deve listar seções distintas: settings, artboards, layers ou swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` é para um filtro, ou um efeito dinâmico com `commands`, com `api` 3 ou posterior e a permissão `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes as informações do documento que o plug-in pede são grandes demais para serem entregues: no máximo {MAX_CONTEXT_ITEMS} mesas de trabalho, camadas e amostras em {MAX_CONTEXT_BYTES} bytes @msg memory budget (object {_1} needs {size} bytes of input, {left} left) orçamento de memória (o objeto {_1} precisa de {size} bytes de entrada, restam {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) orçamento de objetos (mais de {MAX_OBJECTS} objetos somente leitura) @msg instruction budget orçamento de instruções diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..3690bebeb1 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7107,6 +7107,10 @@ axis Y Axis Ось Y @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано дважды @msg `inputs` needs `api` 2 or later для `inputs` нужен `api` 2 или выше @msg `inputs` needs the permission `doc.read` для `inputs` нужно разрешение `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Читать переданные ему объекты, а также параметры, монтажные области, слои и образцы документа +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` должен перечислять разные разделы: settings, artboards, layers или swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` допустим только для фильтра или динамического эффекта с `commands`, с `api` 3 или выше и с разрешением `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes сведения о документе, которые запрашивает модуль, слишком велики для передачи: не более {MAX_CONTEXT_ITEMS} монтажных областей, слоев и образцов в {MAX_CONTEXT_BYTES} байтах @msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет памяти (объекту {_1} нужно {size} байт входных данных, осталось {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) бюджет объектов (более {MAX_OBJECTS} объектов только для чтения) @msg instruction budget бюджет инструкций diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..25b796cacb 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7497,6 +7497,10 @@ axis Y Axis Y-axel @msg `inputs` lists `{shown}` twice `inputs` anger `{shown}` två gånger @msg `inputs` needs `api` 2 or later `inputs` kräver `api` 2 eller senare @msg `inputs` needs the permission `doc.read` `inputs` kräver behörigheten `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Läsa objekten den får, och dokumentets inställningar, ritytor, lager och färgrutor +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` måste ange olika avsnitt: settings, artboards, layers eller swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` gäller ett filter eller en liveeffekt med `commands`, med `api` 3 eller senare och behörigheten `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes dokumentinformationen som pluginet begär är för stor för att lämnas över: högst {MAX_CONTEXT_ITEMS} ritytor, lager och färgrutor på {MAX_CONTEXT_BYTES} byte @msg memory budget (object {_1} needs {size} bytes of input, {left} left) minnesbudget (objekt {_1} behöver {size} byte indata, {left} återstår) @msg object budget (more than {MAX_OBJECTS} read-only objects) objektbudget (fler än {MAX_OBJECTS} skrivskyddade objekt) @msg the plug-in's grant can't be removed from the plug-in store pluginets behörighet kan inte tas bort ur pluginlagret diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..c1617c0e26 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7557,6 +7557,10 @@ axis Y Axis Y ekseni @msg `inputs` lists `{shown}` twice `inputs` `{shown}` değerini iki kez listeliyor @msg `inputs` needs `api` 2 or later `inputs` için `api` 2 veya üstü gerekir @msg `inputs` needs the permission `doc.read` `inputs` için `doc.read` izni gerekir + Read the objects it is given, and the document's settings, artboards, layers and swatches Kendisine verilen nesneleri ve belgenin ayarlarını, çalışma yüzeylerini, katmanlarını ve renk örneklerini okuma +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` farklı bölümleri listelemelidir: settings, artboards, layers veya swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` yalnızca `api` 3 veya sonrasında, `doc.read` izniyle bir filtre ya da `commands` içeren bir canlı efekt içindir +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes eklentinin istediği belge bilgileri aktarılamayacak kadar büyük: {MAX_CONTEXT_BYTES} bayt içinde en fazla {MAX_CONTEXT_ITEMS} çalışma yüzeyi, katman ve renk örneği @msg memory budget (object {_1} needs {size} bytes of input, {left} left) bellek bütçesi (nesne {_1} için {size} bayt girdi gerekiyor, {left} kaldı) @msg object budget (more than {MAX_OBJECTS} read-only objects) nesne bütçesi ({MAX_OBJECTS} adetten fazla salt okunur nesne) @msg instruction budget talimat bütçesi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..8b772a4737 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7089,6 +7089,10 @@ axis Y Axis Вісь Y @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано двічі @msg `inputs` needs `api` 2 or later для `inputs` потрібен `api` 2 або новіший @msg `inputs` needs the permission `doc.read` для `inputs` потрібен дозвіл `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Читати передані йому об’єкти, а також параметри, монтажні області, шари та зразки документа +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` має перелічувати різні розділи: settings, artboards, layers або swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` дозволено лише для фільтра або динамічного ефекту з `commands`, з `api` 3 або вище та з дозволом `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes відомості про документ, які запитує модуль, завеликі для передавання: не більше {MAX_CONTEXT_ITEMS} монтажних областей, шарів і зразків у {MAX_CONTEXT_BYTES} байтах @msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет пам’яті (об’єкту {_1} потрібно {size} байтів вхідних даних, залишилося {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) бюджет об’єктів (понад {MAX_OBJECTS} об’єктів лише для читання) @msg instruction budget бюджет інструкцій diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..cb4110c1b8 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7136,6 +7136,10 @@ axis Y Axis Trục Y @msg `inputs` lists `{shown}` twice `inputs` liệt kê `{shown}` hai lần @msg `inputs` needs `api` 2 or later `inputs` cần `api` 2 trở lên @msg `inputs` needs the permission `doc.read` `inputs` cần quyền `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches Đọc các đối tượng được trao cho nó, cùng các thiết lập, bảng vẽ, lớp và mẫu màu của tài liệu +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` phải liệt kê các phần khác nhau: settings, artboards, layers hoặc swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` dành cho bộ lọc, hoặc hiệu ứng trực tiếp có `commands`, ở `api` 3 trở lên và có quyền `doc.read` +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes thông tin tài liệu mà plug-in yêu cầu quá lớn để chuyển giao: tối đa {MAX_CONTEXT_ITEMS} bảng vẽ, lớp và mẫu màu trong {MAX_CONTEXT_BYTES} byte @msg memory budget (object {_1} needs {size} bytes of input, {left} left) ngân sách bộ nhớ (đối tượng {_1} cần {size} byte đầu vào, còn lại {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) ngân sách đối tượng (hơn {MAX_OBJECTS} đối tượng chỉ đọc) @msg instruction budget ngân sách lệnh diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..926d45dfc5 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7317,6 +7317,10 @@ axis Y Axis Y 轴 @msg `inputs` lists `{shown}` twice `inputs` 列出了两次 `{shown}` @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要权限 `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches 读取交给它的对象,以及文档的设置、画板、图层和色板 +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` 必须列出互不相同的部分:settings、artboards、layers 或 swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` 仅适用于 `api` 3 或更高、具有权限 `doc.read` 的滤镜或带 `commands` 的实时效果 +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes 增效工具请求的文档信息太大,无法传递:画板、图层和色板合计最多 {MAX_CONTEXT_ITEMS} 个,最多 {MAX_CONTEXT_BYTES} 字节 @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 内存预算(对象 {_1} 需要 {size} 字节的输入,剩余 {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) 对象预算(超过 {MAX_OBJECTS} 个只读对象) @msg instruction budget 指令预算 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..c0c540f255 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7138,6 +7138,10 @@ axis Y Axis Y 軸 @msg `inputs` lists `{shown}` twice `inputs` 列出了兩次 `{shown}` @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要權限 `doc.read` + Read the objects it is given, and the document's settings, artboards, layers and swatches 讀取交給它的物件,以及文件的設定、工作區域、圖層和色票 +@msg `context` must list distinct sections: settings, artboards, layers or swatches `context` 必須列出互不相同的部分:settings、artboards、layers 或 swatches +@msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` 僅適用於 `api` 3 或更高、具有權限 `doc.read` 的濾鏡或帶 `commands` 的即時效果 +@msg the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes 增效模組要求的文件資訊太大,無法傳遞:工作區域、圖層和色票合計最多 {MAX_CONTEXT_ITEMS} 個,最多 {MAX_CONTEXT_BYTES} 位元組 @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 記憶體預算(物件 {_1} 需要 {size} 位元組的輸入,剩餘 {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) 物件預算(超過 {MAX_OBJECTS} 個唯讀物件) @msg instruction budget 指令預算 diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 180c459453..f7ed637eaf 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -224,12 +224,17 @@ pub fn install_plugin(app: &mut VectorcraftApp, p: &Value) -> Result String { +/// the `commands` it may call for `commands`, and for `doc.read` of a plug-in whose manifest asks +/// for document information (`context`), that information too; a name the app doesn't know is +/// shown as it is. +fn permission_words(name: &str, commands: &[String], context: bool) -> String { let words = match permissions::Permission::parse(name) { Some(permissions::Permission::Commands) => { return crate::i18n::fmt(tl!("Run these commands on the document: {ids}"), &[("ids", &commands.join(", "))]); } + Some(permissions::Permission::DocRead) if context => { + tl!("Read the objects it is given, and the document's settings, artboards, layers and swatches") + } Some(permissions::Permission::DocRead) => tl!("Read the objects it is given"), Some(permissions::Permission::DocWrite) => tl!("Change, add and delete objects in the document"), Some(permissions::Permission::State) => tl!("Keep data of its own with the document"), @@ -305,7 +310,8 @@ pub fn install_module(app: &mut VectorcraftApp, module: Value) -> Result