Merge pull request #8723 from storytold/train/carry8164

Swatches: Add Selected Colors adds the selected art's colors as global swatches (#8164)
This commit is contained in:
BFlat authored and GitHub committed 2026-11-19 22:21:08 +07:00
commit 67caee2e60
34 files changed
+182 -10

No files matched your search

+32 -9
View File
@@ -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::{
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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; with Global Edit on, the other members keep their colors) → {added: [names], linked}",
has_doc,
swatch_add_used
),
@@ -1037,20 +1037,41 @@ fn swatch_sort(s: &mut Session, _: &Value) -> Result<Value> {
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<Color> {
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<ColorKey> = 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<Value> {
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<Vec<NodeId>> {
let ids: Vec<NodeId> = 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<ColorKey> = 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)
};
// 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}));
}
// 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();
let mut links = vec![];
for c in colors {
@@ -1060,7 +1081,9 @@ fn swatch_add_used(s: &mut Session, p: &Value) -> Result<Value> {
}
let linked = if global { link_colors(d, &ids, &links) } else { 0 };
Ok((links.into_iter().map(|(_, n)| n).collect::<Vec<_>>(), linked))
})?;
});
s.doc_mut()?.global_edit = global_edit;
let (added, linked) = edited?;
Ok(json!({"added": added, "linked": linked}))
}
+63
View File
@@ -125,6 +125,69 @@ 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);
}
/// 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<String> = 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);
+1
View File
@@ -126,6 +126,7 @@
Add to Selection Добавяне към селекцията
Add to Swatches Добавяне към образци
Add Used Colors Добавяне на използваните цветове
Add Selected Colors Добавяне на избраните цветове
Additional Plug-ins Folder Допълнителна папка за плъгини
Plug-in Instruction Budget Бюджет на инструкции за плъгини
Additional Fonts Folder Допълнителна папка за шрифтове
Can't render this file because it is too large.
+1
View File
@@ -4338,6 +4338,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
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -221,6 +221,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
Plug-in Instruction Budget Pressupost d’instruccions dels complements
Can't render this file because it is too large.
+1
View File
@@ -4447,6 +4447,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
Can't render this file because it is too large.
+1
View File
@@ -6901,6 +6901,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
Can't render this file because it is too large.
+1
View File
@@ -115,6 +115,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
Plug-in Instruction Budget Anweisungsbudget für Plug-ins
Additional Fonts Folder Zusätzlicher Schriftenordner
Can't render this file because it is too large.
+1
View File
@@ -120,6 +120,7 @@
Add to Selection Προσθήκη στην επιλογή
Add to Swatches Προσθήκη στα δείγματα χρωμάτων
Add Used Colors Προσθήκη των χρησιμοποιημένων χρωμάτων
Add Selected Colors Προσθήκη των επιλεγμένων χρωμάτων
Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων
Plug-in Instruction Budget Προϋπολογισμός εντολών επεκτάσεων
Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών
Can't render this file because it is too large.
+1
View File
@@ -140,6 +140,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
Plug-in Instruction Budget Presupuesto de instrucciones de plugins
Additional Fonts Folder Carpeta de fuentes adicionales
Can't render this file because it is too large.
+1
View File
@@ -4364,6 +4364,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
Can't render this file because it is too large.
+1
View File
@@ -141,6 +141,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
Plug-in Instruction Budget Budget d’instructions des modules externes
Additional Fonts Folder Dossier de polices supplémentaires
Can't render this file because it is too large.
+1
View File
@@ -149,6 +149,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 બ્રશમાં ઉમેરો
Can't render this file because it contains an unexpected character in line 72 and column 5.
+1
View File
@@ -255,6 +255,7 @@
Add to Symbols सिंबल्स में जोड़ें
Add to the Current Shortcuts वर्तमान शॉर्टकट में जोड़ें
Add Used Colors उपयोग किए रंग जोड़ें
Add Selected Colors सिलेक्टेड रंग जोड़ें
Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर
Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर
Plug-in Instruction Budget प्लग-इन निर्देश बजट
Can't render this file because it is too large.
+1
View File
@@ -209,6 +209,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
Plug-in Instruction Budget Bővítmények utasításkerete
Can't render this file because it is too large.
+1
View File
@@ -4767,6 +4767,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
Can't render this file because it is too large.
+1
View File
@@ -140,6 +140,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
Plug-in Instruction Budget Budget di istruzioni dei plug-in
Additional Fonts Folder Cartella font aggiuntivi
Can't render this file because it is too large.
+1
View File
@@ -1155,6 +1155,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… プロファイルに追加…
Can't render this file because it is too large.
+1
View File
@@ -6180,6 +6180,7 @@ theme Appearance იერსახე
Add to Graphic Styles გრაფიკულ სტილებში დამატება
Graphic Style Library გრაფიკული სტილების ბიბლიოთეკა
Add Used Colors გამოყენებული ფერების დამატება
Add Selected Colors მონიშნული ფერების დამატება
Delete Swatch ფერის ნიმუშის წაშლა
Duplicate Swatch ფერის ნიმუშის დუბლირება
Merge Swatches ფერის ნიმუშების შერწყმა
Can't render this file because it is too large.
+1
View File
@@ -1145,6 +1145,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… 프로필에 추가…
Can't render this file because it is too large.
+1
View File
@@ -4772,6 +4772,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
Can't render this file because it is too large.
+1
View File
@@ -4308,6 +4308,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
Can't render this file because it is too large.
+1
View File
@@ -141,6 +141,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…
Can't render this file because it is too large.
+1
View File
@@ -138,6 +138,7 @@
Add to Selection Добавить к выделению
Add to Swatches Добавить в образцы
Add Used Colors Добавить использованные цвета
Add Selected Colors Добавить выбранные цвета
Additional Plug-ins Folder Папка дополнительных модулей
Plug-in Instruction Budget Бюджет инструкций модулей
Additional Fonts Folder Папка дополнительных шрифтов
Can't render this file because it is too large.
+1
View File
@@ -128,6 +128,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
Plug-in Instruction Budget Instruktionsbudget för plugins
Additional Fonts Folder Mapp för ytterligare typsnitt
Can't render this file because it is too large.
+1
View File
@@ -125,6 +125,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ü
Plug-in Instruction Budget Eklenti Talimat Bütçesi
Additional Fonts Folder Ek Yazı Tipleri Klasörü
Can't render this file because it is too large.
+1
View File
@@ -134,6 +134,7 @@
Add to Selection Додати до виділення
Add to Swatches Додати до зразків
Add Used Colors Додати використані кольори
Add Selected Colors Додати вибрані кольори
Additional Plug-ins Folder Папка додаткових модулів
Plug-in Instruction Budget Бюджет інструкцій модулів
Additional Fonts Folder Папка додаткових шрифтів
Can't render this file because it is too large.
+1
View File
@@ -155,6 +155,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
Plug-in Instruction Budget Ngân sách lệnh của plug-in
Can't render this file because it is too large.
+1
View File
@@ -89,6 +89,7 @@
Add to Selection 添加到选区
Add to Swatches 添加到色板
Add Used Colors 添加已用颜色
Add Selected Colors 添加所选颜色
Additional Plug-ins Folder 附加增效工具文件夹
Plug-in Instruction Budget 增效工具指令预算
Additional Fonts Folder 附加字体文件夹
Can't render this file because it is too large.
+1
View File
@@ -98,6 +98,7 @@
Add to Selection 加入選取範圍
Add to Swatches 新增至色票
Add Used Colors 新增使用中的顏色
Add Selected Colors 新增所選顏色
Additional Plug-ins Folder 額外的增效模組資料夾
Plug-in Instruction Budget 增效模組指令預算
Additional Fonts Folder 額外的字體資料夾
Can't render this file because it is too large.
@@ -276,6 +276,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();
@@ -1738,6 +1738,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 Color Group Options… opens on the selected color group when that group is the
/// whole selection; with nothing selected, a swatch alone, or a swatch or a second group beside the
/// group, it opens nothing. After OK, and after `swatch.renameGroup` run on its own or in a batch,
@@ -2016,3 +2025,44 @@ 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));
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;
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);
}
+3 -1
View File
@@ -1101,7 +1101,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; 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}`, `swatch.renameGroup {group, name}` (Color Group Options: renames the group alone
+1
View File
@@ -1929,6 +1929,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, 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 `<name> copy` and then `<name> 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`.