diff --git a/Cargo.lock b/Cargo.lock index a5d50e3100..222619ab31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1196,6 +1196,15 @@ dependencies = [ "rayon", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=eeb134def2daa7e03512b4946bd59d6b419b9484#eeb134def2daa7e03512b4946bd59d6b419b9484" +dependencies = [ + "md-5", + "rayon", +] + [[package]] name = "craft-codepage" version = "0.1.0" @@ -1305,6 +1314,7 @@ dependencies = [ "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", "crc32fast", "exr", "flate2", @@ -1366,6 +1376,11 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-media" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" + [[package]] name = "craft-metadata" version = "0.1.0" @@ -1517,12 +1532,21 @@ name = "craft-video" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6#5c91598ccc86537a779f438d520fa6406c26efe6" dependencies = [ - "craft-media", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6)", "rav1e", "rayon", "thiserror 2.0.21", ] +[[package]] +name = "craft-video" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" +dependencies = [ + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "thiserror 2.0.21", +] + [[package]] name = "craft-window" version = "0.1.0" @@ -1537,9 +1561,10 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=2d4b8b8ecd79f87c847961901c40305e7f448d6f#2d4b8b8ecd79f87c847961901c40305e7f448d6f" dependencies = [ "quick-xml 0.41.0", + "serde", "thiserror 2.0.21", ] @@ -3964,7 +3989,7 @@ name = "lightcraft-codecs" version = "0.21.1" dependencies = [ "bytemuck", - "craft-cms", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7f30d664695cd5ce14fc30659d36c3e32f234247)", "craft-gainmap", "craft-gif", "craft-heif", @@ -3975,7 +4000,7 @@ dependencies = [ "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", "craft-psd", "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", - "craft-video", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6)", "dhat", "jpeg-encoder 0.7.1", "lightcraft-color", @@ -4226,6 +4251,7 @@ dependencies = [ name = "lightcraft-pipeline" version = "0.21.1" dependencies = [ + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eeb134def2daa7e03512b4946bd59d6b419b9484)", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", "dhat", "lightcraft-color", @@ -8636,18 +8662,3 @@ dependencies = [ "syn 3.0.6", "winnow", ] - -[[patch.unused]] -name = "egui_demo_lib" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - -[[patch.unused]] -name = "egui_inspection" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - -[[patch.unused]] -name = "egui_system_font_provider" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" diff --git a/Cargo.toml b/Cargo.toml index fd26f64fdb..4b1402d458 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,12 +10,13 @@ rust-version = "1.95" repository = "https://github.com/storytold/lightcraft" [workspace.dependencies] +craft-cms-profile = { package = "craft-cms", git = "https://github.com/storytold/craft-libs", rev = "eeb134def2daa7e03512b4946bd59d6b419b9484" } craft-plist = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bea6ed1ff031b81df2d64be470485c1ca808847e" } craft-pdf-print = { package = "craft-pdf", git = "https://github.com/storytold/craft-libs", rev = "0fd30aeb3e02207d9d4c7c601540d9da45abf8de", default-features = false, features = ["write-raster"] } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } # Canon CRW decoder shared with the other Craft apps -craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "e7c96161ddaf860a9fa7f8fd21f935620e553022" } +craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "2d4b8b8ecd79f87c847961901c40305e7f448d6f" } craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "7f30d664695cd5ce14fc30659d36c3e32f234247" } craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", version = "0.1.0" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b77af389f30bb10de10d8436ca9b39fe94e3bb67", features = ["frames"] } @@ -28,7 +29,7 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "c craft-video = { git = "https://github.com/storytold/craft-libs", rev = "5c91598ccc86537a779f438d520fa6406c26efe6", features = ["av1", "av1-large-encode", "threads"] } # Isolate AVIF threading from the existing PNG/TIFF/WebP shared revision. craft-avif-encode = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a", default-features = false, features = ["avif", "threads"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "2d4b8b8ecd79f87c847961901c40305e7f448d6f" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } @@ -205,8 +206,5 @@ egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc79968 egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } diff --git a/README.md b/README.md index a3e4981360..2e817614ba 100644 --- a/README.md +++ b/README.md @@ -499,8 +499,7 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft Without it LightCraft builds and runs the same, but Chinese and Japanese text have no glyphs. Fonts are never committed to this repo — what goes there is described in the [craft-fonts README](https://github.com/storytold/craft-fonts#readme). -**Interface language:** **Edit → Language** (English, 简体中文, 繁體中文(台灣), 日本語, Português (Brasil), Español, Deutsch, Русский, Français, Українська, Polski, Čeština, Italiano, ქართული, Svenska, Suomi, Bahasa Indonesia, Tiếng Việt) or **Settings → General → -Language**; the choice applies immediately and persists. See [docs/localization.md](docs/localization.md). +**Interface language:** **Settings → General → Language** (English, 简体中文, 繁體中文(台灣), 日本語, Português (Brasil), Español, Deutsch, Русский, Français, Українська, Polski, Čeština, Italiano, ქართული, Svenska, Suomi, Bahasa Indonesia, Tiếng Việt); the choice applies immediately and persists. See [docs/localization.md](docs/localization.md). **Logs:** the desktop app writes its log to standard error and to `logs/lightcraft.log` in its settings folder (Linux `$XDG_CONFIG_HOME/lightcraft/logs/`, by default `~/.config/lightcraft/logs/`; macOS diff --git a/README.zh-hans.md b/README.zh-hans.md index a577a8db7b..054f2c1e81 100644 --- a/README.zh-hans.md +++ b/README.zh-hans.md @@ -422,8 +422,7 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft 不指定它时,LightCraft 构建和运行的方式完全相同,只是中文和日文文字没有字形。字体从不提交到 本仓库。 -**界面语言:** **编辑 → 语言**(English、简体中文、繁體中文(台灣)、日本語、Português (Brasil)、Español、Deutsch、Русский、Français)或 **设置 → 一般 → -语言**;选择立即生效并会保留。见 [docs/localization.md](docs/localization.md)。 +**界面语言:** **设置 → 一般 → 语言**(English、简体中文、繁體中文(台灣)、日本語、Português (Brasil)、Español、Deutsch、Русский、Français);选择立即生效并会保留。见 [docs/localization.md](docs/localization.md)。 **日志:** 桌面应用把日志写到标准错误,以及设置文件夹里的 `logs/lightcraft.log` (Linux `$XDG_CONFIG_HOME/lightcraft/logs/`,默认 `~/.config/lightcraft/logs/`;macOS diff --git a/README.zh-hant.md b/README.zh-hant.md index f2c223897a..c8079956f0 100644 --- a/README.zh-hant.md +++ b/README.zh-hant.md @@ -447,8 +447,7 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft 不指定它時,LightCraft 一樣能建置與執行,只是中文和日文文字沒有字形。字型從不提交到 本儲存庫,字型的收錄規範記載在該儲存庫:見 [craft-fonts README](https://github.com/storytold/craft-fonts#readme)。 -**介面語言:** **編輯 → 語言**(English、简体中文、繁體中文(台灣)、日本語、Português (Brasil)、Español、Deutsch、Русский、Français、Українська、Čeština、ქართული)或 **設定 → 一般 → -語言**;選擇後立即生效並會保留。詳見 [docs/localization.md](docs/localization.md)。 +**介面語言:** **設定 → 一般 → 語言**(English、简体中文、繁體中文(台灣)、日本語、Português (Brasil)、Español、Deutsch、Русский、Français、Українська、Čeština、ქართული);選擇後立即生效並會保留。詳見 [docs/localization.md](docs/localization.md)。 **記錄檔:** 桌面應用程式會把記錄檔寫到標準錯誤輸出,以及設定資料夾裡的 `logs/lightcraft.log` (Linux `$XDG_CONFIG_HOME/lightcraft/logs/`,預設為 `~/.config/lightcraft/logs/`;macOS diff --git a/assets/ATTRIBUTION.md b/assets/ATTRIBUTION.md index f0c7d15ca7..36c8972ade 100644 --- a/assets/ATTRIBUTION.md +++ b/assets/ATTRIBUTION.md @@ -45,6 +45,7 @@ covers a whole directory), or if a licence file referenced in the Licence column | `crates/ui-egui/locales/sv.json`, `crates/ui-egui/locales/sv-formats.json` | Swedish interface catalogs | LightCraft contributors | original work: clean-room Swedish translations of English source phrases | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-15 | none | | `crates/ui-egui/locales/fi.json`, `crates/ui-egui/locales/fi-formats.json` | Finnish interface catalogs | @roopeg with Claude Code (AI-assisted; native-speaker review by @roopeg) | original work: translations of the English source phrases, using common Finnish photo-editing vocabulary; no external translation material | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-17 | count-neutral labels for Finnish partitive agreement, Finnish dates and times (`20.9.2026`, `16:04`), reviewed placeholders | | `crates/ui-egui/locales/vi.json`, `crates/ui-egui/locales/vi-formats.json` | Vietnamese interface catalogs | @duydev (DUY Tran Nhat) with AI assistance (Cursor) | original work: translations of English source phrases; no external translation material | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-13 | plural-neutral counts, Vietnamese dates and weekdays, reviewed placeholders | +| `crates/codecs/tests/fixtures/quad-444-gbr-lossless.avif` | AVIF decode test fixture: a 33×17 lossless 8-bit 4:4:4 AV1 still with the identity (GBR) matrix, four flat colour quadrants | craft-libs contributors | [craft-libs 59b4f1e8 `crates/image-codecs/tests/fixtures/avif/quad-444-gbr-lossless.avif`](https://github.com/storytold/craft-libs/blob/59b4f1e8c2909fbcacba491b219958f4a976d5f8/crates/image-codecs/tests/fixtures/avif/quad-444-gbr-lossless.avif) (storytold/craft-libs#1601), encoded with FFmpeg/libaom from a synthetic RGB source as described in `crates/codecs/tests/fixtures/avif-README.md`; no third-party image content | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-11-16 | none: byte-identical copy of the craft-libs fixture; decodes exactly to its four-colour `quad-source.rgb` | Notes - egui's default fonts (Hack, Ubuntu Light, Noto Emoji, egui-icons and emoji-icon-font) come from the diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 9fd089a2d9..08c1c0bc0d 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -40,8 +40,8 @@ jxl = ["dep:craft-jxl"] # distributors choose it at build time (HEVC patents are a distributor's call, same policy as # PhotoCraft); `cargo xtask ci` clippies and tests it (`--features heif`), releases don't ship it yet. heif = ["dep:craft-heif"] -## AVIF/AV1 encoding via craft-image-codecs / craft-video (pure Rust). Native targets only; a no-op on wasm32. -avif = ["dep:craft-video", "dep:craft-avif-encode"] +## AVIF/AV1 encoding via craft-image-codecs / craft-video (pure Rust), plus the shared AVIF decoder. Native targets only; a no-op on wasm32. +avif = ["dep:craft-video", "dep:craft-avif-encode", "craft-image-codecs/avif-decode"] [dev-dependencies] # tests record why they skip (`cargo xtask ci` lists the skips) diff --git a/crates/codecs/README.md b/crates/codecs/README.md index 499aaae3b3..5bef49e043 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -114,8 +114,8 @@ Run `cargo test --release -p lightcraft-codecs --test it bench:: -- --ignored -- ## Gaps / limitations -- **AVIF decode**: no permissively licensed, pure-Rust AV1 decoder exists today (dav1d is C; - rav1d-safe is AGPL). Files are sniffed and rejected with `Error::Unsupported`. +- **AVIF decode** uses the shared pure-Rust AV1 decoder on native builds with the `avif` feature. + Animated AVIF, depth and gain-map auxiliary images, and progressive/layered images are unsupported. - **HEIC** needs the `heif` feature (off by default: HEVC patents are the distributor's call); without it, `Error::Unsupported` says the build has no HEIC support. 4:2:2 and 4:4:4 HEIF (Canon/Sony HIF) is refused: heic-rs 0.1.1 loses sync on those bitstreams. diff --git a/crates/codecs/src/avif_decode.rs b/crates/codecs/src/avif_decode.rs new file mode 100644 index 0000000000..f14275de45 --- /dev/null +++ b/crates/codecs/src/avif_decode.rs @@ -0,0 +1,262 @@ +//! AVIF container and pixel decoding via shared image codecs. +use crate::{DecodeOptions, Decoded, Error, Format, Result}; + +const F: Format = Format::Avif; + +#[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))] +pub(crate) fn header(_: &[u8]) -> Result<(u32, u32, u16)> { + Err(Error::Unsupported(F, "AVIF decoding is not included in this build")) +} +#[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))] +pub(crate) fn decode(_: &[u8], _: &DecodeOptions) -> Result { + Err(Error::Unsupported(F, "AVIF decoding is not included in this build")) +} + +#[cfg(all(feature = "avif", not(target_arch = "wasm32")))] +fn err(e: craft_image_codecs::CodecError) -> Error { + match e { + craft_image_codecs::CodecError::LimitExceeded(_) => Error::TooLarge(0, 0), + craft_image_codecs::CodecError::Unsupported { .. } => Error::Unsupported(F, "unsupported AVIF"), + other => Error::Malformed(F, other.to_string()), + } +} +#[cfg(all(feature = "avif", not(target_arch = "wasm32")))] +pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> { + let (w, h) = craft_image_codecs::probe_size(bytes).map_err(err)?; + Ok((w, h, 1)) +} +// Match craft-video's AV1 store: 128-sample superblocks plus 160 samples of edge padding, +// three u16 planes, eight references, the current picture, and at most eight workers + two +// in-flight pictures. Keep a hard byte ceiling even when the caller permits many pixels. +#[cfg(all(feature = "avif", not(target_arch = "wasm32")))] +fn picture_store_budget(width: u32, height: u32) -> u64 { + let padded = |n: u32| u64::from(n).div_ceil(128) * 128 + 160; + padded(width).saturating_mul(padded(height)).saturating_mul(PICTURE_STORE_BYTES_PER_SAMPLE).min(PICTURE_STORE_CAP) +} +#[cfg(all(feature = "avif", not(target_arch = "wasm32")))] +const PICTURE_STORE_BYTES_PER_SAMPLE: u64 = 3 * 2 * (8 + 1 + 8 + 2); +#[cfg(all(feature = "avif", not(target_arch = "wasm32")))] +const PICTURE_STORE_CAP: u64 = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 1 << 30 }; + +/// The picture-store budget for any stored AV1 canvas the pixel limit admits. `probe_size` reports +/// the size after `clap`, but the decoder builds the stored (pre-crop) canvas, which the shared +/// decoder checks against `max_pixels` from its `ispe` before decoding. A canvas of at most +/// `max_pixels` samples with AV1's 65,536-sample edge limit has `w + h <= min(max_pixels + 1, 2^17)`, +/// and each padded edge is under `edge + 288`, so the padded area is below +/// `max_pixels + 288 * (w + h) + 288^2`. +#[cfg(all(feature = "avif", not(target_arch = "wasm32")))] +fn stored_picture_store_budget(max_pixels: u64) -> u64 { + let edge_sum = max_pixels.saturating_add(1).min(2 * 65_536); + let area = max_pixels.saturating_add(edge_sum.saturating_mul(288)).saturating_add(288 * 288); + area.saturating_mul(PICTURE_STORE_BYTES_PER_SAMPLE).min(PICTURE_STORE_CAP) +} + +#[cfg(all(feature = "avif", not(target_arch = "wasm32")))] +pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { + use crate::convert::{Buf, Meta, Model, Raw, check_size, finish}; + use crate::space::SourceSpace; + let (w, h, _) = header(bytes)?; + check_size(F, w as u64, h as u64, opts)?; + let options = craft_image_codecs::DecodeOptions { + limits: craft_image_codecs::Limits { + max_width: u32::MAX, + max_height: u32::MAX, + max_pixels: opts.max_pixels, + max_alloc: stored_picture_store_budget(opts.max_pixels).max(picture_store_budget(w, h)), + }, + keep_orientation: false, + }; + let (img, bit_depth) = craft_image_codecs::decode_avif_with_depth(bytes, &options).map_err(err)?; + let (w, h) = (img.width(), img.height()); + check_size(F, w as u64, h as u64, opts)?; + let buf = match img.sample_type() { + craft_image_codecs::SampleType::U8 => Buf::U8(img.as_u8().ok_or_else(|| Error::Malformed(F, "expected 8-bit samples".into()))?.to_vec()), + craft_image_codecs::SampleType::U16 => Buf::U16(img.to_u16_samples().ok_or_else(|| Error::Malformed(F, "expected 16-bit samples".into()))?), + craft_image_codecs::SampleType::F32 => Buf::F32(img.to_f32_samples().ok_or_else(|| Error::Malformed(F, "expected float samples".into()))?), + _ => return Err(Error::Unsupported(F, "unsupported AVIF sample type")), + }; + let hint = img.cicp.and_then(|c| SourceSpace::from_cicp(c.primaries, c.transfer)); + let raw = Raw { width: w as usize, height: h as usize, model: Model::Rgb, alpha: img.layout().has_alpha(), premultiplied: false, buf, bit_depth }; + let meta = Meta { icc: img.icc, exif: img.meta.exif, xmp: img.meta.xmp, orientation: Some(1), hint, ..Default::default() }; + let mut decoded = finish(F, raw, meta, (w, h), opts)?; + // AV1 stores integer samples even when HDR transfer decoding produces linear float pixels. + decoded.float = false; + Ok(decoded) +} + +#[cfg(all(test, feature = "avif", not(target_arch = "wasm32")))] +mod tests { + use super::*; + const FIXTURE: &[u8] = include_bytes!("../tests/fixtures/quad-444-gbr-lossless.avif"); + #[test] + fn production_entrypoints_decode_avif_and_enforce_pixel_budget() { + assert!(F.can_decode()); + assert_eq!(crate::sniff(FIXTURE), Some(F)); + let header = crate::read_header(FIXTURE).unwrap(); + assert_eq!((header.width, header.height, header.orientation), (33, 17, 1)); + let decoded = crate::decode(FIXTURE, DecodeOptions::default()).unwrap(); + assert_eq!((decoded.source_width, decoded.source_height), (33, 17)); + assert_eq!(decoded.bit_depth, 8); + let exact = DecodeOptions { max_pixels: 33 * 17, ..DecodeOptions::default() }; + let decoded = crate::decode(FIXTURE, exact).unwrap(); + assert_eq!((decoded.source_width, decoded.source_height), (33, 17)); + assert!(!decoded.float); + let opts = DecodeOptions { max_pixels: 33 * 17 - 1, ..DecodeOptions::default() }; + assert!(matches!(crate::decode(FIXTURE, opts), Err(Error::TooLarge(..)))); + } + #[test] + fn picture_store_budget_accounts_for_padding_and_stays_bounded() { + assert_eq!(picture_store_budget(33, 17), 288 * 288 * 6 * 19); + let cap = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 1 << 30 }; + assert_eq!(picture_store_budget(u32::MAX, u32::MAX), cap); + assert_eq!(stored_picture_store_budget(u64::MAX), cap); + // Every canvas the pixel limit admits fits, whatever its shape. + for max_pixels in [1u64, 561, 512 * 512, 1 << 20] { + let budget = stored_picture_store_budget(max_pixels); + for (w, h) in [(1, max_pixels), (max_pixels, 1), (max_pixels.isqrt(), max_pixels.isqrt())] { + let (w, h) = (w.min(65_536) as u32, h.min(65_536) as u32); + assert!(picture_store_budget(w, h) <= budget, "{w}x{h} under {max_pixels}"); + } + } + } + + /// `probe_size` reports the `clap`-cropped size; the decoder still builds the stored canvas. + /// A 512×512 picture cropped to 16×16 must decode with the default options and at a pixel + /// limit that covers the stored canvas, and fail as too large below it. + #[test] + fn cropped_avif_decodes_with_a_budget_for_its_stored_canvas() { + let pixels = [90u8, 140, 200].repeat(512 * 512); + let image = crate::encode::EncodeImage::new(512, 512, 3, crate::encode::Samples::U8(&pixels)); + let full = crate::encode::encode_avif(&image, 60, 10, &crate::encode::EncodeMeta::default()).unwrap(); + let cropped = with_clap(&full, 16, 16); + assert_eq!(crate::read_header(&cropped).map(|h| (h.width, h.height)).unwrap(), (16, 16)); + // The old budget, sized from the cropped 16×16, is below what the stored canvas needs. + assert!(picture_store_budget(16, 16) < picture_store_budget(512, 512)); + let decoded = crate::decode(&cropped, DecodeOptions::default()).unwrap(); + assert_eq!((decoded.source_width, decoded.source_height), (16, 16)); + let exact = DecodeOptions { max_pixels: 512 * 512, ..DecodeOptions::default() }; + assert_eq!(crate::decode(&cropped, exact).map(|d| (d.source_width, d.source_height)).unwrap(), (16, 16)); + let below = DecodeOptions { max_pixels: 512 * 512 - 1, ..DecodeOptions::default() }; + assert!(crate::decode(&cropped, below).is_err()); + } + + fn be32(b: &[u8], at: usize) -> usize { + u32::from_be_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) as usize + } + fn put32(b: &mut [u8], at: usize, v: usize) { + b[at..at + 4].copy_from_slice(&(v as u32).to_be_bytes()); + } + /// Child boxes of `b[start..end]`: (offset, size, type). + fn boxes(b: &[u8], start: usize, end: usize) -> Vec<(usize, usize, [u8; 4])> { + let mut out = Vec::new(); + let mut at = start; + while at + 8 <= end { + let size = be32(b, at); + out.push((at, size, [b[at + 4], b[at + 5], b[at + 6], b[at + 7]])); + at += size; + } + out + } + fn find(b: &[u8], start: usize, end: usize, kind: &[u8; 4]) -> (usize, usize) { + boxes(b, start, end).into_iter().find(|x| &x.2 == kind).map_or((0, 0), |x| (x.0, x.1)) + } + + /// Adds a centred `clap` of `w × h` to the primary item of a single-item AVIF from the encoder, + /// fixing the enclosing box sizes and the `iloc` offsets into `mdat`. + fn with_clap(file: &[u8], w: u32, h: u32) -> Vec { + let mut b = file.to_vec(); + let (meta, meta_size) = find(&b, 0, b.len(), b"meta"); + let children = meta + 12; + let (iprp, _) = find(&b, children, meta + meta_size, b"iprp"); + let (ipco, ipco_size) = find(&b, iprp + 8, iprp + be32(&b, iprp), b"ipco"); + let index = boxes(&b, ipco + 8, ipco + ipco_size).len() + 1; + let mut clap = Vec::new(); + for v in [w, 1, h, 1, 0, 1, 0, 1] { + clap.extend_from_slice(&v.to_be_bytes()); + } + let clap = [&((8 + clap.len()) as u32).to_be_bytes()[..], b"clap", &clap].concat(); + // ipma: version/flags, entry count, then item id, association count, associations. + let (ipma, ipma_size) = find(&b, iprp + 8, iprp + be32(&b, iprp), b"ipma"); + let (version, flags) = (b[ipma + 8], b[ipma + 11]); + assert_eq!(be32(&b, ipma + 12), 1, "one item"); + let id_len = if version < 1 { 2 } else { 4 }; + let count_at = ipma + 16 + id_len; + let wide = flags & 1 == 1; + let assoc_end = count_at + 1 + b[count_at] as usize * if wide { 2 } else { 1 }; + assert_eq!(assoc_end, ipma + ipma_size); + let assoc: Vec = if wide { (0x8000u16 | index as u16).to_be_bytes().to_vec() } else { vec![0x80 | index as u8] }; + let grow = clap.len() + assoc.len(); + b[count_at] += 1; + b.splice(assoc_end..assoc_end, assoc.iter().copied()); + b.splice(ipco + ipco_size..ipco + ipco_size, clap.iter().copied()); + // ipco precedes ipma inside iprp, so ipma moved by the clap's length. + for (at, by) in [(meta, grow), (iprp, grow), (ipco, clap.len()), (ipma + clap.len(), assoc.len())] { + let size = be32(&b, at); + put32(&mut b, at, size + by); + } + // iloc (version 0 or 1): shift every absolute extent offset by the growth of `meta`. + let (iloc, _) = find(&b, children, meta + be32(&b, meta), b"iloc"); + let v = b[iloc + 8]; + let (offset_size, length_size, base_size) = ((b[iloc + 12] >> 4) as usize, (b[iloc + 12] & 15) as usize, (b[iloc + 13] >> 4) as usize); + let index_size = if v >= 1 { (b[iloc + 13] & 15) as usize } else { 0 }; + let mut at = iloc + 14; + let items = if v < 2 { + let n = u16::from_be_bytes([b[at], b[at + 1]]) as usize; + at += 2; + n + } else { + let n = be32(&b, at); + at += 4; + n + }; + let read = |b: &[u8], at: usize, n: usize| b[at..at + n].iter().fold(0usize, |acc, &x| acc << 8 | x as usize); + let write = |b: &mut [u8], at: usize, n: usize, v: usize| { + for i in 0..n { + b[at + i] = (v >> (8 * (n - 1 - i))) as u8; + } + }; + for _ in 0..items { + at += if v < 2 { 2 } else { 4 }; + if v >= 1 { + at += 2; + } + at += 2; + let base = read(&b, at, base_size); + if base_size > 0 && base > 0 { + write(&mut b, at, base_size, base + grow); + } + at += base_size; + let extents = u16::from_be_bytes([b[at], b[at + 1]]) as usize; + at += 2; + for _ in 0..extents { + at += index_size; + let off = read(&b, at, offset_size); + if base == 0 && offset_size > 0 { + write(&mut b, at, offset_size, off + grow); + } + at += offset_size + length_size; + } + } + b + } + #[test] + fn hdr_avif_round_trips_highlights_through_public_decoder() { + let pixels = vec![2.0f32; 16 * 16 * 3]; + for transfer in [crate::encode::HdrTransfer::Pq, crate::encode::HdrTransfer::Hlg] { + let bytes = crate::encode::encode_avif_hdr(16, 16, &pixels, 95, 10, &crate::encode::EncodeMeta::default(), transfer).unwrap(); + let decoded = crate::decode(&bytes, DecodeOptions::default()).unwrap(); + assert_eq!(decoded.bit_depth, 10); + assert!(!decoded.float, "AV1 source samples are integer for {transfer:?}"); + assert!(decoded.image.data.iter().any(|pixel| pixel[0] > 1.0), "HDR highlights were lost"); + } + } + #[test] + fn avif_alpha_survives_public_round_trip() { + let pixels = [200u8, 100, 50, 96].repeat(16 * 16); + let image = crate::encode::EncodeImage::new(16, 16, 4, crate::encode::Samples::U8(&pixels)); + let bytes = crate::encode::encode_avif(&image, 95, 10, &crate::encode::EncodeMeta::default()).unwrap(); + let decoded = crate::decode(&bytes, DecodeOptions::default()).unwrap(); + let alpha = decoded.alpha.expect("alpha plane"); + assert!((alpha.data[0] - 96.0 / 255.0).abs() < 0.04); + } +} diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index 8fc0b3f4f5..7370bde763 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -18,6 +18,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod avif_decode; mod convert; pub mod display; pub mod encode; @@ -221,6 +222,7 @@ pub fn read_header_unguarded(bytes: &[u8], format: Format) -> Result
{ Format::WebP => webp::header(bytes)?, Format::Psd => psd::header(bytes)?, Format::Heif => heif::header(bytes)?, + Format::Avif => avif_decode::header(bytes)?, Format::Gif | Format::Bmp => other::header(bytes, format)?, // rare here (or, for JPEG XL, without a header reader yet): a small decode, as before _ => { @@ -257,7 +259,8 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R #[cfg(not(feature = "jxl"))] Format::Jxl => unsupported(), Format::Heif => heif::decode(bytes, &opts), - Format::Avif | Format::RawTiffLike | Format::RawOther => unsupported(), + Format::Avif => avif_decode::decode(bytes, &opts), + Format::RawTiffLike | Format::RawOther => unsupported(), } } diff --git a/crates/codecs/src/sniff.rs b/crates/codecs/src/sniff.rs index 181f271038..d8f627f6a2 100644 --- a/crates/codecs/src/sniff.rs +++ b/crates/codecs/src/sniff.rs @@ -76,7 +76,8 @@ impl Format { Format::Jxl => Some("built without the `jxl` feature"), #[cfg(not(feature = "heif"))] Format::Heif => Some(crate::heif::NOT_IN_BUILD), - Format::Avif => Some("no pure-Rust, permissively licensed AV1 decoder yet"), + #[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))] + Format::Avif => Some("AVIF decoding is not included in this build"), Format::RawTiffLike | Format::RawOther => Some("camera raw: decode with lightcraft-raw"), _ => None, } diff --git a/crates/codecs/tests/fixtures/avif-README.md b/crates/codecs/tests/fixtures/avif-README.md new file mode 100644 index 0000000000..b8b3a8c2ab --- /dev/null +++ b/crates/codecs/tests/fixtures/avif-README.md @@ -0,0 +1,12 @@ +# AVIF decode fixtures + +Small AVIF files from an independent encoder (libaom through FFmpeg 7.1), for `src/codecs/avif_decode.rs`. + +- `quad-source.rgb`: the 33×17 source, raw RGB24 four-colour quadrants (red, green, blue, near-white). +- `quad-420-bt709.avif`: 8-bit 4:2:0, limited range, BT.709 matrix, odd size (FFmpeg leaves the primaries and transfer unspecified): + `ffmpeg -f rawvideo -pix_fmt rgb24 -s 33x17 -i quad-source.rgb -c:v libaom-av1 -crf 12 -still-picture 1 -pix_fmt yuv420p -colorspace bt709 -color_primaries bt709 -color_trc iec61966-2-1 -color_range tv quad-420-bt709.avif` +- `quad-420-bt709.dav1d.yuv`: that file's AV1 picture as libdav1d decodes it, planar 8-bit 4:2:0 (Y, then Cb, then Cr): + `ffmpeg -c:v libdav1d -i quad-420-bt709.avif -f rawvideo -pix_fmt yuv420p quad-420-bt709.dav1d.yuv` +- `quad-444-gbr-lossless.avif`: lossless 8-bit 4:4:4 with the identity (GBR) matrix, full range: + `ffmpeg -f rawvideo -pix_fmt rgb24 -s 33x17 -i quad-source.rgb -c:v libaom-av1 -crf 0 -still-picture 1 -pix_fmt gbrp -colorspace rgb -color_range pc quad-444-gbr-lossless.avif`. + It decodes to `quad-source.rgb` exactly. diff --git a/crates/codecs/tests/fixtures/quad-444-gbr-lossless.avif b/crates/codecs/tests/fixtures/quad-444-gbr-lossless.avif new file mode 100644 index 0000000000..c3b1f14233 Binary files /dev/null and b/crates/codecs/tests/fixtures/quad-444-gbr-lossless.avif differ diff --git a/crates/codecs/tests/it/roundtrip.rs b/crates/codecs/tests/it/roundtrip.rs index ddcd8106e2..d30e698356 100644 --- a/crates/codecs/tests/it/roundtrip.rs +++ b/crates/codecs/tests/it/roundtrip.rs @@ -664,7 +664,8 @@ fn avif_encode_native() { if cfg!(feature = "avif") { let b = r.unwrap(); assert_eq!(sniff(&b), Some(Format::Avif)); - assert!(matches!(decode(&b, DecodeOptions::default()), Err(Error::Unsupported(Format::Avif, _)))); + let decoded = decode(&b, DecodeOptions::default()).unwrap(); + assert_eq!((decoded.source_width, decoded.source_height), (64, 48)); } else { assert!(r.is_err()); } diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index d6a9c6eea9..b4a5e44190 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -16,8 +16,8 @@ pub const EXTENSIONS: &[&str] = &[ "srw", "psd", "psb", "jxl", "gif", "bmp", // Decoded when built with the codecs' `heif` feature; otherwise the import reports them as // failed with the reason ("HEIC/HEIF support isn't included in this build"). - "heic", "heif", "avif", // no AV1 decoder yet: reported as failed, like a HEIC without the feature - "iiq", "crw", "mrw", "x3f", "kdc", "mos", "erf", "3fr", "fff", "mef", + "heic", "heif", // AVIF decoding is available in native builds with the codecs' `avif` feature. + "avif", "iiq", "crw", "mrw", "x3f", "kdc", "mos", "erf", "3fr", "fff", "mef", ]; pub fn is_supported(path: &Path) -> bool { diff --git a/crates/pipeline/Cargo.toml b/crates/pipeline/Cargo.toml index 89e69cce43..0a8c41149e 100644 --- a/crates/pipeline/Cargo.toml +++ b/crates/pipeline/Cargo.toml @@ -9,6 +9,7 @@ description = "LightCraft develop pipeline: scene-referred, float, resolution in workspace = true [dependencies] +craft-cms-profile = { workspace = true } lightcraft-geom = { workspace = true } lightcraft-color = { workspace = true } lightcraft-raster = { workspace = true } diff --git a/crates/pipeline/src/lut.rs b/crates/pipeline/src/lut.rs index 971599cbbf..29a9649a1c 100644 --- a/crates/pipeline/src/lut.rs +++ b/crates/pipeline/src/lut.rs @@ -19,48 +19,8 @@ pub struct Lut3d { impl Lut3d { /// Parse a `.cube` file. pub fn parse_cube(text: &str) -> Result { - let (mut size, mut title) = (0usize, None); - let (mut min, mut max) = ([0.0f32; 3], [1.0f32; 3]); - let mut data = Vec::new(); - let three = |rest: &str| -> Option<[f32; 3]> { - let v: Vec = rest.split_whitespace().filter_map(|x| x.parse().ok()).collect(); - (v.len() == 3 && v.iter().all(|x| x.is_finite())).then(|| [v[0], v[1], v[2]]) - }; - for line in text.lines() { - let l = line.trim(); - if l.is_empty() || l.starts_with('#') { - continue; - } - if let Some(r) = l.strip_prefix("TITLE") { - title = Some(r.trim().trim_matches('"').to_string()); - } else if let Some(r) = l.strip_prefix("LUT_3D_SIZE") { - size = r.trim().parse().map_err(|_| format!("bad LUT_3D_SIZE `{}`", r.trim()))?; - if !(2..=256).contains(&size) { - return Err(format!("LUT_3D_SIZE {size} out of range")); - } - } else if l.starts_with("LUT_1D_SIZE") { - return Err("1D LUTs are not supported (only 3D .cube files)".into()); - } else if let Some(r) = l.strip_prefix("DOMAIN_MIN") { - min = three(r).ok_or("bad DOMAIN_MIN")?; - } else if let Some(r) = l.strip_prefix("DOMAIN_MAX") { - max = three(r).ok_or("bad DOMAIN_MAX")?; - } else if l.starts_with(|c: char| c.is_ascii_alphabetic()) { - // a data line of `nan` / `inf` starts with a letter too: it is bad data, not a keyword - if l.split_whitespace().next().is_some_and(|w| w.parse::().is_ok()) { - return Err(format!("bad line `{l}`")); - } - // other keywords (LUT_IN_VIDEO_RANGE…) are ignored - } else { - data.push(three(l).ok_or_else(|| format!("bad line `{l}`"))?); - } - } - if size == 0 { - return Err("not a 3D .cube LUT (no LUT_3D_SIZE)".into()); - } - if data.len() != size * size * size { - return Err(format!("expected {} entries, found {}", size * size * size, data.len())); - } - Ok(Lut3d { size, data, domain_min: min, domain_max: max, title }) + let table = craft_cms_profile::lutfile::parse_cube_3d(text, 256).map_err(|error| error.to_string())?; + Ok(Lut3d { size: table.size, data: table.data, domain_min: table.domain_min, domain_max: table.domain_max, title: table.title }) } /// Look up `c` (trilinear). @@ -132,6 +92,25 @@ mod tests { s } + #[test] + fn shared_profile_parser_keeps_domain_and_title_policy() { + let text = format!( + "TITLE \"literal # title\"\nDOMAIN_MIN 1 0 2\nDOMAIN_MAX 0 0 1\n{}", + cube(|c| c, 2).lines().skip(1).collect::>().join("\n") + ); + let profile = Lut3d::parse_cube(&text).unwrap(); + assert_eq!(profile.title.as_deref(), Some("literal # title")); + assert_eq!(profile.domain_min, [1.0, 0.0, 2.0]); + assert_eq!(profile.domain_max, [0.0, 0.0, 1.0]); + assert!(profile.apply([0.0; 3]).iter().all(|v| v.is_finite())); + let unlabelled = cube(|c| c, 2).lines().skip(1).collect::>().join("\n"); + assert_eq!(Lut3d::parse_cube(&unlabelled).unwrap().title, None); + assert!(Lut3d::parse_cube("LUT_3D_SIZE 256").unwrap_err().contains("16777216")); + for bad in ["0 ignored 0 0", "0 0 0 ignored", "NaN 0 0"] { + assert!(Lut3d::parse_cube(&format!("LUT_3D_SIZE 2\n{bad}\n{}", "0 0 0\n".repeat(7))).is_err()); + } + } + #[test] fn identity_and_swap() { let id = Lut3d::parse_cube(&cube(|c| c, 17)).unwrap(); diff --git a/crates/pipeline/src/tests_light.rs b/crates/pipeline/src/tests_light.rs index 6e9cc9f128..dd38bbf046 100644 --- a/crates/pipeline/src/tests_light.rs +++ b/crates/pipeline/src/tests_light.rs @@ -129,11 +129,13 @@ fn golden(process: ProcessVersion) -> u64 { h } -/// V1 and V2 render byte for byte as they do on main before adding process V3. The hashes were captured -/// on main at e2d18b5fb (before `light_v3`) on macOS aarch64, where they are checked: the renders +/// V1 and V2 render byte for byte as they do on main after #3509's intentional 8-bit dithering. +/// The hashes were captured on unchanged main at a220d3eb on macOS aarch64, where they are checked: the renders /// call the platform's `powf` / `exp2` / `log2`, whose last bit can differ on other platforms, so /// elsewhere the test only prints them. Before updating them during a rebase, run this exact fixture -/// on main and confirm that both hashes match. This PR must not change V1 or V2 rendering. +/// on main and confirm that both hashes match. Restoring only the pre-#3509 quantizer on that +/// baseline reproduces the original e2d18b5fb goldens (0x5bf0a7c8579f3f34, 0x87a3598c15979e4d) +/// exactly: only the intended final quantization change requires this baseline update. #[test] fn v1_and_v2_render_as_before_v3() { let got = [golden(ProcessVersion(1)), golden(ProcessVersion(2))]; @@ -143,7 +145,7 @@ fn v1_and_v2_render_as_before_v3() { } } -const GOLDEN: [u64; 2] = [0x5bf0_a7c8_579f_3f34, 0x87a3_598c_1597_9e4d]; +const GOLDEN: [u64; 2] = [0x4830_59a3_ad92_326c, 0x9653_aed0_ea32_aff3]; fn on(process: Process, s: &DevelopSettings) -> DevelopSettings { DevelopSettings { process: process.version(), ..s.clone() } diff --git a/crates/raw/src/convert.rs b/crates/raw/src/convert.rs index c6ab36eea9..d0224d698a 100644 --- a/crates/raw/src/convert.rs +++ b/crates/raw/src/convert.rs @@ -120,7 +120,7 @@ fn orientation(o: craft_raw::Orientation) -> Orientation { Orientation::from_exif(o.to_exif()) } -fn color(c: craft_raw::ColorData) -> ColorData { +pub(crate) fn color(c: craft_raw::ColorData) -> ColorData { let m = |p: [Option; 2]| p.map(|m| m.map(Mat3)); ColorData { illuminant: c.illuminant, diff --git a/crates/raw/src/dcp.rs b/crates/raw/src/dcp.rs index e0cbea7939..0694d3b31d 100644 --- a/crates/raw/src/dcp.rs +++ b/crates/raw/src/dcp.rs @@ -4,15 +4,13 @@ //! `UniqueCameraModel`, `ProfileName`, the colour/forward matrices and calibration illuminants, the //! hue/saturation map, look table and tone curve. Nothing here ships a profile. -use craft_tiff::{ByteOrder, Ifd, ParseOptions, Tiff, tags as t}; -use lightcraft_color::Xy; +#[cfg(test)] +use craft_tiff::tags as t; -use crate::gaintable::GainTableMap; -use crate::profile::{HsvTable, ProfileLook, ToneCurve}; -use crate::{ColorData, Mat3}; +use crate::ColorData; /// The magic number of a DNG camera profile file (`IIRC` / `MMCR`). -pub const DCP_MAGIC: u16 = 0x4352; +pub use craft_raw::dcp::DCP_MAGIC; /// A parsed camera profile. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] @@ -49,201 +47,30 @@ impl DcpProfile { } } -/// Errors reading a `.dcp`. -#[derive(Debug, thiserror::Error, PartialEq, Eq)] -pub enum DcpError { - #[error("not a DNG camera profile (.dcp)")] - NotDcp, - #[error("damaged camera profile: {0}")] - Damaged(String), - #[error("the camera profile has no usable colour matrix")] - NoMatrix, -} +pub use craft_raw::dcp::{DcpError, MAX_DCP_BYTES, is_dcp, read_dcp}; -/// Is `bytes` a DCP file (by its header)? -pub fn is_dcp(bytes: &[u8]) -> bool { - matches!(bytes.get(0..4), Some([b'I', b'I', b'R', b'C'] | [b'M', b'M', b'C', b'R'])) -} - -/// The largest `.dcp` file read or parsed (real profiles are kilobytes to a few MB). -pub const MAX_DCP_BYTES: u64 = 64 << 20; - -/// Read the `.dcp` file at `path`, reading at most [`MAX_DCP_BYTES`] + 1 bytes: a larger file is refused -/// before it is loaded into memory. -pub fn read_dcp(path: &std::path::Path) -> std::io::Result> { - use std::io::Read; - let mut bytes = Vec::new(); - std::fs::File::open(path)?.take(MAX_DCP_BYTES.saturating_add(1)).read_to_end(&mut bytes)?; - if bytes.len() as u64 > MAX_DCP_BYTES { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "the camera profile is larger than 64 MiB")); - } - Ok(bytes) -} - -/// Parse a `.dcp` file. Files above 64 MiB ([`MAX_DCP_BYTES`]) are refused. +/// Parse the shared file model, keeping application color types at the boundary. pub fn parse_dcp(bytes: &[u8]) -> Result { - if !is_dcp(bytes) { - return Err(DcpError::NotDcp); - } - if bytes.len() as u64 > MAX_DCP_BYTES { - return Err(DcpError::Damaged("larger than 64 MiB".into())); - } - // the TIFF reader only knows 42 / BigTIFF / raw magics: give it a header with 42 in place of RC - let mut data = bytes.to_vec(); - let forty_two: [u8; 2] = if bytes.first() == Some(&b'I') { [42, 0] } else { [0, 42] }; - if let Some(m) = data.get_mut(2..4) { - m.copy_from_slice(&forty_two); - } - let opts = ParseOptions { follow_children: false, max_ifds: 4, value_budget: Some(64 << 20), ..Default::default() }; - let tiff = Tiff::parse_with(&data, &opts).map_err(|e| DcpError::Damaged(e.to_string()))?; - let ifd: &Ifd = tiff.ifds.first().ok_or_else(|| DcpError::Damaged("no IFD".into()))?; - let mut color = color_data(ifd, ifd, tiff.order); - // a profile carries no white balance or calibration of a particular shot - color.as_shot_neutral = None; - color.as_shot_white_xy = None; - color.analog_balance = None; - color.camera_calibration = [None, None]; - color.baseline_sharpness = None; - color.profile.gain_table_map = None; - // only BaselineExposureOffset belongs to a profile (BaselineExposure is the camera's) - color.baseline_exposure = - ifd.f64s(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-4.0, 4.0); - // a single-illuminant profile names one illuminant; its second matrix slot stays empty - if color.color_matrix[0].is_none() { - // the first slot is the one every profile must fill (DNG: ColorMatrix1 is required) - return Err(DcpError::NoMatrix); - } - let text = |tag: u16| ifd.string(tag).map(|s| s.trim_matches(char::from(0)).trim().to_string()).unwrap_or_default(); - Ok(DcpProfile { name: text(t::PROFILE_NAME), camera_model: text(t::UNIQUE_CAMERA_MODEL), color }) + let p = craft_raw::dcp::parse_dcp(bytes)?; + Ok(DcpProfile { name: p.name, camera_model: p.camera_model, color: crate::convert::color(p.color) }) } -/// Write `p` as a `.dcp` file (little-endian): its name, camera, illuminants, matrices, hue/saturation -/// map, look table, tone curve and baseline exposure offset. +/// Write profile wire fields through craft-raw; shot/application policy is not serialized. pub fn write_dcp(p: &DcpProfile) -> Result, DcpError> { - use craft_tiff::writer::srational; - use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; - let c = &p.color; - let mut ifd = IfdBuilder::new(); - ifd.set(t::UNIQUE_CAMERA_MODEL, Value::Ascii(p.camera_model.clone())); - ifd.set(t::PROFILE_NAME, Value::Ascii(p.name.clone())); - let mat = |m: &lightcraft_color::Mat3| Value::SRational(m.0.iter().flatten().map(|v| srational(*v)).collect()); - for i in 0..2 { - if let Some(m) = &c.color_matrix[i] { - ifd.set([t::CALIBRATION_ILLUMINANT_1, t::CALIBRATION_ILLUMINANT_2][i], Value::Short(vec![c.illuminant[i]])); - ifd.set([t::COLOR_MATRIX_1, t::COLOR_MATRIX_2][i], mat(m)); - } - if let Some(m) = &c.forward_matrix[i] { - ifd.set([t::FORWARD_MATRIX_1, t::FORWARD_MATRIX_2][i], mat(m)); - } - } - let flat = |table: &crate::profile::HsvTable| Value::Float(table.data.iter().flatten().copied().collect()); - let dims = - |table: &crate::profile::HsvTable| Value::Long(vec![table.hue_divisions as u32, table.sat_divisions as u32, table.val_divisions as u32]); - if let Some(a) = c.profile.hue_sat_map[0].as_ref() { - ifd.set(t::PROFILE_HUE_SAT_MAP_DIMS, dims(a)); - ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_1, flat(a)); - if a.srgb_value { - ifd.set(t::PROFILE_HUE_SAT_MAP_ENCODING, Value::Long(vec![1])); - } - if let Some(b) = c.profile.hue_sat_map[1] - .as_ref() - .filter(|b| (b.hue_divisions, b.sat_divisions, b.val_divisions) == (a.hue_divisions, a.sat_divisions, a.val_divisions)) - { - ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_2, flat(b)); - } - } - if let Some(l) = &c.profile.look_table { - ifd.set(t::PROFILE_LOOK_TABLE_DIMS, dims(l)); - ifd.set(t::PROFILE_LOOK_TABLE_DATA, flat(l)); - if l.srgb_value { - ifd.set(t::PROFILE_LOOK_TABLE_ENCODING, Value::Long(vec![1])); - } - } - if let Some(tc) = &c.profile.tone_curve { - ifd.set(t::PROFILE_TONE_CURVE, Value::Float(tc.points.iter().flatten().copied().collect())); - } - if c.baseline_exposure != 0.0 { - ifd.set(t::BASELINE_EXPOSURE_OFFSET, Value::SRational(vec![srational(c.baseline_exposure)])); - } - let mut out = TiffWriter::new(ByteOrder::Little, false).write(&[ifd]).map_err(|e| DcpError::Damaged(e.to_string()))?; - // the DCP magic in place of 42 - if let Some(m) = out.get_mut(2..4) { - m.copy_from_slice(&DCP_MAGIC.to_le_bytes()); - } - Ok(out) -} - -// The colour tags a profile shares with DNG, read as DNG reads them (a DNG's own are read by `craft-raw`). - -fn mat3(v: Option>) -> Option { - let v = v?; - if v.len() != 9 || v.iter().any(|x| !x.is_finite()) { - return None; - } - let m = Mat3([[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]]]); - (m.determinant().abs() > 1e-12).then_some(m) -} - -fn vec3(v: Option>) -> Option<[f64; 3]> { - let v = v?; - (v.len() == 3 && v.iter().all(|x| x.is_finite() && *x > 0.0)).then(|| [v[0], v[1], v[2]]) -} - -/// Colour tags: DNG puts them in IFD0, but some writers use the raw IFD; prefer the raw IFD. -/// `order` is the file's byte order (for the binary gain-table-map tags). -fn color_data(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ColorData { - let get = |tag: u16| raw.f64s(tag).or_else(|| ifd0.f64s(tag)); - let geti = |tag: u16| raw.u16(tag).or_else(|| ifd0.u16(tag)); - ColorData { - illuminant: [geti(t::CALIBRATION_ILLUMINANT_1).unwrap_or(0), geti(t::CALIBRATION_ILLUMINANT_2).unwrap_or(0)], - color_matrix: [mat3(get(t::COLOR_MATRIX_1)), mat3(get(t::COLOR_MATRIX_2))], - forward_matrix: [mat3(get(t::FORWARD_MATRIX_1)), mat3(get(t::FORWARD_MATRIX_2))], - camera_calibration: [mat3(get(t::CAMERA_CALIBRATION_1)), mat3(get(t::CAMERA_CALIBRATION_2))], - analog_balance: vec3(get(t::ANALOG_BALANCE)), - as_shot_neutral: vec3(get(t::AS_SHOT_NEUTRAL)), - as_shot_white_xy: get(t::AS_SHOT_WHITE_XY).filter(|v| v.len() == 2 && v[0] > 0.0 && v[1] > 0.0).map(|v| Xy::new(v[0], v[1])), - baseline_exposure: get(t::BASELINE_EXPOSURE).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0) - + get(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0), - // DNG 1.7 BaselineSharpness (IFD 0 or the enhanced IFD); implausible values are ignored - baseline_sharpness: get(t::BASELINE_SHARPNESS).and_then(|v| v.first().copied()).filter(|v| v.is_finite() && *v > 0.0 && *v <= 16.0), - profile: profile_look(ifd0, raw, order), - kelvin_presets: None, - } -} - -/// The profile look tags (`ProfileHueSatMap*`, `ProfileLookTable*`, `ProfileToneCurve`, -/// `ProfileGainTableMap*`); malformed ones are ignored. Like the colour tags, read from the raw IFD -/// first, else IFD 0. -fn profile_look(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ProfileLook { - let pick = |tag: u16| if raw.contains(tag) { raw } else { ifd0 }; - let table = |dims: u16, data: u16, enc: u16| { - let ifd = pick(dims); - let dims = ifd.u64s(dims)?; - let data = ifd.f64s(data)?; - HsvTable::from_tags(&dims, &data, ifd.u64s(enc).and_then(|v| v.first().copied()).unwrap_or(0)) + let color = craft_raw::ColorData { + illuminant: p.color.illuminant, + color_matrix: p.color.color_matrix.map(|m| m.map(|m| m.0)), + forward_matrix: p.color.forward_matrix.map(|m| m.map(|m| m.0)), + baseline_exposure: p.color.baseline_exposure, + profile: p.color.profile.clone(), + ..Default::default() }; - ProfileLook { - hue_sat_map: [ - table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_1, t::PROFILE_HUE_SAT_MAP_ENCODING), - table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_2, t::PROFILE_HUE_SAT_MAP_ENCODING), - ], - look_table: table(t::PROFILE_LOOK_TABLE_DIMS, t::PROFILE_LOOK_TABLE_DATA, t::PROFILE_LOOK_TABLE_ENCODING), - tone_curve: pick(t::PROFILE_TONE_CURVE).f64s(t::PROFILE_TONE_CURVE).and_then(|v| ToneCurve::from_tag(&v)), - gain_table_map: gain_table_map(ifd0, raw, order), - } + craft_raw::dcp::write_dcp(&craft_raw::dcp::DcpProfile { name: p.name.clone(), camera_model: p.camera_model.clone(), color }) } -/// The gain table map (DNG 1.7 precedence): `ProfileGainTableMap2` from IFD 0 (the embedded -/// camera profile), else from the raw IFD; else `ProfileGainTableMap` from the raw IFD (where DNG -/// 1.6 put it, and where Apple writes it), else from IFD 0 (where DNG 1.7 says it was meant to be). -/// A malformed tag falls through to the next one. -fn gain_table_map(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> Option { - let parse = |ifd: &Ifd, tag: u16| ifd.bytes(tag).and_then(|b| GainTableMap::parse(b, order, tag == t::PROFILE_GAIN_TABLE_MAP_2)); - parse(ifd0, t::PROFILE_GAIN_TABLE_MAP_2) - .or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP_2)) - .or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP)) - .or_else(|| parse(ifd0, t::PROFILE_GAIN_TABLE_MAP)) -} +#[cfg(test)] +#[path = "dcp_legacy_tests.rs"] +mod legacy; #[cfg(test)] mod tests { @@ -407,3 +234,36 @@ mod tests { assert!((c.baseline_exposure - 0.25).abs() < 1e-12); } } + +#[cfg(test)] +mod shared_parity { + use super::*; + fn check(bytes: &[u8]) { + let old = legacy::parse_dcp(bytes); + let new = parse_dcp(bytes); + match (old, new) { + (Ok(a), Ok(b)) => { + assert_eq!((a.name.as_str(), a.camera_model.as_str(), &a.color), (b.name.as_str(), b.camera_model.as_str(), &b.color)); + assert_eq!(legacy::write_dcp(&a).map_err(|e| e.to_string()), write_dcp(&b).map_err(|e| e.to_string())); + } + (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()), + other => panic!("different DCP acceptance: {other:?}"), + } + } + #[test] + fn shared_reader_and_writer_match_original_on_both_endian_mutations() { + for little in [false, true] { + let bytes = super::tests::synthetic_dcp(little, true); + for n in 0..=bytes.len() { + check(&bytes[..n]); + } + for at in 0..bytes.len() { + for value in [0, 0xff, 0x80] { + let mut mutated = bytes.clone(); + mutated[at] = value; + check(&mutated); + } + } + } + } +} diff --git a/crates/raw/src/dcp_legacy_tests.rs b/crates/raw/src/dcp_legacy_tests.rs new file mode 100644 index 0000000000..6144de0bf1 --- /dev/null +++ b/crates/raw/src/dcp_legacy_tests.rs @@ -0,0 +1,247 @@ +#![allow(dead_code)] +//! DNG Camera Profiles (`.dcp`): the user's own camera colour profiles, read at run time from +//! files they supply (DNG specification, chapter 6 "Camera Profiles"). A `.dcp` is a TIFF-structured +//! file whose header carries the magic `RC` (0x4352) in place of 42, with the profile tags in IFD 0: +//! `UniqueCameraModel`, `ProfileName`, the colour/forward matrices and calibration illuminants, the +//! hue/saturation map, look table and tone curve. Nothing here ships a profile. + +use craft_tiff::{ByteOrder, Ifd, ParseOptions, Tiff, tags as t}; +use lightcraft_color::Xy; + +use crate::gaintable::GainTableMap; +use crate::profile::{HsvTable, ProfileLook, ToneCurve}; +use crate::{ColorData, Mat3}; + +/// The magic number of a DNG camera profile file (`IIRC` / `MMCR`). +pub const DCP_MAGIC: u16 = 0x4352; + +/// A parsed camera profile. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct DcpProfile { + /// `ProfileName` (empty when the file has none). + pub name: String, + /// `UniqueCameraModel`: the camera the profile was made for (empty when absent). + pub camera_model: String, + /// The colour model: illuminants, matrices and the profile look (hue/sat map, look table, tone curve). + pub color: ColorData, +} + +impl DcpProfile { + /// `color` (a raw file's own colour facts) with this profile's colour model in place of the + /// file's: its matrices, illuminants and look. The file's white balance (as-shot neutral or + /// white, and its white-balance presets), analog balance and baseline exposure stay, plus its + /// camera calibration when the profile has the same calibration illuminants (DNG 6.3: + /// calibration belongs to the camera, the profile to the look). + pub fn applied_to(&self, color: &ColorData) -> ColorData { + let calibration = if self.color.illuminant == color.illuminant { color.camera_calibration } else { [None, None] }; + ColorData { + illuminant: self.color.illuminant, + color_matrix: self.color.color_matrix, + forward_matrix: self.color.forward_matrix, + camera_calibration: calibration, + analog_balance: color.analog_balance, + as_shot_neutral: color.as_shot_neutral, + as_shot_white_xy: color.as_shot_white_xy, + baseline_exposure: color.baseline_exposure + self.color.baseline_exposure, + baseline_sharpness: color.baseline_sharpness, + profile: crate::profile::ProfileLook { gain_table_map: color.profile.gain_table_map.clone(), ..self.color.profile.clone() }, + kelvin_presets: color.kelvin_presets.clone(), + } + } +} + +/// Errors reading a `.dcp`. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum DcpError { + #[error("not a DNG camera profile (.dcp)")] + NotDcp, + #[error("damaged camera profile: {0}")] + Damaged(String), + #[error("the camera profile has no usable colour matrix")] + NoMatrix, +} + +/// Is `bytes` a DCP file (by its header)? +pub fn is_dcp(bytes: &[u8]) -> bool { + matches!(bytes.get(0..4), Some([b'I', b'I', b'R', b'C'] | [b'M', b'M', b'C', b'R'])) +} + +/// The largest `.dcp` file read or parsed (real profiles are kilobytes to a few MB). +pub const MAX_DCP_BYTES: u64 = 64 << 20; + +/// Read the `.dcp` file at `path`, reading at most [`MAX_DCP_BYTES`] + 1 bytes: a larger file is refused +/// before it is loaded into memory. +pub fn read_dcp(path: &std::path::Path) -> std::io::Result> { + use std::io::Read; + let mut bytes = Vec::new(); + std::fs::File::open(path)?.take(MAX_DCP_BYTES.saturating_add(1)).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_DCP_BYTES { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "the camera profile is larger than 64 MiB")); + } + Ok(bytes) +} + +/// Parse a `.dcp` file. Files above 64 MiB ([`MAX_DCP_BYTES`]) are refused. +pub fn parse_dcp(bytes: &[u8]) -> Result { + if !is_dcp(bytes) { + return Err(DcpError::NotDcp); + } + if bytes.len() as u64 > MAX_DCP_BYTES { + return Err(DcpError::Damaged("larger than 64 MiB".into())); + } + // the TIFF reader only knows 42 / BigTIFF / raw magics: give it a header with 42 in place of RC + let mut data = bytes.to_vec(); + let forty_two: [u8; 2] = if bytes.first() == Some(&b'I') { [42, 0] } else { [0, 42] }; + if let Some(m) = data.get_mut(2..4) { + m.copy_from_slice(&forty_two); + } + let opts = ParseOptions { follow_children: false, max_ifds: 4, value_budget: Some(64 << 20), ..Default::default() }; + let tiff = Tiff::parse_with(&data, &opts).map_err(|e| DcpError::Damaged(e.to_string()))?; + let ifd: &Ifd = tiff.ifds.first().ok_or_else(|| DcpError::Damaged("no IFD".into()))?; + let mut color = color_data(ifd, ifd, tiff.order); + // a profile carries no white balance or calibration of a particular shot + color.as_shot_neutral = None; + color.as_shot_white_xy = None; + color.analog_balance = None; + color.camera_calibration = [None, None]; + color.baseline_sharpness = None; + color.profile.gain_table_map = None; + // only BaselineExposureOffset belongs to a profile (BaselineExposure is the camera's) + color.baseline_exposure = + ifd.f64s(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-4.0, 4.0); + // a single-illuminant profile names one illuminant; its second matrix slot stays empty + if color.color_matrix[0].is_none() { + // the first slot is the one every profile must fill (DNG: ColorMatrix1 is required) + return Err(DcpError::NoMatrix); + } + let text = |tag: u16| ifd.string(tag).map(|s| s.trim_matches(char::from(0)).trim().to_string()).unwrap_or_default(); + Ok(DcpProfile { name: text(t::PROFILE_NAME), camera_model: text(t::UNIQUE_CAMERA_MODEL), color }) +} + +/// Write `p` as a `.dcp` file (little-endian): its name, camera, illuminants, matrices, hue/saturation +/// map, look table, tone curve and baseline exposure offset. +pub fn write_dcp(p: &DcpProfile) -> Result, DcpError> { + use craft_tiff::writer::srational; + use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; + let c = &p.color; + let mut ifd = IfdBuilder::new(); + ifd.set(t::UNIQUE_CAMERA_MODEL, Value::Ascii(p.camera_model.clone())); + ifd.set(t::PROFILE_NAME, Value::Ascii(p.name.clone())); + let mat = |m: &lightcraft_color::Mat3| Value::SRational(m.0.iter().flatten().map(|v| srational(*v)).collect()); + for i in 0..2 { + if let Some(m) = &c.color_matrix[i] { + ifd.set([t::CALIBRATION_ILLUMINANT_1, t::CALIBRATION_ILLUMINANT_2][i], Value::Short(vec![c.illuminant[i]])); + ifd.set([t::COLOR_MATRIX_1, t::COLOR_MATRIX_2][i], mat(m)); + } + if let Some(m) = &c.forward_matrix[i] { + ifd.set([t::FORWARD_MATRIX_1, t::FORWARD_MATRIX_2][i], mat(m)); + } + } + let flat = |table: &crate::profile::HsvTable| Value::Float(table.data.iter().flatten().copied().collect()); + let dims = + |table: &crate::profile::HsvTable| Value::Long(vec![table.hue_divisions as u32, table.sat_divisions as u32, table.val_divisions as u32]); + if let Some(a) = c.profile.hue_sat_map[0].as_ref() { + ifd.set(t::PROFILE_HUE_SAT_MAP_DIMS, dims(a)); + ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_1, flat(a)); + if a.srgb_value { + ifd.set(t::PROFILE_HUE_SAT_MAP_ENCODING, Value::Long(vec![1])); + } + if let Some(b) = c.profile.hue_sat_map[1] + .as_ref() + .filter(|b| (b.hue_divisions, b.sat_divisions, b.val_divisions) == (a.hue_divisions, a.sat_divisions, a.val_divisions)) + { + ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_2, flat(b)); + } + } + if let Some(l) = &c.profile.look_table { + ifd.set(t::PROFILE_LOOK_TABLE_DIMS, dims(l)); + ifd.set(t::PROFILE_LOOK_TABLE_DATA, flat(l)); + if l.srgb_value { + ifd.set(t::PROFILE_LOOK_TABLE_ENCODING, Value::Long(vec![1])); + } + } + if let Some(tc) = &c.profile.tone_curve { + ifd.set(t::PROFILE_TONE_CURVE, Value::Float(tc.points.iter().flatten().copied().collect())); + } + if c.baseline_exposure != 0.0 { + ifd.set(t::BASELINE_EXPOSURE_OFFSET, Value::SRational(vec![srational(c.baseline_exposure)])); + } + let mut out = TiffWriter::new(ByteOrder::Little, false).write(&[ifd]).map_err(|e| DcpError::Damaged(e.to_string()))?; + // the DCP magic in place of 42 + if let Some(m) = out.get_mut(2..4) { + m.copy_from_slice(&DCP_MAGIC.to_le_bytes()); + } + Ok(out) +} + +// The colour tags a profile shares with DNG, read as DNG reads them (a DNG's own are read by `craft-raw`). + +fn mat3(v: Option>) -> Option { + let v = v?; + if v.len() != 9 || v.iter().any(|x| !x.is_finite()) { + return None; + } + let m = Mat3([[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]]]); + (m.determinant().abs() > 1e-12).then_some(m) +} + +fn vec3(v: Option>) -> Option<[f64; 3]> { + let v = v?; + (v.len() == 3 && v.iter().all(|x| x.is_finite() && *x > 0.0)).then(|| [v[0], v[1], v[2]]) +} + +/// Colour tags: DNG puts them in IFD0, but some writers use the raw IFD; prefer the raw IFD. +/// `order` is the file's byte order (for the binary gain-table-map tags). +fn color_data(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ColorData { + let get = |tag: u16| raw.f64s(tag).or_else(|| ifd0.f64s(tag)); + let geti = |tag: u16| raw.u16(tag).or_else(|| ifd0.u16(tag)); + ColorData { + illuminant: [geti(t::CALIBRATION_ILLUMINANT_1).unwrap_or(0), geti(t::CALIBRATION_ILLUMINANT_2).unwrap_or(0)], + color_matrix: [mat3(get(t::COLOR_MATRIX_1)), mat3(get(t::COLOR_MATRIX_2))], + forward_matrix: [mat3(get(t::FORWARD_MATRIX_1)), mat3(get(t::FORWARD_MATRIX_2))], + camera_calibration: [mat3(get(t::CAMERA_CALIBRATION_1)), mat3(get(t::CAMERA_CALIBRATION_2))], + analog_balance: vec3(get(t::ANALOG_BALANCE)), + as_shot_neutral: vec3(get(t::AS_SHOT_NEUTRAL)), + as_shot_white_xy: get(t::AS_SHOT_WHITE_XY).filter(|v| v.len() == 2 && v[0] > 0.0 && v[1] > 0.0).map(|v| Xy::new(v[0], v[1])), + baseline_exposure: get(t::BASELINE_EXPOSURE).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0) + + get(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0), + // DNG 1.7 BaselineSharpness (IFD 0 or the enhanced IFD); implausible values are ignored + baseline_sharpness: get(t::BASELINE_SHARPNESS).and_then(|v| v.first().copied()).filter(|v| v.is_finite() && *v > 0.0 && *v <= 16.0), + profile: profile_look(ifd0, raw, order), + kelvin_presets: None, + } +} + +/// The profile look tags (`ProfileHueSatMap*`, `ProfileLookTable*`, `ProfileToneCurve`, +/// `ProfileGainTableMap*`); malformed ones are ignored. Like the colour tags, read from the raw IFD +/// first, else IFD 0. +fn profile_look(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ProfileLook { + let pick = |tag: u16| if raw.contains(tag) { raw } else { ifd0 }; + let table = |dims: u16, data: u16, enc: u16| { + let ifd = pick(dims); + let dims = ifd.u64s(dims)?; + let data = ifd.f64s(data)?; + HsvTable::from_tags(&dims, &data, ifd.u64s(enc).and_then(|v| v.first().copied()).unwrap_or(0)) + }; + ProfileLook { + hue_sat_map: [ + table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_1, t::PROFILE_HUE_SAT_MAP_ENCODING), + table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_2, t::PROFILE_HUE_SAT_MAP_ENCODING), + ], + look_table: table(t::PROFILE_LOOK_TABLE_DIMS, t::PROFILE_LOOK_TABLE_DATA, t::PROFILE_LOOK_TABLE_ENCODING), + tone_curve: pick(t::PROFILE_TONE_CURVE).f64s(t::PROFILE_TONE_CURVE).and_then(|v| ToneCurve::from_tag(&v)), + gain_table_map: gain_table_map(ifd0, raw, order), + } +} + +/// The gain table map (DNG 1.7 precedence): `ProfileGainTableMap2` from IFD 0 (the embedded +/// camera profile), else from the raw IFD; else `ProfileGainTableMap` from the raw IFD (where DNG +/// 1.6 put it, and where Apple writes it), else from IFD 0 (where DNG 1.7 says it was meant to be). +/// A malformed tag falls through to the next one. +fn gain_table_map(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> Option { + let parse = |ifd: &Ifd, tag: u16| ifd.bytes(tag).and_then(|b| GainTableMap::parse(b, order, tag == t::PROFILE_GAIN_TABLE_MAP_2)); + parse(ifd0, t::PROFILE_GAIN_TABLE_MAP_2) + .or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP_2)) + .or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP)) + .or_else(|| parse(ifd0, t::PROFILE_GAIN_TABLE_MAP)) +} diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index dbce6d042d..1b4909c366 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -1045,7 +1045,9 @@ fn malformed_semantic_masks_are_skipped() { assert_eq!(decode(&bytes).unwrap().cpp, 3); let masks = lightcraft_raw::semantic_masks(&bytes); let names: Vec<&str> = masks.iter().map(|m| m.name.as_str()).collect(); - // Truncated strip pixels are rejected by the shared reader instead of zero-filled. + // A 4×4, 8-bit uncompressed mask needs 16 bytes: the three-byte strip + // is truncated, not a valid mask with zero-filled missing pixels. Keep the + // separate complete mask to test invalid MaskSubArea handling. assert_eq!(names, ["sub area too small"]); assert!(masks.iter().all(|m| m.sub_area.is_none()), "sub areas the mask doesn't fit are ignored"); for m in &masks { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index c9e0e6aead..836190bd95 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -1,10 +1,10 @@ //! Presentation-only localization. Command ids, user names and catalog data remain unchanged. //! //! A language is one entry in [`language_table!`] below: its BCP-47 code, the endonym shown in the -//! Language menus, the ISO 15924 script its text needs (which picks the CJK font fallback), and its +//! Settings language row, the ISO 15924 script its text needs (which picks the CJK font fallback), and its //! message catalog (`locales/.json`, embedded at build time). Adding a language is that entry //! plus its catalogs and the corresponding language command in `menus.rs`. Settings read the -//! locale table, while menus and the control channel share the command mapping. +//! locale table, while the control channel uses the command mapping. use std::{cell::RefCell, collections::BTreeMap, sync::OnceLock}; @@ -34,7 +34,7 @@ macro_rules! language_table { match self { Self::$source => $source_code, $(Self::$variant => $code,)* } } - /// The language's own name, as shown in the Language menus. + /// The language's own name, as shown in the Settings language row. pub const fn name(self) -> &'static str { match self { Self::$source => "English", $(Self::$variant => $name,)* } } @@ -140,7 +140,7 @@ language_table! { } impl Locale { - /// Every language in the order the Settings row and Edit ▸ Language list them: English first + /// Every language in the order the Settings row lists them: English first /// (the source language), then the rest by their own name with accents folded, so Čeština /// sits under C. Names in other scripts follow the Latin ones in code point order: Cyrillic, /// Georgian, then the CJK languages. @@ -590,9 +590,9 @@ mod picker_order_tests { } #[test] - fn language_menu_lists_the_picker_order() { + fn language_commands_list_the_picker_order() { let menu: Vec<&str> = crate::menus::LANGUAGE_COMMANDS.iter().map(|c| c.1).collect(); let picker: Vec<&str> = Locale::for_picker().into_iter().map(Locale::name).collect(); - assert_eq!(menu, picker, "Edit ▸ Language and the Settings row list the languages the same way"); + assert_eq!(menu, picker, "the language commands and the Settings row list the languages the same way"); } } diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 47af31e2c6..8540f7b741 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -22,7 +22,6 @@ fn languages_switch_persist_and_keep_user_values() { app.run(&command, serde_json::json!({})).unwrap(); assert_eq!(app.ui.language, locale); assert_eq!(language(), locale); - assert_eq!(crate::menubar::checked(&app, &command), Some(true)); assert_eq!(builtin_label("Warm Glow", false), "Warm Glow"); assert_eq!(builtin_label("Warm Glow", true), locale.tr("Warm Glow")); assert_eq!(tr("photo-{title}.jpg"), "photo-{title}.jpg"); @@ -369,7 +368,7 @@ fn translated_catalogs_do_not_use_missing_menu_triangles() { } } -/// The language menu covers every language, and a language's own command selects it. +/// Every language has a command, and a language's own command selects it. #[test] fn language_commands_cover_every_language() { let commands = [ @@ -392,11 +391,11 @@ fn language_commands_cover_every_language() { ("app.language.indonesian", Locale::Id), ("app.language.vietnamese", Locale::Vi), ]; - // One command per language, and every command reachable from the menu table. + // One command per language, and every command in the UI command tables. assert_eq!(commands.len(), Locale::ALL.len()); for (id, language) in commands { assert_eq!(crate::menus::language_from_command(id), Some(language), "{id}"); - assert!(crate::menus::ui_commands().any(|command| command.0 == id), "{id} is not in the menu"); + assert!(crate::menus::ui_commands().any(|command| command.0 == id), "{id} is not a UI command"); } assert_eq!(crate::menus::language_from_command("app.language.klingon"), None); assert_eq!(crate::menus::language_from_command("view.detail"), None); @@ -586,7 +585,6 @@ fn german_switches_via_menu_and_control_and_persists() { app.run("app.language.german", serde_json::json!({})).unwrap(); assert_eq!(app.ui.language, Locale::De); assert_eq!(language(), Locale::De); - assert_eq!(crate::menubar::checked(&app, "app.language.german"), Some(true)); let saved = serde_json::to_string(&app.ui).unwrap(); assert!(saved.contains(r#""language":"de""#)); assert_eq!(serde_json::from_str::(&saved).unwrap().language, Locale::De); @@ -887,8 +885,6 @@ fn traditional_chinese_switches_through_menu_and_control_and_persists() { assert_eq!(source_label(lightcraft_engine::LibrarySource::All, &app.session.catalog), Locale::ZhHant.tr("All Photos")); assert_eq!(date_group_label("", false), Locale::ZhHant.tr("Unknown Date")); assert_eq!(display_time("a-user-value"), "a-user-value"); - assert_eq!(crate::menubar::checked(&app, "app.language.traditionalChinese"), Some(true)); - assert_eq!(crate::menubar::checked(&app, "app.language.english"), Some(false)); assert_eq!(tr("my-photo.jpg"), "my-photo.jpg"); for id in ["album.addPhotos", "metadata.applyPreset", "label.applySet"] { assert_eq!(crate::menubar::display_item_label(id, &serde_json::json!({"id": 1}), "Color"), "Color"); @@ -1275,7 +1271,6 @@ fn polish_switches_formats_dates_and_reads_every_count() { app.run("app.language.polish", serde_json::json!({})).unwrap(); assert_eq!(app.ui.language, Locale::Pl); assert_eq!(Locale::Pl.name(), "Polski"); - assert_eq!(crate::menubar::checked(&app, "app.language.polish"), Some(true)); assert_eq!(tr("File"), "Plik"); assert_eq!(tr("Exposure"), "Ekspozycja"); assert_eq!(date_group_label("2026-09-20", false), "Niedziela, 20.09.2026"); diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index b73729a913..e298e104c6 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -392,8 +392,6 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option { let u = &app.ui; let panel = |p: RightPanel| Some(u.right == p); match id { - // Every language's command is checked when it is the active one. - _ if crate::menus::language_from_command(id).is_some() => Some(crate::menus::language_from_command(id) == Some(u.language)), "develop.autoSync" => Some(app.session.auto_sync), "view.photoCounts" => Some(u.show_counts), "view.secondWindow" => Some(u.second_window), diff --git a/crates/ui-egui/src/menus/menubar/tests.rs b/crates/ui-egui/src/menus/menubar/tests.rs index cc3c5c4b0f..88019f15bf 100644 --- a/crates/ui-egui/src/menus/menubar/tests.rs +++ b/crates/ui-egui/src/menus/menubar/tests.rs @@ -852,3 +852,20 @@ fn edit_menu_places_the_select_and_paste_rows_with_their_kin() { let after = &nodes[pos("app.settings") + 1..]; assert!(!after.iter().any(|n| matches!(n, MenuNode::Item { .. })), "no row follows Settings… but a submenu: {after:?}"); } + +/// The interface language is chosen in Settings ▸ General (one choice per language), so Edit has no +/// Language submenu of 18 rows. The commands stay: agents and tests still switch language by id. +#[test] +fn edit_menu_has_no_language_submenu_because_settings_has_the_choice() { + let mut a = app(); + let bar = menu_bar(&a); + let edit = bar.iter().find(|(t, _)| t == "Edit").expect("Edit menu").1.as_slice(); + assert!(!edit.iter().any(|n| matches!(n, MenuNode::Submenu { label, .. } if label == "Language")), "Edit still has a Language submenu"); + for (title, nodes) in &bar { + for command in crate::menus::LANGUAGE_COMMANDS { + assert!(find(nodes, command.0).is_none(), "{} is in {title}", command.0); + } + } + run_item(&mut a, "app.language.german", Value::Null).expect("the command still switches language"); + assert_eq!(a.ui.language, crate::i18n::Locale::De); +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fb83b3a746..d22ff8bb43 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1,28 +1,29 @@ use super::UiCommand; -/// The "Edit → Language" entries, one per language in [`crate::i18n::Locale::ALL`], so a language -/// has a matching menu command (also listed through the control channel). Tests check coverage. +/// One command per language in [`crate::i18n::Locale::ALL`], so a language has a matching command +/// (also listed through the control channel). They are in no menu: Settings ▸ General has the +/// language choice. Tests check coverage. pub const LANGUAGE_COMMANDS: &[UiCommand] = &[ - ("app.language.english", crate::i18n::Locale::En.name(), None, "Edit>Language"), + ("app.language.english", crate::i18n::Locale::En.name(), None, ""), // The picker order (`Locale::for_picker`): alphabetical by the language's own name after // English; Cyrillic, Georgian, then CJK names follow the Latin ones. A test keeps them equal. - ("app.language.indonesian", crate::i18n::Locale::Id.name(), None, "Edit>Language"), - ("app.language.czech", crate::i18n::Locale::Cs.name(), None, "Edit>Language"), - ("app.language.german", crate::i18n::Locale::De.name(), None, "Edit>Language"), - ("app.language.spanish", crate::i18n::Locale::Es.name(), None, "Edit>Language"), - ("app.language.french", crate::i18n::Locale::Fr.name(), None, "Edit>Language"), - ("app.language.italian", crate::i18n::Locale::It.name(), None, "Edit>Language"), - ("app.language.polish", crate::i18n::Locale::Pl.name(), None, "Edit>Language"), - ("app.language.portuguese", crate::i18n::Locale::PtBr.name(), None, "Edit>Language"), - ("app.language.finnish", crate::i18n::Locale::Fi.name(), None, "Edit>Language"), - ("app.language.swedish", crate::i18n::Locale::Sv.name(), None, "Edit>Language"), - ("app.language.vietnamese", crate::i18n::Locale::Vi.name(), None, "Edit>Language"), - ("app.language.russian", crate::i18n::Locale::Ru.name(), None, "Edit>Language"), - ("app.language.ukrainian", crate::i18n::Locale::Uk.name(), None, "Edit>Language"), - ("app.language.georgian", crate::i18n::Locale::Ka.name(), None, "Edit>Language"), - ("app.language.japanese", crate::i18n::Locale::Ja.name(), None, "Edit>Language"), - ("app.language.simplifiedChinese", crate::i18n::Locale::ZhHans.name(), None, "Edit>Language"), - ("app.language.traditionalChinese", crate::i18n::Locale::ZhHant.name(), None, "Edit>Language"), + ("app.language.indonesian", crate::i18n::Locale::Id.name(), None, ""), + ("app.language.czech", crate::i18n::Locale::Cs.name(), None, ""), + ("app.language.german", crate::i18n::Locale::De.name(), None, ""), + ("app.language.spanish", crate::i18n::Locale::Es.name(), None, ""), + ("app.language.french", crate::i18n::Locale::Fr.name(), None, ""), + ("app.language.italian", crate::i18n::Locale::It.name(), None, ""), + ("app.language.polish", crate::i18n::Locale::Pl.name(), None, ""), + ("app.language.portuguese", crate::i18n::Locale::PtBr.name(), None, ""), + ("app.language.finnish", crate::i18n::Locale::Fi.name(), None, ""), + ("app.language.swedish", crate::i18n::Locale::Sv.name(), None, ""), + ("app.language.vietnamese", crate::i18n::Locale::Vi.name(), None, ""), + ("app.language.russian", crate::i18n::Locale::Ru.name(), None, ""), + ("app.language.ukrainian", crate::i18n::Locale::Uk.name(), None, ""), + ("app.language.georgian", crate::i18n::Locale::Ka.name(), None, ""), + ("app.language.japanese", crate::i18n::Locale::Ja.name(), None, ""), + ("app.language.simplifiedChinese", crate::i18n::Locale::ZhHans.name(), None, ""), + ("app.language.traditionalChinese", crate::i18n::Locale::ZhHant.name(), None, ""), ]; /// Every UI command: the languages, then everything else. `xtask parity` reads both tables from @@ -31,8 +32,8 @@ pub fn ui_commands() -> impl Iterator { LANGUAGE_COMMANDS.iter().chain(UI_COMMANDS) } -/// The language a Language-menu command selects, if the id is one. The engine and the UI both go -/// through here, so the menu, the settings row and the control channel agree on the mapping. +/// The language a language command selects, if the id is one. The engine and the UI both go +/// through here, so the settings row and the control channel agree on the mapping. pub fn language_from_command(id: &str) -> Option { match id { "app.language.english" => Some(crate::i18n::Locale::En), diff --git a/crates/ui-egui/src/tests/dialog_settings.rs b/crates/ui-egui/src/tests/dialog_settings.rs index 950cae6e66..4398f8c053 100644 --- a/crates/ui-egui/src/tests/dialog_settings.rs +++ b/crates/ui-egui/src/tests/dialog_settings.rs @@ -390,3 +390,21 @@ fn each_tab_remembers_how_far_it_was_scrolled() { show(&mut h, "import"); assert!((rect(&h, "check:settings.perCamera").top() - scrolled).abs() < 0.5, "Import is where it was left after a reopen"); } + +/// Settings ▸ General ▸ Language is where the interface language is chosen (Edit has no Language +/// menu): each choice switches the app at once. +#[test] +fn each_language_choice_in_general_switches_the_interface() { + let mut h = demo([1600.0, 1000.0]); + show(&mut h, "general"); + let picker = crate::i18n::Locale::for_picker(); + for (i, language) in picker.iter().enumerate() { + let r = h.request("ui.clickWidget", json!({"id": format!("button:settingsLanguage-{i}")}), T); + assert_eq!(r["ok"], true, "{language:?}: {r}"); + h.step(); + h.step(); + assert_eq!(h.app.ui.language, *language, "choice {i}"); + assert_eq!(crate::i18n::language(), *language, "choice {i} is applied at once"); + } + crate::i18n::set_language(crate::i18n::Locale::En); +} diff --git a/docs/localization-cs.md b/docs/localization-cs.md index c3ed1ddcf4..c04e8cfe4c 100644 --- a/docs/localization-cs.md +++ b/docs/localization-cs.md @@ -1,7 +1,6 @@ # Čeština -Češtinu (`cs`, English name **Czech**, native name **Čeština**) zapnete přes **Úpravy → Jazyk → -Čeština** nebo **Nastavení → Obecné → Jazyk**. Změna platí ihned a ukládá se pro další spuštění. +Češtinu (`cs`, English name **Czech**, native name **Čeština**) zapnete přes **Nastavení → Obecné → Jazyk → Čeština**. Změna platí ihned a ukládá se pro další spuštění. Příkaz je `app.language.czech`; řídicí kanál přijímá `ui.set {"language":"cs"}` i značky `cs-CZ` a `cs_CZ.UTF-8`. Pro běh bez okna lze nastavit `LIGHTCRAFT_LANGUAGE=cs`. diff --git a/docs/localization-de.md b/docs/localization-de.md index b31e9eff53..2366b83f54 100644 --- a/docs/localization-de.md +++ b/docs/localization-de.md @@ -1,6 +1,6 @@ # LightCraft auf Deutsch -Wähle **Bearbeiten → Sprache → Deutsch** oder **Einstellungen → Allgemein → Sprache**. +Wähle **Einstellungen → Allgemein → Sprache → Deutsch**. Die Auswahl gilt sofort und wird für den nächsten Start gespeichert (`language: "de"` in `ui.json`). Die deutschen Kataloge decken alle Schlüssel der bisherigen Übersetzungen sowie sämtliche diff --git a/docs/localization-es.md b/docs/localization-es.md index d8aeaa7838..91c1fad8bd 100644 --- a/docs/localization-es.md +++ b/docs/localization-es.md @@ -1,6 +1,6 @@ # LightCraft en español -Elegir **Editar → Idioma → Español** o **Ajustes → General → Idioma**. El cambio se aplica al +Elegir **Ajustes → General → Idioma → Español**. El cambio se aplica al momento y se conserva para el próximo inicio (`language: "es"` en `ui.json`). `LIGHTCRAFT_LANGUAGE` acepta cualquier variante del español (`es`, `es-ES`, `es_MX.UTF-8`, `es-419`…). diff --git a/docs/localization-fi.md b/docs/localization-fi.md index fcb89d7844..76483a99da 100644 --- a/docs/localization-fi.md +++ b/docs/localization-fi.md @@ -1,7 +1,7 @@ # Suomi Suomen (`fi`, englanniksi **Finnish**, omakielinen nimi **Suomi**) saa käyttöön valitsemalla -**Muokkaa → Kieli → Suomi** tai **Asetukset → Yleiset → Kieli**. Muutos tulee voimaan heti ja +**Asetukset → Yleiset → Kieli → Suomi**. Muutos tulee voimaan heti ja tallentuu seuraavaa käynnistystä varten. Komento on `app.language.finnish`; ohjauskanava hyväksyy `ui.set {"language":"fi"}` sekä tunnisteet `fi-FI` ja `fi_FI.UTF-8`. Ikkunattomassa ajossa voi käyttää `LIGHTCRAFT_LANGUAGE=fi`. diff --git a/docs/localization-id.md b/docs/localization-id.md index 13fc1c7ee8..328f30fe1a 100644 --- a/docs/localization-id.md +++ b/docs/localization-id.md @@ -1,6 +1,6 @@ # LightCraft in Indonesian -Choose **Edit → Language → Bahasa Indonesia** or **Settings → General → Language**. The choice applies +Choose **Settings → General → Language → Bahasa Indonesia**. The choice applies at once and is saved for the next launch (`language: "id"` in `ui.json`); the control command is `app.language.indonesian`. `LIGHTCRAFT_LANGUAGE` selects it for headless runs and accepts `id`, `id-ID` and `id_ID.UTF-8`; the saved value is always `id`. LightCraft does not follow the system language, for diff --git a/docs/localization-ja.md b/docs/localization-ja.md index 8d40688427..a9f758d6e1 100644 --- a/docs/localization-ja.md +++ b/docs/localization-ja.md @@ -3,7 +3,7 @@ LightCraft は日本語・簡体字中国語・英語(English)の表示に対応しています。 言語設定は `ui.json` の `language` に保存します。 -- 「編集 → 言語」または「設定 → 一般 → 言語」で切り替えます。選択は次回起動にも引き継ぎます。 +- 「設定 → 一般 → 言語」で切り替えます。選択は次回起動にも引き継ぎます。 - メニュー、写真編集、マスク、切り抜き、設定、読み込み、書き出し、主な処理状況を翻訳しています。 - 通常表示と太字の双方に、SIL OFLのBIZ UDPGothicを使います。日本語フォントはこのリポジトリではなく [storytold/craft-fonts](https://github.com/storytold/craft-fonts) にあり、任意のビルド入力 diff --git a/docs/localization-ka.md b/docs/localization-ka.md index 16d878794a..07f231dde9 100644 --- a/docs/localization-ka.md +++ b/docs/localization-ka.md @@ -1,6 +1,6 @@ # LightCraft in Georgian -Choose **Edit → Language → ქართული** or **Settings → General → Language**. The choice applies at once +Choose **Settings → General → Language → ქართული**. The choice applies at once and is saved for the next launch (`language: "ka"` in `ui.json`); the control command is `app.language.georgian`. `LIGHTCRAFT_LANGUAGE` selects it for headless runs and accepts `ka`, `ka-GE` and `ka_GE.UTF-8`; the saved value is always `ka`. LightCraft does not follow the system language, diff --git a/docs/localization-pl.md b/docs/localization-pl.md index 445dbcf639..81a48c9781 100644 --- a/docs/localization-pl.md +++ b/docs/localization-pl.md @@ -1,7 +1,7 @@ # Polski -Język polski (`pl`, English name **Polish**, nazwa natywna **Polski**) włącza się przez **Edytuj → Język → -Polski** albo **Ustawienia → Ogólne → Język**. Zmiana działa od razu i jest zapamiętywana przy kolejnym +Język polski (`pl`, English name **Polish**, nazwa natywna **Polski**) włącza się przez **Ustawienia → Ogólne → Język → +Polski**. Zmiana działa od razu i jest zapamiętywana przy kolejnym uruchomieniu. Polecenie to `app.language.polish`; kanał sterowania przyjmuje `ui.set {"language":"pl"}` oraz znaczniki `pl-PL` i `pl_PL.UTF-8`. Bez okna można ustawić `LIGHTCRAFT_LANGUAGE=pl`. diff --git a/docs/localization-pt-br.md b/docs/localization-pt-br.md index 72d5fcfea0..6baee8d3d0 100644 --- a/docs/localization-pt-br.md +++ b/docs/localization-pt-br.md @@ -3,7 +3,7 @@ O LightCraft pode ser exibido em inglês, chinês simplificado, chinês tradicional (Taiwan), japonês e português do Brasil. A preferência de idioma é gravada em `language` no `ui.json`. -- Troque em **Editar → Idioma** ou em **Configurações → Geral → Idioma**. A escolha é mantida nas +- Troque em **Configurações → Geral → Idioma**. A escolha é mantida nas próximas inicializações. - Traduzimos menus, edição de fotos, máscaras, recorte, configurações, importação, exportação e as principais mensagens de progresso. diff --git a/docs/localization-ru.md b/docs/localization-ru.md index 5ffbeffef5..440bd06233 100644 --- a/docs/localization-ru.md +++ b/docs/localization-ru.md @@ -1,6 +1,6 @@ # LightCraft на русском -Выберите **Правка → Язык → Русский** или **Настройки → Общие → Язык**. Выбор применяется сразу +Выберите **Настройки → Общие → Язык → Русский**. Выбор применяется сразу и сохраняется для следующего запуска (`language: "ru"` в `ui.json`). Русский каталог охватывает меню, сочетания клавиш, библиотеку, обработку, кадрирование, маски, diff --git a/docs/localization-vi.md b/docs/localization-vi.md index 2d8776d8a3..d718a2be2c 100644 --- a/docs/localization-vi.md +++ b/docs/localization-vi.md @@ -1,6 +1,6 @@ # LightCraft bằng tiếng Việt -Chọn **Chỉnh sửa → Ngôn ngữ → Tiếng Việt** hoặc **Cài đặt → Chung → Ngôn ngữ**. +Chọn **Cài đặt → Chung → Ngôn ngữ → Tiếng Việt**. Lựa chọn áp dụng ngay và được lưu cho lần mở sau (`language: "vi"` trong `ui.json`). Các tag locale hệ thống sau cũng chọn tiếng Việt: `vi`, `vi-VN`, `vi_VN`, `vi_VN.UTF-8`. diff --git a/docs/localization-zh-hans.md b/docs/localization-zh-hans.md index bf41dfed57..8944cdbf27 100644 --- a/docs/localization-zh-hans.md +++ b/docs/localization-zh-hans.md @@ -2,13 +2,13 @@ LightCraft 的界面支持英语、简体中文、繁体中文(台湾)和日语。语言设置保存在 `ui.json` 的 `language` 字段中。 -- 通过「编辑 → 语言」或「设置 → 一般 → 语言」切换,选择会保留到下次启动。 +- 通过「设置 → 一般 → 语言」切换,选择会保留到下次启动。 - 已翻译的范围与 `zh-hant.json` 键集完全一致(1246 条),两份目录的键与键序一一对应。 - 正文字重与半粗体都使用 SIL OFL 的 **Noto Sans CJK SC**(简体中文)与 BIZ UDPGothic(日语)。 这些字体不在本仓库,而在 [storytold/craft-fonts](https://github.com/storytold/craft-fonts); 使用可选的构建输入 `CRAFT_FONTS_DIR=../craft-fonts` 时(所有正式发布版)会内嵌进来。 不指定该输入时程序照常构建运行,但中文与日文文字没有字形,会显示为方框 —— - 语言菜单里四种语言仍然都在,选中「简体中文」也只会得到一屏方框。未内嵌字体时构建会打印一条 + 「设置 → 一般 → 语言」里四种语言仍然都在,选中「简体中文」也只会得到一屏方框。未内嵌字体时构建会打印一条 `cargo::warning` 提示这一点。 - 翻译只发生在显示层:命令 ID、照片文件名、用户输入的元数据都不做改动。 - 尚未翻译的技术性错误、补充说明和发行说明仍以英文显示。 diff --git a/docs/localization-zh-hant.md b/docs/localization-zh-hant.md index abf1af6514..858eef8792 100644 --- a/docs/localization-zh-hant.md +++ b/docs/localization-zh-hant.md @@ -1,6 +1,6 @@ # LightCraft 繁體中文(台灣)介面 -從「編輯 → 語言 → 繁體中文(台灣)」切換,或開啟「設定 → 一般 → 語言」選擇。 +從「設定 → 一般 → 語言 → 繁體中文(台灣)」切換。 macOS 的設定也可由「LightCraft → 設定…」或 `⌘,` 開啟。 語言立即生效,並儲存在應用程式設定的 `ui.json`,下次啟動會沿用。 英文、簡體中文、繁體中文與日文可隨時互相切換。 diff --git a/docs/localization.md b/docs/localization.md index 36a28d5447..446d914892 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -39,12 +39,12 @@ are in [`localization-zh-hans.md`](localization-zh-hans.md), [`localization-zh-h ``` The fields are the BCP-47 code (also the settings-file value), the **endonym** shown in the - Language menu, the ISO 15924 script (`Latn`, `Jpan`, `Hans`, `Hant`, `Kore`…), and the embedded + Settings language row, the ISO 15924 script (`Latn`, `Jpan`, `Hans`, `Hant`, `Kore`…), and the embedded catalog. `build.rs` picks up `-formats.json` by name, so the macro and the format lookup follow automatically. Add the corresponding `app.language.` entry to `LANGUAGE_COMMANDS` and `language_from_command` in `src/menus.rs`, and to the - `language_commands_cover_every_language` test. Settings read the locale table; menus and - the control channel share the language-command mapping. + `language_commands_cover_every_language` test. Settings read the locale table; the control + channel uses the language commands (they are in no menu). 3. **Make sure the glyphs exist.** The script drives which craft-fonts faces the UI installs: a language whose script has no face in the build shows boxes (the test says so instead of failing). Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never here; a diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index baa3bb7fe5..84fe76d603 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -482,7 +482,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-TEXTFIELD | Text fields behave alike | P1 | 🟡 | `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/panels/topbar.rs`, `crates/ui-egui/src/widgets.rs`, `crates/ui-egui/src/panels/right.rs` (`meta_field`), `crates/ui-egui/src/dialogs.rs`, `crates/ui-egui/src/panels/unnamed.rs` | one shared field: right-click Cut / Copy / Paste / Select All (no Paste in the browser), Esc gives back the text from before the edit, Return / leaving / Esc reported to the caller, optional select-on-focus; agents use `ui.clipboard` (MCP `clipboard`) and `ui.inspect` → `copied`. Used by Search Photos, slider values, the Info panel's metadata fields (multi-line captions), the one-field dialogs (New / Rename Album, New Smart Album, Rename / Merge Keywords, text prompts) and the unnamed faces' name field so far; the other text fields (most dialogs, import, settings, masking, keywords …) still use egui's own and have no menu | | LR-BEHAV-HEADLESS | Headless UI snapshots | P2 | ✅ | `apps/lightcraft-cli/src/main.rs`, `crates/ui-egui/src/headless.rs`, `docs/control-protocol.md` | `snapshot` rasterizes the UI and defaults photo development to the CPU before the first frame, without adapter discovery; scaled dimensions are validated before allocation, and UI zoom preserves the requested physical viewport; JSON-lines control scripts are supported | | LR-BEHAV-ACCESS | Accessibility | P2 | 🟡 | `crates/ui-egui/src/widgets.rs`, `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/panels/grid.rs`, `crates/ui-egui/tests/it/accessibility.rs` | AccessKit (VoiceOver / Narrator / AT-SPI): sliders announce control, value, range and step and take Increment / Decrement (the value field beside each is named ` value` and describes how to type or drag), buttons / icon buttons / dropdowns / section headers / sources their labels and state, text fields their caption, grid thumbnails file name, rating, flag and label. `tests/it/accessibility.rs` fails on an unnamed control, a slider without range or an untitled dialog in every view, Develop tool and 13 dialogs, and checks that Crop and Remove sliders are reached with Tab and that Tab walks the right panels top to bottom. Canvas tools by keyboard (`crates/ui-egui/src/canvas_keys.rs`, `crates/ui-egui/src/tests/canvas_keys.rs`): crop corners, edges and box, spot targets and sources, a New spot point (Return adds), radial / linear gradient handles and mask pins take the focus, are announced with their position and move with the arrows (Shift: further). Dialogs with one name field (New Album, New Smart Album, Save Metadata Preset, the renames) take the focus once when they open, so Tab and Shift+Tab reach their check box, Cancel and OK, and Return and Esc still confirm and cancel (`crates/ui-egui/src/tests/dialog_tab.rs`). The photo in Detail is named like its grid cell, `Photo: , , ,