PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Monitor profile auto follows each window's display; what is applied is visible (#569) (#591)
Tibor-Florestan Pluto45bedb096295
diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rsindex a9a5d247e..a846d34c3 100644--- a/apps/photocraft/src/main.rs+++ b/apps/photocraft/src/main.rs@@ -137,7 +137,8 @@ fn main() -> eframe::Result {#[cfg(target_os = "macos")]let _tablet = tablet::install_macos(&stylus_feed);- // Read the main display's ICC profile while the window opens (colour-managed canvas).+ // Read the displays' ICC profiles while the window opens (colour-managed canvas; `None`+ // where the platform has no reader).let monitor = monitor_profile::detect_async();// Brush presets load in the background; the app attaches them when they arrive.let presets = services::presets_dir().map(photocraft_engine::preset_store::open_dir_async);@@ -194,8 +195,18 @@ fn main() -> eframe::Result {app.integrated_titlebar = cfg!(target_os = "macos");// Long commands and file opens run as background jobs with progress and Cancel (#210).app.background_jobs = std::env::var_os("PHOTOCRAFT_INLINE_JOBS").is_none();- if let Ok(Some(icc)) = monitor.recv_timeout(std::time::Duration::from_secs(2)) {- app.session.color.monitor_profile = Some(std::sync::Arc::new(icc));+ // Displays and their profiles (#569): wait briefly so the first frames already use+ // the right profile; a slower reading is applied when it arrives, and the shell reads+ // again when the displays may have changed.+ if let Some(rx) = monitor {+ app.services.read_displays = Some(std::sync::Arc::new(monitor_profile::detect_async));+ match rx.recv_timeout(std::time::Duration::from_secs(2)) {+ Ok(r) => photocraft_ui_egui::monitor_status::apply(&mut app, r),+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => photocraft_ui_egui::monitor_status::pending(&mut app, rx),+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {+ photocraft_ui_egui::monitor_status::apply(&mut app, Err("the display profile reader stopped without an answer".into()));+ }+ }}// Preferences › Performance › Use Graphics Processor (and the GPU backend: `cpu`// composites on the CPU).diff --git a/apps/photocraft/src/monitor_profile.rs b/apps/photocraft/src/monitor_profile.rsindex 08492c730..b351be0aa 100644--- a/apps/photocraft/src/monitor_profile.rs+++ b/apps/photocraft/src/monitor_profile.rs@@ -1,45 +1,145 @@-//! The main display's ICC profile, for the colour-managed canvas (Edit › Color Settings ›-//! Monitor Profile = `auto`).+//! The displays and their ICC profiles, for the colour-managed canvas (Edit › Color Settings ›+//! Monitor Profile = `auto`; #569).//!-//! macOS: `NSScreen.mainScreen.colorSpace.ICCProfileData`, a documented AppKit API, read through-//! `osascript` (AppleScriptObjC) so the app needs no `unsafe` FFI. The query runs on a background-//! thread at launch (about 0.4 s) and the profile is applied when it arrives. Other platforms-//! return `None` (sRGB, or the profile chosen in Color Settings).+//! macOS: every `NSScreen` with its `CGDirectDisplayID`, name, frame and+//! `colorSpace.ICCProfileData`, documented AppKit APIs read through `osascript` (AppKit via+//! AppleScriptObjC) so the app needs no `unsafe` FFI. A read takes about 0.4 s on a background+//! thread; the shell starts one at launch and again when the displays may have changed+//! (`photocraft_ui_egui::monitor_status`), and each window then uses the profile of the display+//! it is on. Other platforms report no displays (sRGB, or the profile chosen in Color Settings).use std::sync::mpsc::Receiver;-/// Starts reading the main display's profile in the background.-pub fn detect_async() -> Receiver<Option<Vec<u8>>> {+use photocraft_engine::display_color::Display;++/// What the platform reader returns: the displays, or why there are none.+pub type Detection = Result<Vec<Display>, String>;++/// Starts reading the displays in the background; `None` when the platform has no reader.+pub fn detect_async() -> Option<Receiver<Detection>> {+ if !cfg!(target_os = "macos") {+ return None;+ }let (tx, rx) = std::sync::mpsc::channel();std::thread::spawn(move || {let _ = tx.send(detect());});- rx+ Some(rx)}+/// One line per screen, primary (menu-bar) screen first: id, frame (x, y, width, height in+/// points, Cocoa's bottom-left origin), the profile as base64, the profile's name in System+/// Settings and the display's name, tab-separated. Numbers as integers (text conversion of+/// reals follows the user's locale, e.g. "0,0").#[cfg(target_os = "macos")]-fn detect() -> Option<Vec<u8>> {- let out = std::process::Command::new("/usr/bin/osascript")- .args([- "-e",- "use framework \"AppKit\"",- "-e",- "return ((current application's NSScreen's mainScreen()'s colorSpace()'s ICCProfileData()'s base64EncodedStringWithOptions:0) as text)",- ])- .stderr(std::process::Stdio::null())- .output()- .ok()?;- if !out.status.success() {- return None;+const SCRIPT: &str = r#"use framework "AppKit"+set out to ""+repeat with s in (current application's NSScreen's screens() as list)+ set f to s's frame()+ set n to ((s's deviceDescription()'s objectForKey:"NSScreenNumber") as integer)+ set icc to ""+ set cs to s's colorSpace()+ set csName to ""+ if cs is not missing value then+ set csName to ((cs's localizedName()) as text)+ set d to cs's ICCProfileData()+ if d is not missing value then set icc to ((d's base64EncodedStringWithOptions:0) as text)+ end if+ set out to out & n & tab & ((item 1 of item 1 of f) as integer) & tab & ((item 2 of item 1 of f) as integer) & tab & ((item 1 of item 2 of f) as integer) & tab & ((item 2 of item 2 of f) as integer) & tab & icc & tab & csName & tab & ((s's localizedName()) as text) & linefeed+end repeat+return out"#;++#[cfg(target_os = "macos")]+fn detect() -> Detection {+ let mut cmd = std::process::Command::new("/usr/bin/osascript");+ cmd.args(["-e", SCRIPT]);+ parse_reply(&run_helper(&mut cmd, HELPER_TIMEOUT)?)+}++/// How long a reading may take before the helper is stopped (it normally takes about 0.4 s).+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+const HELPER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);++/// Run the helper and return its standard output; a helper that fails, or runs longer than+/// `timeout`, is an error (and is killed and reaped), so a hung reading can't block later ones.+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+fn run_helper(cmd: &mut std::process::Command, timeout: std::time::Duration) -> Result<String, String> {+ use std::io::Read;+ use std::process::Stdio;+ let mut child =+ cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().map_err(|e| format!("couldn't run the display profile reader: {e}"))?;+ // Drain both pipes while waiting: a reply larger than the pipe buffer would otherwise block+ // the helper until the deadline.+ let drain = |p: Option<Box<dyn Read + Send>>| {+ std::thread::spawn(move || {+ let mut buf = Vec::new();+ if let Some(mut p) = p {+ let _ = p.read_to_end(&mut buf);+ }+ buf+ })+ };+ let out = drain(child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>));+ let err = drain(child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>));+ let deadline = std::time::Instant::now() + timeout;+ let status = loop {+ match child.try_wait() {+ Ok(Some(status)) => break status,+ Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(20)),+ Ok(None) => {+ let _ = child.kill();+ let _ = child.wait();+ return Err(format!("reading the display profiles took longer than {} s and was stopped", timeout.as_secs()));+ }+ Err(e) => {+ let _ = child.kill();+ let _ = child.wait();+ return Err(format!("waiting for the display profile reader failed: {e}"));+ }+ }+ };+ let out = out.join().unwrap_or_default();+ let err = err.join().unwrap_or_default();+ if !status.success() {+ let err = String::from_utf8_lossy(&err);+ let first = err.lines().next().unwrap_or("").trim();+ return Err(format!("reading the display profiles failed ({status}){}", if first.is_empty() { String::new() } else { format!(": {first}") }));}- let bytes = base64_decode(std::str::from_utf8(&out.stdout).ok()?.trim())?;- // An ICC profile starts with its size and carries `acsp` at offset 36.- (bytes.len() >= 132 && bytes.get(36..40) == Some(b"acsp")).then_some(bytes)+ Ok(String::from_utf8_lossy(&out).into_owned())}#[cfg(not(target_os = "macos"))]-fn detect() -> Option<Vec<u8>> {- None+fn detect() -> Detection {+ Err("this platform doesn't report display profiles".into())+}++/// The helper's reply ([`SCRIPT`]) → displays, frames flipped to a top-left origin with y down+/// (the coordinates window positions use). Lines that don't parse are skipped.+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+fn parse_reply(out: &str) -> Detection {+ let mut displays = Vec::new();+ let mut primary_height = None;+ for line in out.lines().filter(|l| !l.trim().is_empty()) {+ let f: Vec<&str> = line.splitn(8, '\t').collect();+ let [id, x, y, w, h, b64, profile_name, name] = f.as_slice() else { continue };+ let num = |s: &str| s.trim().parse::<f64>().ok().filter(|v| v.is_finite());+ let (Some(id), Some(x), Some(y), Some(w), Some(h)) = (id.trim().parse::<u32>().ok(), num(x), num(y), num(w), num(h)) else { continue };+ // Cocoa frames are relative to the primary screen's bottom-left corner, y up.+ let top = *primary_height.get_or_insert(h) - (y + h);+ let name = name.trim();+ let name = if name.is_empty() { format!("Display {id}") } else { name.to_string() };+ let b64 = b64.trim();+ // An ICC profile starts with its size and carries `acsp` at offset 36; anything else is+ // treated as no profile (the engine then says the display has none).+ let icc = (!b64.is_empty()).then(|| base64_decode(b64)).flatten().filter(|b| b.len() >= 132 && b.get(36..40) == Some(b"acsp"));+ let profile_name = Some(profile_name.trim().to_string()).filter(|n| !n.is_empty());+ displays.push(Display { id, name, frame: [x, top, w, h], profile_name, icc: icc.map(std::sync::Arc::new) });+ }+ if displays.is_empty() {+ let first = out.lines().next().unwrap_or("").trim();+ return Err(if first.is_empty() { "the display reader returned nothing".into() } else { format!("couldn't read the display list: {first}") });+ }+ Ok(displays)}/// Standard base64 (RFC 4648, with padding) → bytes; `None` on any invalid character.@@ -87,12 +187,71 @@ mod tests {assert!(base64_decode("a$==").is_none());}- /// The detected profile (when there is one) parses as an RGB profile.#[test]- fn detected_profile_parses() {- if let Some(bytes) = detect() {- let p = photocraft_engine::color_cmds::profile_from_bytes(&std::sync::Arc::new(bytes)).expect("parses");- assert_eq!(format!("{:?}", p.color_space), "Rgb", "{}", p.description);+ fn helper_replies() {+ // Only the ICC signature is checked here; parsing is the engine's job.+ let mut icc = vec![0u8; 132];+ icc[36..40].copy_from_slice(b"acsp");+ let b64 = base64_encode(&icc);+ // The #569 setup: built-in display primary, the external one right of it and higher up.+ let reply = format!(+ "1\t0\t0\t1728\t1117\t{b64}\tColor LCD\tBuilt-in Retina Display\n4\t1728\t92\t3008\t1692\t{b64}\tApple_Display_26-04-13.icc\tROG PG32UQX\n"+ );+ let d = parse_reply(&reply).unwrap();+ assert_eq!(d.len(), 2);+ assert_eq!((d[0].id, d[0].name.as_str(), d[0].frame), (1, "Built-in Retina Display", [0.0, 0.0, 1728.0, 1117.0]));+ assert_eq!((d[1].id, d[1].frame), (4, [1728.0, -667.0, 3008.0, 1692.0]));+ assert_eq!(d[1].profile_name.as_deref(), Some("Apple_Display_26-04-13.icc"));+ assert_eq!(d[1].icc.as_deref(), Some(&icc));+ // No profile, a bad profile, no name: kept, without a profile or with a fallback name.+ let d = parse_reply("2\t0\t0\t800\t600\t\t\t\n3\t800\t0\t800\t600\taGVsbG8=\tX\tY\n").unwrap();+ assert_eq!((d[0].name.as_str(), d[0].icc.is_none(), d[0].profile_name.is_none()), ("Display 2", true, true));+ assert!(d[1].icc.is_none());+ // Garbage lines are skipped; nothing usable is an error.+ assert_eq!(parse_reply("junk\n5\t0\t0\t10\t10\t\t\tZ").unwrap().len(), 1);+ assert!(parse_reply("").is_err());+ assert!(parse_reply("execution error: -1728").unwrap_err().contains("-1728"));+ }++ #[test]+ fn a_hung_helper_is_stopped_and_big_replies_dont_block() {+ let t0 = std::time::Instant::now();+ let e = run_helper(std::process::Command::new("/bin/sleep").arg("30"), std::time::Duration::from_millis(300)).unwrap_err();+ assert!(e.contains("took longer than"), "{e}");+ assert!(t0.elapsed() < std::time::Duration::from_secs(5), "killed at the deadline");+ // 1 MB on stdout (far beyond a pipe buffer) arrives whole.+ let big = run_helper(std::process::Command::new("/bin/sh").args(["-c", "head -c 1048576 /dev/zero | tr '\\0' a"]), std::time::Duration::from_secs(20))+ .unwrap();+ assert_eq!(big.len(), 1 << 20);+ let e = run_helper(std::process::Command::new("/bin/sh").args(["-c", "echo boom >&2; exit 3"]), std::time::Duration::from_secs(5)).unwrap_err();+ assert!(e.contains("boom"), "{e}");+ assert!(run_helper(&mut std::process::Command::new("/nonexistent/helper"), std::time::Duration::from_secs(1)).is_err());+ }++ fn base64_encode(b: &[u8]) -> String {+ const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ let mut s = String::new();+ for c in b.chunks(3) {+ let n = c.iter().enumerate().fold(0u32, |n, (i, v)| n | u32::from(*v) << (16 - 8 * i));+ for i in 0..=c.len() {+ s.push(A[(n >> (18 - 6 * i) & 63) as usize] as char);+ }+ }+ while !s.len().is_multiple_of(4) {+ s.push('=');+ }+ s+ }++ /// On a Mac, every display is read, and the profiles parse as RGB profiles.+ #[test]+ fn detected_displays_parse() {+ if let Ok(displays) = detect() {+ for d in displays {+ let Some(icc) = d.icc else { continue };+ let p = photocraft_engine::color_cmds::profile_from_bytes(&icc).expect("parses");+ assert_eq!(format!("{:?}", p.color_space), "Rgb", "{}: {}", d.name, p.description);+ }}}}diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/color_cmds.rsindex 555ca296b..675bba2a3 100644--- a/crates/engine/src/color_cmds.rs+++ b/crates/engine/src/color_cmds.rs@@ -199,9 +199,14 @@ pub struct ColorState {/// Edit › Color Settings (persisted with the preferences).pub settings: ColorSettings,proofs: HashMap<DocId, ProofView>,- /// The main display's ICC profile as read by the platform (used when Color Settings ›- /// Monitor Profile is `auto`; `None` = sRGB display).- pub monitor_profile: Option<Arc<Vec<u8>>>,+ /// The displays and their ICC profiles as read by the platform, primary (menu-bar) display+ /// first (used when Color Settings › Monitor Profile is `auto`; none = sRGB display).+ pub displays: Vec<crate::display_color::Display>,+ /// Whether `displays` was read, or why not (see [`ColorState::set_displays`]).+ pub monitor_detection: crate::display_color::MonitorDetection,+ /// The display showing the main window (set by the UI each frame; `None` = unknown, the+ /// primary display). Other windows pass their own display to the `*_for` methods.+ pub main_display: Option<u32>,display_cache: Mutex<HashMap<DisplayKey, Arc<Transform>>>,pub(crate) display: crate::display_color::DisplayCaches,/// View › 32-bit Preview Options per document.@@ -296,8 +301,13 @@ impl ColorState {/// the monitor, including the soft proof when View › Proof Colors is on. Cached per/// profile pair and proof settings.pub fn display_transform(&self, doc: &Document) -> Result<Arc<Transform>> {- let src = self.canvas_display(doc)?.source.clone();- let dst = self.monitor();+ self.display_transform_for(doc, self.main_display)+ }++ /// [`ColorState::display_transform`] to `display`'s monitor profile.+ pub fn display_transform_for(&self, doc: &Document, display: Option<u32>) -> Result<Arc<Transform>> {+ let src = self.canvas_display_for(doc, display)?.source.clone();+ let dst = self.monitor_for(display);let pv = self.proof(doc.id);let proof = pv.enabled.then(|| (pv.setup.profile.content_hash(), pv.setup.intent, pv.setup.bpc, pv.setup.simulate_paper));let key = (src.content_hash(), dst.content_hash(), proof);@@ -322,15 +332,16 @@ impl ColorState {/// The display transform as an `size³` RGBA 3D LUT (upload with/// [`Lut3d::to_rgba16f_bytes`] and apply in the canvas shader).pub fn display_lut(&self, doc: &Document, size: usize) -> Result<Lut3d> {- self.display_lut_with(doc, size, true)+ self.display_lut_with(doc, size, true, self.main_display)}- /// [`ColorState::display_lut`], with or without the 32-bit preview (exposure/gamma).- fn display_lut_with(&self, doc: &Document, size: usize, hdr: bool) -> Result<Lut3d> {- if let Some(lut) = crate::proof_sim::display_lut_with(self, doc, size, hdr)? {+ /// [`ColorState::display_lut`], with or without the 32-bit preview (exposure/gamma), for+ /// `display`.+ fn display_lut_with(&self, doc: &Document, size: usize, hdr: bool, display: Option<u32>) -> Result<Lut3d> {+ if let Some(lut) = crate::proof_sim::display_lut_with(self, doc, size, hdr, display)? {return Ok(lut);}- let t = self.display_transform(doc)?;+ let t = self.display_transform_for(doc, display)?;Ok(Lut3d::from_transform(&t, size))}@@ -346,24 +357,29 @@ impl ColorState {/// mapping canvas texture values to the monitor, whose alpha is 255 where the colour is out/// of the proof gamut (only with Gamut Warning on).pub fn canvas_lut(&self, doc: &Document, size: usize) -> Result<Option<Vec<u8>>> {- self.canvas_lut_with(doc, size, true)+ self.canvas_lut_with(doc, size, true, self.main_display)}/// [`ColorState::canvas_lut`] without the 32-bit preview, which the GPU canvas shader applies/// itself (see [`ColorState::hdr_preview`]) so that 32-bit values above 1.0, kept by its float/// texture, are exposed into range rather than clipped by the LUT's 0..1 domain.pub fn gpu_canvas_lut(&self, doc: &Document, size: usize) -> Result<Option<Vec<u8>>> {- self.canvas_lut_with(doc, size, false)+ self.gpu_canvas_lut_for(doc, size, self.main_display)+ }++ /// [`ColorState::gpu_canvas_lut`] for a window on `display`.+ pub fn gpu_canvas_lut_for(&self, doc: &Document, size: usize, display: Option<u32>) -> Result<Option<Vec<u8>>> {+ self.canvas_lut_with(doc, size, false, display)}- fn canvas_lut_with(&self, doc: &Document, size: usize, hdr: bool) -> Result<Option<Vec<u8>>> {+ fn canvas_lut_with(&self, doc: &Document, size: usize, hdr: bool, on: Option<u32>) -> Result<Option<Vec<u8>>> {let size = size.max(2);let pv = self.proof(doc.id);- let display = self.canvas_display(doc)?;+ let display = self.canvas_display_for(doc, on)?;if !pv.enabled && !pv.gamut_warning && !(hdr && crate::proof_sim::hdr_active(self, doc)) {return Ok(display.transform.as_ref().map(|t| Lut3d::from_transform(t, size).to_rgba8()));}- let lut = self.display_lut_with(doc, size, hdr)?;+ let lut = self.display_lut_with(doc, size, hdr, on)?;let mut bytes = lut.to_rgba8();let check = if pv.gamut_warning { Some(GamutCheck::new(&display.source, &pv.setup.profile, pv.gamut_threshold).map_err(cms_err)?) } else { None };let s = (size - 1) as f32;@@ -872,7 +888,9 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {"settings": c,"working": {"rgb": desc(ColorMode::Rgb), "cmyk": desc(ColorMode::Cmyk), "gray": desc(ColorMode::Grayscale)},"monitor": s.color.monitor().description,- "monitorDetected": s.color.monitor_profile.is_some(),+ "monitorDetected": !s.color.displays.is_empty(),+ "monitorStatus": s.color.monitor_status(),+ "displays": s.color.display_statuses(),}))}@@ -955,7 +973,7 @@ pub fn specs() -> Vec<CommandSpec> {"edit.colorSettings","Color Settings…",["Edit"],- r##"{"workingRgb":"srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020","workingCmyk":"coated-cmyk","workingGray":"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,"bpc":bool=true,"dither":bool=true,"monitorProfile":"auto|srgb|display-p3|adobe-rgb-compat|prophoto-compat|rec2020","reset":bool=false} (working spaces and the monitor profile also accept .icc paths; monitor `auto` = the main display's profile when the platform provides it, else sRGB)"##,+ r##"{"workingRgb":"srgb|display-p3|adobe-rgb-compat|prophoto-compat|linear-srgb|rec2020","workingCmyk":"coated-cmyk","workingGray":"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,"bpc":bool=true,"dither":bool=true,"monitorProfile":"auto|srgb|display-p3|adobe-rgb-compat|prophoto-compat|rec2020","reset":bool=false} (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,diff --git a/crates/engine/src/display_color.rs b/crates/engine/src/display_color.rsindex d5c6d2d40..06490dbad 100644--- a/crates/engine/src/display_color.rs+++ b/crates/engine/src/display_color.rs@@ -48,6 +48,10 @@ pub struct CanvasDisplay {pub transform: Option<Arc<Transform>>,/// Changes whenever any of the above changes (for UI caches).pub key: u64,+ /// Changes whenever what the GPU canvas texture stores changes (`source`, `encode_srgb`),+ /// but not with the monitor: the GPU canvas shares its texture between displays and only+ /// the display LUT is per display.+ pub texture_key: u64,}impl CanvasDisplay {@@ -147,49 +151,251 @@ fn hash_of(v: impl std::hash::Hash) -> u64 {h.finish()}-/// The resolved monitor profile and what it was resolved from (setting, platform bytes).-type MonitorCache = Option<(String, Option<Arc<Vec<u8>>>, Arc<Profile>)>;+/// What the platform reported about the displays' profiles (Monitor Profile = `auto`; #569).+#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]+#[serde(tag = "state", rename_all = "camelCase")]+pub enum MonitorDetection {+ /// No platform reader (web, Linux, Windows, tests).+ #[default]+ Unsupported,+ /// Being read (the first time; a re-read keeps the previous displays meanwhile).+ Pending,+ /// The reader ran but returned no displays.+ Failed { reason: String },+ /// [`ColorState::displays`] holds what it read.+ Found,+ /// [`ColorState::displays`] holds an earlier reading: the last re-read failed.+ Retained { reason: String },+}++/// A display as the platform reports it.+#[derive(Clone, Debug, PartialEq, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Display {+ /// Platform display id (macOS: `CGDirectDisplayID`).+ pub id: u32,+ /// E.g. "Built-in Retina Display".+ pub name: String,+ /// `[x, y, width, height]` in OS points; origin at the top-left of the primary display,+ /// y down (the coordinates window positions use).+ pub frame: [f64; 4],+ /// The OS's name for the display's profile (System Settings), when known.+ pub profile_name: Option<String>,+ /// The display's ICC profile; `None` when the OS gave none.+ #[serde(skip)]+ pub icc: Option<Arc<Vec<u8>>>,+}++/// The display showing most of a window whose frame (OS points, as [`Display::frame`]) is+/// `rect`: the one it overlaps most, as AppKit's `NSWindow.screen`. `None` when it overlaps none.+pub fn display_at(displays: &[Display], rect: [f64; 4]) -> Option<u32> {+ let area = |d: &Display| {+ let w = (rect[0] + rect[2]).min(d.frame[0] + d.frame[2]) - rect[0].max(d.frame[0]);+ let h = (rect[1] + rect[3]).min(d.frame[1] + d.frame[3]) - rect[1].max(d.frame[1]);+ if w > 0.0 && h > 0.0 { w * h } else { 0.0 }+ };+ displays.iter().map(|d| (d.id, area(d))).filter(|(_, a)| *a > 0.0).max_by(|a, b| a.1.total_cmp(&b.1)).map(|(id, _)| id)+}-/// Caches of [`ColorState`] for the display (monitor profile and per-document displays).+/// The monitor profile the canvas is actually shown in on one display, and why+/// (`edit.colorSettings`'s `monitorStatus`, Help › System Info).+#[derive(Clone, Debug, PartialEq, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct MonitorStatus {+ /// Color Settings › Monitor Profile as set: `auto`, a built-in id or an `.icc` path.+ pub requested: String,+ /// `auto` (the display's own profile), `manual` (the chosen profile) or `fallback` (sRGB,+ /// because the requested profile isn't available or usable: see `reason`).+ pub source: &'static str,+ /// The display this is for (`auto` reads its profile), when known.+ pub display: Option<String>,+ /// Description of the profile in use (from the profile itself).+ pub profile: String,+ /// The OS's name for it (`auto`), when known.+ pub profile_name: Option<String>,+ /// Its content hash, to tell profiles with the same name apart.+ pub fingerprint: String,+ pub detection: MonitorDetection,+ pub reason: Option<String>,+}++impl MonitorStatus {+ /// One line for Help › System Info and the Color Settings dialog: the profile (by the OS's+ /// name for it in `auto`), the source and any reason. The display is said by the caller.+ pub fn summary(&self) -> String {+ let name = match (&self.profile_name, self.source) {+ (Some(n), "auto") => n.as_str(),+ _ => self.profile.as_str(),+ };+ match &self.reason {+ Some(r) => format!("{name} ({}: {r})", self.source),+ None => format!("{name} ({})", self.source),+ }+ }+}++/// A resolved monitor profile and what it was resolved from (setting, display, profile bytes,+/// detection state).+struct MonitorEntry {+ spec: String,+ display: Option<u32>,+ icc: Option<Arc<Vec<u8>>>,+ detection: MonitorDetection,+ profile: Arc<Profile>,+ status: MonitorStatus,+}++/// Caches of [`ColorState`] for the display (monitor profiles per display, per-document displays).#[derive(Default)]pub struct DisplayCaches {- monitor: Mutex<MonitorCache>,+ monitor: Mutex<HashMap<Option<u32>, MonitorEntry>>,canvas: Mutex<HashMap<(ColorSpace, u64, u64), Arc<CanvasDisplay>>>,}impl ColorState {- /// The monitor profile: Color Settings › Monitor Profile (`auto`: the platform's profile when- /// supplied in [`ColorState::monitor_profile`], else sRGB). Non-RGB or unreadable profiles- /// fall back to sRGB.+ /// The monitor profile of the main window's display ([`ColorState::main_display`]); see+ /// [`ColorState::monitor_for`].pub fn monitor(&self) -> Arc<Profile> {+ self.monitor_for(self.main_display)+ }++ /// The monitor profile for `display`: Color Settings › Monitor Profile (`auto`: that+ /// display's profile as the platform reported it, the primary display's when `display` is+ /// unknown, else sRGB). Profiles that are missing, unreadable, not RGB or unusable as a+ /// display destination fall back to sRGB, and [`ColorState::monitor_status_for`] says so.+ pub fn monitor_for(&self, display: Option<u32>) -> Arc<Profile> {+ self.resolved_monitor(display).0+ }++ /// What [`ColorState::monitor`] resolved to, and why.+ pub fn monitor_status(&self) -> MonitorStatus {+ self.monitor_status_for(self.main_display)+ }++ /// What [`ColorState::monitor_for`] resolved to, and why.+ pub fn monitor_status_for(&self, display: Option<u32>) -> MonitorStatus {+ self.resolved_monitor(display).1+ }++ /// Record the platform's reading of the displays (`auto`). An error keeps displays read+ /// before (a failed re-read shouldn't undo a good one): the detection is then+ /// [`MonitorDetection::Retained`], and the reason is also returned for the log.+ pub fn set_displays(&mut self, r: std::result::Result<Vec<Display>, String>) -> Option<String> {+ let reason = match r {+ Ok(d) if !d.is_empty() => {+ self.displays = d;+ self.monitor_detection = MonitorDetection::Found;+ return None;+ }+ Ok(_) => "the platform reported no displays".to_string(),+ Err(reason) => reason,+ };+ if self.displays.is_empty() {+ self.monitor_detection = MonitorDetection::Failed { reason };+ None+ } else {+ self.monitor_detection = MonitorDetection::Retained { reason: reason.clone() };+ Some(reason)+ }+ }++ /// Every display with what its monitor profile resolves to (Help › System Info).+ pub fn display_statuses(&self) -> Vec<serde_json::Value> {+ self.displays+ .iter()+ .map(|d| {+ serde_json::json!({+ "id": d.id, "name": d.name, "frame": d.frame, "profileName": d.profile_name,+ "main": self.main_display == Some(d.id), "status": self.monitor_status_for(Some(d.id)),+ })+ })+ .collect()+ }++ /// The display `id`, else the primary one (the first reported).+ fn display_or_primary(&self, id: Option<u32>) -> Option<&Display> {+ id.and_then(|id| self.displays.iter().find(|d| d.id == id)).or(self.displays.first())+ }++ fn resolved_monitor(&self, display: Option<u32>) -> (Arc<Profile>, MonitorStatus) {let spec = self.settings.monitor_profile.as_str();+ let auto = spec.is_empty() || spec == "auto";+ let shown = self.display_or_primary(display);+ let icc = if auto { shown.and_then(|d| d.icc.clone()) } else { None };let mut cache = self.display.monitor.lock().unwrap_or_else(|e| e.into_inner());- if let Some((s, b, p)) = cache.as_ref()- && s == spec- && match (b, &self.monitor_profile) {+ if let Some(e) = cache.get(&display)+ && e.spec == spec+ && e.display == shown.map(|d| d.id)+ && e.detection == self.monitor_detection+ && match (&e.icc, &icc) {(None, None) => true,(Some(a), Some(b)) => Arc::ptr_eq(a, b),_ => false,}{- return p.clone();+ return (e.profile.clone(), e.status.clone());}- let p = if spec.is_empty() || spec == "auto" {- self.monitor_profile.as_ref().and_then(|b| profile_from_bytes(b).ok())+ let found = if auto {+ match (shown, &icc, &self.monitor_detection) {+ (_, Some(b), _) => profile_from_bytes(b).map_err(|e| format!("the display profile can't be read: {e}")),+ (Some(d), None, _) => Err(format!("{} has no ICC profile", d.name)),+ (None, None, MonitorDetection::Pending) => Err("the display profile hasn't been read yet".into()),+ (None, None, MonitorDetection::Failed { reason }) => Err(reason.clone()),+ (None, None, _) => Err("this platform doesn't report display profiles".into()),+ }} else {- resolve_profile(spec, None, Some(photocraft_color::ColorMode::Rgb)).ok()+ resolve_profile(spec, None, Some(photocraft_color::ColorMode::Rgb)).map_err(|e| e.to_string())+ };+ let usable = found.and_then(|p| {+ if p.color_space != ColorSpace::Rgb {+ return Err(format!("`{}` is a {:?} profile, not RGB", p.description, p.color_space));+ }+ // The canvas transforms end at this profile: one that can't be a destination would+ // otherwise leave the canvas silently unmanaged.+ Transform::new(Builtin::Srgb.profile(), &p, DISPLAY_INTENT, DISPLAY_BPC)+ .map_err(|e| format!("`{}` can't be used as a display profile: {e}", p.description))?;+ Ok(p)+ });+ let (p, source, reason) = match usable {+ Ok(p) => (p, if auto { "auto" } else { "manual" }, None),+ Err(r) => (Arc::new(Builtin::Srgb.profile().clone()), "fallback", Some(r)),+ };+ let status = MonitorStatus {+ requested: if spec.is_empty() { "auto".into() } else { spec.to_string() },+ source,+ display: shown.map(|d| d.name.clone()),+ profile: p.description.clone(),+ profile_name: if auto { shown.and_then(|d| d.profile_name.clone()) } else { None },+ fingerprint: format!("{:016x}", p.content_hash()),+ detection: self.monitor_detection.clone(),+ reason,+ };+ if cache.len() > 16 {+ cache.clear();}- .filter(|p| p.color_space == ColorSpace::Rgb)- .unwrap_or_else(|| Arc::new(Builtin::Srgb.profile().clone()));- *cache = Some((spec.to_string(), self.monitor_profile.clone(), p.clone()));- p+ let entry = MonitorEntry {+ spec: spec.to_string(),+ display: shown.map(|d| d.id),+ icc,+ detection: self.monitor_detection.clone(),+ profile: p.clone(),+ status: status.clone(),+ };+ cache.insert(display, entry);+ (p, status)}- /// How the canvas shows `doc` (cached per document profile, mode and monitor profile).+ /// How the canvas shows `doc` on the main window's display.pub fn canvas_display(&self, doc: &Document) -> Result<Arc<CanvasDisplay>> {+ self.canvas_display_for(doc, self.main_display)+ }++ /// How the canvas shows `doc` on `display` (cached per document profile, mode and monitor+ /// profile).+ 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 monitor = self.monitor();+ let monitor = self.monitor_for(display);let key = (space, doc_hash, monitor.content_hash());if let Some(d) = self.display.canvas.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {return Ok(d.clone());@@ -206,6 +412,7 @@ impl ColorState {let d = Arc::new(CanvasDisplay {encode_srgb,key: hash_of((source.content_hash(), monitor.content_hash(), encode_srgb, transform.is_some())),+ texture_key: hash_of((source.content_hash(), encode_srgb)),source,monitor,transform,@@ -218,10 +425,15 @@ impl ColorState {Ok(d)}- /// Changes whenever the canvas display of `doc` changes: profiles, monitor, Proof Colors,- /// Gamut Warning and 32-bit preview settings (for the UI's LUT cache).+ /// Changes whenever the canvas display of `doc` on the main window's display changes.pub fn display_signature(&self, doc: &Document) -> u64 {- let cm = self.canvas_display(doc).map(|d| d.key).unwrap_or(0);+ self.display_signature_for(doc, self.main_display)+ }++ /// Changes whenever the canvas display of `doc` on `display` changes: profiles, monitor,+ /// Proof Colors, Gamut Warning and 32-bit preview settings (for the UI's LUT cache).+ pub fn display_signature_for(&self, doc: &Document, display: Option<u32>) -> u64 {+ let cm = self.canvas_display_for(doc, display).map(|d| d.key).unwrap_or(0);// Per frame: read the proof state in place (the default state allocates a profile).let proof = self.proof_ref(doc.id).filter(|pv| pv.enabled || pv.gamut_warning).map(|pv| {let s = &pv.setup;diff --git a/crates/engine/src/display_color_tests.rs b/crates/engine/src/display_color_tests.rsindex 9785faa01..674c572c3 100644--- a/crates/engine/src/display_color_tests.rs+++ b/crates/engine/src/display_color_tests.rs@@ -207,11 +207,11 @@ fn monitor_profile_setting() {// `auto` uses the platform's profile when supplied, else sRGB.s.execute("edit.colorSettings", json!({"monitorProfile": "auto"})).unwrap();assert!(s.color.canvas_display(&srgb).unwrap().is_identity());- s.color.monitor_profile = Some(Builtin::DisplayP3.profile().to_bytes());+ s.color.set_displays(Ok(vec![display(1, [0.0, 0.0, 100.0, 100.0], Some(Builtin::DisplayP3.profile().to_bytes().to_vec()))]));assert_eq!(s.color.monitor().description, "Display P3");assert!(s.color.canvas_display(&p3).unwrap().is_identity());// Garbage platform bytes fall back to sRGB.- s.color.monitor_profile = Some(Arc::new(vec![0u8; 16]));+ s.color.set_displays(Ok(vec![display(1, [0.0, 0.0, 100.0, 100.0], Some(vec![0u8; 16]))]));assert_eq!(s.color.monitor().content_hash(), Builtin::Srgb.profile().content_hash());// The signature follows the monitor.let a = s.color.display_signature(&p3);@@ -219,6 +219,131 @@ fn monitor_profile_setting() {assert_ne!(a, s.color.display_signature(&p3));}+fn display(id: u32, frame: [f64; 4], icc: Option<Vec<u8>>) -> crate::display_color::Display {+ crate::display_color::Display { id, name: format!("Display {id}"), frame, profile_name: None, icc: icc.map(Arc::new) }+}++fn p3() -> Option<Vec<u8>> {+ Some(Builtin::DisplayP3.profile().to_bytes().to_vec())+}++#[test]+fn monitor_status_says_what_is_applied() {+ use crate::display_color::MonitorDetection;+ let mut s = Session::new();+ let status = |s: &mut Session| s.execute("edit.colorSettings", json!({})).unwrap()["monitorStatus"].clone();+ // No platform reader: sRGB, and the reply says it's a fallback.+ let st = status(&mut s);+ assert_eq!((st["requested"].as_str(), st["source"].as_str()), (Some("auto"), Some("fallback")));+ assert_eq!(st["detection"]["state"], "unsupported");+ assert!(st["reason"].as_str().unwrap().contains("doesn't report"), "{st}");+ s.color.monitor_detection = MonitorDetection::Pending;+ assert!(status(&mut s)["reason"].as_str().unwrap().contains("hasn't been read"));+ // A profile read for a named display.+ let mut studio = display(7, [0.0, 0.0, 100.0, 100.0], p3());+ studio.name = "Studio Display".into();+ studio.profile_name = Some("Studio Display (calibrated)".into());+ s.color.set_displays(Ok(vec![studio]));+ let st = status(&mut s);+ assert_eq!((st["source"].as_str(), st["profile"].as_str()), (Some("auto"), Some("Display P3")));+ assert_eq!((st["display"].as_str(), st["detection"]["state"].as_str()), (Some("Studio Display"), Some("found")));+ assert_eq!(st["fingerprint"], format!("{:016x}", Builtin::DisplayP3.profile().content_hash()));+ assert!(st["reason"].is_null());+ assert_eq!(s.color.monitor_status().summary(), "Studio Display (calibrated) (auto)");+ // Bytes that aren't a profile, a non-RGB profile, one that can't be a destination and none+ // at all fall back to sRGB with the reason.+ let mut link = Builtin::Srgb.profile().clone();+ link.class = photocraft_cms::ProfileClass::DeviceLink;+ let link = link.with_encoded_bytes();+ for (icc, why) in [+ (Some(vec![0u8; 16]), "can't be read"),+ (Some(Builtin::SGray.profile().to_bytes().to_vec()), "not RGB"),+ (Some(link.to_bytes().to_vec()), "can't be used as a display profile"),+ (None, "Display 2 has no ICC profile"),+ ] {+ s.color.set_displays(Ok(vec![display(2, [0.0, 0.0, 100.0, 100.0], icc)]));+ let st = status(&mut s);+ assert_eq!(st["source"], "fallback", "{why}");+ assert!(st["reason"].as_str().unwrap().contains(why), "{st}");+ assert_eq!(s.color.monitor().content_hash(), Builtin::Srgb.profile().content_hash());+ }+ // A failed re-read keeps the displays read before and is returned for the log.+ s.color.set_displays(Ok(vec![display(2, [0.0, 0.0, 100.0, 100.0], p3())]));+ assert_eq!(s.color.set_displays(Err("osascript failed".into())).as_deref(), Some("osascript failed"));+ assert_eq!((s.color.monitor().description.as_str(), s.color.displays.len()), ("Display P3", 1));+ // ... and the status says the reading is an earlier one.+ let st = status(&mut s);+ assert_eq!((st["source"].as_str(), st["detection"]["state"].as_str()), (Some("auto"), Some("retained")));+ assert_eq!(st["detection"]["reason"], "osascript failed");+ // A later successful read makes it current again.+ s.color.set_displays(Ok(vec![display(2, [0.0, 0.0, 100.0, 100.0], p3())]));+ assert_eq!(status(&mut s)["detection"]["state"], "found");+ // Without displays read before, the failure is the reason.+ let mut fresh = Session::new();+ assert_eq!(fresh.color.set_displays(Err("osascript failed".into())), None);+ let st = status(&mut fresh);+ assert_eq!((st["source"].as_str(), st["reason"].as_str()), (Some("fallback"), Some("osascript failed")));+ // A manual choice wins over the display's profile.+ s.execute("edit.colorSettings", json!({"monitorProfile": "rec2020"})).unwrap();+ let st = status(&mut s);+ assert_eq!((st["requested"].as_str(), st["source"].as_str()), (Some("rec2020"), Some("manual")));+ assert_ne!(st["profile"], "Display P3");+}++#[test]+fn each_display_gets_its_own_profile() {+ let mut s = Session::new();+ // Built-in (primary, menu bar) left, a wide-gamut external display right and higher up,+ // as on the #569 setup (frames in points, y down).+ s.color.set_displays(Ok(vec![display(1, [0.0, 0.0, 1728.0, 1117.0], None), display(4, [1728.0, -667.0, 3008.0, 1692.0], p3())]));+ let displays = s.color.displays.clone();+ let at = |r: [f64; 4]| crate::display_color::display_at(&displays, r);+ assert_eq!(at([100.0, 100.0, 800.0, 600.0]), Some(1));+ assert_eq!(at([2000.0, -500.0, 800.0, 600.0]), Some(4));+ // Spanning both: the one showing more of it.+ assert_eq!(at([1500.0, 100.0, 800.0, 600.0]), Some(4));+ assert_eq!(at([1200.0, 100.0, 800.0, 600.0]), Some(1));+ assert_eq!(at([-5000.0, 0.0, 10.0, 10.0]), None);+ // Display 1 has no profile here (sRGB fallback); display 4 is P3; unknown = the primary.+ let srgb = rgb_doc(None, [0.8, 0.5, 0.3], SampleType::U8);+ assert_eq!(s.color.monitor_for(Some(4)).description, "Display P3");+ assert_eq!(s.color.monitor_for(Some(1)).content_hash(), Builtin::Srgb.profile().content_hash());+ assert_eq!(s.color.monitor_for(None).content_hash(), s.color.monitor_for(Some(1)).content_hash());+ assert_eq!(s.color.monitor_for(Some(99)).content_hash(), s.color.monitor_for(Some(1)).content_hash());+ // The same document has a different display (and LUT signature) per display; the texture key+ // (what the GPU canvas texture stores) is shared.+ let (a, b) = (s.color.canvas_display_for(&srgb, Some(1)).unwrap(), s.color.canvas_display_for(&srgb, Some(4)).unwrap());+ assert!(a.is_identity() && !b.is_identity());+ assert_ne!(a.key, b.key);+ assert_eq!(a.texture_key, b.texture_key);+ assert_ne!(s.color.display_signature_for(&srgb, Some(1)), s.color.display_signature_for(&srgb, Some(4)));+ assert!(s.color.gpu_canvas_lut_for(&srgb, 9, Some(1)).unwrap().is_none());+ assert!(s.color.gpu_canvas_lut_for(&srgb, 9, Some(4)).unwrap().is_some());+ // The main window's display is what the unqualified methods use.+ s.color.main_display = Some(4);+ assert_eq!(s.color.monitor().description, "Display P3");+ assert_eq!(s.color.display_signature(&srgb), s.color.display_signature_for(&srgb, Some(4)));+ let statuses = s.color.display_statuses();+ assert_eq!((statuses.len(), statuses[1]["main"].as_bool()), (2, Some(true)));+ assert_eq!(statuses[0]["status"]["source"], "fallback");+ // Proof Colors follow the display too.+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();+ let doc = s.active().unwrap().doc.clone();+ s.execute("view.proofColors", json!({"on": true})).unwrap();+ assert_ne!(s.color.gpu_canvas_lut_for(&doc, 9, Some(1)).unwrap(), s.color.gpu_canvas_lut_for(&doc, 9, Some(4)).unwrap());+}++#[test]+fn saved_monitor_profile_that_is_gone_is_reported() {+ // Preferences load settings without validating them: a saved .icc path deleted since.+ let mut s = Session::new();+ s.color.settings.monitor_profile = "/nonexistent/photocraft/display.icc".into();+ let st = s.color.monitor_status();+ assert_eq!((st.requested.as_str(), st.source), ("/nonexistent/photocraft/display.icc", "fallback"));+ assert!(st.reason.as_deref().unwrap_or("").contains("cannot read profile"), "{st:?}");+ assert_eq!(s.color.monitor().content_hash(), Builtin::Srgb.profile().content_hash());+}+#[test]fn monitor_profile_bad_params_fail_gracefully() {let mut s = Session::new();diff --git a/crates/engine/src/proof_sim.rs b/crates/engine/src/proof_sim.rsindex f5aa4de9a..f225a5a7a 100644--- a/crates/engine/src/proof_sim.rs+++ b/crates/engine/src/proof_sim.rs@@ -146,12 +146,12 @@ pub fn dichromat(rgb_lin: [f32; 3], protan: bool) -> [f32; 3] {/// The display LUT when a simulation or 32-bit preview applies (None = plain profile proof).pub fn display_lut(c: &ColorState, doc: &Document, size: usize) -> Result<Option<Lut3d>> {- display_lut_with(c, doc, size, true)+ display_lut_with(c, doc, size, true, c.main_display)}/// [`display_lut`], leaving the 32-bit preview out when `include_hdr` is false (the GPU canvas/// applies it in its shader).-pub fn display_lut_with(c: &ColorState, doc: &Document, size: usize, include_hdr: bool) -> Result<Option<Lut3d>> {+pub fn display_lut_with(c: &ColorState, doc: &Document, size: usize, include_hdr: bool, display: Option<u32>) -> Result<Option<Lut3d>> {let pv = c.proof(doc.id);let kind = if pv.enabled { pv.setup.kind } else { ProofKind::Profile };let hdr = if include_hdr { c.hdr_preview(doc) } else { None };@@ -159,8 +159,8 @@ pub fn display_lut_with(c: &ColorState, doc: &Document, size: usize, include_hdrreturn Ok(None);}let err = |e: photocraft_cms::CmsError| EngineError::Other(format!("colour management: {e}"));- let src = c.canvas_display(doc)?.source.clone();- let mon = c.monitor();+ let src = c.canvas_display_for(doc, display)?.source.clone();+ let mon = c.monitor_for(display);let srgb = Builtin::Srgb.profile();let setup = &pv.setup;// composite → display for the plain case (with the profile proof when on).diff --git a/crates/ui-egui/examples/type_bench.rs b/crates/ui-egui/examples/type_bench.rsindex fe1b2989a..c5cbaf0d9 100644--- a/crates/ui-egui/examples/type_bench.rs+++ b/crates/ui-egui/examples/type_bench.rs@@ -32,7 +32,7 @@ fn typing(app: &mut PhotocraftApp, steps: usize) {app.run(&format!("type.orientation.{orient}"), json!({"layer": id})).expect("orientation");app.sync_views();let ctx = egui::Context::default();- let _ = photocraft_ui_egui::canvas::ensure_texture(app, &ctx, 0);+ let _ = photocraft_ui_egui::canvas::ensure_texture(app, &ctx, 0, None);let (mut cmd, mut lay, mut canvas, mut total) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());for i in 0..steps {let c = text.get(i % text.len()).copied().unwrap_or('あ');@@ -42,7 +42,7 @@ fn typing(app: &mut PhotocraftApp, steps: usize) {let t1 = Instant::now();let _ = photocraft_ui_egui::type_tool::layout(app, photocraft_doc::LayerId(id));let t2 = Instant::now();- let _ = photocraft_ui_egui::canvas::ensure_texture(app, &ctx, 0);+ let _ = photocraft_ui_egui::canvas::ensure_texture(app, &ctx, 0, None);let t3 = Instant::now();cmd.push((t1 - t0).as_secs_f64() * 1e3);lay.push((t2 - t1).as_secs_f64() * 1e3);@@ -92,7 +92,7 @@ fn main() {app.sync_views();let ctx = egui::Context::default();let t0 = Instant::now();- let _ = photocraft_ui_egui::canvas::ensure_texture(&mut app, &ctx, 0);+ let _ = photocraft_ui_egui::canvas::ensure_texture(&mut app, &ctx, 0, None);eprintln!("first canvas composite: {:.0} ms", t0.elapsed().as_secs_f64() * 1e3);let id = ids.get(n / 2).copied().unwrap_or(0);@@ -108,7 +108,7 @@ fn main() {}).expect("type.setStyle");let t1 = Instant::now();- let _ = photocraft_ui_egui::canvas::ensure_texture(&mut app, &ctx, 0);+ let _ = photocraft_ui_egui::canvas::ensure_texture(&mut app, &ctx, 0, None);let t2 = Instant::now();cmd.push((t1 - t0).as_secs_f64() * 1e3);canvas.push((t2 - t1).as_secs_f64() * 1e3);diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex f69dfeaab..512c1d264 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -396,10 +396,11 @@ fn display_image(display: Option<&photocraft_engine::display_color::CanvasDispla}}-/// The canvas display of `doc` and a key that changes with it (folded into the canvas caches'-/// preview keys, so a monitor or profile change re-renders).-fn canvas_display(app: &PhotocraftApp, doc: &Document) -> (Option<std::sync::Arc<photocraft_engine::display_color::CanvasDisplay>>, u64) {- match app.session.color.canvas_display(doc) {+/// The canvas display of `doc` on `display` (`None`: the main window's) and a key that changes+/// with it (folded into the canvas caches' preview keys, so a monitor or profile change+/// re-renders).+fn canvas_display(app: &PhotocraftApp, doc: &Document, display: Option<u32>) -> (Option<std::sync::Arc<photocraft_engine::display_color::CanvasDisplay>>, u64) {+ match app.session.color.canvas_display_for(doc, display.or(app.session.color.main_display)) {Ok(d) => {let k = d.key;(Some(d), k)@@ -408,6 +409,21 @@ fn canvas_display(app: &PhotocraftApp, doc: &Document) -> (Option<std::sync::Arc}}+/// [`canvas_display`]'s key for the GPU canvas texture: what the texture stores, the same on+/// every display (the display LUT holds the monitor profile).+fn texture_key(display: Option<&photocraft_engine::display_color::CanvasDisplay>) -> u64 {+ display.map_or(0, |d| d.texture_key)+}++/// `app.canvases` key: CPU canvas textures are per document and display (they hold monitor+/// values); the GPU canvas state uses [`GPU_OUTPUT`].+fn cache_key(doc: photocraft_doc::DocId, display: Option<u32>) -> (photocraft_doc::DocId, u32) {+ (doc, display.unwrap_or(0))+}++/// `app.canvases` output of the GPU canvas state (one texture per document for all displays).+pub(crate) const GPU_OUTPUT: u32 = u32::MAX;+/// The document to render: the committed one, or a clone with the live adjustment preview applied.fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arc<Document>, u64) {// Puppet / Perspective Warp previews hide the layer they draw on a mesh.@@ -487,12 +503,12 @@ const NAVIGATOR_SETTLE_MS: f64 = 200.0;/// doesn't also pay a full-resolution CPU composite for the navigator.pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize) -> Option<egui::TextureId> {if app.gpu.is_none() {- return ensure_texture(app, ctx, idx).map(|(t, _)| t);+ return ensure_texture(app, ctx, idx, app.session.color.main_display).map(|(t, _)| t);}// Keyed by the document snapshot, not its revision: selecting a layer changes no pixels.let (snapshot, id) = app.session.documents().get(idx).map(|st| (std::sync::Arc::downgrade(&st.doc), st.doc.id))?;let (doc, preview_key) = display_doc(app, idx);- let (display, display_key) = canvas_display(app, &doc);+ let (display, display_key) = canvas_display(app, &doc, None);let preview_key = preview_key ^ display_key;let key = egui::Id::new(("navigator", id.0));type Cached = (std::sync::Weak<Document>, u64, egui::TextureHandle);@@ -532,8 +548,10 @@ pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usizSome(tex.id())}-/// Make sure the canvas texture for document `idx` is current; returns (texture id, scale).-pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize) -> Option<(egui::TextureId, f32)> {+/// Make sure the canvas texture for document `idx` on `display` is current; returns (texture+/// id, scale).+pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, display: Option<u32>) -> Option<(egui::TextureId, f32)> {+ let output = display;let (revision, last_damage, id) = {let st = app.session.documents().get(idx)?;(st.revision, st.last_damage.map(|r| if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }), st.doc.id)@@ -547,11 +565,11 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize){(doc, preview_key) = (st.doc.clone(), 0);}- let (display, display_key) = canvas_display(app, &doc);- let seen = app.canvases.get(&id).map(|c| (c.tex_revision, c.tex_preview_key));+ let (display, display_key) = canvas_display(app, &doc, output);+ let seen = app.canvases.get(&cache_key(id, output)).map(|c| (c.tex_revision, c.tex_preview_key));let damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, preview_key), display_key, last_damage));let preview_key = preview_key ^ display_key;- let cache = app.canvases.entry(id).or_insert(CanvasCache {+ let cache = app.canvases.entry(cache_key(id, output)).or_insert(CanvasCache {revision: 0,texture: None,scale: 1.0,@@ -584,7 +602,7 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize)let (img, scale) = (display_image(display.as_deref(), &full), 1.0 / factor as f32);match cache.texture.as_mut() {Some(t) if t.size() == img.size => t.set(img, TextureOptions::LINEAR),- _ => cache.texture = Some(ctx.load_texture(format!("canvas-{}", id.0), img, TextureOptions::LINEAR)),+ _ => cache.texture = Some(ctx.load_texture(format!("canvas-{}-{}", id.0, cache_key(id, output).1), img, TextureOptions::LINEAR)),}cache.scale = scale;app.perf.record("full", doc.size.width as u64 * doc.size.height as u64, t1 - t0, crate::gpu_canvas::now_ms() - t1);@@ -633,13 +651,19 @@ fn damage_since(app: &PhotocraftApp, idx: usize, seen: (u64, u64), now: (u64, u6/// (`was_preview` tells its keys): count it as the document itself, so the commit's damage rect/// refreshes only that area instead of everything.pub(crate) fn shown_as_document(app: &mut PhotocraftApp, doc: photocraft_doc::DocId, was_preview: impl Fn(u64) -> bool) {- let display_key = app.session.active().map_or(0, |st| canvas_display(app, &st.doc).1);- if let Some(c) = app.canvases.get_mut(&doc) {- if was_preview(c.preview_key ^ display_key) {- c.preview_key = display_key;+ let Some(d) = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| st.doc.clone()) else { return };+ // Every display's cache of the document: the GPU state folds in the texture key, CPU+ // textures their display's key.+ let outputs: Vec<u32> = app.canvases.keys().filter(|k| k.0 == doc).map(|k| k.1).collect();+ for out in outputs {+ let (display, key) = canvas_display(app, &d, (out != 0 && out != GPU_OUTPUT).then_some(out));+ let gpu_key = texture_key(display.as_deref());+ let Some(c) = app.canvases.get_mut(&(doc, out)) else { continue };+ if was_preview(c.preview_key ^ gpu_key) {+ c.preview_key = gpu_key;}- if was_preview(c.tex_preview_key ^ display_key) {- c.tex_preview_key = display_key;+ if was_preview(c.tex_preview_key ^ key) {+ c.tex_preview_key = key;}}}@@ -676,8 +700,10 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize, visible: DRect) -> bool {return false;};let (doc, raw_key) = display_doc(app, idx);- let (display, display_key) = canvas_display(app, &doc);- let seen = app.canvases.get(&id).map(|c| (c.revision, c.preview_key));+ let (display, _) = canvas_display(app, &doc, None);+ // The texture is shared by every display: only what it stores counts, not the monitor.+ let display_key = texture_key(display.as_deref());+ let seen = app.canvases.get(&(id, GPU_OUTPUT)).map(|c| (c.revision, c.preview_key));let mut damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, raw_key), display_key, last_damage));// To an adjustment dialog's preview: only what the view shows now (the rest as it moves there).if damage.is_some()@@ -687,7 +713,7 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize, visible: DRect) -> bool {}let preview_key = raw_key ^ display_key;let size = [doc.size.width, doc.size.height];- let cache = app.canvases.entry(id).or_insert(CanvasCache {+ let cache = app.canvases.entry((id, GPU_OUTPUT)).or_insert(CanvasCache {revision: 0,texture: None,scale: 1.0,@@ -723,7 +749,7 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize, visible: DRect) -> bool {} else {app.perf.gpu_fallback = r.fallback;}- let Some(cache) = app.canvases.get_mut(&id) else { return true };+ let Some(cache) = app.canvases.get_mut(&(id, GPU_OUTPUT)) else { return true };cache.revision = revision;cache.preview_key = preview_key;cache.on_gpu = true;@@ -773,7 +799,7 @@ fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u6if let Some(r) = &result {let buf = photocraft_compose::flatten(r);let t1 = crate::gpu_canvas::now_ms();- let (display, _) = canvas_display(app, &doc);+ let (display, _) = canvas_display(app, &doc, None);app.gpu.as_ref()?.upload_buffer_full(key, &texture_buffer(display.as_deref(), &buf), doc.depth);app.perf.record("filter-preview", r.size.area(), t1 - t0, crate::gpu_canvas::now_ms() - t1);}@@ -799,7 +825,7 @@ fn ensure_adjust_proxy(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Optionlet gpu = app.gpu.clone()?;if frame.stale || !gpu.has(key, size) {let doc = app.session.documents().get(idx)?.doc.clone();- let (display, _) = canvas_display(app, &doc);+ let (display, _) = canvas_display(app, &doc, None);let r = gpu.refresh(key, &frame.doc, frame.damage, display.as_deref());app.perf.record(if r.kind.starts_with("gpu") { "gpu-adjust-proxy" } else { "adjust-proxy" }, r.px, r.composite_ms, r.upload_ms);crate::adjust_preview::proxy_drawn(app, &frame);@@ -838,7 +864,7 @@ fn ensure_proxy_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u64let t0 = crate::gpu_canvas::now_ms();let buf = photocraft_compose::flatten(&p);let t1 = crate::gpu_canvas::now_ms();- let (display, _) = canvas_display(app, &doc);+ let (display, _) = canvas_display(app, &doc, None);app.gpu.as_ref()?.upload_buffer_full(key, &texture_buffer(display.as_deref(), &buf), doc.depth);app.perf.record("proxy", p.size.area(), t1 - t0, crate::gpu_canvas::now_ms() - t1);app.proxy_uploaded = Some((doc_id, hash));@@ -1311,32 +1337,33 @@ const DISPLAY_LUT: usize = 33;/// `doc`'s colour management: document → monitor profile and View › Proof Colors / Gamut/// Warning (the 32-bit preview is applied by the canvas shader, see [`hdr_preview`]). Returns the canvas `display` mode (0 none — the identity, e.g. sRGB on/// an sRGB monitor —, 1 LUT, 2 LUT + gamut warning).-fn sync_display_lut(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, key: u64) -> u8 {+fn sync_display_lut(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, key: u64, display: Option<u32>) -> u8 {let Some(gpu) = app.gpu.clone() else { return 0 };+ let output = display.unwrap_or(0);// Rebuild only when anything feeding the LUT changes.- let sig = app.session.color.display_signature(doc);- if let Some((s, mode)) = gpu.display_lut_signature(key)+ let sig = app.session.color.display_signature_for(doc, display);+ if let Some((s, mode)) = gpu.display_lut_signature(key, output)&& s == sig{return mode;}let gamut = app.session.color.proof(doc.id).gamut_warning;- let mode = match app.session.color.gpu_canvas_lut(doc, DISPLAY_LUT) {+ let mode = match app.session.color.gpu_canvas_lut_for(doc, DISPLAY_LUT, display) {Ok(Some(bytes)) => {- gpu.set_display_lut(key, DISPLAY_LUT as u32, Some(&bytes));+ gpu.set_display_lut(key, output, DISPLAY_LUT as u32, Some(&bytes));if gamut { 2 } else { 1 }}Ok(None) => {- gpu.set_display_lut(key, DISPLAY_LUT as u32, None);+ gpu.set_display_lut(key, output, DISPLAY_LUT as u32, None);0}Err(e) => {app.ui.status = format!("Color management: {e}");- gpu.set_display_lut(key, DISPLAY_LUT as u32, None);+ gpu.set_display_lut(key, output, DISPLAY_LUT as u32, None);0}};- gpu.cache_display_lut_signature(key, sig, mode);+ gpu.cache_display_lut_signature(key, output, sig, mode);mode}@@ -1348,6 +1375,12 @@ fn hdr_preview(app: &PhotocraftApp, doc: &photocraft_doc::Document) -> Option<[f/// Draw one canvas view and handle its input. `primary` = main window (tools active).pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: Rect, mut view: View, primary: bool) -> View {let ctx = ui.ctx().clone();+ // The display this window is on: its monitor profile (#569). A document window on a display+ // the last reading didn't know asks for a new one.+ let output = crate::monitor_status::view_display(app, &ctx);+ if !primary {+ crate::monitor_status::check_window(app, &ctx);+ }let full = rect;let rect = if primary { crate::rulers::content_rect(app, rect) } else { rect };let doc = app.session.documents()[idx].doc.clone();@@ -1403,7 +1436,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:},pixel_grid: false,view_key: egui::Id::new(("pc-canvas-proxy", ctx.viewport_id(), idx)).value(),- display: sync_display_lut(app, &doc, key),+ display: sync_display_lut(app, &doc, key, output),+ output: output.unwrap_or(0),hdr: hdr_preview(app, &doc),};crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params);@@ -1422,7 +1456,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:},pixel_grid,view_key: egui::Id::new(("pc-canvas", ctx.viewport_id(), idx)).value(),- display: sync_display_lut(app, &doc, doc.id.0),+ display: sync_display_lut(app, &doc, doc.id.0, output),+ output: output.unwrap_or(0),hdr: hdr_preview(app, &doc),};crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params);@@ -1440,7 +1475,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:painter.rect_filled(img_rect, 0.0, Color32::WHITE);}}- if let Some((tex, _scale)) = ensure_texture(app, &ctx, idx) {+ if let Some((tex, _scale)) = ensure_texture(app, &ctx, idx, output) {let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) };painter.image(tex, img_rect, uv, Color32::WHITE);}@@ -2411,16 +2446,8 @@ fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {if app.run(stroke_command(d.tool), p).is_ok()&& let Some(l) = live{- let display_key = app.session.active().map_or(0, |st| canvas_display(app, &st.doc).1);- if let Some(c) = app.canvases.get_mut(&l.doc) {- // Raw preview key 0 = the document itself (its colour display folded in).- if l.since(c.preview_key ^ display_key).is_some() {- c.preview_key = display_key;- }- if l.since(c.tex_preview_key ^ display_key).is_some() {- c.tex_preview_key = display_key;- }- }+ // Raw preview key 0 = the document itself (its colour display folded in).+ shown_as_document(app, l.doc, |k| l.since(k).is_some());}}Tool::RectMarquee | Tool::EllipseMarquee => {@@ -2573,6 +2600,78 @@ fn hex(c: [f32; 4]) -> String {mod tests {use super::*;+ /// #569: displays 1 (sRGB) and 4 (Display P3) side by side, and a document filled with an+ /// sRGB colour.+ fn app_on_two_displays() -> PhotocraftApp {+ use photocraft_engine::color_cmds::resolve_profile;+ use photocraft_engine::display_color::Display;+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.run("file.new", json!({"width": 64, "height": 64})).unwrap();+ app.run("edit.fill", json!({"color": "#cc8040"})).unwrap();+ let icc = |id: &str| Some(resolve_profile(id, None, None).unwrap().to_bytes());+ app.session.color.set_displays(Ok(vec![+ Display { id: 1, name: "A".into(), frame: [0.0, 0.0, 100.0, 100.0], profile_name: None, icc: icc("srgb") },+ Display { id: 4, name: "B".into(), frame: [100.0, 0.0, 100.0, 100.0], profile_name: None, icc: icc("display-p3") },+ ]));+ app+ }++ #[test]+ fn cpu_canvas_textures_are_per_display() {+ // Two windows of one document on different displays: each has its own texture of+ // monitor values, and drawing them in turn re-renders neither.+ let mut app = app_on_two_displays();+ let ctx = egui::Context::default();+ let id = app.session.documents()[0].doc.id;+ let a = ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0;+ let b = ensure_texture(&mut app, &ctx, 0, Some(4)).unwrap().0;+ assert_ne!(a, b);+ app.perf.last_refresh = "";+ for _ in 0..3 {+ assert_eq!(ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0, a);+ assert_eq!(ensure_texture(&mut app, &ctx, 0, Some(4)).unwrap().0, b);+ }+ assert_eq!(app.perf.last_refresh, "", "no re-render");+ let doc = app.session.documents()[0].doc.clone();+ assert!(canvas_display(&app, &doc, Some(1)).0.unwrap().is_identity());+ assert!(!canvas_display(&app, &doc, Some(4)).0.unwrap().is_identity());+ assert_ne!(app.canvases[&(id, 1)].tex_preview_key, app.canvases[&(id, 4)].tex_preview_key);+ // An edit updates both.+ app.run("edit.fill", json!({"color": "#2060c0"})).unwrap();+ ensure_texture(&mut app, &ctx, 0, Some(1));+ ensure_texture(&mut app, &ctx, 0, Some(4));+ let rev = app.session.documents()[0].revision;+ assert_eq!((app.canvases[&(id, 1)].tex_revision, app.canvases[&(id, 4)].tex_revision), (rev, rev));+ }++ #[test]+ fn gpu_display_luts_are_per_display() {+ let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else {+ eprintln!("skipping: no GPU adapter");+ return;+ };+ let mut app = app_on_two_displays();+ app.set_wgpu(rs);+ let doc = app.session.documents()[0].doc.clone();+ let key = doc.id.0;+ // sRGB on the sRGB display needs no LUT; on the P3 display it does.+ assert_eq!(sync_display_lut(&mut app, &doc, key, Some(1)), 0);+ assert_eq!(sync_display_lut(&mut app, &doc, key, Some(4)), 1);+ let gpu = app.gpu.clone().unwrap();+ let (s1, s4) = (gpu.display_lut_signature(key, 1).unwrap(), gpu.display_lut_signature(key, 4).unwrap());+ assert_ne!(s1.0, s4.0);+ assert!(gpu.has_display_lut(key, 4) && !gpu.has_display_lut(key, 1));+ // Drawing one window leaves the other's LUT alone.+ for _ in 0..3 {+ assert_eq!(sync_display_lut(&mut app, &doc, key, Some(1)), 0);+ assert_eq!(sync_display_lut(&mut app, &doc, key, Some(4)), 1);+ }+ assert_eq!((gpu.display_lut_signature(key, 1), gpu.display_lut_signature(key, 4)), (Some(s1), Some(s4)));+ assert!(gpu.has_display_lut(key, 4));+ // The shared texture's key is the same for both displays.+ assert_eq!(texture_key(canvas_display(&app, &doc, Some(1)).0.as_deref()), texture_key(canvas_display(&app, &doc, Some(4)).0.as_deref()));+ }+#[test]fn tab_context_uses_clicked_document_and_existing_close_commands() {let items = tab_context_items(2, 3);@@ -2745,7 +2844,7 @@ mod tests {assert!(alpha(&shown, 40, 30) > 0.5 && (0.01..0.5).contains(&alpha(&shown, 40, 38)), "soft stroke while drawing");assert_eq!(alpha(&app.session.documents()[0].doc, 40, 30), 0.0, "not committed yet");// The canvas redraws only what the stroke touched.- let dk = canvas_display(&app, &app.session.documents()[0].doc).1;+ let dk = canvas_display(&app, &app.session.documents()[0].doc, None).1;let d = damage_since(&app, 0, (rev, dk), (rev, key), dk, None).unwrap();assert!(d.contains(40, 30) && !d.contains(40, 2) && d.width() < 120, "{d:?}");tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 30.0 }, m);@@ -2765,19 +2864,19 @@ mod tests {let tilt = json!({"size": 30, "hardness": 1.0, "spacing": 0.05, "shapeDynamics": {"enabled": true, "size": {"control": "penTilt"}}});app.run("tools.setBrush", json!({ "brush": tilt })).unwrap();app.ui.tool = Tool::Brush;- assert_eq!(ensure_texture(&mut app, &ctx, 0).map(|t| t.1), Some(0.5));+ assert_eq!(ensure_texture(&mut app, &ctx, 0, None).map(|t| t.1), Some(0.5));let m = egui::Modifiers::NONE;app.stylus.feed.set(Some(crate::stylus::PenSample { pressure: 1.0, tilt_x: 60.0, tilt_y: 0.0, rotation: 0.0, eraser: false }));tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 45.0, pressure: 1.0 }, m);for x in [300.0, 600.0, 900.0] {tool_event(&mut app, ToolEvent::Move { x, y: 45.0, pressure: 1.0 }, m);- ensure_texture(&mut app, &ctx, 0);+ ensure_texture(&mut app, &ctx, 0, None);assert_eq!(app.perf.last_refresh, "rect");assert!(app.perf.last_refresh_px < 4097 * 90 / 4, "{}", app.perf.last_refresh_px);}let shown = display_doc(&mut app, 0).0;tool_event(&mut app, ToolEvent::Up { x: 900.0, y: 45.0 }, m);- ensure_texture(&mut app, &ctx, 0);+ ensure_texture(&mut app, &ctx, 0, None);assert_eq!(app.perf.last_refresh, "rect", "the commit refreshes only the stroke");let doc = app.session.documents()[0].doc.clone();let (a, b) = (doc.layers[0].surface().unwrap(), shown.layers[0].surface().unwrap());@@ -2798,19 +2897,19 @@ mod tests {// What the options bar's Smoothing field writes.app.session.tools.brush.smoothing.amount = smoothing;app.ui.tool = Tool::Brush;- ensure_texture(&mut app, &ctx, 0);+ ensure_texture(&mut app, &ctx, 0, None);let m = egui::Modifiers::NONE;tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 1.0 }, m);for &x in xs {tool_event(&mut app, ToolEvent::Move { x, y: 40.0 + (x / 7.0).sin() * 8.0, pressure: 1.0 }, m);- ensure_texture(&mut app, &ctx, 0);+ ensure_texture(&mut app, &ctx, 0, None);}let live = display_doc(&mut app, 0).0;let last = *xs.last().unwrap();tool_event(&mut app, ToolEvent::Up { x: last, y: 40.0 + (last / 7.0).sin() * 8.0 }, m);let (next, key) = display_doc(&mut app, 0);assert_eq!(key, 0, "the frame after release shows the committed document");- ensure_texture(&mut app, &ctx, 0);+ ensure_texture(&mut app, &ctx, 0, None);let partial = app.perf.last_refresh == "rect";(live, next, partial, app)}diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 919b54304..6c2a68b85 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -143,7 +143,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {DialogKind::Command if fields.contains_key("__export") => crate::export_dialog::body(app, ui, &mut fields),DialogKind::Command if fields.contains_key("__sizing") => crate::sizing::body(ui, &mut fields),DialogKind::Command if crate::adjust_dialog::owns(&fields) => crate::adjust_dialog::body(app, ui, &mut fields),- DialogKind::Command if fields.contains_key("__filter") => crate::filter_dialog::body(ui, &mut fields),+ DialogKind::Command if fields.contains_key("__filter") => {+ // Color Settings: the monitor profile in use can change while it is open.+ if fields.get("__command").and_then(Value::as_str) == Some("edit.colorSettings") {+ fields.insert("__note".into(), Value::String(crate::monitor_status::note(app)));+ }+ crate::filter_dialog::body(ui, &mut fields)+ }DialogKind::Command if fields.contains_key("__form") => crate::view_cmds::form_body(ui, &mut fields),DialogKind::Command => {}DialogKind::LayerStyle => crate::layer_style::body(ui, &mut fields),diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rsindex 5389ea55b..b16a31e38 100644--- a/crates/ui-egui/src/filter_dialog.rs+++ b/crates/ui-egui/src/filter_dialog.rs@@ -361,6 +361,11 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {}}}+ // Read-only context the dialog opener supplies (e.g. the monitor profile in use).+ if let Some(note) = f.get("__note").and_then(Value::as_str) {+ ui.add_space(4.0);+ ui.add(egui::Label::new(egui::RichText::new(note).color(t.text_dim)).wrap());+ }if let Some(mut preview) = f.get("__preview").and_then(Value::as_bool) {ui.add_space(4.0);crate::widgets::checkbox(ui, &mut preview, tl!("Preview"));diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rsindex 3be11919f..693de94b7 100644--- a/crates/ui-egui/src/gpu_canvas.rs+++ b/crates/ui-egui/src/gpu_canvas.rs@@ -66,6 +66,8 @@ pub struct ViewParams {/// Display transform: 0 none, 1 the document's display LUT (document → monitor profile,/// Proof Colors), 2 LUT plus the gamut warning (see [`GpuCanvas::set_display_lut`]).pub display: u8,+ /// The display the view is on (its LUT is per document and display, #569; 0 = unknown).+ pub output: u32,/// View › 32-bit Preview Options (exposure in stops, gamma), applied to the texture values/// before the display LUT; `None` when off. The display LUT must then leave it out/// (`ColorState::gpu_canvas_lut`).@@ -581,36 +583,43 @@ impl GpuCanvas {}// LUTs and identity-transform signatures can outlive document textures. Prune both,// or a preserved-ID reopen can skip rebuilding a missing LUT.- res.luts.retain(|k, _| live.contains(k));- res.display_lut_signatures.retain(|k, _| live.contains(k));+ res.luts.retain(|k, _| live.contains(&k.0));+ res.display_lut_signatures.retain(|k, _| live.contains(&k.0));}- pub(crate) fn display_lut_signature(&self, doc: u64) -> Option<(u64, u8)> {+ pub(crate) fn display_lut_signature(&self, doc: u64, output: u32) -> Option<(u64, u8)> {let renderer = self.rs.renderer.read();- renderer.callback_resources.get::<Resources>()?.display_lut_signatures.get(&doc).copied()+ renderer.callback_resources.get::<Resources>()?.display_lut_signatures.get(&(doc, output)).copied()}- pub(crate) fn cache_display_lut_signature(&self, doc: u64, signature: u64, mode: u8) {+ /// Whether document `doc` has a display LUT for display `output` (tests).+ #[cfg(test)]+ pub(crate) fn has_display_lut(&self, doc: u64, output: u32) -> bool {+ let renderer = self.rs.renderer.read();+ renderer.callback_resources.get::<Resources>().is_some_and(|r| r.luts.contains_key(&(doc, output)))+ }++ pub(crate) fn cache_display_lut_signature(&self, doc: u64, output: u32, signature: u64, mode: u8) {let mut renderer = self.rs.renderer.write();if let Some(res) = renderer.callback_resources.get_mut::<Resources>() {- res.display_lut_signatures.insert(doc, (signature, mode));+ res.display_lut_signatures.insert((doc, output), (signature, mode));}}- /// Set (or clear with `None`) the display LUT of document `doc`: `size`³ RGBA8 texels, red- /// fastest. RGB is the display colour for each lattice input; alpha 255 marks out-of-gamut- /// colours for the gamut warning.- pub fn set_display_lut(&self, doc: u64, size: u32, rgba: Option<&[u8]>) {+ /// Set (or clear with `None`) the display LUT of document `doc` on display `output`:+ /// `size`³ RGBA8 texels, red fastest. RGB is the display colour for each lattice input;+ /// alpha 255 marks out-of-gamut colours for the gamut warning.+ pub fn set_display_lut(&self, doc: u64, output: u32, size: u32, rgba: Option<&[u8]>) {if !self.health.is_ok() {return;}let (device, queue) = (&self.rs.device, &self.rs.queue);let mut renderer = self.rs.renderer.write();let Some(res) = renderer.callback_resources.get_mut::<Resources>() else { return };- res.display_lut_signatures.remove(&doc);+ res.display_lut_signatures.remove(&(doc, output));match rgba {None => {- res.luts.remove(&doc);+ res.luts.remove(&(doc, output));}Some(bytes) => {if size < 2 || bytes.len() as u64 != (size as u64).pow(3) * 4 {@@ -618,7 +627,7 @@ impl GpuCanvas {return;}let bg = lut_bind_group(device, queue, &res.lut_bgl, size, bytes);- res.luts.insert(doc, bg);+ res.luts.insert((doc, output), bg);}}}@@ -1105,10 +1114,11 @@ struct Resources {encode_bgl: wgpu::BindGroupLayout,encode_pipeline: wgpu::RenderPipeline,lut_bgl: wgpu::BindGroupLayout,- /// Display LUTs per document (Proof Colors / Gamut Warning); `identity_lut` otherwise.- luts: HashMap<u64, wgpu::BindGroup>,+ /// Display LUTs per (document, display) (monitor profile, Proof Colors / Gamut Warning);+ /// `identity_lut` otherwise.+ luts: HashMap<(u64, u32), wgpu::BindGroup>,/// Signatures belong to their renderer resources, including identity transforms (mode 0).- display_lut_signatures: HashMap<u64, (u64, u8)>,+ display_lut_signatures: HashMap<(u64, u32), (u64, u8)>,identity_lut: wgpu::BindGroup,/// Transparency checkerboard and gamut warning colours (Preferences › Transparency & Gamut).style: CanvasStyle,@@ -1651,7 +1661,7 @@ impl CallbackTrait for CanvasCallback {let (cx0, cy0) = (clip.left_px as f32, clip.top_px as f32);let (cx1, cy1) = (cx0 + clip.width_px as f32, cy0 + clip.height_px as f32);pass.set_pipeline(&res.tile_pipeline);- pass.set_bind_group(2, res.luts.get(&self.params.doc).unwrap_or(&res.identity_lut), &[]);+ pass.set_bind_group(2, res.luts.get(&(self.params.doc, self.params.output)).unwrap_or(&res.identity_lut), &[]);for t in &doc.tiles {let [tx, ty, tw, th] = t.rect.map(|v| v as f32);let (x0, y0) = (origin[0] + tx * scale, origin[1] + ty * scale);diff --git a/crates/ui-egui/src/gpu_status.rs b/crates/ui-egui/src/gpu_status.rsindex 96de7c148..23b2be6f7 100644--- a/crates/ui-egui/src/gpu_status.rs+++ b/crates/ui-egui/src/gpu_status.rs@@ -2,7 +2,7 @@//! GPU canvas is dropped and every document keeps drawing through the CPU compositor and egui//! textures for the rest of the session, with a recovery warning. Also runs the desktop app's//! "started" hook once the first frames have rendered (the crash-safe startup marker), and-//! provides the Help › System Info text.+//! provides the Help › System Info text (including the monitor profile in use).use serde_json::json;@@ -63,6 +63,7 @@ pub fn system_info(app: &PhotocraftApp) -> Vec<String> {let mut v =vec![format!("PhotoCraft {}", photocraft_engine::build_info::long_version()), format!("Platform: {} {}", std::env::consts::OS, std::env::consts::ARCH)];v.extend(app.perf.gpu_info.lines());+ v.extend(crate::monitor_status::summary_lines(app));v}@@ -73,6 +74,8 @@ pub fn system_info_json(app: &PhotocraftApp) -> serde_json::Value {"os": std::env::consts::OS,"arch": std::env::consts::ARCH,"gpu": app.perf.gpu_info,+ "monitor": app.session.color.monitor_status(),+ "displays": app.session.color.display_statuses(),"lines": system_info(app),})}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex d0478e87e..8b951a7ed 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -74,6 +74,7 @@ pub mod mask_thumbs_ui;pub mod menu_catalog;pub mod menu_nav;pub mod menus;+pub mod monitor_status;pub mod move_mods;pub mod move_ui;pub mod new_doc_ui;@@ -245,13 +246,20 @@ pub struct Services {/// `photocraft_engine::preset_store`). Attached to the session once it arrives; without/// one, brush presets are session-only (web, tests).pub preset_store: Option<std::sync::mpsc::Receiver<photocraft_engine::preset_store::Opened>>,+ /// Reads the displays and their ICC profiles in the background (desktop macOS; see+ /// `monitor_status`). Without one, the canvas uses the profile chosen in Color Settings, or sRGB.+ pub read_displays: Option<monitor_status::ReadDisplaysFn>,}pub struct PhotocraftApp {pub session: Session,pub ui: UiState,pub services: Services,- canvases: HashMap<DocId, canvas::CanvasCache>,+ /// Canvas caches per (document, display): CPU textures hold monitor values; the GPU+ /// canvas state is shared (`canvas::GPU_OUTPUT`).+ canvases: HashMap<(DocId, u32), canvas::CanvasCache>,+ /// Display profile readings (#569).+ monitors: monitor_status::State,checker: Option<egui::TextureHandle>,drag: Option<canvas::Drag>,/// Brush/Eraser stroke being drawn, rendered by the engine (see `canvas::LiveStroke`).@@ -394,6 +402,7 @@ impl PhotocraftApp {ui: UiState::default(),services,canvases: HashMap::new(),+ monitors: Default::default(),checker: None,drag: None,live_stroke: None,@@ -871,6 +880,7 @@ impl eframe::App for PhotocraftApp {self.collect_screenshots(ctx);self.issue_screenshots(ctx);prefs_ui::tick(self, ctx);+ monitor_status::poll(self, ctx);// A window bigger than its display (1440 × 900 on 1366 × 768) runs under the taskbar:// maximize it into the work area once (#315).work_area::fit_window(ctx);diff --git a/crates/ui-egui/src/monitor_status.rs b/crates/ui-egui/src/monitor_status.rsnew file mode 100644index 000000000..fd485e7b9--- /dev/null+++ b/crates/ui-egui/src/monitor_status.rs@@ -0,0 +1,502 @@+//! The monitor profile in the shell (#569): reads the displays and their profiles through the+//! platform (`Services::read_displays`) at launch and again whenever they may have changed,+//! picks the display each window is on (its canvas is then shown in that display's profile),+//! says when the canvas falls back to sRGB, and gives Help › System Info its lines.+//!+//! A re-read is started when the app comes back to the front (a profile changed in System+//! Settings or by a calibration tool meanwhile), when any window is on no known display or the+//! display it is on doesn't have the size the reading said (a display connected, removed,+//! rearranged or set to another resolution), and when Edit › Color Settings opens. At most one+//! read runs at a time; the automatic triggers start at most one every [`REREAD_SECS`] (a+//! trigger inside that window is deferred, not dropped).+//!+//! There is deliberately no periodic re-read (#569 decision): a read costs about 0.2 s of CPU,+//! and a profile reassigned while PhotoCraft stays in front with no window moving practically+//! doesn't happen; it is picked up at the next return to the front or Color Settings.++use std::sync::mpsc::Receiver;++use photocraft_engine::display_color::{Display, MonitorDetection, display_at};++use crate::PhotocraftApp;++/// A platform reading: the displays, or why there are none.+pub type Detection = Result<Vec<Display>, String>;++/// Starts a reading in the background (`None`: no reader on this platform).+pub type ReadDisplaysFn = std::sync::Arc<dyn Fn() -> Option<Receiver<Detection>> + Send + Sync>;++/// Notice title when a display's profile can't be used.+pub const FALLBACK_TITLE: &str = "Display profile not used";++/// Minimum time between two readings started by the automatic triggers above.+pub const REREAD_SECS: f64 = 30.0;++/// The shell's reading state (`PhotocraftApp::monitors`).+#[derive(Default)]+pub struct State {+ pending: Option<Receiver<Detection>>,+ /// Another reading is wanted once the pending one is done or the interval has passed.+ again: bool,+ /// A reading is wanted at once (ignores the interval).+ now: bool,+ /// When the last reading started (egui time).+ started: Option<f64>,+ /// Whether any PhotoCraft window had the focus last frame (macOS reports focus per window:+ /// the user can come back to a document window while the main window stays unfocused).+ focused: Option<bool>,+ /// A document window had the focus this frame ([`check_window`]); counted at the next+ /// [`poll`], which runs before the document windows are drawn.+ window_focused: bool,+ /// Fallbacks already reported (display id, reason), so each is told once.+ reported: Vec<(u32, String)>,+}++/// A reading started before the shell existed (the desktop app starts one at launch and waits+/// for it briefly so the first frames already use the right profile): applied when it arrives.+pub fn pending(app: &mut PhotocraftApp, rx: Receiver<Detection>) {+ if app.session.color.displays.is_empty() {+ app.session.color.monitor_detection = MonitorDetection::Pending;+ }+ app.monitors.pending = Some(rx);+}++/// Per-frame (main window): apply a reading that arrived, track the main window's display, and+/// start a new reading when the displays may have changed.+pub fn poll(app: &mut PhotocraftApp, ctx: &egui::Context) {+ if let Some(rx) = &app.monitors.pending {+ let r = match rx.try_recv() {+ Ok(r) => Some(r),+ // No input may come for a while: keep a frame scheduled to pick it up.+ Err(std::sync::mpsc::TryRecvError::Empty) => None,+ Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(Err("the display profile reader stopped without an answer".into())),+ };+ match r {+ Some(r) => {+ app.monitors.pending = None;+ apply(app, r);+ ctx.request_repaint();+ }+ None => ctx.request_repaint_after(std::time::Duration::from_millis(250)),+ }+ }+ let main = view_display(app, ctx);+ if main != app.session.color.main_display {+ app.session.color.main_display = main;+ ctx.request_repaint();+ }+ let focused = ctx.input(|i| i.focused) || std::mem::take(&mut app.monitors.window_focused);+ let regained = focused && app.monitors.focused == Some(false);+ app.monitors.focused = Some(focused);+ if regained || displays_changed(app, ctx) {+ app.monitors.again = true;+ }+ if (app.monitors.again || app.monitors.now) && app.monitors.pending.is_none() {+ let now = ctx.input(|i| i.time);+ let wait = if app.monitors.now { 0.0 } else { app.monitors.started.map_or(0.0, |t| t + REREAD_SECS - now) };+ if wait <= 0.0 {+ start(app, now);+ // The reader doesn't wake the UI: keep frames coming until its result is in.+ if app.monitors.pending.is_some() {+ ctx.request_repaint_after(std::time::Duration::from_millis(250));+ }+ } else {+ ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait));+ }+ }+}++/// A document window's part of [`poll`] (`ctx` draws it): its focus counts as PhotoCraft+/// being in front, and a display it is on that the last reading didn't know (or whose size+/// changed) asks for a new reading. Either wakes the main window, whose frame starts the read+/// (r2: without that, nothing happens until other input arrives).+pub fn check_window(app: &mut PhotocraftApp, ctx: &egui::Context) {+ let mut wake = false;+ if ctx.input(|i| i.focused) {+ app.monitors.window_focused = true;+ wake |= app.monitors.focused == Some(false);+ }+ if displays_changed(app, ctx) && !app.monitors.again {+ app.monitors.again = true;+ wake = true;+ }+ if wake {+ ctx.request_repaint_of(egui::ViewportId::ROOT);+ }+}++/// Read the displays at the next frame regardless of the interval (a user action that shows+/// the result: opening Color Settings).+pub fn read_now(app: &mut PhotocraftApp) {+ app.monitors.now = true;+}++/// The Color Settings dialog's line: the monitor profile in use for the main window, as it is+/// now (the dialog asks again each time it draws).+pub fn note(app: &PhotocraftApp) -> String {+ let st = app.session.color.monitor_status();+ let on = st.display.as_ref().map(|d| format!(" on {d}")).unwrap_or_default();+ format!("Monitor profile in use{on}: {}{}", st.summary(), retained(app).map(|r| format!(" ({r})")).unwrap_or_default())+}++/// When the last re-read failed and an earlier reading is shown: why.+fn retained(app: &PhotocraftApp) -> Option<String> {+ match &app.session.color.monitor_detection {+ MonitorDetection::Retained { reason } => Some(format!("previous reading kept; the last re-read failed: {reason}")),+ _ => None,+ }+}++fn start(app: &mut PhotocraftApp, now: f64) {+ app.monitors.again = false;+ app.monitors.now = false;+ let Some(read) = app.services.read_displays.clone() else { return };+ app.monitors.started = Some(now);+ app.monitors.pending = read();+}++/// Record a reading. Displays whose profile can't be used leave their windows on sRGB: say so+/// once per display and reason (an unusable profile must not look like working colour+/// management). Manual monitor profiles don't depend on the reading. A failed re-read keeps the+/// previous reading and says so in the status.+pub fn apply(app: &mut PhotocraftApp, r: Detection) {+ if let Some(e) = app.session.color.set_displays(r) {+ log::warn!("re-reading the display profiles failed: {e}; keeping the previous ones");+ }+ let c = &app.session.color;+ let fallbacks: Vec<(u32, String, String)> = if c.displays.is_empty() {+ let st = c.monitor_status();+ match (st.source, st.reason, &st.detection) {+ ("fallback", Some(r), MonitorDetection::Failed { .. }) => vec![(0, String::new(), r)],+ _ => vec![],+ }+ } else {+ c.displays+ .iter()+ .filter_map(|d| {+ let st = c.monitor_status_for(Some(d.id));+ (st.source == "fallback" && st.requested == "auto").then(|| (d.id, d.name.clone(), st.reason.unwrap_or_default()))+ })+ .collect()+ };+ for (id, name, reason) in fallbacks {+ if app.monitors.reported.iter().any(|(i, r)| *i == id && *r == reason) {+ continue;+ }+ app.monitors.reported.push((id, reason.clone()));+ let on = if name.is_empty() { String::new() } else { format!(" on {name}") };+ let lines = vec![reason, format!("The canvas{on} is shown as sRGB. Choose a monitor profile in Edit › Color Settings.")];+ crate::notices::post(app, FALLBACK_TITLE, lines, true, None);+ }+}++/// The frame of the window `ctx` draws, in OS points (as `Display::frame`). egui reports it in+/// its own points, which include the UI zoom.+fn window_frame(ctx: &egui::Context) -> Option<[f64; 4]> {+ let (r, native) = ctx.input(|i| (i.viewport().outer_rect, i.viewport().native_pixels_per_point));+ let r = r?;+ let f = f64::from(ctx.pixels_per_point() / native.filter(|n| *n > 0.0)?);+ let v = [f64::from(r.min.x) * f, f64::from(r.min.y) * f, f64::from(r.width()) * f, f64::from(r.height()) * f];+ v.iter().all(|x| x.is_finite()).then_some(v)+}++/// The display showing most of the window `ctx` draws (`None`: unknown, e.g. no displays read+/// or no window position, as on Wayland).+pub fn view_display(app: &PhotocraftApp, ctx: &egui::Context) -> Option<u32> {+ display_at(&app.session.color.displays, window_frame(ctx)?)+}++/// The window is on no display we know, or on one whose size differs from what was read.+fn displays_changed(app: &PhotocraftApp, ctx: &egui::Context) -> bool {+ let c = &app.session.color;+ if c.displays.is_empty() || !matches!(c.monitor_detection, MonitorDetection::Found | MonitorDetection::Retained { .. }) {+ return false;+ }+ let Some(frame) = window_frame(ctx) else { return false };+ let Some(d) = display_at(&c.displays, frame).and_then(|id| c.displays.iter().find(|d| d.id == id)) else { return true };+ // egui's monitor size is the window's display (winit's rule, AppKit's on macOS).+ let size = ctx.input(|i| i.viewport().monitor_size);+ let native = ctx.input(|i| i.viewport().native_pixels_per_point).filter(|n| *n > 0.0);+ match (size, native) {+ (Some(s), Some(n)) => {+ let f = f64::from(ctx.pixels_per_point() / n);+ (f64::from(s.x) * f - d.frame[2]).abs() > 2.0 || (f64::from(s.y) * f - d.frame[3]).abs() > 2.0+ }+ _ => false,+ }+}++/// Help › System Info's lines: the monitor profile of each display.+pub fn summary_lines(app: &PhotocraftApp) -> Vec<String> {+ let c = &app.session.color;+ if c.displays.is_empty() {+ return vec![format!("Monitor profile: {}", c.monitor_status().summary())];+ }+ let mut lines: Vec<String> = c+ .displays+ .iter()+ .map(|d| {+ let main = if c.main_display == Some(d.id) { " (main window)" } else { "" };+ format!("Monitor profile on {}{main}: {}", d.name, c.monitor_status_for(Some(d.id)).summary())+ })+ .collect();+ lines.extend(retained(app).map(|r| format!("Display profiles: {r}")));+ lines+}++#[cfg(test)]+mod tests {+ use super::*;+ use photocraft_engine::Session;+ use std::sync::Arc;++ fn app() -> PhotocraftApp {+ PhotocraftApp::new(Session::new(), Default::default())+ }++ fn p3() -> Option<Arc<Vec<u8>>> {+ Some(photocraft_engine::color_cmds::resolve_profile("display-p3", None, None).unwrap().to_bytes())+ }++ /// The #569 setup: built-in display (primary) without a usable profile here, a P3 one to its+ /// right and higher up.+ fn displays(builtin: Option<Arc<Vec<u8>>>) -> Vec<Display> {+ vec![+ Display { id: 1, name: "Built-in Retina Display".into(), frame: [0.0, 0.0, 1728.0, 1117.0], profile_name: Some("Color LCD".into()), icc: builtin },+ Display { id: 4, name: "ROG PG32UQX".into(), frame: [1728.0, -667.0, 3008.0, 1692.0], profile_name: Some("Apple_Display".into()), icc: p3() },+ ]+ }++ /// One frame of the main window at `pos` (points; UI zoom 1) with `focused`; returns when+ /// egui is asked to draw the next one.+ fn frame(app: &mut PhotocraftApp, ctx: &egui::Context, t: f64, pos: [f32; 2], monitor: [f32; 2], focused: bool) -> std::time::Duration {+ let mut input = egui::RawInput { time: Some(t), focused, ..Default::default() };+ let vp = input.viewports.entry(egui::ViewportId::ROOT).or_default();+ vp.native_pixels_per_point = Some(1.0);+ vp.outer_rect = Some(egui::Rect::from_min_size(egui::pos2(pos[0], pos[1]), egui::vec2(800.0, 600.0)));+ vp.monitor_size = Some(egui::vec2(monitor[0], monitor[1]));+ vp.focused = Some(focused);+ let mut out = ctx.run_ui(input, |ui| poll(app, ui.ctx()));+ out.textures_delta.clear();+ out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay)+ }++ /// A reader whose readings arrive only when the test sends them (on `tx`).+ fn manual_reader(app: &mut PhotocraftApp) -> (Arc<std::sync::atomic::AtomicUsize>, std::sync::mpsc::Receiver<std::sync::mpsc::Sender<Detection>>) {+ let n = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let count = n.clone();+ let (give, take) = std::sync::mpsc::channel();+ let give = std::sync::Mutex::new(give);+ app.services.read_displays = Some(Arc::new(move || {+ count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ let (tx, rx) = std::sync::mpsc::channel();+ let _ = give.lock().unwrap().send(tx);+ Some(rx)+ }));+ (n, take)+ }++ /// A reader that counts its readings and returns `displays` each time.+ fn reader(app: &mut PhotocraftApp, displays: Vec<Display>) -> Arc<std::sync::atomic::AtomicUsize> {+ let n = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let count = n.clone();+ app.services.read_displays = Some(Arc::new(move || {+ count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ let (tx, rx) = std::sync::mpsc::channel();+ let _ = tx.send(Ok(displays.clone()));+ Some(rx)+ }));+ n+ }++ #[test]+ fn a_late_reading_is_applied_and_windows_follow_their_display() {+ let mut app = app();+ let ctx = egui::Context::default();+ let (tx, rx) = std::sync::mpsc::channel();+ pending(&mut app, rx);+ frame(&mut app, &ctx, 0.0, [100.0, 100.0], [1728.0, 1117.0], true);+ assert!(app.monitors.pending.is_some(), "still waiting");+ assert!(summary_lines(&app)[0].contains("hasn't been read yet"), "{:?}", summary_lines(&app));+ tx.send(Ok(displays(None))).unwrap();+ frame(&mut app, &ctx, 0.1, [100.0, 100.0], [1728.0, 1117.0], true);+ assert!(app.monitors.pending.is_none());+ // On the built-in display (no profile here): sRGB, reported once.+ assert_eq!(app.session.color.main_display, Some(1));+ assert_eq!(app.ui.notices.len(), 1);+ assert!(app.ui.notices[0].lines[0].contains("Built-in Retina Display has no ICC profile"));+ // Moved to the external display: its profile, without a restart.+ frame(&mut app, &ctx, 0.2, [2000.0, -500.0], [3008.0, 1692.0], true);+ assert_eq!(app.session.color.main_display, Some(4));+ assert_eq!(app.session.color.monitor().description, "Display P3");+ let lines = summary_lines(&app);+ assert_eq!(lines[1], "Monitor profile on ROG PG32UQX (main window): Apple_Display (auto)", "{lines:?}");+ assert!(lines[0].starts_with("Monitor profile on Built-in Retina Display: sRGB"), "{lines:?}");+ }++ #[test]+ fn displays_are_read_again_when_they_may_have_changed() {+ let mut app = app();+ let ctx = egui::Context::default();+ app.session.color.set_displays(Ok(displays(p3())));+ let reads = reader(&mut app, displays(p3()));+ let count = || reads.load(std::sync::atomic::Ordering::SeqCst);+ frame(&mut app, &ctx, 100.0, [100.0, 100.0], [1728.0, 1117.0], true);+ assert_eq!(count(), 0, "nothing changed: no periodic reading");+ for t in 1..20 {+ frame(&mut app, &ctx, 100.0 + 10.0 * f64::from(t), [100.0, 100.0], [1728.0, 1117.0], true);+ }+ assert_eq!(count(), 0, "still none after minutes");+ // Back to the front after another app had it (e.g. System Settings, a calibration tool).+ frame(&mut app, &ctx, 400.0, [100.0, 100.0], [1728.0, 1117.0], false);+ frame(&mut app, &ctx, 401.0, [100.0, 100.0], [1728.0, 1117.0], true);+ assert_eq!(count(), 1);+ // Back to the front again within 30 s: deferred, not dropped.+ frame(&mut app, &ctx, 405.0, [100.0, 100.0], [1728.0, 1117.0], false);+ let wait = frame(&mut app, &ctx, 406.0, [100.0, 100.0], [1728.0, 1117.0], true);+ assert_eq!(count(), 1);+ assert!(wait <= std::time::Duration::from_secs(26), "a frame is scheduled for the deferred read: {wait:?}");+ frame(&mut app, &ctx, 431.5, [100.0, 100.0], [1728.0, 1117.0], true);+ assert_eq!(count(), 2);+ // The display reports another size (resolution changed).+ app.monitors.started = None;+ frame(&mut app, &ctx, 500.0, [100.0, 100.0], [1512.0, 982.0], true);+ assert_eq!(count(), 3);+ // Opening Color Settings reads at once, inside the interval.+ crate::prefs_ui::invoke(&mut app, &ctx, "edit.colorSettings", &serde_json::json!({}));+ frame(&mut app, &ctx, 501.0, [100.0, 100.0], [1728.0, 1117.0], true);+ assert_eq!(count(), 4);+ }++ #[test]+ fn a_started_reading_is_picked_up_without_input() {+ // r1 finding 2: a reading started when the interval runs out must schedule the frame+ // that applies its result; the reader doesn't wake the UI.+ let mut app = app();+ let ctx = egui::Context::default();+ app.session.color.set_displays(Ok(displays(None)));+ let (count, readers) = manual_reader(&mut app);+ frame(&mut app, &ctx, 0.0, [100.0, 100.0], [1728.0, 1117.0], false);+ let wait = frame(&mut app, &ctx, 1.0, [100.0, 100.0], [1728.0, 1117.0], true);+ assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1);+ assert!(wait <= std::time::Duration::from_millis(250), "next frame scheduled: {wait:?}");+ readers.recv().unwrap().send(Ok(displays(p3()))).unwrap();+ frame(&mut app, &ctx, 1.25, [100.0, 100.0], [1728.0, 1117.0], true);+ assert_eq!(app.session.color.monitor().description, "Display P3");+ }++ /// One frame of a document window at `pos` with `focused` (its part of the shell is+ /// [`check_window`]); returns when the main window is asked to draw next.+ fn doc_window(app: &mut PhotocraftApp, ctx: &egui::Context, pos: [f32; 2], focused: bool) -> std::time::Duration {+ let mut input = egui::RawInput { focused, ..Default::default() };+ let vp = input.viewports.entry(egui::ViewportId::ROOT).or_default();+ vp.native_pixels_per_point = Some(1.0);+ vp.outer_rect = Some(egui::Rect::from_min_size(egui::pos2(pos[0], pos[1]), egui::vec2(800.0, 600.0)));+ vp.monitor_size = Some(egui::vec2(1728.0, 1117.0));+ let mut out = ctx.run_ui(input, |ui| check_window(app, ui.ctx()));+ out.textures_delta.clear();+ out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay)+ }++ #[test]+ fn a_document_window_on_an_unknown_display_asks_for_a_reading() {+ // r1 finding 1 / r2 finding 2: a display connected while only a document window is on+ // it. The trigger must also wake the main window, whose frame starts the read.+ let mut app = app();+ let (main, doc) = (egui::Context::default(), egui::Context::default());+ app.session.color.set_displays(Ok(displays(p3())));+ let reads = reader(&mut app, displays(p3()));+ frame(&mut app, &main, 100.0, [100.0, 100.0], [1728.0, 1117.0], true);+ // A new egui context asks for a few frames of its own first.+ for _ in 0..3 {+ doc_window(&mut app, &doc, [100.0, 100.0], false);+ }+ assert_eq!(doc_window(&mut app, &doc, [100.0, 100.0], false), std::time::Duration::MAX, "nothing changed: no wake-up");+ assert_eq!(doc_window(&mut app, &doc, [9000.0, 0.0], false), std::time::Duration::ZERO, "the main window is woken");+ frame(&mut app, &main, 100.1, [100.0, 100.0], [1728.0, 1117.0], true);+ assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 1);+ }++ #[test]+ fn coming_back_through_a_document_window_reads_again() {+ // r2 finding 1: System Settings → back to a document window; the main window stays+ // unfocused (macOS reports focus per window).+ let mut app = app();+ let (main, doc) = (egui::Context::default(), egui::Context::default());+ app.session.color.set_displays(Ok(displays(p3())));+ let reads = reader(&mut app, displays(p3()));+ let count = || reads.load(std::sync::atomic::Ordering::SeqCst);+ // Working in the document window: PhotoCraft is in front, no reading.+ for _ in 0..3 {+ doc_window(&mut app, &doc, [100.0, 100.0], true);+ }+ frame(&mut app, &main, 100.0, [100.0, 100.0], [1728.0, 1117.0], false);+ doc_window(&mut app, &doc, [100.0, 100.0], true);+ frame(&mut app, &main, 101.0, [100.0, 100.0], [1728.0, 1117.0], false);+ assert_eq!(count(), 0);+ // Another app in front: no PhotoCraft window has the focus.+ doc_window(&mut app, &doc, [100.0, 100.0], false);+ frame(&mut app, &main, 102.0, [100.0, 100.0], [1728.0, 1117.0], false);+ frame(&mut app, &main, 150.0, [100.0, 100.0], [1728.0, 1117.0], false);+ assert_eq!(count(), 0);+ // Back to the document window: it wakes the main window, which reads.+ assert_eq!(doc_window(&mut app, &doc, [100.0, 100.0], true), std::time::Duration::ZERO);+ frame(&mut app, &main, 151.0, [100.0, 100.0], [1728.0, 1117.0], false);+ assert_eq!(count(), 1);+ // Staying there doesn't read again.+ for t in 0..10 {+ doc_window(&mut app, &doc, [100.0, 100.0], true);+ frame(&mut app, &main, 152.0 + 10.0 * f64::from(t), [100.0, 100.0], [1728.0, 1117.0], false);+ }+ assert_eq!(count(), 1);+ }++ #[test]+ fn color_settings_shows_the_profile_in_use_now() {+ // r1 finding 4: the dialog's line follows a reading that arrives while it is open.+ let mut app = app();+ let ctx = egui::Context::default();+ app.session.color.set_displays(Ok(displays(None)));+ app.session.color.main_display = Some(1);+ let d = crate::prefs_ui::invoke(&mut app, &ctx, "edit.colorSettings", &serde_json::json!({})).unwrap().unwrap()["dialog"].as_u64().unwrap();+ let shown = |app: &PhotocraftApp| app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["__note"].as_str().unwrap().to_string();+ assert!(shown(&app).contains("on Built-in Retina Display: sRGB") && shown(&app).contains("fallback"), "{}", shown(&app));+ apply(&mut app, Ok(displays(p3())));+ app.session.color.main_display = Some(4);+ // Drawing the dialog refreshes the line.+ PhotocraftApp::setup_context(&ctx, Default::default());+ let mut out = ctx.run_ui(Default::default(), |ui| crate::dialogs::show(&mut app, ui.ctx()));+ out.textures_delta.clear();+ assert_eq!(shown(&app), "Monitor profile in use on ROG PG32UQX: Apple_Display (auto)");+ // A failed re-read keeps the reading and says so.+ apply(&mut app, Err("osascript failed".into()));+ assert!(note(&app).ends_with("(previous reading kept; the last re-read failed: osascript failed)"), "{}", note(&app));+ assert!(summary_lines(&app).last().unwrap().contains("the last re-read failed"));+ }++ #[test]+ fn a_reader_that_dies_is_a_fallback() {+ let mut app = app();+ let (tx, rx) = std::sync::mpsc::channel::<Detection>();+ pending(&mut app, rx);+ drop(tx);+ poll(&mut app, &egui::Context::default());+ assert!(app.monitors.pending.is_none());+ assert_eq!(app.ui.notices.len(), 1);+ assert!(app.ui.notices[0].lines[0].contains("stopped without an answer"));+ }++ #[test]+ fn manual_profiles_are_quiet_and_a_failed_reread_keeps_the_displays() {+ let mut app = app();+ apply(&mut app, Ok(displays(p3())));+ assert!(app.ui.notices.is_empty());+ apply(&mut app, Err("osascript failed".into()));+ assert_eq!(app.session.color.displays.len(), 2);+ assert!(app.ui.notices.is_empty());+ app.run("edit.colorSettings", serde_json::json!({"monitorProfile": "srgb"})).unwrap();+ apply(&mut app, Ok(displays(Some(Arc::new(vec![0u8; 200])))));+ assert!(app.ui.notices.is_empty());+ assert!(summary_lines(&app).iter().all(|l| l.contains("(manual)")), "{:?}", summary_lines(&app));+ }+}diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rsindex abc3be82d..9ac034492 100644--- a/crates/ui-egui/src/prefs_ui.rs+++ b/crates/ui-egui/src/prefs_ui.rs@@ -548,13 +548,18 @@ pub fn invoke(app: &mut PhotocraftApp, _ctx: &egui::Context, id: &str, params: &"edit.toolbar" => Some(Ok(json!({"dialog": open_shortcuts(app, 2)}))),"edit.colorSettings" => {let d = crate::filter_dialog::open(app, "edit.colorSettings");+ let cur = serde_json::to_value(&app.session.color.settings).unwrap_or_default();+ // What Monitor Profile resolves to, so a fallback to sRGB is visible (#569): read the+ // displays again now, and the dialog refreshes this line as it draws.+ crate::monitor_status::read_now(app);+ let note = crate::monitor_status::note(app);if let Some(dm) = d.and_then(|d| app.ui.dialog_mut(d)) {- let cur = serde_json::to_value(&app.session.color.settings).unwrap_or_default();for (k, v) in cur.as_object().into_iter().flatten() {if dm.fields.contains_key(k) {dm.fields.insert(k.clone(), v.clone());}}+ dm.fields.insert("__note".into(), json!(note));}dialog(d)}@@ -1944,6 +1949,8 @@ mod tests {app.sync_views();let d = crate::menus::invoke(&mut app, &ctx, "edit.colorSettings", json!({})).unwrap()["dialog"].as_u64().unwrap();assert_eq!(app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["workingRgb"], "srgb");+ let note = app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["__note"].as_str().unwrap().to_string();+ assert!(note.starts_with("Monitor profile in use: sRGB") && note.contains("fallback"), "{note}");assert!(crate::menus::invoke(&mut app, &ctx, "edit.fade", json!({})).is_err());app.run("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap();let d = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({})).unwrap()["dialog"].as_u64().unwrap();diff --git a/crates/ui-egui/tests/gpu_device_loss.rs b/crates/ui-egui/tests/gpu_device_loss.rsindex f8da5cdb0..22cdd0e2d 100644--- a/crates/ui-egui/tests/gpu_device_loss.rs+++ b/crates/ui-egui/tests/gpu_device_loss.rs@@ -49,7 +49,7 @@ fn injected_loss_stops_gpu_work_without_panicking() {assert!(g.composite(&d, d.bounds(), false).is_err());assert!(!g.upload_rect(key, [0, 0], [1, 1], &[0; 4]));g.upload_full(key, [1, 1], &[0; 4]);- g.set_display_lut(key, 2, Some(&[0; 32]));+ g.set_display_lut(key, 0, 2, Some(&[0; 32]));assert!(g.read_texels(key).is_none());g.release();assert!(!g.has(key, [300, 200]));diff --git a/docs/architecture.md b/docs/architecture.mdindex 330d15d84..932889ae6 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -318,7 +318,7 @@ Both backends consume the same plan. This is the only place that encodes Photosh- Blending happens in document space by default, which is Photoshop-compatible. A per-document "linear light blending" option is also available.- **Display transform** (`engine/src/display_color.rs`): the canvas is always colour-managed, document profile → monitor profile (relative colorimetric + BPC), cached per (document profile, mode, monitor). On the GPU canvas the transform, plus Proof Colors / Gamut Warning / 32-bit preview, is baked into a 33³ 3D LUT the canvas shader's final pass applies; the CPU canvas runs an 8-bit `photocraft-cms` transform on the composite. When the document profile matches the monitor (sRGB on sRGB) there is no LUT and no transform. Linear composites (EXR/HDR, tagged linear sRGB on import) are stored sRGB-encoded in the 8-bit canvas texture. CMYK documents are read through their embedded CMYK profile (`photocraft_color::convert::with_cmyk_space`, entered by the compositors and composite exports).-- **Monitor profile:** Edit › Color Settings › Monitor Profile: `auto` (macOS: the main display's profile, read at launch through `osascript`/AppKit `NSScreen.colorSpace.ICCProfileData`, no FFI; elsewhere sRGB), a built-in RGB profile or an `.icc` path. The profile is not re-read when the window moves to another display.+- **Monitor profile:** Edit › Color Settings › Monitor Profile: `auto`, a built-in RGB profile or an `.icc` path. In `auto` each window uses the profile of the display it is on (#569): the desktop app reads every display's id, name, frame and ICC profile (macOS: AppKit `NSScreen` through `osascript`, no FFI) at launch and again when the app comes back to the front, when any window is on an unknown or resized display (at most every 30 s; a trigger inside that window is deferred) and when Edit › Color Settings opens (`ui-egui/src/monitor_status.rs`; the helper is stopped after 10 s). There is deliberately no periodic re-read (#569 decision: a read costs about 0.2 s of CPU), so a profile reassigned while PhotoCraft stays in front with no window moving is picked up at the next return to the front or Color Settings, and each window picks the display it overlaps most (`display_color::display_at`, AppKit's `NSWindow.screen` rule). Elsewhere `auto` is sRGB. The GPU canvas keeps one texture per document and a display LUT per (document, display); CPU canvas textures are per (document, display). `ColorState::monitor_status_for` says what is applied per display: `auto`, `manual`, or `fallback` to sRGB with the reason (missing, unreadable, non-RGB or unusable as a destination), and whether the reading is an earlier one kept after a failed re-read; `edit.colorSettings` (`monitorStatus`, `displays`), Help › System Info and the Color Settings dialog show it, and a fallback in `auto` posts a notice. Letting macOS colour-match the canvas instead is #581 (an architecture decision).- **HDR/EDR output** (an `rgba16float` surface with an extended-range colorspace) is a later-phase feature. The interfaces already carry `f32` pixels.### 7.4 Oracle