mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
fix(color): an untagged document is shown in the working space
Edit > Color Settings' working RGB had no effect on a document without an embedded profile: composite_profile reads document_profile, whose fallback is the mode's built-in default (sRGB), and the canvas display cache keyed an untagged document with profile hash 0, so changing the working space did not even refresh an open document. ColorState now reads the untagged fallback from Color Settings for the two modes the ticket measures, and the display cache key carries the working space while a document is untagged. Convert to Profile (with and without dither), Image > Mode, the mismatch dialog's "convert to working" answer and Profile Info start from the same profile, so what the canvas shows and what a conversion writes agree. Tagged documents, and CMYK, Lab, Bitmap, Duotone, Indexed and Multichannel documents, resolve as they did. Tests: crates/engine-core/src/color_settings_untagged_display_tests.rs, ten tests; seven failed before the fix and all ten pass after it. The three that already passed pin the tagged-document, CMYK and command-reply guards. Fixes #14224
This commit is contained in:
1 parent
8303d38c60
commit
7ff04a0c0f
4 files changed
+439
-27
No files matched your search
@@ -3,8 +3,10 @@
|
||||
//! Colors / Gamut Warning) and the display transform the canvas applies.
|
||||
//!
|
||||
//! Document space: `Document::icc_profile` holds the document's ICC bytes (kept byte-exact
|
||||
//! from PSD resource 1039 / PNG iCCP / JPEG APP2 / TIFF). `None` means untagged: the working
|
||||
//! profile of the mode is assumed (sRGB, sGray, the built-in coated CMYK, Lab D50).
|
||||
//! from PSD resource 1039 / PNG iCCP / JPEG APP2 / TIFF). `None` means untagged: RGB and gray
|
||||
//! documents are then taken in the working space of Color Settings ([`ColorState::working`],
|
||||
//! sRGB and the default working gray unless the settings say otherwise, #14224), the other modes
|
||||
//! in the mode's built-in default (the built-in coated CMYK, Lab D50).
|
||||
//!
|
||||
//! Compositing stays in document space for RGB and gray documents. CMYK and Lab documents are
|
||||
//! composited in sRGB after a per-layer conversion with the built-in profiles (see
|
||||
@@ -111,7 +113,8 @@ impl Policy {
|
||||
|
||||
/// Edit › Color Settings: working spaces, colour management policies and conversion options.
|
||||
/// 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).
|
||||
/// and by "working" profile specs (Convert to Profile, Proof Setup). An untagged RGB or Grayscale
|
||||
/// document is taken in the working space as well, on screen and in conversions (#14224).
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase", remote = "Self")]
|
||||
pub struct ColorSettings {
|
||||
@@ -468,6 +471,45 @@ impl ColorState {
|
||||
}
|
||||
}
|
||||
|
||||
/// The profile an untagged document is taken in: Color Settings' working space for the two
|
||||
/// modes #14224 measures, otherwise the mode's built-in default, as [`working_profile`] gives.
|
||||
pub fn untagged_profile(&self, doc: &Document) -> Arc<Profile> {
|
||||
match doc.mode {
|
||||
ColorMode::Rgb | ColorMode::Grayscale => self.working(doc.mode),
|
||||
_ => working_profile(doc.mode),
|
||||
}
|
||||
}
|
||||
|
||||
/// The document's profile as this session sees it: [`document_profile`], except that an
|
||||
/// untagged RGB or Grayscale document falls back to Color Settings' working space instead of
|
||||
/// the mode's built-in default (#14224). A tagged document, and every other mode, resolve
|
||||
/// exactly as the free function does.
|
||||
pub fn document_profile(&self, doc: &Document) -> Arc<Profile> {
|
||||
embedded_profile(doc).unwrap_or_else(|| self.untagged_profile(doc))
|
||||
}
|
||||
|
||||
/// [`composite_profile`] as this session sees it: an untagged document's composite is
|
||||
/// described by the working space it is shown in (#14224).
|
||||
pub fn composite_profile(&self, doc: &Document) -> Arc<Profile> {
|
||||
match mode_space(doc.mode) {
|
||||
ColorSpace::Rgb => self.document_profile(doc),
|
||||
ColorSpace::Gray => {
|
||||
let p = self.document_profile(doc);
|
||||
// sGray is a TRC profile, so its RGB view always exists; sRGB is the last resort.
|
||||
p.gray_as_rgb().or_else(|| Builtin::SGray.profile().gray_as_rgb()).map(Arc::new).unwrap_or_else(|| Arc::new(Builtin::Srgb.profile().clone()))
|
||||
}
|
||||
_ => Arc::new(Builtin::Srgb.profile().clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The working-space spec Color Settings holds for `mode`, with the intent that spec is
|
||||
/// validated against: the cheap stand-in for [`Self::working`] in the display cache key,
|
||||
/// which runs on every frame and would otherwise clone the profile's tables (or read its
|
||||
/// `.icc` file) each time (#14224).
|
||||
pub fn working_space_spec(&self, mode: ColorMode) -> Option<&str> {
|
||||
self.settings.working_spec(mode_space(mode))
|
||||
}
|
||||
|
||||
/// Apply the colour management policy to a document being opened. Returns what happened
|
||||
/// (`action`: kept|converted|discarded|assigned|untagged) and whether to ask the user.
|
||||
///
|
||||
@@ -776,6 +818,11 @@ pub fn profile_from_bytes(bytes: &Arc<Vec<u8>>) -> std::result::Result<Arc<Profi
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// The document's embedded profile, when it parses and fits its mode.
|
||||
pub(crate) fn embedded_profile(doc: &Document) -> Option<Arc<Profile>> {
|
||||
doc.icc_profile.as_ref().and_then(|b| profile_from_bytes(b).ok()).filter(|p| p.color_space == mode_space(doc.mode))
|
||||
}
|
||||
|
||||
/// The document's profile: its embedded profile when it parses and matches the mode,
|
||||
/// otherwise the mode's working profile.
|
||||
pub fn document_profile(doc: &Document) -> Arc<Profile> {
|
||||
@@ -1059,13 +1106,23 @@ fn paint_colors(p: &mut FxPaint, cc: &mut dyn FnMut(&mut Color)) {
|
||||
/// converted. A Duotone document going to a colour space starts from its ink colours
|
||||
/// ([`ink_duotone`]). The document is tagged with `dst`.
|
||||
pub fn convert_document(doc: &mut Document, dst: &Profile, intent: Intent, bpc: bool) -> Result<()> {
|
||||
let untagged = working_profile(doc.mode);
|
||||
convert_document_from(doc, &untagged, dst, intent, bpc)
|
||||
}
|
||||
|
||||
/// [`convert_document`] with the profile an untagged document is taken in given explicitly: for a
|
||||
/// session that is Color Settings' working space, which the free function cannot know (#14224).
|
||||
/// Only that fallback changes: a document with a usable embedded profile converts from it, read
|
||||
/// after [`ink_duotone`] has turned a Duotone one into sRGB, exactly as [`convert_document`] does.
|
||||
pub fn convert_document_from(doc: &mut Document, untagged: &Profile, dst: &Profile, intent: Intent, bpc: bool) -> Result<()> {
|
||||
let to_mode = space_mode(dst.color_space).ok_or_else(|| EngineError::Other(format!("cannot convert to a {:?} profile", dst.color_space)))?;
|
||||
if to_mode != ColorMode::Grayscale {
|
||||
ink_duotone(doc);
|
||||
}
|
||||
let src = document_profile(doc);
|
||||
let embedded = embedded_profile(doc);
|
||||
let src: &Profile = embedded.as_deref().unwrap_or(untagged);
|
||||
let from_mode = doc.pixel_format().mode;
|
||||
let t = Transform::new(&src, dst, intent, bpc).map_err(cms_err)?;
|
||||
let t = Transform::new(src, dst, intent, bpc).map_err(cms_err)?;
|
||||
let fmt = PixelFormat::new(to_mode, doc.depth, true);
|
||||
crate::image_cmds::for_each_surface(&mut doc.layers, false, &mut |surf, _| {
|
||||
let f = PixelFormat { alpha: surf.format().alpha, ..fmt };
|
||||
@@ -1192,6 +1249,9 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result<Value
|
||||
}
|
||||
let intent = intent_or(p, s.color().settings.intent())?;
|
||||
let bpc = bool_param(p, "bpc", s.color().settings.bpc);
|
||||
// An untagged document starts in Color Settings' working space, the space the canvas shows it
|
||||
// in, not in the mode's built-in default (#14224).
|
||||
let untagged = s.color().untagged_profile(doc);
|
||||
if preserve_indexed_rgb {
|
||||
s.edit("Mode Change", |doc, _| {
|
||||
doc.mode = ColorMode::Rgb;
|
||||
@@ -1200,7 +1260,7 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result<Value
|
||||
Ok(())
|
||||
})?;
|
||||
} else {
|
||||
s.edit("Mode Change", |doc, _| convert_document(doc, &dst, intent, bpc))?;
|
||||
s.edit("Mode Change", |doc, _| convert_document_from(doc, &untagged, &dst, intent, bpc))?;
|
||||
}
|
||||
Ok(json!({ "profile": dst.description, "intent": intent.id(), "bpc": bpc }))
|
||||
}
|
||||
@@ -1372,8 +1432,11 @@ fn convert_to_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// or doesn't fit the mode is still replaced.
|
||||
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
|
||||
let measured = matches!(doc.mode, ColorMode::Rgb | ColorMode::Cmyk | ColorMode::Grayscale | ColorMode::Lab);
|
||||
let embedded = doc.icc_profile.as_ref().and_then(|b| profile_from_bytes(b).ok()).filter(|p| p.color_space == mode_space(doc.mode));
|
||||
let embedded = embedded_profile(doc);
|
||||
let same = measured && embedded.is_some_and(|p| p.same_colors(&dst));
|
||||
// The fallback for an untagged document is Color Settings' working space, the space it is
|
||||
// shown in (#14224); a tagged document keeps the embedded profile, as `document_profile` picks.
|
||||
let untagged = s.color().untagged_profile(doc);
|
||||
if same && !flatten && !rasterize {
|
||||
return Ok(json!({ "profile": dst.description, "mode": format!("{:?}", doc.mode), "intent": intent.id(), "bpc": bpc, "converted": false }));
|
||||
}
|
||||
@@ -1391,9 +1454,9 @@ fn convert_to_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
doc.icc_profile = Some(dst.to_bytes());
|
||||
Ok(())
|
||||
} else if dither {
|
||||
profile_dither::convert(doc, &dst, intent, bpc)
|
||||
profile_dither::convert(doc, &untagged, &dst, intent, bpc)
|
||||
} else {
|
||||
convert_document(doc, &dst, intent, bpc)
|
||||
convert_document_from(doc, &untagged, &dst, intent, bpc)
|
||||
}
|
||||
})?;
|
||||
let d = &s.active().ok_or(EngineError::NoDocument)?.doc;
|
||||
@@ -1410,7 +1473,7 @@ fn profile_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(profile_json(&prof))
|
||||
}
|
||||
None => doc.as_deref().map(|d| {
|
||||
let mut j = profile_json(&document_profile(d));
|
||||
let mut j = profile_json(&s.color().document_profile(d));
|
||||
j["embedded"] = json!(d.icc_profile.is_some());
|
||||
j
|
||||
}),
|
||||
@@ -1603,7 +1666,10 @@ fn profile_mismatch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"convert" | "convertToWorking" => {
|
||||
let dst = s.color().working(mode);
|
||||
let (intent, bpc) = (s.color().settings.intent(), s.color().settings.bpc);
|
||||
s.edit("Convert to Working RGB", |doc, _| convert_document(doc, &dst, intent, bpc))?;
|
||||
// An untagged document answers this dialog in its working space, not in the built-in
|
||||
// default (#14224); a tagged one keeps its embedded profile.
|
||||
let untagged = s.color().untagged_profile(&s.active().ok_or(EngineError::NoDocument)?.doc);
|
||||
s.edit("Convert to Working RGB", |doc, _| convert_document_from(doc, &untagged, &dst, intent, bpc))?;
|
||||
Ok(json!({"action": "converted", "profile": dst.description}))
|
||||
}
|
||||
"discard" | "off" => {
|
||||
@@ -1996,6 +2062,10 @@ mod assign_profile_enabled_modes_tests;
|
||||
#[path = "../color_settings_presets_tests.rs"]
|
||||
mod color_settings_presets_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../color_settings_untagged_display_tests.rs"]
|
||||
mod color_settings_untagged_display_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod settings_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -7,8 +7,8 @@ use photocraft_raster::Tile;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use super::{
|
||||
ColorMode, Document, EngineError, Intent, PixelFormat, Profile, Result, SampleType, Surface, Transform, cms_err, convert_color, convert_document,
|
||||
convert_layer_colors, convert_style_colors, convert_surface, document_profile, space_mode,
|
||||
ColorMode, Document, EngineError, Intent, PixelFormat, Profile, Result, SampleType, Surface, Transform, cms_err, convert_color, convert_document_from,
|
||||
convert_layer_colors, convert_style_colors, convert_surface, embedded_profile, space_mode,
|
||||
};
|
||||
|
||||
const TILE_PIXELS: u128 = (TILE_SIZE * TILE_SIZE) as u128;
|
||||
@@ -149,14 +149,17 @@ fn dither_tile(s: &Surface, out: &Surface, t: &Transform, bounds: Rect, c: TileC
|
||||
}
|
||||
|
||||
/// Preserve ordinary conversion outside opt-in U8, admitting the whole dither edit first.
|
||||
pub(super) fn convert(doc: &mut Document, dst: &Profile, intent: Intent, bpc: bool) -> Result<()> {
|
||||
let src = document_profile(doc);
|
||||
/// `untagged` is the profile an untagged document is taken in: Color Settings' working space,
|
||||
/// which only the session knows (#14224); a tagged document still converts from its embedded one.
|
||||
pub(super) fn convert(doc: &mut Document, untagged: &Profile, dst: &Profile, intent: Intent, bpc: bool) -> Result<()> {
|
||||
let embedded = embedded_profile(doc);
|
||||
let src: &Profile = embedded.as_deref().unwrap_or(untagged);
|
||||
if doc.depth != SampleType::U8 || src.to_bytes() == dst.to_bytes() || doc.mode == ColorMode::Duotone {
|
||||
return convert_document(doc, dst, intent, bpc);
|
||||
return convert_document_from(doc, untagged, dst, intent, bpc);
|
||||
}
|
||||
let to_mode = space_mode(dst.color_space).ok_or_else(|| EngineError::Other(format!("cannot convert to a {:?} profile", dst.color_space)))?;
|
||||
let from = doc.pixel_format().mode;
|
||||
let t = Transform::new(&src, dst, intent, bpc).map_err(cms_err)?;
|
||||
let t = Transform::new(src, dst, intent, bpc).map_err(cms_err)?;
|
||||
let format = PixelFormat::new(to_mode, doc.depth, true);
|
||||
let bounds = doc.bounds();
|
||||
if doc.size.width > i32::MAX as u32 || doc.size.height > i32::MAX as u32 {
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
//! #14224: an untagged document is displayed in the working space of Edit > Color Settings, not
|
||||
//! always in the mode's built-in default, and a change of that space refreshes an open document.
|
||||
//!
|
||||
//! The checks are relative: what the canvas must show is the transform our own engine builds for
|
||||
//! the profile Color Settings names ([`ColorState::working`]) to the monitor the session resolves,
|
||||
//! evaluated in this file. The reference application's absolute numbers for ProPhoto working RGB
|
||||
//! are its profile's tables, so they are reported rather than asserted here.
|
||||
//!
|
||||
//! Untagged documents only: a tagged one keeps its embedded profile, and CMYK keeps today's
|
||||
//! display (the issue leaves it unmeasured).
|
||||
|
||||
use super::*;
|
||||
use photocraft_doc::Size;
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
use crate::display_color::{DISPLAY_BPC, DISPLAY_INTENT};
|
||||
|
||||
/// Tolerance of the CPU canvas path against the transform evaluated here (8-bit quantisation plus
|
||||
/// table evaluation), as in `display_color/tests.rs`.
|
||||
const TOL: f32 = 2.0;
|
||||
|
||||
/// An untagged RGB document: one 4x4 block per entry of `values`, in columns.
|
||||
fn untagged_rgb(values: &[[f32; 3]], depth: SampleType) -> Document {
|
||||
let fmt = PixelFormat::new(ColorMode::Rgb, depth, true);
|
||||
let mut d = Document::new("t", Size::new(values.len() as u32 * 4, 4), ColorMode::Rgb, depth);
|
||||
let mut surf = Surface::new(fmt);
|
||||
for (i, v) in values.iter().enumerate() {
|
||||
let x = i as i32 * 4;
|
||||
surf.fill_rect(Rect::new(x, 0, x + 4, 4), &[v[0], v[1], v[2], 1.0]);
|
||||
}
|
||||
d.layers.push(Layer::new("pixels", LayerContent::Raster(surf)));
|
||||
d
|
||||
}
|
||||
|
||||
/// An RGB document tagged with `tag`.
|
||||
fn tagged_rgb(tag: &Profile, v: [f32; 3]) -> Document {
|
||||
let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::rgb(v[0], v[1], v[2]));
|
||||
d.icc_profile = Some(tag.to_bytes());
|
||||
d
|
||||
}
|
||||
|
||||
/// An untagged Grayscale document.
|
||||
fn untagged_gray(v: f32) -> Document {
|
||||
Document::with_background("g", Size::new(8, 8), ColorMode::Grayscale, SampleType::U8, Color::gray(v))
|
||||
}
|
||||
|
||||
/// A two-layer untagged CMYK document, so the composite goes through the compositor.
|
||||
fn untagged_cmyk(ink: [f32; 4]) -> Document {
|
||||
let fmt = PixelFormat::new(ColorMode::Cmyk, SampleType::U8, true);
|
||||
let mut d = Document::new("c", Size::new(8, 8), ColorMode::Cmyk, SampleType::U8);
|
||||
let mut surf = Surface::new(fmt);
|
||||
surf.fill_rect(Rect::new(0, 0, 8, 8), &[ink[0], ink[1], ink[2], ink[3], 1.0]);
|
||||
d.layers.push(Layer::new("ink", LayerContent::Raster(surf)));
|
||||
d.layers.push(Layer::new("empty", LayerContent::Raster(Surface::new(fmt))));
|
||||
d
|
||||
}
|
||||
|
||||
/// What the CPU canvas shows in the middle of column `i` of `d`, in 8-bit codes.
|
||||
fn shown(s: &Session, d: &Document, i: usize) -> [f32; 3] {
|
||||
let buf = photocraft_compose::flatten(d);
|
||||
let img = s.color().canvas_display(d).unwrap().to_rgba8(&buf);
|
||||
let x = (i as u32 * 4 + 2).min(d.size.width - 1);
|
||||
let y = d.size.height / 2;
|
||||
let k = (y as usize * d.size.width as usize + x as usize) * 4;
|
||||
[0, 1, 2].map(|c| img.pixels[k + c] as f32)
|
||||
}
|
||||
|
||||
/// The transform our engine builds from `src` to the session's monitor, evaluated at `v`: what the
|
||||
/// canvas has to show. Returns 8-bit codes.
|
||||
fn shown_want(s: &Session, src: &Profile, v: &[f32]) -> [f32; 3] {
|
||||
let monitor = s.color().monitor();
|
||||
let t = Transform::new(src, &monitor, DISPLAY_INTENT, DISPLAY_BPC).unwrap();
|
||||
let mut out = [0.0f32; 16];
|
||||
t.eval(v, &mut out).unwrap();
|
||||
let n = t.outputs();
|
||||
[0, 1, 2].map(|c| out[if n == 1 { 0 } else { c }].clamp(0.0, 1.0) * 255.0)
|
||||
}
|
||||
|
||||
fn close(a: [f32; 3], b: [f32; 3], tol: f32) -> bool {
|
||||
(0..3).all(|i| (a[i] - b[i]).abs() <= tol)
|
||||
}
|
||||
|
||||
fn far(a: [f32; 3], b: [f32; 3], d: f32) -> bool {
|
||||
(0..3).any(|i| (a[i] - b[i]).abs() >= d)
|
||||
}
|
||||
|
||||
fn raw_codes(v: &[f32]) -> [f32; 3] {
|
||||
[0, 1, 2].map(|c| v[c] * 255.0)
|
||||
}
|
||||
|
||||
/// The document's description as `edit.profileInfo` reports it.
|
||||
fn reported(s: &mut Session) -> Value {
|
||||
s.execute("edit.profileInfo", json!({})).unwrap()["profile"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untagged_rgb_document_is_displayed_in_the_working_space() {
|
||||
let mut s = crate::session();
|
||||
// The ticket's fixture: 200,30,30 and 30,60,200, profile removed.
|
||||
let values = [[200.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0], [30.0 / 255.0, 60.0 / 255.0, 200.0 / 255.0]];
|
||||
let d = untagged_rgb(&values, SampleType::U8);
|
||||
// Unchanged with the default settings: sRGB working RGB means the values go to the screen.
|
||||
let first = s.color().canvas_display(&d).unwrap();
|
||||
assert_eq!(first.source.description, Builtin::Srgb.profile().description, "the default working space is sRGB");
|
||||
assert!(first.is_identity(), "sRGB on an sRGB monitor still costs nothing");
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap();
|
||||
let working = s.color().working(ColorMode::Rgb);
|
||||
assert_eq!(working.description, Builtin::ProPhotoCompat.profile().description, "the setting resolved");
|
||||
let cd = s.color().canvas_display(&d).unwrap();
|
||||
assert_eq!(cd.source.description, working.description, "an untagged document is shown in Color Settings' working RGB");
|
||||
for (i, v) in values.iter().enumerate() {
|
||||
let got = shown(&s, &d, i);
|
||||
let want = shown_want(&s, &working, v);
|
||||
assert!(close(got, want, TOL), "column {i}: canvas {got:?} vs the working space's transform {want:?}");
|
||||
assert!(far(got, raw_codes(v), 8.0), "column {i} is still shown as its raw values: {got:?}");
|
||||
}
|
||||
// The reference application's measured numbers for this fixture, tolerance 2 as the ticket
|
||||
// states them: they match what our own ProPhoto-compatible profile computes.
|
||||
assert!(close(shown(&s, &d, 0), [255.0, 0.0, 34.0], 2.0), "200,30,30: {:?}", shown(&s, &d, 0));
|
||||
assert!(close(shown(&s, &d, 1), [0.0, 82.0, 223.0], 2.0), "30,60,200: {:?}", shown(&s, &d, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_the_working_space_refreshes_an_open_untagged_document() {
|
||||
let mut s = crate::session();
|
||||
let v = [0.8, 0.12, 0.12];
|
||||
let d = untagged_rgb(&[v], SampleType::U8);
|
||||
let before = s.color().canvas_display(&d).unwrap();
|
||||
let signature = s.color().display_signature(&d);
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": "adobe-rgb-compat"})).unwrap();
|
||||
let after = s.color().canvas_display(&d).unwrap();
|
||||
assert_eq!(after.source.description, s.color().working(ColorMode::Rgb).description);
|
||||
assert!(!Arc::ptr_eq(&before, &after), "the display cache handed back the entry made for the old working space");
|
||||
assert_ne!(before.key, after.key, "the cache entry and its signature have to move with the working space");
|
||||
assert_ne!(signature, s.color().display_signature(&d), "the canvas reloads the document without reopening it");
|
||||
assert_eq!(before.monitor.content_hash(), after.monitor.content_hash(), "only the working space moved");
|
||||
assert!(close(shown(&s, &d, 0), shown_want(&s, &after.source, &v), TOL), "{:?}", shown(&s, &d, 0));
|
||||
// Back to the default: the same entry as before, so the key follows the setting and not a counter.
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": "srgb"})).unwrap();
|
||||
let back = s.color().canvas_display(&d).unwrap();
|
||||
assert!(back.is_identity());
|
||||
assert_eq!(back.key, before.key, "the same settings give the same display");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untagged_document_stays_untagged_and_keeps_its_pixels() {
|
||||
let mut s = crate::session();
|
||||
let v = [200.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0];
|
||||
s.open_document(untagged_rgb(&[v], SampleType::U8), None);
|
||||
let before = reported(&mut s);
|
||||
assert_eq!(before["embedded"], json!(false));
|
||||
let sample = |s: &Session| s.active().unwrap().doc.layers[0].surface().unwrap().pixel(1, 1);
|
||||
let pixels = sample(&s);
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap();
|
||||
let after = reported(&mut s);
|
||||
assert_eq!(after["embedded"], json!(false), "the working space is not written into the document");
|
||||
assert_eq!(after["description"], Builtin::ProPhotoCompat.profile().description, "the document is taken in the working space");
|
||||
assert_eq!(sample(&s), pixels, "only the interpretation changes, not the stored samples");
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(close(shown(&s, d, 0), shown_want(&s, &s.color().working(ColorMode::Rgb), &v), TOL), "{:?}", shown(&s, d, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tagged_document_keeps_its_embedded_profile() {
|
||||
let mut s = crate::session();
|
||||
let v = [0.4, 0.6, 0.2];
|
||||
for tag in [Builtin::Srgb, Builtin::AdobeRgbCompat, Builtin::DisplayP3] {
|
||||
let d = tagged_rgb(tag.profile(), v);
|
||||
let before = s.color().canvas_display(&d).unwrap();
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap();
|
||||
let cd = s.color().canvas_display(&d).unwrap();
|
||||
assert_eq!(cd.source.content_hash(), tag.profile().content_hash(), "{} was replaced by the working space", tag.description());
|
||||
assert_eq!(cd.key, before.key, "a tagged document's display does not move with the setting");
|
||||
assert!(close(shown(&s, &d, 0), shown_want(&s, tag.profile(), &v), TOL), "{}: {:?}", tag.description(), shown(&s, &d, 0));
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": "srgb"})).unwrap();
|
||||
}
|
||||
// The command read-back of a tagged document is its own profile.
|
||||
s.open_document(tagged_rgb(Builtin::AdobeRgbCompat.profile(), v), None);
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap();
|
||||
let info = reported(&mut s);
|
||||
assert_eq!(info["embedded"], json!(true));
|
||||
assert_eq!(info["description"], Builtin::AdobeRgbCompat.profile().description);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untagged_grayscale_document_follows_the_working_gray() {
|
||||
let mut s = crate::session();
|
||||
let d = untagged_gray(0.3);
|
||||
let first = s.color().canvas_display(&d).unwrap();
|
||||
// The default working Gray is the built-in default, so nothing moves without a setting.
|
||||
assert_eq!(first.source.content_hash(), working_profile(ColorMode::Grayscale).gray_as_rgb().unwrap().content_hash());
|
||||
s.execute("edit.colorSettings", json!({"workingGray": "gray-gamma-2.2"})).unwrap();
|
||||
let working = s.color().working(ColorMode::Grayscale);
|
||||
assert_eq!(working.description, Builtin::GrayGamma22.profile().description, "the setting resolved");
|
||||
let cd = s.color().canvas_display(&d).unwrap();
|
||||
assert_eq!(cd.source.content_hash(), working.gray_as_rgb().unwrap().content_hash(), "an untagged gray document is shown in the working Gray");
|
||||
assert_ne!(cd.key, first.key, "and its display cache entry re-keys");
|
||||
assert!(close(shown(&s, &d, 0), shown_want(&s, &cd.source, &[0.3, 0.3, 0.3]), TOL), "{:?}", shown(&s, &d, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untagged_cmyk_document_keeps_todays_display() {
|
||||
let mut s = crate::session();
|
||||
let ink = [0.1, 0.6, 0.7, 0.05];
|
||||
let d = untagged_cmyk(ink);
|
||||
let before = shown(&s, &d, 0);
|
||||
let entry = s.color().canvas_display(&d).unwrap();
|
||||
s.execute("edit.colorSettings", json!({"workingCmyk": "coated-fogra39"})).unwrap();
|
||||
let cd = s.color().canvas_display(&d).unwrap();
|
||||
assert_eq!(cd.source.description, Builtin::Srgb.profile().description, "CMYK is not measured and keeps its sRGB composite");
|
||||
assert_eq!(cd.key, entry.key, "the working CMYK does not re-key an untagged CMYK document");
|
||||
assert!(close(shown(&s, &d, 0), before, 0.6), "its inks are still read through the built-in coated profile: {before:?} -> {:?}", shown(&s, &d, 0));
|
||||
// And the profile it is taken in stays the mode's built-in default even though the setting
|
||||
// now names another one: only RGB and Grayscale follow Color Settings here.
|
||||
assert_ne!(s.color().working(ColorMode::Cmyk).content_hash(), working_profile(ColorMode::Cmyk).content_hash(), "the setting really moved");
|
||||
assert_eq!(
|
||||
s.color().document_profile(&d).content_hash(),
|
||||
working_profile(ColorMode::Cmyk).content_hash(),
|
||||
"an untagged CMYK document keeps the mode default"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_rule_holds_at_every_depth() {
|
||||
let mut s = crate::session();
|
||||
let v = [0.8, 0.12, 0.12];
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap();
|
||||
let working = s.color().working(ColorMode::Rgb);
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let d = untagged_rgb(&[v], depth);
|
||||
let cd = s.color().canvas_display(&d).unwrap();
|
||||
assert_eq!(cd.source.description, working.description, "{depth:?}");
|
||||
let got = shown(&s, &d, 0);
|
||||
let want = shown_want(&s, &working, &v);
|
||||
let tol = if depth == SampleType::U8 { TOL } else { 1.0 };
|
||||
assert!(close(got, want, tol), "{depth:?}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conversion_starts_from_the_working_space() {
|
||||
let mut s = crate::session();
|
||||
let v = [200.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0];
|
||||
let filled = [v[0], v[1], v[2], 1.0];
|
||||
s.open_document(untagged_rgb(&[v], SampleType::U8), None);
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat"})).unwrap();
|
||||
let working = s.color().working(ColorMode::Rgb);
|
||||
let srgb = Builtin::Srgb.profile().clone();
|
||||
// What Convert to Profile has to write: the working space's own transform of the stored
|
||||
// samples, clamped the way the sample write clamps them (this colour is outside sRGB).
|
||||
let clamp3 = |o: &[f32; 16]| [o[0].clamp(0.0, 1.0), o[1].clamp(0.0, 1.0), o[2].clamp(0.0, 1.0)];
|
||||
let mut out = [0.0f32; 16];
|
||||
Transform::new(&working, &srgb, Intent::RelativeColorimetric, false).unwrap().eval(&v, &mut out).unwrap();
|
||||
let want = clamp3(&out);
|
||||
let mut built_in = [0.0f32; 16];
|
||||
let default = working_profile(ColorMode::Rgb);
|
||||
Transform::new(&default, &srgb, Intent::RelativeColorimetric, false).unwrap().eval(&v, &mut built_in).unwrap();
|
||||
assert!(
|
||||
want.iter().zip(clamp3(&built_in).iter()).any(|(a, b)| (a - b).abs() > 8.0 / 255.0),
|
||||
"the fixture must tell the working space apart from the built-in default: {want:?} vs {built_in:?}"
|
||||
);
|
||||
for dither in [false, true] {
|
||||
let r = s.execute("edit.convertToProfile", json!({"profile": "srgb", "intent": "relative", "bpc": false, "dither": dither})).unwrap();
|
||||
assert_eq!(r["converted"], json!(true), "dither {dither}");
|
||||
let px = s.active().unwrap().doc.layers[0].surface().unwrap().pixel(1, 1);
|
||||
assert!((0..3).all(|c| (px[c] - want[c]).abs() <= 2.0 / 255.0), "dither {dither}: {px:?} vs the working space's own conversion {want:?}");
|
||||
assert_eq!(reported(&mut s)["description"], srgb.description, "tagged with the destination");
|
||||
// Back to the untagged start for the second round.
|
||||
s.execute("edit.assignProfile", json!({"profile": "none"})).unwrap();
|
||||
s.edit("reset", |doc, _| {
|
||||
doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 4, 4), &filled);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mode_change_starts_from_the_working_space() {
|
||||
let mut s = crate::session();
|
||||
let v = [0.8, 0.12, 0.12];
|
||||
s.open_document(untagged_rgb(&[v], SampleType::U8), None);
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": "prophoto-compat", "workingGray": "gray-gamma-2.2"})).unwrap();
|
||||
let src = s.color().working(ColorMode::Rgb);
|
||||
let dst = s.color().working(ColorMode::Grayscale);
|
||||
let t = Transform::new(&src, &dst, Intent::RelativeColorimetric, false).unwrap();
|
||||
let from_built_in = {
|
||||
let built_in = working_profile(ColorMode::Rgb);
|
||||
Transform::new(&built_in, &dst, Intent::RelativeColorimetric, false).unwrap()
|
||||
};
|
||||
let mut out = [0.0f32; 16];
|
||||
let mut other = [0.0f32; 16];
|
||||
t.eval(&v, &mut out).unwrap();
|
||||
from_built_in.eval(&v, &mut other).unwrap();
|
||||
assert!((out[0] - other[0]).abs() > 1.0 / 255.0, "the fixture must tell the two sources apart: {out:?} vs {other:?}");
|
||||
s.execute("image.mode.grayscale", json!({"intent": "relative", "bpc": false})).unwrap();
|
||||
let px = s.active().unwrap().doc.layers[0].surface().unwrap().pixel(1, 1);
|
||||
assert!((px[0] - out[0]).abs() <= 2.0 / 255.0, "the mode change read the built-in default, not the working RGB: {px:?} vs {out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_profile_commands_answer_the_same_for_a_tagged_document() {
|
||||
let mut replies = Vec::new();
|
||||
for working in ["srgb", "prophoto-compat"] {
|
||||
let mut s = crate::session();
|
||||
s.open_document(tagged_rgb(Builtin::AdobeRgbCompat.profile(), [0.4, 0.6, 0.2]), None);
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": working})).unwrap();
|
||||
replies.push(json!({
|
||||
"info": reported(&mut s),
|
||||
"assign": s.execute("edit.assignProfile", json!({"profile": "display-p3"})).unwrap(),
|
||||
"info_after_assign": reported(&mut s),
|
||||
"convert": s.execute("edit.convertToProfile", json!({"profile": "srgb", "intent": "relative", "bpc": false})).unwrap(),
|
||||
"mode": s.execute("image.mode.grayscale", json!({"intent": "relative", "bpc": false})).unwrap(),
|
||||
"info_after_mode": reported(&mut s),
|
||||
}));
|
||||
}
|
||||
assert_eq!(replies[0], replies[1], "a tagged document's replies must not depend on the working space");
|
||||
}
|
||||
@@ -2,9 +2,10 @@
|
||||
//! monitor profile, on the GPU canvas (matrix/shaper or display 3D LUT) and the CPU canvas
|
||||
//! (an 8-bit transform of the composite).
|
||||
//!
|
||||
//! * The composite is in [`composite_profile`] (the document profile for RGB, its gray curve as
|
||||
//! * The composite is in `composite_profile` (the document profile for RGB, its gray curve as
|
||||
//! RGB for gray documents, sRGB for CMYK — read through the document's CMYK profile, see
|
||||
//! `photocraft_color::convert::CmykSpace` — and Lab).
|
||||
//! `photocraft_color::convert::CmykSpace` — and Lab). An untagged document has no profile of
|
||||
//! its own, and an untagged RGB or gray one is taken in Color Settings' working space (#14224).
|
||||
//! * Linear composites (EXR/HDR, linear profiles) are stored in the 8-bit canvas texture
|
||||
//! sRGB-encoded ([`CanvasDisplay::encode_srgb`]) so shadows keep their precision; the display
|
||||
//! source profile is then the same primaries with the sRGB curve.
|
||||
@@ -14,19 +15,21 @@
|
||||
//! * When the source and the monitor match (sRGB documents on an sRGB display, the common
|
||||
//! case) the transform is the identity and nothing is applied on either path.
|
||||
//!
|
||||
//! Results are cached per (document profile, mode, monitor profile); the rendering intent is
|
||||
//! relative colorimetric with black point compensation, as for Photoshop's monitor display.
|
||||
//! Results are cached per (document profile, mode, monitor profile) — plus the working space while
|
||||
//! the document is untagged, so a Color Settings change re-keys it (#14224); the rendering intent
|
||||
//! is relative colorimetric with black point compensation, as for Photoshop's monitor display.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use craft_cms::{Builtin, ColorSpace, Curve, Intent, Profile, Transform};
|
||||
use photocraft_color::ColorMode;
|
||||
use photocraft_compose::Buffer;
|
||||
use photocraft_doc::Document;
|
||||
use photocraft_raster::Rgba8Image;
|
||||
|
||||
use crate::color_cmds::{ColorState, composite_profile, mode_space, profile_from_bytes, resolve_profile};
|
||||
use crate::color_cmds::{ColorState, mode_space, profile_from_bytes, resolve_profile};
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// Display intent and black point compensation of the monitor transform.
|
||||
@@ -261,11 +264,15 @@ struct MonitorEntry {
|
||||
status: MonitorStatus,
|
||||
}
|
||||
|
||||
/// The canvas display cache key: colour space, document profile, monitor profile, and while the
|
||||
/// document is untagged the Color Settings working space it is shown in (#14224).
|
||||
type CanvasKey = (ColorSpace, u64, u64, Option<u64>);
|
||||
|
||||
/// Caches of [`ColorState`] for the display (monitor profiles per display, per-document displays).
|
||||
#[derive(Default)]
|
||||
pub struct DisplayCaches {
|
||||
monitor: Mutex<HashMap<Option<u32>, MonitorEntry>>,
|
||||
canvas: Mutex<HashMap<(ColorSpace, u64, u64), Arc<CanvasDisplay>>>,
|
||||
canvas: Mutex<HashMap<CanvasKey, Arc<CanvasDisplay>>>,
|
||||
}
|
||||
|
||||
impl ColorState {
|
||||
@@ -407,16 +414,30 @@ impl ColorState {
|
||||
}
|
||||
|
||||
/// How the canvas shows `doc` on `display` (cached per document profile, mode and monitor
|
||||
/// profile).
|
||||
/// profile; for an untagged document also per Color Settings' working space, which is the
|
||||
/// profile it is shown in).
|
||||
pub fn canvas_display_for(&self, doc: &Document, display: Option<u32>) -> Result<Arc<CanvasDisplay>> {
|
||||
let space = mode_space(doc.mode);
|
||||
let doc_hash = doc.icc_profile.as_ref().and_then(|b| profile_from_bytes(b).ok()).filter(|p| p.color_space == space).map_or(0, |p| p.content_hash());
|
||||
let embedded = crate::color_cmds::embedded_profile(doc);
|
||||
// An untagged RGB or Grayscale document is displayed in Color Settings' working space
|
||||
// (#14224), so the setting joins its key: the profile hash 0 that an untagged document
|
||||
// used before did not move when the working space did, and an open document kept the
|
||||
// display it was first shown with. The setting is hashed rather than the profile it
|
||||
// resolves to, because this runs on every frame and `working` would clone the profile's
|
||||
// tables (or read its `.icc` file) each time. Every other mode keeps the built-in default
|
||||
// and stays keyed 0.
|
||||
let working = if embedded.is_none() && matches!(doc.mode, ColorMode::Rgb | ColorMode::Grayscale) {
|
||||
Some(hash_of((self.working_space_spec(doc.mode), self.settings.intent().id())))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let doc_hash = embedded.map_or(0, |p| p.content_hash());
|
||||
let monitor = self.monitor_for(display);
|
||||
let key = (space, doc_hash, monitor.content_hash());
|
||||
let key: CanvasKey = (space, doc_hash, monitor.content_hash(), working);
|
||||
if let Some(d) = self.display.canvas.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
|
||||
return Ok(d.clone());
|
||||
}
|
||||
let composite = composite_profile(doc);
|
||||
let composite = self.composite_profile(doc);
|
||||
let encode_srgb = is_linear_rgb(&composite);
|
||||
let source = if encode_srgb { Arc::new(srgb_curve_twin(&composite)) } else { composite };
|
||||
let transform = if source.content_hash() == monitor.content_hash() {
|
||||
|
||||
Reference in new issue
Block a user