Color Wheel: Show Document Colors lists the colors the art uses

The Color Wheel panel menu gets Show Document Colors. It adds a row
under the wheel or the box with the colors of the selection, headed
Selection Colors, or with nothing selected the colors of the art Select
All takes, headed Document Colors, most used first and as many as fit
in one row. A color's tooltip gives its hex value and how many times
the art uses it. A click applies it to the active proxy or to the
selected gradient stop, keeping its color model and its link to a
global swatch, or to the selected freeform point, which takes the
color alone. Alt+click applies it to the other proxy.

The row keeps its colors during a drag. In art with more than 5,000
color uses, it reads them again at most once every half second after
an edit; a change of document or selection reads them at once.

color.used {selection?, limit?} lists the colors recolor.colors lists,
each with the color in its own model and the tint of its swatch to
three decimals. The swatch and tint come from the color's first linked
use in paint order, a plain use before a gradient stop that mixes a
spot ink with process inks; a color that only such stops link has no
swatch there. ui.colorWheel {documentColors} sets the option, which is
kept with the preferences.

Docs: docs/control-protocol.md, docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
dotCooCoo committed 2026-11-14 09:52:09 -08:00
1 parent 22b8c6ce5a
commit b83cec1545
40 files changed
+845 -46

No files matched your search

