Part of #978: the Color Wheel panel can gray out colors the CMYK space cannot print

The panel menu gains Show Out-of-Gamut Colors. While it is on, the wheel's
square and the box's color field draw gray over the cells of a 16 by 16 grid
whose colors fail the out-of-gamut warning's test (`Cms::out_of_gamut` on the
color a pick there would store). The grid is kept in panel state per channel,
strip value, color settings and loaded profiles, so it is computed again only
when one of them changes, including when a profile is loaded again under the
same name. `ui.colorWheel {gamut?}` sets it, and the setting is kept with the
preferences.
This commit is contained in:
dotCooCoo committed 2026-11-14 08:03:37 -08:00
1 parent 22b8c6ce5a
commit 804f844fcf
40 files changed
+443 -36

No files matched your search

+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, gamut?: 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); gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; 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, gamut}",
),
(
"ui.savePdfDialog",
+1
View File
@@ -2373,6 +2373,7 @@ font-technology Variable Променливи
The Scripts folder cannot be read Папката Scripts не може да бъде прочетена
Other Script… Друг скрипт…
Out of Gamut Warning Предупреждение за излизане извън цветовата гама
Show Out-of-Gamut Colors Показване на цветовете извън цветовата гама
Out of Web Color Warning Предупреждение за цвят извън уеб палитрата
Out Tangent Handles Външни тангентни дръжки
Outer Glow… Външно разсейване…
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -1649,6 +1649,7 @@ digits Malayalam Malajalam
Create New Swatch… Kreiraj novi uzorak boje…
Name 40% Naziv 40%
Out of Gamut Warning Upozorenje o izlasku iz gamuta
Show Out-of-Gamut Colors Prikaži boje izvan gamuta
Out of Web Color Warning Upozorenje o boji izvan weba
Web Safe RGB Sigurni web RGB
{warning}: click to correct to the closest color ({hex}) {warning}: kliknite za ispravku na najbližu boju ({hex})
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -3010,6 +3010,7 @@ digits Malayalam Malaiàlam
Other Library… Una altra biblioteca…
Other Script… Un altre script…
Out of Gamut Warning Avís fora de gama
Show Out-of-Gamut Colors Mostra els colors fora de gama
Out of Web Color Warning Avís fora dels colors web
Out Tangent Handles Nanses tangents de sortida
Outer Corner Tile Mosaic de cantonada exterior
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -1678,6 +1678,7 @@ digits Malayalam Malajálamské
Create New Swatch… Vytvořit novou položku vzorníku…
Name 40% Název 40 %
Out of Gamut Warning Upozornění na barvu mimo gamut
Show Out-of-Gamut Colors Zobrazit barvy mimo gamut
Out of Web Color Warning Upozornění na barvu mimo webovou paletu
Web Safe RGB Webově bezpečné RGB
{warning}: click to correct to the closest color ({hex}) {warning}: kliknutím opravíte na nejbližší barvu ({hex})
Can't render this file because it is too large.
+1
View File
@@ -1584,6 +1584,7 @@ digits Malayalam Malayalam
Create New Swatch… Opret ny farveprøve…
Name 40% Navn 40%
Out of Gamut Warning Advarsel: uden for gamut
Show Out-of-Gamut Colors Vis farver uden for gamut
Out of Web Color Warning Advarsel: ikke-websikker farve
Web Safe RGB Websikker RGB
{warning}: click to correct to the closest color ({hex}) {warning}: klik for at rette til den nærmeste farve ({hex})
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -2411,6 +2411,7 @@ file-filter Templates Vorlagen
Other Library… Andere Bibliothek…
Other Script… Anderes Skript…
Out of Gamut Warning Warnung: außerhalb des Farbumfangs
Show Out-of-Gamut Colors Farben außerhalb des Farbumfangs einblenden
Out of Web Color Warning Warnung: keine Webfarbe
Out Tangent Handles Ausgehende Tangentengriffe
Outer Glow… Schein nach außen…
Can't render this file because it is too large.
+1
View File
@@ -3273,6 +3273,7 @@ theme Appearance Εμφάνιση
Other Library… Άλλη βιβλιοθήκη…
Other Script… Άλλο σενάριο…
Out of Gamut Warning Προειδοποίηση εκτός χρωματικής γκάμας
Show Out-of-Gamut Colors Εμφάνιση χρωμάτων εκτός χρωματικής γκάμας
Out of Web Color Warning Προειδοποίηση εκτός χρωμάτων ιστού
Out Tangent Handles Λαβές εξερχόμενης εφαπτομένης
Outline Others Περιγράμματα άλλων
Can't render this file because it is too large.
+1
View File
@@ -2449,6 +2449,7 @@ font-technology Variable Variables
Other Library… Otra biblioteca…
Other Script… Otro script…
Out of Gamut Warning Aviso de fuera de gama
Show Out-of-Gamut Colors Mostrar colores fuera de gama
Out of Web Color Warning Aviso de color no apto para web
Out Tangent Handles Manejadores de tangente de salida
Outer Glow… Resplandor exterior…
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -1651,6 +1651,7 @@ digits Malayalam Malajalam
Create New Swatch… Luo uusi värimalli…
Name 40% Nimi 40%
Out of Gamut Warning Väriavaruuden ulkopuolella -varoitus
Show Out-of-Gamut Colors Näytä väriavaruuden ulkopuoliset värit
Out of Web Color Warning Verkkovärien ulkopuolella -varoitus
Web Safe RGB Verkkoturvallinen RGB
{warning}: click to correct to the closest color ({hex}) {warning}: korjaa lähimpään väriin ({hex}) napsauttamalla
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -2441,6 +2441,7 @@ font-technology Variable Variables
Other Library… Autre bibliothèque…
Other Script… Autre script…
Out of Gamut Warning Avertissement hors gamme
Show Out-of-Gamut Colors Afficher les couleurs hors gamme
Out of Web Color Warning Avertissement de couleur non Web
Out Tangent Handles Poignées de tangente sortantes
Outer Glow… Lueur externe…
Can't render this file because it is too large.
+1
View File
@@ -4229,6 +4229,7 @@
Box Channel બૉક્સ ચેનલ
Color box રંગ બૉક્સ
Color Wheel Options રંગ વ્હીલ વિકલ્પો
Show Out-of-Gamut Colors ગેમટ બહારના રંગો બતાવો
{name} (spot) {name} (સ્પૉટ)
{pages} in all, {count} per copy કુલ {pages}, પ્રતિ નકલ {count}
{page} of {count} {count} માંથી {page}
Can't render this file because it contains an unexpected character in line 72 and column 5.
+1
View File
@@ -3287,6 +3287,7 @@ antiAlias Sharp शार्प
Other Library… अन्य लाइब्रेरी…
Other Script… अन्य स्क्रिप्ट…
Out of Gamut Warning गैमट से बाहर होने की चेतावनी
Show Out-of-Gamut Colors गैमट से बाहर के रंग दिखाएँ
Out of Web Color Warning वेब कलर चेतावनी से बाहर
Out Tangent Handles आउट टैंगेंट हैंडल
Out: आउटपुट:
Can't render this file because it is too large.
+1
View File
@@ -2923,6 +2923,7 @@ file-filter Templates Sablonok
Other Library… Másik könyvtár…
Other Script… Másik szkript…
Out of Gamut Warning Színtartományon kívüli szín figyelmeztetés
Show Out-of-Gamut Colors Színtartományon kívüli színek megjelenítése
Out of Web Color Warning Nem webbiztos szín figyelmeztetés
Out Tangent Handles Kimenő érintőfogantyúk
Outer Corner Tile Külső sarokcsempe
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -1584,6 +1584,7 @@ digits Malayalam Malayalam
Create New Swatch… Buat swatch baru…
Name 40% Nama 40%
Out of Gamut Warning Peringatan di luar gamut
Show Out-of-Gamut Colors Tampilkan warna di luar gamut
Out of Web Color Warning Peringatan di luar warna web
Web Safe RGB RGB aman web
{warning}: click to correct to the closest color ({hex}) {warning}: klik untuk mengoreksi ke warna terdekat ({hex})
1 # Indonesian (id) catalog. Same format as zh-hant.tsv: context <TAB> source <TAB> translation
1584
1585
1586
1587
1588
1589
1590
+1
View File
@@ -2487,6 +2487,7 @@ file-filter Templates Modelli
Other Library… Altra libreria…
Other Script… Altro script…
Out of Gamut Warning Avviso fuori gamma
Show Out-of-Gamut Colors Mostra colori fuori gamma
Out of Web Color Warning Avviso colore non web
Out Tangent Handles Maniglie tangente in uscita
Outer Glow… Bagliore esterno…
Can't render this file because it is too large.
+1
View File
@@ -3946,6 +3946,7 @@ file-filter Templates テンプレート
Offset X X 軸オフセット
Other Libraries その他のライブラリ
Out of Gamut Warning 色域外警告
Show Out-of-Gamut Colors 色域外のカラーを表示
Out of Web Color Warning Web カラー外警告
Output 出力
Output Black 出力ブラック
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -1522,6 +1522,7 @@ digits Malayalam მალაიალამური
Create New Swatch… ახალი ფერის ნიმუშის შექმნა…
Name 40% სახელი 40%
Out of Gamut Warning ფერთა გამიდან გასვლის გაფრთხილება
Show Out-of-Gamut Colors ფერთა გამის გარეთ მყოფი ფერების ჩვენება
Out of Web Color Warning გაფრთხილება: ფერი ვებფერი არ არის
Web Safe RGB ვებისთვის უსაფრთხო RGB
{warning}: click to correct to the closest color ({hex}) {warning}: დაწკაპეთ უახლოეს ფერზე ჩასასწორებლად ({hex})
Can't render this file because it is too large.
+1
View File
@@ -3934,6 +3934,7 @@ file-filter Templates 템플릿
Offset X X 오프셋
Other Libraries 기타 라이브러리
Out of Gamut Warning 색상 범위 초과 경고
Show Out-of-Gamut Colors 색상 범위를 벗어난 색상 표시
Out of Web Color Warning 웹 색상 초과 경고
Output 출력
Output Black 출력 검정
Can't render this file because it is too large.
+1
View File
@@ -2102,6 +2102,7 @@ digits Malayalam Malayalam
Create New Swatch… Nieuw staal maken…
Name 40% Naam 40%
Out of Gamut Warning Waarschuwing buiten gamut
Show Out-of-Gamut Colors Kleuren buiten gamut tonen
Out of Web Color Warning Waarschuwing buiten webkleur
Web Safe RGB Websafe RGB
{warning}: click to correct to the closest color ({hex}) {warning}: klik om te corrigeren naar de dichtstbijzijnde kleur ({hex})
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -1590,6 +1590,7 @@ digits Malayalam Malajalam
Create New Swatch… Utwórz nową próbkę…
Name 40% Nazwa 40%
Out of Gamut Warning Ostrzeżenie: poza gamutem
Show Out-of-Gamut Colors Pokaż kolory poza gamutem
Out of Web Color Warning Ostrzeżenie: poza kolorami WWW
Web Safe RGB RGB bezpieczne dla WWW
{warning}: click to correct to the closest color ({hex}) {warning}: kliknij, aby poprawić na najbliższy kolor ({hex})
Can't render this file because it is too large.
+1
View File
@@ -5110,6 +5110,7 @@ axis Both Ambos
Opacity: Default Opacidade: Padrão
Other Libraries Outras Bibliotecas
Out of Gamut Warning Aviso de Fora do Gamut
Show Out-of-Gamut Colors Mostrar Cores Fora do Gamut
Out of Web Color Warning Aviso de Cor Fora da Web
Output Saída
Output Black Preto de Saída
Can't render this file because it is too large.
+1
View File
@@ -2474,6 +2474,7 @@ file-filter Templates Шаблоны
Other Library… Другая библиотека…
Other Script… Другая письменность…
Out of Gamut Warning Предупреждение о выходе из цветового охвата
Show Out-of-Gamut Colors Показать цвета вне цветового охвата
Out of Web Color Warning Предупреждение о цвете, не поддерживаемом web
Out Tangent Handles Маркеры исходящей касательной
Outer Glow… Внешнее свечение…
Can't render this file because it is too large.
+1
View File
@@ -2388,6 +2388,7 @@ font-technology Variable Variabla
Other Library… Annat bibliotek…
Other Script… Annat skript…
Out of Gamut Warning Färgomfångsvarning
Show Out-of-Gamut Colors Visa färger utanför färgomfånget
Out of Web Color Warning Varning för färg utanför webbfärger
Out Tangent Handles Utgående tangenthandtag
Outer Glow… Yttre glöd…
Can't render this file because it is too large.
+1
View File
@@ -2234,6 +2234,7 @@ shape Open Açık
Other Library… Diğer Kütüphane…
Other Script… Diğer Komut Dosyası…
Out of Gamut Warning Gamut Dışı Uyarısı
Show Out-of-Gamut Colors Gamut Dışı Renkleri Göster
Out of Web Color Warning Web Dışı Renk Uyarısı
Out Tangent Handles Dışarıya Teğet Tutamaçlar
Outer Glow… Dış Parıltı…
Can't render this file because it contains an unexpected character in line 5 and column 25.
+1
View File
@@ -2479,6 +2479,7 @@ file-filter Templates Шаблони
Other Library… Інша бібліотека…
Other Script… Інша писемність…
Out of Gamut Warning Попередження про вихід із колірного охоплення
Show Out-of-Gamut Colors Показати кольори поза колірним охопленням
Out of Web Color Warning Попередження про колір, що не підтримується web
Out Tangent Handles Маркери вихідної дотичної
Outer Glow… Зовнішнє свічення…
Can't render this file because it is too large.
+1
View File
@@ -2743,6 +2743,7 @@ digits Hindi Hindi
Other Library… Thư viện khác…
Other Script… Script khác…
Out of Gamut Warning Cảnh báo ngoài dải màu
Show Out-of-Gamut Colors Hiện màu ngoài dải màu
Out of Web Color Warning Cảnh báo ngoài màu web
Out Tangent Handles Tay nắm tiếp tuyến ra
Outer Corner Tile Ô góc ngoài
Can't render this file because it contains an unexpected character in line 204 and column 5.
+1
View File
@@ -2342,6 +2342,7 @@ file-filter Templates 模板
Other Library… 其他库…
Other Script… 其他脚本…
Out of Gamut Warning 超出色域警告
Show Out-of-Gamut Colors 显示超出色域的颜色
Out of Web Color Warning 非网页安全色警告
Out Tangent Handles 外切线控制手柄
Outer Glow… 外光晕…
Can't render this file because it is too large.
+1
View File
@@ -3558,6 +3558,7 @@ file-filter Templates 範本
Other Library… 其他資料庫…
Other Script… 其他指令碼…
Out of Gamut Warning 超出色域警告
Show Out-of-Gamut Colors 顯示超出色域的顏色
Out of Web Color Warning 非網頁安全色警告
Out Tangent Handles 外切線控制把手
Outer Glow… 外光暈…
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, gamut?: 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); gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; 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, gamut}",
),
(
"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_gamut;
#[cfg(test)]
mod tests_constrain;
#[cfg(test)]
mod tests_css_properties;
+103 -12
View File
@@ -11,11 +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`).
//!
//! Show Out-of-Gamut Colors grays out the cells of the wheel's square and the box's field whose
//! colors the CMYK space cannot print, by the out-of-gamut warning's test ([`Cms::out_of_gamut`]),
//! on a [`GAMUT_CELLS`] by [`GAMUT_CELLS`] grid kept until the channel, its value, the color
//! settings or the loaded profiles change.
use egui::{Ui, UiBuilder, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::cms::{self, Cms};
use vectorcraft_color::cms::{self, Cms, ColorSettings};
use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb};
use vectorcraft_doc::{ColorMode, NodeId};
@@ -67,6 +72,14 @@ pub struct Settings {
pub view: View,
#[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")]
pub channel: Channel,
/// Show Out-of-Gamut Colors: gray out the colors the CMYK space cannot print.
#[serde(deserialize_with = "deserialize_flag")]
pub gamut: bool,
}
fn deserialize_flag<'de, D: serde::Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
let v = <Value as Deserialize>::deserialize(d)?;
Ok(v.as_bool().unwrap_or_default())
}
fn deserialize_view<'de, D: serde::Deserializer<'de>>(d: D) -> Result<View, D::Error> {
@@ -90,11 +103,11 @@ 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
/// 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.
/// `ui.colorWheel {view?, channel?, gamut?}`: show the wheel or the box, pick the box's channel,
/// and show or hide the out-of-gamut shading. 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", "gamut"];
match p {
Value::Null => {}
Value::Object(o) => {
@@ -113,11 +126,19 @@ 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")?,
}
match p.get("gamut") {
None | Some(Value::Null) => {}
Some(v) => {
let key = "gamut";
set.gamut = v.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?;
}
}
app.ui.color_wheel = set;
Ok(json!(app.ui.color_wheel))
}
/// The panel menu: Wheel View and Box View, and Box Channel while the box shows.
/// The panel menu: Wheel View and Box View, Box Channel while the box shows, and Show
/// Out-of-Gamut Colors.
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
let set = app.ui.color_wheel.clone();
for (label, view) in [(tl!("Wheel View"), View::Wheel), (tl!("Box View"), View::Box)] {
@@ -134,6 +155,68 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
}
});
});
ui.separator();
if menu_item(ui, tl!("Show Out-of-Gamut Colors"), true, set.gamut) {
command(app, &json!({ "gamut": !set.gamut })).ok();
}
}
/// The cells across and down of the grid the out-of-gamut shading tests.
pub(crate) const GAMUT_CELLS: usize = 16;
/// The cells of a field whose colors are out of the CMYK gamut, a row per [`GAMUT_CELLS`] from the
/// top: bit `i` of a row is its cell `i` from the left.
pub(crate) type GamutGrid = [u16; GAMUT_CELLS];
/// The out-of-gamut cells of the box of channel `ch` at strip value `z` through `cms`, each tested
/// at its center by the out-of-gamut warning's test ([`Cms::out_of_gamut`]) on the color a pick
/// there stores in the working RGB space. The wheel's square is the box of [`Channel::Hue`] at the
/// ring's hue.
pub(crate) fn gamut_grid(cms: &Cms, ch: Channel, z: f32) -> GamutGrid {
let n = GAMUT_CELLS as f32;
let mut grid = [0; GAMUT_CELLS];
for (row, bits) in grid.iter_mut().enumerate() {
for col in 0..GAMUT_CELLS {
let (x, y) = ((col as f32 + 0.5) / n, (row as f32 + 0.5) / n);
// A gray has no hue, and the hue a gray keeps does not change its color.
let [r, g, b] = cms.srgb_to_rgb(hsb_to_rgb(box_pick(ch, z, x, y, [0.0; 3])));
if cms.out_of_gamut(&Color::rgb(r, g, b)) {
*bits |= 1 << col;
}
}
}
grid
}
/// What the out-of-gamut grid depends on: the channel, its value's bits, the color settings and
/// [`cms::profiles_generation`], which changes when a profile is loaded again under the same name.
pub(crate) type GamutKey = (Channel, u32, ColorSettings, u64);
/// The grid for `key` from `slot`, computed with `compute` and kept in `slot` when `slot` holds
/// another key's.
pub(crate) fn cached_grid(slot: &mut Option<(GamutKey, GamutGrid)>, key: GamutKey, compute: impl FnOnce() -> GamutGrid) -> GamutGrid {
match slot {
Some((k, grid)) if *k == key => *grid,
_ => {
let grid = compute();
*slot = Some((key, grid));
grid
}
}
}
/// Panel state: the out-of-gamut grid drawn last and its [`GamutKey`].
pub(crate) const GAMUT: &str = "color-wheel-gamut";
/// The out-of-gamut grid of channel `ch` at value `z` through `cms`, kept in the panel state so a
/// frame with the same channel, value, color settings and loaded profiles does not test the colors
/// again.
fn gamut_shade(ui: &Ui, cms: &Cms, ch: Channel, z: f32) -> GamutGrid {
let mut slot = pstate::<Option<(GamutKey, GamutGrid)>>(ui.ctx(), GAMUT);
let key = (ch, z.to_bits(), cms.settings().clone(), cms::profiles_generation());
let grid = cached_grid(&mut slot, key, || gamut_grid(cms, ch, z));
set_pstate(ui.ctx(), GAMUT, slot);
grid
}
/// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness,
@@ -180,16 +263,19 @@ fn strip_number(ch: Channel, hsb: [f32; 3]) -> (f64, &'static str, f64) {
}
/// The box in a `size` × `size` area: the field of channel `ch` and its strip, on HSB `hsb`, with
/// markers when `marked`. Returns the HSB a click, a drag, a key or a screen reader's action picks,
/// and its phase.
fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<([f32; 3], Live)> {
/// markers when `marked` and the field's out-of-gamut cells grayed out when `gamut`. Returns the
/// HSB a click, a drag, a key or a screen reader's action picks, and its phase.
fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32, gamut: Option<&Cms>) -> Option<([f32; 3], Live)> {
let (z, x, y) = box_pos(ch, hsb);
let mut pick = None;
let grid = gamut.map(|cms| gamut_shade(ui, cms, ch, z));
let shade = grid.as_ref().map_or(&[][..], |g| &g[..]);
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = STRIP_GAP;
let field = vec2((size - STRIP_GAP - STRIP).max(1.0), size);
let at = |x: f32, y: f32| widgets::hsb32(box_pick(ch, z, x, y, hsb));
if let (Some((x, y)), phase) = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at) {
let labels = (tl!("Color box"), ch.field_axes());
if let (Some((x, y)), phase) = widgets::color_field_shaded(ui, "color-wheel-box", labels, field, (x, y), marked, (&at, shade)) {
pick = Some((box_pick(ch, z, x, y, hsb), phase));
}
// The hue strip shows the whole spectrum; the others change only their own component.
@@ -310,6 +396,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
(c, _) => display_hsb(&cms, &c.unwrap_or(app.session.last_solid)),
};
let marked = color.is_some();
let gamut = app.ui.color_wheel.gamut.then_some(&*cms);
let mut pick: Option<([f32; 3], Live)> = None;
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
@@ -318,7 +405,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
});
let size = ui.available_width().min(MAX_WHEEL);
if app.ui.color_wheel.view == View::Box {
pick = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size);
pick = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size, gamut);
return;
}
let ring = widgets::hue_ring(ui, "color-wheel-ring", tl!("Hue ring"), size, hsb[0], marked);
@@ -328,7 +415,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
[FieldAxis { name: tl!("Saturation"), units: 100.0, suffix: "%" }, FieldAxis { name: tl!("Brightness"), units: 100.0, suffix: "%" }];
let at = |x: f32, y: f32| widgets::hsb32([hsb[0], x, 1.0 - y]);
let name = tl!("Saturation and brightness");
let (field, field_phase) = widgets::color_field(&mut field_ui, "field", (name, axes), square.size(), (hsb[1], 1.0 - hsb[2]), marked, &at);
// The square is the hue box at the ring's hue, so it shares the box's grid.
let grid = gamut.map(|cms| gamut_shade(ui, cms, Channel::Hue, box_pos(Channel::Hue, hsb).0));
let shade = grid.as_ref().map_or(&[][..], |g| &g[..]);
let pos = (hsb[1], 1.0 - hsb[2]);
let (field, field_phase) = widgets::color_field_shaded(&mut field_ui, "field", (name, axes), square.size(), pos, marked, (&at, shade));
if let Some((h, phase)) = ring.hue {
pick = Some(([h, hsb[1], hsb[2]], phase));
}
@@ -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", "gamut": false}));
assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue", "gamut": false}));
assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green", "gamut": 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", "gamut": 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, gamut");
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, gamut");
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,8 @@ 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 color_wheel = Settings { view: View::Box, channel: Channel::Blue, ..Default::default() };
let ui = crate::UiState { color_wheel, 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 +263,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, ..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,216 @@
//! The Color Wheel panel's Show Out-of-Gamut Colors: the grid of out-of-gamut cells, its cache, the
//! wheel's square and the box sharing it, `ui.colorWheel {gamut}`, the panel menu and the saved
//! setting.
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use vectorcraft_color::cms::{self, Cms, ColorSettings};
use vectorcraft_color::{Color, hsb_to_rgb};
use vectorcraft_engine::Session;
use super::color_wheel::{GAMUT, GAMUT_CELLS, GamutGrid, GamutKey, Settings, View, box_pick, cached_grid, gamut_grid, show};
use crate::VectorcraftApp;
use crate::dialogs::color_picker::Channel;
/// Whether cell `col` of row `row` (from the top-left) of `grid` is out of gamut.
fn marked(grid: &GamutGrid, col: usize, row: usize) -> bool {
(grid[row] >> col) & 1 == 1
}
/// An app with a selected rectangle filled with `fill`, its Color Wheel panel on `view` with Show
/// Out-of-Gamut Colors set to `gamut`.
fn app(fill: &str, view: &str, gamut: bool) -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
app.run("paint.setFill", json!({"color": fill})).unwrap();
app.run("ui.colorWheel", json!({"view": view, "channel": "hue", "gamut": gamut})).unwrap();
app
}
fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> {
let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app);
h.run_steps(2);
h
}
/// The grid the panel drew last, with its key.
fn drawn(h: &Harness<'static, VectorcraftApp>) -> Option<(GamutKey, GamutGrid)> {
super::pstate::<Option<(GamutKey, GamutGrid)>>(&h.ctx, GAMUT)
}
/// At hue 240° the field's top-right cell is nearly pure blue, which the CMYK space cannot print,
/// and its bottom-left cell is nearly black, which it can. Each cell is the color a pick at its
/// center stores, tested as the out-of-gamut warning tests it.
#[test]
fn the_hue_grid_marks_blue_and_leaves_black() {
let cms = Cms::default();
let grid = gamut_grid(&cms, Channel::Hue, 240.0 / 360.0);
let last = GAMUT_CELLS - 1;
assert!(marked(&grid, last, 0), "{grid:04x?}");
assert!(!marked(&grid, 0, last), "{grid:04x?}");
for row in 0..GAMUT_CELLS {
for col in 0..GAMUT_CELLS {
let n = GAMUT_CELLS as f32;
let hsb = box_pick(Channel::Hue, 240.0 / 360.0, (col as f32 + 0.5) / n, (row as f32 + 0.5) / n, [0.0; 3]);
let [r, g, b] = cms.srgb_to_rgb(hsb_to_rgb(hsb));
assert_eq!(marked(&grid, col, row), cms.out_of_gamut(&Color::rgb(r, g, b)), "cell {col}, {row}");
}
}
}
/// In the Blue box at full blue, the field's bottom-left cell (no red, no green) is nearly pure
/// blue.
#[test]
fn an_rgb_box_marks_its_own_cells() {
let grid = gamut_grid(&Cms::default(), Channel::Blue, 1.0);
assert!(marked(&grid, 0, GAMUT_CELLS - 1), "{grid:04x?}");
}
/// With uncalibrated CMYK as the CMYK space every color counts as printable, as the out-of-gamut
/// warning has it, so no cell is marked.
#[test]
fn uncalibrated_cmyk_marks_nothing() {
let cms = Cms::new(&ColorSettings { cmyk: cms::DEVICE_CMYK.into(), ..ColorSettings::default() }).unwrap();
assert_eq!(gamut_grid(&cms, Channel::Hue, 240.0 / 360.0), [0; GAMUT_CELLS]);
}
/// The cache computes a grid once per key: the same channel, value, color settings and profile
/// generation reuse it, and a change of any of them computes it again.
#[test]
fn the_cache_computes_once_per_key() {
let mut slot = None;
let mut runs = 0;
let settings = ColorSettings::default();
let mut get = |slot: &mut Option<(GamutKey, GamutGrid)>, key: GamutKey| {
cached_grid(slot, key, || {
runs += 1;
[runs; GAMUT_CELLS]
})
};
let key = (Channel::Hue, 0.5f32.to_bits(), settings.clone(), 0);
assert_eq!(get(&mut slot, key.clone()), [1; GAMUT_CELLS]);
assert_eq!(get(&mut slot, key.clone()), [1; GAMUT_CELLS], "the same key is not computed again");
assert_eq!(get(&mut slot, (Channel::Hue, 0.25f32.to_bits(), settings.clone(), 0)), [2; GAMUT_CELLS]);
assert_eq!(get(&mut slot, (Channel::Red, 0.25f32.to_bits(), settings.clone(), 0)), [3; GAMUT_CELLS]);
let device = ColorSettings { cmyk: cms::DEVICE_CMYK.into(), ..settings };
assert_eq!(get(&mut slot, (Channel::Red, 0.25f32.to_bits(), device.clone(), 0)), [4; GAMUT_CELLS]);
assert_eq!(get(&mut slot, (Channel::Red, 0.25f32.to_bits(), device, 1)), [5; GAMUT_CELLS], "a profile loaded again");
}
/// A profile loaded again under the same name can change which colors are printable while the
/// color settings stay the same, so the panel tests the colors again after a profile is
/// registered.
#[test]
fn the_grid_is_computed_again_after_a_profile_is_loaded() {
let mut h = harness(app("#3366cc", "box", true));
let Some((before, _)) = drawn(&h) else { panic!("the box drew no grid") };
let name = "Color Wheel Gamut Reload CMYK";
let bytes = cms::icc_bytes(cms::GENERIC_CMYK).unwrap();
cms::register_icc(&bytes, Some(name.into())).unwrap();
h.run_steps(2);
cms::unregister_icc(name);
let Some((after, _)) = drawn(&h) else { panic!("the box drew no grid") };
assert_eq!((after.0, after.1, &after.2), (before.0, before.1, &before.2));
assert!(after.3 > before.3, "the key follows the loaded profiles: {} then {}", before.3, after.3);
}
/// The wheel's square is the hue box at the ring's hue: both draw the same grid, under one key, so
/// a switch between them does not test the colors again.
#[test]
fn the_wheel_and_the_hue_box_shade_the_same_cells() {
let mut h = harness(app("#3366cc", "wheel", true));
let cms = cms::active();
let Some((key, grid)) = drawn(&h) else { panic!("the wheel drew no grid") };
let z = f32::from_bits(key.1);
assert_eq!((key.0, &key.2), (Channel::Hue, cms.settings()));
assert!((z * 360.0 - 220.0).abs() < 0.5, "the ring's hue: {}", z * 360.0);
assert_eq!(grid, gamut_grid(&cms, Channel::Hue, z));
h.state_mut().run("ui.colorWheel", json!({"view": "box"})).unwrap();
h.run_steps(2);
// Other tests in this process may register profiles between the frames, which changes the
// key's profile generation; the channel, value, settings and grid stay the same.
let Some((boxed, boxed_grid)) = drawn(&h) else { panic!("the box drew no grid") };
assert_eq!((boxed.0, boxed.1, &boxed.2, boxed_grid), (key.0, key.1, &key.2, grid));
}
/// With Show Out-of-Gamut Colors off, the panel tests no colors.
#[test]
fn with_the_setting_off_no_grid_is_computed() {
let h = harness(app("#3366cc", "box", false));
assert_eq!(drawn(&h), None);
}
/// `ui.colorWheel {gamut}` sets the setting and keeps the others; a value that is not true or
/// false is an error that changes nothing, translated where messages are.
#[test]
fn ui_color_wheel_sets_gamut() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("ui.colorWheel", json!({"view": "box"})).unwrap();
assert_eq!(app.run("ui.colorWheel", json!({"gamut": true})).unwrap(), json!({"view": "box", "channel": "hue", "gamut": true}));
let e = app.run("ui.colorWheel", json!({"view": "wheel", "gamut": "yes"})).unwrap_err();
assert_eq!(e, "`gamut` must be true or false");
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, gamut: true, ..Default::default() }, "an error changes nothing");
assert_eq!(app.run("ui.colorWheel", json!({"gamut": null})).unwrap()["gamut"], json!(true), "null keeps the value");
assert_eq!(app.run("ui.colorWheel", json!({"gamut": false})).unwrap()["gamut"], json!(false));
for code in ["de", "fr", "ja", "zh-hans"] {
let lang = crate::i18n::Lang::from_code(code).expect("registered");
let shown = crate::i18n::message(lang, &e);
assert_ne!(shown, e, "{code}");
assert!(shown.contains("`gamut`"), "{code}: {shown}");
}
}
/// The setting survives a JSON round trip of the preferences, and a saved value that is not true
/// or false reads as off without losing the other settings.
#[test]
fn the_gamut_setting_is_kept_and_read_leniently() {
let ui = crate::UiState { color_wheel: Settings { view: View::Box, gamut: true, ..Default::default() }, ..Default::default() };
let saved = serde_json::to_value(&ui).unwrap();
assert_eq!(saved["color_wheel"]["gamut"], json!(true));
let back: crate::UiState = serde_json::from_value(saved.clone()).unwrap();
assert_eq!(back.color_wheel, ui.color_wheel);
let mut odd = saved;
odd["color_wheel"] = json!({"view": "box", "channel": "red", "gamut": "yes"});
let back: crate::UiState = serde_json::from_value(odd).unwrap();
assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::Red, gamut: false });
}
/// The panel menu's Show Out-of-Gamut Colors is checked while the setting is on, and switches it.
#[test]
fn the_panel_menu_switches_the_shading() {
let app = app("#ff0000", "wheel", false);
let mut fonts = false;
let mut h = Harness::builder().with_size(vec2(260.0, 360.0)).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
// The fonts, which draw the check mark, take effect from the next frame.
if !fonts {
crate::theme::install_fonts(ui.ctx());
fonts = true;
return;
}
assert!(super::panel_menu_items(app, ui, super::color_wheel::ID));
},
app,
);
h.run_steps(3);
h.get_by_label(" Show Out-of-Gamut Colors").click();
h.run_steps(2);
assert!(h.state().ui.color_wheel.gamut);
assert!(h.query_by_label("✓ Show Out-of-Gamut Colors").is_some());
h.get_by_label("✓ Show Out-of-Gamut Colors").click();
h.run_steps(2);
assert!(!h.state().ui.color_wheel.gamut);
}
/// The edge runs between the marked cells and the others, inside the grid only, and bits past the
/// grid's width are not cells.
#[test]
fn the_edge_runs_between_marked_and_unmarked_cells() {
assert_eq!(crate::widgets::shade_edges(&[0b01, 0b00]), vec![[(1, 0), (1, 1)], [(0, 1), (1, 1)]]);
assert_eq!(crate::widgets::shade_edges(&[0b11, 0b11]), Vec::<[(usize, usize); 2]>::new(), "all marked");
assert_eq!(crate::widgets::shade_edges(&[0b100]), Vec::<[(usize, usize); 2]>::new(), "bit 2 is past a 1 × 1 grid");
assert_eq!(crate::widgets::shade_edges(&[]), Vec::<[(usize, usize); 2]>::new());
}
+1 -1
View File
@@ -734,7 +734,7 @@ pub struct UiState {
/// of an RGB field, `ui.colorPanel`, [`crate::panels::color::deserialize_rgb_percent`]).
#[serde(default, deserialize_with = "crate::panels::color::deserialize_rgb_percent")]
pub color_rgb_percent: bool,
/// Color Wheel panel: the wheel or the box, and the box's channel (`ui.colorWheel`,
/// Color Wheel panel: the wheel or the box, the box's channel and the out-of-gamut shading (`ui.colorWheel`,
/// [`crate::panels::color_wheel::deserialize_settings`]).
#[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")]
pub color_wheel: crate::panels::color_wheel::Settings,
+4 -2
View File
@@ -34,10 +34,12 @@ pub(crate) use buttons::{button_width, icon_button_info, primary_button_width, s
#[cfg(test)]
use chips::gradient_chip_colors;
pub use chips::{ProxyClicks, chip_button, chip_button_named, fill_stroke_proxy, gradient_chip, paint_chip, proxy_chip, swatch_tile};
#[cfg(test)]
pub(crate) use color::shade_edges;
pub use color::{
FieldAxis, Live, RingResponse, SliderValue, WheelResponse, channel_slider, channel_slider_named, channel_slider_stepped, channel_slider_valued,
color_field, color_mesh, color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named,
hsb32, hue_ring, region_texture, ring_square, segment_color, segmented_wheel, stepped_area,
color_field, color_field_shaded, color_mesh, color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel,
hex_field, hex_field_named, hsb32, hue_ring, region_texture, ring_square, segment_color, segmented_wheel, stepped_area,
};
pub(crate) use color::{HEX_FIELD_CHARS, hex_text, pointer_phase};
pub use drag::{
+66 -1
View File
@@ -383,11 +383,26 @@ fn focus_outline(ui: &Ui, resp: &Response, rect: Rect) {
pub fn color_field(
ui: &mut Ui,
id: impl std::hash::Hash,
(name, axes): (&str, [FieldAxis<'_>; 2]),
labels: (&str, [FieldAxis<'_>; 2]),
size: Vec2,
pos: (f32, f32),
marked: bool,
color_at: &dyn Fn(f32, f32) -> Color32,
) -> (Option<(f32, f32)>, Live) {
color_field_shaded(ui, id, labels, size, pos, marked, (color_at, &[]))
}
/// A [`color_field`] with the cells `shade` marks grayed out under its marker, each run of them
/// edged with a dark and a light line. `shade` holds a row of an n × n grid over the field for each
/// of its n rows (16 at most) from the top, and bit `i` of a row marks its cell `i` from the left.
pub fn color_field_shaded(
ui: &mut Ui,
id: impl std::hash::Hash,
(name, axes): (&str, [FieldAxis<'_>; 2]),
size: Vec2,
pos: (f32, f32),
marked: bool,
(color_at, shade): (&dyn Fn(f32, f32) -> Color32, &[u16]),
) -> (Option<(f32, f32)>, Live) {
use egui::accesskit::{Action, ActionData};
let t = Tokens::get(ui.ctx());
@@ -396,6 +411,7 @@ pub fn color_field(
focus_on_press(&resp);
let painter = ui.painter_at(rect.expand(6.0));
painter.add(color_mesh(rect, (32, 32), color_at));
shade_cells(&painter, rect, shade);
painter.rect_stroke(rect, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside);
focus_outline(ui, &resp, rect);
let (x, y) = pos;
@@ -446,6 +462,55 @@ pub fn color_field(
(None, Live::Idle)
}
/// The gray over a shaded cell of a [`color_field_shaded`].
const SHADE: Color32 = Color32::from_rgba_premultiplied(96, 96, 96, 192);
/// Whether cell `col` of row `row` of `shade` is marked; a cell outside the grid is not.
fn shaded(shade: &[u16], col: usize, row: usize) -> bool {
col < shade.len().min(16) && shade.get(row).is_some_and(|bits| (bits >> col) & 1 == 1)
}
/// The lines between the marked and the unmarked cells of `shade` (see [`color_field_shaded`]),
/// each from one grid point to the next, as (column, row) from the top-left corner.
pub(crate) fn shade_edges(shade: &[u16]) -> Vec<[(usize, usize); 2]> {
let n = shade.len().min(16);
let mut edges = Vec::new();
for row in 0..n {
for col in 0..n {
let here = shaded(shade, col, row);
if col + 1 < n && here != shaded(shade, col + 1, row) {
edges.push([(col + 1, row), (col + 1, row + 1)]);
}
if row + 1 < n && here != shaded(shade, col, row + 1) {
edges.push([(col, row + 1), (col + 1, row + 1)]);
}
}
}
edges
}
/// Gray out the cells `shade` marks over `rect`, and draw the lines between them and the others
/// dark under light.
fn shade_cells(painter: &egui::Painter, rect: Rect, shade: &[u16]) {
let n = shade.len().min(16);
if n == 0 {
return;
}
let cell = rect.size() / n as f32;
let at = |(col, row): (usize, usize)| rect.min + vec2(col as f32 * cell.x, row as f32 * cell.y);
for row in 0..n {
for col in (0..n).filter(|&col| shaded(shade, col, row)) {
painter.rect_filled(Rect::from_min_size(at((col, row)), cell), 0.0, SHADE);
}
}
let edges = shade_edges(shade);
for stroke in [Stroke::new(2.0, Color32::BLACK), Stroke::new(1.0, Color32::WHITE)] {
for [a, b] in &edges {
painter.line_segment([at(*a), at(*b)], stroke);
}
}
}
/// A smoothly shaded colour area: a `cols` × `rows` grid over `rect` with `color_at(x, y)` (0..1
/// each, y down) at its vertices.
pub fn color_mesh(rect: Rect, (cols, rows): (u32, u32), color_at: &dyn Fn(f32, f32) -> Color32) -> egui::Shape {
+3 -3
View File
@@ -265,9 +265,9 @@ My Themes tab lists the saved themes; every action runs a command (`colorTheme.s
Color Wheel panel (`window.panel {panel: "colorWheel"}`): a hue ring around a saturation and brightness square. A
pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint.setStroke` with `keepModel`,
`paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected
point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?}` shows the wheel or the box (a
color field with a channel strip at its right) and picks the box's channel; it returns the settings, and `ui.inspect`
reports them as `ui.color_wheel`.
point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, gamut?}` shows the wheel or
the box (a color field with a channel strip at its right), picks the box's channel, and with `gamut` grays out the
colors the CMYK space cannot print; it returns the settings, and `ui.inspect` reports them as `ui.color_wheel`.
Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/
`global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`,
+5 -3
View File
@@ -622,9 +622,11 @@ RGB fields in percent, as a double-click right of an RGB field does, and `false`
and answers true when the fields show in percent.
`ui.colorWheel {"view": "box", "channel": "red"}` shows the Color Wheel panel's box (a color field with the channel's
strip at its right) in place of the wheel, as the panel menu's Box View and Box Channel do, and `"view": "wheel"`
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.
shows the wheel again. `"gamut": true` grays out the parts of the wheel's square and the box's field whose colors
the CMYK space cannot print, as the panel menu's Show Out-of-Gamut Colors does, and `false` shows them again. The
test is the out-of-gamut warning's, which `color.gamutCheck` answers for one color. 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, gamut}`, and the settings are 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 -1
View File
@@ -1502,7 +1502,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels.
- **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 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. Show Out-of-Gamut Colors grays out the parts of the square and the box's field whose colors the CMYK space cannot print, by the out-of-gamut warning's test on a 16 by 16 grid (`ui.colorWheel {gamut}`). Scores and estimates are unchanged.
- **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`.