From a75757eb311c0b2d2ee5458cf2c4ea5e1e55a065 Mon Sep 17 00:00:00 2001 From: Alex-BB44 <273073052+Alex-BB44@users.noreply.github.com> Date: Sun, 18 Oct 2026 22:52:51 +0200 Subject: [PATCH 1/4] feat(io): open .tx textures (tiled MIP-mapped TIFF) read-only A `.tx` file (OpenImageIO's maketx, used by V-Ray, Arnold, RenderMan) is a tiled TIFF with one directory per MIP level, full resolution first. The TIFF reader already opens it by content; this adds `.tx` to File > Open (desktop and web), the batch extensions and `photocraft-cli batch`, and opens it read-only so Save asks for a new name instead of replacing the texture with a plain TIFF. `.tx` stays out of the TIFF codec's writable extensions, so "Save As x.tx" keeps refusing. The "only the first of N pages" warning is dropped only for a MIP pyramid as maketx writes it: from the page that opens (a leading thumbnail is skipped), every full-resolution main-chain level is tiled, halves the one before (rounded down or up) and the chain ends at 1x1. Anything less conclusive keeps the warning. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft-cli/src/lib.rs | 21 ++++- apps/photocraft-web/src/web.rs | 6 +- apps/photocraft/src/services.rs | 8 +- crates/engine/src/file_cmds.rs | 6 +- crates/io/src/flat.rs | 39 ++++++++ crates/io/src/lib.rs | 10 ++ crates/io/tests/tx_texture.rs | 131 ++++++++++++++++++++++++++ crates/ui-egui/src/file_open/tests.rs | 24 +++++ crates/ui-egui/src/lib.rs | 4 +- 9 files changed, 237 insertions(+), 12 deletions(-) create mode 100644 crates/io/tests/tx_texture.rs diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs index 03001ab02d..bf2c03ab68 100644 --- a/apps/photocraft-cli/src/lib.rs +++ b/apps/photocraft-cli/src/lib.rs @@ -438,7 +438,8 @@ fn same_dir(a: &Path, b: &Path) -> bool { fn is_input(p: &Path) -> bool { let known = |e: &str| { - matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "kra" | "krz" | "af" | "afdesign" | "afphoto" | "afpub") + // `.tx` textures are TIFFs the codecs read but deliberately don't list (they can't write one). + matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "kra" | "krz" | "af" | "afdesign" | "afphoto" | "afpub" | "tx") || photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read) }; p.is_file() && p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase())) @@ -713,6 +714,24 @@ mod batch_action_set_tests { (code, String::from_utf8(output).unwrap(), String::from_utf8(errors).unwrap()) } + /// A folder of `.tx` textures (tiled MIP-mapped TIFFs the codecs read but can't write) is picked + /// up by `batch`, and each one is written in the format asked for. + #[test] + fn batch_picks_up_tx_textures_and_writes_the_chosen_format() { + let dir = std::env::temp_dir().join(format!("photocraft-cli-tx-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = |name: &str| dir.join(name).to_string_lossy().to_string(); + std::fs::create_dir_all(dir.join("in")).unwrap(); + let (code, _, stderr) = invoke(&["run", "--new", r#"{"width":8,"height":6}"#, "--out", &path("in/wall.tif")]); + assert_eq!(code, 0, "{stderr}"); + std::fs::rename(dir.join("in/wall.tif"), dir.join("in/wall.tx")).unwrap(); + std::fs::write(dir.join("steps.json"), r#"["image.adjustments.invert"]"#).unwrap(); + let (code, stdout, stderr) = invoke(&["batch", "--actions", &path("steps.json"), "--in", &path("in"), "--out", &path("out"), "--format", "png"]); + assert_eq!(code, 0, "{stdout}{stderr}"); + assert!(dir.join("out/wall.png").is_file(), "{stdout}{stderr}"); + let _ = std::fs::remove_dir_all(&dir); + } + /// A batched action that plays another action of its set finds it in every file's session; a /// failure inside the called action fails the file, and a self-call stops instead of looping. #[test] diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rs index a248ecbb13..6c88d1a04c 100644 --- a/apps/photocraft-web/src/web.rs +++ b/apps/photocraft-web/src/web.rs @@ -19,9 +19,9 @@ type Inbox = Arc)>>>; /// Everything File › Open reads: PhotoCraft, Photoshop, OpenRaster, Krita and Affinity documents, flat images, and /// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries. const OPEN_EXTS: &[&str] = &[ - "pcraft", "pdn", "ora", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", - "pbm", "pgm", "ppm", "pam", "pfm", "dds", "fits", "fit", "fts", "dpx", "cin", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", - "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af", "afdesign", "afphoto", "afpub", + "pcraft", "pdn", "ora", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "tx", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", + "hdr", "pbm", "pgm", "ppm", "pam", "pfm", "dds", "fits", "fit", "fts", "dpx", "cin", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", + "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af", "afdesign", "afphoto", "afpub", ]; const SVG_EXTS: &[&str] = &["svg", "svgz"]; const CANVAS_ID: &str = "photocraft_canvas"; diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 20de0d6be8..32af055d19 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -20,9 +20,9 @@ mod recovery_tests; /// Photoshop brushes (.abr), gradients (.grd), swatches (.aco, .ase) and keyboard shortcut sets /// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts. const OPEN_EXTS: &[&str] = &[ - "pcraft", "pdn", "ora", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", - "pbm", "pgm", "ppm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "cin", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", - "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub", + "pcraft", "pdn", "ora", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "tx", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", + "hdr", "pbm", "pgm", "ppm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "cin", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", + "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub", ]; const SVG_EXTS: &[&str] = &["svg", "svgz"]; @@ -52,6 +52,8 @@ const OPEN_FILTERS: &[(&str, &[&str])] = &[ ("JPEG", &["jpg", "jpeg"]), ("HEIF", &["heic", "heif", "hif"]), ("TIFF", &["tif", "tiff"]), + // maketx render textures (tiled, MIP-mapped TIFF); they open read-only. + ("TX Texture", &["tx"]), ("WebP", &["webp"]), ("GIF", &["gif"]), ("BMP", &["bmp"]), diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f99aefcff0..9a61285a95 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -119,9 +119,9 @@ pub fn list_images(dir: &str) -> Result> { /// Extensions the batch commands pick up from a folder. #[cfg(not(target_arch = "wasm32"))] const OPENABLE: &[&str] = &[ - "pdn", "ora", "kra", "krz", "psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", "ico", "pnm", - "ppm", "pgm", "fits", "fit", "fts", "dpx", "heic", "heif", "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign", "afphoto", - "afpub", + "pdn", "ora", "kra", "krz", "psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "tx", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", "ico", + "pnm", "ppm", "pgm", "fits", "fit", "fts", "dpx", "heic", "heif", "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign", + "afphoto", "afpub", ]; /// Whether saving `doc` as a TIFF writes Photoshop layer data (anything beyond a lone diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 773e692729..96e004d46b 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -187,6 +187,45 @@ pub fn import_tiff_page(name: &str, bytes: &[u8], page: Option) -> Result None => (codecs::decode_with(bytes, &keep)?, codecs::tiff_orientation(bytes)), Some(p) => (codecs::decode_tiff_page(bytes, p, &keep)?, codecs::tiff_page_orientation(bytes, p)), }; + tiff_to_document(name, img, orientation) +} + +/// A `.tx` texture (written by OpenImageIO's `maketx` for V-Ray, Arnold, RenderMan and others): a +/// tiled TIFF with one directory per MIP level, full resolution first. It opens as that level, +/// read-only: Save can't write the MIP chain and tiling back, so it asks for a new name instead of +/// replacing the texture with a plain TIFF. The smaller levels are derived from the first one, so +/// leaving them out loses nothing and the "more pages" warning is dropped for a MIP chain. +pub(crate) fn import_tx(name: &str, bytes: &[u8]) -> Result { + let keep = codecs::DecodeOptions { keep_orientation: true, ..Default::default() }; + let mut img = codecs::decode_with(bytes, &keep)?; + if codecs::tiff_info(bytes).is_ok_and(|info| is_mip_chain(&info)) { + img.warnings.retain(|w| !matches!(w, codecs::DecodeWarning::MorePages { .. })); + } + let mut r = tiff_to_document(name, img, codecs::tiff_orientation(bytes))?; + r.source_read_only = true; + Ok(r) +} + +/// Whether the page that opens starts a MIP pyramid as `maketx` writes it. From that page (the one +/// [`codecs::TiffInfo::default_page`] picks, so a leading thumbnail is skipped) over the full-resolution +/// main-chain pages the "more pages" warning counts: every level is tiled, each one shrinks the one +/// before by half (rounded down or up, never below 1), and the chain ends at 1×1. Anything less +/// conclusive keeps the warning, so real extra pages are never left out silently. +fn is_mip_chain(info: &codecs::TiffInfo) -> bool { + let Some(start) = info.default_page() else { return false }; + let levels: Vec<_> = + info.pages.iter().skip(start).filter(|p| p.parent.is_none() && p.kind == codecs::TiffPageKind::Page && p.width > 0 && p.height > 0).collect(); + let halves = |big: u32, small: u32| small == (big / 2).max(1) || small == big.div_ceil(2).max(1); + let next_level = + |a: &codecs::TiffPage, b: &codecs::TiffPage| (a.width, a.height) != (b.width, b.height) && halves(a.width, b.width) && halves(a.height, b.height); + levels.len() > 1 + && levels.iter().all(|p| p.tiled) + && levels.last().is_some_and(|p| p.width == 1 && p.height == 1) + && levels.windows(2).all(|l| next_level(l[0], l[1])) +} + +/// A decoded TIFF page as a document: its Photoshop layers when it carries them, else one layer. +fn tiff_to_document(name: &str, img: Image, orientation: u16) -> Result { if let Some(layers) = img.meta.photoshop_layers.as_deref().filter(|l| !l.is_empty()) { let mut r = crate::tiff_layers::import_layered(name, &img, layers)?; if orientation != 1 { diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 3543cd359c..2b6c620298 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -315,6 +315,9 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, m if is_svg_input(name, bytes) { return svg::import_svg_with_group_depth(name, bytes, max_group_depth); } + if is_tx_texture(name, bytes) { + return flat::import_tx(name, bytes); + } flat::import_flat(name, bytes) } @@ -334,6 +337,13 @@ fn extension(name_or_ext: &str) -> String { name_or_ext.rsplit(['.', '/', '\\']).next().unwrap_or(name_or_ext).to_ascii_lowercase() } +/// Whether `name` and `bytes` are a `.tx` render texture (a TIFF named `.tx`), which opens +/// read-only (see [`import`]). For open paths that don't get the importer's +/// [`ImportResult::source_read_only`], such as the app's inline and automation opens. +pub fn is_tx_texture(name: &str, bytes: &[u8]) -> bool { + has_extension(name, "tx") && photocraft_codecs::detect(bytes) == Some(photocraft_codecs::Format::Tiff) +} + fn has_extension(name: &str, expected: &str) -> bool { name.rsplit(['/', '\\']).next().and_then(|name| name.rsplit_once('.')).is_some_and(|(base, ext)| !base.is_empty() && ext.eq_ignore_ascii_case(expected)) } diff --git a/crates/io/tests/tx_texture.rs b/crates/io/tests/tx_texture.rs new file mode 100644 index 0000000000..c1d8e25096 --- /dev/null +++ b/crates/io/tests/tx_texture.rs @@ -0,0 +1,131 @@ +//! `.tx` textures (OpenImageIO's `maketx`, read by V-Ray, Arnold and RenderMan): a tiled TIFF with +//! one directory per MIP level, full resolution first. File › Open shows the first level, read-only +//! (Save asks for a new name, so the texture is never replaced by a plain TIFF), without the +//! "more pages" warning a MIP chain doesn't deserve. Every file here is hand-built by `tiffgen`. + +#[path = "../../codecs/tests/common/tiffgen.rs"] +mod tiffgen; +use tiffgen::*; + +const ORDERS: [(bool, bool); 4] = [(true, false), (false, false), (true, true), (false, true)]; + +/// A tiled RGB 8-bit directory of `w`×`h` filled with `rgb`, in `tile`×`tile` tiles, as `maketx` +/// writes them (no NewSubfileType). +fn level(w: u32, h: u32, rgb: [u8; 3], tile: usize) -> Dir { + let px: Vec = (0..w * h).flat_map(|_| rgb).collect(); + let d = Dir { entries: base(w, h, 8, 3, 2), chunks: tile_split(&px, w as usize, h as usize, 3, 1, tile, tile, false), tiled: true }; + d.tag(322, SHORT, &[tile as u64]).tag(323, SHORT, &[tile as u64]) +} + +/// A `maketx`-style pyramid from `w`×`h` down to 1×1 (sizes rounded down), each level its own colour. +fn pyramid(little: bool, big: bool, w: u32, h: u32) -> Vec { + let mut dirs = Vec::new(); + let (mut lw, mut lh) = (w, h); + loop { + let shade = u8::try_from(dirs.len() * 20).unwrap_or(u8::MAX); + dirs.push(level(lw, lh, [200, 100, shade], 16)); + if lw == 1 && lh == 1 { + break; + } + (lw, lh) = ((lw / 2).max(1), (lh / 2).max(1)); + } + let chain: Vec = (0..dirs.len()).collect(); + build(little, big, &dirs, &chain).bytes +} + +fn first_pixel(doc: &photocraft_doc::Document) -> Vec { + let img = photocraft_io::document_to_image(doc, &mut Vec::new()).unwrap(); + img.data()[..3].to_vec() +} + +#[test] +fn a_tx_opens_its_full_resolution_level_read_only_without_a_pages_warning() { + for (little, big) in ORDERS { + let bytes = pyramid(little, big, 37, 20); + // 37×20, 18×10, 9×5, 4×2, 2×1, 1×1. + assert_eq!(photocraft_codecs::tiff_info(&bytes).unwrap().pages.len(), 6); + let r = photocraft_io::import("wall_diffuse.tx", &bytes).unwrap(); + assert_eq!((r.document.size.width, r.document.size.height), (37, 20), "little {little} big {big}"); + assert_eq!(first_pixel(&r.document), [200, 100, 0], "the full-resolution level, not a smaller one"); + assert!(r.source_read_only, "Save must not write a plain TIFF over the texture"); + assert!(r.warnings.iter().all(|w| !w.contains("page")), "{:?}", r.warnings); + // Upper-case extensions are textures too. + assert!(photocraft_io::import("WALL.TX", &bytes).unwrap().source_read_only); + } +} + +#[test] +fn the_same_file_named_tif_still_opens_as_an_ordinary_tiff() { + let bytes = pyramid(true, false, 16, 16); + let r = photocraft_io::import("pyramid.tif", &bytes).unwrap(); + assert_eq!((r.document.size.width, r.document.size.height), (16, 16)); + assert!(!r.source_read_only); + assert!(r.warnings.iter().any(|w| w == "only the first of 5 pages was imported"), "{:?}", r.warnings); +} + +#[test] +fn a_tx_whose_pages_are_not_a_mip_chain_keeps_the_pages_warning() { + // Two full-size pages: the second one is real content, so leaving it out is worth a warning. + let dirs = [level(16, 16, [10, 20, 30], 16), level(16, 16, [40, 50, 60], 16)]; + let bytes = build(true, false, &dirs, &[0, 1]).bytes; + let r = photocraft_io::import("pages.tx", &bytes).unwrap(); + assert!(r.source_read_only); + assert!(r.warnings.iter().any(|w| w == "only the first of 2 pages was imported"), "{:?}", r.warnings); +} + +#[test] +fn a_thumbnail_in_front_of_the_pyramid_is_skipped() { + // NewSubfileType 1 marks a reduced copy: the full-resolution level after it opens, and the + // pyramid that follows still counts as one. + let mut dirs = vec![level(4, 4, [9, 9, 9], 16).tag(254, LONG, &[1])]; + for (s, shade) in [(8, 0), (4, 20), (2, 40), (1, 60)] { + dirs.push(level(s, s, [200, 100, shade], 16)); + } + let bytes = build(true, false, &dirs, &[0, 1, 2, 3, 4]).bytes; + let r = photocraft_io::import("thumb.tx", &bytes).unwrap(); + assert_eq!((r.document.size.width, r.document.size.height), (8, 8)); + assert_eq!(first_pixel(&r.document), [200, 100, 0]); + assert!(r.warnings.iter().all(|w| !w.contains("page")), "{:?}", r.warnings); +} + +#[test] +fn halving_pages_that_are_not_a_full_tiled_pyramid_keep_the_pages_warning() { + let pages_warning = |r: &photocraft_io::ImportResult| r.warnings.iter().any(|w| w.starts_with("only the first of")); + // Halving sizes, but stored in strips: an ordinary multi-page TIFF. + let strips_only: Vec = [(8u32, 1u8), (4, 2), (2, 3), (1, 4)].iter().map(|&(s, v)| strips(s, s, 8, 1, 1, s, &vec![v; (s * s) as usize])).collect(); + // Tiled and halving, but stopping before 1×1. + let short: Vec = [16u32, 8, 4].iter().map(|&s| level(s, s, [1, 2, 3], 16)).collect(); + // Down to 1×1, then another 1×1 page with other content. + let repeated: Vec = [(4u32, 0u8), (2, 1), (1, 2), (1, 3)].iter().map(|&(s, v)| level(s, s, [v, v, v], 16)).collect(); + for (what, dirs) in [("strips", strips_only), ("short", short), ("repeated 1×1", repeated)] { + let chain: Vec = (0..dirs.len()).collect(); + let r = photocraft_io::import("pages.tx", &build(true, false, &dirs, &chain).bytes).unwrap(); + assert!(r.source_read_only, "{what}"); + assert!(pages_warning(&r), "{what}: {:?}", r.warnings); + } +} + +#[test] +fn a_single_level_tx_opens_read_only() { + let bytes = build(false, false, &[level(8, 8, [1, 2, 3], 16)], &[0]).bytes; + let r = photocraft_io::import("flat.tx", &bytes).unwrap(); + assert_eq!(first_pixel(&r.document), [1, 2, 3]); + assert!(r.source_read_only && r.warnings.is_empty(), "{:?}", r.warnings); +} + +#[test] +fn a_tx_that_is_not_a_tiff_is_left_to_the_other_readers() { + // Only a TIFF signature makes a `.tx` a texture; anything else goes the usual way. + use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let img = Image::new(2, 2, ChannelLayout::Rgb, SampleType::U8).unwrap(); + let png = photocraft_codecs::encode(&img, Format::Png, &EncodeOptions::default()).unwrap(); + let r = photocraft_io::import("not_a_texture.tx", &png).unwrap(); + assert!(!r.source_read_only); +} + +#[test] +fn saving_as_tx_is_refused_rather_than_writing_a_plain_tiff() { + let bytes = pyramid(true, false, 8, 8); + let doc = photocraft_io::import("t.tx", &bytes).unwrap().document; + assert!(photocraft_io::export(&doc, "t.tx", &photocraft_io::ExportOptions::default()).is_err()); +} diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 00db3ef96e..687e0a3ad5 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -80,6 +80,30 @@ fn open_file_sets_name_path_and_recent() { assert!(app.ui.notices.is_empty()); } +/// A `.tx` render texture opens read-only on the inline and automation paths too (the +/// background open gets it from the importer): Save asks for a new file instead of writing a +/// plain TIFF over the texture. +#[test] +fn tx_texture_does_not_acquire_its_path() { + let tiff = b"II*\x00\x08\x00\x00\x00"; + for automation in [false, true] { + let (mut app, _written) = app_with(vec![None]); + if automation { + app.open_automation_bytes("wall.tx", tiff).unwrap(); + } else { + app.open_file("/tex/wall.tx", tiff).unwrap(); + } + let st = app.session.active().unwrap(); + assert!(st.source_read_only, "automation: {automation}"); + assert!(st.path.is_none(), "automation: {automation}"); + assert_eq!(menus::invoke(&mut app, &egui::Context::default(), "file.save", json!({})).unwrap(), json!({"fileDialog": "save"})); + } + // The same bytes under a TIFF name keep their path, as before. + let (mut app, _written) = app_with(vec![None]); + app.open_file("/tex/wall.tif", tiff).unwrap(); + assert!(!app.session.active().unwrap().source_read_only); +} + #[test] fn affinity_preview_does_not_acquire_the_source_path_even_when_renamed() { for automation in [false, true] { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f97c6968fc..cd3e3246aa 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1378,7 +1378,7 @@ impl PhotocraftApp { self, open_prompt::Held { doc, - read_only: photocraft_io::affinity::is_affinity(bytes), + read_only: photocraft_io::affinity::is_affinity(bytes) || photocraft_io::is_tx_texture(name, bytes), name: name.to_string(), path: path.map(str::to_string), warnings: warnings.clone(), @@ -1419,7 +1419,7 @@ impl PhotocraftApp { // The caller records the path it read from. self.session.add_document(doc, None); if let Some(st) = self.session.active_mut() { - st.source_read_only = photocraft_io::affinity::is_affinity(bytes); + st.source_read_only = photocraft_io::affinity::is_affinity(bytes) || photocraft_io::is_tx_texture(name, bytes); } self.sync_views(); self.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]); From a43c2474603f92a303dc8e2d4681fd9cecc6756a Mon Sep 17 00:00:00 2001 From: Alex-BB44 <273073052+Alex-BB44@users.noreply.github.com> Date: Mon, 19 Oct 2026 08:23:35 +0200 Subject: [PATCH 2/4] fix(io): a .tx keeps the pages warning unless every counted page is a MIP level TiffInfo::page_count counts every main-chain page, including one without a size, but is_mip_chain left such pages out before checking the chain. A valid pyramid plus an empty directory (after it or in front of it) lost the "only the first of N pages" warning. Every page the warning counts must now be a level of the chain. Test: a_page_without_a_size_beside_the_pyramid_keeps_the_pages_warning (fails without the fix). Reported by the CodeRabbit review. --- crates/io/src/flat.rs | 16 ++++++++++++---- crates/io/tests/tx_texture.rs | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 96e004d46b..550616e71a 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -209,12 +209,20 @@ pub(crate) fn import_tx(name: &str, bytes: &[u8]) -> Result bool { let Some(start) = info.default_page() else { return false }; - let levels: Vec<_> = - info.pages.iter().skip(start).filter(|p| p.parent.is_none() && p.kind == codecs::TiffPageKind::Page && p.width > 0 && p.height > 0).collect(); + let counted = |p: &codecs::TiffPage| p.parent.is_none() && p.kind == codecs::TiffPageKind::Page; + if info.pages.iter().take(start).any(counted) { + return false; + } + let levels: Vec<_> = info.pages.iter().skip(start).filter(|p| counted(p)).collect(); + if levels.len() != info.page_count() || levels.iter().any(|p| p.width == 0 || p.height == 0) { + return false; + } let halves = |big: u32, small: u32| small == (big / 2).max(1) || small == big.div_ceil(2).max(1); let next_level = |a: &codecs::TiffPage, b: &codecs::TiffPage| (a.width, a.height) != (b.width, b.height) && halves(a.width, b.width) && halves(a.height, b.height); diff --git a/crates/io/tests/tx_texture.rs b/crates/io/tests/tx_texture.rs index c1d8e25096..12d94f7424 100644 --- a/crates/io/tests/tx_texture.rs +++ b/crates/io/tests/tx_texture.rs @@ -105,6 +105,24 @@ fn halving_pages_that_are_not_a_full_tiled_pyramid_keep_the_pages_warning() { } } +/// Every page the warning counts must be a level of the chain: a directory without a size, after +/// the pyramid or in front of it, is still a page the import leaves out. +#[test] +fn a_page_without_a_size_beside_the_pyramid_keeps_the_pages_warning() { + let empty = || Dir { entries: base(0, 0, 8, 3, 2), chunks: Vec::new(), tiled: true }.tag(322, SHORT, &[16]).tag(323, SHORT, &[16]); + let pyramid_dirs = || [(8u32, 0u8), (4, 20), (2, 40), (1, 60)].map(|(s, v)| level(s, s, [200, 100, v], 16)).to_vec(); + let mut after = pyramid_dirs(); + after.push(empty()); + let mut before = vec![empty()]; + before.extend(pyramid_dirs()); + for (what, dirs) in [("after", after), ("before", before)] { + let chain: Vec = (0..dirs.len()).collect(); + let r = photocraft_io::import("pages.tx", &build(true, false, &dirs, &chain).bytes).unwrap(); + assert_eq!((r.document.size.width, r.document.size.height), (8, 8), "{what}"); + assert!(r.warnings.iter().any(|w| w.starts_with("only the first of")), "{what}: {:?}", r.warnings); + } +} + #[test] fn a_single_level_tx_opens_read_only() { let bytes = build(false, false, &[level(8, 8, [1, 2, 3], 16)], &[0]).bytes; From 41d5572c3646e359e768b3c385017f800e207044 Mon Sep 17 00:00:00 2001 From: Alex-BB44 <273073052+Alex-BB44@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:48:12 +0100 Subject: [PATCH 3/4] fix(io): keep the pages warning for an incomplete walk; batch saves .tx as PSD (review) A MIP chain whose directory walk stopped early (a loop or a damaged directory) no longer drops the "more pages" warning. Batch "same format" saves .tx inputs as PSD like other read-only formats, so a batch without --format no longer fails on every texture. --- apps/photocraft-cli/src/batch.rs | 4 ++++ crates/engine/src/cmd/file_cmds/batch_run.rs | 8 +++++--- crates/io/src/flat.rs | 4 ++++ crates/io/tests/it/tx_texture.rs | 15 +++++++++++++++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/apps/photocraft-cli/src/batch.rs b/apps/photocraft-cli/src/batch.rs index d2fed3ae69..0a9a679d05 100644 --- a/apps/photocraft-cli/src/batch.rs +++ b/apps/photocraft-cli/src/batch.rs @@ -212,6 +212,10 @@ mod batch_action_set_tests { invoke(&["batch", "--actions", &path("steps.json"), "--in", &path("in"), "--out", &path("out"), "--format", "png"]); assert_eq!(code, 0, "{stdout}{stderr}"); assert!(dir.join("out/wall.png").is_file(), "{stdout}{stderr}"); + // Without `--format` a texture is saved as PSD, as other formats PhotoCraft only reads. + let Invoke { code, stdout, stderr } = invoke(&["batch", "--actions", &path("steps.json"), "--in", &path("in"), "--out", &path("same")]); + assert_eq!(code, 0, "{stdout}{stderr}"); + assert!(dir.join("same/wall.psd").is_file(), "{stdout}{stderr}"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 1a981298c0..6582817327 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -146,8 +146,10 @@ pub(crate) fn process_tree( /// The format Batch's "Save in the same format" writes for `path`: its own, or PSD for a file /// PhotoCraft only opens. pub fn same_format(path: &str) -> String { - const IMPORT_ONLY: &[&str] = - &["pdn", "kra", "krz", "af", "afdesign", "afphoto", "afpub", "heic", "heif", "hif", "svg", "svgz", "cin", "pcx", "xpm", "xcf", "xcfgz", "gz", "psdt"]; + const IMPORT_ONLY: &[&str] = &[ + "pdn", "kra", "krz", "af", "afdesign", "afphoto", "afpub", "heic", "heif", "hif", "svg", "svgz", "cin", "pcx", "xpm", "xcf", "xcfgz", "gz", "psdt", + "tx", + ]; let ext = extension(path).unwrap_or_else(|| "png".into()); let no_writer = photocraft_codecs::from_extension(&ext).is_some_and(|f| !f.caps().write); if photocraft_io::raw::EXTENSIONS.contains(&ext.as_str()) || IMPORT_ONLY.contains(&ext.as_str()) || no_writer { "psd".into() } else { ext } @@ -163,7 +165,7 @@ fn same_format_takes_the_file_names_extension() { assert_eq!(same_format("/in/logo.svg"), "psd"); assert_eq!(same_format("/in/scan.cin"), "psd"); // Formats PhotoCraft opens and does not write are saved as PSD. - for name in ["/in/scan.dcm", "/in/scan.DICOM", "/in/scan.dc3", "/in/page.xcf", "/in/page.xcf.gz", "/in/page.xcfgz", "/in/card.psdt"] { + for name in ["/in/scan.dcm", "/in/scan.DICOM", "/in/scan.dc3", "/in/page.xcf", "/in/page.xcf.gz", "/in/page.xcfgz", "/in/card.psdt", "/in/wall.tx"] { assert_eq!(same_format(name), "psd", "{name}"); } for f in photocraft_codecs::Format::ALL.into_iter().filter(|f| f.caps().read && !f.caps().write) { diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 818045e081..ee48bb1bfd 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -431,6 +431,10 @@ pub(crate) fn import_tx(name: &str, bytes: &[u8], opts: &crate::ImportOptions, c /// page that opens, none without a size. Anything less conclusive keeps the warning, so real extra /// pages are never left out silently. fn is_mip_chain(info: &codecs::TiffInfo) -> bool { + // A walk that stopped early (a loop or a damaged directory) hides what came after it. + if !info.complete { + return false; + } let Some(start) = info.default_page() else { return false }; let counted = |p: &codecs::TiffPage| p.parent.is_none() && p.kind == codecs::TiffPageKind::Page; if info.pages.iter().take(start).any(counted) { diff --git a/crates/io/tests/it/tx_texture.rs b/crates/io/tests/it/tx_texture.rs index c699a797ce..928774f459 100644 --- a/crates/io/tests/it/tx_texture.rs +++ b/crates/io/tests/it/tx_texture.rs @@ -73,6 +73,21 @@ fn a_tx_whose_pages_are_not_a_mip_chain_keeps_the_pages_warning() { assert!(r.warnings.iter().any(|w| w == "only the first of 2 pages was imported"), "{:?}", r.warnings); } +#[test] +fn a_mip_chain_whose_directory_walk_stops_early_keeps_the_pages_warning() { + // A full 4×4 → 1×1 pyramid whose last directory points back to the first: the walk stops at + // the loop, so whatever came after it is unknown and the warning has to stay. + let dirs = [level(4, 4, [200, 100, 0], 16), level(2, 2, [200, 100, 20], 16), level(1, 1, [200, 100, 40], 16)]; + let built = build(true, false, &dirs, &[0, 1, 2]); + let mut bytes = built.bytes; + let at = usize::try_from(built.next_at[2]).unwrap(); + bytes[at..at + 4].copy_from_slice(&u32::try_from(built.ifd_at[0]).unwrap().to_le_bytes()); + assert!(!photocraft_codecs::tiff_info(&bytes).unwrap().complete); + let r = photocraft_io::import("loop.tx", &bytes).unwrap(); + assert!(r.source_read_only); + assert!(r.warnings.iter().any(|w| w.starts_with("only the first")), "{:?}", r.warnings); +} + #[test] fn a_thumbnail_in_front_of_the_pyramid_is_skipped() { // NewSubfileType 1 marks a reduced copy: the full-resolution level after it opens, and the From 0a0b6675ba3bd95f664645ef74a386b9819b15d2 Mon Sep 17 00:00:00 2001 From: Alex-BB44 <273073052+Alex-BB44@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:13:55 +0100 Subject: [PATCH 4/4] test: follow main's moved test helpers in the .tx tests The io tests included crates/codecs/tests/it/common/tiffgen.rs by path. The codecs moved to craft-libs, so that file is gone; keep the part these tests use next to them. The file-open test's scripted picker now answers with Picked::Cancelled instead of None. --- crates/io/tests/it/tx_texture.rs | 3 +- crates/io/tests/it/tx_texture/tiffgen.rs | 187 +++++++++++++++++++++++ crates/ui-egui/src/file_open/tests.rs | 4 +- 3 files changed, 190 insertions(+), 4 deletions(-) create mode 100644 crates/io/tests/it/tx_texture/tiffgen.rs diff --git a/crates/io/tests/it/tx_texture.rs b/crates/io/tests/it/tx_texture.rs index 928774f459..d4b9b27e89 100644 --- a/crates/io/tests/it/tx_texture.rs +++ b/crates/io/tests/it/tx_texture.rs @@ -3,7 +3,6 @@ //! (Save asks for a new name, so the texture is never replaced by a plain TIFF), without the //! "more pages" warning a MIP chain doesn't deserve. Every file here is hand-built by `tiffgen`. -#[path = "../../../codecs/tests/it/common/tiffgen.rs"] mod tiffgen; use tiffgen::*; @@ -13,7 +12,7 @@ const ORDERS: [(bool, bool); 4] = [(true, false), (false, false), (true, true), /// writes them (no NewSubfileType). fn level(w: u32, h: u32, rgb: [u8; 3], tile: usize) -> Dir { let px: Vec = (0..w * h).flat_map(|_| rgb).collect(); - let d = Dir { entries: base(w, h, 8, 3, 2), chunks: tile_split(&px, w as usize, h as usize, 3, 1, tile, tile, false), tiled: true }; + let d = Dir { entries: base(w, h, 8, 3, 2), chunks: tile_split(&px, w as usize, h as usize, 3, 1, tile, tile), tiled: true }; d.tag(322, SHORT, &[tile as u64]).tag(323, SHORT, &[tile as u64]) } diff --git a/crates/io/tests/it/tx_texture/tiffgen.rs b/crates/io/tests/it/tx_texture/tiffgen.rs new file mode 100644 index 0000000000..9ecabf3c6b --- /dev/null +++ b/crates/io/tests/it/tx_texture/tiffgen.rs @@ -0,0 +1,187 @@ +//! A tiny hand-rolled TIFF / BigTIFF writer for the `.tx` tests: either byte order, strips or +//! tiles, several directories in one IFD chain. Trimmed from the writer that lived in +//! `crates/codecs/tests/it/common/tiffgen.rs` before the codecs moved to craft-libs. + +/// TIFF field types used by the tests. +pub const SHORT: u16 = 3; +pub const LONG: u16 = 4; +const LONG8: u16 = 16; + +fn type_size(ty: u16) -> usize { + match ty { + SHORT => 2, + LONG => 4, + _ => 8, + } +} + +#[derive(Clone, Debug, Default)] +pub struct Dir { + /// `(tag, type, values)`; strip / tile offsets and byte counts are added from `chunks`. + pub entries: Vec<(u16, u16, Vec)>, + /// Pixel data, one blob per strip or tile. + pub chunks: Vec>, + /// Tiles (322/323 must be in `entries`) instead of strips. + pub tiled: bool, +} + +impl Dir { + pub fn tag(mut self, tag: u16, ty: u16, values: &[u64]) -> Self { + self.entries.push((tag, ty, values.to_vec())); + self + } +} + +/// A basic directory: `w`×`h`, `spp` samples of `bits` bits, the given photometric, chunky, +/// uncompressed, one strip per `rows` rows holding `data` (already in file byte order). +pub fn strips(w: u32, h: u32, bits: u16, spp: u16, photometric: u16, rows: u32, data: &[u8]) -> Dir { + let row = (w as usize * bits as usize * spp as usize).div_ceil(8); + let chunks = data.chunks((row * rows as usize).max(1)).map(<[u8]>::to_vec).collect(); + Dir { entries: base(w, h, bits, spp, photometric), chunks, tiled: false }.tag(278, LONG, &[u64::from(rows)]) +} + +pub fn base(w: u32, h: u32, bits: u16, spp: u16, photometric: u16) -> Vec<(u16, u16, Vec)> { + vec![ + (256, LONG, vec![u64::from(w)]), + (257, LONG, vec![u64::from(h)]), + (258, SHORT, vec![u64::from(bits); spp as usize]), + (259, SHORT, vec![1]), + (262, SHORT, vec![u64::from(photometric)]), + (277, SHORT, vec![u64::from(spp)]), + ] +} + +/// Where things ended up in a built file. +pub struct Built { + pub bytes: Vec, + /// Offset of each directory (`dirs` order). + pub ifd_at: Vec, + /// Offset of each directory's next-IFD pointer field. + pub next_at: Vec, +} + +/// Builds a file whose IFD chain lists `dirs` in the order of `chain`. +pub fn build(little: bool, big: bool, dirs: &[Dir], chain: &[usize]) -> Built { + let e16 = |v: u16| if little { v.to_le_bytes().to_vec() } else { v.to_be_bytes().to_vec() }; + let e32 = |v: u32| if little { v.to_le_bytes().to_vec() } else { v.to_be_bytes().to_vec() }; + let e64 = |v: u64| if little { v.to_le_bytes().to_vec() } else { v.to_be_bytes().to_vec() }; + let enc = |ty: u16, v: u64| -> Vec { + match type_size(ty) { + 2 => e16(v as u16), + 4 => e32(v as u32), + _ => e64(v), + } + }; + let header = if big { 16 } else { 8 }; + let entry_len = if big { 20 } else { 12 }; + let inline = if big { 8 } else { 4 }; + let off_ty = if big { LONG8 } else { LONG }; + + // Complete entry lists (with chunk offsets / byte counts), sorted by tag. + let mut full: Vec)>> = Vec::new(); + for d in dirs { + let mut e = d.entries.clone(); + let (ot, ct) = if d.tiled { (324, 325) } else { (273, 279) }; + e.retain(|x| x.0 != ot && x.0 != ct); + e.push((ot, off_ty, vec![0; d.chunks.len()])); + e.push((ct, off_ty, d.chunks.iter().map(|c| c.len() as u64).collect())); + e.sort_by_key(|x| x.0); + full.push(e); + } + + // Pass 1: positions. Layout: header, then per directory its chunks, its out-of-line values + // and its table. + let mut pos = header as u64; + let mut ifd_at = Vec::new(); + let mut chunk_at = Vec::new(); + for (d, e) in dirs.iter().zip(&full) { + let mut ca = Vec::new(); + for c in &d.chunks { + ca.push(pos); + pos += c.len() as u64; + } + chunk_at.push(ca); + for (_, ty, vals) in e { + let n = type_size(*ty) * vals.len(); + if n > inline { + pos += n as u64; + } + } + pos += pos % 2; // word alignment + ifd_at.push(pos); + pos += (if big { 8 } else { 2 }) + (e.len() * entry_len) as u64 + if big { 8 } else { 4 }; + } + + // Pass 2: bytes. + let mut f = Vec::new(); + f.extend_from_slice(if little { b"II" } else { b"MM" }); + let first = chain.first().map_or(0, |&i| ifd_at[i]); + if big { + f.extend(e16(43)); + f.extend(e16(8)); + f.extend(e16(0)); + f.extend(e64(first)); + } else { + f.extend(e16(42)); + f.extend(e32(first as u32)); + } + let mut next_at = vec![0; dirs.len()]; + for (k, (d, e)) in dirs.iter().zip(&full).enumerate() { + for c in &d.chunks { + f.extend_from_slice(c); + } + let ot = if d.tiled { 324 } else { 273 }; + let mut table = Vec::new(); + table.extend(if big { e64(e.len() as u64) } else { e16(e.len() as u16) }); + for (tag, ty, vals) in e { + let mut data = Vec::new(); + for (i, &v) in vals.iter().enumerate() { + data.extend(enc(*ty, if *tag == ot { chunk_at[k][i] } else { v })); + } + table.extend(e16(*tag)); + table.extend(e16(*ty)); + table.extend(if big { e64(vals.len() as u64) } else { e32(vals.len() as u32) }); + if data.len() <= inline { + data.resize(inline, 0); + table.extend(data); + } else { + let at = f.len() as u64; + f.extend(data); + table.extend(if big { e64(at) } else { e32(at as u32) }); + } + } + if f.len() % 2 == 1 { + f.push(0); + } + assert_eq!(f.len() as u64, ifd_at[k]); + let next = chain.iter().position(|&c| c == k).and_then(|p| chain.get(p + 1)).map_or(0, |&n| ifd_at[n]); + f.extend(table); + next_at[k] = f.len() as u64; + f.extend(if big { e64(next) } else { e32(next as u32) }); + } + Built { bytes: f, ifd_at, next_at } +} + +/// Splits an interleaved `w`×`h` image of `spp` samples (`bps` bytes each) into chunky tiles of +/// `tw`×`th` (one blob per tile), padded with zeros. +pub fn tile_split(px: &[u8], w: usize, h: usize, spp: usize, bps: usize, tw: usize, th: usize) -> Vec> { + let mut out = Vec::new(); + for ty in 0..h.div_ceil(th) { + for tx in 0..w.div_ceil(tw) { + let mut t = vec![0u8; tw * th * spp * bps]; + for y in 0..th { + for x in 0..tw { + let (ix, iy) = (tx * tw + x, ty * th + y); + if ix >= w || iy >= h { + continue; + } + let src = (iy * w + ix) * spp * bps; + let dst = (y * tw + x) * spp * bps; + t[dst..dst + spp * bps].copy_from_slice(&px[src..src + spp * bps]); + } + } + out.push(t); + } + } + out +} diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 6f33d39160..40ca128cd4 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -102,7 +102,7 @@ fn tx_texture_does_not_acquire_its_path() { let img = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Gray, vec![40; 4]).unwrap(); let tiff = photocraft_codecs::encode(&img, photocraft_codecs::Format::Tiff, &Default::default()).unwrap(); for automation in [false, true] { - let (mut app, _written) = app_with(vec![None]); + let (mut app, _written) = app_with(vec![Picked::Cancelled]); if automation { app.open_automation_bytes("wall.tx", &tiff).unwrap(); } else { @@ -114,7 +114,7 @@ fn tx_texture_does_not_acquire_its_path() { assert_eq!(menus::invoke(&mut app, &egui::Context::default(), "file.save", json!({})).unwrap(), json!({"fileDialog": "save"})); } // The same bytes under a TIFF name keep their path, as before. - let (mut app, _written) = app_with(vec![None]); + let (mut app, _written) = app_with(vec![Picked::Cancelled]); app.open_file("/tex/wall.tif", &tiff).unwrap(); assert!(!app.session.active().unwrap().source_read_only); }