@@ -138,6 +138,7 @@ pub(super) const ALLOWED: &[&str] = &[
"color.gamutCheck",
"color.harmony",
"color.plates",
"color.used",
"dataset.capture",
"dataset.delete",
"dataset.list",
+84 -29
View File
@@ -29,6 +29,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
colors
),
cmd!(
query "color.used",
"Document Colors",
[],
None,
"{selection?: true (false: the objects select.all takes, also while something is selected), limit?: n (only the n most used; default all)} → {colors: [{key, hex, color: the color in its own model ({model, …}), count, swatch?: the global swatch it is linked to (from its first linked use in paint order, a plain use before a gradient stop that mixes the swatch's ink with process inks; left out when only such stops link it), tint?: 0..100 to three decimals (the percent of that swatch's color the same use stores)}] as recolor.colors lists them, selection: true when they are the selection's, uses: the uses of every color, those past limit included} the unique colors of the selection, or with nothing selected or selection false of the objects select.all takes without the hidden and locked objects inside them, most used first; the selection is left as it is",
has_doc,
used
),
cmd!(
"recolor.apply",
"Recolor Artwork",
@@ -945,11 +954,15 @@ fn pick_theme(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"colors": colors.iter().map(key_str).collect::<Vec<_>>(), "objects": theme.objects}))
}
/// A colour the art uses: how often, and the global swatch it is linked to.
/// A color the art uses: how often, and the global swatch it is linked to with the tint (0..1) of
/// the swatch its paint stores, when the paint gives one.
struct Used {
color: Color,
count: usize,
swatch: Option<String>,
tint: Option<f32>,
/// The link comes from a gradient stop that mixes the swatch's ink with process inks.
mixed: bool,
}
/// The unique colours of the objects `ids` and the objects inside them, most used first (ties by
@@ -967,16 +980,23 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
}
let mut index: HashMap<ColorKey, usize> = HashMap::new();
let mut used: Vec<(ColorKey, Used)> = vec![];
let mut count = |c: &Color, link: Option<&str>| {
let mut count_tint = |c: &Color, link: Option<&str>, tint: Option<f32>, mixed: bool| {
let k = ColorKey::of(c);
let i = *index.entry(k).or_insert_with(|| {
used.push((k, Used { color: *c, count: 0, swatch: None }));
used.push((k, Used { color: *c, count: 0, swatch: None, tint: None, mixed: false }));
used.len() - 1
});
let u = &mut used[i].1;
u.count += 1;
if u.swatch.is_none() {
u.swatch = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())).map(str::to_string);
// The first linked use in paint order gives the swatch and tint; a plain linked use
// replaces one from a stop that mixes the swatch's ink with process inks.
if u.swatch.is_none() || (u.mixed && !mixed) {
let linked = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some()));
if let Some(l) = linked {
u.swatch = Some(l.to_string());
u.tint = tint;
u.mixed = mixed;
}
}
};
// The patterns used as fills or strokes: their tiles count once each.
@@ -986,25 +1006,32 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
read(n, only, &mut nodes);
}
for m in nodes {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, .. } => count(color, swatch.as_deref()),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref())),
Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern),
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| count(&p.color, None));
}
paints(m, &mut count_tint, &mut patterns);
}
for def in patterns.iter().filter_map(|p| d.pattern(p)) {
def.art.iter().for_each(|n| node_colors(n, &mut count));
def.art.iter().for_each(|n| n.walk(&mut |m| paints(m, &mut count_tint, &mut vec![])));
}
used.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(&b.0)));
used.into_iter().map(|(_, u)| u).collect()
}
/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint
/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and
/// add the patterns it is painted with to `patterns`.
fn paints<'a>(m: &'a Node, count: &mut impl FnMut(&Color, Option<&str>, Option<f32>, bool), patterns: &mut Vec<&'a str>) {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, tint } => count(color, swatch.as_deref(), Some(*tint), false),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref(), Some(s.tint), s.plates.is_some())),
Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern),
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| count(&p.color, None, None, false));
}
}
/// The colors `n` shows, in paint order ([`node_colors`]), then the colors of the tiles of the
/// patterns it uses as fills or strokes, and of the patterns those tiles use (each pattern once).
fn shown_colors<'a>(d: &'a Document, n: &'a Node) -> Vec<Color> {
@@ -1047,30 +1074,58 @@ fn scope_ids(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<NodeId>, Option<B
let st = s.doc()?;
let ids = match p.get("ids") {
Some(_) => checked_ids_param(s, p, "ids", cmd)?,
None if st.selection.is_empty() => {
let only = super::select::selectable_ids(&st.doc, st.isolation);
return Ok((super::select::selectable(&st.doc, st.isolation), Some(only)));
}
None if st.selection.is_empty() => return Ok(all_art(st)),
None => st.selection.objects.clone(),
};
let mut seen = BTreeSet::new();
Ok((super::edit::outermost(&st.doc, ids).into_iter().filter(|id| seen.insert(*id)).collect(), None))
}
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
let (ids, only) = scope_ids(s, p, "recolor.colors")?;
let st = s.doc()?;
let v: Vec<Value> = used_colors(&st.doc, &ids, only.as_ref())
.iter()
/// The objects Select All takes, and the objects whose colors count ([`scope_ids`] with nothing
/// selected).
fn all_art(st: &crate::DocState) -> (Vec<NodeId>, Option<BTreeSet<NodeId>>) {
let only = super::select::selectable_ids(&st.doc, st.isolation);
(super::select::selectable(&st.doc, st.isolation), Some(only))
}
/// The `colors` list of `recolor.colors` and `color.used` for the objects `ids` (see
/// [`used_colors`]). With `with_color`, each has its color in its own model and the tint of its
/// swatch, and a gradient stop's color that mixes the swatch's ink with process inks has no swatch.
fn colors_json(used: &[Used], with_color: bool) -> Vec<Value> {
used.iter()
.map(|u| {
let mut v = json!({"key": key_str(&u.color), "hex": u.color.to_hex(), "count": u.count});
if let Some(w) = &u.swatch {
if with_color {
v["color"] = json!(u.color);
}
if let Some(w) = u.swatch.as_ref().filter(|_| !(with_color && u.mixed)) {
v["swatch"] = json!(w);
if let Some(t) = u.tint.filter(|_| with_color) {
v["tint"] = json!((f64::from(t) * 100_000.0).round() / 1000.0);
}
}
v
})
.collect();
Ok(json!({ "colors": v }))
.collect()
}
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
let (ids, only) = scope_ids(s, p, "recolor.colors")?;
let st = s.doc()?;
Ok(json!({ "colors": colors_json(&used_colors(&st.doc, &ids, only.as_ref()), false) }))
}
/// `color.used {selection?, limit?}`: the colors of the selection, or of the art Select All takes.
fn used(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.used";
let limit = super::index_opt(p, "limit", C)?.unwrap_or(usize::MAX);
let selection = switch_or(p, "selection", true, C)? && !s.doc()?.selection.is_empty();
let (ids, only) = if selection { scope_ids(s, &json!({}), C)? } else { all_art(s.doc()?) };
let st = s.doc()?;
let used = used_colors(&st.doc, &ids, only.as_ref());
let uses: usize = used.iter().map(|u| u.count).sum();
let shown = used.get(..limit.min(used.len())).unwrap_or_default();
Ok(json!({ "colors": colors_json(shown, true), "selection": selection, "uses": uses }))
}
/// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a
+116
View File
@@ -133,6 +133,122 @@ fn colors_with_nothing_selected_leave_out_what_select_all_leaves_out() {
assert_eq!(hexes(&run(&mut s, "recolor.colors", json!({"ids": [hidden.0]}))), ["#0000ff"]);
}
#[test]
fn used_colors_list_the_most_used_first_with_their_colors() {
let mut s = session();
let reds: Vec<NodeId> = (0..3).map(|_| rect(&mut s, json!("#ff0000"))).collect();
let blue = rect(&mut s, json!({"c": 100, "m": 100, "y": 0, "k": 0}));
run(&mut s, "select.set", json!({"ids": []}));
let r = run(&mut s, "color.used", json!({}));
assert_eq!(r["selection"], false, "{r}");
let colors = r["colors"].as_array().unwrap();
assert_eq!(colors.len(), 2, "{r}");
assert_eq!((colors[0]["key"].as_str(), colors[0]["hex"].as_str(), colors[0]["count"].as_u64()), (Some("rgb 255 0 0"), Some("#ff0000"), Some(3)));
assert_eq!(colors[1]["count"], 1);
let first = run(&mut s, "color.used", json!({"limit": 1}));
assert_eq!(first["colors"], json!([colors[0]]), "`limit` keeps the most used");
assert_eq!((r["uses"].clone(), first["uses"].clone()), (json!(4), json!(4)), "`uses` counts every color");
// `color` is the color in its own model, which the paint commands take back.
assert_eq!(colors[1]["color"]["model"], "cmyk", "{r}");
assert!(close(color_value(&colors[1]["color"]).unwrap(), fill(&s, blue)));
// The selection's colors while something is selected; `selection: false` reads all the art.
run(&mut s, "select.set", json!({"ids": [blue.0]}));
let r = run(&mut s, "color.used", json!({}));
assert_eq!((r["selection"].clone(), r["colors"].as_array().unwrap().len()), (json!(true), 1), "{r}");
let all = run(&mut s, "color.used", json!({"selection": false}));
assert_eq!((all["selection"].clone(), all["colors"][0]["count"].clone()), (json!(false), json!(3)), "{all}");
assert_eq!(s.doc().unwrap().selection.objects, [blue], "the selection is left as it was");
// A hidden object's color is left out with nothing selected, as Select All leaves it out.
run(&mut s, "object.hide", json!({"ids": [reds[0].0]}));
assert_eq!(run(&mut s, "color.used", json!({"selection": false}))["colors"][0]["count"], 2);
let e = s.execute("color.used", &json!({"selection": "no"})).unwrap_err().to_string();
assert!(e.contains("`selection` must be true or false"), "{e}");
assert!(s.execute("color.used", &json!({"ids": [blue.0]})).is_err(), "an unknown key is refused");
}
#[test]
fn used_colors_name_the_swatch_and_tint_a_color_is_linked_to() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
let tinted = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [tinted.0], "swatch": "Ink", "tint": 40}));
run(&mut s, "select.set", json!({"ids": []}));
let r = run(&mut s, "color.used", json!({}));
let c = &r["colors"][0];
assert_eq!(c["swatch"].as_str(), Some("Ink"), "{r}");
assert!((c["tint"].as_f64().unwrap() - 40.0).abs() < 1e-4, "{r}");
// recolor.colors keeps its own fields.
assert_eq!(run(&mut s, "recolor.colors", json!({}))["colors"][0].get("tint"), None);
// A swatch of paper white looks the same at every tint; the tint comes from the paint.
run(&mut s, "swatch.new", json!({"name": "Paper", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true}));
let paper = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [paper.0], "swatch": "Paper", "tint": 33.333}));
run(&mut s, "select.set", json!({"ids": [paper.0]}));
let c = run(&mut s, "color.used", json!({}))["colors"][0].clone();
assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}");
// The tint is the paint's own, unrounded.
let vectorcraft_color::Paint::Solid { tint, .. } = s.doc().unwrap().doc.node(paper).unwrap().appearance.fill_paint() else {
panic!("a solid fill")
};
assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}");
assert!((tint - 0.33333).abs() < 1e-5);
// A pattern's tile keeps its tint as well.
run(&mut s, "select.set", json!({"ids": [paper.0]}));
run(&mut s, "object.pattern.make", json!({"name": "Sheet", "width": 20, "height": 20}));
run(&mut s, "object.pattern.done", json!({}));
let filled = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [filled.0], "swatch": "Sheet"}));
run(&mut s, "select.set", json!({"ids": [filled.0]}));
let c = run(&mut s, "color.used", json!({}))["colors"][0].clone();
assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}");
assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}");
}
#[test]
fn used_colors_give_no_swatch_for_a_stop_that_mixes_its_ink_with_process_inks() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
let shape = rect(&mut s, json!("#000000"));
let mixed = Color::Cmyk { c: 0.3, m: 0.5, y: 0.3, k: 0.0 };
let stop = |color, plates| GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates, ..GradientStop::new(0.0, color) };
let mut end = stop(Color::Cmyk { c: 0.0, m: 0.5, y: 0.3, k: 0.0 }, None);
end.offset = 1.0;
let g = Gradient::new(GradientKind::Linear, vec![stop(mixed, Some([0.3, 0.0, 0.0, 0.0])), end]);
let st = s.doc_mut().unwrap();
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
let r = run(&mut s, "color.used", json!({}));
let entry = |key: &str| r["colors"].as_array().unwrap().iter().find(|c| c["key"] == key).cloned().unwrap();
let mix = entry("cmyk 30 50 30 0");
assert_eq!((mix.get("swatch"), mix.get("tint")), (None, None), "{r}");
assert_eq!(entry("cmyk 0 50 30 0")["swatch"], "Ink", "{r}");
// recolor.colors keeps the swatch it lists.
let listed = run(&mut s, "recolor.colors", json!({}));
assert!(listed["colors"].as_array().unwrap().iter().all(|c| c["swatch"] == "Ink"), "{listed}");
}
#[test]
fn used_colors_take_the_swatch_of_a_plain_use_painted_after_a_mixed_stop_of_the_same_color() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
let shape = rect(&mut s, json!("#000000"));
let plain = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Ink", "tint": 50}));
let ink = fill(&s, plain);
// The stop below the plain fill has the same color, and process plates that add nothing.
let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) };
let mut end = stop.clone();
end.offset = 1.0;
let g = Gradient::new(GradientKind::Linear, vec![stop, end]);
let st = s.doc_mut().unwrap();
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
run(&mut s, "select.set", json!({"ids": []}));
let r = run(&mut s, "color.used", json!({}));
let c = r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap();
assert_eq!((c["swatch"].as_str(), c["tint"].as_f64()), (Some("Ink"), Some(50.0)), "{r}");
}
#[test]
fn colors_with_nothing_selected_leave_out_hidden_and_locked_objects_in_groups() {
let mut s = session();
+1 -1
View File
@@ -1324,7 +1324,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, all three are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, documentColors}",
),
(
"ui.savePdfDialog",
+4
View File
@@ -124,6 +124,10 @@
Add to Selection Добавяне към селекцията
Add to Swatches Добавяне към образци
Add Used Colors Добавяне на използваните цветове
Show Document Colors Показване на цветовете на документа
Document Colors Цветове на документа
Selection Colors Цветове на селекцията
@plural Used {n} time|Used {n} times Използван {n} път|Използван {n} пъти
Additional Plug-ins Folder Допълнителна папка за плъгини
Additional Fonts Folder Допълнителна папка за шрифтове
Adjust Adjoining Width Points Регулиране на прилежащите точки за ширина
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -3996,6 +3996,10 @@ 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
Show Document Colors Prikaži boje dokumenta
Document Colors Boje dokumenta
Selection Colors Boje odabira
@plural Used {n} time|Used {n} times Korišteno {n} put|Korišteno {n} puta|Korišteno {n} puta
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.
+4
View File
@@ -220,6 +220,10 @@
Add to Symbols Afegeix als símbols
Add to the Current Shortcuts Afegeix a les dreceres actuals
Add Used Colors Afegeix els colors utilitzats
Show Document Colors Mostra els colors del document
Document Colors Colors del document
Selection Colors Colors de la selecció
@plural Used {n} time|Used {n} times Utilitzat {n} vegada|Utilitzat {n} vegades
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
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -4052,6 +4052,10 @@ 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
Show Document Colors Zobrazit barvy dokumentu
Document Colors Barvy dokumentu
Selection Colors Barvy výběru
@plural Used {n} time|Used {n} times Použito {n}krát|Použito {n}krát|Použito {n}krát
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.
+4
View File
@@ -3769,6 +3769,10 @@ theme Appearance Udseende
Add to Graphic Styles Føj til grafikstile
Graphic Style Library Grafikstilbibliotek
Add Used Colors Tilføj anvendte farver
Show Document Colors Vis dokumentfarver
Document Colors Dokumentfarver
Selection Colors Markeringens farver
@plural Used {n} time|Used {n} times Brugt {n} gang|Brugt {n} gange
Delete Swatch Slet farveprøve
Duplicate Swatch Duplikér farveprøve
Merge Swatches Flet farveprøver
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -113,6 +113,10 @@
Add to Selection Zur Auswahl hinzufügen
Add to Swatches Zu Farbfeldern hinzufügen
Add Used Colors Verwendete Farben hinzufügen
Show Document Colors Dokumentfarben einblenden
Document Colors Dokumentfarben
Selection Colors Farben der Auswahl
@plural Used {n} time|Used {n} times {n}-mal verwendet|{n}-mal verwendet
Additional Plug-ins Folder Zusätzlicher Plug-in-Ordner
Additional Fonts Folder Zusätzlicher Schriftenordner
Adjust Adjoining Width Points Angrenzende Breitenpunkte anpassen
Can't render this file because it is too large.
+4
View File
@@ -118,6 +118,10 @@
Add to Selection Προσθήκη στην επιλογή
Add to Swatches Προσθήκη στα δείγματα χρωμάτων
Add Used Colors Προσθήκη των χρησιμοποιημένων χρωμάτων
Show Document Colors Εμφάνιση χρωμάτων εγγράφου
Document Colors Χρώματα εγγράφου
Selection Colors Χρώματα επιλογής
@plural Used {n} time|Used {n} times Χρησιμοποιείται {n} φορά|Χρησιμοποιείται {n} φορές
Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων
Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών
Adjust Adjoining Width Points Ρύθμιση γειτονικών σημείων πλάτους
Can't render this file because it is too large.
+4
View File
@@ -138,6 +138,10 @@
Add to Selection Agregar a la selección
Add to Swatches Agregar a muestras
Add Used Colors Agregar colores usados
Show Document Colors Mostrar colores del documento
Document Colors Colores del documento
Selection Colors Colores de la selección
@plural Used {n} time|Used {n} times Usado {n} vez|Usado {n} veces
Additional Plug-ins Folder Carpeta de plugins adicionales
Additional Fonts Folder Carpeta de fuentes adicionales
Adjust Adjoining Width Points Ajustar puntos de anchura contiguos
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -3976,6 +3976,10 @@ theme Appearance Ulkoasu
Add to Graphic Styles Lisää grafiikkatyyleihin
Graphic Style Library Grafiikkatyylikirjasto
Add Used Colors Lisää käytetyt värit
Show Document Colors Näytä asiakirjan värit
Document Colors Asiakirjan värit
Selection Colors Valinnan värit
@plural Used {n} time|Used {n} times Käytetty {n} kerran|Käytetty {n} kertaa
Delete Swatch Poista värimalli
Duplicate Swatch Monista värimalli
Merge Swatches Yhdistä värimallit
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -139,6 +139,10 @@
Add to Selection Ajouter à la sélection
Add to Swatches Ajouter au nuancier
Add Used Colors Ajouter les couleurs utilisées
Show Document Colors Afficher les couleurs du document
Document Colors Couleurs du document
Selection Colors Couleurs de la sélection
@plural Used {n} time|Used {n} times Utilisée {n} fois|Utilisée {n} fois
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
Can't render this file because it is too large.
+4
View File
@@ -148,6 +148,10 @@
Add Selected Artwork as One Asset પસંદ કરેલી આર્ટવર્ક એક સંપત્તિ તરીકે ઉમેરો
Add Spine Point સ્પાઇન બિંદુ ઉમેરો
Add Used Colors વપરાયેલા રંગ ઉમેરો
Show Document Colors દસ્તાવેજના રંગો બતાવો
Document Colors દસ્તાવેજના રંગો
Selection Colors પસંદગીના રંગો
@plural Used {n} time|Used {n} times {n} વાર વપરાયો|{n} વાર વપરાયો
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.
+4
View File
@@ -254,6 +254,10 @@
Add to Symbols सिंबल्स में जोड़ें
Add to the Current Shortcuts वर्तमान शॉर्टकट में जोड़ें
Add Used Colors उपयोग किए रंग जोड़ें
Show Document Colors डॉक्यूमेंट के रंग दिखाएँ
Document Colors डॉक्यूमेंट के रंग
Selection Colors चयन के रंग
@plural Used {n} time|Used {n} times {n} बार उपयोग किया गया|{n} बार उपयोग किया गया
Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर
Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर
Adjust Adjoining Width Points सटे हुए चौड़ाई पॉइंट समायोजित करें
Can't render this file because it is too large.
+4
View File
@@ -208,6 +208,10 @@
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
Show Document Colors Dokumentumszínek megjelenítése
Document Colors Dokumentumszínek
Selection Colors A kijelölés színei
@plural Used {n} time|Used {n} times {n} alkalommal használva
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
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -3769,6 +3769,10 @@ theme Appearance Tampilan
Add to Graphic Styles Tambahkan ke gaya grafis
Graphic Style Library Pustaka gaya grafis
Add Used Colors Tambahkan warna yang digunakan
Show Document Colors Tampilkan warna dokumen
Document Colors Warna dokumen
Selection Colors Warna pilihan
@plural Used {n} time|Used {n} times Dipakai {n} kali
Delete Swatch Hapus sampel
Duplicate Swatch Duplikatkan sampel
Merge Swatches Gabungkan sampel
Can't render this file because it contains an unexpected character in line 2438 and column 5.
+4
View File
@@ -138,6 +138,10 @@
Add to Selection Aggiungi alla selezione
Add to Swatches Aggiungi ai campioni
Add Used Colors Aggiungi colori usati
Show Document Colors Mostra colori del documento
Document Colors Colori del documento
Selection Colors Colori della selezione
@plural Used {n} time|Used {n} times Usato {n} volta|Usato {n} volte
Additional Plug-ins Folder Cartella plug-in aggiuntivi
Additional Fonts Folder Cartella font aggiuntivi
Adjust Adjoining Width Points Regola punti di larghezza adiacenti
Can't render this file because it is too large.
+4
View File
@@ -1046,6 +1046,10 @@ digits Malayalam マラヤーラム数字
Add Selected Artwork as One Asset 選択したアートワークを 1 つのアセットとして追加
Add Spine Point スパインポイントを追加
Add Used Colors 使用中のカラーを追加
Show Document Colors ドキュメントのカラーを表示
Document Colors ドキュメントのカラー
Selection Colors 選択範囲のカラー
@plural Used {n} time|Used {n} times {n} 回使用
Add to Graphic Styles グラフィックスタイルに追加
Add to Profiles プロファイルに追加
Add to Profiles… プロファイルに追加…
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -3608,6 +3608,10 @@ theme Appearance იერსახე
Add to Graphic Styles გრაფიკულ სტილებში დამატება
Graphic Style Library გრაფიკული სტილების ბიბლიოთეკა
Add Used Colors გამოყენებული ფერების დამატება
Show Document Colors დოკუმენტის ფერების ჩვენება
Document Colors დოკუმენტის ფერები
Selection Colors მონიშნულის ფერები
@plural Used {n} time|Used {n} times გამოყენებულია {n}-ჯერ
Delete Swatch ფერის ნიმუშის წაშლა
Duplicate Swatch ფერის ნიმუშის დუბლირება
Merge Swatches ფერის ნიმუშების შერწყმა
Can't render this file because it is too large.
+4
View File
@@ -1036,6 +1036,10 @@ digits Malayalam 말라얄람어
Add Selected Artwork as One Asset 선택한 아트워크를 하나의 에셋으로 추가
Add Spine Point 스파인 포인트 추가
Add Used Colors 사용한 색상 추가
Show Document Colors 문서 색상 표시
Document Colors 문서 색상
Selection Colors 선택 영역 색상
@plural Used {n} time|Used {n} times {n}회 사용
Add to Graphic Styles 그래픽 스타일에 추가
Add to Profiles 프로필에 추가
Add to Profiles… 프로필에 추가…
Can't render this file because it is too large.
+4
View File
@@ -4287,6 +4287,10 @@ theme Appearance Vormgeving
Add to Graphic Styles Aan grafische stijlen toevoegen
Graphic Style Library Bibliotheek met grafische stijlen
Add Used Colors Gebruikte kleuren toevoegen
Show Document Colors Documentkleuren tonen
Document Colors Documentkleuren
Selection Colors Kleuren van de selectie
@plural Used {n} time|Used {n} times {n} keer gebruikt|{n} keer gebruikt
Delete Swatch Kleurstaal verwijderen
Duplicate Swatch Kleurstaal dupliceren
Merge Swatches Kleurstalen samenvoegen
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -3911,6 +3911,10 @@ 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
Show Document Colors Pokaż kolory dokumentu
Document Colors Kolory dokumentu
Selection Colors Kolory zaznaczenia
@plural Used {n} time|Used {n} times Użyty {n} raz|Użyty {n} razy|Użyty {n} razy
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.
+4
View File
@@ -140,6 +140,10 @@
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
Show Document Colors Mostrar Cores do Documento
Document Colors Cores do Documento
Selection Colors Cores da Seleção
@plural Used {n} time|Used {n} times Usada {n} vez|Usada {n} vezes
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.
+4
View File
@@ -136,6 +136,10 @@
Add to Selection Добавить к выделению
Add to Swatches Добавить в образцы
Add Used Colors Добавить использованные цвета
Show Document Colors Показать цвета документа
Document Colors Цвета документа
Selection Colors Цвета выделения
@plural Used {n} time|Used {n} times Используется {n} раз|Используется {n} раза|Используется {n} раз
Additional Plug-ins Folder Папка дополнительных модулей
Additional Fonts Folder Папка дополнительных шрифтов
Adjust Adjoining Width Points Настроить смежные точки ширины
Can't render this file because it is too large.
+4
View File
@@ -126,6 +126,10 @@
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
Show Document Colors Visa dokumentfärger
Document Colors Dokumentfärger
Selection Colors Markeringens färger
@plural Used {n} time|Used {n} times Används {n} gång|Används {n} gånger
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
Can't render this file because it is too large.
+4
View File
@@ -123,6 +123,10 @@
Add to Selection Seçime Ekle
Add to Swatches Renk Örneklerine Ekle
Add Used Colors Kullanılan Renkleri Ekle
Show Document Colors Belge Renklerini Göster
Document Colors Belge Renkleri
Selection Colors Seçim Renkleri
@plural Used {n} time|Used {n} times {n} kez kullanıldı
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
Can't render this file because it contains an unexpected character in line 5 and column 25.
+4
View File
@@ -132,6 +132,10 @@
Add to Selection Додати до виділення
Add to Swatches Додати до зразків
Add Used Colors Додати використані кольори
Show Document Colors Показати кольори документа
Document Colors Кольори документа
Selection Colors Кольори виділення
@plural Used {n} time|Used {n} times Використано {n} раз|Використано {n} рази|Використано {n} разів
Additional Plug-ins Folder Папка додаткових модулів
Additional Fonts Folder Папка додаткових шрифтів
Adjust Adjoining Width Points Налаштувати суміжні точки ширини
Can't render this file because it is too large.
+4
View File
@@ -154,6 +154,10 @@
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
Show Document Colors Hiện màu của tài liệu
Document Colors Màu của tài liệu
Selection Colors Màu của vùng chọn
@plural Used {n} time|Used {n} times Dùng {n} lầ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
1 # Vietnamese (vi) catalog. Same format as zh-hant.tsv: context <TAB> source <TAB> translation
154
155
156
157
158
159
160 @plural
161
162
163
+4
View File
@@ -88,6 +88,10 @@
Add to Selection 添加到选区
Add to Swatches 添加到色板
Add Used Colors 添加已用颜色
Show Document Colors 显示文档颜色
Document Colors 文档颜色
Selection Colors 所选对象的颜色
@plural Used {n} time|Used {n} times 使用 {n} 次
Additional Plug-ins Folder 附加增效工具文件夹
Additional Fonts Folder 附加字体文件夹
Adjust Adjoining Width Points 调整相邻宽度点
Can't render this file because it is too large.
+4
View File
@@ -97,6 +97,10 @@
Add to Selection 加入選取範圍
Add to Swatches 新增至色票
Add Used Colors 新增使用中的顏色
Show Document Colors 顯示文件顏色
Document Colors 文件顏色
Selection Colors 所選物件的顏色
@plural Used {n} time|Used {n} times 使用 {n} 次
Additional Plug-ins Folder 額外的增效模組資料夾
Additional Fonts Folder 額外的字體資料夾
Adjust Adjoining Width Points 調整相鄰寬度點
Can't render this file because it is too large.
+1 -1
View File
@@ -1325,7 +1325,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, all three are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, documentColors}",
),
(
"ui.savePdfDialog",
+2
View File
@@ -698,6 +698,8 @@ mod tests_color_wheel;
#[cfg(test)]
mod tests_color_wheel_box;
#[cfg(test)]
mod tests_color_wheel_document_colors;
#[cfg(test)]
mod tests_constrain;
#[cfg(test)]
mod tests_css_properties;
+175 -4
View File
@@ -11,8 +11,16 @@
//! channel strip at its right, for the channel picked under Box Channel (Hue, Saturation,
//! Brightness, Red, Green or Blue). The field shows the other two components on the Color
//! Picker's axes. The view and the channel are kept with the preferences (`ui.colorWheel`).
//!
//! The panel menu's Show Document Colors adds a row under the wheel or the box with the colors
//! of the selection, or with nothing selected of the art Select All takes, most used first
//! (`color.used`). A click on one applies it as a pick does. The active proxy and a selected
//! gradient stop keep its swatch link; a freeform point takes the color alone.
use egui::{Ui, UiBuilder, vec2};
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use egui::{Rect, Sense, Ui, UiBuilder, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::cms::{self, Cms};
@@ -23,6 +31,7 @@ use super::color::{Target, apply, wheel_target};
use super::{pstate, set_pstate};
use crate::VectorcraftApp;
use crate::dialogs::color_picker::Channel;
use crate::theme::Tokens;
use crate::widgets::{self, FieldAxis, Live, SliderValue, menu_item};
pub const ID: &str = "colorWheel";
@@ -67,6 +76,13 @@ pub struct Settings {
pub view: View,
#[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")]
pub channel: Channel,
/// Show Document Colors: the row of the colors the art uses, under the wheel or the box.
#[serde(deserialize_with = "deserialize_flag")]
pub document_colors: bool,
}
fn deserialize_flag<'de, D: serde::Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
Ok(<Value as Deserialize>::deserialize(d)?.as_bool().unwrap_or_default())
}
fn deserialize_view<'de, D: serde::Deserializer<'de>>(d: D) -> Result<View, D::Error> {
@@ -90,11 +106,12 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Se
Ok(serde_json::from_value(v).unwrap_or_default())
}
/// `ui.colorWheel {view?, channel?}`: show the wheel or the box, and pick the box's channel. Keys
/// `ui.colorWheel {view?, channel?, documentColors?}`: show the wheel or the box, pick the box's
/// channel, and show or hide the Show Document Colors row. Keys
/// left out keep their values; params that are not an object, another key or a value off the list
/// are an error and change nothing. → the settings.
pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
const KEYS: [&str; 2] = ["view", "channel"];
const KEYS: [&str; 3] = ["view", "channel", "documentColors"];
match p {
Value::Null => {}
Value::Object(o) => {
@@ -113,6 +130,9 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, Stri
None | Some(Value::Null) => {}
Some(v) => set.channel = v.as_str().and_then(Channel::parse).ok_or("`channel` must be hue, saturation, brightness, red, green or blue")?,
}
if let Some(on) = crate::menus::opt_bool(p, "documentColors")? {
set.document_colors = on;
}
app.ui.color_wheel = set;
Ok(json!(app.ui.color_wheel))
}
@@ -134,6 +154,151 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
}
});
});
ui.separator();
if menu_item(ui, tl!("Show Document Colors"), true, set.document_colors) {
command(app, &json!({ "documentColors": !set.document_colors })).ok();
}
}
/// Panel state: the Show Document Colors row's colors, with the [`UsedKey`] they were read for.
const USED: &str = "color-wheel-used";
/// The most chips the row asks `color.used` for.
const MAX_CHIPS: usize = 128;
/// Above this many color uses, an edit makes the row read the colors again at most once every
/// [`LARGE_EVERY`] seconds; a change of document or selection still reads them at once.
const LARGE_USES: u64 = 5_000;
const LARGE_EVERY: f64 = 0.5;
/// What the Show Document Colors row depends on: the document, its revision, and the number of
/// selected objects with a hash of their ids.
type UsedKey = Option<(u64, u64, usize, u64)>;
/// The row's colors as last read, kept in the panel state behind an `Arc`, so a frame that reads
/// them back copies no list.
#[derive(Debug, PartialEq)]
struct UsedCache {
key: UsedKey,
/// The frame time the colors were read at.
at: f64,
/// The uses of every color (`color.used`'s `uses`).
uses: u64,
/// Whether the colors are the selection's.
selected: bool,
colors: Vec<Used>,
}
/// A color of the row: the color, its hex value, how many times the art uses it, and the global
/// swatch it is linked to with the tint (0..1) of that swatch it is.
#[derive(Clone, Debug, PartialEq)]
struct Used {
color: Color,
hex: String,
count: u64,
link: Option<(String, f32)>,
}
impl Used {
/// The paint the color applies and drags: linked to its swatch at its tint when it has one.
fn paint(&self) -> Paint {
match &self.link {
Some((name, tint)) => Paint::Solid { color: self.color, swatch: Some(name.clone()), tint: *tint },
None => Paint::solid(self.color),
}
}
}
/// The colors the row shows and whether they are the selection's, read with `color.used` once per
/// document revision and selection and kept as they are while an interaction is in progress (a
/// preview raises the revision on every frame of a drag). In art with more than [`LARGE_USES`]
/// color uses, an edit reads them again only after [`LARGE_EVERY`] seconds.
fn used_colors(app: &mut VectorcraftApp, ui: &Ui) -> Arc<UsedCache> {
let key: UsedKey = app.session.active().map(|d| {
let mut h = std::collections::hash_map::DefaultHasher::new();
d.selection.objects.hash(&mut h);
(d.uid, d.revision, d.selection.objects.len(), h.finish())
});
let now = ui.input(|i| i.time);
if let Some(cache) = pstate::<Option<Arc<UsedCache>>>(ui.ctx(), USED) {
if cache.key == key || app.session.in_interaction() {
return cache;
}
let scope = |k: &UsedKey| k.map(|(doc, _, n, h)| (doc, n, h));
let wait = LARGE_EVERY - (now - cache.at);
if cache.uses > LARGE_USES && scope(&cache.key) == scope(&key) && wait > 0.0 {
ui.ctx().request_repaint_after_secs(wait as f32);
return cache;
}
}
let r = key.as_ref().and_then(|_| app.session.execute("color.used", &json!({ "limit": MAX_CHIPS })).ok());
let colors: Vec<Used> = r
.as_ref()
.and_then(|r| r["colors"].as_array())
.map(|a| {
a.iter()
.filter_map(|c| {
let color = serde_json::from_value::<Color>(c["color"].clone()).ok()?;
let hex = c["hex"].as_str().map_or_else(|| color.to_hex(), str::to_string);
let link = c["swatch"].as_str().zip(c["tint"].as_f64()).map(|(n, t)| (n.to_string(), (t / 100.0).clamp(0.0, 1.0) as f32));
Some(Used { color, hex, count: c["count"].as_u64().unwrap_or(0), link })
})
.collect()
})
.unwrap_or_default();
let selected = r.as_ref().is_some_and(|r| r["selection"] == true);
let uses = r.as_ref().and_then(|r| r["uses"].as_u64()).unwrap_or(0);
let cache = Arc::new(UsedCache { key, at: now, uses, selected, colors });
set_pstate(ui.ctx(), USED, Some(Arc::clone(&cache)));
cache
}
/// The Show Document Colors row: a heading (Selection Colors or Document Colors) and the colors,
/// most used first, as many as fit in one row. Returns the color clicked.
fn document_colors_row(app: &mut VectorcraftApp, ui: &mut Ui) -> Option<Used> {
let cache = used_colors(app, ui);
widgets::subheader(ui, if cache.selected { tl!("Selection Colors") } else { tl!("Document Colors") });
let t = Tokens::get(ui.ctx());
let width = ui.available_width();
// Chips are 16 px on a 19 px pitch, inset 3 px, with 2 px kept clear of the right edge, as
// in the Recent Colors row.
let per_row = (((width - 21.0) / 19.0).floor().max(0.0) as usize + 1).max(1);
let (r, _) = ui.allocate_exact_size(vec2(width, 22.0), Sense::hover());
ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside);
let mut chosen = None;
for (i, u) in cache.colors.iter().take(per_row).enumerate() {
let cell = Rect::from_min_size(r.min + vec2(3.0 + i as f32 * 19.0, 3.0), vec2(16.0, 16.0));
let resp = ui.interact(cell, ui.scope_id().with(("document-color", i)), Sense::click_and_drag());
let paint = u.paint();
widgets::drag_source(ui, &resp, || widgets::PanelDrag::paint(paint.clone()));
widgets::swatch_tile(ui, cell, &paint, false, resp.hovered());
let tip = format!("{}\n{}", u.hex, crate::i18n::tn(u.count, "Used {n} time", "Used {n} times"));
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &tip));
if resp.on_hover_text(&tip).clicked() {
chosen = Some(u.clone());
}
}
chosen
}
/// Apply a color of the Show Document Colors row as a pick does, to the inactive proxy when
/// `behind`. A color linked to a swatch stays linked at its tint, except at a freeform gradient's
/// point, which takes the color alone.
fn apply_used(app: &mut VectorcraftApp, tgt: &Target, u: &Used, behind: bool) {
let Some((name, tint)) = &u.link else { return apply(app, tgt, u.color, Live::Released, behind) };
match tgt {
Target::Stop { paint: Paint::Gradient(g), index, .. } if !behind => {
let mut stops = g.gradient.stops.clone();
if let Some(s) = stops.get_mut(*index) {
s.set_color(u.color, Some((name.clone(), *tint)));
}
super::gradient::set_stops(app, &stops, None, Live::Released);
}
Target::Point { .. } if !behind => apply(app, tgt, u.color, Live::Released, behind),
_ => {
let mut p = super::paint_params(&u.paint());
p["focus"] = json!(!behind);
super::live_run(app, "Color", super::proxy_cmd(app, behind), p, Live::Released);
}
}
}
/// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness,
@@ -344,8 +509,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
pick = Some(([hsb[0], x, 1.0 - y], field_phase));
}
});
let Some((hsb, phase)) = pick else { return };
let behind = super::alt_held(ui);
if app.ui.color_wheel.document_colors
&& let Some(u) = document_colors_row(app, ui)
{
apply_used(app, &tgt, &u, behind);
return;
}
let Some((hsb, phase)) = pick else { return };
let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk);
let c = stored(&cms, hsb, replaced(app, &tgt, behind).as_ref(), cmyk_doc);
apply(app, &tgt, c, phase, behind);
@@ -167,16 +167,16 @@ fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() {
#[test]
fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue"}));
assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue"}));
assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green"}));
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue", "documentColors": false}));
assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue", "documentColors": false}));
assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green", "documentColors": false}));
let e = app.run("ui.colorWheel", json!({"view": "triangle"})).unwrap_err();
assert_eq!(e, "`view` must be wheel or box");
let e = app.run("ui.colorWheel", json!({"view": "wheel", "channel": 7})).unwrap_err();
assert_eq!(e, "`channel` must be hue, saturation, brightness, red, green or blue");
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green }, "an error changes nothing");
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green, ..Default::default() }, "an error changes nothing");
let ui = crate::control::inspect(&app, &egui::Context::default());
assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green"}));
assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green", "documentColors": false}));
}
/// The command's errors are translated in the catalogs that translate status and error messages,
@@ -211,10 +211,10 @@ fn ui_color_wheel_rejects_other_params() {
let e = app.run("ui.colorWheel", json!([1])).unwrap_err();
assert_eq!(e, "the params must be an object, not [1]");
let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err();
assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel");
assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, documentColors");
let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err();
assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel");
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red }, "an error changes nothing");
assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, documentColors");
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing");
}
/// With None there is no color to edit: the strip reads 0 to screen readers, as the hue ring does,
@@ -249,7 +249,11 @@ fn ui_color_wheel_answers_junk_params_without_a_panic() {
/// not know reads as the key's default without losing the other preferences.
#[test]
fn the_settings_are_kept_and_read_leniently() {
let ui = crate::UiState { color_wheel: Settings { view: View::Box, channel: Channel::Blue }, color_rgb_percent: true, ..Default::default() };
let ui = crate::UiState {
color_wheel: Settings { view: View::Box, channel: Channel::Blue, ..Default::default() },
color_rgb_percent: true,
..Default::default()
};
let saved = serde_json::to_value(&ui).unwrap();
let back: crate::UiState = serde_json::from_value(saved.clone()).unwrap();
assert_eq!(back.color_wheel, ui.color_wheel);
@@ -262,11 +266,11 @@ fn the_settings_are_kept_and_read_leniently() {
let mut odd = saved.clone();
odd["color_wheel"] = json!({"view": "box", "channel": 7});
let back: crate::UiState = serde_json::from_value(odd).unwrap();
assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default() });
assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default(), ..Default::default() });
let mut odd = saved.clone();
odd["color_wheel"] = json!({"view": "triangle", "channel": "blue"});
let back: crate::UiState = serde_json::from_value(odd).unwrap();
assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue });
assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue, ..Default::default() });
let mut odd = saved;
odd["color_wheel"] = json!("box");
let back: crate::UiState = serde_json::from_value(odd).unwrap();
@@ -0,0 +1,323 @@
//! The Color Wheel panel's Show Document Colors row drawn headless: its colors and their order,
//! the heading that follows the selection, the colors that fit in one row, a click and an Alt+click
//! on a color, swatch links, gradient stops, the colors kept during a drag, the panel menu,
//! `ui.colorWheel {documentColors}` and the saved setting.
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_engine::Session;
use super::color_wheel::show;
use crate::VectorcraftApp;
/// A rectangle filled with `fill` (any paint `paint.setFill` takes), without a stroke, which
/// becomes the selection. → its id.
fn rect(app: &mut VectorcraftApp, x: f64, fill: Value) -> Value {
let id = app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 30})).unwrap()["id"].clone();
app.run("paint.setFill", fill).unwrap();
app.run("paint.setStroke", json!({"none": true, "focus": false})).unwrap();
id
}
/// A document with three red rectangles and one blue one (selected), with Show Document Colors on.
/// → the app, the ids of the red rectangles and the id of the blue one.
fn app() -> (VectorcraftApp, Vec<Value>, Value) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let reds = (0..3).map(|i| rect(&mut app, 10.0 + 40.0 * i as f64, json!({"color": "#ff0000"}))).collect();
let blue = rect(&mut app, 130.0, json!({"color": "#0000ff"}));
app.run("ui.colorWheel", json!({"documentColors": true})).unwrap();
(app, reds, blue)
}
fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> {
let mut h = Harness::builder().with_size(vec2(260.0, 360.0)).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app);
h.run_steps(2);
h
}
fn label(hex: &str, n: u64) -> String {
format!("{hex}\n{}", if n == 1 { "Used 1 time".to_string() } else { format!("Used {n} times") })
}
fn has(h: &Harness<'static, VectorcraftApp>, label: &str) -> bool {
h.query_by_label(label).is_some()
}
fn press(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, pressed: bool, modifiers: Modifiers) {
h.event(Event::ModifiersChanged(modifiers));
h.event(Event::PointerMoved(pos));
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers });
h.run_steps(1);
}
fn click(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, modifiers: Modifiers) {
press(h, pos, true, modifiers);
press(h, pos, false, modifiers);
h.event(Event::ModifiersChanged(Modifiers::NONE));
h.run_steps(1);
}
/// The hex value of the one color object `id` uses (its fill: it has no stroke).
fn fill_of(app: &mut VectorcraftApp, id: &Value) -> String {
let r = app.session.execute("recolor.colors", &json!({"ids": [id]})).unwrap();
assert_eq!(r["colors"].as_array().map(Vec::len), Some(1), "{r}");
r["colors"][0]["hex"].as_str().unwrap().to_string()
}
/// With nothing selected, the row is headed Document Colors and lists the art's colors, the red
/// that three rectangles use before the blue that one uses.
#[test]
fn show_document_colors_lists_the_art_colors_most_used_first() {
let (mut app, _, _) = app();
app.run("select.none", json!({})).unwrap();
let h = harness(app);
assert!(has(&h, "Document Colors"));
let red = h.get_by_label(&label("#ff0000", 3)).rect();
let blue = h.get_by_label(&label("#0000ff", 1)).rect();
assert!(red.left() < blue.left(), "red {red:?} comes before blue {blue:?}");
}
/// With something selected the row is headed Selection Colors and lists the selection's colors.
#[test]
fn the_heading_and_the_colors_follow_the_selection() {
let (app, _, _) = app();
let mut h = harness(app);
assert!(has(&h, "Selection Colors"));
assert!(has(&h, &label("#0000ff", 1)));
assert!(!has(&h, &label("#ff0000", 3)));
h.state_mut().run("select.none", json!({})).unwrap();
h.run_steps(2);
assert!(has(&h, "Document Colors") && !has(&h, "Selection Colors"));
assert!(has(&h, &label("#ff0000", 3)));
}
/// The row shows the most used colors that fit in one row and leaves out the rest.
#[test]
fn the_row_shows_only_the_colors_that_fit() {
let (mut app, _, _) = app();
for i in 0..30 {
rect(&mut app, 170.0 + i as f64, json!({"color": format!("#00{:02x}00", 40 + 6 * i)}));
}
app.run("select.none", json!({})).unwrap();
let h = harness(app);
let red = h.get_by_label(&label("#ff0000", 3)).rect();
let shown: Vec<_> = (0..30).filter_map(|i| h.query_by_label(&label(&format!("#00{:02x}00", 40 + 6 * i), 1)).map(|n| n.rect())).collect();
assert!(!shown.is_empty() && shown.len() < 30, "{} of the 30 greens show", shown.len());
assert!(shown.iter().all(|r| (r.top() - red.top()).abs() < 0.5 && r.right() <= 260.0), "one row inside the panel: {shown:?}");
}
/// A click on a color fills the selection with it, as one undo step.
#[test]
fn a_click_on_a_color_sets_the_fill() {
let (mut app, reds, blue) = app();
app.run("select.set", json!({"ids": [reds[0], blue]})).unwrap();
let undo = app.session.doc().unwrap().history.undo.len();
let mut h = harness(app);
let at = h.get_by_label(&label("#0000ff", 1)).rect().center();
click(&mut h, at, Modifiers::NONE);
let app = h.state_mut();
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
assert_eq!(fill_of(app, &reds[0]), "#0000ff");
assert_eq!(fill_of(app, &blue), "#0000ff");
assert_eq!(fill_of(app, &reds[1]), "#ff0000");
}
/// Alt+click applies the color to the inactive proxy (the stroke) and leaves the fill in front.
#[test]
fn alt_click_on_a_color_sets_the_stroke() {
let (mut app, reds, blue) = app();
app.run("select.set", json!({"ids": [reds[0], blue]})).unwrap();
let mut h = harness(app);
let at = h.get_by_label(&label("#ff0000", 1)).rect().center();
click(&mut h, at, Modifiers::ALT);
let app = h.state_mut();
assert!(app.session.fill_active, "the fill stays in front");
let st = app.session.doc().unwrap();
let paints = |id: &Value| {
let n = st.doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap();
(n.appearance.fill_paint().color().map(|c| c.to_hex()), n.appearance.stroke_paint().color().map(|c| c.to_hex()))
};
assert_eq!(paints(&blue), (Some("#0000ff".into()), Some("#ff0000".into())));
}
/// A color linked to a spot swatch stays linked at its tint when a click applies it.
#[test]
fn a_click_keeps_a_swatch_link_and_its_tint() {
let (mut app, _, blue) = app();
app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})).unwrap();
let ink = rect(&mut app, 170.0, json!({"swatch": "Ink", "tint": 40}));
app.run("select.set", json!({"ids": [ink, blue]})).unwrap();
let hex = app.session.execute("color.used", &json!({})).unwrap()["colors"]
.as_array()
.unwrap()
.iter()
.find(|c| c["swatch"] == "Ink")
.expect("the tint is listed")["hex"]
.as_str()
.unwrap()
.to_string();
let mut h = harness(app);
let at = h.get_by_label(&label(&hex, 1)).rect().center();
click(&mut h, at, Modifiers::NONE);
let st = h.state().session.doc().unwrap();
let fill = st.doc.node(vectorcraft_doc::NodeId(blue.as_u64().unwrap())).unwrap().appearance.fill_paint().clone();
let Paint::Solid { swatch, tint, .. } = fill else { panic!("a solid fill, not {fill:?}") };
assert_eq!(swatch.as_deref(), Some("Ink"));
assert!((tint - 0.4).abs() < 1e-3, "tint {tint}");
}
/// A click recolors the selected gradient stop, linking it to a color's swatch.
#[test]
fn a_click_recolors_the_selected_gradient_stop() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})).unwrap();
let stops = json!([{"offset": 0, "color": "#000000", "swatch": "Ink"}, {"offset": 1, "color": "#0000ff"}]);
rect(&mut app, 10.0, json!({"gradient": {"stops": stops, "start": [10, 25], "end": [40, 25]}}));
app.select_tool("gradient");
app.run("gradient.selectStop", json!({"index": 1})).unwrap();
app.run("ui.colorWheel", json!({"documentColors": true})).unwrap();
let hex = app.session.execute("color.used", &json!({})).unwrap()["colors"]
.as_array()
.unwrap()
.iter()
.find(|c| c["swatch"] == "Ink")
.expect("the stop's color is listed")["hex"]
.as_str()
.unwrap()
.to_string();
let mut h = harness(app);
let at = h.get_by_label(&label(&hex, 1)).rect().center();
click(&mut h, at, Modifiers::NONE);
let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") };
let stop = &g.gradient.stops[1];
assert_eq!((stop.color.to_hex(), stop.swatch.as_deref()), (hex, Some("Ink")));
}
/// While a drag on the wheel recolors the selection, the row keeps the colors from before the
/// drag; once it ends, it lists the new color.
#[test]
fn a_drag_on_the_wheel_does_not_read_the_colors_again_until_it_ends() {
let (app, _, blue) = app();
let revision = app.session.active().unwrap().revision;
let mut h = harness(app);
let ring = h.get_by_label("Hue ring").rect();
// The left of the ring (cyan), then its bottom, in the middle of the band.
let r = ring.width() / 2.0 - 11.0;
let (a, b) = (ring.center() - vec2(r, 0.0), ring.center() + vec2(0.0, r));
press(&mut h, a, true, Modifiers::NONE);
for p in [a, b, b] {
h.event(Event::PointerMoved(p));
h.run_steps(1);
}
assert!(h.state().session.in_interaction(), "the drag is in progress");
assert_ne!(h.state().session.active().unwrap().revision, revision, "the drag changed the document");
assert!(has(&h, &label("#0000ff", 1)), "the row keeps the colors from before the drag");
press(&mut h, b, false, Modifiers::NONE);
h.run_steps(2);
let now = fill_of(h.state_mut(), &blue);
assert_ne!(now, "#0000ff");
assert!(!has(&h, &label("#0000ff", 1)));
assert!(has(&h, &label(&now, 1)), "the row lists {now} after the drag");
}
/// In art with more than 5,000 color uses, the row reads the colors again after an edit at most
/// once every half second of frames, and a change of selection reads them at once.
#[test]
fn in_large_art_an_edit_reads_the_colors_again_after_half_a_second() {
let (mut app, reds, _) = app();
app.run("select.set", json!({"ids": [reds[0]]})).unwrap();
for _ in 0..11 {
app.run("select.all", json!({})).unwrap();
app.run("edit.duplicate", json!({})).unwrap();
}
app.run("select.none", json!({})).unwrap();
let uses = app.session.execute("color.used", &json!({})).unwrap()["uses"].as_u64().unwrap();
assert!(uses > 5_000, "{uses} uses");
let reds_used = app.session.execute("color.used", &json!({})).unwrap()["colors"][0]["count"].as_u64().unwrap();
let mut h = Harness::builder().with_size(vec2(260.0, 360.0)).with_step_dt(0.1).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app);
h.run_steps(6);
assert!(has(&h, &label("#ff0000", reds_used)));
// Half a second after the last read, an edit is read at once.
h.state_mut().run("paint.setFill", json!({"ids": [reds[0]], "color": "#00ff00"})).unwrap();
h.run_steps(1);
assert!(has(&h, &label("#ff0000", reds_used - 1)) && has(&h, &label("#00ff00", 1)), "the first edit is read at once");
// The next edit within half a second waits.
h.state_mut().run("paint.setFill", json!({"ids": [reds[1]], "color": "#00ff00"})).unwrap();
h.run_steps(1);
assert!(has(&h, &label("#00ff00", 1)), "the row waits after the second edit");
h.run_steps(5);
assert!(has(&h, &label("#ff0000", reds_used - 2)) && has(&h, &label("#00ff00", 2)), "the row reads the colors again");
h.state_mut().run("paint.setFill", json!({"ids": [reds[2]], "color": "#00ff00"})).unwrap();
h.state_mut().run("select.set", json!({"ids": [reds[2]]})).unwrap();
h.run_steps(1);
assert!(has(&h, "Selection Colors") && has(&h, &label("#00ff00", 1)), "a new selection reads the colors at once");
assert!(!has(&h, &label("#00ff00", 3)));
}
/// Without the setting the row is not drawn, and the panel menu's Show Document Colors turns it on.
#[test]
fn the_panel_menu_turns_the_row_on_and_off() {
let off = || {
let (mut a, _, _) = app();
a.run("ui.colorWheel", json!({"documentColors": false})).unwrap();
a
};
let mut h = harness(off());
assert!(!has(&h, "Selection Colors"));
// The menu in a context of its own, as the other panel menu tests draw it.
let mut app = off();
let ctx = egui::Context::default();
let raw = |events| egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(240.0, 200.0))), ..Default::default() };
let click_item = |app: &mut VectorcraftApp| {
let mut out = ctx.run_ui(raw(vec![]), |ui| super::color_wheel::menu(app, ui));
out.textures_delta.clear();
let item = out
.shapes
.iter()
.find_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.text().ends_with("Show Document Colors") => Some(t.visual_bounding_rect().center()),
_ => None,
})
.expect("the menu shows Show Document Colors");
let button = |pressed| Event::PointerButton { pos: item, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
ctx.run_ui(raw(vec![Event::PointerMoved(item), button(true), button(false)]), |ui| super::color_wheel::menu(app, ui)).textures_delta.clear();
};
click_item(&mut app);
assert!(app.ui.color_wheel.document_colors);
click_item(&mut app);
assert!(!app.ui.color_wheel.document_colors);
h.state_mut().run("ui.colorWheel", json!({"documentColors": true})).unwrap();
h.run_steps(2);
assert!(has(&h, "Selection Colors"));
}
/// `ui.colorWheel {documentColors}` sets the row's setting, keeps the others, and refuses a value
/// that is not a bool, changing nothing.
#[test]
fn ui_color_wheel_sets_document_colors() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["documentColors"], json!(false));
app.run("ui.colorWheel", json!({"view": "box"})).unwrap();
let r = app.run("ui.colorWheel", json!({"documentColors": true})).unwrap();
assert_eq!((r["documentColors"].clone(), r["view"].clone()), (json!(true), json!("box")));
assert_eq!(app.run("ui.colorWheel", json!({"documentColors": "no"})).unwrap_err(), "`documentColors` must be true or false");
assert!(app.ui.color_wheel.document_colors);
assert_eq!(app.run("ui.colorWheel", json!({"documentColors": null})).unwrap()["documentColors"], json!(true));
}
/// The saved setting reads leniently: a value this build does not know reads as off, and the other
/// settings and preferences are kept.
#[test]
fn the_saved_setting_reads_leniently() {
let read = |v: Value| serde_json::from_value::<crate::UiState>(v).expect("the preferences read");
let s = read(json!({"color_wheel": {"documentColors": true, "view": "box"}, "color_rgb_percent": true}));
assert!(s.color_wheel.document_colors && s.color_rgb_percent);
let s = read(json!({"color_wheel": {"documentColors": "yes", "view": "box"}, "color_rgb_percent": true}));
assert!(!s.color_wheel.document_colors && s.color_rgb_percent);
assert_eq!(s.color_wheel.view, super::color_wheel::View::Box);
}
+10
View File
@@ -298,6 +298,16 @@ selects its row for the sliders and a drag moves the row without changing a colo
step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder,
or the options button while a group is selected, opens it.
`color.used {selection?, limit?}` lists the colors of the selection, or with nothing selected the colors of the art
`select.all` takes, most used first, as `recolor.colors {}` counts them. Each entry adds `color`, the color in its own
model as the paint commands take it, and `tint`, the percent of its global `swatch` it is, to three decimals. The
swatch and tint come from the color's first linked use in paint order; a plain use goes before a gradient stop that
mixes a spot ink with process inks, and a color only such stops link has no `swatch` here. `selection: false` reads
the art `select.all` takes while something is selected, and the answer's `selection` says whether the colors are
the selection's. `limit` keeps only the most used entries, and the answer's `uses` counts the uses of every color.
The selection does not change. The Color Wheel panel's Show Document Colors row (`ui.colorWheel {documentColors:
true}`) shows these colors.
Library panel: `engine.execute {command: "window.swatchLibrary", params: {library}}` opens the read-only library
panel on a swatch library (`ui.inspect` shows it as `library_panel: {kind, id}`; `library: null` closes it).
Clicking a swatch there runs `swatch.library.add {library, names: [name], apply}` (the active proxy, or the other
+4
View File
@@ -625,6 +625,10 @@ strip at its right) in place of the wheel, as the panel menu's Box View and Box
shows the wheel again. Keys left out keep their values. Params that are not an object, another key or a value off
the list return an error and change nothing. The command returns `{view, channel}`, and both settings are kept with
the preferences.
`ui.colorWheel {"documentColors": true}` shows the Color Wheel panel's row of the colors the selection uses, or with
nothing selected the colors of the art `select.all` takes, in the order `color.used {}` lists them. A click on a color
applies it to the active proxy, keeping its link to a global swatch. The answer includes `documentColors`
with the other settings, and the setting is kept with the preferences.
In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's
screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop
+1
View File
@@ -1503,6 +1503,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel.
- **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given.
- **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Scores and estimates are unchanged.
- **Color Wheel document colors (part of #978):** the Color Wheel panel menu's Show Document Colors adds a row under the wheel or the box with the colors of the selection, headed Selection Colors, or with nothing selected of the art Select All takes, headed Document Colors, most used first and as many as fit in one row (`color.used`, `ui.colorWheel {documentColors}`). A color's tooltip gives its hex value and how many times the art uses it, and a click applies it as a pick does, keeping its color model; the active proxy and a selected gradient stop also keep its link to a global swatch. Tests: `crates/engine/src/tests/recolor.rs`, `crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs`.
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode").
Recent Colors keeps the last 30 solid colors applied, newest first and each once, and the list stays the same when another document is opened or made active; a 31st color drops the oldest ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). The list lasts for the session. In the Color and Swatches panels the chips wrap onto further rows when the panel is too narrow for one row (`paint.recent`). Tests: `recent_colors_keep_thirty_colors_across_documents` in `crates/engine/src/tests/paintproxy.rs`, `all_thirty_recent_colors_wrap_into_a_narrow_panel` in `crates/ui-egui/src/panels/color/tests.rs`.