Color Settings: Blend Text Colors Using Gamma is a checkbox with a 1.00-3.00 field

Blend Text Colors Using Gamma was a 1.0 to 2.2 slider where 1.0 meant off, so turning it off and on lost a custom value. ColorSettings now keeps the field's value (blend_text_gamma, 1.00 to 3.00, two decimals) and the box (blend_text_gamma_on) apart; text_gamma() is what the compositor blends in (1 while the box is off), and the compositor takes up to 3.00. edit.colorSettings still takes a bool for blendTextGamma (the box alone) or a number in range (the value, and the box checked), plus blendTextGammaOn. The dialog shows the checkbox with the field beside it: typing a value checks the box, focusing does not, an out-of-range value alerts "A number between 1.00 and 3.00 is required. Closest value inserted." and an emptied field puts its value back. Settings saved as one number still load: 1 as the box off with 1.45, any other value as the box on with that value (#14243).
This commit is contained in:
qvest-ssels committed 2026-11-26 17:22:41 +01:00
1 parent 038d035110
commit ee10c0804e
14 files changed
+489 -34

No files matched your search

+4 -2
View File
@@ -314,18 +314,20 @@ fn normal_rgb(backdrop: [f32; 4], source: [f32; 4], as_: f32, ao: f32) -> [f32;
/// mix of the encoded values (psd-tools layer_effects.psd: a 69 % edge pixel of a blue overlay
/// over grey is 57/255 in red, an encoded mix gives 40).
pub const TEXT_GAMMA: f32 = 1.45;
/// The highest text blending gamma Color Settings takes (Photoshop's field runs 1.00–3.00).
pub const MAX_TEXT_GAMMA: f32 = 3.0;
static TEXT_GAMMA_SETTING: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0x3fb9_999a); // 1.45f32
/// Sets Color Settings › "Blend Text Colors Using Gamma" (1 = off). It is an application
/// setting, not stored in documents (1 here means switched off: a plain mix of the encoded
/// values). Values are clamped to Photoshop's 1.00–2.20.
/// values). Values are clamped to Photoshop's 1.00–3.00.
///
/// The value is process-wide: a test that changes it races every concurrently running test
/// that composites a type layer, so such tests belong in their own test binary (see
/// `crates/engine/tests/text_gamma.rs`).
pub fn set_text_gamma(gamma: f32) {
let g = if gamma.is_finite() { gamma.clamp(1.0, 2.2) } else { TEXT_GAMMA };
let g = if gamma.is_finite() { gamma.clamp(1.0, MAX_TEXT_GAMMA) } else { TEXT_GAMMA };
TEXT_GAMMA_SETTING.store(g.to_bits(), std::sync::atomic::Ordering::Relaxed);
}
+61 -10
View File
@@ -113,7 +113,7 @@ impl Policy {
/// Honoured when files are opened ([`ColorExt::open_document`](crate::color_cmds::ColorExt::open_document)), by Image › Mode conversions
/// and by "working" profile specs (Convert to Profile, Proof Setup).
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(default, rename_all = "camelCase")]
#[serde(default, rename_all = "camelCase", remote = "Self")]
pub struct ColorSettings {
/// Working spaces: built-in profile ids (see `edit.profileInfo`) or `.icc` paths.
pub working_rgb: String,
@@ -131,9 +131,13 @@ pub struct ColorSettings {
pub intent: String,
pub bpc: bool,
pub dither: bool,
/// Advanced › "Blend Text Colors Using Gamma" (1 = off; Photoshop's default 1.45): type
/// layers mix anti-aliased edges in this gamma (`photocraft_compose::psblend::set_text_gamma`).
/// Advanced › "Blend Text Colors Using Gamma": the field's value, 1.00 to 3.00 (Photoshop's
/// default 1.45). While [`blend_text_gamma_on`](Self::blend_text_gamma_on) is set, type layers
/// mix anti-aliased edges in this gamma ([`text_gamma`](Self::text_gamma),
/// `photocraft_compose::psblend::set_text_gamma`); the field keeps it while the box is off.
pub blend_text_gamma: f32,
/// Advanced › the "Blend Text Colors Using Gamma" checkbox (on by default).
pub blend_text_gamma_on: bool,
/// Working Spaces › Spot: the dot gain, in percent at a 50 % dot, that previews of spot
/// channels add (Photoshop's default Dot Gain 20 %; its menu offers 10–30 % and custom
/// values). Lives in the compositor too (`photocraft_compose::multichannel::set_spot_dot_gain`).
@@ -163,6 +167,7 @@ impl Default for ColorSettings {
bpc: true,
dither: true,
blend_text_gamma: photocraft_compose::psblend::TEXT_GAMMA,
blend_text_gamma_on: true,
spot_dot_gain: photocraft_compose::multichannel::SPOT_DOT_GAIN,
monitor_profile: "auto".into(),
// PhotoCraft's defaults match none of the named setups.
@@ -278,6 +283,7 @@ pub fn preset_setup(from: &ColorSettings, name: &str, monitor_rgb: &str) -> Opti
bpc: true,
dither: true,
blend_text_gamma: photocraft_compose::psblend::TEXT_GAMMA,
blend_text_gamma_on: true,
spot_dot_gain: p.spot,
preset: p.name.into(),
// The rest (the monitor profile) is not part of a setup. A setting a setup does
@@ -301,7 +307,38 @@ fn same_setup(a: &ColorSettings, b: &ColorSettings) -> bool {
&& (&a.intent, a.bpc, a.dither) == (&b.intent, b.bpc, b.dither)
}
/// The lowest text blending gamma the field takes; 1 also mixes the encoded values, as the box off does.
pub const MIN_TEXT_GAMMA: f32 = 1.0;
impl serde::Serialize for ColorSettings {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
ColorSettings::serialize(self, serializer)
}
}
impl<'de> serde::Deserialize<'de> for ColorSettings {
/// Reads the settings, and settings saved before the checkbox (#14243): those held one number,
/// `blendTextGamma`, with 1 meaning off. A 1 there loads as the box off with 1.45 in the
/// field, any other number as the box on with that number.
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
let raw = Value::deserialize(deserializer)?;
let legacy = raw.as_object().is_some_and(|m| m.contains_key("blendTextGamma") && !m.contains_key("blendTextGammaOn"));
let mut settings = ColorSettings::deserialize(raw).map_err(serde::de::Error::custom)?;
if legacy && settings.blend_text_gamma <= MIN_TEXT_GAMMA {
settings.blend_text_gamma = photocraft_compose::psblend::TEXT_GAMMA;
settings.blend_text_gamma_on = false;
}
Ok(settings)
}
}
impl ColorSettings {
/// The gamma type layers blend their colours in: the field's value while the box is on, else 1
/// (a mix of the encoded values).
pub fn text_gamma(&self) -> f32 {
if self.blend_text_gamma_on { self.blend_text_gamma } else { 1.0 }
}
pub fn intent(&self) -> Intent {
Intent::parse(&self.intent).unwrap_or(Intent::RelativeColorimetric)
}
@@ -327,6 +364,10 @@ impl ColorSettings {
/// Check that each working space resolves to the right colour space and RGB can be both a
/// source and editing destination for the configured rendering intent.
pub fn validate_settings(c: &ColorSettings) -> std::result::Result<(), String> {
let g = c.blend_text_gamma;
if !(g.is_finite() && (MIN_TEXT_GAMMA..=photocraft_compose::psblend::MAX_TEXT_GAMMA).contains(&g)) {
return Err(format!("`blendTextGamma` {g} is not in {MIN_TEXT_GAMMA:.2}..{:.2}", photocraft_compose::psblend::MAX_TEXT_GAMMA));
}
for (space, spec) in [(ColorSpace::Rgb, &c.working_rgb), (ColorSpace::Cmyk, &c.working_cmyk), (ColorSpace::Gray, &c.working_gray)] {
let p = resolve_profile(spec, None, space_mode(space)).map_err(|e| e.to_string())?;
if p.color_space != space {
@@ -1487,18 +1528,28 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = str_of("intent") {
next.intent = Intent::parse(&v).map(|i| i.id().to_string()).unwrap_or(v);
}
// A bool is the checkbox alone (the field keeps its value); a number in range is the field's
// value and checks the box, as typing into the field does. `blendTextGammaOn` sets the box
// after that, so the dialog can send a value with the box off.
let max = f64::from(photocraft_compose::psblend::MAX_TEXT_GAMMA);
match p.get("blendTextGamma") {
Some(Value::Bool(false)) => next.blend_text_gamma = 1.0,
Some(Value::Bool(true)) => next.blend_text_gamma = photocraft_compose::psblend::TEXT_GAMMA,
Some(Value::Bool(on)) => next.blend_text_gamma_on = *on,
Some(v) => {
let g = v
.as_f64()
.filter(|g| (1.0..=2.2).contains(g))
.ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: "`blendTextGamma` must be 1.0..2.2 or a bool".into() })?;
next.blend_text_gamma = g as f32;
.filter(|g| (f64::from(MIN_TEXT_GAMMA)..=max).contains(g))
.ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`blendTextGamma` must be {MIN_TEXT_GAMMA:.2}..{max:.2} or a bool") })?;
// Two decimals, as the field shows it.
next.blend_text_gamma = ((g * 100.0).round() / 100.0) as f32;
next.blend_text_gamma_on = true;
}
None => {}
}
match p.get("blendTextGammaOn") {
Some(Value::Bool(on)) => next.blend_text_gamma_on = *on,
Some(_) => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "`blendTextGammaOn` must be a bool".into() }),
None => {}
}
if let Some(v) = p.get("spotDotGain") {
let max = f64::from(photocraft_compose::multichannel::MAX_SPOT_DOT_GAIN);
let g = v
@@ -1522,7 +1573,7 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
};
validate_settings(&next).map_err(|msg| EngineError::BadParams { cmd: cmd.into(), msg })?;
if next != s.color().settings {
photocraft_compose::psblend::set_text_gamma(next.blend_text_gamma);
photocraft_compose::psblend::set_text_gamma(next.text_gamma());
photocraft_compose::multichannel::set_spot_dot_gain(next.spot_dot_gain);
s.color_mut().settings = next;
// Persisted with the preferences.
@@ -1636,7 +1687,7 @@ pub fn specs() -> Vec<CommandSpec> {
"edit.colorSettings",
"Color Settings…",
["Edit"],
r##"{"preset":"Custom|Europe General Purpose 3|Europe Prepress 3|Europe Web/Internet 2|Monitor Color|Japan Color for Newspaper|Japan General Purpose 2|Japan Magazine Advertisement Color|Japan Prepress 2|Japan Web/Internet|North America General Purpose 2|North America Newspaper|North America Prepress 2|North America Web/Internet","workingRgb":"srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020","workingCmyk":"coated-cmyk|coated-fogra39","workingGray":"dot-gain-20-compat|sgray|gray-gamma-2.2","policyRgb":"preserve|convert|off","policyCmyk":"preserve|convert|off","policyGray":"preserve|convert|off","askOnMismatch":bool=true,"askOnPaste":bool=true,"askOnMissing":bool=false,"intent":"relative|perceptual|saturation|absolute","blendTextGamma":1.0..2.2|bool=1.45,"spotDotGain":0..49=20,"bpc":bool=true,"dither":bool=true,"monitorProfile":"auto|srgb|display-p3|adobe-rgb-compat|prophoto-compat|rec2020","reset":bool=false} (preset = the Settings menu: a named setup sets the working spaces, policies, Ask boxes and intent, Black Point Compensation and Dither on and Blend Text Colors Using Gamma 1.45, then the other params change those values; the reply's `preset` is that name while the values still match it, else Custom, as after any change made without `preset`; spotDotGain = the Spot working space: the dot gain, in % at a 50 % dot, that spot channel previews add, as Photoshop's Spot menu (Dot Gain 10–30 %, or a custom value); working spaces and the monitor profile also accept .icc paths; monitor `auto` = the main display's profile when the platform provides it, else sRGB; the reply's `monitorStatus` says which profile is in use and why: source auto|manual|fallback, reason)"##,
r##"{"preset":"Custom|Europe General Purpose 3|Europe Prepress 3|Europe Web/Internet 2|Monitor Color|Japan Color for Newspaper|Japan General Purpose 2|Japan Magazine Advertisement Color|Japan Prepress 2|Japan Web/Internet|North America General Purpose 2|North America Newspaper|North America Prepress 2|North America Web/Internet","workingRgb":"srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020","workingCmyk":"coated-cmyk|coated-fogra39","workingGray":"dot-gain-20-compat|sgray|gray-gamma-2.2","policyRgb":"preserve|convert|off","policyCmyk":"preserve|convert|off","policyGray":"preserve|convert|off","askOnMismatch":bool=true,"askOnPaste":bool=true,"askOnMissing":bool=false,"intent":"relative|perceptual|saturation|absolute","blendTextGamma":1.0..3.0|bool=1.45,"blendTextGammaOn":bool=true,"spotDotGain":0..49=20,"bpc":bool=true,"dither":bool=true,"monitorProfile":"auto|srgb|display-p3|adobe-rgb-compat|prophoto-compat|rec2020","reset":bool=false} (preset = the Settings menu: a named setup sets the working spaces, policies, Ask boxes and intent, Black Point Compensation and Dither on and Blend Text Colors Using Gamma 1.45, then the other params change those values; the reply's `preset` is that name while the values still match it, else Custom, as after any change made without `preset`; spotDotGain = the Spot working space: the dot gain, in % at a 50 % dot, that spot channel previews add, as Photoshop's Spot menu (Dot Gain 10–30 %, or a custom value); working spaces and the monitor profile also accept .icc paths; monitor `auto` = the main display's profile when the platform provides it, else sRGB; the reply's `monitorStatus` says which profile is in use and why: source auto|manual|fallback, reason)"##,
always,
color_settings,
true,
@@ -114,14 +114,15 @@ fn fresh_settings_are_custom() {
#[test]
fn a_scripted_setup_is_stored_and_reported() {
let mut s = crate::session();
// Blend Text Colors Using Gamma off: a scripted setup turns it back on at 1.45.
s.color_mut().settings.blend_text_gamma = 1.0;
// Blend Text Colors Using Gamma off at 1.8: a scripted setup turns it back on at 1.45.
s.color_mut().settings.blend_text_gamma = 1.8;
s.color_mut().settings.blend_text_gamma_on = false;
let r = s.execute(CMD, json!({"preset": "North America Prepress 2"})).unwrap();
assert_eq!(r["preset"], "North America Prepress 2");
let c = &s.color().settings;
assert_eq!(c.preset, "North America Prepress 2");
assert_eq!((c.working_rgb.as_str(), c.policy_rgb, c.ask_on_missing), ("adobe-rgb-compat", Policy::Preserve, true));
assert_eq!(c.blend_text_gamma, photocraft_compose::psblend::TEXT_GAMMA);
assert_eq!((c.blend_text_gamma, c.blend_text_gamma_on), (photocraft_compose::psblend::TEXT_GAMMA, true));
// Reading the settings again keeps the name.
assert_eq!(s.execute(CMD, json!({})).unwrap()["preset"], "North America Prepress 2");
// So does setting a value to what it already is, and changing the monitor profile.
+2 -2
View File
@@ -53,7 +53,7 @@ fn prefs_set(s: &mut Session, p: &Value) -> Result<Value> {
// `edit.colorSettings` sets them. Process-wide: only a colour change moves them, so another
// session's values survive this one's unrelated preferences.
if color_changed {
photocraft_compose::psblend::set_text_gamma(s.color().settings.blend_text_gamma);
photocraft_compose::psblend::set_text_gamma(s.color().settings.text_gamma());
photocraft_compose::multichannel::set_spot_dot_gain(s.color().settings.spot_dot_gain);
}
s.apply_prefs();
@@ -94,7 +94,7 @@ fn prefs_reset(s: &mut Session, p: &Value) -> Result<Value> {
}
s.prefs.edit(|_| ());
if path.is_none_or(|path| path == "colorSettings" || path.starts_with("colorSettings.")) {
photocraft_compose::psblend::set_text_gamma(s.color().settings.blend_text_gamma);
photocraft_compose::psblend::set_text_gamma(s.color().settings.text_gamma());
photocraft_compose::multichannel::set_spot_dot_gain(s.color().settings.spot_dot_gain);
}
s.apply_prefs();
+8 -1
View File
@@ -220,7 +220,14 @@ impl SavedPrefsExt for Session {
invalid.push(InvalidPref { keys: vec!["colorSettings".into(), "spotDotGain".into()], value: json!(gain) });
self.color_mut().settings.spot_dot_gain = photocraft_compose::multichannel::SPOT_DOT_GAIN;
}
photocraft_compose::psblend::set_text_gamma(self.color().settings.blend_text_gamma);
// A field value outside 1.00..3.00 (a hand-edited file) loads as the default, as an
// unreadable one does; `validate_settings` would refuse every later edit otherwise.
let gamma = self.color().settings.blend_text_gamma;
if !(gamma.is_finite() && (crate::color_cmds::MIN_TEXT_GAMMA..=photocraft_compose::psblend::MAX_TEXT_GAMMA).contains(&gamma)) {
invalid.push(InvalidPref { keys: vec!["colorSettings".into(), "blendTextGamma".into()], value: json!(gamma) });
self.color_mut().settings.blend_text_gamma = photocraft_compose::psblend::TEXT_GAMMA;
}
photocraft_compose::psblend::set_text_gamma(self.color().settings.text_gamma());
photocraft_compose::multichannel::set_spot_dot_gain(self.color().settings.spot_dot_gain);
self.prefs.edit(|p| *p = prefs);
self.load_presets_json(presets);
@@ -21,6 +21,8 @@ fn every_setup_runs_and_sets_the_compositor() {
let r = s.execute("edit.colorSettings", json!({"preset": name})).unwrap();
assert_eq!(r["preset"], name);
assert_eq!(r["settings"]["blendTextGamma"], json!(TEXT_GAMMA), "{name}");
assert_eq!(r["settings"]["blendTextGammaOn"], json!(true), "{name}");
assert_eq!(photocraft_compose::psblend::text_gamma(), TEXT_GAMMA, "{name}");
// The compositor follows the setup's Spot dot gain.
let spot = r["settings"]["spotDotGain"].as_f64().unwrap() as f32;
assert_eq!(spot_dot_gain(), spot, "{name}");
@@ -0,0 +1,148 @@
//! Color Settings › Blend Text Colors Using Gamma is a checkbox with a 1.00 to 3.00 field
//! (photocraft#14243): the box off keeps the field's value, a number in range sets the value and
//! checks the box, the compositor takes up to 3.00, and settings saved as one number (1 = off)
//! still load.
//!
//! In the `global_state` binary, beside `text_gamma.rs`: the text gamma is process-wide and would
//! change how other tests' type layers composite.
use photocraft_compose::psblend::{MAX_TEXT_GAMMA, TEXT_GAMMA, set_text_gamma, text_gamma};
use photocraft_engine::Session;
use photocraft_engine::color_cmds::{ColorExt, ColorSettings, MIN_TEXT_GAMMA};
use photocraft_engine::prefs::SavedPrefsExt;
use serde_json::{Value, json};
const CMD: &str = "edit.colorSettings";
/// The box and the field as the command reports them, the field in hundredths.
fn shown(r: &Value) -> (bool, i64) {
let s = &r["settings"];
(s["blendTextGammaOn"].as_bool().expect("the box"), (s["blendTextGamma"].as_f64().expect("the field") * 100.0).round() as i64)
}
#[test]
fn the_field_takes_1_to_3_with_two_decimals_and_checks_the_box() {
let _process = crate::lock(&crate::PROCESS);
let mut s = Session::new();
assert_eq!((MIN_TEXT_GAMMA, MAX_TEXT_GAMMA), (1.0, 3.0));
assert_eq!(shown(&s.execute(CMD, json!({})).unwrap()), (true, 145), "on at 1.45 by default");
for (gamma, hundredths) in [(1.0, 100), (3.0, 300), (2.5, 250), (1.234, 123), (2.996, 300)] {
s.execute(CMD, json!({"blendTextGamma": false})).unwrap();
let r = s.execute(CMD, json!({"blendTextGamma": gamma})).unwrap();
assert_eq!(shown(&r), (true, hundredths), "{gamma}: a number checks the box");
assert!((text_gamma() - hundredths as f32 / 100.0).abs() < 1e-6, "{gamma}: the compositor follows");
}
// The dialog sends the field and the box: a value with the box off keeps it off.
let r = s.execute(CMD, json!({"blendTextGamma": 2.2, "blendTextGammaOn": false})).unwrap();
assert_eq!(shown(&r), (false, 220));
assert_eq!(text_gamma(), 1.0, "the box off blends in gamma 1");
s.execute(CMD, json!({"reset": true})).unwrap();
}
#[test]
fn the_box_off_keeps_the_value_and_on_again_uses_it() {
let _process = crate::lock(&crate::PROCESS);
let mut s = Session::new();
s.execute(CMD, json!({"blendTextGamma": 2.8})).unwrap();
let r = s.execute(CMD, json!({"blendTextGamma": false})).unwrap();
assert_eq!(shown(&r), (false, 280));
assert_eq!(text_gamma(), 1.0);
let r = s.execute(CMD, json!({"blendTextGammaOn": true})).unwrap();
assert_eq!(shown(&r), (true, 280));
assert!((text_gamma() - 2.8).abs() < 1e-6, "2.8 is no longer clamped to 2.2");
s.execute(CMD, json!({"blendTextGammaOn": false})).unwrap();
let r = s.execute(CMD, json!({"blendTextGamma": true})).unwrap();
assert_eq!(shown(&r), (true, 280), "`true` checks the box and keeps the value");
s.execute(CMD, json!({"reset": true})).unwrap();
}
#[test]
fn bad_params_are_errors_and_change_nothing() {
let _process = crate::lock(&crate::PROCESS);
let mut s = Session::new();
s.execute(CMD, json!({"blendTextGamma": 1.8})).unwrap();
let before = s.color().settings.clone();
for bad in [
json!({"blendTextGamma": 0.99}),
json!({"blendTextGamma": 3.01}),
json!({"blendTextGamma": -1.45}),
json!({"blendTextGamma": 0}),
json!({"blendTextGamma": 9}),
json!({"blendTextGamma": 1e308}),
// A NaN or an infinity reaches JSON as null.
json!({"blendTextGamma": f64::NAN}),
json!({"blendTextGamma": f64::INFINITY}),
json!({"blendTextGamma": null}),
json!({"blendTextGamma": "1.8"}),
json!({"blendTextGamma": "on"}),
json!({"blendTextGamma": [1.8]}),
json!({"blendTextGamma": {"value": 1.8}}),
json!({"blendTextGammaOn": "yes"}),
json!({"blendTextGammaOn": 1}),
json!({"blendTextGammaOn": null}),
] {
assert!(s.execute(CMD, bad.clone()).is_err(), "{bad}");
assert_eq!(s.color().settings, before, "{bad}");
}
assert!((text_gamma() - 1.8).abs() < 1e-6);
s.execute(CMD, json!({"reset": true})).unwrap();
}
#[test]
fn the_compositor_clamps_to_1_to_3() {
let _process = crate::lock(&crate::PROCESS);
for (set, read) in [(2.8, 2.8), (3.0, 3.0), (3.5, 3.0), (0.5, 1.0), (f32::NAN, TEXT_GAMMA), (f32::INFINITY, TEXT_GAMMA)] {
set_text_gamma(set);
assert!((text_gamma() - read).abs() < 1e-6, "{set} reads back {}", text_gamma());
}
set_text_gamma(TEXT_GAMMA);
}
#[test]
fn settings_saved_as_one_number_still_load() {
let _process = crate::lock(&crate::PROCESS);
// Before the checkbox, one number: 1 meant off.
let legacy = |gamma: Value| serde_json::from_value::<ColorSettings>(json!({"workingRgb": "srgb", "blendTextGamma": gamma})).unwrap();
let off = legacy(json!(1.0));
assert_eq!((off.blend_text_gamma_on, off.blend_text_gamma), (false, TEXT_GAMMA), "1 loads as the box off with 1.45");
assert_eq!(off.text_gamma(), 1.0);
let on = legacy(json!(1.8));
assert_eq!((on.blend_text_gamma_on, on.blend_text_gamma), (true, 1.8), "any other number loads as the box on with it");
let default = legacy(json!(1.45));
assert_eq!((default.blend_text_gamma_on, default.blend_text_gamma), (true, 1.45));
// Saved without the gamma at all: the defaults.
let none = serde_json::from_value::<ColorSettings>(json!({"workingRgb": "srgb"})).unwrap();
assert_eq!((none.blend_text_gamma_on, none.blend_text_gamma), (true, TEXT_GAMMA));
// Saved with the box: read as saved, 1.00 with the box on included.
let new = serde_json::from_value::<ColorSettings>(json!({"blendTextGamma": 1.0, "blendTextGammaOn": true})).unwrap();
assert_eq!((new.blend_text_gamma_on, new.blend_text_gamma), (true, 1.0));
// And they round-trip.
let saved = ColorSettings { blend_text_gamma: 2.4, blend_text_gamma_on: false, ..ColorSettings::default() };
assert_eq!(serde_json::from_value::<ColorSettings>(serde_json::to_value(&saved).unwrap()).unwrap(), saved);
// Through the settings file, into the session and the compositor.
let mut s = Session::new();
let invalid = s.load_prefs_json(r#"{"colorSettings": {"blendTextGamma": 1.0}}"#).unwrap();
assert!(invalid.is_empty(), "{invalid:?}");
assert_eq!((s.color().settings.blend_text_gamma_on, s.color().settings.blend_text_gamma), (false, TEXT_GAMMA));
assert_eq!(text_gamma(), 1.0);
// Turning the box on uses 1.45, not the old file's 1.
s.execute(CMD, json!({"blendTextGammaOn": true})).unwrap();
assert!((text_gamma() - TEXT_GAMMA).abs() < 1e-6);
s.load_prefs_json(r#"{"colorSettings": {"blendTextGamma": 2.0}}"#).unwrap();
assert_eq!((s.color().settings.blend_text_gamma_on, s.color().settings.blend_text_gamma), (true, 2.0));
assert!((text_gamma() - 2.0).abs() < 1e-6);
// The new format saves and loads both.
s.execute(CMD, json!({"blendTextGamma": 2.6, "blendTextGammaOn": false})).unwrap();
let file = s.prefs_to_json();
let mut reopened = Session::new();
reopened.load_prefs_json(&file).unwrap();
assert_eq!((reopened.color().settings.blend_text_gamma_on, reopened.color().settings.blend_text_gamma), (false, 2.6));
assert_eq!(text_gamma(), 1.0);
// A field value out of range (a hand-edited file) loads as 1.45 and is reported.
let invalid = reopened.load_prefs_json(r#"{"colorSettings": {"blendTextGamma": 7.0, "blendTextGammaOn": true}}"#).unwrap();
assert!(invalid.iter().any(|i| i.keys == ["colorSettings", "blendTextGamma"]), "{invalid:?}");
assert_eq!(reopened.color().settings.blend_text_gamma, TEXT_GAMMA);
assert!(reopened.execute(CMD, json!({"bpc": false})).is_ok(), "later edits are accepted");
s.execute(CMD, json!({"reset": true})).unwrap();
}
+1
View File
@@ -4,6 +4,7 @@
mod artboard_export_scratch;
mod color_settings_presets;
mod color_settings_text_gamma;
mod lut_row_cache_purge;
mod mask_cache_purge;
mod memory_gate;
+15 -7
View File
@@ -6,7 +6,7 @@
//! to the engine's unit tests let a concurrent test flatten one document under two gammas
//! (`canvas_geom::tests::turns_at_every_depth_and_mode` compares the composite before an edit
//! with the one after its undo, and failed on Windows CI that way). Keep any other test that
//! changes the gamma in this file.
//! changes the gamma in this file or in `color_settings_text_gamma.rs`.
use photocraft_engine::Session;
use photocraft_engine::color_cmds::ColorExt;
@@ -17,33 +17,41 @@ fn blend_text_gamma_setting() {
let _process = crate::lock(&crate::PROCESS);
let mut s = Session::new();
assert!((s.color().settings.blend_text_gamma - 1.45).abs() < 1e-6);
assert!(s.execute("edit.colorSettings", json!({"blendTextGamma": 3.0})).is_err());
assert!(s.color().settings.blend_text_gamma_on);
assert!(s.execute("edit.colorSettings", json!({"blendTextGamma": 3.01})).is_err());
// The compositor's (application-wide) gamma follows the setting.
s.execute("edit.colorSettings", json!({"blendTextGamma": 1.45})).unwrap();
assert!((photocraft_compose::psblend::text_gamma() - 1.45).abs() < 1e-6);
// The box off blends in gamma 1 and keeps the field's value.
let r = s.execute("edit.colorSettings", json!({"blendTextGamma": false})).unwrap();
assert_eq!(r["settings"]["blendTextGamma"], 1.0);
assert_eq!((r["settings"]["blendTextGamma"].as_f64().map(|g| (g * 100.0).round()), &r["settings"]["blendTextGammaOn"]), (Some(145.0), &json!(false)));
assert_eq!(photocraft_compose::psblend::text_gamma(), 1.0);
s.execute("edit.colorSettings", json!({"blendTextGamma": 1.8})).unwrap();
assert!((photocraft_compose::psblend::text_gamma() - 1.8).abs() < 1e-6);
s.execute("edit.colorSettings", json!({"blendTextGamma": false})).unwrap();
s.execute("edit.colorSettings", json!({"blendTextGamma": true})).unwrap();
assert!((s.color().settings.blend_text_gamma - 1.45).abs() < 1e-6);
assert!((photocraft_compose::psblend::text_gamma() - 1.45).abs() < 1e-6);
assert!((s.color().settings.blend_text_gamma - 1.8).abs() < 1e-6, "the box on again uses the field's value");
assert!((photocraft_compose::psblend::text_gamma() - 1.8).abs() < 1e-6);
// `prefs.set` and `prefs.reset` on `colorSettings` move the compositor's gamma too (#987).
// Same function, not a second test: tests in one binary run concurrently.
let in_sync = |s: &Session| (photocraft_compose::psblend::text_gamma() - s.color().settings.blend_text_gamma).abs() < 1e-6;
let in_sync = |s: &Session| (photocraft_compose::psblend::text_gamma() - s.color().settings.text_gamma()).abs() < 1e-6;
s.execute("edit.colorSettings", json!({"blendTextGamma": 1.8})).unwrap();
s.execute("prefs.set", json!({"path": "colorSettings.blendTextGammaOn", "value": false})).unwrap();
assert_eq!(photocraft_compose::psblend::text_gamma(), 1.0);
assert!(in_sync(&s));
s.execute("prefs.set", json!({"path": "colorSettings.blendTextGamma", "value": 1.0})).unwrap();
s.execute("prefs.set", json!({"path": "colorSettings.blendTextGammaOn", "value": true})).unwrap();
assert_eq!(photocraft_compose::psblend::text_gamma(), 1.0);
assert!(in_sync(&s));
s.execute("prefs.reset", json!({"path": "colorSettings.blendTextGamma"})).unwrap();
assert!((photocraft_compose::psblend::text_gamma() - 1.45).abs() < 1e-6);
assert!(in_sync(&s));
for reset in [json!({"path": "colorSettings"}), json!({})] {
s.execute("edit.colorSettings", json!({"blendTextGamma": 1.8})).unwrap();
s.execute("edit.colorSettings", json!({"blendTextGamma": 1.8, "blendTextGammaOn": false})).unwrap();
s.execute("prefs.reset", reset).unwrap();
assert!((photocraft_compose::psblend::text_gamma() - 1.45).abs() < 1e-6);
assert!(s.color().settings.blend_text_gamma_on);
assert!(in_sync(&s));
}
}
@@ -233,7 +233,7 @@ impl KeptComposites {
/// application setting, not part of the document. Read from the session's settings, which the
/// engine keeps in step with the process-wide value compose reads (`psblend::set_text_gamma`).
fn text_gamma(app: &PhotocraftApp) -> u32 {
app.session.color().settings.blend_text_gamma.to_bits()
app.session.color().settings.text_gamma().to_bits()
}
/// Bytes kept composites of document `doc` may hold: what Memory Usage leaves beside its pixels
@@ -59,8 +59,8 @@ fn opening_shows_the_stored_setup_and_keeps_its_values() {
#[test]
fn picking_a_setup_loads_it_but_keeps_the_text_gamma() {
// Blend Text Colors Using Gamma off (1.0) before the pick.
let mut app = app_with(ColorSettings { blend_text_gamma: 1.0, ..ColorSettings::default() });
// Blend Text Colors Using Gamma off, at 1.8, before the pick.
let mut app = app_with(ColorSettings { blend_text_gamma: 1.8, blend_text_gamma_on: false, ..ColorSettings::default() });
let id = open_dialog(&mut app, 1);
assert_eq!(fields(&app, id)["preset"], CUSTOM_SETTINGS, "PhotoCraft's defaults match no setup");
dialog_set(&mut app, id, "preset", json!("Europe Prepress 3"));
@@ -70,7 +70,8 @@ fn picking_a_setup_loads_it_but_keeps_the_text_gamma() {
assert_eq!((&f["workingRgb"], &f["workingCmyk"], &f["workingGray"]), (&json!("adobe-rgb-compat"), &json!("coated-fogra39"), &json!("dot-gain-20-compat")));
assert_eq!((&f["askOnMismatch"], &f["askOnPaste"], &f["askOnMissing"]), (&json!(true), &json!(true), &json!(true)));
assert!(same(&f["spotDotGain"], &json!(15.0)), "{}", f["spotDotGain"]);
assert!(same(&f["blendTextGamma"], &json!(1.0)), "kept: {}", f["blendTextGamma"]);
assert!(same(&f["blendTextGamma"], &json!(1.8)), "kept: {}", f["blendTextGamma"]);
assert_eq!(f["blendTextGammaOn"], json!(false), "the box is kept too");
}
#[test]
@@ -0,0 +1,182 @@
//! #14243: Color Settings' Blend Text Colors Using Gamma is a checkbox (on by default) with a
//! 1.00 to 3.00 field beside it. The field stays editable while the box is off; typing a value
//! checks the box, focusing the field alone does not. A value typed out of range alerts "A number
//! between 1.00 and 3.00 is required. Closest value inserted." and puts in the closest end; 1.234
//! becomes 1.23 without one; an empty field puts back its value. OK sends both, so the box off
//! keeps the value and on again uses it.
use craft::ui::dialog::DialogId;
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use egui::accesskit::{Role, Toggled};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use photocraft_engine::color_cmds::{ColorExt, ColorSettings};
use serde_json::{Value, json};
use crate::PhotocraftApp;
const COMMAND: &str = "edit.colorSettings";
const BOX: &str = "Blend Text Colors Using Gamma";
type H = Harness<'static, Box<PhotocraftApp>>;
/// Color Settings holding `settings`, opened from the menu and shown through `dialogs::run`.
fn dialog(settings: ColorSettings) -> (H, DialogId) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.session.color_mut().settings = settings;
let mut h = Harness::builder()
.with_size(egui::vec2(1440.0, 1100.0))
.with_step_dt(1.0 / 60.0)
.with_context(app.ctx().clone())
.build_ui_state(|ui, app: &mut Box<PhotocraftApp>| crate::dialogs::run(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, Default::default());
let ctx = h.ctx.clone();
let reply = crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap();
let want = reply["dialog"].as_str().unwrap().to_owned();
let id = h.state().framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|d| d.value().to_string() == want).unwrap();
h.run_steps(4);
(h, id)
}
fn fields(h: &H, id: DialogId) -> Value {
let form = h.state().framework.dialogs.get_by_id::<HostedParamDialog>(id).expect("Color Settings is open");
serde_json::to_value(form.fields()).unwrap()
}
/// The box and the field, the field in hundredths.
fn shown(h: &H, id: DialogId) -> (bool, i64) {
let f = fields(h, id);
(f["blendTextGammaOn"].as_bool().expect("the box"), (f["blendTextGamma"].as_f64().expect("the field") * 100.0).round() as i64)
}
fn checked(h: &H) -> bool {
h.get_by_role_and_label(Role::CheckBox, BOX).accesskit_node().toggled() == Some(Toggled::True)
}
/// The gamma field, on the checkbox's line.
fn field(h: &H) -> egui_kittest::Node<'_> {
let line = h.get_by_role_and_label(Role::CheckBox, BOX).rect();
let field = h.get_by_role_and_label(Role::SpinButton, BOX);
let at = field.rect().center();
assert!(at.y > line.top() - 4.0 && at.y < line.bottom() + 4.0 && at.x > line.right(), "the field is beside the checkbox");
field
}
/// `number` written with the decimal mark the fields read on this system.
fn local(number: &str) -> String {
let mark = craft::i18n::Region::system().decimal.filter(|c| *c == ',').unwrap_or('.');
number.replace('.', &mark.to_string())
}
fn focus_field(h: &mut H) {
field(h).click();
h.run_steps(2);
}
/// Types `text` over the field's value, then leaves it with Tab.
fn type_into(h: &mut H, text: &str) {
focus_field(h);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.run_steps(1);
if text.is_empty() {
h.key_press(egui::Key::Backspace);
} else {
h.event(egui::Event::Text(local(text)));
}
h.run_steps(1);
h.key_press(egui::Key::Tab);
h.run_steps(4);
}
/// The messages of the open alerts.
fn alerts(h: &H) -> Vec<String> {
h.state().framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(str::to_owned)).collect()
}
fn close_alert(h: &mut H) {
h.get_by_role(Role::AlertDialog).get_by_label("OK").click();
h.run_steps(4);
}
fn toggle_box(h: &mut H) {
h.get_by_role_and_label(Role::CheckBox, BOX).click();
h.run_steps(4);
}
fn confirm(h: &mut H, id: DialogId) {
crate::dialogs::testing::confirm(h.state_mut(), id).unwrap();
h.run_steps(2);
}
#[test]
fn a_checkbox_on_by_default_with_the_field_beside_it() {
let (h, id) = dialog(ColorSettings::default());
assert!(checked(&h), "on by default");
assert_eq!(shown(&h, id), (true, 145));
assert_eq!(field(&h).accesskit_node().numeric_value().map(|v| (v * 100.0).round()), Some(145.0), "1.45 in the field");
assert!(h.query_all_by_label("Blend Text Gamma").next().is_none(), "no slider row of the old name");
}
#[test]
fn the_box_off_keeps_the_value_and_on_again_uses_it() {
let (mut h, id) = dialog(ColorSettings { blend_text_gamma: 2.4, ..ColorSettings::default() });
toggle_box(&mut h);
assert!(!checked(&h));
assert_eq!(shown(&h, id), (false, 240), "the field keeps 2.40 while the box is off");
confirm(&mut h, id);
let c = h.state().session.color().settings.clone();
assert_eq!((c.blend_text_gamma_on, c.blend_text_gamma), (false, 2.4));
assert_eq!(c.text_gamma(), 1.0);
let (mut h, id) = dialog(c);
assert_eq!(shown(&h, id), (false, 240), "reopened with the box off and the value");
toggle_box(&mut h);
confirm(&mut h, id);
let c = &h.state().session.color().settings;
assert_eq!((c.blend_text_gamma_on, c.text_gamma()), (true, 2.4));
}
#[test]
fn typing_checks_the_box_and_focusing_alone_does_not() {
let (mut h, id) = dialog(ColorSettings { blend_text_gamma_on: false, ..ColorSettings::default() });
focus_field(&mut h);
h.key_press(egui::Key::Tab);
h.run_steps(4);
assert_eq!(shown(&h, id), (false, 145), "clicking into the field and tabbing out leaves the box off");
type_into(&mut h, "2.2");
assert_eq!(shown(&h, id), (true, 220), "the field is editable with the box off, and typing checks it");
assert!(checked(&h));
confirm(&mut h, id);
let c = &h.state().session.color().settings;
assert_eq!((c.blend_text_gamma_on, (c.blend_text_gamma * 100.0).round()), (true, 220.0));
}
#[test]
fn out_of_range_alerts_and_puts_in_the_closest_value() {
// "1.00" and "3.00" in the system's number format.
let message = format!("A number between {} and {} is required. Closest value inserted.", local("1.00"), local("3.00"));
for (typed, closest) in [("0", 100), ("9", 300), ("0.5", 100), ("3.01", 300)] {
let (mut h, id) = dialog(ColorSettings::default());
type_into(&mut h, typed);
assert_eq!(alerts(&h), std::slice::from_ref(&message), "{typed}");
assert_eq!(shown(&h, id).1, closest, "{typed}");
close_alert(&mut h);
assert!(alerts(&h).is_empty(), "{typed}: OK closes the alert");
assert_eq!(shown(&h, id).1, closest, "{typed}: the closest value stays");
}
// Two decimals: 1.234 is 1.23, with no alert.
let (mut h, id) = dialog(ColorSettings::default());
type_into(&mut h, "1.234");
assert!(alerts(&h).is_empty(), "{:?}", alerts(&h));
assert_eq!(shown(&h, id), (true, 123));
confirm(&mut h, id);
assert!((h.state().session.color().settings.blend_text_gamma - 1.23).abs() < 1e-6);
}
#[test]
fn an_empty_field_puts_back_its_value() {
let (mut h, id) = dialog(ColorSettings { blend_text_gamma: 1.8, ..ColorSettings::default() });
type_into(&mut h, "");
assert!(alerts(&h).is_empty(), "{:?}", alerts(&h));
assert_eq!(shown(&h, id), (true, 180));
}
@@ -380,6 +380,7 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec<
if let Some(p) = list.iter_mut().find(|p| p.key == "preset") {
*p = color_settings_presets::row(Label::from(tl!("Settings")));
}
color_settings_presets::text_gamma_rows(&mut list);
// The monitor line under the rows: the cell holds the text each frame refreshes, which the build closure cannot read from the app.
let note = crate::monitor_status::note_cell(app);
list.push(craft::ui::patterns::form_dialogs::Param::custom("monitorNote", craft::ui::runtime::env::Label::Empty, move |ui, _, _| {
@@ -5,13 +5,17 @@
//! The menu is a custom row ([`row`]); [`reconcile`] does the rest after each pass of the dialog
//! host and after each `ui.dialog.set`, so a confirm that follows a script's set sends the same
//! name and values a draw would have shown.
//!
//! Blend Text Colors Using Gamma is a checkbox beside a 1.00 to 3.00 field ([`text_gamma_rows`],
//! #14243).
use craft::ui::contract::{Bind, Entry, Outcome as _, Show as _};
use craft::ui::dialog::dialog_id;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param};
use craft::ui::dialog::{Alert, dialog_id};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamKind};
use craft::ui::pickers::Select;
use craft::ui::runtime::env::Label;
use photocraft_engine::color_cmds::{COLOR_SETTINGS_PRESETS, CUSTOM_SETTINGS, ColorExt, ColorSettings, is_settings_preset, preset_setup};
use craft::ui::runtime::env::{Env, Label};
use craft::ui::text::{NumberField, RangeAlert};
use photocraft_engine::color_cmds::{COLOR_SETTINGS_PRESETS, CUSTOM_SETTINGS, ColorExt, ColorSettings, MIN_TEXT_GAMMA, is_settings_preset, preset_setup};
use serde_json::{Map, Value, json};
use crate::PhotocraftApp;
@@ -29,7 +33,10 @@ const BASE: &str = "__presetBase";
/// The setup whose working RGB is the monitor profile.
const MONITOR_COLOR: &str = "Monitor Color";
/// What a setup leaves as the controls show it.
const KEPT: [&str; 2] = ["blendTextGamma", "monitorProfile"];
const KEPT: [&str; 3] = [GAMMA, GAMMA_ON, "monitorProfile"];
/// Blend Text Colors Using Gamma's field and checkbox.
const GAMMA: &str = "blendTextGamma";
const GAMMA_ON: &str = "blendTextGammaOn";
/// The menu entry `value` names (Custom for anything the menu doesn't have).
fn entry_of(value: Option<&str>) -> String {
@@ -57,10 +64,50 @@ pub(super) fn row(label: Label) -> Param {
})
}
/// Blend Text Colors Using Gamma, in place of the spec's two rows: the checkbox, with the field
/// beside it. The field shows two decimals, 1.00 to 3.00, and stays editable while the box is off;
/// a value typed or stepped into it checks the box. A value typed out of range is held to the
/// closest end with the range alert, written with the field's two decimals, which [`reconcile`]
/// opens; an emptied field puts its value back.
pub(super) fn text_gamma_rows(list: &mut Vec<Param>) {
list.retain(|p| p.key != GAMMA_ON);
let Some(at) = list.iter().position(|p| p.key == GAMMA) else { return };
let (min, max) = (f64::from(MIN_TEXT_GAMMA), f64::from(photocraft_compose::psblend::MAX_TEXT_GAMMA));
let default = f64::from(photocraft_compose::psblend::TEXT_GAMMA);
let label = Label::from(tl!("Blend Text Colors Using Gamma").to_string());
let on = Param::new(GAMMA_ON, label.clone(), ParamKind::bool(true)).beside_next();
let field = Param::custom(GAMMA, Label::Empty, move |ui, fields, _| {
let value = fields.number(GAMMA).filter(|v| v.is_finite()).unwrap_or(default);
let shown = NumberField::new(label.clone(), Bind::given(Some(value))).fixed_decimals(2).range(min..=max).step(0.01).show(ui);
if let Some(alert) = shown.out_of_range.clone() {
ui.ctx().data_mut(|d| d.insert_temp(gamma_alert_id(), Some((alert, Env::of(ui)))));
}
if let Some(v) = shown.edit.value().copied().flatten().filter(|v| v.is_finite()) {
fields.set(GAMMA, FieldValue::Number(((v * 100.0).round() / 100.0).clamp(min, max)));
fields.set(GAMMA_ON, FieldValue::Bool(true));
}
shown.edit.response.clone()
})
.opens_with(FieldValue::Number(default));
list.splice(at..=at, [on, field]);
}
/// Where the gamma field leaves its range alert for [`reconcile`], which can open it.
fn gamma_alert_id() -> egui::Id {
egui::Id::unique("pc-color-settings-gamma-alert")
}
/// Opens the gamma field's range alert, titled as the dialog.
fn show_gamma_alert(app: &mut PhotocraftApp, ctx: &egui::Context) {
let Some((alert, env)) = ctx.data_mut(|d| d.remove_temp::<Option<(RangeAlert, Env)>>(gamma_alert_id())).flatten() else { return };
let _ = crate::dialogs::alerts::show(app, Alert::range(tl!("Color Settings"), &alert, &env));
}
/// After a pass or a set: shows Custom for a name the menu doesn't have, loads a newly picked setup
/// (from the menu or `ui.dialog.set`), or shows Custom once a control differs from the values the
/// shown setup gave.
pub(crate) fn reconcile(app: &mut PhotocraftApp, ctx: &egui::Context) {
show_gamma_alert(app, ctx);
let Some(dialog) = app.framework.dialogs.get_by_id::<HostedParamDialog>(dialog_id(COMMAND)) else { return };
let f = fields_map(dialog.fields());
let shown = entry_of(f.get(KEY).and_then(Value::as_str));
@@ -194,3 +241,7 @@ fn same(a: &Value, b: &Value) -> bool {
#[cfg(test)]
#[path = "../color_settings_presets_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "../color_settings_text_gamma_tests.rs"]
mod text_gamma_tests;