From eb9387dbb3b55a04e99fafcb16c8c104c9b89f07 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:06:16 -0800 Subject: [PATCH 01/16] Swatches: Add Selected Colors adds the selected art's colors as global swatches The Swatches panel menu gets Add Selected Colors next to Add Used Colors. It is on while art is selected and runs swatch.addUsedColors with selection and global: each color of the selected art that the panel does not hold yet becomes a global swatch, and the art's matching paints link to it, in one undo step. swatch.addUsedColors no longer records an undo step when there is no new color to add. --- crates/engine/src/cmd/swatch.rs | 32 +++++++++++---- crates/engine/src/tests/swatchcmds.rs | 21 ++++++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/panels/swatches/actions.rs | 5 +++ crates/ui-egui/src/panels/swatches/tests.rs | 39 +++++++++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 34 files changed, 121 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index b43446af8b..bdd916d5f0 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -6,7 +6,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Gradient, GradientKind, GradientMethod, GradientStop, Paint, Swatch, SwatchGroup, tint_percent}; use vectorcraft_doc::pattern::pattern_paint; use vectorcraft_doc::swatches::{LinkFn, PaintFn, color_name, map_node_paints, map_node_solid_paints, node_colors}; -use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_doc::{Document, NodeId, Selection}; use super::paint::paint_from; use super::{CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, index, ok, str_param, switch_or}; @@ -75,7 +75,7 @@ pub fn specs() -> Vec { "Add Used Colors", ["Window", "Swatches"], None, - "{selection?: false (only the selected art's colours; default: all the art's), global?: false (the new swatches are global and the matching unlinked colours in that art link to them)} add a swatch for each colour used (fills, strokes, text, gradient stops, mesh points) that no solid swatch has yet, as one undo step → {added: [names], linked}", + "{selection?: false (only the selected art's colours; default: all the art's), global?: false (the new swatches are global and the matching unlinked colours in that art link to them)} add a swatch for each colour used (fills, strokes, text, gradient stops, mesh points) that no solid swatch has yet, as one undo step (none when there is no new color; the Swatches panel menu's Add Selected Colors sends selection and global) → {added: [names], linked}", has_doc, swatch_add_used ), @@ -1003,20 +1003,36 @@ fn swatch_sort(s: &mut Session, _: &Value) -> Result { ok() } +/// The colors of the art `ids` that no swatch links them to and no solid swatch has, each once, in +/// paint order: the swatches Add Used Colors makes. +fn new_used_colors(d: &Document, ids: &[NodeId]) -> Vec { + let (mut linked_to, mut colors) = (vec![], vec![]); + artwork_colors(d, ids, false, &mut linked_to, &mut colors); + // Colors a solid swatch already has are skipped. + let have: HashSet = d.swatches_iter().filter_map(|w| w.paint.color()).filter_map(|c| color_key(&c)).collect(); + colors.retain(|c| color_key(c).is_none_or(|k| !have.contains(&k))); + colors +} + fn swatch_add_used(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.addUsedColors"; let global = switch_or(p, "global", false, C)?; let only_selection = switch_or(p, "selection", false, C)?; - let (added, linked) = s.edit("Add Used Colors", |d, sel| { + let used_ids = |d: &Document, sel: &Selection| -> Result> { let ids: Vec = if only_selection { sel.objects.clone() } else { d.layers.iter().map(|l| l.id).collect() }; if only_selection && ids.is_empty() { return Err(bad(C, "select artwork to add its colours")); } - let (mut linked_to, mut colors) = (vec![], vec![]); - artwork_colors(d, &ids, false, &mut linked_to, &mut colors); - // Colours a solid swatch already has are skipped. - let have: HashSet = d.swatches_iter().filter_map(|w| w.paint.color()).filter_map(|c| color_key(&c)).collect(); - colors.retain(|c| color_key(c).is_none_or(|k| !have.contains(&k))); + Ok(ids) + }; + // With no new color there is nothing to add or link, so no edit and no undo step. + let st = s.doc()?; + if new_used_colors(&st.doc, &used_ids(&st.doc, &st.selection)?).is_empty() { + return Ok(json!({"added": [], "linked": 0})); + } + let (added, linked) = s.edit("Add Used Colors", |d, sel| { + let ids = used_ids(&*d, &*sel)?; + let colors = new_used_colors(d, &ids); let mut free = d.free_swatch_names(); let mut links = vec![]; for c in colors { diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index af059e5e33..b190459802 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -125,6 +125,27 @@ fn add_used_colors_skips_colours_that_have_swatches() { assert!(doc(&s).swatch("R=171 G=205 B=239").unwrap().global); } +/// A run that finds no new color, over all the art or the selection, records no undo step. +#[test] +fn add_used_colors_with_no_new_color_records_no_undo_step() { + let mut s = session(); + let a = rect_filled(&mut s, json!({"color": "#123456"})); + run(&mut s, "swatch.addUsedColors", json!({})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let before = doc(&s).clone(); + let undo = undo_len(&s); + for p in [json!({}), json!({"selection": true, "global": true})] { + assert_eq!(run(&mut s, "swatch.addUsedColors", p), json!({"added": [], "linked": 0})); + assert_eq!(undo_len(&s), undo); + assert_eq!(*doc(&s), before); + } + // An empty selection is still an error, with nothing changed. + run(&mut s, "select.set", json!({"ids": []})); + let undo = undo_len(&s); + assert!(s.execute("swatch.addUsedColors", &json!({"selection": true})).is_err()); + assert_eq!(undo_len(&s), undo); +} + /// Give `id` the fill `p` exactly as written (a command would round or convert some colors). fn set_fill(s: &mut Session, id: NodeId, p: Paint) { std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.set_fill(p); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..cf8a2b6be1 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -125,6 +125,7 @@ Add to Selection Добавяне към селекцията Add to Swatches Добавяне към образци Add Used Colors Добавяне на използваните цветове + Add Selected Colors Добавяне на избраните цветове Additional Plug-ins Folder Допълнителна папка за плъгини Additional Fonts Folder Допълнителна папка за шрифтове Adjust Adjoining Width Points Регулиране на прилежащите точки за ширина diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..088a9555a5 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4103,6 +4103,7 @@ theme Appearance Izgled Add to Graphic Styles Dodaj u grafičke stilove Graphic Style Library Biblioteka grafičkih stilova Add Used Colors Dodaj korištene boje + Add Selected Colors Dodaj odabrane boje Delete Swatch Izbriši uzorak boje Duplicate Swatch Dupliciraj uzorak boje Merge Swatches Spoji uzorke boja diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..2221aa545a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -220,6 +220,7 @@ Add to Symbols Afegeix als símbols Add to the Current Shortcuts Afegeix a les dreceres actuals Add Used Colors Afegeix els colors utilitzats + Add Selected Colors Afegeix els colors seleccionats Additional Fonts Folder Carpeta addicional de tipus de lletra Additional Plug-ins Folder Carpeta addicional de complements Adjust Adjoining Width Points Ajusta els punts d’amplada contigus diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..a144e1b28e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4208,6 +4208,7 @@ theme Appearance Motiv Add to Graphic Styles Přidat do grafických stylů Graphic Style Library Knihovna grafických stylů Add Used Colors Přidat použité barvy + Add Selected Colors Přidat vybrané barvy Delete Swatch Odstranit položku vzorníku Duplicate Swatch Duplikovat položku vzorníku Merge Swatches Sloučit položky vzorníku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..9bd3dbdc46 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6591,6 +6591,7 @@ theme Appearance Udseende Add to Graphic Styles Føj til grafikstile Graphic Style Library Grafikstilbibliotek Add Used Colors Tilføj anvendte farver + Add Selected Colors Tilføj valgte farver Delete Swatch Slet farveprøve Duplicate Swatch Duplikér farveprøve Merge Swatches Flet farveprøver diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..c0c04bc125 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -114,6 +114,7 @@ Add to Selection Zur Auswahl hinzufügen Add to Swatches Zu Farbfeldern hinzufügen Add Used Colors Verwendete Farben hinzufügen + Add Selected Colors Ausgewählte Farben hinzufügen Additional Plug-ins Folder Zusätzlicher Plug-in-Ordner Additional Fonts Folder Zusätzlicher Schriftenordner Adjust Adjoining Width Points Angrenzende Breitenpunkte anpassen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..5ef66fa13b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -119,6 +119,7 @@ Add to Selection Προσθήκη στην επιλογή Add to Swatches Προσθήκη στα δείγματα χρωμάτων Add Used Colors Προσθήκη των χρησιμοποιημένων χρωμάτων + Add Selected Colors Προσθήκη των επιλεγμένων χρωμάτων Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών Adjust Adjoining Width Points Ρύθμιση γειτονικών σημείων πλάτους diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..87e5e4f821 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -139,6 +139,7 @@ Add to Selection Agregar a la selección Add to Swatches Agregar a muestras Add Used Colors Agregar colores usados + Add Selected Colors Agregar colores seleccionados Additional Plug-ins Folder Carpeta de plugins adicionales Additional Fonts Folder Carpeta de fuentes adicionales Adjust Adjoining Width Points Ajustar puntos de anchura contiguos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..ff79bdd9fe 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4132,6 +4132,7 @@ theme Appearance Ulkoasu Add to Graphic Styles Lisää grafiikkatyyleihin Graphic Style Library Grafiikkatyylikirjasto Add Used Colors Lisää käytetyt värit + Add Selected Colors Lisää valitut värit Delete Swatch Poista värimalli Duplicate Swatch Monista värimalli Merge Swatches Yhdistä värimallit diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1cff1c8ad0..1c5092f1e3 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -140,6 +140,7 @@ Add to Selection Ajouter à la sélection Add to Swatches Ajouter au nuancier Add Used Colors Ajouter les couleurs utilisées + Add Selected Colors Ajouter les couleurs sélectionnées Additional Plug-ins Folder Dossier de modules externes supplémentaires Additional Fonts Folder Dossier de polices supplémentaires Adjust Adjoining Width Points Ajuster les points de largeur adjacents diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..0cf3e191c8 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -148,6 +148,7 @@ Add Selected Artwork as One Asset પસંદ કરેલી આર્ટવર્ક એક સંપત્તિ તરીકે ઉમેરો Add Spine Point સ્પાઇન બિંદુ ઉમેરો Add Used Colors વપરાયેલા રંગ ઉમેરો + Add Selected Colors પસંદ કરેલા રંગ ઉમેરો Add as Effect ઇફેક્ટ તરીકે ઉમેરો Add space to fit ફિટ કરવા જગ્યા ઉમેરો Add to Brushes બ્રશમાં ઉમેરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..d1d3857154 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -254,6 +254,7 @@ Add to Symbols सिंबल्स में जोड़ें Add to the Current Shortcuts वर्तमान शॉर्टकट में जोड़ें Add Used Colors उपयोग किए रंग जोड़ें + Add Selected Colors सिलेक्टेड रंग जोड़ें Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर Adjust Adjoining Width Points सटे हुए चौड़ाई पॉइंट समायोजित करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..8cabbafab8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -208,6 +208,7 @@ Add to Selection Hozzáadás a kijelöléshez Add to Swatches Hozzáadás a színmintákhoz Add Used Colors Használt színek hozzáadása + Add Selected Colors Kijelölt színek hozzáadása Additional Fonts Folder További betűtípusok mappája Additional Plug-ins Folder További bővítmények mappája Adjust Adjoining Width Points Szomszédos szélességi pontok igazítása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..89e7029652 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3868,6 +3868,7 @@ theme Appearance Tampilan Add to Graphic Styles Tambahkan ke gaya grafis Graphic Style Library Pustaka gaya grafis Add Used Colors Tambahkan warna yang digunakan + Add Selected Colors Tambahkan warna terpilih Delete Swatch Hapus sampel Duplicate Swatch Duplikatkan sampel Merge Swatches Gabungkan sampel diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..9edd8be8ae 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -139,6 +139,7 @@ Add to Selection Aggiungi alla selezione Add to Swatches Aggiungi ai campioni Add Used Colors Aggiungi colori usati + Add Selected Colors Aggiungi colori selezionati Additional Plug-ins Folder Cartella plug-in aggiuntivi Additional Fonts Folder Cartella font aggiuntivi Adjust Adjoining Width Points Regola punti di larghezza adiacenti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..06cc690f82 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1063,6 +1063,7 @@ digits Malayalam マラヤーラム数字 Add Selected Artwork as One Asset 選択したアートワークを 1 つのアセットとして追加 Add Spine Point スパインポイントを追加 Add Used Colors 使用中のカラーを追加 + Add Selected Colors 選択したカラーを追加 Add to Graphic Styles グラフィックスタイルに追加 Add to Profiles プロファイルに追加 Add to Profiles… プロファイルに追加… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..77a80337ec 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5841,6 +5841,7 @@ theme Appearance იერსახე Add to Graphic Styles გრაფიკულ სტილებში დამატება Graphic Style Library გრაფიკული სტილების ბიბლიოთეკა Add Used Colors გამოყენებული ფერების დამატება + Add Selected Colors მონიშნული ფერების დამატება Delete Swatch ფერის ნიმუშის წაშლა Duplicate Swatch ფერის ნიმუშის დუბლირება Merge Swatches ფერის ნიმუშების შერწყმა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..7233e7e60b 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1053,6 +1053,7 @@ digits Malayalam 말라얄람어 Add Selected Artwork as One Asset 선택한 아트워크를 하나의 에셋으로 추가 Add Spine Point 스파인 포인트 추가 Add Used Colors 사용한 색상 추가 + Add Selected Colors 선택한 색상 추가 Add to Graphic Styles 그래픽 스타일에 추가 Add to Profiles 프로필에 추가 Add to Profiles… 프로필에 추가… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..f479269e2c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4485,6 +4485,7 @@ theme Appearance Vormgeving Add to Graphic Styles Aan grafische stijlen toevoegen Graphic Style Library Bibliotheek met grafische stijlen Add Used Colors Gebruikte kleuren toevoegen + Add Selected Colors Geselecteerde kleuren toevoegen Delete Swatch Kleurstaal verwijderen Duplicate Swatch Kleurstaal dupliceren Merge Swatches Kleurstalen samenvoegen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..d54bdddc4c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4067,6 +4067,7 @@ theme Appearance Wygląd Add to Graphic Styles Dodaj do stylów graficznych Graphic Style Library Biblioteka stylów graficznych Add Used Colors Dodaj użyte kolory + Add Selected Colors Dodaj zaznaczone kolory Delete Swatch Usuń próbkę Duplicate Swatch Powiel próbkę Merge Swatches Scal próbki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..ed47a0d4b8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -140,6 +140,7 @@ Add Selected Artwork as One Asset Adicionar Arte Selecionada como Um Ativo Add Spine Point Adicionar Ponto de Coluna Add Used Colors Adicionar Cores Usadas + Add Selected Colors Adicionar Cores Selecionadas Add to Graphic Styles Adicionar aos Estilos Gráficos Add to Profiles Adicionar aos Perfis Add to Profiles… Adicionar aos Perfis… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..68e5080c5c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -137,6 +137,7 @@ Add to Selection Добавить к выделению Add to Swatches Добавить в образцы Add Used Colors Добавить использованные цвета + Add Selected Colors Добавить выбранные цвета Additional Plug-ins Folder Папка дополнительных модулей Additional Fonts Folder Папка дополнительных шрифтов Adjust Adjoining Width Points Настроить смежные точки ширины diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..11b04498ef 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -127,6 +127,7 @@ Add to Selection Lägg till i markering Add to Swatches Lägg till i färgrutor Add Used Colors Lägg till använda färger + Add Selected Colors Lägg till markerade färger Additional Plug-ins Folder Mapp för ytterligare plugins Additional Fonts Folder Mapp för ytterligare typsnitt Adjust Adjoining Width Points Justera angränsande breddpunkter diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..14fa4bfa54 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -124,6 +124,7 @@ Add to Selection Seçime Ekle Add to Swatches Renk Örneklerine Ekle Add Used Colors Kullanılan Renkleri Ekle + Add Selected Colors Seçilen Renkleri Ekle Additional Plug-ins Folder Ek Eklentiler Klasörü Additional Fonts Folder Ek Yazı Tipleri Klasörü Adjust Adjoining Width Points Bitişik Genişlik Noktalarını Ayarlayın diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..0423218610 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -133,6 +133,7 @@ Add to Selection Додати до виділення Add to Swatches Додати до зразків Add Used Colors Додати використані кольори + Add Selected Colors Додати вибрані кольори Additional Plug-ins Folder Папка додаткових модулів Additional Fonts Folder Папка додаткових шрифтів Adjust Adjoining Width Points Налаштувати суміжні точки ширини diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..174d660777 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -154,6 +154,7 @@ Add to Selection Thêm vào vùng chọn Add to Swatches Thêm vào mẫu màu Add Used Colors Thêm các màu đã dùng + Add Selected Colors Thêm các màu đã chọn Additional Fonts Folder Thư mục phông bổ sung Additional Plug-ins Folder Thư mục plug-in bổ sung Adjust Adjoining Width Points Điều chỉnh các điểm chiều rộng kề nhau diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..eee893426b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -88,6 +88,7 @@ Add to Selection 添加到选区 Add to Swatches 添加到色板 Add Used Colors 添加已用颜色 + Add Selected Colors 添加所选颜色 Additional Plug-ins Folder 附加增效工具文件夹 Additional Fonts Folder 附加字体文件夹 Adjust Adjoining Width Points 调整相邻宽度点 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..9170b11adc 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -97,6 +97,7 @@ Add to Selection 加入選取範圍 Add to Swatches 新增至色票 Add Used Colors 新增使用中的顏色 + Add Selected Colors 新增所選顏色 Additional Plug-ins Folder 額外的增效模組資料夾 Additional Fonts Folder 額外的字體資料夾 Adjust Adjoining Width Points 調整相鄰寬度點 diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index b183787366..c022395bdd 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -164,6 +164,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Add Used Colors"), true, false) { app.run("swatch.addUsedColors", json!({})).ok(); } + // The selected art's new colors, as global swatches its paints link to. + let art_selected = app.session.active().is_some_and(|st| !st.selection.objects.is_empty()); + if menu_item(ui, tl!("Add Selected Colors"), art_selected, false) { + app.run("swatch.addUsedColors", json!({"selection": true, "global": true})).ok(); + } ui.separator(); if menu_item(ui, tl!("Sort by Name"), true, false) { app.run("swatch.sortByName", json!({})).ok(); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index a847fd44cf..98d66b96fa 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -1069,3 +1069,42 @@ fn the_list_fills_a_tall_panel_above_its_footer() { let loose = list(None); assert!(loose.height() <= 150.5, "unsized, the list keeps its height: {loose:?}"); } + +/// The panel menu's Add Selected Colors adds only the selected art's new colors, as global swatches +/// the art links to, in one undo step; with nothing selected it is off. +#[test] +fn add_selected_colors_adds_the_selection_colors_as_global_swatches() { + let mut app = app(); + let rect = |app: &mut VectorcraftApp, color: &str| { + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [id], "color": color})).unwrap(); + app.run("paint.setStroke", json!({"ids": [id], "none": true})).unwrap(); + id + }; + let picked = rect(&mut app, "#abcdef"); + rect(&mut app, "#fedcba"); + let ctx = context(); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + app.run("select.set", json!({"ids": []})).unwrap(); + let (before, steps) = (app.session.active().unwrap().doc.clone(), undo(&app)); + click_menu_item(&mut app, &ctx, "Add Selected Colors"); + assert_eq!(app.session.active().unwrap().doc, before, "off with nothing selected"); + assert_eq!(undo(&app), steps); + app.run("select.set", json!({"ids": [picked]})).unwrap(); + let (before, steps) = (app.session.active().unwrap().doc.clone(), undo(&app)); + click_menu_item(&mut app, &ctx, "Add Selected Colors"); + let doc = &app.session.active().unwrap().doc; + let swatch = doc.swatch("R=171 G=205 B=239").expect("the selected art's color is a swatch"); + assert!(swatch.global); + assert!(doc.swatch("R=254 G=220 B=186").is_none(), "unselected art adds nothing"); + let fill = doc.node(vectorcraft_doc::NodeId(picked.as_u64().unwrap())).unwrap().appearance.fill_paint(); + assert!(matches!(fill, Paint::Solid { swatch: Some(ref n), .. } if n == "R=171 G=205 B=239"), "{fill:?}"); + assert_eq!(undo(&app), steps + 1); + // Run again, the color is in the panel already: nothing is added and no undo step is recorded. + let after = app.session.active().unwrap().doc.clone(); + click_menu_item(&mut app, &ctx, "Add Selected Colors"); + assert_eq!(app.session.active().unwrap().doc, after); + assert_eq!(undo(&app), steps + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, before); +} diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..4bb1633eae 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1034,7 +1034,9 @@ art's colours (by default as global swatches the art links to). `swatch.move {names, to?, group?}` reorders swatches or moves them into or out of a colour group (as dragging them in the Swatches panel does); give colour group names instead to reorder the groups. Dropping a swatch on art in the app runs `paint.setFill` (or `paint.setStroke`, the active proxy) with `ids: [the object under the pointer]`. -The Swatches panel menu's commands: `swatch.addUsedColors {selection?, global?}`, `swatch.unused` (a query: the +The Swatches panel menu's commands: `swatch.addUsedColors {selection?, global?}` (Add Used Colors sends `{}`; Add +Selected Colors, on while art is selected, sends `{selection: true, global: true}`; a run with no new color records no +undo step), `swatch.unused` (a query: the names Select All Unused selects; a spot swatch counts as used while an image placed from a DCS file has a plate of its ink), `swatch.merge {names}` (the first is kept; gradient stops linked to the others drop their process plates), `swatch.ungroup {name}` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..ed93183ec2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1650,6 +1650,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. A swatch step in `command.batch` (Delete, Swatch Options, Merge, Edit Color Group) changes the fill and stroke for new art as the command run on its own does, so art drawn later in the batch or after it takes the same paint; a batch that fails, and a canceled batch preview, put back the paints it started with, and a canceled Swatch Options preview leaves them as they were. These swatch commands also change the fills and strokes of the appearance new art takes, and Undo and Redo of the command or the batch put the paints for new art back with the swatches. Spot Colors options (`swatch.spotOptions`) and Default Swatches with replace (`swatch.resetDefaults {replace: true}`) as `command.batch` steps also change the fill and stroke for new art as each command run on its own does: a fill or stroke linked to a Lab spot swatch keeps its link and tint and takes the Lab values or their CMYK equivalent, and one linked to a swatch the replace removes keeps its color and loses the link. Evidence: `swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do`, `spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does`, `default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does`, `undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints`, `swatch_edits_reach_the_paints_of_the_new_art_template`, `a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed` and `canceling_a_swatch_options_preview_keeps_the_new_art_paints` in `crates/engine/src/tests/swatches.rs`. Add Used Colors (`swatch.addUsedColors`) and Select All Unused (`swatch.unused`) look colors, swatch names, links, tints and gradients up in hash sets instead of searching every swatch and color for each color or linked paint (New Color Group from artwork too), and New Swatch with several colors (`swatch.new`), New Color Group (`swatch.newGroup`) and Edit Color Group (`swatch.editGroup`) name their new swatches from one set of the names already taken. The new swatches keep their names, order and links, and Select All Unused lists the same swatches. Evidence: `add_used_colors_adds_each_new_color_once_with_free_names`, `add_used_colors_global_links_every_paint_of_a_new_color`, `unused_matches_links_tints_colors_gradients_and_patterns_exactly`, `new_swatches_from_colors_are_numbered_after_names_already_taken`, `new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches`, `new_color_group_from_artwork_lists_each_color_once_with_free_names` and `edit_color_group_numbers_extra_colors_after_the_names_it_keeps` in `crates/engine/src/tests/swatchcmds.rs`; `free_swatch_names_match_naming_each_swatch_as_it_is_added` and `free_swatch_names_match_new_swatch_names_as_swatches_are_added` in `crates/doc/src/swatches.rs`. + The Swatches panel menu has Add Selected Colors, on while art is selected: it adds a swatch for each color of the selected art that the panel does not hold yet, as global swatches the art's matching paints link to, in one undo step ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/use-swatches/add-colors-to-swatches.html) describes the panel menu command that adds the selected artwork's colors). The swatch names and the colors it reads (fills, strokes, text, gradient stops, mesh points) are VectorCraft's own, as for Add Used Colors. Add Used Colors and Add Selected Colors record no undo step when there is no new color. Evidence: `add_selected_colors_adds_the_selection_colors_as_global_swatches` in `crates/ui-egui/src/panels/swatches/tests.rs`; `add_used_colors_with_no_new_color_records_no_undo_step` in `crates/engine/src/tests/swatchcmds.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. SVG writes the fill color through a coverage mask (or a colorized PNG in Tiny 1.2); EPS writes binary coverage as an image mask in the color's ink, and a grayscale image as ink samples scaled by coverage, with white pixels left out at Level 3 and gray midtones written over white. The prompt for deleting several swatches and groups uses the interface language's plural form for the count. Evidence: `deleting_several_swatches_uses_each_count_form` in `crates/ui-egui/src/panels/swatches/tests.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. From 1add474fd92fc75bbb99b5019605107e121d0d4e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:07:49 -0800 Subject: [PATCH 02/16] Docs: place the Add Selected Colors line after the Swatches context menu entry --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ed93183ec2..f7086e3a16 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1647,10 +1647,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, seven gradient libraries (among them Organic Fades, soft perceptually mixed multi-stop fades that thin out to transparent, and Holographic, seven opaque linear foils of narrow pastel and pearl bands and seven radial glows that fade out to a clear edge) and three pattern libraries (Geometric Patterns; Grit Textures with eight seamless grain, speckle, stipple, scratch and fleck tiles; and Optical Effects with eight of VectorCraft's own seamless wave, ring, warped-check, stripe, chevron and lens tiles; their swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. Right-clicking a swatch in either list or thumbnail view selects it without applying paint and offers Swatch Options…, Duplicate Swatch and Delete Swatch for that item. None, [Registration] and missing swatches disable these actions. Existing active-item multiselection is retained; actions still target only the clicked item. Evidence: `panels::swatches::tests::context_menu` harness tests cover all five views, selection, dialog dispatch, duplicate/delete and Undo. All 39 Swatches tests pass; the regression fails with the menu hooks removed. Rendered headless list and thumbnail menus were inspected, and a fresh local deep CodeRabbit review reported zero findings. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. Validation on 2026-11-15: native Windows formatting, workspace Clippy and all 39 focused Swatches tests passed. Windows full CI stopped at unchanged engine tests `tests::package::a_confined_package_names_files_outside_the_read_root_by_name` (slash-sensitive report assertion) and `tests::plugins::plugin_storage_behind_a_link_is_left_alone` (storage-link setup returned AlreadyExists). Both cases pass in the Linux/WSL full CI run, which passed all 13 gates. No engine or CI workflow changes are included. + The Swatches panel menu has Add Selected Colors, on while art is selected: it adds a swatch for each color of the selected art that the panel does not hold yet, as global swatches the art's matching paints link to, in one undo step ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/use-swatches/add-colors-to-swatches.html) describes the panel menu command that adds the selected artwork's colors). The swatch names and the colors it reads (fills, strokes, text, gradient stops, mesh points) are VectorCraft's own, as for Add Used Colors. Add Used Colors and Add Selected Colors record no undo step when there is no new color. Evidence: `add_selected_colors_adds_the_selection_colors_as_global_swatches` in `crates/ui-egui/src/panels/swatches/tests.rs`; `add_used_colors_with_no_new_color_records_no_undo_step` in `crates/engine/src/tests/swatchcmds.rs`. Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. A swatch step in `command.batch` (Delete, Swatch Options, Merge, Edit Color Group) changes the fill and stroke for new art as the command run on its own does, so art drawn later in the batch or after it takes the same paint; a batch that fails, and a canceled batch preview, put back the paints it started with, and a canceled Swatch Options preview leaves them as they were. These swatch commands also change the fills and strokes of the appearance new art takes, and Undo and Redo of the command or the batch put the paints for new art back with the swatches. Spot Colors options (`swatch.spotOptions`) and Default Swatches with replace (`swatch.resetDefaults {replace: true}`) as `command.batch` steps also change the fill and stroke for new art as each command run on its own does: a fill or stroke linked to a Lab spot swatch keeps its link and tint and takes the Lab values or their CMYK equivalent, and one linked to a swatch the replace removes keeps its color and loses the link. Evidence: `swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do`, `spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does`, `default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does`, `undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints`, `swatch_edits_reach_the_paints_of_the_new_art_template`, `a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed` and `canceling_a_swatch_options_preview_keeps_the_new_art_paints` in `crates/engine/src/tests/swatches.rs`. Add Used Colors (`swatch.addUsedColors`) and Select All Unused (`swatch.unused`) look colors, swatch names, links, tints and gradients up in hash sets instead of searching every swatch and color for each color or linked paint (New Color Group from artwork too), and New Swatch with several colors (`swatch.new`), New Color Group (`swatch.newGroup`) and Edit Color Group (`swatch.editGroup`) name their new swatches from one set of the names already taken. The new swatches keep their names, order and links, and Select All Unused lists the same swatches. Evidence: `add_used_colors_adds_each_new_color_once_with_free_names`, `add_used_colors_global_links_every_paint_of_a_new_color`, `unused_matches_links_tints_colors_gradients_and_patterns_exactly`, `new_swatches_from_colors_are_numbered_after_names_already_taken`, `new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches`, `new_color_group_from_artwork_lists_each_color_once_with_free_names` and `edit_color_group_numbers_extra_colors_after_the_names_it_keeps` in `crates/engine/src/tests/swatchcmds.rs`; `free_swatch_names_match_naming_each_swatch_as_it_is_added` and `free_swatch_names_match_new_swatch_names_as_swatches_are_added` in `crates/doc/src/swatches.rs`. - The Swatches panel menu has Add Selected Colors, on while art is selected: it adds a swatch for each color of the selected art that the panel does not hold yet, as global swatches the art's matching paints link to, in one undo step ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/use-swatches/add-colors-to-swatches.html) describes the panel menu command that adds the selected artwork's colors). The swatch names and the colors it reads (fills, strokes, text, gradient stops, mesh points) are VectorCraft's own, as for Add Used Colors. Add Used Colors and Add Selected Colors record no undo step when there is no new color. Evidence: `add_selected_colors_adds_the_selection_colors_as_global_swatches` in `crates/ui-egui/src/panels/swatches/tests.rs`; `add_used_colors_with_no_new_color_records_no_undo_step` in `crates/engine/src/tests/swatchcmds.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. SVG writes the fill color through a coverage mask (or a colorized PNG in Tiny 1.2); EPS writes binary coverage as an image mask in the color's ink, and a grayscale image as ink samples scaled by coverage, with white pixels left out at Level 3 and gray midtones written over white. The prompt for deleting several swatches and groups uses the interface language's plural form for the count. Evidence: `deleting_several_swatches_uses_each_count_form` in `crates/ui-egui/src/panels/swatches/tests.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. From f874bcd7531fabd989f73495aeb3d7f7a63e425b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 06:16:51 -0800 Subject: [PATCH 03/16] Docs: add Add Selected Colors to the Colour area row --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b173c84769..16135ae360 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -250,7 +250,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Swatches panel menu's Add Selected Colors adds the selected art's colors as global swatches (#8164), score, missing items and hours unchanged | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | From c1139c7a2d60351f9cf8701587cf944a61711c67 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 11:36:09 -0800 Subject: [PATCH 04/16] Tools: a Three-Point Arc tool draws an arc between two ends and a third point The Three-Point Arc tool, after the Arc tool in the Line Segment tool's group, places two ends by a drag or two clicks, then a third point. The arc passes through the third point, or with Third Point Sets Direction on it leaves the first end heading toward it, or with Alt arrives at the second end along the line from it. The setting is in the tool's Tool Options (a double-click on the tool), and ] switches it while drawing. The tool previews the arc, its center and radius, and shows "Arc too large" where no arc fits. shape.threePointArc {start, end, through | toward, at?} draws the open arc in one undo step and refuses points with no arc, malformed points, both or neither of through and toward, an at other than start or end, and an at given with through. Part of #7178. --- ASSETS.md | 1 + ROADMAP.md | 1 + assets/icons/dc-arc-three-point.svg | 1 + crates/engine/src/cmd/create.rs | 53 +++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/three_point_arc.rs | 200 ++++++++++++ crates/geom/src/shapes.rs | 275 ++++++++++++++++ crates/tools/src/catalog.rs | 1 + crates/tools/src/lib.rs | 2 + crates/tools/src/settings.rs | 1 + crates/tools/src/three_point_arc.rs | 307 ++++++++++++++++++ crates/tools/src/three_point_arc/tests.rs | 259 +++++++++++++++ crates/ui-egui/src/dialogs.rs | 2 + .../src/dialogs/three_point_arc_options.rs | 84 +++++ crates/ui-egui/src/i18n/bg.tsv | 8 + crates/ui-egui/src/i18n/bs.tsv | 8 + crates/ui-egui/src/i18n/ca.tsv | 8 + crates/ui-egui/src/i18n/cs.tsv | 8 + crates/ui-egui/src/i18n/da.tsv | 8 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/el.tsv | 8 + crates/ui-egui/src/i18n/es.tsv | 8 + crates/ui-egui/src/i18n/fi.tsv | 8 + crates/ui-egui/src/i18n/fr.tsv | 8 + crates/ui-egui/src/i18n/gu.tsv | 8 + crates/ui-egui/src/i18n/hi.tsv | 8 + crates/ui-egui/src/i18n/hu.tsv | 8 + crates/ui-egui/src/i18n/id.tsv | 8 + crates/ui-egui/src/i18n/it.tsv | 8 + crates/ui-egui/src/i18n/ja.tsv | 8 + crates/ui-egui/src/i18n/ka.tsv | 8 + crates/ui-egui/src/i18n/ko.tsv | 8 + crates/ui-egui/src/i18n/nl.tsv | 8 + crates/ui-egui/src/i18n/pl.tsv | 8 + crates/ui-egui/src/i18n/pt-br.tsv | 8 + crates/ui-egui/src/i18n/ru.tsv | 8 + crates/ui-egui/src/i18n/sv.tsv | 8 + crates/ui-egui/src/i18n/tr.tsv | 8 + crates/ui-egui/src/i18n/uk.tsv | 8 + crates/ui-egui/src/i18n/vi.tsv | 8 + crates/ui-egui/src/i18n/zh-hans.tsv | 8 + crates/ui-egui/src/i18n/zh-hant.tsv | 8 + crates/ui-egui/src/icon_data.rs | 1 + crates/ui-egui/src/icons.rs | 1 + crates/ui-egui/src/toolbar.rs | 4 +- docs/mcp.md | 31 +- docs/target-app-parity.md | 1 + docs/ui-parity.md | 1 + 49 files changed, 1450 insertions(+), 2 deletions(-) create mode 100644 assets/icons/dc-arc-three-point.svg create mode 100644 crates/engine/src/tests/three_point_arc.rs create mode 100644 crates/tools/src/three_point_arc.rs create mode 100644 crates/tools/src/three_point_arc/tests.rs create mode 100644 crates/ui-egui/src/dialogs/three_point_arc_options.rs diff --git a/ASSETS.md b/ASSETS.md index dbdd8b84d8..a21a052f9b 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -115,6 +115,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-anchor-smooth.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-appearance.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arc.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-arc-three-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Three-Point Arc tool: an arc through its two ends and a third point | | `assets/icons/dc-arrow-down.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-extend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline | diff --git a/ROADMAP.md b/ROADMAP.md index 4358817b60..e43e64ae14 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -151,6 +151,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. +- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/assets/icons/dc-arc-three-point.svg b/assets/icons/dc-arc-three-point.svg new file mode 100644 index 0000000000..479a9a5930 --- /dev/null +++ b/assets/icons/dc-arc-three-point.svg @@ -0,0 +1 @@ + diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 013b373d19..3c437e8c43 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -85,6 +85,15 @@ pub fn specs() -> Vec { has_doc, arc ), + cmd!( + "shape.threePointArc", + "Three-Point Arc", + [], + None, + "{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn", + has_doc, + three_point_arc + ), cmd!( "shape.rectangularGrid", "Rectangular Grid", @@ -760,6 +769,50 @@ fn arc(s: &mut Session, p: &Value) -> Result { insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true) } +/// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or +/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is. +fn three_point_arc(s: &mut Session, p: &Value) -> Result { + const C: &str = "shape.threePointArc"; + let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]"))); + let (start, end) = (point("start")?, point("end")?); + let from_end = match p.get("at") { + None => false, + Some(Value::String(v)) if v == "start" || v == "end" => v == "end", + Some(_) => return Err(bad(C, "`at` must be \"start\" or \"end\"")), + }; + // The arc, and the point it passes through (an anchor of the path, so the path meets it exactly). + let (arc, via) = match (p.get("through"), p.get("toward")) { + (Some(_), None) if p.get("at").is_some() => return Err(bad(C, "give `at` only with `toward`")), + (Some(_), None) => { + let through = point("through")?; + (shapes::CircularArc::through(start, end, through), Some(through)) + } + (None, Some(_)) if from_end => { + let toward = point("toward")?; + (shapes::CircularArc::arriving(start, end, end - toward), None) + } + (None, Some(_)) => { + let toward = point("toward")?; + (shapes::CircularArc::leaving(start, toward - start, end), None) + } + _ => return Err(bad(C, "give exactly one of `through` and `toward`")), + }; + let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?; + let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v)); + let look = s.new_art_look( + vectorcraft_color::Paint::None, + if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() }, + s.paint.stroke_width.max(0.1), + ); + // Not pixel-aligned: the ends stay on the given points. + let mut out = insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, 0.0, false)?; + out["cx"] = json!(arc.center.x); + out["cy"] = json!(arc.center.y); + out["radius"] = json!(arc.radius); + out["sweep"] = json!(arc.sweep.to_degrees()); + Ok(out) +} + /// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the /// current fill when `fill`; a path of several subpaths becomes a compound path of them. The group /// and its members get the bounding-box angle `bbox_angle` (a grid drawn along a Constrain Angle). diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 6a0caf4cd6..579d28156b 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -558,6 +558,7 @@ pub(super) const ALLOWED: &[&str] = &[ "shape.rectangularGrid", "shape.spiral", "shape.star", + "shape.threePointArc", "shapeBuilder.merge", "shapeBuilder.regions", "shaper.expand", diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e6c622963a..a9bca8d47d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -203,6 +203,7 @@ mod targeting; mod textcombos; mod textedit; pub(super) mod textimport; +mod three_point_arc; mod tileedge; mod tints; mod toolsettings; diff --git a/crates/engine/src/tests/three_point_arc.rs b/crates/engine/src/tests/three_point_arc.rs new file mode 100644 index 0000000000..8a7a349220 --- /dev/null +++ b/crates/engine/src/tests/three_point_arc.rs @@ -0,0 +1,200 @@ +//! `shape.threePointArc`: an open circular arc between two ends, through a third point or +//! leaving an end toward it, and the Three-Point Arc tool's clicks that run it. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::Point; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::*; + +const C: &str = "shape.threePointArc"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn object_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|_| n += 1); + n +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +/// The largest distance of `points` from the path of `id`. +fn farthest_from_path(s: &Session, id: NodeId, points: &[Point]) -> f64 { + let n = node(s, id); + let path = n.path_data().unwrap(); + points.iter().map(|p| path.nearest(*p).unwrap().4).fold(0.0, f64::max) +} + +/// The arc from (0, 0) to (80, 0) through (40, -40) is the upper half of the circle about +/// (40, 0) with radius 40: an open path from one end to the other, through the third point, with +/// no fill and a stroke, selected, and one undo step. +#[test] +fn the_arc_through_a_third_point_is_an_open_path_and_one_undo_step() { + let mut s = session(); + let undo = undo_len(&s); + let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "through": [40, -40]})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}"); + // From (0, 0) over the top to (80, 0): clockwise on the page. + assert!((out["sweep"].as_f64().unwrap() - 180.0).abs() < 1e-9, "{out}"); + let id = id_of(&out); + let n = node(&s, id); + let NodeKind::Path { path, live: None, .. } = &n.kind else { panic!("not a plain path: {:?}", n.kind) }; + let sp = &path.subpaths[0]; + assert!(!sp.closed && path.subpaths.len() == 1); + assert_eq!((sp.anchors.first().map(|a| a.p), sp.anchors.last().map(|a| a.p)), (Some(Point::ORIGIN), Some(Point::new(80.0, 0.0)))); + assert!(farthest_from_path(&s, id, &[Point::new(40.0, -40.0)]) < 1e-9); + assert!(n.appearance.fill_paint().is_none(), "no fill"); + assert!(!n.appearance.stroke_paint().is_none(), "a stroke"); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert_eq!(undo_len(&s), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).is_none()); + // A third point between the quarter turns is an anchor too, so the path meets it exactly. + let via = Point::new(1000.0 * 20f64.to_radians().cos(), 1000.0 * 20f64.to_radians().sin()); + let out = s.execute(C, &json!({"start": [1000, 0], "end": [0, 1000], "through": [via.x, via.y]})).unwrap(); + let id = id_of(&out); + assert!(node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().any(|a| a.p == via)); + assert!(farthest_from_path(&s, id, &[via]) < 1e-9); +} + +/// With `toward`, the arc leaves `start` heading at the point (its first handle points there), +/// or with `at: "end"` arrives at `end` along the line from the point to `end` (run backward, the +/// arc leaves `end` heading at the point). +#[test] +fn the_arc_toward_a_point_has_that_tangent_at_its_end() { + let mut s = session(); + let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [30, -30]})).unwrap(); + let n = node(&s, id_of(&out)); + let first = n.path_data().unwrap().subpaths[0].anchors[0]; + let d = (first.h_out - first.p).normalize(); + assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, -1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}"); + // A quarter turn's tangent: the center is at (40, 40) and the radius √3200. + assert!((out["radius"].as_f64().unwrap() - 3200f64.sqrt()).abs() < 1e-9, "{out}"); + let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [50, -30], "at": "end"})).unwrap(); + let n = node(&s, id_of(&out)); + let last = *n.path_data().unwrap().subpaths[0].anchors.last().unwrap(); + let d = (last.p - last.h_in).normalize(); + assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, 1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}"); + // The direction from the start and from the end mirror each other. + assert!((out["cx"].as_f64().unwrap() - 40.0).abs() < 1e-9 && (out["cy"].as_f64().unwrap() - 40.0).abs() < 1e-9, "{out}"); +} + +/// Points that are the same, a third point on the line through the ends, and an arc reaching past +/// the canvas are refused with a message; nothing is drawn and no undo step is added. +#[test] +fn points_with_no_arc_are_refused() { + let mut s = session(); + let (undo, count) = (undo_len(&s), object_count(&s)); + for p in [ + json!({"start": [0, 0], "end": [0, 0], "through": [10, 10]}), + json!({"start": [0, 0], "end": [80, 0], "through": [40, 0]}), + json!({"start": [0, 0], "end": [80, 0], "through": [120, 0]}), + json!({"start": [0, 0], "end": [80, 0], "through": [80, 0]}), + json!({"start": [0, 0], "end": [80, 0], "toward": [0, 0]}), + json!({"start": [0, 0], "end": [80, 0], "toward": [-50, 0]}), + json!({"start": [0, 0], "end": [80, 0], "toward": [40, 0], "at": "end"}), + json!({"start": [0, 0], "end": [0, 0], "toward": [10, 10]}), + ] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains("no arc fits these points"), "{p}: {e}"); + } + // Nearly in line beyond the end: the circle's center is about 1.2·10⁷ pt down the page, and the + // arc goes round the far side of it. + let far = json!({"start": [0, 0], "end": [80, 0], "through": [200, 0.001]}); + let e = s.execute(C, &far).unwrap_err().to_string(); + assert!(e.contains("result would exceed the canvas"), "{e}"); + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// Missing or malformed points, both or neither of `through` and `toward`, an `at` that is not +/// "start" or "end", and an `at` with `through` are errors; nothing is drawn. +#[test] +fn malformed_params_are_refused() { + let mut s = session(); + let count = object_count(&s); + for (p, want) in [ + (json!({"end": [80, 0], "through": [40, 40]}), "`start` must be [x, y]"), + (json!({"start": [0, 0], "end": [80], "through": [40, 40]}), "`end` must be [x, y]"), + (json!({"start": [0, 0], "end": [80, 0], "through": [40, "a"]}), "`through` must be [x, y]"), + (json!({"start": [0, 0], "end": [80, 0], "through": null}), "`through` must be [x, y]"), + (json!({"start": [0, 0], "end": [80, 0], "toward": [10, 0, 0]}), "`toward` must be [x, y]"), + (json!({"start": [0, 0], "end": [80, 0]}), "give exactly one of `through` and `toward`"), + (json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "toward": [0, 40]}), "give exactly one of `through` and `toward`"), + (json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": "middle"}), "`at` must be \"start\" or \"end\""), + (json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": null}), "`at` must be \"start\" or \"end\""), + (json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "end"}), "give `at` only with `toward`"), + (json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "start"}), "give `at` only with `toward`"), + ] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert_eq!(object_count(&s), count); +} + +/// With Align New Objects to Pixel Grid on, the ends stay on the given points. +#[test] +fn the_arc_is_not_moved_onto_the_pixel_grid() { + let mut s = session(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let id = id_of(&s.execute(C, &json!({"start": [0.3, 0.2], "end": [80.6, 0.1], "through": [40.4, -39.7]})).unwrap()); + let n = node(&s, id); + let sp = &n.path_data().unwrap().subpaths[0]; + assert_eq!(sp.anchors.first().map(|a| a.p), Some(Point::new(0.3, 0.2))); + assert_eq!(sp.anchors.last().map(|a| a.p), Some(Point::new(80.6, 0.1))); + assert!(!n.extras().pixel_aligned); +} + +fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..ViewInfo::default() } +} + +fn click(s: &mut Session, x: f64, y: f64) { + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, x, y).with_mods(Mods::default()), view()).unwrap(); + } +} + +/// With the Three-Point Arc tool, three clicks draw the arc in one undo step; `]` before the third +/// click makes the third point give the direction instead. Escape drops the ends. +#[test] +fn three_clicks_with_the_tool_draw_the_arc() { + let mut s = session(); + s.select_tool("threePointArc", view()).unwrap(); + let (undo, count) = (undo_len(&s), object_count(&s)); + click(&mut s, 100.0, 200.0); + click(&mut s, 180.0, 200.0); + assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "two ends draw nothing yet"); + click(&mut s, 140.0, 160.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(farthest_from_path(&s, id, &[Point::new(100.0, 200.0), Point::new(140.0, 160.0), Point::new(180.0, 200.0)]) < 1e-9); + // Escape after the ends: the next clicks start afresh. + click(&mut s, 0.0, 0.0); + click(&mut s, 10.0, 300.0); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 180.0, 300.0); + s.tool_key(ToolKey::BracketRight, Mods::default(), view()).unwrap(); + let undo = undo_len(&s); + // Straight up from the first end: the upper half circle about (140, 300). + click(&mut s, 100.0, 250.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(farthest_from_path(&s, id, &[Point::new(140.0, 260.0)]) < 1e-9); +} diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 76b9b71798..27568147b9 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -468,6 +468,143 @@ pub fn arc(a: Point, b: Point, slope: f64, closed: bool, _base_along_x: bool) -> PathData::single(SubPath::new(anchors, closed)) } +/// A circular arc from `start` to `end`: its circle's `center` and `radius`, and the turn from +/// `start` to `end` about the center in radians, positive the way the angle `atan2(y, x)` grows +/// (clockwise on the y-down page). The turn is never 0 and never a whole turn. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CircularArc { + pub start: Point, + pub end: Point, + pub center: Point, + pub radius: f64, + pub sweep: f64, +} + +impl CircularArc { + /// The arc from `start` to `end` that passes through `through`. `None` when two of the points + /// are the same or the three lie on one line ([`circle_through`]). + pub fn through(start: Point, end: Point, through: Point) -> Option { + let (center, radius) = circle_through(start, end, through)?; + let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x); + let a = angle(start); + let to_end = (angle(end) - a).rem_euclid(TAU); + let to_through = (angle(through) - a).rem_euclid(TAU); + // The turn that goes past `through` on its way to `end`. + let sweep = if to_through < to_end { to_end } else { to_end - TAU }; + Self::checked(start, end, center, radius, sweep) + } + + /// The arc that leaves `start` heading along `direction` (its tangent there) and ends at + /// `end`. `None` when `start` and `end` are the same, `direction` is zero, or `end` lies on the + /// line through `start` along `direction` (no circle touches that line at `start` and passes + /// through `end`). The same test as [`circle_through`] decides that: twice the area of the + /// triangle `start`, `end` and `start + direction` scaled to the chord's length is at most + /// 10⁻¹⁰ of the chord's length squared. + pub fn leaving(start: Point, direction: Vec2, end: Point) -> Option { + let len = direction.hypot(); + let chord = end - start; + let c2 = chord.hypot2(); + if !(len.is_finite() && len > 0.0 && c2.is_finite() && c2 > 0.0) { + return None; + } + let t = direction / len; + // Twice the triangle's area with the tangent as long as the chord. + let cross = t.cross(chord); + if cross.is_nan() || (cross * c2.sqrt()).abs() <= 1e-10 * c2 { + return None; + } + // The center lies on the normal at `start` on the side `end` is: `start + n * s` with + // `|n * s - chord| = |s|`, so `s = |chord|² / (2 n·chord)`. + let n = Vec2::new(-t.y, t.x); + let s = c2 / (2.0 * n.dot(chord)); + let center = start + n * s; + let radius = s.abs(); + let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x); + let a = angle(start); + let to_end = (angle(end) - a).rem_euclid(TAU); + // Leaving along `t`: the turn grows when `t` points the way the angle grows at `start`. + let grows = Vec2::new(-(start.y - center.y), start.x - center.x).dot(t) > 0.0; + let sweep = if grows { to_end } else { to_end - TAU }; + Self::checked(start, end, center, radius, sweep) + } + + /// The arc that ends at `end` arriving along `direction` and starts at `start`: [`Self::leaving`] + /// from `end` back along `-direction`, turned round. + pub fn arriving(start: Point, end: Point, direction: Vec2) -> Option { + let back = Self::leaving(end, -direction, start)?; + Some(Self { start, end, center: back.center, radius: back.radius, sweep: -back.sweep }) + } + + fn checked(start: Point, end: Point, center: Point, radius: f64, sweep: f64) -> Option { + let ok = center.is_finite() && radius.is_finite() && radius > 0.0 && sweep.is_finite() && sweep != 0.0 && sweep.abs() < TAU; + ok.then_some(Self { start, end, center, radius, sweep }) + } + + /// The point at `t` (0 at `start`, 1 at `end`) along the arc. + pub fn at(&self, t: f64) -> Point { + let a = (self.start.y - self.center.y).atan2(self.start.x - self.center.x) + self.sweep * t; + Point::new(self.center.x + self.radius * a.cos(), self.center.y + self.radius * a.sin()) + } + + /// The open path of the arc: an anchor at `start`, at `end`, and between them as many smooth + /// anchors, evenly spaced, as keep each cubic piece to a quarter turn at most. The ends are the + /// given points exactly. + pub fn to_path(&self) -> PathData { + let quarter = std::f64::consts::FRAC_PI_2; + // A quarter turn and a hair more is still one piece. + let pieces = ((self.sweep.abs() / quarter) - 1e-9).ceil().clamp(1.0, 4.0) as u32; + let step = self.sweep / f64::from(pieces); + // The handle length of a cubic that follows a circle through the turn `step`, per unit + // of radius; negative when the arc runs the other way. + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let a0 = (self.start.y - self.center.y).atan2(self.start.x - self.center.x); + let mut anchors = Vec::with_capacity(pieces as usize + 1); + for i in 0..=pieces { + let a = a0 + step * f64::from(i); + let p = if i == 0 { + self.start + } else if i == pieces { + self.end + } else { + Point::new(self.center.x + self.radius * a.cos(), self.center.y + self.radius * a.sin()) + }; + // The handle along the tangent the way the arc runs. + let d = Vec2::new(-a.sin(), a.cos()) * (self.radius * k); + let h_in = if i == 0 { p } else { p - d }; + let h_out = if i == pieces { p } else { p + d }; + let kind = if i == 0 || i == pieces { AnchorKind::Corner } else { AnchorKind::Smooth }; + anchors.push(Anchor { p, h_in, h_out, kind }); + } + PathData::single(SubPath::new(anchors, false)) + } + + /// [`Self::to_path`] with a smooth anchor at `via`, a point on the arc such as the one + /// [`Self::through`] passes through, so the path passes through it exactly: the arc to `via` + /// and the arc on from it, each cut into quarter turns at most. A `via` at an end, or off the + /// stretch between the ends, gives [`Self::to_path`]. + pub fn to_path_via(&self, via: Point) -> PathData { + let angle = |p: Point| (p.y - self.center.y).atan2(p.x - self.center.x); + let turn = (angle(via) - angle(self.start)).rem_euclid(TAU); + // The turn from `start` to `via` the way the arc runs. + let to_via = if self.sweep > 0.0 { turn } else { turn - TAU }; + let share = to_via / self.sweep; + if !(share > 0.0 && share < 1.0) || via == self.start || via == self.end { + return self.to_path(); + } + let first = Self { end: via, sweep: to_via, ..*self }.to_path(); + let second = Self { start: via, sweep: self.sweep - to_via, ..*self }.to_path(); + let (Some(a), Some(b)) = (first.subpaths.into_iter().next(), second.subpaths.into_iter().next()) else { return self.to_path() }; + let mut anchors: Vec = a.anchors.iter().copied().collect(); + let mut rest = b.anchors.iter().copied(); + if let (Some(joint), Some(next)) = (anchors.last_mut(), rest.next()) { + joint.h_out = next.h_out; + joint.kind = AnchorKind::Smooth; + } + anchors.extend(rest); + PathData::single(SubPath::new(anchors, false)) + } +} + /// Logarithmic spiral with decay per full wind (`segments` quarter turns). pub fn spiral(center: Point, radius: f64, decay_percent: f64, segments: u32, clockwise: bool) -> PathData { let decay = (decay_percent / 100.0).clamp(0.05, 0.9999); @@ -744,6 +881,144 @@ mod tests { assert!(c.distance(Point::new(4.0, 3.0) + far) < 1e-6 && (radius - 5.0).abs() < 1e-6, "{c:?} {radius}"); } + /// Every point of `path`'s cubics lies on the arc's circle (to 3·10⁻⁴ of the radius, the + /// quarter-turn cubic's error), and the path runs from the arc's start to its end. + fn assert_on_circle(arc: &CircularArc) { + use kurbo::ParamCurve; + let path = arc.to_path(); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.first().map(|a| a.p), Some(arc.start)); + assert_eq!(sp.anchors.last().map(|a| a.p), Some(arc.end)); + for seg in path.to_bezpath().segments() { + for i in 0..=8 { + let p = seg.eval(f64::from(i) / 8.0); + assert!((p.distance(arc.center) - arc.radius).abs() <= 3e-4 * arc.radius, "{p:?} off the circle"); + } + } + } + + /// The arc through a third point: from (0, 0) to (8, 0) through (4, -2) (above the chord on the + /// page) bulges up; through (4, 2) it bulges down; each has the circle through the three points + /// and goes past the third point. Through (4, 10) it is the larger part of its circle. + #[test] + fn the_arc_through_a_point_passes_through_it() { + let (a, b) = (Point::ORIGIN, Point::new(8.0, 0.0)); + for (c, major) in + [(Point::new(4.0, -2.0), false), (Point::new(4.0, 2.0), false), (Point::new(4.0, 10.0), true), (Point::new(-1.0, -3.0), true)] + { + let arc = CircularArc::through(a, b, c).unwrap(); + let (center, radius) = circle_through(a, b, c).unwrap(); + assert!(arc.center.distance(center) < 1e-12 && (arc.radius - radius).abs() < 1e-12); + assert_eq!(arc.sweep.abs() > PI, major, "{c:?}: {}", arc.sweep); + // The third point is on the arc: some point along it is the third point. + let nearest = (0..=10_000).map(|i| arc.at(f64::from(i) / 10_000.0).distance(c)).fold(f64::INFINITY, f64::min); + assert!(nearest < 0.01, "{c:?}: {nearest}"); + assert!(arc.at(0.0).distance(a) < 1e-12 && arc.at(1.0).distance(b) < 1e-9); + assert_on_circle(&arc); + } + // A half circle: two pieces, its middle anchor at the third point. + let arc = CircularArc::through(a, b, Point::new(4.0, -4.0)).unwrap(); + let path = arc.to_path(); + assert_eq!(path.subpaths[0].anchors.len(), 3); + assert!(path.subpaths[0].anchors[1].p.distance(Point::new(4.0, -4.0)) < 1e-12); + assert_eq!(path.subpaths[0].anchors[1].kind, AnchorKind::Smooth); + // Almost a whole circle: four pieces. + let arc = CircularArc::through(a, Point::new(0.0, 0.01), Point::new(8.0, 0.0)).unwrap(); + assert_eq!(arc.to_path().subpaths[0].anchors.len(), 5); + assert_on_circle(&arc); + } + + /// With an anchor at the third point, the path passes through it exactly, whichever way the + /// arc runs, even where one cubic would miss it (a quarter turn of radius 1000 misses a point + /// 20° along by about 0.27). Each part keeps to a quarter turn, the anchor there is smooth, and + /// a point at an end leaves the path as `to_path` makes it. + #[test] + fn the_path_via_the_third_point_passes_through_it_exactly() { + let center = Point::new(0.0, 0.0); + let on = |deg: f64| Point::new(1000.0 * deg.to_radians().cos(), 1000.0 * deg.to_radians().sin()); + for (a, b, c) in [(0.0, 90.0, 20.0), (90.0, 0.0, 20.0), (0.0, 300.0, 170.0), (300.0, 0.0, 10.0)] { + let arc = CircularArc::through(on(a), on(b), on(c)).unwrap(); + assert!(arc.center.distance(center) < 1e-6); + let path = arc.to_path_via(on(c)); + let sp = &path.subpaths[0]; + let joint = sp.anchors.iter().find(|x| x.p == on(c)).expect("an anchor at the third point"); + assert_eq!(joint.kind, AnchorKind::Smooth); + assert_eq!((sp.anchors.first().map(|x| x.p), sp.anchors.last().map(|x| x.p)), (Some(arc.start), Some(arc.end))); + // No piece turns more than a quarter turn. + let points: Vec = sp.anchors.iter().map(|x| x.p).collect(); + for w in points.windows(2) { + let (u, v) = (w[0] - arc.center, w[1] - arc.center); + assert!(u.cross(v).atan2(u.dot(v)).abs() <= std::f64::consts::FRAC_PI_2 + 1e-9, "{a} {b} {c}"); + } + use kurbo::ParamCurve; + for seg in path.to_bezpath().segments() { + for i in 0..=8 { + let p = seg.eval(f64::from(i) / 8.0); + assert!((p.distance(arc.center) - arc.radius).abs() <= 0.3, "{p:?} off the circle"); + } + } + } + // A third point a hair from an end is still an anchor. + let near = Point::new(1000.0, 0.0000005); + let arc = CircularArc::through(on(0.0), on(90.0), near).unwrap(); + assert!(arc.to_path_via(near).subpaths[0].anchors.iter().any(|x| x.p == near)); + let arc = CircularArc::through(on(0.0), on(90.0), on(20.0)).unwrap(); + assert_eq!(arc.to_path_via(on(0.0)), arc.to_path()); + assert_eq!(arc.to_path_via(on(180.0)), arc.to_path()); + } + + /// The arc that leaves its start along a direction: from (0, 0) heading up the page (-y) to + /// (8, 0) is the upper half circle about (4, 0); heading down, the lower one. Its tangent at the + /// start is the direction, and arriving at the end mirrors it. + #[test] + fn the_arc_leaving_along_a_direction_has_that_tangent() { + let (a, b) = (Point::ORIGIN, Point::new(8.0, 0.0)); + let up = CircularArc::leaving(a, Vec2::new(0.0, -3.0), b).unwrap(); + assert!(up.center.distance(Point::new(4.0, 0.0)) < 1e-12 && (up.radius - 4.0).abs() < 1e-12); + assert!(up.at(0.5).distance(Point::new(4.0, -4.0)) < 1e-9, "{:?}", up.at(0.5)); + let down = CircularArc::leaving(a, Vec2::new(0.0, 3.0), b).unwrap(); + assert!(down.at(0.5).distance(Point::new(4.0, 4.0)) < 1e-9, "{:?}", down.at(0.5)); + // Leaving at 45° up and right: a quarter circle, tangent along the direction. + for d in [Vec2::new(1.0, -1.0), Vec2::new(1.0, 1.0), Vec2::new(-1.0, -0.2), Vec2::new(-1.0, 3.0)] { + let arc = CircularArc::leaving(a, d, b).unwrap(); + let first = &arc.to_path().subpaths[0].anchors[0]; + let tangent = first.h_out - first.p; + assert!((tangent.normalize().dot(d.normalize()) - 1.0).abs() < 1e-12, "{d:?}: {tangent:?}"); + assert_on_circle(&arc); + // Arriving along a direction at the end: the tangent into the end is the direction. + let arc = CircularArc::arriving(a, b, d).unwrap(); + let last = arc.to_path().subpaths[0].anchors.last().copied().unwrap(); + let tangent = last.p - last.h_in; + assert!((tangent.normalize().dot(d.normalize()) - 1.0).abs() < 1e-12, "{d:?}: {tangent:?}"); + assert_eq!((arc.start, arc.end), (a, b)); + assert_on_circle(&arc); + } + } + + /// No arc for points that are the same, a third point on the chord's line, a zero or not + /// finite direction, or a direction along the chord's line. + #[test] + fn degenerate_points_give_no_arc() { + let (a, b) = (Point::new(1.0, 2.0), Point::new(5.0, 7.0)); + assert_eq!(CircularArc::through(a, a, b), None); + assert_eq!(CircularArc::through(a, b, b), None); + assert_eq!(CircularArc::through(a, b, a.midpoint(b)), None); + assert_eq!(CircularArc::through(a, b, a + (b - a) * 3.0), None); + assert_eq!(CircularArc::through(a, b, Point::new(f64::INFINITY, 0.0)), None); + assert_eq!(CircularArc::leaving(a, Vec2::new(1.0, 0.0), a), None); + assert_eq!(CircularArc::leaving(a, Vec2::ZERO, b), None); + assert_eq!(CircularArc::leaving(a, Vec2::new(f64::NAN, 1.0), b), None); + assert_eq!(CircularArc::leaving(a, b - a, b), None); + assert_eq!(CircularArc::leaving(a, a - b, b), None); + assert_eq!(CircularArc::arriving(a, b, b - a), None); + // Off the line by 10⁻⁴ over a chord of 2000 still makes an arc. + let (p, q) = (Point::new(-1000.0, 0.0), Point::new(1000.0, 0.0)); + assert!(CircularArc::leaving(p, Vec2::new(2000.0, 1e-4), q).is_some()); + // Off the line by 10⁻¹² of the chord is in line: no arc, rather than a circle 10¹² chords wide. + assert_eq!(CircularArc::leaving(p, Vec2::new(1.0, 1e-12), q), None); + } + /// Two points that are the same, or three on one line, give no circle. #[test] fn coincident_or_collinear_points_give_no_circle() { diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 529aa80d18..3c754efcdf 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -48,6 +48,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ &[ t("lineSegment", "Line Segment Tool", Some("\\"), "tool-line"), t("arc", "Arc Tool", None, "tool-arc"), + t(crate::three_point_arc::ID, "Three-Point Arc Tool", None, "tool-three-point-arc"), t("spiral", "Spiral Tool", None, "tool-spiral"), t("rectangularGrid", "Rectangular Grid Tool", None, "tool-rect-grid"), t("polarGrid", "Polar Grid Tool", None, "tool-polar-grid"), diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 7526717665..e08d4fdb6f 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -43,6 +43,7 @@ pub mod shaperwidget; pub mod slice; pub mod symbolism; pub mod text; +pub mod three_point_arc; pub mod touchtype; pub mod typewidget; pub mod xform; @@ -366,6 +367,7 @@ pub fn create(id: &str) -> Box { "rectangle" | "roundedRectangle" | "ellipse" | "polygon" | "star" | "lineSegment" => Box::new(shape::ShapeTool::new(id)), // Not in the toolbar: `file.place.queue` loads it. "place" => Box::new(place::PlaceTool::default()), + three_point_arc::ID => Box::new(three_point_arc::ThreePointArcTool::default()), other => symbolism::create(other) .or_else(|| builder::create(other)) .or_else(|| draw2::create(other)) diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 97e980e3c0..f33a0456b1 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -27,6 +27,7 @@ const ROWS: &[Row] = &[ (&["mirrorCut"], None, &["axis", "keep"]), (&["puppetWarp"], None, &["showMesh", "expand"]), (&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]), + (&[crate::three_point_arc::ID], None, &["direction"]), (&["spiral"], None, &["decay", "segments", "clockwise"]), // The grids' Tool Options: the dividers and switches the drag uses, the Default Size and // Reference Point a click's dialog opens with. diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs new file mode 100644 index 0000000000..67ce63e03f --- /dev/null +++ b/crates/tools/src/three_point_arc.rs @@ -0,0 +1,307 @@ +//! The Three-Point Arc tool draws an open circular arc between two ends it is given +//! (`shape.threePointArc`). +//! +//! The ends come first: a drag from one to the other, or a click on each. Shift keeps the second +//! end at 45° steps from the first (from General › Constrain Angle). A third point then shapes the +//! arc, placed by a click or by a press dragged to it: the arc passes through it, or, with the +//! `direction` option on, the arc leaves the first end heading toward it (Alt: the arc arrives at +//! the second end along the line from that end to the point, and Shift keeps the line at 45° +//! steps). `direction` is set in the tool's Tool Options and kept with the preferences; `]` (with +//! or without Shift) switches it while the ends are placed. Every point snaps to Smart Guides. +//! Until the third point is placed, the tool shows the arc as a dashed outline with its ends, its +//! center as a small cross, the direction line in direction mode and, with Measurement Labels on, +//! the radius by the pointer. Where no arc fits (the third point lies on the line through the +//! ends) or the arc would reach past the canvas, the tool shows "Arc too large" by the pointer +//! (nothing while the pointer is on an end) and a click there draws nothing. The arc is one undo +//! step. Escape, a press dropped part way, and an edit, Undo or Redo made outside the tool drop +//! the ends; a second click on the first end (a double-click) places nothing. + +use serde_json::{Value, json}; +use vectorcraft_doc::MAX_COORD; +use vectorcraft_geom::shapes::CircularArc; +use vectorcraft_geom::{PathData, Point, Vec2}; + +use crate::guides::{DrawSnap, Leave}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +pub const ID: &str = "threePointArc"; + +/// How far (screen points) the pointer travels from a press before the press counts as a drag. +const DRAG_PX: f64 = 2.0; +/// Half the length (screen points) of each arm of the cross at the arc's center. +const CROSS_PX: f64 = 4.0; +/// How near (screen points) the first end a second click counts as a click on it. +const REACH_PX: f64 = 3.0; +/// The label the tool shows by the pointer where no arc fits. +pub const TOO_LARGE: &str = "Arc too large"; + +/// The press in progress. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Press { + /// The first end, pressed at `at`: a release after a drag places the second end there. + Start { at: Point, dragged: bool }, + /// The second end, pressed after a click placed the first: the release places it. + End, + /// The third point, pressed once both ends are placed: the release draws the arc. + Third, +} + +#[derive(Default)] +pub struct ThreePointArcTool { + snap: DrawSnap, + /// The third point gives the arc's direction at an end instead of a point it passes through. + direction: bool, + start: Option, + end: Option, + press: Option, + /// Where the pointer is, snapped: the point the next press or release places. + pointer: Option, + /// Alt was held at the last pointer event: in direction mode, the direction is at the second end. + at_end: bool, + /// Where the pressed pointer was at its last event, before snapping. + raw: Option, +} + +/// The arc from `start` to `end` shaped by `third`, as `shape.threePointArc` draws it: through +/// `third`, or with `direction`, heading toward `third` from `start` (or, with `at_end`, arriving +/// at `end` along the line from `end` to `third`). None where no arc fits or the arc would reach +/// past the canvas. With it, the path the command draws. +pub fn arc_of(start: Point, end: Point, third: Point, direction: bool, at_end: bool) -> Option<(CircularArc, PathData)> { + let (arc, path) = match (direction, at_end) { + (false, _) => CircularArc::through(start, end, third).map(|arc| (arc, arc.to_path_via(third))), + (true, false) => CircularArc::leaving(start, third - start, end).map(|arc| (arc, arc.to_path())), + (true, true) => CircularArc::arriving(start, end, end - third).map(|arc| (arc, arc.to_path())), + }?; + let on_canvas = path.anchors().all(|(_, _, a)| [a.p, a.h_in, a.h_out].iter().all(|q| q.x.abs() <= MAX_COORD && q.y.abs() <= MAX_COORD)); + on_canvas.then_some((arc, path)) +} + +/// The command the tool runs for the arc from `start` to `end` shaped by `third`. +fn command(start: Point, end: Point, third: Point, direction: bool, at_end: bool) -> (String, Value) { + let pair = |p: Point| json!([p.x, p.y]); + let params = if direction { + json!({ "start": pair(start), "end": pair(end), "toward": pair(third), "at": if at_end { "end" } else { "start" } }) + } else { + json!({ "start": pair(start), "end": pair(end), "through": pair(third) }) + }; + ("shape.threePointArc".into(), params) +} + +impl ThreePointArcTool { + fn clear(&mut self) { + self.start = None; + self.end = None; + self.press = None; + self.pointer = None; + self.snap.clear(); + } + + /// How the point being placed keeps to the points before it: the second end to the first, and + /// in direction mode the third point to the end its direction line starts from. + fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { + match (self.start, self.end) { + (Some(a), None) => Some(Leave::segment(cx, a, mods.shift)), + (Some(a), Some(b)) if self.direction => Some(Leave::segment(cx, if mods.alt { b } else { a }, mods.shift)), + _ => None, + } + } + + /// The pressed pointer moved to `ev`: the point being placed follows it. + fn follow(&mut self, cx: &ToolContext, ev: &PointerEvent) { + self.raw = Some(ev.pos); + match &mut self.press { + Some(Press::Start { at, dragged }) => { + *dragged |= ev.pos.distance(*at) >= cx.tol(DRAG_PX); + let leave = Leave::segment(cx, *at, ev.mods.shift); + self.pointer = Some(self.snap.drag(cx, ev.pos, Some(&leave))); + } + Some(Press::End | Press::Third) => { + let leave = self.leave(cx, ev.mods); + self.pointer = Some(self.snap.drag(cx, ev.pos, leave.as_ref())); + } + None => {} + } + } + + /// The arc as the tool shows it now, and its path: both ends placed and the pointer on a point + /// that fits. + fn arc(&self) -> Option<(CircularArc, PathData)> { + arc_of(self.start?, self.end?, self.pointer?, self.direction, self.at_end) + } +} + +impl Tool for ThreePointArcTool { + fn id(&self) -> &'static str { + ID + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + if !ev.pos.is_finite() { + return vec![]; + } + if self.end.is_some() { + self.at_end = ev.mods.alt; + } + match ev.kind { + PointerKind::Move => { + let leave = self.leave(cx, ev.mods); + self.pointer = Some(self.snap.hover(cx, ev.pos, &[], leave.as_ref())); + vec![] + } + PointerKind::Down => { + self.raw = Some(ev.pos); + let leave = self.leave(cx, ev.mods); + match (self.start, self.end) { + (None, _) => { + let at = self.snap.press(cx, ev.pos, &[], None); + self.start = Some(at); + self.press = Some(Press::Start { at, dragged: false }); + self.pointer = Some(at); + } + (Some(a), None) => { + let at = self.snap.press(cx, ev.pos, &[], leave.as_ref()); + // The second click of a double-click lands on the first end. + if at.distance(a) <= cx.tol(REACH_PX) { + self.press = None; + return vec![]; + } + self.press = Some(Press::End); + self.pointer = Some(at); + } + (Some(_), Some(_)) => { + self.pointer = Some(self.snap.press(cx, ev.pos, &[], leave.as_ref())); + self.press = Some(Press::Third); + } + } + vec![] + } + PointerKind::Drag => { + self.follow(cx, ev); + vec![] + } + PointerKind::Up => { + // A release away from the last drag event places the point where it is let go. + if self.press.is_some() && self.raw != Some(ev.pos) { + self.follow(cx, ev); + } + match (self.press.take(), self.start, self.pointer) { + (Some(Press::Start { at, dragged: true }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.end = Some(b), + (Some(Press::End), Some(a), Some(b)) if b.distance(a) > cx.tol(REACH_PX) => self.end = Some(b), + (Some(Press::Third), Some(a), Some(c)) => { + let Some(b) = self.end else { return vec![] }; + // Where no arc fits, nothing is drawn and the ends stay for another try. + if self.arc().is_none() { + self.snap.clear(); + return vec![]; + } + let (name, params) = command(a, b, c, self.direction, self.at_end); + self.clear(); + return vec![Action::Exec(name, params)]; + } + _ => {} + } + // A placed end: the guides of the press go. + self.snap.clear(); + vec![] + } + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + match key { + ToolKey::Escape => self.clear(), + ToolKey::BracketRight if self.start.is_some() => self.direction = !self.direction, + _ => {} + } + vec![] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + matches!(key, ToolKey::Escape | ToolKey::BracketRight) && self.start.is_some() + } + + /// An end placed: Escape drops it. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.start.is_some() + } + + fn busy(&self) -> bool { + self.start.is_some() + } + + /// A dropped press (a second finger, a canceled touch) drops the ends placed so far. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + if self.press.is_none() { + self.pointer = None; + self.snap.clear(); + } + } + + /// An edit, Undo or Redo made outside the tool, or another document, drops the ends. + fn history_moved(&mut self) { + self.clear(); + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut o = self.snap.guides().to_vec(); + let color = crate::draw2::FEEDBACK; + match (self.start, self.end, self.pointer) { + // Placing the second end: the chord so far. + (Some(a), None, Some(b)) if b != a => o.push(Overlay::Line { a, b, color, dashed: true }), + (Some(a), Some(b), Some(p)) => { + if self.direction { + o.push(Overlay::Line { a: if self.at_end { b } else { a }, b: p, color, dashed: false }); + } + match self.arc() { + Some((arc, path)) => { + o.push(Overlay::Path { path: path.to_bezpath(), color, width: 1.0, dashed: true }); + let (c, arm) = (arc.center, cx.tol(CROSS_PX)); + o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false }); + o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false }); + if cx.measurement_labels { + o.push(Overlay::Measure { p, text: format!("R: {}", cx.len(arc.radius)) }); + } + } + // A pointer on an end gives no third point yet, so no label. + None if p.distance(a) <= cx.tol(REACH_PX) || p.distance(b) <= cx.tol(REACH_PX) => {} + None => o.push(Overlay::Label { p, text: TOO_LARGE.into(), color }), + } + } + _ => {} + } + for p in self.start.iter().chain(self.end.iter()) { + o.push(Overlay::Anchor { p: *p, color, filled: true, size: 6.0 }); + } + o + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } + + fn options(&self) -> Value { + json!({ "direction": self.direction }) + } + + fn set_option(&mut self, key: &str, value: &Value) { + if key == "direction" + && let Some(on) = value.as_bool() + { + self.direction = on; + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs new file mode 100644 index 0000000000..88e63dc1b4 --- /dev/null +++ b/crates/tools/src/three_point_arc/tests.rs @@ -0,0 +1,259 @@ +use super::*; +use crate::testutil::*; +use vectorcraft_doc::Selection; +use vectorcraft_geom::Rect; + +fn ev(kind: PointerKind, (x, y): (f64, f64), mods: Mods) -> PointerEvent { + PointerEvent::new(kind, x, y).with_mods(mods) +} + +fn click_with(t: &mut ThreePointArcTool, cx: &ToolContext, p: (f64, f64), mods: Mods) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, p, mods)); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, p, mods))); + acts +} + +fn click(t: &mut ThreePointArcTool, cx: &ToolContext, p: (f64, f64)) -> Vec { + click_with(t, cx, p, Mods::default()) +} + +fn hover(t: &mut ThreePointArcTool, cx: &ToolContext, p: (f64, f64), mods: Mods) { + assert!(t.pointer(cx, &ev(PointerKind::Move, p, mods)).is_empty()); +} + +/// A press at `from`, dragged through `path` and let go at its last point. +fn drag(t: &mut ThreePointArcTool, cx: &ToolContext, from: (f64, f64), path: &[(f64, f64)], mods: Mods) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, from, mods)); + for p in path { + acts.extend(t.pointer(cx, &ev(PointerKind::Drag, *p, mods))); + } + let end = path.last().copied().unwrap_or(from); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, end, mods))); + acts +} + +fn through(start: (f64, f64), end: (f64, f64), via: (f64, f64)) -> Vec { + let pair = |(x, y): (f64, f64)| json!([x, y]); + vec![Action::Exec("shape.threePointArc".into(), json!({ "start": pair(start), "end": pair(end), "through": pair(via) }))] +} + +fn toward(start: (f64, f64), end: (f64, f64), to: (f64, f64), at: &str) -> Vec { + let pair = |(x, y): (f64, f64)| json!([x, y]); + vec![Action::Exec("shape.threePointArc".into(), json!({ "start": pair(start), "end": pair(end), "toward": pair(to), "at": at }))] +} + +/// The dashed arc the tool shows: its bounding box. +fn preview(o: &[Overlay]) -> Option { + o.iter().find_map(|o| match o { + Overlay::Path { path, dashed: true, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + _ => None, + }) +} + +fn too_large(o: &[Overlay]) -> bool { + o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == TOO_LARGE)) +} + +/// A drag places the two ends; a click on a third point then draws the arc through it. Until +/// then, nothing is drawn. +#[test] +fn a_drag_and_a_click_draw_the_arc_through_the_third_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + assert!(drag(&mut t, &cx, (300.0, 300.0), &[(340.0, 300.0), (380.0, 300.0)], Mods::default()).is_empty()); + assert!(t.busy() && t.ends_on_escape(&cx)); + assert_eq!(click(&mut t, &cx, (340.0, 260.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0))); + assert!(!t.busy() && t.overlays(&cx).is_empty(), "the tool starts afresh"); +} + +/// Two clicks place the ends. Between the second click and the third, the tool shows the arc +/// through the pointer (a half circle here, bulging up the page), its center cross and its +/// radius; the third click draws it. +#[test] +fn three_clicks_draw_the_arc_and_the_tool_shows_it_on_the_way() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + assert!(click(&mut t, &cx, (300.0, 300.0)).is_empty()); + hover(&mut t, &cx, (380.0, 300.0), Mods::default()); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Line { dashed: true, .. })), "the chord so far"); + assert!(click(&mut t, &cx, (380.0, 300.0)).is_empty()); + hover(&mut t, &cx, (340.0, 260.0), Mods::default()); + let o = t.overlays(&cx); + let b = preview(&o).expect("the arc"); + assert!((b.x0 - 300.0).abs() < 0.1 && (b.x1 - 380.0).abs() < 0.1 && (b.y0 - 260.0).abs() < 0.1 && (b.y1 - 300.0).abs() < 1e-9, "{b:?}"); + let radius = format!("R: {}", cx.len(40.0)); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if *text == radius)), "{o:?}"); + // The center cross at (340, 300). + assert!(o.iter().any(|o| matches!(o, Overlay::Line { a, b, dashed: false, .. } if a.midpoint(*b).distance(Point::new(340.0, 300.0)) < 1e-9))); + let quiet = ToolContext { measurement_labels: false, ..cx }; + assert!(!t.overlays(&quiet).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + assert_eq!(click(&mut t, &cx, (340.0, 260.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0))); +} + +/// A third point on the line through the ends, an arc reaching past the canvas, or a third point +/// on an end gives no arc: a click draws nothing and keeps the ends, and a click on a point that +/// fits then draws the arc. The tool shows "Arc too large" by the pointer, except on an end. +#[test] +fn a_third_point_in_line_with_the_ends_draws_nothing() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + // Nearly in line beyond the end: the circle's center is about 1.2·10⁷ pt away. + for (bad, label) in [((420.0, 300.0), true), ((250.0, 300.0), true), ((340.0, 300.0), true), ((500.0, 300.001), true), ((380.0, 300.0), false)] { + hover(&mut t, &cx, bad, Mods::default()); + let o = t.overlays(&cx); + assert!(too_large(&o) == label && preview(&o).is_none(), "{bad:?}: {o:?}"); + assert!(click(&mut t, &cx, bad).is_empty(), "{bad:?}"); + assert!(t.busy()); + } + assert_eq!(click(&mut t, &cx, (340.0, 340.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 340.0))); +} + +/// In direction mode, Shift keeps the direction line at 45° steps from the end it starts at. +#[test] +fn shift_keeps_the_direction_at_45_degree_steps() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + t.set_option("direction", &json!(true)); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + let shift = Mods { shift: true, ..Mods::default() }; + let acts = click_with(&mut t, &cx, (303.0, 250.0), shift); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9), "{params}"); + // With Alt, from the second end. + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + let both = Mods { shift: true, alt: true, ..Mods::default() }; + let acts = click_with(&mut t, &cx, (383.0, 250.0), both); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 380.0).abs() < 1e-9) && params["at"] == "end", "{params}"); +} + +/// With the `direction` option, the third point gives the direction the arc leaves its first +/// end in, and the tool shows the line from that end to the pointer. Alt moves the direction to +/// the second end. `]` switches the option while the ends are placed, and only then. +#[test] +fn in_direction_mode_the_third_point_sets_the_tangent_at_an_end() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + assert!(!t.claims_key(&cx, ToolKey::BracketRight), "no ends: ] is left to the app"); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.options(), json!({ "direction": false })); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + assert!(t.claims_key(&cx, ToolKey::BracketRight)); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.options(), json!({ "direction": true })); + // Straight up the page from (300, 300): the upper half circle about (340, 300). + hover(&mut t, &cx, (300.0, 250.0), Mods::default()); + let o = t.overlays(&cx); + let b = preview(&o).expect("the arc"); + assert!((b.y0 - 260.0).abs() < 0.1 && (b.y1 - 300.0).abs() < 1e-9, "{b:?}"); + // The direction line: solid, from the end it starts at. + let line = |o: &[Overlay], from: Point| o.iter().any(|o| matches!(o, Overlay::Line { a, dashed: false, .. } if *a == from)); + assert!(line(&o, Point::new(300.0, 300.0)), "{o:?}"); + assert_eq!(click(&mut t, &cx, (300.0, 250.0)), toward((300.0, 300.0), (380.0, 300.0), (300.0, 250.0), "start")); + // Alt: the direction line starts at the second end. + t.set_option("direction", &json!(true)); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + let alt = Mods { alt: true, ..Mods::default() }; + hover(&mut t, &cx, (380.0, 250.0), alt); + assert!(line(&t.overlays(&cx), Point::new(380.0, 300.0))); + assert!(preview(&t.overlays(&cx)).is_some()); + assert_eq!(click_with(&mut t, &cx, (380.0, 250.0), alt), toward((300.0, 300.0), (380.0, 300.0), (380.0, 250.0), "end")); + // ] switches back to passing through the third point. + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(click(&mut t, &cx, (340.0, 260.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0))); +} + +/// The `direction` option takes a bool; anything else leaves it as it was. +#[test] +fn the_direction_option_takes_a_bool() { + let mut t = ThreePointArcTool::default(); + t.set_option("direction", &json!(true)); + for v in [json!("false"), json!(0), json!(null)] { + t.set_option("direction", &v); + assert_eq!(t.options(), json!({ "direction": true }), "{v}"); + } + t.set_option("direction", &json!(false)); + assert_eq!(t.options(), json!({ "direction": false })); +} + +/// A release away from the last drag event places the point where the pointer is let go, for +/// the second end and for the third point. +#[test] +fn a_point_is_placed_where_the_press_is_let_go() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let none = Mods::default(); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), none)); + t.pointer(&cx, &ev(PointerKind::Drag, (340.0, 300.0), none)); + t.pointer(&cx, &ev(PointerKind::Up, (380.0, 300.0), none)); + assert_eq!(t.end, Some(Point::new(380.0, 300.0))); + t.pointer(&cx, &ev(PointerKind::Down, (340.0, 250.0), none)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (340.0, 260.0), none)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0))); + // A press that only moves when it is let go still counts as a drag for the ends. + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), none)); + t.pointer(&cx, &ev(PointerKind::Up, (380.0, 300.0), none)); + assert_eq!(t.end, Some(Point::new(380.0, 300.0))); +} + +/// Shift keeps the second end at 45° steps from the first. +#[test] +fn shift_keeps_the_second_end_at_45_degree_steps() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let shift = Mods { shift: true, ..Mods::default() }; + drag(&mut t, &cx, (300.0, 300.0), &[(340.0, 303.0), (380.0, 306.0)], shift); + assert_eq!(t.end.map(|e| e.y), Some(300.0), "{:?}", t.end); +} + +/// Escape, an edit made outside the tool and a dropped press drop the ends; a second click on +/// the first end (a double-click) places nothing. +#[test] +fn escape_history_and_a_double_click_drop_or_keep_the_ends() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + assert!(t.claims_key(&cx, ToolKey::Escape)); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(!t.busy() && !t.claims_key(&cx, ToolKey::Escape)); + click(&mut t, &cx, (300.0, 300.0)); + assert!(click(&mut t, &cx, (300.5, 300.0)).is_empty()); + assert_eq!((t.start, t.end), (Some(Point::new(300.0, 300.0)), None), "the double-click's second click places nothing"); + click(&mut t, &cx, (380.0, 300.0)); + t.history_moved(); + assert!(!t.busy()); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + t.drop_press(&cx); + assert!(!t.busy() && t.overlays(&cx).is_empty()); +} + +/// The catalog lists the tool in the Line Segment tool's group, after the Arc tool, with no +/// default shortcut, and `create` makes it. +#[test] +fn the_tool_is_in_the_line_segment_group_after_the_arc_tool() { + let group = crate::TOOL_GROUPS.iter().find(|g| g.iter().any(|t| t.id == ID)).expect("in a toolbar group"); + let ids: Vec<_> = group.iter().map(|t| t.id).collect(); + let arc = ids.iter().position(|id| *id == "arc").expect("the Arc tool's group"); + assert_eq!(ids.first(), Some(&"lineSegment")); + assert_eq!(ids.get(arc + 1), Some(&ID)); + let info = crate::tool_info(ID).expect("catalogued"); + assert_eq!((info.label, info.shortcut), ("Three-Point Arc Tool", None)); + assert_eq!(crate::create(ID).id(), ID); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9e54eb12f6..98e6cfe0cf 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -141,6 +141,7 @@ mod text_export; pub mod text_import; mod three_d_classic; pub(crate) mod three_d_materials; +pub mod three_point_arc_options; mod tiff_bmp_tga; pub mod tile_edge_color; mod tools; @@ -449,6 +450,7 @@ registry! { FreehandOptions: [freehand::KIND] => freehand::SPEC, ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC, + ThreePointArcOptions: [three_point_arc_options::KIND] => three_point_arc_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, DeleteSymbol: [symbol_delete::KIND] => symbol_delete::SPEC, diff --git a/crates/ui-egui/src/dialogs/three_point_arc_options.rs b/crates/ui-egui/src/dialogs/three_point_arc_options.rs new file mode 100644 index 0000000000..6d0eee96d1 --- /dev/null +++ b/crates/ui-egui/src/dialogs/three_point_arc_options.rs @@ -0,0 +1,84 @@ +//! Three-Point Arc Tool Options (double-click the Three-Point Arc tool, or `tool.options`): +//! Third Point Sets Direction, the tool's `direction` option. With it on, the third point gives the +//! direction the arc leaves an end in; with it off, the arc passes through the third point. OK +//! sets it with `tool.setOption {tool: "threePointArc", values: {direction}}`; it lasts across +//! tool switches and is saved with the preferences. `]` also switches it while an arc is drawn. + +use serde_json::{Map, Value, json}; +use vectorcraft_tools::three_point_arc::ID as TOOL; + +use super::{DialogSpec, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Three-Point Arc Tool Options. +pub const KIND: &str = "threePointArcOptions"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 280.0, ..DialogSpec::FORM }; + +fn heading(_: &Dialog) -> String { + let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label); + crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))]) +} + +/// Open the tool's options with their current values. +pub fn open(app: &mut VectorcraftApp) -> Value { + let on = app.session.tool_options_of(TOOL).get("direction").and_then(Value::as_bool).unwrap_or(false); + let mut fields = Map::new(); + fields.insert("direction".into(), json!(on)); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + json!({ "dialog": KIND }) +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let on = d.bool("direction"); + if widgets::check(ui, tl!("Third Point Sets Direction"), on, true) { + d.fields.insert("direction".into(), json!(!on)); + } + false +} + +/// OK: set the tool's `direction`. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": { "direction": d.bool("direction") } })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app + } + + /// The labels the open dialog paints. + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + #[test] + fn double_clicking_the_tool_opens_its_options_and_ok_sets_the_direction() { + let mut app = app(); + assert_eq!(app.session.tool_options_of(TOOL)["direction"], json!(false)); + let r = app.run("tool.options", json!({"tool": TOOL})).unwrap(); + assert_eq!(r["dialog"], json!(KIND)); + let text = painted(&mut app); + for label in ["Three-Point Arc Tool Options", "Third Point Sets Direction", "OK", "Cancel"] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert!(!d.bool("direction")); + d.fields.insert("direction".into(), json!(true)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.tool_options_of(TOOL)["direction"], json!(true)); + // It lasts while another tool is chosen, and the dialog opens on it again. + app.select_tool(TOOL); + app.select_tool("selection"); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("direction")); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..73b82cc903 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -217,6 +217,10 @@ font-technology Variable Променливи Arc Дъга Arc Lower… Дъга надолу… Arc Tool Инструмент „Дъга“ + Three-Point Arc Tool Инструмент „Дъга през три точки“ + Three-Point Arc Дъга през три точки + Arc too large Дъгата е твърде голяма + Third Point Sets Direction Третата точка задава посоката Arc Upper… Дъга нагоре… Arch… Извиване… Arc… Дъга… @@ -7237,3 +7241,7 @@ breakText Glyphs Глифи @msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" +@msg `at` must be "start" or "end" `at` трябва да е "start" или "end" +@msg give exactly one of `through` and `toward` посочете точно едно от `through` и `toward` +@msg no arc fits these points: two are the same or all three lie on one line няма дъга през тези точки: две съвпадат или и трите лежат на една права +@msg give `at` only with `toward` задайте `at` само заедно с `toward` diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..3259fa3dd8 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1404,6 +1404,10 @@ lighting Light Svjetlo Add Anchor Point Tool Alat za dodavanje sidrene tačke Anchor Point Tool Alat sidrena tačka Arc Tool Alat luk + Three-Point Arc Tool Alat luk kroz tri tačke + Three-Point Arc Luk kroz tri tačke + Arc too large Luk je prevelik + Third Point Sets Direction Treća tačka određuje smjer Area Graph Tool Alat za površinski grafikon Area Type Tool Alat za tekst u području Artboard Tool Alat radna ploča @@ -7291,3 +7295,7 @@ shape Open Otvoren @msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" +@msg `at` must be "start" or "end" `at` mora biti "start" ili "end" +@msg give exactly one of `through` and `toward` navedite tačno jedno od `through` i `toward` +@msg no arc fits these points: two are the same or all three lie on one line nijedan luk ne odgovara ovim tačkama: dvije su iste ili sve tri leže na jednoj pravoj +@msg give `at` only with `toward` navedite `at` samo uz `toward` diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..c66c35daa1 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -338,6 +338,10 @@ antiAlias Sharp Nítid Arc Lower… Arc inferior… Arc Segment Tool Options Opcions de l’eina de segment d’arc Arc Tool Eina d’arc + Three-Point Arc Tool Eina d’arc per tres punts + Three-Point Arc Arc per tres punts + Arc too large Arc massa gran + Third Point Sets Direction El tercer punt indica la direcció Arc Upper… Arc superior… Arch… Arqueja… Arc… Arc… @@ -6152,6 +6156,10 @@ liquify-list-end {0}, {1} {0} i {1} @msg `points` must be three [x, y] pairs of numbers `points` han de ser tres parells de nombres [x, y] @msg direct-select three anchor points, or give `points` seleccioneu directament tres punts d’ancoratge o indiqueu `points` @msg no circle passes through these points: two are the same or all three lie on one line cap cercle no passa per aquests punts: dos són iguals o tots tres són en una mateixa recta +@msg `at` must be "start" or "end" `at` ha de ser "start" o "end" +@msg give exactly one of `through` and `toward` indiqueu exactament un de `through` i `toward` +@msg no arc fits these points: two are the same or all three lie on one line cap arc no s’ajusta a aquests punts: dos són iguals o tots tres són en una mateixa recta +@msg give `at` only with `toward` indiqueu `at` només amb `toward` @msg no app to open files here aquí no hi ha cap aplicació per obrir fitxers @msg no artboard no hi ha tauler @msg no artboard {i} (0-based; the document has {_1}) no hi ha el tauler {i} (basat en 0; el document en té {_1}) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..96b00951be 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1430,6 +1430,10 @@ lighting Light Světlo Add Anchor Point Tool Nástroj Přidat kotevní bod Anchor Point Tool Nástroj Kotevní bod Arc Tool Nástroj Oblouk + Three-Point Arc Tool Nástroj Oblouk třemi body + Three-Point Arc Oblouk třemi body + Arc too large Oblouk je příliš velký + Third Point Sets Direction Třetí bod určuje směr Area Graph Tool Nástroj Plošný graf Area Type Tool Nástroj Text v oblasti Artboard Tool Nástroj Pracovní plocha @@ -5317,6 +5321,10 @@ liquify-list-end {0}, {1} {0} a {1} @msg `points` must be three [x, y] pairs of numbers `points` musí být tři dvojice čísel [x, y] @msg direct-select three anchor points, or give `points` vyberte přímým výběrem tři kotevní body, nebo zadejte `points` @msg no circle passes through these points: two are the same or all three lie on one line těmito body neprochází žádná kružnice: dva jsou stejné nebo všechny tři leží na jedné přímce +@msg `at` must be "start" or "end" `at` musí být "start" nebo "end" +@msg give exactly one of `through` and `toward` zadejte právě jeden z parametrů `through` a `toward` +@msg no arc fits these points: two are the same or all three lie on one line těmto bodům neodpovídá žádný oblouk: dva jsou stejné nebo všechny tři leží na jedné přímce +@msg give `at` only with `toward` parametr `at` zadejte jen s `toward` @msg no app to open files here zde chybí aplikace pro otevírání souborů @msg no artboard žádná pracovní plocha @msg no artboard {i} (0-based; the document has {_1}) pracovní plocha {i} neexistuje (číslováno od 0; dokument jich má {_1}) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..04009d2ee7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4030,6 +4030,10 @@ lighting Light Lys Add Anchor Point Tool Tilføj ankerpunkt-værktøj Anchor Point Tool Ankerpunktværktøj Arc Tool Bueværktøj + Three-Point Arc Tool Værktøj til bue gennem tre punkter + Three-Point Arc Bue gennem tre punkter + Arc too large Buen er for stor + Third Point Sets Direction Tredje punkt angiver retningen Area Graph Tool Områdediagramværktøj Area Type Tool Områdetekstværktøj Artboard Tool Tegnebrætværktøj @@ -7506,6 +7510,10 @@ imageTrace Outline Kontur @msg `points` must be three [x, y] pairs of numbers `points` skal være tre talpar [x, y] @msg direct-select three anchor points, or give `points` direkte markér tre ankerpunkter, eller angiv `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går gennem disse punkter: to er ens, eller alle tre ligger på én linje +@msg `at` must be "start" or "end" `at` skal være "start" eller "end" +@msg give exactly one of `through` and `toward` angiv præcis én af `through` og `toward` +@msg no arc fits these points: two are the same or all three lie on one line ingen bue passer til disse punkter: to er ens, eller alle tre ligger på én linje +@msg give `at` only with `toward` angiv kun `at` sammen med `toward` @msg no app to open files here ingen app til at åbne filer her @msg no artboard ingen tegneflade @msg no artboard {i} (0-based; the document has {_1}) ingen tegneflade {i} (0-baseret; dokumentet har {_1}) diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..84f56dacb8 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -208,6 +208,10 @@ font-technology Variable Variabel Arc Bogen Arc Lower… Bogen unten… Arc Tool Bogen-Werkzeug + Three-Point Arc Tool Dreipunkt-Bogen-Werkzeug + Three-Point Arc Dreipunkt-Bogen + Arc too large Bogen zu groß + Third Point Sets Direction Dritter Punkt gibt die Richtung an Arc Upper… Bogen oben… Arch… Torbogen… Arc… Bogen… @@ -4918,6 +4922,10 @@ liquify-list-end {0}, {1} {0} und {1} @msg `points` must be three [x, y] pairs of numbers `points` muss aus drei Zahlenpaaren [x, y] bestehen @msg direct-select three anchor points, or give `points` wählen Sie drei Ankerpunkte direkt aus oder geben Sie `points` an @msg no circle passes through these points: two are the same or all three lie on one line durch diese Punkte verläuft kein Kreis: zwei sind gleich oder alle drei liegen auf einer Linie +@msg `at` must be "start" or "end" `at` muss „start“ oder „end“ sein +@msg give exactly one of `through` and `toward` geben Sie genau eines von `through` und `toward` an +@msg no arc fits these points: two are the same or all three lie on one line zu diesen Punkten passt kein Bogen: zwei sind gleich oder alle drei liegen auf einer Linie +@msg give `at` only with `toward` geben Sie `at` nur zusammen mit `toward` an @msg no app to open files here hier gibt es keine App zum Öffnen von Dateien @msg no artboard keine Zeichenfläche @msg no artboard {i} (0-based; the document has {_1}) keine Zeichenfläche {i} (Zählung ab 0; das Dokument hat {_1}) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..47c73809f3 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -210,6 +210,10 @@ font-technology Variable Μεταβλητές Arc Τόξο Arc Lower… Κάτω τόξο… Arc Tool Τόξο (Arc Tool) + Three-Point Arc Tool Εργαλείο τόξου τριών σημείων + Three-Point Arc Τόξο τριών σημείων + Arc too large Το τόξο είναι πολύ μεγάλο + Third Point Sets Direction Το τρίτο σημείο ορίζει την κατεύθυνση Arc Upper… Πάνω τόξο… Arch… Αψίδα… Arc… Τόξο… @@ -4976,6 +4980,10 @@ digits Malayalam Μαλαγιάλαμ @msg `points` must be three [x, y] pairs of numbers το `points` πρέπει να είναι τρία ζεύγη αριθμών [x, y] @msg direct-select three anchor points, or give `points` επιλέξτε άμεσα τρία σημεία αγκύρωσης ή δώστε `points` @msg no circle passes through these points: two are the same or all three lie on one line κανένας κύκλος δεν περνά από αυτά τα σημεία: δύο είναι ίδια ή και τα τρία βρίσκονται σε μία ευθεία +@msg `at` must be "start" or "end" το `at` πρέπει να είναι "start" ή "end" +@msg give exactly one of `through` and `toward` δώστε ακριβώς ένα από τα `through` και `toward` +@msg no arc fits these points: two are the same or all three lie on one line κανένα τόξο δεν ταιριάζει σε αυτά τα σημεία: δύο είναι ίδια ή και τα τρία βρίσκονται σε μία ευθεία +@msg give `at` only with `toward` δώστε το `at` μόνο μαζί με το `toward` @msg no app to open files here δεν υπάρχει εφαρμογή για άνοιγμα αρχείων εδώ @msg no artboard δεν υπάρχει πίνακας σχεδίασης @msg no artboard {i} (0-based; the document has {_1}) δεν υπάρχει πίνακας σχεδίασης {i} (αρίθμηση από 0· το έγγραφο περιέχει {_1}) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..55f8679f6b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -231,6 +231,10 @@ font-technology Variable Variables Arc Arco Arc Lower… Arco inferior… Arc Tool Herramienta Arco + Three-Point Arc Tool Herramienta Arco por tres puntos + Three-Point Arc Arco por tres puntos + Arc too large Arco demasiado grande + Third Point Sets Direction El tercer punto indica la dirección Arc Upper… Arco superior… Arch… Arcada… Arc… Arco… @@ -5022,6 +5026,10 @@ liquify-list-end {0}, {1} {0}, {1} @msg `points` must be three [x, y] pairs of numbers `points` debe ser tres pares de números [x, y] @msg direct-select three anchor points, or give `points` seleccione directamente tres puntos de ancla o indique `points` @msg no circle passes through these points: two are the same or all three lie on one line ningún círculo pasa por estos puntos: dos son iguales o los tres están en una misma línea +@msg `at` must be "start" or "end" `at` debe ser "start" o "end" +@msg give exactly one of `through` and `toward` indique exactamente uno de `through` y `toward` +@msg no arc fits these points: two are the same or all three lie on one line ningún arco se ajusta a estos puntos: dos son iguales o los tres están en una misma línea +@msg give `at` only with `toward` indique `at` solo junto con `toward` @msg no app to open files here aquí no hay ninguna aplicación para abrir archivos @msg no artboard no hay mesa de trabajo @msg no artboard {i} (0-based; the document has {_1}) no existe la mesa de trabajo {i} (contando desde 0; el documento tiene {_1}) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..584a7e2b38 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1406,6 +1406,10 @@ lighting Light Valo Add Anchor Point Tool Lisää ankkuripiste -työkalu Anchor Point Tool Ankkuripistetyökalu Arc Tool Kaarityökalu + Three-Point Arc Tool Kolmen pisteen kaaren työkalu + Three-Point Arc Kolmen pisteen kaari + Arc too large Kaari on liian suuri + Third Point Sets Direction Kolmas piste määrää suunnan Area Graph Tool Aluekaaviotyökalu Area Type Tool Aluetekstityökalu Artboard Tool Piirtoalustatyökalu @@ -5246,6 +5250,10 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `points` must be three [x, y] pairs of numbers `points` on annettava kolmena lukuparina [x, y] @msg direct-select three anchor points, or give `points` valitse suoraan kolme ankkuripistettä tai anna `points` @msg no circle passes through these points: two are the same or all three lie on one line näiden pisteiden kautta ei kulje ympyrää: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla +@msg `at` must be "start" or "end" `at` on oltava "start" tai "end" +@msg give exactly one of `through` and `toward` anna täsmälleen yksi parametreista `through` ja `toward` +@msg no arc fits these points: two are the same or all three lie on one line näihin pisteisiin ei sovi kaarta: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla +@msg give `at` only with `toward` anna `at` vain yhdessä parametrin `toward` kanssa @msg no app to open files here täällä ei ole sovellusta tiedostojen avaamiseen @msg no artboard ei piirtoalustaa @msg no artboard {i} (0-based; the document has {_1}) ei piirtoalustaa {i} (0-pohjainen; asiakirjassa on {_1}) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..6486babbde 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -232,6 +232,10 @@ font-technology Variable Variables Arc Arc Arc Lower… Arc inférieur… Arc Tool Outil Arc + Three-Point Arc Tool Outil Arc par trois points + Three-Point Arc Arc par trois points + Arc too large Arc trop grand + Third Point Sets Direction Le troisième point indique la direction Arc Upper… Arc supérieur… Arch… Arche… Arc… Arc… @@ -4984,6 +4988,10 @@ liquify-list-end {0}, {1} {0} et {1} @msg `points` must be three [x, y] pairs of numbers `points` doit contenir trois paires de nombres [x, y] @msg direct-select three anchor points, or give `points` sélectionnez trois points d’ancrage avec l’outil Sélection directe, ou indiquez `points` @msg no circle passes through these points: two are the same or all three lie on one line aucun cercle ne passe par ces points : deux sont identiques ou les trois sont alignés +@msg `at` must be "start" or "end" `at` doit valoir "start" ou "end" +@msg give exactly one of `through` and `toward` indiquez exactement un seul de `through` et `toward` +@msg no arc fits these points: two are the same or all three lie on one line aucun arc ne correspond à ces points : deux sont identiques ou les trois sont alignés +@msg give `at` only with `toward` indiquez `at` uniquement avec `toward` @msg no app to open files here aucune application pour ouvrir des fichiers ici @msg no artboard aucun plan de travail @msg no artboard {i} (0-based; the document has {_1}) aucun plan de travail {i} (numérotation à partir de 0 ; le document en a {_1}) diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..5d82f47415 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -275,6 +275,10 @@ Arc Lower… નીચે આર્ક… Arc Segment Tool Options આર્ક સેગમેન્ટ ટૂલ વિકલ્પો Arc Tool આર્ક ટૂલ + Three-Point Arc Tool ત્રણ-પૉઇન્ટ આર્ક ટૂલ + Three-Point Arc ત્રણ-પૉઇન્ટ આર્ક + Arc too large આર્ક ખૂબ મોટો છે + Third Point Sets Direction ત્રીજો પૉઇન્ટ દિશા નક્કી કરે છે Arc Upper… ઉપર આર્ક… Arch… કમાન… Arc… આર્ક… @@ -4987,3 +4991,7 @@ swatch [Registration] [રજિસ્ટ્રેશન] Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" +@msg `at` must be "start" or "end" `at` "start" અથવા "end" હોવું જોઈએ +@msg give exactly one of `through` and `toward` `through` અને `toward` માંથી બરાબર એક આપો +@msg no arc fits these points: two are the same or all three lie on one line આ પૉઇન્ટ્સમાં કોઈ આર્ક બેસતો નથી: બે એકસરખા છે અથવા ત્રણેય એક જ રેખા પર છે +@msg give `at` only with `toward` `at` ફક્ત `toward` સાથે જ આપો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..65d42fc13c 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -391,6 +391,10 @@ antiAlias Sharp शार्प Arc Lower… निचला आर्क… Arc Segment Tool Options आर्क सेगमेंट टूल ऑप्शन्स Arc Tool आर्क टूल + Three-Point Arc Tool थ्री-पॉइंट आर्क टूल + Three-Point Arc थ्री-पॉइंट आर्क + Arc too large आर्क बहुत बड़ा है + Third Point Sets Direction तीसरा पॉइंट दिशा तय करता है Arc Upper… ऊपरी आर्क… Arc… आर्क… Arch… मेहराब… @@ -7634,6 +7638,10 @@ liquify-list-end {0}, {1} {0} और {1} @msg `points` must be three [x, y] pairs of numbers `points` में संख्याओं के तीन [x, y] जोड़े होने चाहिए @msg direct-select three anchor points, or give `points` तीन एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें, या `points` दें @msg no circle passes through these points: two are the same or all three lie on one line इन पॉइंट्स से होकर कोई वृत्त नहीं गुज़रता: दो एक जैसे हैं या तीनों एक ही रेखा पर हैं +@msg `at` must be "start" or "end" `at` को "start" या "end" होना चाहिए। +@msg give exactly one of `through` and `toward` `through` और `toward` में से ठीक एक दें +@msg no arc fits these points: two are the same or all three lie on one line इन पॉइंट्स पर कोई आर्क फ़िट नहीं होता: दो एक जैसे हैं या तीनों एक ही रेखा पर हैं +@msg give `at` only with `toward` `at` केवल `toward` के साथ दें @msg no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है @msg no appearance item {index} कोई उपस्थिति आइटम {index} @msg no artboard कोई आर्टबोर्ड नहीं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..dd38f6dc7f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -315,6 +315,10 @@ font-technology Variable Változó Arc Ív Arc Lower… Alsó ív… Arc Tool Ív + Three-Point Arc Tool Hárompontos ív eszköz + Three-Point Arc Hárompontos ív + Arc too large Az ív túl nagy + Third Point Sets Direction A harmadik pont adja meg az irányt Arc Upper… Felső ív… Arch… Boltív… Arc… Ív… @@ -5685,6 +5689,10 @@ liquify-list-end {0}, {1} {0} és {1} @msg `points` must be three [x, y] pairs of numbers a `points` három [x, y] számpár legyen @msg direct-select three anchor points, or give `points` jelölj ki közvetlen kijelöléssel három horgonypontot, vagy add meg a `points` értéket @msg no circle passes through these points: two are the same or all three lie on one line ezeken a pontokon nem halad át kör: kettő egybeesik, vagy mindhárom egy egyenesen van +@msg `at` must be "start" or "end" `at`: "start" vagy "end" kell +@msg give exactly one of `through` and `toward` pontosan egyet adjon meg a `through` és a `toward` közül +@msg no arc fits these points: two are the same or all three lie on one line ezekre a pontokra nem illeszkedik ív: kettő egybeesik, vagy mindhárom egy egyenesen van +@msg give `at` only with `toward` az `at` csak a `toward` mellett adható meg @msg no app to open files here itt nincs fájlmegnyitó alkalmazás @msg no artboard nincs rajztábla @msg no artboard {i} (0-based; the document has {_1}) nincs ilyen sorszámú rajztábla: {i} (0-tól számozva; a dokumentumban ennyi van: {_1}) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..131b42d7dc 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1331,6 +1331,10 @@ lighting Light Cahaya Add Anchor Point Tool Alat tambah titik jangkar Anchor Point Tool Alat titik jangkar Arc Tool Alat busur + Three-Point Arc Tool Alat busur tiga titik + Three-Point Arc Busur tiga titik + Arc too large Busur terlalu besar + Third Point Sets Direction Titik ketiga menentukan arah Area Graph Tool Alat grafik area Area Type Tool Alat teks area Artboard Tool Alat artboard @@ -7252,3 +7256,7 @@ breakText Glyphs Glif @msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" +@msg `at` must be "start" or "end" `at` harus "start" atau "end" +@msg give exactly one of `through` and `toward` berikan tepat satu dari `through` dan `toward` +@msg no arc fits these points: two are the same or all three lie on one line tidak ada busur yang cocok dengan titik-titik ini: dua titik sama atau ketiganya segaris +@msg give `at` only with `toward` berikan `at` hanya bersama `toward` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..4c433d9170 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -233,6 +233,10 @@ font-technology Variable Variabili Arc Arco Arc Lower… Arco inferiore… Arc Tool Strumento Arco + Three-Point Arc Tool Strumento Arco per tre punti + Three-Point Arc Arco per tre punti + Arc too large Arco troppo grande + Third Point Sets Direction Il terzo punto indica la direzione Arc Upper… Arco superiore… Arch… Arcata… Arc… Arco… @@ -5052,6 +5056,10 @@ liquify-list-end {0}, {1} {0} e {1} @msg `points` must be three [x, y] pairs of numbers `points` deve essere composto da tre coppie di numeri [x, y] @msg direct-select three anchor points, or give `points` seleziona con Selezione diretta tre punti di ancoraggio oppure indica `points` @msg no circle passes through these points: two are the same or all three lie on one line nessun cerchio passa per questi punti: due coincidono oppure tutti e tre sono allineati +@msg `at` must be "start" or "end" `at` deve essere "start" o "end" +@msg give exactly one of `through` and `toward` indicare esattamente uno tra `through` e `toward` +@msg no arc fits these points: two are the same or all three lie on one line nessun arco si adatta a questi punti: due coincidono oppure tutti e tre sono allineati +@msg give `at` only with `toward` indicare `at` solo insieme a `toward` @msg no app to open files here nessuna app per aprire file qui @msg no artboard nessuna tavola da disegno @msg no artboard {i} (0-based; the document has {_1}) nessuna tavola da disegno {i} (a partire da 0; il documento ne ha {_1}) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..77827e1efa 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1142,6 +1142,10 @@ antiAlias Sharp シャープ @plural Apply to All ({n} more missing)|Apply to All ({n} more missing) すべてに適用 (ほかに {n} 個が見つかりません) Arc 円弧 Arc Tool 円弧ツール + Three-Point Arc Tool 3 点円弧ツール + Three-Point Arc 3 点円弧 + Arc too large 円弧が大きすぎます + Third Point Sets Direction 3 点目で方向を指定 Area / Path Type エリア内文字/パス上文字 Area Graph Tool 面グラフツール Area Type Tool エリア内文字ツール @@ -4846,6 +4850,10 @@ swatch Bright Violet ビビッドバイオレット @msg `points` must be three [x, y] pairs of numbers `points` は 3 組の数値 [x, y] にしてください @msg direct-select three anchor points, or give `points` アンカーポイントを 3 つダイレクト選択するか、`points` を指定してください @msg no circle passes through these points: two are the same or all three lie on one line これらの点を通る円はありません: 2 つの点が同じか、3 点すべてが一直線上にあります +@msg `at` must be "start" or "end" `at` には "start" または "end" を指定してください +@msg give exactly one of `through` and `toward` `through` と `toward` のどちらか一方だけを指定してください +@msg no arc fits these points: two are the same or all three lie on one line これらの点に合う円弧はありません: 2 つの点が同じか、3 点すべてが一直線上にあります +@msg give `at` only with `toward` `at` は `toward` と一緒にだけ指定してください @msg select at least two objects オブジェクトを 2 つ以上選択してください @msg exit isolation mode first 先に分離モードを終了してください @msg no saved presets 保存したプリセットはありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..42f7301bc3 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3483,6 +3483,10 @@ lighting Light სინათლე Add Anchor Point Tool საყრდენი წერტილის დამატების ხელსაწყო Anchor Point Tool საყრდენი წერტილის ხელსაწყო Arc Tool რკალის ხელსაწყო + Three-Point Arc Tool სამწერტილიანი რკალის ხელსაწყო + Three-Point Arc სამწერტილიანი რკალი + Arc too large რკალი ზედმეტად დიდია + Third Point Sets Direction მესამე წერტილი მიმართულებას განსაზღვრავს Area Graph Tool ფართობითი დიაგრამის ხელსაწყო Area Type Tool არის ტექსტის ხელსაწყო Artboard Tool სამუშაო დაფის ხელსაწყო @@ -6831,6 +6835,10 @@ font-technology Variable ცვლადი @msg `points` must be three [x, y] pairs of numbers `points` უნდა იყოს რიცხვების სამი [x, y] წყვილი @msg direct-select three anchor points, or give `points` პირდაპირი მონიშვნით მონიშნეთ სამი საყრდენი წერტილი ან მიუთითეთ `points` @msg no circle passes through these points: two are the same or all three lie on one line ამ წერტილებზე წრეწირი არ გადის: ორი ერთნაირია ან სამივე ერთ წრფეზე მდებარეობს +@msg `at` must be "start" or "end" `at` უნდა იყოს "start" ან "end" +@msg give exactly one of `through` and `toward` მიუთითეთ ზუსტად ერთი: `through` ან `toward` +@msg no arc fits these points: two are the same or all three lie on one line ამ წერტილებს რკალი არ ერგება: ორი ერთნაირია ან სამივე ერთ წრფეზე მდებარეობს +@msg give `at` only with `toward` `at` მიუთითეთ მხოლოდ `toward`-თან ერთად @msg no app to open files here აქ ფაილების გასახსნელი აპი არ არის @msg no artboard სამუშაო დაფა არ არის @msg no artboard {i} (0-based; the document has {_1}) სამუშაო დაფა {i} არ არსებობს (0-დან ითვლება; დოკუმენტს აქვს {_1}) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..37db37b4b6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1132,6 +1132,10 @@ antiAlias Sharp 날카롭게 @plural Apply to All ({n} more missing)|Apply to All ({n} more missing) 모두에 적용(누락 {n}개 더 있음) Arc 호 Arc Tool 호 도구 + Three-Point Arc Tool 3점 호 도구 + Three-Point Arc 3점 호 + Arc too large 호가 너무 큽니다 + Third Point Sets Direction 세 번째 점으로 방향 지정 Area / Path Type 영역/패스 문자 Area Graph Tool 영역 그래프 도구 Area Type Tool 영역 문자 도구 @@ -4773,6 +4777,10 @@ theme Appearance 외관 @msg `points` must be three [x, y] pairs of numbers `points`는 숫자 쌍 [x, y] 세 개여야 합니다 @msg direct-select three anchor points, or give `points` 앵커 포인트 세 개를 직접 선택하거나 `points`를 지정하세요 @msg no circle passes through these points: two are the same or all three lie on one line 이 점들을 지나는 원이 없습니다: 두 점이 같거나 세 점이 모두 한 직선 위에 있습니다 +@msg `at` must be "start" or "end" `at`은(는) "start" 또는 "end"여야 합니다 +@msg give exactly one of `through` and `toward` `through`와 `toward` 중 정확히 하나만 지정하세요 +@msg no arc fits these points: two are the same or all three lie on one line 이 점들에 맞는 호가 없습니다: 두 점이 같거나 세 점이 모두 한 직선 위에 있습니다 +@msg give `at` only with `toward` `at`은(는) `toward`와 함께만 지정하세요 @msg select at least two objects 개체를 두 개 이상 선택하세요 @msg exit isolation mode first 먼저 격리 모드를 종료하세요 @msg no saved presets 저장된 프리셋이 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..89d7e0835a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1904,6 +1904,10 @@ lighting Light Licht Add Anchor Point Tool Ankerpunt toevoegen Anchor Point Tool Ankerpunt-gereedschap Arc Tool Boog-gereedschap + Three-Point Arc Tool Driepuntsboog-gereedschap + Three-Point Arc Driepuntsboog + Arc too large Boog te groot + Third Point Sets Direction Derde punt geeft de richting aan Area Graph Tool Vlakdiagram-gereedschap Area Type Tool Vlaktype-gereedschap Artboard Tool Tekengebied-gereedschap @@ -5379,6 +5383,10 @@ imageTrace Outline Contour @msg `points` must be three [x, y] pairs of numbers `points` moet uit drie getallenparen [x, y] bestaan @msg direct-select three anchor points, or give `points` selecteer met directe selectie drie ankerpunten of geef `points` op @msg no circle passes through these points: two are the same or all three lie on one line er gaat geen cirkel door deze punten: twee zijn gelijk of alle drie liggen op één lijn +@msg `at` must be "start" or "end" `at` moet "start" of "end" zijn +@msg give exactly one of `through` and `toward` geef precies één van `through` en `toward` +@msg no arc fits these points: two are the same or all three lie on one line er past geen boog bij deze punten: twee zijn gelijk of alle drie liggen op één lijn +@msg give `at` only with `toward` geef `at` alleen samen met `toward` @msg no app to open files here hier is geen app om bestanden mee te openen @msg no artboard geen tekengebied @msg no artboard {i} (0-based; the document has {_1}) geen tekengebied {i} (vanaf 0; het document heeft er {_1}) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..21d511ffa2 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1356,6 +1356,10 @@ lighting Light Światło Add Anchor Point Tool Narzędzie Dodaj punkt kontrolny Anchor Point Tool Narzędzie Punkt kontrolny Arc Tool Narzędzie Łuk + Three-Point Arc Tool Narzędzie Łuk przez trzy punkty + Three-Point Arc Łuk przez trzy punkty + Arc too large Łuk jest za duży + Third Point Sets Direction Trzeci punkt wyznacza kierunek Area Graph Tool Narzędzie Wykres warstwowy Area Type Tool Narzędzie Tekst akapitowy Artboard Tool Narzędzie Obszar kompozycji @@ -5140,6 +5144,10 @@ liquify-list-end {0}, {1} {0} i {1} @msg `points` must be three [x, y] pairs of numbers `points` musi zawierać trzy pary liczb [x, y] @msg direct-select three anchor points, or give `points` zaznacz bezpośrednio trzy punkty kontrolne lub podaj `points` @msg no circle passes through these points: two are the same or all three lie on one line przez te punkty nie przechodzi żaden okrąg: dwa są takie same albo wszystkie trzy leżą na jednej prostej +@msg `at` must be "start" or "end" `at` musi mieć wartość "start" lub "end" +@msg give exactly one of `through` and `toward` podaj dokładnie jeden z parametrów `through` i `toward` +@msg no arc fits these points: two are the same or all three lie on one line żaden łuk nie pasuje do tych punktów: dwa są takie same albo wszystkie trzy leżą na jednej prostej +@msg give `at` only with `toward` podaj `at` tylko razem z `toward` @msg no app to open files here brak aplikacji do otwierania plików @msg no artboard brak obszaru kompozycji @msg no artboard {i} (0-based; the document has {_1}) brak obszaru kompozycji {i} (numeracja od 0; dokument ma {_1}) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..f9851ce49b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -226,6 +226,10 @@ antiAlias Sharp Nítido Arc Arco Arc Lower… Arco Inferior… Arc Tool Ferramenta Arco + Three-Point Arc Tool Ferramenta Arco por três pontos + Three-Point Arc Arco por três pontos + Arc too large Arco grande demais + Third Point Sets Direction O terceiro ponto indica a direção Arc Upper… Arco Superior… Arch… Abóbada… Arc… Arco… @@ -4326,6 +4330,10 @@ axis Both Ambos @msg `points` must be three [x, y] pairs of numbers `points` deve ter três pares de números [x, y] @msg direct-select three anchor points, or give `points` selecione diretamente três pontos de ancoragem ou informe `points` @msg no circle passes through these points: two are the same or all three lie on one line nenhum círculo passa por esses pontos: dois são iguais ou os três estão na mesma reta +@msg `at` must be "start" or "end" `at` deve ser "start" ou "end" +@msg give exactly one of `through` and `toward` informe exatamente um entre `through` e `toward` +@msg no arc fits these points: two are the same or all three lie on one line nenhum arco se ajusta a esses pontos: dois são iguais ou os três estão na mesma reta +@msg give `at` only with `toward` informe `at` somente com `toward` @msg no app to open files here nenhum aplicativo para abrir arquivos aqui @msg no artboard nenhuma prancheta @msg no artboard {i} (0-based; the document has {_1}) nenhuma prancheta {i} (base 0; o documento tem {_1}) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..d1007f216f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -229,6 +229,10 @@ font-technology Variable Вариативные Arc Дуга Arc Lower… Дуга снизу… Arc Tool Инструмент «Дуга» + Three-Point Arc Tool Инструмент «Дуга по трём точкам» + Three-Point Arc Дуга по трём точкам + Arc too large Дуга слишком велика + Third Point Sets Direction Третья точка задаёт направление Arc Upper… Дуга сверху… Arch… Арка… Arc… Дуга… @@ -5046,6 +5050,10 @@ liquify-list-end {0}, {1} {0} и {1} @msg `points` must be three [x, y] pairs of numbers `points` должен содержать три пары чисел [x, y] @msg direct-select three anchor points, or give `points` выделите прямым выделением три опорные точки или задайте `points` @msg no circle passes through these points: two are the same or all three lie on one line через эти точки не проходит ни одна окружность: две точки совпадают или все три лежат на одной прямой +@msg `at` must be "start" or "end" `at` должно быть "start" или "end" +@msg give exactly one of `through` and `toward` укажите ровно один из параметров `through` и `toward` +@msg no arc fits these points: two are the same or all three lie on one line ни одна дуга не подходит к этим точкам: две точки совпадают или все три лежат на одной прямой +@msg give `at` only with `toward` указывайте `at` только вместе с `toward` @msg no app to open files here здесь нет приложения для открытия файлов @msg no artboard нет монтажной области @msg no artboard {i} (0-based; the document has {_1}) нет монтажной области {i} (счёт с 0; в документе {_1}) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..a0bd35fb66 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -219,6 +219,10 @@ font-technology Variable Variabla Arc Båge Arc Lower… Nedre båge… Arc Tool Bågverktyg + Three-Point Arc Tool Verktyg för trepunktsbåge + Three-Point Arc Trepunktsbåge + Arc too large Bågen är för stor + Third Point Sets Direction Tredje punkten anger riktningen Arc Upper… Övre båge… Arch… Valv… Arc… Båge… @@ -4919,6 +4923,10 @@ liquify-list-end {0}, {1} {0} och {1} @msg `points` must be three [x, y] pairs of numbers `points` måste vara tre talpar [x, y] @msg direct-select three anchor points, or give `points` direktmarkera tre ankarpunkter eller ange `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går genom de här punkterna: två är samma punkt eller så ligger alla tre på en linje +@msg `at` must be "start" or "end" `at` måste vara "start" eller "end" +@msg give exactly one of `through` and `toward` ange exakt en av `through` och `toward` +@msg no arc fits these points: two are the same or all three lie on one line ingen båge passar de här punkterna: två är samma punkt eller så ligger alla tre på en linje +@msg give `at` only with `toward` ange `at` endast tillsammans med `toward` @msg no app to open files here det finns ingen app för att öppna filer här @msg no artboard ingen rityta @msg no artboard {i} (0-based; the document has {_1}) ingen rityta {i} (räknat från 0; dokumentet har {_1}) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..935008b5e3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -216,6 +216,10 @@ font-technology Variable Değişken Arc Yay Arc Lower… Ark Alt… Arc Tool Yay Aracı + Three-Point Arc Tool Üç Noktalı Yay Aracı + Three-Point Arc Üç Noktalı Yay + Arc too large Yay çok büyük + Third Point Sets Direction Üçüncü Nokta Yönü Belirler Arc Upper… Ark Üst… Arch… Kemer… Arc… Yay… @@ -4739,6 +4743,10 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `points` must be three [x, y] pairs of numbers `points` üç [x, y] sayı çifti olmalıdır @msg direct-select three anchor points, or give `points` üç bağlantı noktasını doğrudan seçin veya `points` verin @msg no circle passes through these points: two are the same or all three lie on one line bu noktalardan geçen bir çember yok: ikisi aynı ya da üçü de aynı doğru üzerinde +@msg `at` must be "start" or "end" `at` "start" veya "end" olmalıdır +@msg give exactly one of `through` and `toward` `through` ve `toward` değerlerinden tam olarak birini verin +@msg no arc fits these points: two are the same or all three lie on one line bu noktalara uyan bir yay yok: ikisi aynı ya da üçü de aynı doğru üzerinde +@msg give `at` only with `toward` `at` değerini yalnızca `toward` ile birlikte verin @msg no app to open files here burada dosyaları açacak uygulama yok @msg no artboard çalışma yüzeyi yok @msg no artboard {i} (0-based; the document has {_1}) çalışma yüzeyi yok {i} (0 tabanlı; belgede {_1} var) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..5edad94723 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -227,6 +227,10 @@ font-technology Variable Варіативні Arc Дуга Arc Lower… Дуга знизу… Arc Tool Інструмент «Дуга» + Three-Point Arc Tool Інструмент «Дуга за трьома точками» + Three-Point Arc Дуга за трьома точками + Arc too large Дуга завелика + Third Point Sets Direction Третя точка задає напрямок Arc Upper… Дуга зверху… Arch… Арка… Arc… Дуга… @@ -5036,6 +5040,10 @@ liquify-list-end {0}, {1} {0} і {1} @msg `points` must be three [x, y] pairs of numbers `points` має містити три пари чисел [x, y] @msg direct-select three anchor points, or give `points` виділіть три опорні точки прямим виділенням або задайте `points` @msg no circle passes through these points: two are the same or all three lie on one line через ці точки не проходить жодне коло: дві точки збігаються або всі три лежать на одній прямій +@msg `at` must be "start" or "end" `at` має бути "start" або "end" +@msg give exactly one of `through` and `toward` вкажіть рівно один із параметрів `through` і `toward` +@msg no arc fits these points: two are the same or all three lie on one line жодна дуга не підходить до цих точок: дві точки збігаються або всі три лежать на одній прямій +@msg give `at` only with `toward` вказуйте `at` лише разом із `toward` @msg no app to open files here тут немає програми для відкриття файлів @msg no artboard немає монтажної області @msg no artboard {i} (0-based; the document has {_1}) немає монтажної області {i} (рахунок з 0; у документі {_1}) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..21d3a9cc9b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -252,6 +252,10 @@ font-technology Variable Biến thiên Arc Cung Arc Lower… Cung dưới… Arc Tool Công cụ Cung + Three-Point Arc Tool Công cụ Cung ba điểm + Three-Point Arc Cung ba điểm + Arc too large Cung quá lớn + Third Point Sets Direction Điểm thứ ba chỉ hướng Arc Upper… Cung trên… Arch… Vòm… Arc… Cung… @@ -5368,6 +5372,10 @@ liquify-list-end {0}, {1} {0} và {1} @msg `points` must be three [x, y] pairs of numbers `points` phải là ba cặp số [x, y] @msg direct-select three anchor points, or give `points` hãy chọn trực tiếp ba điểm neo hoặc cung cấp `points` @msg no circle passes through these points: two are the same or all three lie on one line không có đường tròn nào đi qua các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng +@msg `at` must be "start" or "end" `at` phải là "start" hoặc "end" +@msg give exactly one of `through` and `toward` hãy cho đúng một trong hai `through` và `toward` +@msg no arc fits these points: two are the same or all three lie on one line không có cung nào khớp với các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng +@msg give `at` only with `toward` chỉ cho `at` cùng với `toward` @msg no app to open files here không có ứng dụng để mở tệp ở đây @msg no artboard không có bảng vẽ @msg no artboard {i} (0-based; the document has {_1}) không có bảng vẽ {i} (bắt đầu từ 0; tài liệu có {_1}) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..4f9eac1140 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -177,6 +177,10 @@ antiAlias Sharp 锐利 Arc 弧形 Arc Lower… 下弧形… Arc Tool 弧形工具 + Three-Point Arc Tool 三点弧形工具 + Three-Point Arc 三点弧形 + Arc too large 弧形过大 + Third Point Sets Direction 第三点指示方向 Arc Upper… 上弧形… Arch… 拱形… Arc… 弧形… @@ -4544,6 +4548,10 @@ imageTrace Outline 轮廓 @msg `points` must be three [x, y] pairs of numbers `points` 必须是三对数字 [x, y] @msg direct-select three anchor points, or give `points` 请直接选择三个锚点,或提供 `points` @msg no circle passes through these points: two are the same or all three lie on one line 没有圆经过这些点:有两点相同,或三点共线 +@msg `at` must be "start" or "end" `at` 必须是 "start" 或 "end" +@msg give exactly one of `through` and `toward` `through` 和 `toward` 必须且只能指定一个 +@msg no arc fits these points: two are the same or all three lie on one line 没有弧形符合这些点:有两点相同,或三点共线 +@msg give `at` only with `toward` `at` 只能与 `toward` 一起指定 @msg select at least two objects 请至少选择两个对象 @msg exit isolation mode first 请先退出隔离模式 @msg no saved presets 没有已保存的预设 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..8b9dc7f67f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -191,6 +191,10 @@ font-technology Variable 可變 Arc 弧形 Arc Lower… 下弧形… Arc Tool 弧形工具 + Three-Point Arc Tool 三點弧形工具 + Three-Point Arc 三點弧形 + Arc too large 弧形過大 + Third Point Sets Direction 第三點指示方向 Arc Upper… 上弧形… Arch… 拱形… Arc… 弧形… @@ -2077,6 +2081,10 @@ file-filter Templates 範本 @msg `points` must be three [x, y] pairs of numbers `points` 必須是三組數字 [x, y] @msg direct-select three anchor points, or give `points` 請以直接選取方式選取三個錨點,或提供 `points` @msg no circle passes through these points: two are the same or all three lie on one line 沒有圓通過這些點:有兩點相同,或三點共線 +@msg `at` must be "start" or "end" `at` 必須是 "start" 或 "end" +@msg give exactly one of `through` and `toward` `through` 與 `toward` 必須且只能指定一個 +@msg no arc fits these points: two are the same or all three lie on one line 沒有弧形符合這些點:有兩點相同,或三點共線 +@msg give `at` only with `toward` `at` 只能與 `toward` 一起指定 @msg select at least two objects 請選取至少兩個物件 @msg exit isolation mode first 請先結束隔離模式 @msg no saved presets 沒有已儲存的預設集 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index f521e45c22..03786cd0ce 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -45,6 +45,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-anchor-smooth", include_bytes!("../../../assets/icons/dc-anchor-smooth.svg")), ("dc-appearance", include_bytes!("../../../assets/icons/dc-appearance.svg")), ("dc-arc", include_bytes!("../../../assets/icons/dc-arc.svg")), + ("dc-arc-three-point", include_bytes!("../../../assets/icons/dc-arc-three-point.svg")), ("dc-arrow-down", include_bytes!("../../../assets/icons/dc-arrow-down.svg")), ("dc-arrow-extend", include_bytes!("../../../assets/icons/dc-arrow-extend.svg")), ("dc-arrow-tip", include_bytes!("../../../assets/icons/dc-arrow-tip.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index e352653279..7a9d64b15a 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -38,6 +38,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-touch-type" => "dc-touch-type", "tool-line" => "dc-line", "tool-arc" => "dc-arc", + "tool-three-point-arc" => "dc-arc-three-point", "tool-spiral" => "tornado", "tool-rect-grid" => "dc-rect-grid", "tool-polar-grid" => "dc-polar-grid", diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 56de30acff..709780df21 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -37,7 +37,7 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[ ( "Shapes", &[ - &["rectangle", "roundedRectangle", "star", "lineSegment", "arc", "spiral", "rectangularGrid", "polarGrid", "flare"], + &["rectangle", "roundedRectangle", "star", "lineSegment", "arc", "threePointArc", "spiral", "rectangularGrid", "polarGrid", "flare"], &["ellipse"], &["polygon"], &["shaper"], @@ -460,6 +460,8 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result crate::dialogs::shapes::open_options(app, tool), + // The Three-Point Arc tool: whether the third point gives a direction. + vectorcraft_tools::three_point_arc::ID => Ok(crate::dialogs::three_point_arc_options::open(app)), // The Flare tool: its options, which draw the next flare (OK draws none). "flare" => Ok(crate::dialogs::flare_options::open(app, None)), // A double click on the Print Tiling tool puts the pages back where the placement puts them. diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..2662b3fc37 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -788,6 +788,35 @@ from −100 to 100 and is 50 when left out with `lengthX` and `lengthY`, or 100 `` `baseAlong` must be one of x, y ``), as is a `slope` outside its range; the arc is not drawn and no undo step is added. +`shape.threePointArc {start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: "start"|"end"}` draws an +open circular arc from `start` to `end` and selects it. With `through`, the arc passes through that point. With +`toward`, the arc leaves `start` heading toward that point, so the line from `start` to the point is the arc's tangent +there. With `at: "end"`, the line from `end` to the point is the tangent at `end` instead. `at` is `"start"` when left +out, and `at` with `through` is an error. The arc has no fill and the current stroke (black when the stroke is none), +its ends are exactly the two points (it is not pixel-aligned), and it has a smooth anchor at the `through` point and +further smooth anchors so that no curve of the path turns more than a quarter turn. The result is +`{id, cx, cy, radius, sweep}`: the circle's center and radius, and the arc's turn in degrees, positive clockwise on the +page. One undo removes the arc. The command returns an error and draws nothing when two of the points are the same, +when the third point lies on the line through the ends, when the arc would reach past the canvas, when a point is not +`[x, y]`, when both or neither of `through` and `toward` are given, when `at` is anything but `"start"` or `"end"`, and +when `at` is given with `through`. + +The Three-Point Arc tool, in the Line Segment tool's group after the Arc tool, runs this command. A drag from one end to +the other, or a click on each, places the ends; Shift keeps the second end at 45° steps from the first (from General › +Constrain Angle). A click on a third point, or a press dragged to it, then draws the arc through it. With the tool's +`direction` option on, the third point gives the direction the arc leaves the first end in; with `mods.alt`, the +direction is at the second end, and Shift keeps the direction at 45° steps. Three-Point Arc Tool Options (`tool.options`, +or a double-click on the tool) sets `direction` with its Third Point Sets Direction box, and +`]` (with or without Shift) switches it while the ends are placed; the option is saved with the preferences. Until the +third point is placed, the tool shows the arc as a dashed outline, its center as a small cross, the direction line in +direction mode and, with Measurement Labels on, the radius. Where no arc fits, the tool shows "Arc too large" by the +pointer (nothing while the pointer is on an end), and a click there draws nothing and keeps the ends. Escape, and an +edit, Undo or Redo made outside the tool, remove the ends. + +```json +{"name":"run_command","arguments":{"command":"shape.threePointArc","params":{"start":[0,0],"end":[80,0],"through":[40,-40]}}} +``` + While a spiral is being dragged out with the Spiral tool, a `drag` event with `mods.alt` or `mods.cmd` keeps the spiral's inner end at the distance from the center it had on the first modified `drag` event, and the outer end follows the pointer. With `mods.alt` alone, dragging outward adds whole winds of four segments and dragging inward removes @@ -7119,7 +7148,7 @@ snap the pointer as drawing tools do, so dragging a corner onto another object's Every point a drawing tool places snaps the same way, through one snapper (#506): the Pen's and Curvature tool's anchors, the shape tools' start and dragged corner or radius (`rectangle`, `roundedRectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, `arc`, `spiral`, `rectangularGrid`, `polarGrid`), the -Type tool's click and frame, and a new artboard's corners. The Pencil ignores Smart Guides and Snap to Point and +Three-Point Arc tool's ends and third point, the Type tool's click and frame, and a new artboard's corners. The Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides: its strokes and straight lines follow the hand (Snap to Grid and Snap to Pixel still move their ends). The point lands on another object's anchor, centre or path ("anchor", "center", "path"), else lines up with the anchors, edges and centres of the art and the artboards (a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..a8c443bd1a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -687,6 +687,7 @@ since 2026-10-01. - **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. - **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page () describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged. - **Spirals turn as they are dragged, and along General › Constrain Angle:** a spiral dragged out with the Spiral tool turns about its center so that its outer end is at the pointer, so dragging around the center turns it, while Alt, Ctrl/Cmd, ↑/↓, Space and Escape work as before. A spiral placed from the Spiral dialog starts along the x axis turned by a Constrain Angle other than 0° or a whole turn, with its bounding box turned. `shape.spiral` takes an optional `rotation` (degrees clockwise about `cx`, `cy`); a `rotation` that is not a number is an error, and without one spirals are drawn as before. The help page () says that moving the pointer around in a curve during the drag turns the new spiral, and the help page () describes new objects being drawn along the turned axes. Putting the outer end exactly at the pointer, keeping the last direction while the pointer is within 0.01 pt of the center, and leaving a dragged spiral's direction to the pointer with Shift or a Constrain Angle are VectorCraft's own rules (tools `draw2::family::tests::spiral_drag_turns_the_spiral_to_the_pointer`; engine `a_dragged_spiral_turns_its_outer_end_to_the_pointer`, `constrain_angle_turns_a_click_made_spiral`, `spiral_rotation_turns_it_and_must_be_a_number`; UI `spiral_click_dialog_starts_along_the_constrain_angle`). Scores and hours unchanged. +- **Three-Point Arc tool:** a new tool in the Line Segment tool's group, after the Arc tool, draws an open circular arc. A drag or two clicks place its ends (Shift keeps the second end at 45° steps), and a third click places a point the arc passes through. With Third Point Sets Direction on (the tool's Tool Options, or `]` while drawing), the third point gives the direction the arc leaves its first end in, or with Alt the direction at its second end. The tool previews the arc, its center and its radius, shows "Arc too large" where no arc fits, and draws the arc in one undo step with `shape.threePointArc {start, end, through | toward, at?}` (geom `shapes::tests::the_arc_through_a_point_passes_through_it`, `the_arc_leaving_along_a_direction_has_that_tangent`, `degenerate_points_give_no_arc`, `the_path_via_the_third_point_passes_through_it_exactly`; tools `three_point_arc::tests`; engine `tests::three_point_arc`; ui-egui `dialogs::three_point_arc_options::tests`). Scores and hours unchanged. - **Shape commands refuse invalid options:** `shape.arc` refuses a `reference` that is not a whole number from 0 to 8, a `baseAlong` other than `x` or `y` (either case), null included for both, and a `slope` outside −100…100, in both of its forms; before, such a value drew the arc with reference point 0 or 8, the X axis or the nearest slope. `shape.rectangularGrid` and `shape.polarGrid` refuse a divider count that is not a whole number of at least 0; before, such a count was 5. Each error names the key, and nothing is drawn. Left-out values keep their defaults. These ranges are VectorCraft's own command rules (engine `draw2::shape_arc_rejects_an_invalid_reference_base_along_or_slope`, `draw2::shape_arc_takes_every_reference_point_and_either_base_axis`, `draw2::grid_divider_counts_reject_fractions_and_negatives`). Scores and hours unchanged. - **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4182189c4a..d587d64527 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -320,6 +320,7 @@ tools, never checked side by side) isn't captured row by row. | Sliders in dialogs and popups (Save for Web, raster export options, Preferences, the opacity popup) show their rail, filled up to the handle | done | #1483 | | Rectangular Grid and Polar Grid click dialogs: size, divider counts with a skew slider each, Use Outside Rectangle As Frame / Create Compound Path From Ellipses, Fill Grid; kept as the tool's options, used by drags too | done | #1377. The options are the documented ones; how far a skew percentage moves the dividers and which way the radial skew turns are our own choice (the public documentation gives neither). The reference point locator is in the dialog, and a double-click on the tool opens it as the tool's Tool Options (next row) | | Double-click the Line Segment, Arc, Rectangular Grid or Polar Grid tool: its Tool Options ([Rectangular Grid tool](https://helpx.adobe.com/illustrator/using/tool-techniques/rectangular-grid-tool.html) and [Arc tool](https://helpx.adobe.com/illustrator/using/tool-techniques/arc-tool.html) step 3, [Tools](https://helpx.adobe.com/illustrator/using/tools.html)) | done | #2691. The tool's click dialog without a place to draw: Line Segment's Length, Angle and Fill Line; Arc's lengths, Reference Point, Type, Base Along, Slope and Fill Arc; the grids' Reference Point, Default Size, dividers, skews and switches. OK draws nothing and sets what the next drag draws with (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and what a click's dialog opens at (with the Length, Angle and Default Size); Cancel changes nothing (`double_clicking_the_line_arc_and_grid_tools_opens_their_tool_options`) | +| Three-Point Arc tool (VectorCraft addition), after the Arc tool: two ends, then a third point the open arc passes through or, with Third Point Sets Direction (its Tool Options, or `]` while drawing), the direction it leaves an end in; a preview with the center and radius; one undo step | done | `shape.threePointArc` (`crates/engine/src/cmd/create.rs`), the tool in `crates/tools/src/three_point_arc.rs`, the geometry in `crates/geom/src/shapes.rs` (`CircularArc`), and their tests; a VectorCraft addition, so it is not scored | ## Modifier keys and temporary tools From aa2983906938031625eaec83a855b6a826b30a50 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:31:13 -0800 Subject: [PATCH 05/16] Tools: the Three-Point Arc tool places a point with the keys held at release A release at the position of the last pointer event kept the point that the earlier keys had constrained. Pressing the third point with Shift and letting go with Shift and Alt drew the direction from the second end but kept the 45-degree step taken from the first. The release now places the point again when Shift or Alt changed, for both ends and the third point. A change of keys alone does not make the first press a drag, so a click that snaps to an anchor and is let go with Shift changed places only the first end. --- crates/tools/src/three_point_arc.rs | 20 ++++++----- crates/tools/src/three_point_arc/tests.rs | 41 +++++++++++++++++++++++ 2 files changed, 53 insertions(+), 8 deletions(-) diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs index 67ce63e03f..c25a3dca05 100644 --- a/crates/tools/src/three_point_arc.rs +++ b/crates/tools/src/three_point_arc.rs @@ -58,8 +58,8 @@ pub struct ThreePointArcTool { pointer: Option, /// Alt was held at the last pointer event: in direction mode, the direction is at the second end. at_end: bool, - /// Where the pressed pointer was at its last event, before snapping. - raw: Option, + /// Where the pressed pointer was at its last event, before snapping, and the keys held then. + raw: Option<(Point, Mods)>, } /// The arc from `start` to `end` shaped by `third`, as `shape.threePointArc` draws it: through @@ -106,12 +106,14 @@ impl ThreePointArcTool { } } - /// The pressed pointer moved to `ev`: the point being placed follows it. + /// The pressed pointer moved to `ev`, or Shift or Alt changed: the point being placed follows + /// it. A change of keys alone does not make the press a drag. fn follow(&mut self, cx: &ToolContext, ev: &PointerEvent) { - self.raw = Some(ev.pos); + let moved = self.raw.is_none_or(|(p, _)| p != ev.pos); + self.raw = Some((ev.pos, ev.mods)); match &mut self.press { Some(Press::Start { at, dragged }) => { - *dragged |= ev.pos.distance(*at) >= cx.tol(DRAG_PX); + *dragged |= moved && ev.pos.distance(*at) >= cx.tol(DRAG_PX); let leave = Leave::segment(cx, *at, ev.mods.shift); self.pointer = Some(self.snap.drag(cx, ev.pos, Some(&leave))); } @@ -149,7 +151,7 @@ impl Tool for ThreePointArcTool { vec![] } PointerKind::Down => { - self.raw = Some(ev.pos); + self.raw = Some((ev.pos, ev.mods)); let leave = self.leave(cx, ev.mods); match (self.start, self.end) { (None, _) => { @@ -180,8 +182,10 @@ impl Tool for ThreePointArcTool { vec![] } PointerKind::Up => { - // A release away from the last drag event places the point where it is let go. - if self.press.is_some() && self.raw != Some(ev.pos) { + // A release away from the last drag event places the point where it is let go, and + // a release with Shift or Alt changed places it as those keys keep it. + let same = self.raw.is_some_and(|(p, m)| p == ev.pos && (m.shift, m.alt) == (ev.mods.shift, ev.mods.alt)); + if self.press.is_some() && !same { self.follow(cx, ev); } match (self.press.take(), self.start, self.pointer) { diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs index 88e63dc1b4..d7c35ddc8b 100644 --- a/crates/tools/src/three_point_arc/tests.rs +++ b/crates/tools/src/three_point_arc/tests.rs @@ -209,6 +209,47 @@ fn a_point_is_placed_where_the_press_is_let_go() { assert_eq!(t.end, Some(Point::new(380.0, 300.0))); } +/// A release with Shift or Alt changed since the press places the point as the keys at the +/// release keep it, even where the pointer did not move. +#[test] +fn a_release_places_the_point_with_the_keys_held_then() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let (none, shift) = (Mods::default(), Mods { shift: true, ..Mods::default() }); + // The second end: pressed without Shift, let go with it. + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 306.0), none)); + t.pointer(&cx, &ev(PointerKind::Up, (380.0, 306.0), shift)); + assert_eq!(t.end.map(|e| e.y), Some(300.0), "{:?}", t.end); + // The third point in direction mode: pressed with Shift, let go with Shift and Alt, so the + // direction line keeps to 45° steps from the second end. + t.set_option("direction", &json!(true)); + let both = Mods { alt: true, ..shift }; + t.pointer(&cx, &ev(PointerKind::Down, (303.0, 250.0), shift)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, (303.0, 250.0), both)); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + let at = |key: &str, i: usize| params[key][i].as_f64().unwrap_or(f64::NAN); + let (dx, dy) = (at("toward", 0) - at("end", 0), at("toward", 1) - at("end", 1)); + assert!(params["at"] == "end" && (dx.abs() - dy.abs()).abs() < 1e-9, "{params}"); +} + +/// A first click that snaps to the rectangle's corner, 3 pt from the pointer, and is let go with +/// Shift changed places only the first end: a change of keys alone is not a drag. +#[test] +fn a_click_let_go_with_shift_changed_is_not_a_drag() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let g = Point::new(200.0, 200.0); + let off = (203.0, 201.0); + let mut t = ThreePointArcTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, off, Mods::default())); + t.pointer(&cx, &ev(PointerKind::Up, off, Mods { shift: true, ..Mods::default() })); + assert_eq!((t.start, t.end), (Some(g), None)); +} + /// Shift keeps the second end at 45° steps from the first. #[test] fn shift_keeps_the_second_end_at_45_degree_steps() { From 38021e7d3c337d2746f8949d62fd6f3edc242aa1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 16:31:03 -0800 Subject: [PATCH 06/16] Rerun CI From 33af033ab0e044d8eb7a95807b079dcbffd5fedd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 14:58:18 -0800 Subject: [PATCH 07/16] Rerun CI From 1ea9a2775adbed14b8e58a7d4d6167d78dcca533 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:01:23 -0800 Subject: [PATCH 08/16] Three-Point Arc: save the direction option, fix two placement cases - `tool.setOption` (and the Tool Options dialog) now accepts `direction` as true or false and refuses other values or unknown options. - The first press counts as a drag when the pointer moves 2 pt from where it was pressed, not from the point it snapped to. - `]` pressed while the third point is held down places that point as the new mode keeps it. --- crates/engine/src/tests/three_point_arc.rs | 20 ++++++++++++ crates/tools/src/three_point_arc.rs | 31 +++++++++++++----- crates/tools/src/three_point_arc/tests.rs | 38 ++++++++++++++++++++++ 3 files changed, 81 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/tests/three_point_arc.rs b/crates/engine/src/tests/three_point_arc.rs index 8a7a349220..ebd755dda7 100644 --- a/crates/engine/src/tests/three_point_arc.rs +++ b/crates/engine/src/tests/three_point_arc.rs @@ -198,3 +198,23 @@ fn three_clicks_with_the_tool_draw_the_arc() { let id = *s.doc().unwrap().selection.objects.first().unwrap(); assert!(farthest_from_path(&s, id, &[Point::new(140.0, 260.0)]) < 1e-9); } + +/// `tool.setOption` (the Tool Options dialog's Save) sets the tool's `direction` option, and +/// refuses a value that is not true or false, or an option the tool doesn't have. +#[test] +fn set_option_sets_the_direction_and_refuses_bad_values() { + let mut s = session(); + for on in [true, false] { + let set = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "values": {"direction": on}})).unwrap(); + assert_eq!(set["direction"], json!(on)); + assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(on)); + } + let cases = [ + (json!({"tool": "threePointArc", "key": "direction", "value": "yes"}), "tool `threePointArc`: `direction` must be true or false"), + (json!({"tool": "threePointArc", "key": "bogus", "value": true}), "tool `threePointArc`: unknown option `bogus`"), + ]; + for (p, want) in cases { + assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}"); + } + assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(false)); +} diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs index c25a3dca05..2732836dc1 100644 --- a/crates/tools/src/three_point_arc.rs +++ b/crates/tools/src/three_point_arc.rs @@ -38,8 +38,9 @@ pub const TOO_LARGE: &str = "Arc too large"; /// The press in progress. #[derive(Clone, Copy, Debug, PartialEq)] enum Press { - /// The first end, pressed at `at`: a release after a drag places the second end there. - Start { at: Point, dragged: bool }, + /// The first end, placed at `at` by a press at `from` (before snapping): a release after a + /// drag places the second end there. The drag is measured from `from`. + Start { at: Point, from: Point, dragged: bool }, /// The second end, pressed after a click placed the first: the release places it. End, /// The third point, pressed once both ends are placed: the release draws the arc. @@ -112,8 +113,8 @@ impl ThreePointArcTool { let moved = self.raw.is_none_or(|(p, _)| p != ev.pos); self.raw = Some((ev.pos, ev.mods)); match &mut self.press { - Some(Press::Start { at, dragged }) => { - *dragged |= moved && ev.pos.distance(*at) >= cx.tol(DRAG_PX); + Some(Press::Start { at, from, dragged }) => { + *dragged |= moved && ev.pos.distance(*from) >= cx.tol(DRAG_PX); let leave = Leave::segment(cx, *at, ev.mods.shift); self.pointer = Some(self.snap.drag(cx, ev.pos, Some(&leave))); } @@ -157,7 +158,7 @@ impl Tool for ThreePointArcTool { (None, _) => { let at = self.snap.press(cx, ev.pos, &[], None); self.start = Some(at); - self.press = Some(Press::Start { at, dragged: false }); + self.press = Some(Press::Start { at, from: ev.pos, dragged: false }); self.pointer = Some(at); } (Some(a), None) => { @@ -189,7 +190,7 @@ impl Tool for ThreePointArcTool { self.follow(cx, ev); } match (self.press.take(), self.start, self.pointer) { - (Some(Press::Start { at, dragged: true }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.end = Some(b), + (Some(Press::Start { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.end = Some(b), (Some(Press::End), Some(a), Some(b)) if b.distance(a) > cx.tol(REACH_PX) => self.end = Some(b), (Some(Press::Third), Some(a), Some(c)) => { let Some(b) = self.end else { return vec![] }; @@ -212,10 +213,16 @@ impl Tool for ThreePointArcTool { } } - fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { match key { ToolKey::Escape => self.clear(), - ToolKey::BracketRight if self.start.is_some() => self.direction = !self.direction, + ToolKey::BracketRight if self.start.is_some() => { + self.direction = !self.direction; + // A press in progress: the point being placed keeps to the new mode. + if let (Some(_), Some((p, mods))) = (self.press, self.raw) { + self.follow(cx, &PointerEvent::new(PointerKind::Drag, p.x, p.y).with_mods(mods)); + } + } _ => {} } vec![] @@ -305,6 +312,14 @@ impl Tool for ThreePointArcTool { self.direction = on; } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "direction" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs index d7c35ddc8b..2481de1bff 100644 --- a/crates/tools/src/three_point_arc/tests.rs +++ b/crates/tools/src/three_point_arc/tests.rs @@ -188,6 +188,44 @@ fn the_direction_option_takes_a_bool() { assert_eq!(t.options(), json!({ "direction": false })); } +/// `]` pressed while the third point is held down places the point as the new mode keeps it: the +/// point Shift kept on the direction line goes back to where the pointer is, and the other way. +#[test] +fn bracket_during_a_press_places_the_third_point_in_the_new_mode() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let shift = Mods { shift: true, ..Mods::default() }; + t.set_option("direction", &json!(true)); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + t.pointer(&cx, &ev(PointerKind::Down, (303.0, 250.0), shift)); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (303.0, 250.0), shift)), through((300.0, 300.0), (380.0, 300.0), (303.0, 250.0))); + // Through mode first, switched to direction mode during the press: Shift keeps the line upright. + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + t.pointer(&cx, &ev(PointerKind::Down, (303.0, 250.0), shift)); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + let acts = t.pointer(&cx, &ev(PointerKind::Up, (303.0, 250.0), shift)); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9) && params["at"] == "start", "{params}"); +} + +/// With Snap to Point, a first press that snaps to the rectangle's corner, 1.5 pt from the +/// pointer, and moves 1.9 pt before it is let go is a click: the drag is measured from the press, +/// not from the corner, so only the first end is placed. +#[test] +fn a_short_move_from_a_snapped_press_is_not_a_drag() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, snap_to_point: true, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, (201.5, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (203.4, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Up, (203.4, 200.0), Mods::default())); + assert_eq!((t.start, t.end), (Some(Point::new(200.0, 200.0)), None)); +} + /// A release away from the last drag event places the point where the pointer is let go, for /// the second end and for the third point. #[test] From bd54c2a63bcafd15c03fa4c0d4dbb13d5250fe64 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:37:07 -0800 Subject: [PATCH 09/16] Three-Point Arc: measure the arc's curve, not its handles, against the canvas An arc near the canvas edge whose handles reach past it while the curve stays inside showed "Arc too large", though shape.threePointArc draws it. The tool now measures the curve's bounds, as the document's range check does for such a path. --- crates/tools/src/three_point_arc.rs | 5 ++++- crates/tools/src/three_point_arc/tests.rs | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs index 2732836dc1..4145c549e7 100644 --- a/crates/tools/src/three_point_arc.rs +++ b/crates/tools/src/three_point_arc.rs @@ -73,7 +73,10 @@ pub fn arc_of(start: Point, end: Point, third: Point, direction: bool, at_end: b (true, false) => CircularArc::leaving(start, third - start, end).map(|arc| (arc, arc.to_path())), (true, true) => CircularArc::arriving(start, end, end - third).map(|arc| (arc, arc.to_path())), }?; - let on_canvas = path.anchors().all(|(_, _, a)| [a.p, a.h_in, a.h_out].iter().all(|q| q.x.abs() <= MAX_COORD && q.y.abs() <= MAX_COORD)); + // The curve is measured, not its handles, which can reach past the canvas while the curve stays + // inside, as the document's own range check measures a path. + let inside = |x: f64, y: f64| x.abs() <= MAX_COORD && y.abs() <= MAX_COORD; + let on_canvas = path.bounds().is_some_and(|r| inside(r.x0, r.y0) && inside(r.x1, r.y1)); on_canvas.then_some((arc, path)) } diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs index 2481de1bff..70f1f51e69 100644 --- a/crates/tools/src/three_point_arc/tests.rs +++ b/crates/tools/src/three_point_arc/tests.rs @@ -115,6 +115,25 @@ fn a_third_point_in_line_with_the_ends_draws_nothing() { assert_eq!(click(&mut t, &cx, (340.0, 340.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 340.0))); } +/// An arc near the canvas edge fits while its curve stays inside, even where a handle reaches past +/// the edge, and gives no arc once the curve reaches past it. +#[test] +fn an_arc_near_the_canvas_edge_is_measured_by_its_curve() { + // A 60° arc of radius 1000 whose rightmost point is `edge`: the handles at its ends reach about + // 45 pt further right. + let arc = |edge: f64| { + let (r, c) = (1000.0, edge - 1000.0); + let (dx, dy) = (r * 30f64.to_radians().cos(), r * 30f64.to_radians().sin()); + let start = Point::new(c + dx, -dy); + let end = Point::new(c + dx, dy); + arc_of(start, end, start + Vec2::new(0.5, 3f64.sqrt() / 2.0) * 100.0, true, false) + }; + let Some((_, path)) = arc(MAX_COORD - 1.0) else { panic!("an arc inside the canvas fits") }; + assert!(path.control_bounds().is_some_and(|r| r.x1 > MAX_COORD), "a handle reaches past the edge"); + assert!(path.bounds().is_some_and(|r| r.x1 <= MAX_COORD && (r.x1 - (MAX_COORD - 1.0)).abs() < 1e-6)); + assert!(arc(MAX_COORD + 1.0).is_none(), "an arc reaching past the canvas does not fit"); +} + /// In direction mode, Shift keeps the direction line at 45° steps from the end it starts at. #[test] fn shift_keeps_the_direction_at_45_degree_steps() { From aec24ad610eb2b5ef241dddafe0f29a5aaa426f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:36:02 -0800 Subject: [PATCH 10/16] Swatches: Add Used Colors ends typing first and keeps other Global Edit members' colors swatch.addUsedColors ends a typing session in progress before it reads the colors, so typing is its own undo step and its colors are counted, also when the run finds no new color. With Global Edit on, linking the selected art to its new swatches no longer gives that paint to the other members, so a member with another color keeps it. The menu test also checks that Add Selected Colors is disabled with nothing selected. --- crates/engine/src/cmd/swatch.rs | 13 +++++-- crates/engine/src/tests/swatchcmds.rs | 42 +++++++++++++++++++++ crates/ui-egui/src/panels/swatches/tests.rs | 11 ++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 5 files changed, 65 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 28885a1123..8a8a2cfccf 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -75,7 +75,7 @@ pub fn specs() -> Vec { "Add Used Colors", ["Window", "Swatches"], None, - "{selection?: false (only the selected art's colours; default: all the art's), global?: false (the new swatches are global and the matching unlinked colours in that art link to them)} add a swatch for each colour used (fills, strokes, text, gradient stops, mesh points) that no solid swatch has yet, as one undo step (none when there is no new color; the Swatches panel menu's Add Selected Colors sends selection and global) → {added: [names], linked}", + "{selection?: false (only the selected art's colours; default: all the art's), global?: false (the new swatches are global and the matching unlinked colours in that art link to them)} add a swatch for each colour used (fills, strokes, text, gradient stops, mesh points) that no solid swatch has yet, as one undo step (none when there is no new color; the Swatches panel menu's Add Selected Colors sends selection and global; with Global Edit on, the other members keep their colors) → {added: [names], linked}", has_doc, swatch_add_used ), @@ -1048,12 +1048,17 @@ fn swatch_add_used(s: &mut Session, p: &Value) -> Result { } Ok(ids) }; + // Typing in progress is its own undo step and is in the document the colors are read from. + super::variablecmds::settle_typing(s)?; // With no new color there is nothing to add or link, so no edit and no undo step. let st = s.doc()?; if new_used_colors(&st.doc, &used_ids(&st.doc, &st.selection)?).is_empty() { return Ok(json!({"added": [], "linked": 0})); } - let (added, linked) = s.edit("Add Used Colors", |d, sel| { + // Linking a paint to its new swatch keeps its color, so Global Edit gives the link to no other + // member: a member whose color differs keeps it. + let global_edit = s.doc_mut()?.global_edit.take(); + let edited = s.edit("Add Used Colors", |d, sel| { let ids = used_ids(&*d, &*sel)?; let colors = new_used_colors(d, &ids); let mut free = d.free_swatch_names(); @@ -1065,7 +1070,9 @@ fn swatch_add_used(s: &mut Session, p: &Value) -> Result { } let linked = if global { link_colors(d, &ids, &links) } else { 0 }; Ok((links.into_iter().map(|(_, n)| n).collect::>(), linked)) - })?; + }); + s.doc_mut()?.global_edit = global_edit; + let (added, linked) = edited?; Ok(json!({"added": added, "linked": linked})) } diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index 0ac3ee7ed0..f043ae08ae 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -146,6 +146,48 @@ fn add_used_colors_with_no_new_color_records_no_undo_step() { assert_eq!(undo_len(&s), undo); } +/// A run that finds no new color, while the Type tool is typing, still ends the typing session: the +/// typing is its own undo step. +#[test] +fn add_used_colors_with_no_new_color_ends_the_typing() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let v = ViewInfo::default(); + let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 10, "text": "Hello"}))["id"].as_u64().unwrap()); + run(&mut s, "swatch.addUsedColors", json!({})); + s.select_tool("type", v).unwrap(); + let b = doc(&s).bounds_of(&[t], false).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, b.x1 - 1.0, b.center().y), v).unwrap(); + } + s.tool_text("!", v).unwrap(); + assert!(crate::cmd::typing_in_progress(&s)); + let steps = undo_len(&s); + assert_eq!(run(&mut s, "swatch.addUsedColors", json!({})), json!({"added": [], "linked": 0})); + assert!(!crate::cmd::typing_in_progress(&s)); + let labels: Vec = s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect(); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Typing"))); +} + +/// Add Selected Colors while Global Edit is on links only the selected art: a member of the same +/// shape with another color keeps its color and stays unlinked, and Global Edit stays on. +#[test] +fn add_selected_colors_in_global_edit_keeps_the_other_members_colors() { + let mut s = session(); + let a = rect_filled(&mut s, json!({"color": "#123456"})); + let b = rect_filled(&mut s, json!({"color": "#654321"})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let r = run(&mut s, "select.globalEdit", json!({})); + assert_eq!((r["active"].clone(), r["ids"].clone()), (json!(true), json!([a.0, b.0])), "the other rectangle is a member"); + let other = fill(&s, b); + let undo = undo_len(&s); + run(&mut s, "swatch.addUsedColors", json!({"selection": true, "global": true})); + assert!(matches!(fill(&s, a), Paint::Solid { swatch: Some(_), .. }), "{:?}", fill(&s, a)); + assert_eq!(fill(&s, b), other, "the unselected member keeps its color"); + assert_eq!(undo_len(&s), undo + 1); + assert!(s.doc().unwrap().global_edit.is_some(), "Global Edit stays on"); +} + /// Give `id` the fill `p` exactly as written (a command would round or convert some colors). fn set_fill(s: &mut Session, id: NodeId, p: Paint) { std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.set_fill(p); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index d173e6b2a7..61756f633e 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -1421,6 +1421,15 @@ fn click_menu_item(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { menu_frame(app, ctx, vec![button(false)]); } +/// Whether the panel menu's item `label` is enabled, as the accessibility tree reports it. +fn menu_item_enabled(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) -> bool { + ctx.enable_accesskit(); + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(236.0, 700.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| menu(app, ui)); + out.textures_delta.clear(); + footer_button(&out, label).1 +} + /// The panel menu's Show Recent Colors hides and shows the panel's Recent Colors row (#6617): /// checked by default, applied colors still join the list while the row is hidden, and the Color /// panel keeps its own row and setting. @@ -1583,10 +1592,12 @@ fn add_selected_colors_adds_the_selection_colors_as_global_swatches() { let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); app.run("select.set", json!({"ids": []})).unwrap(); let (before, steps) = (app.session.active().unwrap().doc.clone(), undo(&app)); + assert!(!menu_item_enabled(&mut app, &ctx, "Add Selected Colors"), "off with nothing selected"); click_menu_item(&mut app, &ctx, "Add Selected Colors"); assert_eq!(app.session.active().unwrap().doc, before, "off with nothing selected"); assert_eq!(undo(&app), steps); app.run("select.set", json!({"ids": [picked]})).unwrap(); + assert!(menu_item_enabled(&mut app, &ctx, "Add Selected Colors"), "on with art selected"); let (before, steps) = (app.session.active().unwrap().doc.clone(), undo(&app)); click_menu_item(&mut app, &ctx, "Add Selected Colors"); let doc = &app.session.active().unwrap().doc; diff --git a/docs/mcp.md b/docs/mcp.md index 616fa82447..0f09dba6cd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1100,7 +1100,7 @@ them in the Swatches panel does); give colour group names instead to reorder the in the app runs `paint.setFill` (or `paint.setStroke`, the active proxy) with `ids: [the object under the pointer]`. The Swatches panel menu's commands: `swatch.addUsedColors {selection?, global?}` (Add Used Colors sends `{}`; Add Selected Colors, on while art is selected, sends `{selection: true, global: true}`; a run with no new color records no -undo step), `swatch.unused` (a query: the +undo step; with Global Edit on, the other members keep their colors), `swatch.unused` (a query: the names Select All Unused selects; a spot swatch counts as used while an image placed from a DCS file has a plate of its ink), `swatch.merge {names}` (the first is kept; gradient stops linked to the others drop their process plates), `swatch.ungroup {name}` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 07b25adf60..28fee7e34b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1862,7 +1862,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, seven gradient libraries (among them Organic Fades, soft perceptually mixed multi-stop fades that thin out to transparent, and Holographic, seven opaque linear foils of narrow pastel and pearl bands and seven radial glows that fade out to a clear edge) and three pattern libraries (Geometric Patterns; Grit Textures with eight seamless grain, speckle, stipple, scratch and fleck tiles; and Optical Effects with eight of VectorCraft's own seamless wave, ring, warped-check, stripe, chevron and lens tiles; their swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. Right-clicking a swatch in either list or thumbnail view selects it without applying paint and offers Swatch Options…, Duplicate Swatch and Delete Swatch for that item. None, [Registration] and missing swatches disable these actions. Existing active-item multiselection is retained; actions still target only the clicked item. Evidence: `panels::swatches::tests::context_menu` harness tests cover all five views, selection, dialog dispatch, duplicate/delete and Undo. All 39 Swatches tests pass; the regression fails with the menu hooks removed. Rendered headless list and thumbnail menus were inspected, and a fresh local deep CodeRabbit review reported zero findings. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. Validation on 2026-11-15: native Windows formatting, workspace Clippy and all 39 focused Swatches tests passed. Windows full CI stopped at unchanged engine tests `tests::package::a_confined_package_names_files_outside_the_read_root_by_name` (slash-sensitive report assertion) and `tests::plugins::plugin_storage_behind_a_link_is_left_alone` (storage-link setup returned AlreadyExists). Both cases pass in the Linux/WSL full CI run, which passed all 13 gates. No engine or CI workflow changes are included. - The Swatches panel menu has Add Selected Colors, on while art is selected: it adds a swatch for each color of the selected art that the panel does not hold yet, as global swatches the art's matching paints link to, in one undo step ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/use-swatches/add-colors-to-swatches.html) describes the panel menu command that adds the selected artwork's colors). The swatch names and the colors it reads (fills, strokes, text, gradient stops, mesh points) are VectorCraft's own, as for Add Used Colors. Add Used Colors and Add Selected Colors record no undo step when there is no new color. Evidence: `add_selected_colors_adds_the_selection_colors_as_global_swatches` in `crates/ui-egui/src/panels/swatches/tests.rs`; `add_used_colors_with_no_new_color_records_no_undo_step` in `crates/engine/src/tests/swatchcmds.rs`. + The Swatches panel menu has Add Selected Colors, on while art is selected: it adds a swatch for each color of the selected art that the panel does not hold yet, as global swatches the art's matching paints link to, in one undo step ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/use-swatches/add-colors-to-swatches.html) describes the panel menu command that adds the selected artwork's colors). The swatch names and the colors it reads (fills, strokes, text, gradient stops, mesh points) are VectorCraft's own, as for Add Used Colors. Add Used Colors and Add Selected Colors record no undo step when there is no new color, and still end typing in progress as its own step. With Global Edit on, the members the command does not read keep their colors. Evidence: `add_selected_colors_adds_the_selection_colors_as_global_swatches` in `crates/ui-egui/src/panels/swatches/tests.rs`; `add_used_colors_with_no_new_color_records_no_undo_step`, `add_used_colors_with_no_new_color_ends_the_typing` and `add_selected_colors_in_global_edit_keeps_the_other_members_colors` in `crates/engine/src/tests/swatchcmds.rs`. The panel's Delete Swatch and Swatch Options (footer buttons and panel menu), New Color Group and Save Swatch Library treat only None and [Registration] as reserved, so a user swatch or color group whose name starts with `[` can be deleted, edited, grouped and saved; selected names the document no longer holds are left out (`panels::swatches::tests::bracketed_user_swatches_and_groups_can_be_deleted_and_edited`). Dragging swatches onto Delete Swatch deletes them ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=136), Replace, merge, or delete swatches section, lists this drag as one of the ways to delete the selected swatches): a swatch or color group dragged from the Swatches panel, in any view, and released on the Delete Swatch button is deleted through `swatch.delete`, even while nothing was selected and the button is disabled for clicks. A swatch that is part of the selection carries the other selected swatches of its kind with it. VectorCraft's own rules: the drop asks first as a plain click does, and Alt does not skip the question; Cancel keeps everything, and OK deletes them in one undo step; None and [Registration] are never taken; the button is enabled while swatches are selected or while a swatch or group of the active document is being dragged, and it is outlined only while such a swatch or group is held over it, so a paint from another panel, art and a swatch dragged from another document delete nothing. Tests: `panels::swatches::tests::swatches_dropped_on_delete_swatch_are_deleted_after_asking`, `delete_swatch_ignores_other_drags`. Dragging swatches onto New Swatch duplicates them ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/use-swatches/duplicate-swatches.html) gives this drag as another way to duplicate the selected swatches): a swatch dragged from the Swatches panel, in any view, and released on the New Swatch button is copied through `swatch.duplicate` without opening the New Swatch dialog. A swatch that is part of the selection carries the other selected swatches with it. VectorCraft's own rules: each copy goes just after its swatch and in its color group, named ` copy` and then ` copy 2`; the copies of one drop are one undo step and are selected; modifiers held on release do not change the drop; color groups, None and [Registration] are not duplicated; the button is outlined only while such a swatch of the active document is held over it, so a paint from another panel, art, a swatch dragged from another document and a swatch deleted during the drag duplicate nothing. Tests: `panels::swatches::tests::swatches_dropped_on_new_swatch_are_duplicated`, `new_swatch_ignores_other_drags`. From 3d5a6c3c01f46e3f4dd2f2a27a056e5432206932 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:47:52 -0800 Subject: [PATCH 11/16] Three-Point Arc: `]` while hovering moves the shown third point to the new mode With both ends placed and Shift held, switching modes with `]` left the point the tool showed where the old mode put it until the pointer moved, while a click there drew the arc of the new mode. --- crates/tools/src/three_point_arc.rs | 14 +++++++--- crates/tools/src/three_point_arc/tests.rs | 31 +++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs index 4145c549e7..60314cbe1f 100644 --- a/crates/tools/src/three_point_arc.rs +++ b/crates/tools/src/three_point_arc.rs @@ -59,7 +59,8 @@ pub struct ThreePointArcTool { pointer: Option, /// Alt was held at the last pointer event: in direction mode, the direction is at the second end. at_end: bool, - /// Where the pressed pointer was at its last event, before snapping, and the keys held then. + /// Where the pointer was at its last event, pressed or hovering, before snapping, and the keys + /// held then. raw: Option<(Point, Mods)>, } @@ -150,6 +151,7 @@ impl Tool for ThreePointArcTool { } match ev.kind { PointerKind::Move => { + self.raw = Some((ev.pos, ev.mods)); let leave = self.leave(cx, ev.mods); self.pointer = Some(self.snap.hover(cx, ev.pos, &[], leave.as_ref())); vec![] @@ -222,8 +224,14 @@ impl Tool for ThreePointArcTool { ToolKey::BracketRight if self.start.is_some() => { self.direction = !self.direction; // A press in progress: the point being placed keeps to the new mode. - if let (Some(_), Some((p, mods))) = (self.press, self.raw) { - self.follow(cx, &PointerEvent::new(PointerKind::Drag, p.x, p.y).with_mods(mods)); + // A hovering pointer: the third point it shows keeps to the new mode too. + match (self.press, self.raw) { + (Some(_), Some((p, mods))) => self.follow(cx, &PointerEvent::new(PointerKind::Drag, p.x, p.y).with_mods(mods)), + (None, Some((p, mods))) if self.end.is_some() && self.pointer.is_some() => { + let leave = self.leave(cx, mods); + self.pointer = Some(self.snap.hover(cx, p, &[], leave.as_ref())); + } + _ => {} } } _ => {} diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs index 70f1f51e69..eaf269e974 100644 --- a/crates/tools/src/three_point_arc/tests.rs +++ b/crates/tools/src/three_point_arc/tests.rs @@ -230,6 +230,37 @@ fn bracket_during_a_press_places_the_third_point_in_the_new_mode() { assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9) && params["at"] == "start", "{params}"); } +/// `]` pressed while the pointer hovers moves the third point the tool shows to where the new mode +/// keeps it, so the arc shown is the arc a click there draws. +#[test] +fn bracket_while_hovering_shows_the_third_point_in_the_new_mode() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let shift = Mods { shift: true, ..Mods::default() }; + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + hover(&mut t, &cx, (303.0, 250.0), shift); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + // The direction line from the first end: Shift keeps it upright. + let start = Point::new(300.0, 300.0); + let line = t.overlays(&cx).into_iter().find_map(|o| match o { + Overlay::Line { a, b, dashed: false, .. } if a == start => Some(b), + _ => None, + }); + assert!(line.is_some_and(|b| (b.x - 300.0).abs() < 1e-9), "{line:?}"); + let acts = click_with(&mut t, &cx, (303.0, 250.0), shift); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9), "{params}"); + // Back to through mode while hovering: the point goes back to the pointer. + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + hover(&mut t, &cx, (303.0, 250.0), shift); + assert!(t.pointer.is_some_and(|q| (q.x - 300.0).abs() < 1e-9), "{:?}", t.pointer); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.pointer, Some(Point::new(303.0, 250.0))); + assert_eq!(click_with(&mut t, &cx, (303.0, 250.0), shift), through((300.0, 300.0), (380.0, 300.0), (303.0, 250.0))); +} + /// With Snap to Point, a first press that snaps to the rectangle's corner, 1.5 pt from the /// pointer, and moves 1.9 pt before it is let go is a click: the drag is measured from the press, /// not from the corner, so only the first end is placed. From c5863cd11ab20f48f012d92c0d4b67afd46aa73a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 17:25:09 -0800 Subject: [PATCH 12/16] Docs: radius preview of the Three-Point Arc tool needs Measurement Labels The tool shows the radius by the pointer only with Measurement Labels on. The progress lines in docs/target-app-parity.md, docs/ui-parity.md and ROADMAP.md now say so. --- ROADMAP.md | 2 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index ecc21a96fe..fed8d57326 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -156,7 +156,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. -- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged. +- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b411cc405e..52e802d906 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -716,7 +716,7 @@ since 2026-10-01. - **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. - **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page () describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged. - **Spirals turn as they are dragged, and along General › Constrain Angle:** a spiral dragged out with the Spiral tool turns about its center so that its outer end is at the pointer, so dragging around the center turns it, while Alt, Ctrl/Cmd, ↑/↓, Space and Escape work as before. A spiral placed from the Spiral dialog starts along the x axis turned by a Constrain Angle other than 0° or a whole turn, with its bounding box turned. `shape.spiral` takes an optional `rotation` (degrees clockwise about `cx`, `cy`); a `rotation` that is not a number is an error, and without one spirals are drawn as before. The help page () says that moving the pointer around in a curve during the drag turns the new spiral, and the help page () describes new objects being drawn along the turned axes. Putting the outer end exactly at the pointer, keeping the last direction while the pointer is within 0.01 pt of the center, and leaving a dragged spiral's direction to the pointer with Shift or a Constrain Angle are VectorCraft's own rules (tools `draw2::family::tests::spiral_drag_turns_the_spiral_to_the_pointer`; engine `a_dragged_spiral_turns_its_outer_end_to_the_pointer`, `constrain_angle_turns_a_click_made_spiral`, `spiral_rotation_turns_it_and_must_be_a_number`; UI `spiral_click_dialog_starts_along_the_constrain_angle`). Scores and hours unchanged. -- **Three-Point Arc tool:** a new tool in the Line Segment tool's group, after the Arc tool, draws an open circular arc. A drag or two clicks place its ends (Shift keeps the second end at 45° steps), and a third click places a point the arc passes through. With Third Point Sets Direction on (the tool's Tool Options, or `]` while drawing), the third point gives the direction the arc leaves its first end in, or with Alt the direction at its second end. The tool previews the arc, its center and its radius, shows "Arc too large" where no arc fits, and draws the arc in one undo step with `shape.threePointArc {start, end, through | toward, at?}` (geom `shapes::tests::the_arc_through_a_point_passes_through_it`, `the_arc_leaving_along_a_direction_has_that_tangent`, `degenerate_points_give_no_arc`, `the_path_via_the_third_point_passes_through_it_exactly`; tools `three_point_arc::tests`; engine `tests::three_point_arc`; ui-egui `dialogs::three_point_arc_options::tests`). Scores and hours unchanged. +- **Three-Point Arc tool:** a new tool in the Line Segment tool's group, after the Arc tool, draws an open circular arc. A drag or two clicks place its ends (Shift keeps the second end at 45° steps), and a third click places a point the arc passes through. With Third Point Sets Direction on (the tool's Tool Options, or `]` while drawing), the third point gives the direction the arc leaves its first end in, or with Alt the direction at its second end. The tool previews the arc and its center, and with Measurement Labels on its radius, shows "Arc too large" where no arc fits, and draws the arc in one undo step with `shape.threePointArc {start, end, through | toward, at?}` (geom `shapes::tests::the_arc_through_a_point_passes_through_it`, `the_arc_leaving_along_a_direction_has_that_tangent`, `degenerate_points_give_no_arc`, `the_path_via_the_third_point_passes_through_it_exactly`; tools `three_point_arc::tests`; engine `tests::three_point_arc`; ui-egui `dialogs::three_point_arc_options::tests`). Scores and hours unchanged. - **Shape commands refuse invalid options:** `shape.arc` refuses a `reference` that is not a whole number from 0 to 8, a `baseAlong` other than `x` or `y` (either case), null included for both, and a `slope` outside −100…100, in both of its forms; before, such a value drew the arc with reference point 0 or 8, the X axis or the nearest slope. `shape.rectangularGrid` and `shape.polarGrid` refuse a divider count that is not a whole number of at least 0; before, such a count was 5. Each error names the key, and nothing is drawn. Left-out values keep their defaults. These ranges are VectorCraft's own command rules (engine `draw2::shape_arc_rejects_an_invalid_reference_base_along_or_slope`, `draw2::shape_arc_takes_every_reference_point_and_either_base_axis`, `draw2::grid_divider_counts_reject_fractions_and_negatives`). Scores and hours unchanged. - **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index cddc571578..d74a5f8edb 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -337,7 +337,7 @@ tools, never checked side by side) isn't captured row by row. | Sliders in dialogs and popups (Save for Web, raster export options, Preferences, the opacity popup) show their rail, filled up to the handle | done | #1483 | | Rectangular Grid and Polar Grid click dialogs: size, divider counts with a skew slider each, Use Outside Rectangle As Frame / Create Compound Path From Ellipses, Fill Grid; kept as the tool's options, used by drags too | done | #1377. The options are the documented ones; how far a skew percentage moves the dividers and which way the radial skew turns are our own choice (the public documentation gives neither). The reference point locator is in the dialog, and a double-click on the tool opens it as the tool's Tool Options (next row) | | Double-click the Line Segment, Arc, Rectangular Grid or Polar Grid tool: its Tool Options ([Rectangular Grid tool](https://helpx.adobe.com/illustrator/using/tool-techniques/rectangular-grid-tool.html) and [Arc tool](https://helpx.adobe.com/illustrator/using/tool-techniques/arc-tool.html) step 3, [Tools](https://helpx.adobe.com/illustrator/using/tools.html)) | done | #2691. The tool's click dialog without a place to draw: Line Segment's Length, Angle and Fill Line; Arc's lengths, Reference Point, Type, Base Along, Slope and Fill Arc; the grids' Reference Point, Default Size, dividers, skews and switches. OK draws nothing and sets what the next drag draws with (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and what a click's dialog opens at (with the Length, Angle and Default Size); Cancel changes nothing (`double_clicking_the_line_arc_and_grid_tools_opens_their_tool_options`) | -| Three-Point Arc tool (VectorCraft addition), after the Arc tool: two ends, then a third point the open arc passes through or, with Third Point Sets Direction (its Tool Options, or `]` while drawing), the direction it leaves an end in; a preview with the center and radius; one undo step | done | `shape.threePointArc` (`crates/engine/src/cmd/create.rs`), the tool in `crates/tools/src/three_point_arc.rs`, the geometry in `crates/geom/src/shapes.rs` (`CircularArc`), and their tests; a VectorCraft addition, so it is not scored | +| Three-Point Arc tool (VectorCraft addition), after the Arc tool: two ends, then a third point the open arc passes through or, with Third Point Sets Direction (its Tool Options, or `]` while drawing), the direction it leaves an end in; a preview with the center and, with Measurement Labels on, the radius; one undo step | done | `shape.threePointArc` (`crates/engine/src/cmd/create.rs`), the tool in `crates/tools/src/three_point_arc.rs`, the geometry in `crates/geom/src/shapes.rs` (`CircularArc`), and their tests; a VectorCraft addition, so it is not scored | ## Modifier keys and temporary tools From 6cb7b510762879690c3f1fe4a02af19f944e4df5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 02:30:52 -0800 Subject: [PATCH 13/16] Gradient: an aspect with no object to edit is an error, not a silent no-op paint.editGradient with an aspect returned ok and changed nothing when it edited no object: with the Live Paint Bucket active (its default gradient) or with nothing paintable selected. The default gradient for new art is fitted to each object it paints and keeps no aspect, so the aspect was dropped. - paint.editGradient now refuses an aspect when it edits no object, and leaves the default gradient as it was. Named or selected objects still take the aspect. - The Gradient panel's Aspect Ratio field is dimmed in that case (Session::gradient_edit_has_objects). - Params text and docs/mcp.md say so. --- crates/engine/src/cmd/gradient.rs | 16 ++++++- crates/engine/src/tests/build.rs | 52 +++++++++++++++++++++ crates/ui-egui/src/panels/gradient.rs | 3 +- crates/ui-egui/src/panels/gradient/tests.rs | 31 ++++++++++++ docs/mcp.md | 4 +- 5 files changed, 103 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 53e0f5456f..df75e2f8dd 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected or the Live Paint Bucket's gradient: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)", has_doc, edit_gradient ), @@ -113,6 +113,16 @@ impl StopOwner { } impl Session { + /// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not + /// while the Live Paint Bucket is active or when nothing it can paint is selected: it then edits only the + /// default gradient, which takes no `aspect`. + pub fn gradient_edit_has_objects(&self, stroke: bool) -> bool { + let p = json!({ "stroke": stroke }); + !super::paint::for_bucket(self, &p) + && item_target(self, &p, "paint.editGradient") + .is_ok_and(|item| item.of_kind(self, !stroke).targets(self, &p).is_ok_and(|ids| !ids.is_empty())) + } + /// The selected gradient stop (`gradient.selectStop`), while the gradient it was selected on /// is still the one behind the active proxy. Callers check it against the stop count (an undo /// can remove stops). @@ -543,6 +553,10 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { // Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then // not one for new art. let selected = !ids.is_empty(); + // The default gradient for new art (and the bucket's) is fitted to each object, so it has no aspect of its own. + if !selected && p.get("aspect").is_some() { + return Err(bad(C, "`aspect` needs objects to place the gradient on: give ids or select objects")); + } let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?; // How the gradient lies on a stroke (the panel's Stroke buttons). let mode = match str_param(p, "strokeMode") { diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index fade868bb6..294d14d917 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3331,6 +3331,58 @@ fn live_paint_bucket_paint_and_stroke_commands_leave_the_selection_unpainted() { assert!(failed.is_empty(), "{failed:#?}"); } +/// `paint.editGradient` with an `aspect` and no object to edit (the Live Paint Bucket's gradient, +/// or nothing selected) is an error that leaves the default gradient as it was, since a gradient +/// fitted to each object has no aspect of its own. Named objects still take the aspect. +#[test] +fn edit_gradient_aspect_without_objects_is_an_error() { + let aspect = |n: &Node| match n.appearance.fill_paint() { + Paint::Gradient(g) => g.geom.map(|x| x.aspect), + _ => None, + }; + let mut s = session(); + let g = live(&mut s); + let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0); + s.execute("select.set", &json!({"ids": [g.0, rect.0]})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("gradient.presets.apply", &json!({"name": "vignette"})).unwrap(); + let (group, art, fill) = (node(&s, g), node(&s, rect), s.paint.fill.clone()); + let steps = s.doc().unwrap().history.undo.len(); + assert!(!s.gradient_edit_has_objects(false), "the bucket edits its own gradient"); + for params in [json!({"stroke": false, "aspect": 50}), json!({"stroke": false, "aspect": 50, "reverse": true})] { + assert!(s.execute("paint.editGradient", ¶ms).is_err(), "{params}"); + assert_eq!(s.paint.fill, fill, "{params}: the bucket's gradient stays"); + } + assert_eq!((node(&s, g), node(&s, rect)), (group, art), "the selection keeps its paint"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step"); + // Named objects take it. + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "radial", "aspect": 50, "ids": [rect.0]})).unwrap(); + assert_eq!(aspect(&node(&s, rect)), Some(0.5)); + // Without the bucket and with nothing selected, the default gradient has no aspect either. + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + let fill = s.paint.fill.clone(); + assert!(!s.gradient_edit_has_objects(false)); + assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err()); + assert_eq!(s.paint.fill, fill, "the default gradient stays"); + // An empty group has nothing to paint. + let empty = s + .edit("Group", |d, _| { + let id = d.alloc_id(); + d.insert(d.default_layer(), 0, Node::group(id, vec![]))?; + Ok(id) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [empty.0]})).unwrap(); + assert!(!s.gradient_edit_has_objects(false), "an empty group"); + assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err()); + // A selected object takes it. + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + assert!(s.gradient_edit_has_objects(false) && s.gradient_edit_has_objects(true)); + s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 25})).unwrap(); + assert_eq!(aspect(&node(&s, rect)), Some(0.25)); +} + /// With the Live Paint Bucket active, objects named with `ids` still take a stroke, and a brush /// still goes to the selection. #[test] diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 7baaa062ab..e04c2780c1 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -347,7 +347,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { edit(app, json!({"reverse": true}), Live::Released); } }); - let radial = kind.is_centered() && placed; + // The default gradient (with nothing selected, or the Live Paint Bucket's) fits each object and has no aspect. + let radial = kind.is_centered() && placed && app.session.gradient_edit_has_objects(!app.session.fill_active); ui.horizontal(|ui| { icons::icon(ui, "scaling", 15.0, if radial { t.icon } else { t.text_disabled }).on_hover_text(tl!("Aspect Ratio")); // A mirrored conic's negative aspect shows as its size; an edit keeps the mirror. diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index bbf833b1aa..f91d4fbcf5 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -433,6 +433,37 @@ fn the_aspect_field_keeps_a_mirrored_conic_mirrored() { assert!((geom.aspect + 0.8).abs() < 1e-9 && geom.is_mirrored(), "{geom:?}"); } +/// With nothing selected, and while the Live Paint Bucket is active, the Aspect Ratio field is +/// dimmed: the default gradient fits each object and has no aspect, so typing in it changes +/// nothing and reports no error. +#[test] +fn the_aspect_field_is_dimmed_for_the_default_gradient() { + for bucket in [false, true] { + let mut app = app(json!({"gradient": {"kind": "radial"}})); + if bucket { + app.select_tool("livePaintBucket"); + } else { + app.run("select.set", json!({"ids": []})).unwrap(); + } + let default = app.session.paint.fill.clone(); + let mut p = Panel::new(); + let texts = p.frame(&mut app, vec![], Modifiers::NONE); + // The aspect field is the first 100% (above Opacity's). + let field = texts + .iter() + .filter(|(t, _)| t == "100%") + .map(|(_, at)| *at) + .min_by(|a, b| a.y.total_cmp(&b.y)) + .unwrap_or_else(|| panic!("the aspect field: {texts:?}")); + p.click(&mut app, field); + let key = |k, modifiers| Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }; + p.frame(&mut app, vec![key(egui::Key::A, Modifiers::COMMAND), Event::Text("80".into())], Modifiers::NONE); + p.frame(&mut app, vec![key(egui::Key::Enter, Modifiers::NONE)], Modifiers::NONE); + assert_eq!(app.session.paint.fill, default, "bucket {bucket}: the default gradient"); + assert!(app.ui.status.is_empty(), "bucket {bucket}: {}", app.ui.status); + } +} + /// The Type row's Diamond button (the fourth of five) makes the gradient a diamond, and the /// Aspect Ratio field then edits its aspect. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 79f6183e79..a0bcd3f1fb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1649,7 +1649,9 @@ A conic gradient (`kind: "conic"`, also accepted as `angle` or `conical`) sweeps draws the extent ellipse, aspect dot and center ring of a radial gradient, without a focal point; a `focal` given for a conic gradient is an error. A negative `aspect` mirrors the sweep (counterclockwise), as reflecting the object does; for the other kinds a negative `aspect` is an error. The Gradient panel's Aspect Ratio field and the aspect dot -keep a mirrored sweep mirrored. Dither and Method apply as they do to a linear gradient. PDF export writes it as a +keep a mirrored sweep mirrored. The default gradient for new art, and the Live Paint Bucket's, fits each object it +paints and keeps no aspect, so `paint.editGradient` with an `aspect` is an error when it edits no object (nothing +selected, or the bucket's gradient without `ids`) and leaves the default as it was. Dither and Method apply as they do to a linear gradient. PDF export writes it as a function-based shading (type 1) whose calculator function turns the angle into the ramp, and PDF import reads a function-based shading whose color turns around the origin of its space back as a conic gradient, with its stops' opacity, also when the origin lies outside the painted area; in a PDF/A file, or with more than 97 stops on its From 16de36545ce78ada24115d4f4443f9cc07fa53a1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:04:10 -0800 Subject: [PATCH 14/16] Retype: retype.find's params text says a null more runs a new search retype.find reads `more` with opt_bool, which treats null as omitted, so `{more: null}` runs a new search. The params text said any value other than true or false is an error. The params text, its MCP mirror and docs/mcp.md now say that false, omitted or null runs a new search and that a value other than true, false or null is an error. A test checks that a null more lists the first ten again. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/retype/tests.rs | 2 ++ docs/mcp.md | 5 +++-- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index d9415a9549..a8588825cf 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -837,7 +837,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "retype.find", "Find Matching Fonts", "", - "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does, or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more that is not true or false, is an error and leaves the list as it was; returns what retype.list returns", + "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", ), ( "retype.list", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 7b520b7718..88b7c1c6a6 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -838,7 +838,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "retype.find", "Find Matching Fonts", "", - "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does, or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more that is not true or false, is an error and leaves the list as it was; returns what retype.list returns", + "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", ), ( "retype.list", diff --git a/crates/ui-egui/src/panels/retype/tests.rs b/crates/ui-egui/src/panels/retype/tests.rs index 8a7370bc5a..215a502a4a 100644 --- a/crates/ui-egui/src/panels/retype/tests.rs +++ b/crates/ui-egui/src/panels/retype/tests.rs @@ -97,6 +97,8 @@ fn more_adds_fonts_until_none_is_left() { } assert_eq!(last["more"], json!(false), "{last}"); assert_eq!(app.run("retype.find", json!({"more": true})).unwrap(), last, "nothing is left to add"); + // A null more is omitted: a new search lists the first ten again. + assert_eq!(app.run("retype.find", json!({"more": null})).unwrap(), first); // Before any search, more is a first search. app.run("retype.reset", json!({})).unwrap(); assert_eq!(app.run("retype.find", json!({"more": true})).unwrap(), first); diff --git a/docs/mcp.md b/docs/mcp.md index c242a3c9be..e052e5ff87 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12171,8 +12171,9 @@ path selected it is an error. Window › Retype shows the Retype panel. Find Matching Fonts runs `retype.find {}`, which shows the panel, ranks up to 96 fonts and lists the first ten. Find more font matches, at the end of the list when `more` is true, runs `retype.find {more: true}`, which adds the next five fonts that search found, whatever is selected now. Before any -search, `retype.find {more: true}` runs a first search. A search that fails is an error and leaves the list as it -was. Each row shows the font's family and style over a sample of the font. While live type is selected or edited, a +search, `retype.find {more: true}` runs a first search. With `more` false, omitted or null, `retype.find` runs a new +search; any other value than true, false or null is an error. A search that fails is an error and leaves the list as +it was. Each row shows the font's family and style over a sample of the font. While live type is selected or edited, a click on a row sets that font on it, as the font menus do; live type inside a selected group counts too. The list stays when the selection changes. From 25bb2abfc8e81f447261a2a7f073c0a79730d604 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:36:53 -0800 Subject: [PATCH 15/16] Retype: the null more test adds a font so a new search is told apart When ten or fewer fonts match, adding more to the exhausted list returns the same list as a new search, so the null more assertion could not tell the two apart. The test now adds a font to the list before the null more call, and only a new search drops it. --- crates/ui-egui/src/panels/retype/tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/retype/tests.rs b/crates/ui-egui/src/panels/retype/tests.rs index 215a502a4a..49f067c0b2 100644 --- a/crates/ui-egui/src/panels/retype/tests.rs +++ b/crates/ui-egui/src/panels/retype/tests.rs @@ -97,7 +97,9 @@ fn more_adds_fonts_until_none_is_left() { } assert_eq!(last["more"], json!(false), "{last}"); assert_eq!(app.run("retype.find", json!({"more": true})).unwrap(), last, "nothing is left to add"); - // A null more is omitted: a new search lists the first ten again. + // A null more is omitted: a new search lists the first ten again. A font added to the list + // tells the new search apart from adding more when ten or fewer fonts match. + app.ui.retype.fonts.push(super::Found { family: "Not Found".into(), style: "Regular".into(), matched: 0 }); assert_eq!(app.run("retype.find", json!({"more": null})).unwrap(), first); // Before any search, more is a first search. app.run("retype.reset", json!({})).unwrap(); From 8d7eaf36bbe3e0130f4b5bfba44af280cca1cff5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:53:08 -0800 Subject: [PATCH 16/16] Gradient: an aspect for a Live Paint group without faces is an error A fill edit of a selected Live Paint group with edges and no faces edits no object, yet paint.editGradient accepted an aspect there and returned no ids, and the Aspect Ratio field stayed enabled. - paint.editGradient refuses an aspect when the Live Paint filter leaves no object. Graph design art alone still changes nothing without an error, as for the other params. - Session::gradient_edit_has_objects reads the same filtered targets, so the field is dimmed in that case. - Params text and docs/mcp.md name the case. --- crates/engine/src/cmd/gradient.rs | 15 +++++++++------ crates/engine/src/tests/build.rs | 12 +++++++++++- docs/mcp.md | 2 +- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 2a90441934..f5270c9780 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected or the Live Paint Bucket's gradient: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)", has_doc, edit_gradient ), @@ -118,13 +118,14 @@ impl StopOwner { impl Session { /// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not - /// while the Live Paint Bucket is active or when nothing it can paint is selected: it then edits only the - /// default gradient, which takes no `aspect`. + /// while the Live Paint Bucket is active or when nothing it can paint is selected (a Live Paint group stands + /// only for its faces in a fill edit and its edges in a stroke edit): it then edits no object and takes no + /// `aspect`. pub fn gradient_edit_has_objects(&self, stroke: bool) -> bool { let p = json!({ "stroke": stroke }); !super::paint::for_bucket(self, &p) && item_target(self, &p, "paint.editGradient") - .is_ok_and(|item| item.of_kind(self, !stroke).targets(self, &p).is_ok_and(|ids| !ids.is_empty())) + .is_ok_and(|item| item.of_kind(self, !stroke).targets_for(self, &p, !stroke).is_ok_and(|ids| !ids.is_empty())) } /// The selected gradient stop (`gradient.selectStop`), while the gradient it was selected on @@ -557,8 +558,10 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { // Objects were given or selected, even when all of them are graph design art left out below, or Live Paint group parts // of the other kind left out above: the stroke mode is then not one for new art. let selected = !ids.is_empty() || skipped; - // The default gradient for new art (and the bucket's) is fitted to each object, so it has no aspect of its own. - if !selected && p.get("aspect").is_some() { + // The default gradient for new art (and the bucket's) is fitted to each object, so it has no aspect of its own. A + // Live Paint group with no part of the edited kind gives no object either. Graph design art is left out below + // without an error, as for every other param. + if ids.is_empty() && p.get("aspect").is_some() { return Err(bad(C, "`aspect` needs objects to place the gradient on: give ids or select objects")); } let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?; diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 6c3cd26d8d..424e5678bb 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3332,7 +3332,7 @@ fn live_paint_bucket_paint_and_stroke_commands_leave_the_selection_unpainted() { } /// `paint.editGradient` with an `aspect` and no object to edit (the Live Paint Bucket's gradient, -/// or nothing selected) is an error that leaves the default gradient as it was, since a gradient +/// nothing selected, or a fill edit of a Live Paint group without faces) is an error that leaves the default gradient as it was, since a gradient /// fitted to each object has no aspect of its own. Named objects still take the aspect. #[test] fn edit_gradient_aspect_without_objects_is_an_error() { @@ -3376,6 +3376,16 @@ fn edit_gradient_aspect_without_objects_is_an_error() { s.execute("select.set", &json!({"ids": [empty.0]})).unwrap(); assert!(!s.gradient_edit_has_objects(false), "an empty group"); assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err()); + // A fill edit of a Live Paint group with edges and no faces edits no object; a stroke edit edits its edges. + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 100, "y2": 0})).unwrap()["id"].as_u64().unwrap()); + let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap(); + let (fill, group, steps) = (s.paint.fill.clone(), node(&s, edges_only), s.doc().unwrap().history.undo.len()); + assert!(!s.gradient_edit_has_objects(false), "a Live Paint group without faces"); + assert!(s.gradient_edit_has_objects(true), "its edges take a stroke edit"); + assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err()); + assert_eq!((&s.paint.fill, node(&s, edges_only)), (&fill, group), "the default and the group stay"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step"); // A selected object takes it. s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); assert!(s.gradient_edit_has_objects(false) && s.gradient_edit_has_objects(true)); diff --git a/docs/mcp.md b/docs/mcp.md index c575b3c53a..5729e763ac 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1651,7 +1651,7 @@ for a conic gradient is an error. A negative `aspect` mirrors the sweep (counter does; for the other kinds a negative `aspect` is an error. The Gradient panel's Aspect Ratio field and the aspect dot keep a mirrored sweep mirrored. The default gradient for new art, and the Live Paint Bucket's, fits each object it paints and keeps no aspect, so `paint.editGradient` with an `aspect` is an error when it edits no object (nothing -selected, or the bucket's gradient without `ids`) and leaves the default as it was. Dither and Method apply as they do to a linear gradient. PDF export writes it as a +selected, the bucket's gradient without `ids`, or a fill edit of a Live Paint group without faces) and leaves the default as it was. Dither and Method apply as they do to a linear gradient. PDF export writes it as a function-based shading (type 1) whose calculator function turns the angle into the ramp, and PDF import reads a function-based shading whose color turns around the origin of its space back as a conic gradient, with its stops' opacity, also when the origin lies outside the painted area; in a PDF/A file, or with more than 97 stops on its