diff --git a/apps/photocraft-web/src/preset_bridge.rs b/apps/photocraft-web/src/preset_bridge.rs index a7445bbc14..a39fdfb4b4 100644 --- a/apps/photocraft-web/src/preset_bridge.rs +++ b/apps/photocraft-web/src/preset_bridge.rs @@ -9,8 +9,8 @@ use photocraft_engine::{ }; pub type Batch = BTreeMap>>; -/// Three sampled images per preset (tip, dual tip, texture), plus group/index/action records. -pub const MAX_RECORDS: usize = MAX_GROUPS + MAX_PRESETS_PER_GROUP * 3 + 2; +/// Three sampled images per preset (tip, dual tip, texture), plus group/index/action/pattern records. +pub const MAX_RECORDS: usize = MAX_GROUPS + MAX_PRESETS_PER_GROUP * 3 + 3; #[derive(Default)] struct State { @@ -45,6 +45,7 @@ pub fn record_limit(name: &str) -> Result { match name { INDEX_FILE => Ok(MAX_INDEX_BYTES), ACTIONS_FILE => Ok(MAX_ACTIONS_BYTES), + PATTERNS_FILE => Ok(MAX_PATTERNS_BYTES), _ if name.starts_with("tips/") && leaf.ends_with(".pctip") => Ok(MAX_TIP_BYTES), _ if !name.contains('/') && name.ends_with(".pcbrushes") => Ok(MAX_GROUP_BYTES), _ => Err("unknown preset record type".into()), diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 089ea97062..69442735a5 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -105,6 +105,7 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[ // Game and 3D textures; DDS Options asks for the compression and mipmaps (#1327). ("DDS", &["dds"]), ("Cineon", &["cin"]), + ("Amiga IFF", &["iff"]), ]; /// Non-document files the shell saves (Swatches panel exports): offered alone, so the dialog diff --git a/contributors/people.toml b/contributors/people.toml index 3fdb201a7f..22fa8991e1 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -267,3 +267,14 @@ real_name = "Kushagra Sharma" [people.WebWork-rrs] display_name = "Ratul Paul" + +[people.softwaregames1] +sync_github_name = true + +[people.VoiceLessQ] +display_name = "VoiceLessQ" +sync_github_name = false + +[people.erenova] +display_name = "Erenova" +sync_github_name = false diff --git a/crates/algo/src/camera_raw.rs b/crates/algo/src/camera_raw.rs index 5cf7a241a9..5bd0c8ab06 100644 --- a/crates/algo/src/camera_raw.rs +++ b/crates/algo/src/camera_raw.rs @@ -948,23 +948,25 @@ fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, amount: f32) { *s = s.map(|v| v / c.max(1.0)); } let r = (sw.max(sh) / 60).max(2); - let min_filter = |v: &[f32]| -> Vec { + // The minimum (or, with `f32::max`, maximum) over each (2r + 1)² window. + let rank_filter = |v: &[f32], start: f32, pick: fn(f32, f32) -> f32| -> Vec { let mut a = vec![0.0f32; sw * sh]; for y in 0..sh { for x in 0..sw { let (x0, x1) = (x.saturating_sub(r), (x + r).min(sw - 1)); - a[y * sw + x] = (x0..=x1).map(|xx| v[y * sw + xx]).fold(f32::MAX, f32::min); + a[y * sw + x] = (x0..=x1).map(|xx| v[y * sw + xx]).fold(start, pick); } } let mut b = vec![0.0f32; sw * sh]; for y in 0..sh { for x in 0..sw { let (y0, y1) = (y.saturating_sub(r), (y + r).min(sh - 1)); - b[y * sw + x] = (y0..=y1).map(|yy| a[yy * sw + x]).fold(f32::MAX, f32::min); + b[y * sw + x] = (y0..=y1).map(|yy| a[yy * sw + x]).fold(start, pick); } } b }; + let min_filter = |v: &[f32]| rank_filter(v, f32::MAX, f32::min); let dark = min_filter(&small.iter().map(|c| c[0].min(c[1]).min(c[2])).collect::>()); // Atmospheric light: mean colour of the brightest 0.1 % of the dark channel. let mut idx: Vec = (0..sw * sh).collect(); @@ -978,7 +980,15 @@ fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, amount: f32) { } let air = air.map(|v| v.max(0.2)); let norm_dark = min_filter(&small.iter().map(|c| (c[0] / air[0]).min(c[1] / air[1]).min(c[2] / air[2])).collect::>()); - let t_raw: Vec = norm_dark.iter().map(|d| 1.0 - 0.95 * d).collect(); + // Opened (a maximum filter of the same radius after the minimum): the minimum grows every + // dark object by `r`, so sky beside a dark building took its dark channel, counted as + // haze-free and kept a bright halo (#9273). Opening shrinks dark regions back to their + // outline and is still a lower bound of the dark channel over the window. It raises the dark + // channel on average, so the 0.95 weight is scaled to keep the slider's overall strength. + let opened = rank_filter(&norm_dark, f32::MIN, f32::max); + let mean = |v: &[f32]| v.iter().sum::() / v.len().max(1) as f32; + let weight = 0.95 * mean(&norm_dark) / mean(&opened).max(1e-6); + let t_raw: Vec = opened.iter().map(|d| 1.0 - weight * d).collect(); let guide: Vec = small.iter().map(|c| luma(*c)).collect(); let t = guided(&guide, &t_raw, sw, sh, r * 2, 1e-3); let ks = k as f32; @@ -1098,6 +1108,37 @@ fn vignette(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw) { mod tests { use super::*; + /// #9273: Dehaze clears the haze evenly over a sky, right up to a dark building, instead of + /// leaving a bright halo of uncorrected haze around it. Synthetic scene: a clear sky and a + /// dark tower, hazed with `I = J·t + A·(1 − t)`. + #[test] + fn dehaze_leaves_no_halo_beside_dark_objects() { + let (w, h) = (600usize, 400usize); + let tower = |x: usize, y: usize| (250..350).contains(&x) && y >= 120; + let (t, air) = (0.55f32, [0.9f32, 0.9, 0.9]); + let mut px: Vec<[f32; 4]> = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let j = if tower(x, y) { [0.06, 0.06, 0.07] } else { [0.35 + 0.1 * y as f32 / h as f32, 0.5, 0.8] }; + let c: [f32; 3] = std::array::from_fn(|k| j[k] * t + air[k] * (1.0 - t)); + [c[0], c[1], c[2], 1.0] + }) + .collect(); + dehaze(&mut px, w, h, 1.0); + let sky = |xs: std::ops::Range| { + let v: Vec = + (150..390).flat_map(|y| xs.clone().map(move |x| (x, y))).map(|(x, y)| luma([px[y * w + x][0], px[y * w + x][1], px[y * w + x][2]])).collect(); + v.iter().sum::() / v.len() as f32 + }; + // Sky 1–8 px from the tower against open sky: the haze left beside it, in 8-bit levels. + let halo = (sky(242..250) - sky(20..80)) * 255.0; + // 6.4 levels before the dark channel was opened, under 1 after. + assert!(halo < 3.0, "a {halo:.1}-level halo beside the tower"); + // The open sky is still cleared: darker than the hazy input. + let hazy = luma(std::array::from_fn(|k| [0.4, 0.5, 0.8][k] * t + air[k] * (1.0 - t))); + assert!(sky(20..80) < hazy - 0.02, "{} vs hazy {hazy}", sky(20..80)); + } + #[test] fn new_curves_are_validated_but_saved_curves_still_load_and_render() { for field in ["pointCurve", "pointCurveRed", "pointCurveGreen", "pointCurveBlue"] { diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index e8566b439e..12e7329180 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -806,6 +806,21 @@ mod tests { assert!(authorize_desktop_engine_step("file.saveACopy", &serde_json::json!({})).is_err()); } + // Regression test for #3763: `edit.installedProfiles` scans the OS and user ICC folders but + // takes no path parameter, so automation let it through until it was listed as ambient. + #[test] + fn installed_profiles_listing_is_refused_for_automation() { + for params in [serde_json::json!({}), serde_json::json!({"class": "output", "colorSpace": "cmyk"})] { + assert!(authorize_engine_command("edit.installedProfiles", ¶ms).is_err(), "authorize_engine_command allowed it with {params}"); + assert!(authorize_desktop_engine_command("edit.installedProfiles", ¶ms).is_err(), "authorize_desktop_engine_command allowed it with {params}"); + assert!(authorize_engine_step("edit.installedProfiles", ¶ms).is_err(), "authorize_engine_step allowed it with {params}"); + } + // The sandboxed session refuses it before the engine scans any folder. + let mut headless = crate::Headless::new(); + let refused = headless.command_run("edit.installedProfiles", serde_json::json!({})).unwrap_err(); + assert!(refused.to_string().contains("ambient filesystem paths"), "{refused}"); + } + #[test] fn apply_data_set_is_judged_by_the_values_it_applies() { let mut headless = crate::Headless::new(); diff --git a/crates/automation/tests/it/smart_filter_authorization.rs b/crates/automation/tests/it/smart_filter_authorization.rs index 594832c41d..0a39df85f5 100644 --- a/crates/automation/tests/it/smart_filter_authorization.rs +++ b/crates/automation/tests/it/smart_filter_authorization.rs @@ -1,94 +1,15 @@ //! Stored smart-filter parameters must not grant automation ambient filesystem access. -use std::path::{Path, PathBuf}; -use std::sync::{ - Arc, - atomic::{AtomicU64, Ordering}, -}; +use std::path::Path; +use std::sync::Arc; -use photocraft_automation::{AuthorizedWorkspace, Headless, workspace::authorize_desktop_engine_step}; -use photocraft_doc::{Document, LayerContent, LayerId}; +#[path = "../support/smart_filter_fixture.rs"] +mod fixture; + +use fixture::{Fixture, assert_denied, cube, path_params}; +use photocraft_automation::{Headless, workspace::authorize_desktop_engine_step}; +use photocraft_doc::LayerContent; use photocraft_engine::{Session, actions_cmds::Action, jobs::Started, smart_cmds}; -use serde_json::{Value, json}; - -struct Fixture(PathBuf); - -impl Fixture { - fn new() -> Self { - static NEXT: AtomicU64 = AtomicU64::new(0); - let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); - let base = std::env::temp_dir().join(format!("pc-filter-auth-{}-{stamp}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); - std::fs::create_dir(&base).unwrap(); - std::fs::create_dir(base.join("workspace")).unwrap(); - std::fs::create_dir(base.join("outside")).unwrap(); - let f = Self(base); - std::fs::write(f.root().join("stripes.png"), png(|x| if (x / 2) % 2 == 0 { 0 } else { 255 })).unwrap(); - std::fs::write(f.outside("black.png"), png(|_| 0)).unwrap(); - std::fs::write(f.outside("white.png"), png(|_| 255)).unwrap(); - std::fs::write(f.outside("black.cube"), cube(0)).unwrap(); - std::fs::write(f.outside("white.cube"), cube(1)).unwrap(); - f - } - - fn root(&self) -> PathBuf { - self.0.join("workspace") - } - fn outside(&self, name: &str) -> PathBuf { - self.0.join("outside").join(name) - } - fn headless(&self) -> Headless { - Headless::with_workspace(AuthorizedWorkspace::new(Some(&self.root()), Some(&self.root())).unwrap()) - } - fn setup(&self, lookup: bool) -> (Headless, LayerId) { - let mut h = self.headless(); - h.handle("doc.new", json!({"width": 32, "height": 32, "background": "#808080"})).unwrap(); - h.handle("doc.new", json!({"width": 32, "height": 32})).unwrap(); - let layer = LayerId(h.handle("doc.place", json!({"path": "stripes.png"})).unwrap()["layer"].as_u64().unwrap()); - let (id, params) = if lookup { - ("image.adjustments.colorLookup", json!({"layer": layer.0, "lut": "none"})) - } else { - ("filter.distort.displace", json!({"layer": layer.0, "mapDocument": 0, "horizontal": 50, "vertical": 0})) - }; - h.session.execute(id, params).unwrap(); - (h, layer) - } - fn saved_filter(&self, lookup: bool) -> (Document, LayerId) { - let (h, layer) = self.setup(lookup); - let mut doc = (*h.session.active().unwrap().doc).clone(); - let LayerContent::Smart(sm) = &mut doc.layer_mut(layer).unwrap().content else { panic!("smart object") }; - sm.smart_filters[0].params = path_params(lookup, &self.outside(if lookup { "white.cube" } else { "white.png" })); - let bytes = photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap(); - std::fs::write(self.root().join("stored.pcraft"), bytes).unwrap(); - (doc, layer) - } -} -impl Drop for Fixture { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - -fn png(value: impl Fn(u32) -> u8) -> Vec { - let mut pixels = Vec::new(); - for _ in 0..32 { - for x in 0..32 { - pixels.extend([value(x); 3]); - } - } - let image = photocraft_codecs::Image::from_u8(32, 32, photocraft_codecs::ChannelLayout::Rgb, pixels).unwrap(); - photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap() -} -fn cube(value: u8) -> String { - format!("LUT_3D_SIZE 2\n{}", format!("{value} {value} {value}\n").repeat(8)) -} -fn path_params(lookup: bool, path: &Path) -> Value { - if lookup { json!({"file": path}) } else { json!({"mapPath": path, "mapDocument": null}) } -} -fn assert_denied(result: Result) { - match result { - Err(error) => assert!(error.to_string().contains("ambient filesystem"), "{error}"), - Ok(value) => panic!("ambient file access was accepted: {value:?}"), - } -} +use serde_json::json; #[test] fn parameter_edits_reject_outside_images_and_luts_without_changing_the_document() { @@ -243,21 +164,6 @@ fn a_refresh_outside_command_execution_surfaces_the_denial_instead_of_rendering_ } } -#[test] -fn an_ambient_map_or_lut_never_renders_unfiltered_pixels_into_the_stack_cache() { - // The denial path must fail the render before any stage is cached process-wide. - for lookup in [false, true] { - let f = Fixture::new(); - let (doc, layer) = f.saved_filter(lookup); - let mut s = Session::new(); - s.add_document(doc, None); - s.authorize = Some(authorize_desktop_engine_step); - let bytes = smart_cmds::stack_cache_bytes(); - assert_denied(s.execute("layer.smartFilter.setVisible", json!({"layer": layer.0, "visible": true}))); - assert_eq!(bytes, smart_cmds::stack_cache_bytes(), "a denied render cached no stage"); - } -} - /// Choosing another Displace map through `setParams` embeds it (#7423), so the new map is read /// before the edit: a path outside the workspace is refused before that read, and the filter /// keeps the map it had. diff --git a/crates/automation/tests/smart_filter_stack_cache.rs b/crates/automation/tests/smart_filter_stack_cache.rs new file mode 100644 index 0000000000..f7698a4db1 --- /dev/null +++ b/crates/automation/tests/smart_filter_stack_cache.rs @@ -0,0 +1,25 @@ +//! One integration-test process keeps the global smart filter stage cache isolated from the +//! parallel tests in `tests/it`, so a denied render can be shown to have cached nothing. +use photocraft_automation::workspace::authorize_desktop_engine_step; +use photocraft_engine::{Session, smart_cmds}; +use serde_json::json; + +#[path = "support/smart_filter_fixture.rs"] +mod fixture; + +use fixture::{Fixture, assert_denied}; + +#[test] +fn an_ambient_map_or_lut_never_renders_unfiltered_pixels_into_the_stack_cache() { + // The denial path must fail the render before any stage is cached process-wide. + for lookup in [false, true] { + let f = Fixture::new(); + let (doc, layer) = f.saved_filter(lookup); + let mut s = Session::new(); + s.add_document(doc, None); + s.authorize = Some(authorize_desktop_engine_step); + let bytes = smart_cmds::stack_cache_bytes(); + assert_denied(s.execute("layer.smartFilter.setVisible", json!({"layer": layer.0, "visible": true}))); + assert_eq!(bytes, smart_cmds::stack_cache_bytes(), "a denied render cached no stage"); + } +} diff --git a/crates/automation/tests/support/smart_filter_fixture.rs b/crates/automation/tests/support/smart_filter_fixture.rs new file mode 100644 index 0000000000..26d5cab27b --- /dev/null +++ b/crates/automation/tests/support/smart_filter_fixture.rs @@ -0,0 +1,89 @@ +//! The smart filter authorization tests' fixture: a workspace with a striped image to place and +//! maps and LUTs outside it (`#[path]`-included by `it/smart_filter_authorization.rs` and +//! `smart_filter_stack_cache.rs`). +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use photocraft_automation::{AuthorizedWorkspace, Headless}; +use photocraft_doc::{Document, LayerContent, LayerId}; +use serde_json::{Value, json}; + +pub struct Fixture(PathBuf); + +impl Fixture { + pub fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let base = std::env::temp_dir().join(format!("pc-filter-auth-{}-{stamp}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir(&base).unwrap(); + std::fs::create_dir(base.join("workspace")).unwrap(); + std::fs::create_dir(base.join("outside")).unwrap(); + let f = Self(base); + std::fs::write(f.root().join("stripes.png"), png(|x| if (x / 2) % 2 == 0 { 0 } else { 255 })).unwrap(); + std::fs::write(f.outside("black.png"), png(|_| 0)).unwrap(); + std::fs::write(f.outside("white.png"), png(|_| 255)).unwrap(); + std::fs::write(f.outside("black.cube"), cube(0)).unwrap(); + std::fs::write(f.outside("white.cube"), cube(1)).unwrap(); + f + } + + pub fn root(&self) -> PathBuf { + self.0.join("workspace") + } + pub fn outside(&self, name: &str) -> PathBuf { + self.0.join("outside").join(name) + } + pub fn headless(&self) -> Headless { + Headless::with_workspace(AuthorizedWorkspace::new(Some(&self.root()), Some(&self.root())).unwrap()) + } + pub fn setup(&self, lookup: bool) -> (Headless, LayerId) { + let mut h = self.headless(); + h.handle("doc.new", json!({"width": 32, "height": 32, "background": "#808080"})).unwrap(); + h.handle("doc.new", json!({"width": 32, "height": 32})).unwrap(); + let layer = LayerId(h.handle("doc.place", json!({"path": "stripes.png"})).unwrap()["layer"].as_u64().unwrap()); + let (id, params) = if lookup { + ("image.adjustments.colorLookup", json!({"layer": layer.0, "lut": "none"})) + } else { + ("filter.distort.displace", json!({"layer": layer.0, "mapDocument": 0, "horizontal": 50, "vertical": 0})) + }; + h.session.execute(id, params).unwrap(); + (h, layer) + } + pub fn saved_filter(&self, lookup: bool) -> (Document, LayerId) { + let (h, layer) = self.setup(lookup); + let mut doc = (*h.session.active().unwrap().doc).clone(); + let LayerContent::Smart(sm) = &mut doc.layer_mut(layer).unwrap().content else { panic!("smart object") }; + sm.smart_filters[0].params = path_params(lookup, &self.outside(if lookup { "white.cube" } else { "white.png" })); + let bytes = photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap(); + std::fs::write(self.root().join("stored.pcraft"), bytes).unwrap(); + (doc, layer) + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +pub fn png(value: impl Fn(u32) -> u8) -> Vec { + let mut pixels = Vec::new(); + for _ in 0..32 { + for x in 0..32 { + pixels.extend([value(x); 3]); + } + } + let image = photocraft_codecs::Image::from_u8(32, 32, photocraft_codecs::ChannelLayout::Rgb, pixels).unwrap(); + photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap() +} +pub fn cube(value: u8) -> String { + format!("LUT_3D_SIZE 2\n{}", format!("{value} {value} {value}\n").repeat(8)) +} +pub fn path_params(lookup: bool, path: &Path) -> Value { + if lookup { json!({"file": path}) } else { json!({"mapPath": path, "mapDocument": null}) } +} +pub fn assert_denied(result: Result) { + match result { + Err(error) => assert!(error.to_string().contains("ambient filesystem"), "{error}"), + Ok(value) => panic!("ambient file access was accepted: {value:?}"), + } +} diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs index 9ce3ba974a..bd7faae838 100644 --- a/crates/cms/src/lutfile.rs +++ b/crates/cms/src/lutfile.rs @@ -90,7 +90,7 @@ impl LutFile { /// Parses a LUT, picking the format from `file_name`'s extension (falls back to sniffing). pub fn parse(file_name: &str, bytes: &[u8]) -> Result { let lower = file_name.to_ascii_lowercase(); - let text = String::from_utf8_lossy(bytes); + let text = decode_text(bytes); if lower.ends_with(".3dl") { parse_3dl(&text) } else if lower.ends_with(".look") || text.trim_start().starts_with('<') { @@ -100,6 +100,19 @@ pub fn parse(file_name: &str, bytes: &[u8]) -> Result { } } +/// UTF-16 with a byte-order mark (Photoshop loads such `.look` files, #9118), else UTF-8. +fn decode_text(bytes: &[u8]) -> std::borrow::Cow<'_, str> { + let utf16 = |rest: &[u8], from: fn([u8; 2]) -> u16| { + let units: Vec = rest.as_chunks::<2>().0.iter().map(|&c| from(c)).collect(); + String::from_utf16_lossy(&units).into() + }; + match bytes { + [0xFF, 0xFE, rest @ ..] => utf16(rest, u16::from_le_bytes), + [0xFE, 0xFF, rest @ ..] => utf16(rest, u16::from_be_bytes), + _ => String::from_utf8_lossy(bytes), + } +} + /// Adobe / Resolve `.cube`. 1D LUTs (`LUT_1D_SIZE`) are expanded to a 33³ table. A Resolve file /// with both sizes holds a 1D shaper and then a 3D table; the shaper runs first and its output /// feeds the table, so the two are baked into one table ([`compose_shaper`]). @@ -227,12 +240,15 @@ fn compose_shaper(title: String, size1: usize, size3: usize, rows: &[f32], range } /// Lustre `.3dl`: an optional shaper line of input values, then integer RGB rows with **blue** -/// varying fastest; the output bit depth is inferred from the largest value. +/// varying fastest; the output bit depth is inferred from the largest value, and is at least 12 +/// bits in a file without a header. pub fn parse_3dl(text: &str) -> Result { let mut rows: Vec<[f64; 3]> = Vec::new(); + let mut header = false; for line in text.lines() { let line = line.split('#').next().unwrap_or("").trim(); if line.is_empty() || line.starts_with(|c: char| c.is_ascii_alphabetic()) { + header |= !line.is_empty(); continue; } let v: Vec = line.split_whitespace().filter_map(|s| s.parse().ok()).collect(); @@ -246,7 +262,9 @@ pub fn parse_3dl(text: &str) -> Result { return err(format!("{} rows is not a cube", rows.len())); } let max = rows.iter().flatten().fold(0.0f64, |a, &b| a.max(b)); - let scale = if max <= 1.0 { 1.0 } else { [1023.0, 4095.0, 16383.0, 65535.0].into_iter().find(|&s| max <= s).unwrap_or(max) }; + // Photoshop 27.11 reads a headerless table peaking at 255 or 1023 on the 12-bit scale (#9121). + let depths: &[f64] = if header { &[1023.0, 4095.0, 16383.0, 65535.0] } else { &[4095.0, 16383.0, 65535.0] }; + let scale = if max <= 1.0 { 1.0 } else { depths.iter().copied().find(|&s| max <= s).unwrap_or(max) }; let mut data = vec![0.0f32; n * n * n * 3]; for (i, row) in rows.iter().enumerate() { let (r, g, b) = (i / (n * n), (i / n) % n, i % n); @@ -261,6 +279,15 @@ pub fn parse_3dl(text: &str) -> Result { /// SpeedGrade `.look`: `` and a hex `` string of little-endian float32 RGB triplets /// (red fastest). pub fn parse_look(text: &str) -> Result { + // Comments may hold tag-like text, so drop them before looking for tags (#9109). + let mut clean = String::with_capacity(text.len()); + let mut rest = text; + while let Some(i) = rest.find("").map_or("", |e| &rest[i + 4 + e + 3..]); + } + clean.push_str(rest); + let text = clean.as_str(); let tag = |name: &str| -> Option { let open = format!("<{name}>"); let start = text.find(&open)? + open.len(); @@ -536,6 +563,25 @@ DOMAIN_MAX 0.5 1 1 assert!(parse_cube(&text).is_err()); } + #[test] + fn three_dl_without_a_header_reads_low_nodes_as_12_bit() { + let table = |peak: u32| -> String { + let mut text = String::from("0 1023\n"); + for i in 0..8 { + let on = |bit: u32| if i & bit != 0 { peak } else { 0 }; + text.push_str(&format!("{} {} {}\n", on(4), on(2), on(1))); + } + text + }; + for peak in [255, 1023, 4095] { + let white = parse_3dl(&table(peak)).unwrap().data[21..24].to_vec(); + assert_eq!(white, [peak as f32 / 4095.0; 3], "peak {peak}"); + } + // A header keeps the inferred 10-bit depth. + let white = parse_3dl(&format!("3DMESH\nMesh 1 10\n{}", table(1023))).unwrap().data[21..24].to_vec(); + assert_eq!(white, [1.0; 3]); + } + #[test] fn three_dl_blue_fastest_and_bit_depth() { let mut text = String::from("0 1023\n"); @@ -559,6 +605,29 @@ DOMAIN_MAX 0.5 1 1 assert_eq!(parse("a.look", xml.as_bytes()).unwrap().data, id.data); } + #[test] + fn look_reads_utf16_with_either_byte_order() { + let id = LutFile::identity(2); + let hex: String = id.data.iter().flat_map(|v| v.to_le_bytes()).map(|b| format!("{b:02X}")).collect(); + let xml = format!("\"2\"\"{hex}\""); + let le: Vec = [0xFF, 0xFE].into_iter().chain(xml.encode_utf16().flat_map(u16::to_le_bytes)).collect(); + let be: Vec = [0xFE, 0xFF].into_iter().chain(xml.encode_utf16().flat_map(u16::to_be_bytes)).collect(); + assert_eq!(parse("a.look", &le).unwrap().data, id.data); + assert_eq!(parse("a.look", &be).unwrap().data, id.data); + } + + #[test] + fn look_ignores_tags_inside_xml_comments() { + let hex = |l: &LutFile| -> String { l.data.iter().flat_map(|v| v.to_le_bytes()).map(|b| format!("{b:02X}")).collect() }; + let inverse = LutFile::from_fn("", 2, |[r, g, b]| [1.0 - r, 1.0 - g, 1.0 - b]); + let xml = format!( + "\"2\"\"{}\"