Merge pull request #9103 from dotCooCoo/feat/recolor-preset-library

Recolor with Preset: ask whether to limit colors to a swatch library first
This commit is contained in:
BFlat
2026-11-26 08:46:55 +07:00
committed by GitHub
11 changed files with 445 additions and 37 deletions
+1 -1
View File
@@ -994,7 +994,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.recolorDialog",
"Recolor Artwork…",
"",
"{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)",
"{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library; an error with `group`)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)",
),
(
"ui.recolorUndo",
+1
View File
@@ -117,6 +117,7 @@ mod psd_options;
pub mod raster_effects;
pub mod rearrange_artboards;
pub mod recolor;
pub mod recolor_preset;
pub mod relink;
pub mod rename_artboards;
pub(crate) mod revolve;
+71 -27
View File
@@ -262,16 +262,45 @@ pub(crate) struct Open {
pub preview: LivePreview,
}
/// Open Recolor Artwork (`ui.recolorDialog {colors?, library?, group?}`) on the selected art and,
/// with `group`, on that colour group: art is reduced to as many rows as the group has colours,
/// which become their new colours; without art the rows are the group's colours. `colors` is a
/// count (an n-colour job) or the new colours to assign (without art or a group they are the
/// Open Recolor Artwork (`ui.recolorDialog {colors?, library?, group?, preset?}`) on the selected
/// art and, with `group`, on that colour group: art is reduced to as many rows as the group has
/// colours, which become their new colours; without art the rows are the group's colours. `colors`
/// is a count (an n-colour job) or the new colours to assign (without art or a group they are the
/// rows, which OK saves as a new colour group); `library` limits to a library or "document" (""
/// picks the first library).
/// picks the first library). With `preset: true` the Recolor with Preset dialog opens first.
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
match p.get("preset") {
None | Some(Value::Bool(false)) => {}
Some(Value::Bool(true)) => return super::recolor_preset::open(app, p),
Some(_) => return Err("`preset` must be true or false".into()),
}
let st = app.session.active().ok_or("no document open")?;
let art = !st.selection.is_empty();
let group = p.get("group").and_then(Value::as_str);
let group = match p.get("group") {
None | Some(Value::Null) => None,
Some(Value::String(g)) => Some(g.as_str()),
Some(_) => return Err("`group` must be a colour group name".into()),
};
// The group is looked for in the document without the preview of a Recolor Artwork this one
// replaces (which can rename the group), as that dialog's rollback below leaves it.
let unpreviewed = match &st.interaction {
Some(it) if app.color_dialogs.recolor.is_some() => &it.doc,
_ => &st.doc,
};
if let Some(g) = group
&& !unpreviewed.swatch_groups.iter().any(|x| x.name == g)
{
return Err(format!("no colour group `{g}`"));
}
// Colours alone (no art, no group) become a new colour group.
let new_group = !art && group.is_none();
if new_group && !matches!(p.get("colors"), Some(Value::Array(cs)) if cs.iter().any(|c| color_value(c).is_some())) {
return Err("select artwork (or a colour group) to recolor".into());
}
let limit = library_param(app, p)?;
// A Recolor Artwork still open is replaced: its preview goes before the group's colours are read.
cancel_open(app);
let st = app.session.active().ok_or("no document open")?;
let group_colors: Option<Vec<Color>> = match group {
Some(g) => {
let g = st.doc.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| format!("no colour group `{g}`"))?;
@@ -284,21 +313,11 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
(None, Some(Value::Array(cs))) => cs.iter().filter_map(color_value).map(|c| key(&c)).collect(),
_ => vec![],
};
// Colours alone (no art, no group) become a new colour group.
let new_group = !art && group.is_none();
if new_group && assign.is_empty() {
return Err("select artwork (or a colour group) to recolor".into());
}
let count = match p.get("colors").and_then(Value::as_u64) {
Some(n) => json!(n.max(1)),
None if !assign.is_empty() => json!(assign.len()),
None => Value::Null,
};
let limit = match p.get("library").and_then(Value::as_str) {
Some("") => first_library(app).unwrap_or_default(),
Some(l) => limit_key(app, l)?,
None => String::new(),
};
// Without art the rows are the group's colours, as they are.
let mut start: Vec<Value> = if art { vec![] } else { assign.iter().map(|k| json!({"from": [k], "to": k})).collect() };
number_slots(&mut start);
@@ -317,10 +336,6 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let mut rs = rows(&d);
snap(app, &d, &mut rs);
d.fields.insert("rows".into(), Value::Array(rs));
// A Recolor Artwork still open is replaced: its preview goes before this one's starts.
if let Some(old) = app.color_dialogs.recolor.take() {
old.preview.cancel(app);
}
let dialog = RecolorDialog::new(app, d);
let options = HeldOptions { cancel: Some(Box::new(cancelled)), ..HeldOptions::default() };
let id = open_held_with(app, dialog, confirm, options).ok_or("no window to show Recolor Artwork in")?;
@@ -346,10 +361,43 @@ fn key(c: &Color) -> Value {
/// The name a new colour group (opened on colours alone) starts with.
const NEW_GROUP: &str = "Color Group";
/// Ends an open Recolor Artwork as Cancel ends it: its preview is rolled back and it closes.
pub(super) fn cancel_open(app: &mut VectorcraftApp) {
let Some(old) = app.color_dialogs.recolor.take() else { return };
let id = old.id;
old.preview.cancel(app);
if let (Some(dialogs), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) {
dialogs.with(|host| {
host.cancel_by_id(&ctx, id);
});
}
}
fn first_library(app: &VectorcraftApp) -> Option<String> {
colour_libraries(app).into_iter().next().map(|l| l.id)
}
/// Limit to Library's choices: the key `limitTo` takes and the name the menu shows. None, the
/// document's swatches, then the colour libraries: the built-in ones translated, those the user
/// saved or loaded by their names.
pub(super) fn library_choices(app: &VectorcraftApp) -> Vec<(String, String)> {
let libs = colour_libraries(app);
let fixed = [("", tl!("None")), (swatchlib::DOCUMENT_SWATCHES, tl!(DOCUMENT_SWATCHES))].map(|(k, n)| (k.to_owned(), n.to_owned()));
let named = libs.iter().map(|l| (l.id.clone(), library_panel::library_name(&l.id, &l.name).to_owned()));
fixed.into_iter().chain(named).collect()
}
/// The `limitTo` key of `ui.recolorDialog`'s `library`: none without it or for null, the first
/// library for ""; a `library` that is not a string is an error.
pub(super) fn library_param(app: &VectorcraftApp, p: &Value) -> Result<String, String> {
match p.get("library") {
Some(Value::String(l)) if l.is_empty() => Ok(first_library(app).unwrap_or_default()),
Some(Value::String(l)) => limit_key(app, l),
None | Some(Value::Null) => Ok(String::new()),
Some(_) => Err("`library` must be a library id or name".into()),
}
}
/// `recolor.reduce` parameters (Method only picks each row's colour, so changing it keeps the rows).
fn reduce_params(d: &Fields) -> Value {
json!({
@@ -1441,15 +1489,11 @@ struct Feed {
impl Feed {
fn of(app: &VectorcraftApp, d: &Fields) -> Feed {
// None, the document's swatches, then the colour libraries: the built-in ones translated,
// those the user saved or loaded by their names.
let libs = colour_libraries(app);
let fixed = [("", tl!("None")), (swatchlib::DOCUMENT_SWATCHES, tl!(DOCUMENT_SWATCHES))].map(|(k, n)| (k.to_owned(), n.to_owned()));
let named = libs.iter().map(|l| (l.id.clone(), library_panel::library_name(&l.id, &l.name).to_owned()));
let libraries = fixed.into_iter().chain(named).collect();
let libraries = library_choices(app);
Feed {
// The colour libraries follow None and the document's swatches.
first_library: libraries.get(2).map(|(k, _)| k.clone()),
libraries,
first_library: libs.first().map(|l| l.id.clone()),
groups: doc_groups(app),
other_paints: other_paint_groups(app),
previewing: app.session.in_interaction(),
@@ -0,0 +1,61 @@
//! Edit → Edit Colors → Recolor with Preset: before Recolor Artwork opens on a preset (an n-color
//! job or Color Library), this dialog asks whether to limit the new colors to a swatch library
//! (`ui.recolorDialog {preset: true, colors?, library?}`, without `group`). OK opens Recolor Artwork with the
//! preset's colors and the library chosen (None: no limit); Cancel opens nothing.
//!
//! Fields: `limitTo` (a library id, `"document"` for the document's swatches, `""` for None), as
//! Recolor Artwork's.
use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamKind, ParamResult};
use craft::ui::runtime::env::Label;
use serde_json::{Value, json};
use super::recolor::{cancel_open, library_choices, library_param};
use super::swatch_options::{NO_WINDOW, field_label, hosted};
use crate::VectorcraftApp;
/// The dialog kind of Recolor with Preset.
pub const KIND: &str = "recolorPreset";
/// Open the dialog for the preset of `p` (`colors`: a count; `library`: the library it starts on,
/// "" the first library) on the selected art.
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
if st.selection.is_empty() {
return Err("select artwork to recolor".into());
}
if p.get("group").is_some_and(|g| !g.is_null()) {
return Err("`group` does not apply to a preset".into());
}
let colors = count(p.get("colors"))?;
let limit = library_param(app, p)?;
let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?;
// A Recolor Artwork this one opens over ends as Cancel ends it, its preview rolled back.
cancel_open(app);
let options = library_choices(app).into_iter().map(|(key, name)| (key, Label::from(name))).collect();
let mut fields = DialogFields::new();
fields.set("limitTo", limit.clone());
let rows = vec![Param::new("limitTo", field_label(tl!("Limit to Library:")), ParamKind::choice(options, Some(limit)))];
let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false);
// Recolor Artwork takes the dialog's place; when it cannot open, this dialog stays.
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
let mut p = serde_json::Map::new();
if let Some(n) = colors {
p.insert("colors".into(), json!(n));
}
if let Some(limit) = answer.fields.text("limitTo").filter(|l| !l.is_empty()) {
p.insert("library".into(), json!(limit));
}
super::recolor::open(app, &Value::Object(p)).map(|_| ())
};
super::host::open_held(app, dialog, ok).ok_or(NO_WINDOW)?;
Ok(Value::Null)
}
/// The preset's count of new colors: none for Color Library, else at least 1.
fn count(v: Option<&Value>) -> Result<Option<u64>, String> {
match v {
None | Some(Value::Null) => Ok(None),
Some(n) => n.as_u64().filter(|n| *n >= 1).map(Some).ok_or_else(|| "`colors` must be a count of at least 1".into()),
}
}
+4 -4
View File
@@ -148,10 +148,10 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec
sub(
"Recolor with Preset",
vec![
cp("1 Color Job…", "ui.recolorDialog", json!({"colors": 1})),
cp("2 Color Job…", "ui.recolorDialog", json!({"colors": 2})),
cp("3 Color Job…", "ui.recolorDialog", json!({"colors": 3})),
cp("Color Library…", "ui.recolorDialog", json!({"library": ""})),
cp("1 Color Job…", "ui.recolorDialog", json!({"colors": 1, "preset": true})),
cp("2 Color Job…", "ui.recolorDialog", json!({"colors": 2, "preset": true})),
cp("3 Color Job…", "ui.recolorDialog", json!({"colors": 3, "preset": true})),
cp("Color Library…", "ui.recolorDialog", json!({"library": "", "preset": true})),
],
),
c("Adjust Color Balance…", "ui.colorBalanceDialog"),
+1 -1
View File
@@ -995,7 +995,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.recolorDialog",
"Recolor Artwork…",
"",
"{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)",
"{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library; an error with `group`)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)",
),
(
"ui.recolorUndo",
+296 -1
View File
@@ -3,7 +3,7 @@
use std::sync::Arc;
use craft::color_ui::ui::ColorPickerDialog;
use craft::ui::dialog::{DialogId, StackDialog};
use craft::ui::dialog::{DialogId, HeldOk, StackDialog};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, pos2, vec2};
use serde_json::{Value, json};
use vectorcraft_color::Color;
@@ -208,6 +208,47 @@ fn assign(app: VectorcraftApp, params: Value) -> Recolor {
r
}
/// The open Recolor with Preset dialog: its id and its fields.
fn preset(r: &Recolor) -> Option<(DialogId, Value)> {
r.host(|host, _| {
let open = host.open_dialogs().into_iter().find(|d| d.key.as_deref() == Some(dialogs::recolor_preset::KIND));
open.map(|d| (d.id, d.fields.unwrap_or_default()))
})
.flatten()
}
/// Field `k` of the open Recolor with Preset dialog; null when it is not open.
fn preset_field(r: &Recolor, k: &str) -> Value {
preset(r).map(|(_, fields)| fields[k].clone()).unwrap_or_default()
}
/// Sets field `k` of the open Recolor with Preset dialog, as `ui.dialog.set` does.
fn set_preset(r: &mut Recolor, k: &str, v: Value) -> Result<(), String> {
let (id, _) = preset(r).ok_or("no Recolor with Preset")?;
r.host(|host, ctx| host.set_json_field(ctx, id, k, v)).unwrap_or_else(|| Err("no window".into()))
}
/// OK in Recolor with Preset, as `ui.dialog.confirm` gives it, and the frames in which it closes.
/// `Err` with the reason it was refused, which keeps the dialog open.
fn confirm_preset(r: &mut Recolor) -> Result<(), String> {
let (id, _) = preset(r).ok_or("no Recolor with Preset")?;
r.host(|host, ctx| host.confirm_by_id(ctx, id));
r.frame().frame();
match r.host(|host, _| host.held_state(id)).flatten() {
Some(HeldOk::Refused(reason)) => Err(reason.as_str().to_owned()),
_ if preset(r).is_some() => Err("Recolor with Preset stayed open".into()),
_ => Ok(()),
}
}
/// Cancel in Recolor with Preset, and the frame in which it closes.
fn cancel_preset(r: &mut Recolor) {
if let Some((id, _)) = preset(r) {
r.host(|host, ctx| host.cancel_by_id(ctx, id));
}
r.frame();
}
#[test]
fn the_dialog_reduces_previews_and_applies_as_one_undo_step() {
let mut app = app();
@@ -246,11 +287,14 @@ fn presets_open_colour_jobs_and_libraries_and_both_tabs_draw() {
.collect();
assert_eq!(presets.iter().map(|p| p.0.as_str()).collect::<Vec<_>>(), ["1 Color Job…", "2 Color Job…", "3 Color Job…", "Color Library…"]);
let mut r = open(app, presets[1].1.clone());
confirm_preset(&mut r).unwrap();
r.settled();
assert_eq!((field(&r, "colors"), field(&r, "method")), (json!(2), json!("scaleTints")));
assert_eq!(field(&r, "rows").as_array().unwrap().len(), 2);
r.cancel();
r.app().run("ui.recolorDialog", presets[3].1.clone()).unwrap();
assert_eq!(preset_field(&r, "limitTo"), "web-safe-216", "Color Library asks with the first library chosen");
confirm_preset(&mut r).unwrap();
assert_eq!(field(&r, "limitTo"), "web-safe-216", "Color Library starts on the first library");
r.settled();
let web = |k: &Value| vectorcraft_engine::cmd::color_value(k).unwrap().to_rgb().iter().all(|v| ((v * 5.0).round() - v * 5.0).abs() < 1e-3);
@@ -1458,3 +1502,254 @@ fn the_recolor_undo_and_redo_commands_preview_the_step() {
assert_eq!(fills(&r.app()), adjusted, "Redo Changes previews the step after");
r.cancel();
}
/// Edit › Edit Colors › Recolor with Preset asks whether to limit the colors to a swatch library
/// before Recolor Artwork opens: Cancel opens nothing, and OK opens Recolor Artwork with the
/// preset's colors and the library chosen.
#[test]
fn recolor_with_preset_asks_for_a_library_first() {
let mut r = Recolor::new(app());
assert!(r.app().run("ui.recolorDialog", json!({"colors": 1, "preset": true})).is_err(), "nothing selected");
assert!(preset(&r).is_none());
art(&mut r.app(), &["#333333", "#999999"]);
for (p, why) in [
(json!({"colors": 1, "preset": 1}), "`preset` is true or false"),
(json!({"colors": 0, "preset": true}), "a preset has at least one color"),
(json!({"colors": 1, "preset": true, "group": "Grays"}), "a preset takes no group"),
] {
assert!(r.app().run("ui.recolorDialog", p).is_err(), "{why}");
}
assert!(preset(&r).is_none() && !r.is_open());
let presets: Vec<Value> = crate::menus::menu_entries(&r.app())
.iter()
.filter(|e| e.path.last().is_some_and(|p| p == "Recolor with Preset"))
.map(|e| e.params.clone())
.collect();
assert_eq!(presets.len(), 4);
for p in &presets {
r.app().run("ui.recolorDialog", p.clone()).unwrap();
r.settled();
assert!(preset(&r).is_some() && !r.is_open(), "{p}");
cancel_preset(&mut r);
assert!(preset(&r).is_none() && !r.is_open(), "Cancel opens nothing: {p}");
}
// A preset opened over Recolor Artwork's preview rolls the preview back.
let start = colors(&mut r.app());
r.app().run("ui.recolorDialog", json!({})).unwrap();
r.set("colors", json!(1)).unwrap();
r.set("method", json!("exact")).unwrap();
r.settled();
assert_eq!(colors(&mut r.app()), 1, "previewed");
r.app().run("ui.recolorDialog", presets[0].clone()).unwrap();
assert!(preset(&r).is_some());
assert_eq!(colors(&mut r.app()), start, "the preview is rolled back");
r.settled();
assert!(!r.is_open(), "Recolor Artwork closed");
assert_eq!(preset_field(&r, "limitTo"), json!(""), "a color job starts on None");
set_preset(&mut r, "limitTo", json!("document")).unwrap();
// OK with nothing to recolor leaves the dialog open.
r.app().run("select.none", json!({})).unwrap();
assert!(confirm_preset(&mut r).is_err());
assert!(preset(&r).is_some() && !r.is_open(), "the dialog stays");
r.app().run("select.all", json!({})).unwrap();
confirm_preset(&mut r).unwrap();
assert!(r.is_open());
assert_eq!((field(&r, "colors"), field(&r, "method"), field(&r, "limitTo")), (json!(1), json!("scaleTints"), json!("document")));
// Recolor Artwork opened over its own preview rolls that preview back too.
r.set("method", json!("exact")).unwrap();
r.set("limitTo", json!("")).unwrap();
r.settled();
assert_eq!(colors(&mut r.app()), 1, "previewed");
r.app().run("ui.recolorDialog", json!({})).unwrap();
assert_eq!(colors(&mut r.app()), start, "the preview is rolled back");
r.cancel();
}
/// Recolor Artwork opened on a colour group over its own preview of that group starts on the
/// group's colours as the rolled-back preview leaves them.
#[test]
fn reopening_a_group_over_its_preview_starts_on_the_groups_colours() {
let mut app = app();
art(&mut app, &["#ff0000", "#0000ff"]);
let before = group_keys(&app, "Brights");
let mut r = open(app, json!({"group": "Brights"}));
r.settled();
let mut rows = field(&r, "rows");
rows[1]["to"] = json!("rgb 1 2 3");
r.set("rows", rows).unwrap();
r.settled();
assert_ne!(group_keys(&r.app(), "Brights"), before, "the preview changes the group");
r.app().run("ui.recolorDialog", json!({"group": "Brights"})).unwrap();
assert_eq!(group_keys(&r.app(), "Brights"), before, "the preview is rolled back");
assert_eq!(field(&r, "__assign"), json!(before), "the new dialog starts on the group's colours");
r.cancel();
}
/// Recolor Artwork opened on a colour group over a preview that renames it finds the group by its
/// name without the preview; an unknown group leaves the open dialog as it is.
#[test]
fn reopening_a_group_over_a_preview_that_renames_it_finds_the_group() {
let mut app = app();
art(&mut app, &["#ff0000", "#0000ff"]);
let before = group_keys(&app, "Brights");
let mut r = open(app, json!({"group": "Brights"}));
r.settled();
r.set("groupName", json!("Renamed")).unwrap();
r.settled();
let named = |r: &Recolor, n: &str| r.app().session.doc().unwrap().doc.swatch_groups.iter().any(|g| g.name == n);
assert!(named(&r, "Renamed") && !named(&r, "Brights"), "the preview renames the group");
assert!(r.app().run("ui.recolorDialog", json!({"group": "Nope"})).is_err());
assert_eq!(field(&r, "groupName"), json!("Renamed"), "an unknown group leaves the dialog open");
r.app().run("ui.recolorDialog", json!({"group": "Brights"})).unwrap();
assert!(named(&r, "Brights") && !named(&r, "Renamed"), "the preview is rolled back");
assert_eq!(field(&r, "__assign"), json!(before), "the new dialog starts on the group's colours");
r.cancel();
}
/// A `library` or `group` that is not a string is an error, with or without a preset, and opens
/// no dialog.
#[test]
fn recolor_rejects_a_library_or_group_that_is_not_a_string() {
let mut app = app();
art(&mut app, &["#ff0000", "#0000ff"]);
let mut r = Recolor::new(app);
for p in [
json!({"colors": 1, "library": 123}),
json!({"preset": true, "colors": 1, "library": 123}),
json!({"preset": true, "colors": 1, "library": true}),
json!({"group": 5}),
json!({"group": ["Brights"]}),
] {
assert!(r.app().run("ui.recolorDialog", p.clone()).is_err(), "{p}");
assert!(!r.is_open() && preset(&r).is_none(), "{p} opens no dialog");
}
r.app().run("ui.recolorDialog", json!({"colors": 1, "library": null, "group": null})).unwrap();
assert_eq!(field(&r, "limitTo"), json!(""), "a null library is no limit");
r.cancel();
}
/// Every paint under `v`, in order: its color, the swatch it is linked to and its tint.
fn paints_in(v: &Value, out: &mut Vec<(Color, Option<String>, f64)>) {
match v {
Value::Object(m) => {
if let Some(c) = m.get("color").and_then(|c| serde_json::from_value::<Color>(c.clone()).ok()) {
out.push((c, m.get("swatch").and_then(Value::as_str).map(String::from), m.get("tint").and_then(Value::as_f64).unwrap_or(1.0)));
}
m.values().for_each(|x| paints_in(x, out));
}
Value::Array(a) => a.iter().for_each(|x| paints_in(x, out)),
_ => {}
}
}
/// Every number under an `opacity` key under `v`, in order.
fn opacities_in(v: &Value, out: &mut Vec<f64>) {
match v {
Value::Object(m) => {
out.extend(m.get("opacity").and_then(Value::as_f64));
m.values().for_each(|x| opacities_in(x, out));
}
Value::Array(a) => a.iter().for_each(|x| opacities_in(x, out)),
_ => {}
}
}
/// The art of every layer as saved.
fn art_json(app: &VectorcraftApp) -> Value {
let d = &app.session.doc().unwrap().doc;
Value::Array(d.layers.iter().filter_map(|l| l.children()).map(|c| serde_json::to_value(c).unwrap()).collect())
}
fn art_paints(app: &VectorcraftApp) -> Vec<(Color, Option<String>, f64)> {
let mut out = vec![];
paints_in(&art_json(app), &mut out);
out
}
/// A gray other than black or white, with its lightness.
fn gray(c: &Color) -> Option<f32> {
let [r, g, b] = c.to_rgb();
((r - g).abs() < 1e-3 && (g - b).abs() < 1e-3 && r > 0.01 && r < 0.99).then_some(r)
}
/// Gray art placed from an SVG file (fills, a stroke, a group at 50% opacity, `fill-opacity`, a
/// compound path, a gradient's stops and type) with a 1 Color Job of Recolor with Preset limited
/// to the document's swatches and a spot or global ink picked for its row becomes tints of that
/// ink linked to its swatch, darker grays at higher tints, with its opacities kept; editing the
/// swatch then recolors the art at the same tints. A process swatch gives tints of its color with
/// no link.
#[test]
fn a_one_color_job_limited_to_document_swatches_links_gray_art_to_the_ink() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="240" height="80"><rect x="0" y="0" width="20" height="20" fill="#000000"/><rect x="25" y="0" width="20" height="20" fill="#333333" stroke="#808080" stroke-width="2"/><g opacity="0.5"><rect x="50" y="0" width="20" height="20" fill="#808080"/></g><rect x="75" y="0" width="20" height="20" fill="#cccccc" fill-opacity="0.7"/><rect x="100" y="0" width="20" height="20" fill="#ffffff" stroke="#000000"/><path d="M130 0 L150 0 L150 20 Z M135 5 L145 5 L145 15 Z" fill="#666666" fill-rule="evenodd"/><defs><linearGradient id="g"><stop offset="0" stop-color="#222222"/><stop offset="1" stop-color="#dddddd"/></linearGradient></defs><rect x="160" y="0" width="20" height="20" fill="url(#g)"/><text x="0" y="60" font-size="18" fill="#555555">Ink</text></svg>"##;
let path = std::env::temp_dir().join(format!("vectorcraft-recolor-preset-{}.svg", std::process::id()));
std::fs::write(&path, svg).unwrap();
for (kind, options, linked) in [("spot", json!({"spot": true}), true), ("global", json!({"global": true}), true), ("process", json!({}), false)] {
let mut r = Recolor::new(app());
let mut swatch = json!({"name": "Ink", "color": "cmyk 0 100 0 0"});
swatch.as_object_mut().unwrap().extend(options.as_object().unwrap().clone());
r.app().run("swatch.new", swatch).unwrap();
r.app().run("file.place", json!({"path": path.to_string_lossy(), "at": [120, 50]})).unwrap();
r.app().run("select.all", json!({})).unwrap();
let before = art_paints(&r.app());
let grays: Vec<usize> = (0..before.len()).filter(|&i| gray(&before[i].0).is_some()).collect();
assert!(grays.len() >= 9, "{kind}: the fills, the stroke, the stops and the type are gray: {before:?}");
let mut opacities = vec![];
opacities_in(&art_json(&r.app()), &mut opacities);
assert!(opacities.iter().any(|o| (o - 0.5).abs() < 1e-6), "the group's opacity came in: {opacities:?}");
assert!(opacities.iter().any(|o| (o - 0.7).abs() < 1e-6), "the fill opacity came in: {opacities:?}");
let job = crate::menus::menu_entries(&r.app()).iter().find(|e| e.label == "1 Color Job…").unwrap().params.clone();
r.app().run("ui.recolorDialog", job).unwrap();
set_preset(&mut r, "limitTo", json!("document")).unwrap();
confirm_preset(&mut r).unwrap();
r.settled();
let ink = r.app().session.doc().unwrap().doc.swatch("Ink").unwrap().paint.color().unwrap();
let mut rows = field(&r, "rows").as_array().unwrap().clone();
let row = rows.iter().position(|r| !r["exclude"].as_bool().unwrap_or(false)).unwrap();
assert!(rows.iter().enumerate().all(|(i, r)| i == row || r["exclude"].as_bool().unwrap_or(false)), "one row: {rows:?}");
rows[row]["to"] = json!(ColorKey::of(&ink).to_string());
r.set("rows", Value::Array(rows)).unwrap();
r.settled();
r.confirm().unwrap();
assert!(!r.is_open());
let after = art_paints(&r.app());
assert_eq!(after.len(), before.len(), "{kind}: the art has the same paints");
let mut kept = vec![];
opacities_in(&art_json(&r.app()), &mut kept);
assert_eq!(kept, opacities, "{kind}: the opacities are kept");
for &i in &grays {
let (c, link, tint) = &after[i];
assert!(gray(c).is_none(), "{kind}: paint {i} is no longer gray: {c:?}");
assert_eq!(link.is_some(), linked, "{kind}: paint {i} linked: {link:?}");
if linked {
assert_eq!(link.as_deref(), Some("Ink"));
assert!(*tint > 0.0 && *tint <= 1.0, "{kind}: paint {i} at a tint: {tint}");
}
}
for (i, c) in before.iter().enumerate().filter(|(i, _)| !grays.contains(i)) {
assert_eq!(after[i].0, c.0, "{kind}: black and white are kept");
}
for &a in &grays {
for &b in &grays {
if gray(&before[a].0) < gray(&before[b].0) {
if linked {
assert!(after[a].2 > after[b].2, "{kind}: a darker gray takes more ink: {:?} {:?}", after[a], after[b]);
} else {
assert_ne!(after[a].0, after[b].0, "{kind}: grays of different lightness get different colors: {a} {b}");
}
}
}
}
if linked {
r.app().run("swatch.edit", json!({"name": "Ink", "color": "cmyk 100 0 0 0"})).unwrap();
let edited = art_paints(&r.app());
for &i in &grays {
assert_eq!(edited[i].1.as_deref(), Some("Ink"), "{kind}: paint {i} stays linked");
assert!((edited[i].2 - after[i].2).abs() < 1e-6, "{kind}: paint {i} keeps its tint");
assert_ne!(edited[i].0, after[i].0, "{kind}: paint {i} takes the edited ink");
}
}
}
let _ = std::fs::remove_file(&path);
}
+6 -2
View File
@@ -288,9 +288,13 @@ canvas while open; `ui.dialog.confirm` keeps the result as one undo step (`edit.
`edit.colors.saturate`) and `ui.dialog.cancel` rolls it back. Global mode answers with an error until tints of global
and spot colours exist; the dialog then stays open.
Recolor Artwork: `ui.recolorDialog {colors?, library?, group?}` opens the `recolor` dialog on the selected art
Recolor Artwork: `ui.recolorDialog {colors?, library?, group?, preset?}` opens the `recolor` dialog on the selected art
(`colors`: a count for an n-colour job, or colours to assign as the new colours; `library`: Limit to Library, a library
or `"document"`, `""` for the first library; `group`: a colour group, Edit or Apply Color Group). Fields: `rows` (`[{from: [keys], to: key, exclude?, tint?, model?}]`
or `"document"`, `""` for the first library; `group`: a colour group, Edit or Apply Color Group). With `preset: true`
(the Edit › Edit Colors › Recolor with Preset items) it first opens the `recolorPreset` dialog, which asks whether to
limit the colors to a swatch library: its field `limitTo` (a library id, `"document"`, or `""` for None) starts on
`library`, and its OK opens the `recolor` dialog with `colors` and that library; `preset: true` with `group` is an
error. Fields: `rows` (`[{from: [keys], to: key, exclude?, tint?, model?}]`
as `recolor.reduce` returns them), `colors` (null for Auto), `method`, `preserveWhite`, `preserveBlack`,
`preserveGrays`, `limitTo`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`,
`sliderMode` (the mode of the color sliders under the rows: `hsb`, `rgb`, `cmyk`, `lab`, or `tint` for a row whose new
+1 -1
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -644,6 +644,7 @@ since 2026-10-01.
- **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). A drag or double-click on a ruler makes no guide while it is on (no preview, no undo step, a status message). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths`, `trim_view_makes_no_guide_from_the_rulers` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`.
- **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged.
- **Recolor with Preset asks for a library first:** Edit › Edit Colors › Recolor with Preset (1, 2 and 3 Color Job, Color Library) opens a Recolor with Preset dialog whose Limit to Library menu (None, Document Swatches or a library) is applied when Recolor Artwork opens (<https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=251>, "Quickly reduce colors using a preset"). A 1 Color Job limited to the document's swatches with a spot or global ink picked turns gray art into tints of that ink linked to its swatch, so editing the swatch recolors the art. Tests `recolor_with_preset_asks_for_a_library_first` and `a_one_color_job_limited_to_document_swatches_links_gray_art_to_the_ink`. Area score and hours unchanged.
- **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged.
- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, Alt tapped during a press moves the piece's end onto or off the tick for the new action, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `an_alt_tap_during_a_press_moves_the_end_for_the_new_action`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged.
- **Quick Pen arc center:** wherever the Quick Pen tool shows an arc's protractor, it also marks the arc's center with a small cross. The cross is VectorCraft's own behavior. Test: engine `an_arc_shows_a_cross_at_its_center`. Score and hours unchanged.
+2
View File
@@ -583,6 +583,8 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
- [x] Recolor Artwork › Assign: double-click a row's new color to pick it in the Color Picker, in the model it was picked in, with native Lab entry, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#8031, follow-up to #4090/#5113 for #4028). Evidence: `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise numeric entry and actual menu clicks.
- [x] Edit › Edit Colors › Recolor with Preset: the 1, 2 and 3 Color Job and Color Library presets first open a Recolor with Preset dialog whose Limit to Library menu (None, Document Swatches or a library) is applied when Recolor Artwork opens; Cancel opens nothing. A 1 Color Job limited to the document's swatches with a spot or global ink picked turns gray art into tints of that ink linked to its swatch. Evidence: `recolor_with_preset_asks_for_a_library_first` and `a_one_color_job_limited_to_document_swatches_links_gray_art_to_the_ink`.
- [x] Recolor Artwork › Color Theme Picker: with the button beside the tabs on, a click on the canvas takes the color palette of an object or image, a drag takes the palette of the art inside its marquee, and Shift adds more picks; the rows that aren't excluded take the palette as their new colors and the art previews them ([Recolor artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-artwork.html)). The number and order of the picked colors are VectorCraft's own rule (`recolor.pickTheme`). Tests: `theme_picks_give_the_rows_the_palette_of_the_art_picked` and `the_theme_picker_takes_clicks_and_shift_drags_on_the_canvas` in `crates/ui-egui/src/dialogs/recolor.rs`, `theme_picker_*` in `crates/engine/src/tests/recolor.rs`.
- [x] Recolor Artwork › Prominent Colors: with art, a bar under the Edit tab's wheel shows the new colors, each as wide as its share of the art; dragging the edge between two parts raises one color's weight and lowers the other's, and the art previews the result; the New Color Group menu has Save All Colors and Save Prominent Colors ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html)). How a share is measured and how a weight moves colors between rows are VectorCraft's own rules (`recolor.weigh`). Tests: `weights_move_the_rows_colors_and_the_art_previews_them`, `dragging_a_prominent_edge_moves_colors_between_rows` and `save_all_and_prominent_colors_make_color_groups` in `crates/ui-egui/src/dialogs/recolor.rs`, `weigh_*` in `crates/engine/src/tests/recolor.rs`.