mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 14:51:31 -05:00
Merge pull request #7567 from Alex-BB44/pr/tx-open
feat(io): open .tx textures (tiled MIP-mapped TIFF) read-only
This commit is contained in:
@@ -22,7 +22,8 @@ fn same_dir(a: &Path, b: &Path) -> bool {
|
||||
|
||||
pub(crate) fn is_input(p: &Path) -> bool {
|
||||
let known = |e: &str| {
|
||||
matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "kra" | "krz" | "af" | "afdesign" | "afphoto" | "afpub" | "xcf" | "xcfgz")
|
||||
// `.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" | "xcf" | "xcfgz" | "tx")
|
||||
|| photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read)
|
||||
};
|
||||
// Only GIMP's compound suffix is an image; an arbitrary .gz is not a batch input.
|
||||
@@ -221,6 +222,29 @@ mod batch_action_set_tests {
|
||||
use crate::test_support::{Invoke, invoke};
|
||||
use serde_json::Value;
|
||||
|
||||
/// 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 Invoke { 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 Invoke { 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}");
|
||||
// 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);
|
||||
}
|
||||
|
||||
/// 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]
|
||||
|
||||
@@ -22,9 +22,9 @@ type PlaceInbox = photocraft_ui_egui::PlaceInbox;
|
||||
/// Everything File › Open reads: PhotoCraft, Photoshop, OpenRaster, Krita and Affinity documents, flat images, and
|
||||
/// Photoshop brushes (.abr), gradients (.grd), layer styles (.asl) and swatches (.aco, .act, .ase), which go to the preset libraries.
|
||||
const OPEN_EXTS: &[&str] = &[
|
||||
"pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "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", "dcm", "dicom", "dc3", "iff", "lbm", "ilbm", "heic",
|
||||
"heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg", "svgz", "aco", "act", "ase", "af",
|
||||
"pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "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", "dcm", "dicom", "dc3", "iff", "lbm", "ilbm",
|
||||
"heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg", "svgz", "aco", "act", "ase", "af",
|
||||
"afdesign", "afphoto", "afpub",
|
||||
];
|
||||
const SVG_EXTS: &[&str] = &["svg", "svgz"];
|
||||
|
||||
@@ -211,8 +211,10 @@ pub(super) 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_formats::from_extension(&ext).is_some_and(|f| f.capabilities().write != photocraft_formats::Availability::Available);
|
||||
if photocraft_io::raw::EXTENSIONS.contains(&ext.as_str()) || IMPORT_ONLY.contains(&ext.as_str()) || no_writer { "psd".into() } else { ext }
|
||||
@@ -228,7 +230,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_formats::Format::ALL.into_iter().filter(|f| {
|
||||
|
||||
@@ -102,11 +102,12 @@ pub(crate) fn openable_name(path: &str) -> bool {
|
||||
/// raws whose usual files `photocraft_raw::decode` develops. Not CR3, ORF, RAF, RW2, SRF or SR2:
|
||||
/// CR3, compressed ORF and RAF and RW2 raw formats other than 3, 4 and 5 aren't decoded yet, and
|
||||
/// import falls back to the embedded JPEG preview with only a warning, which a batch must not
|
||||
/// process silently.
|
||||
/// process silently. Also `.tx` render textures: they open as the TIFF they are, but `tx` isn't a
|
||||
/// TIFF extension, so a save under that name isn't a plain TIFF without its MIP levels.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const OPENABLE: &[&str] = &[
|
||||
"pdn", "ora", "xcf", "xcfgz", "kra", "krz", "psd", "psb", "psdt", "pcraft", "svg", "svgz", "af", "afdesign", "afphoto", "afpub", "dng", "cr2", "nef",
|
||||
"nrw", "arw", "pef",
|
||||
"nrw", "arw", "pef", "tx",
|
||||
];
|
||||
|
||||
pub(crate) fn file_name(path: &str) -> String {
|
||||
|
||||
@@ -766,6 +766,53 @@ fn import_tiff_with_extras(
|
||||
image_to_document(name, &img.oriented(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], opts: &crate::ImportOptions, ctl: &photocraft_raster::Interrupt) -> Result<ImportResult, IoError> {
|
||||
let mut r = import_tiff_page_with_options(name, bytes, None, opts, ctl)?;
|
||||
if let Some(info) = codecs::tiff_info(bytes).ok().filter(is_mip_chain) {
|
||||
// The warning as the decoder words it, with or without the page count.
|
||||
let more = |total| codecs::DecodeWarning::MorePages { total }.to_string();
|
||||
let (counted, unknown) = (more(u32::try_from(info.page_count()).ok()), more(None));
|
||||
r.warnings.retain(|w| *w != counted && *w != unknown);
|
||||
}
|
||||
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. Every page the
|
||||
/// warning counts ([`codecs::TiffInfo::page_count`]) must be one of those levels: none before the
|
||||
/// 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) {
|
||||
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);
|
||||
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]))
|
||||
}
|
||||
|
||||
/// Whether the TIFF page that opens (`page`, else the default one) is bilevel: one 1-bit sample
|
||||
/// per pixel, black-and-white (PhotometricInterpretation 0 or 1).
|
||||
fn tiff_is_bilevel(bytes: &[u8], page: Option<usize>) -> bool {
|
||||
|
||||
@@ -1079,6 +1079,8 @@ fn import_stages(
|
||||
}
|
||||
}
|
||||
Route::Svg => svg::import_svg_with_group_depth(name, bytes, opts.max_group_depth),
|
||||
// A `.tx` texture opens as its first MIP level, read-only.
|
||||
Route::Flat if is_tx_texture(name, bytes) => flat::import_tx(name, bytes, opts, ctl),
|
||||
Route::Flat => flat::import_flat_with_options(name, bytes, opts, ctl),
|
||||
}
|
||||
}
|
||||
@@ -1094,6 +1096,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))
|
||||
}
|
||||
|
||||
@@ -91,6 +91,7 @@ mod tiff_layers;
|
||||
mod tiff_pages;
|
||||
mod tiff_save_options;
|
||||
mod tiff_type_geometry;
|
||||
mod tx_texture;
|
||||
mod vector;
|
||||
mod xcf;
|
||||
mod xmp_export;
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
//! `.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`.
|
||||
|
||||
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<u8> = (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), 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<u8> {
|
||||
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<usize> = (0..dirs.len()).collect();
|
||||
build(little, big, &dirs, &chain).bytes
|
||||
}
|
||||
|
||||
fn first_pixel(doc: &photocraft_doc::Document) -> Vec<u8> {
|
||||
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_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
|
||||
// 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<Dir> = [(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<Dir> = [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<Dir> = [(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<usize> = (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);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<usize> = (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;
|
||||
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());
|
||||
}
|
||||
@@ -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<u64>)>,
|
||||
/// Pixel data, one blob per strip or tile.
|
||||
pub chunks: Vec<Vec<u8>>,
|
||||
/// 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<u64>)> {
|
||||
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<u8>,
|
||||
/// Offset of each directory (`dirs` order).
|
||||
pub ifd_at: Vec<u64>,
|
||||
/// Offset of each directory's next-IFD pointer field.
|
||||
pub next_at: Vec<u64>,
|
||||
}
|
||||
|
||||
/// 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<u8> {
|
||||
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<(u16, u16, Vec<u64>)>> = 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<Vec<u8>> {
|
||||
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
|
||||
}
|
||||
@@ -141,7 +141,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),
|
||||
damage_pending: damaged,
|
||||
name: name.to_string(),
|
||||
path: path.map(str::to_string),
|
||||
@@ -192,7 +192,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)]);
|
||||
|
||||
@@ -10,10 +10,10 @@ use photocraft_color::{ColorMode, SampleType};
|
||||
/// Photoshop brushes (.abr), gradients (.grd), layer styles (.asl), swatches (.aco, .act, .ase) and keyboard shortcut sets
|
||||
/// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts.
|
||||
pub(super) const OPEN_EXTS: &[&str] = &[
|
||||
"pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "dib", "tga",
|
||||
"ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pnm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "cin", "dcm", "dicom", "dc3",
|
||||
"iff", "lbm", "ilbm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg", "svgz",
|
||||
"aco", "act", "ase", "kys", "af", "afdesign", "afphoto", "afpub",
|
||||
"pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "tx", "webp", "gif", "bmp", "dib",
|
||||
"tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pnm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "cin", "dcm", "dicom",
|
||||
"dc3", "iff", "lbm", "ilbm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg",
|
||||
"svgz", "aco", "act", "ase", "kys", "af", "afdesign", "afphoto", "afpub",
|
||||
];
|
||||
const SVG_EXTS: &[&str] = &["svg", "svgz"];
|
||||
|
||||
@@ -50,6 +50,8 @@ pub(super) const OPEN_FILTERS: &[(&str, &[&str])] = &[
|
||||
("SVG", SVG_EXTS),
|
||||
("Targa", &["tga"]),
|
||||
("TIFF", &["tif", "tiff"]),
|
||||
// maketx render textures (tiled, MIP-mapped TIFF); they open read-only.
|
||||
("TX Texture", &["tx"]),
|
||||
("WebP", &["webp"]),
|
||||
("XPM", &["xpm"]),
|
||||
("Brushes", &["abr"]),
|
||||
|
||||
@@ -95,6 +95,31 @@ 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 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![Picked::Cancelled]);
|
||||
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![Picked::Cancelled]);
|
||||
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] {
|
||||
|
||||
Reference in New Issue
Block a user