Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

32.1 KB
Raw Blame
//! DirectLook image decoding, including a separate fast path for embedded RAW previews.

use std::io::{Cursor, Read, Seek, SeekFrom};
use std::path::Path;

use anyhow::{Context, anyhow};
use image::{AnimationDecoder, DynamicImage, ImageDecoder, RgbaImage};

use crate::thumbs::Bgra;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DecodedSource {
    Image,
    WindowsCodec,
    EmbeddedJpeg,
    ShellThumbnail,
    /// Legacy shell result for callers that also accept a file icon.
    ShellImage,
}

/// Çözülmüş resim: kareler (BGRA, süre ms), yön (EXIF 1–8), EXIF alanları.
pub struct Decoded {
    pub source: DecodedSource,
    pub frames: Vec<(Bgra, u32)>,
    /// EXIF yönü (1 = düz). Kareler zaten bu yöne göre döndürülmüş gelir.
    pub orientation: u8,
    pub exif: Vec<(String, String)>,
    /// Asıl boyut (döndürülmüş, küçültülmemiş).
    pub width: u32,
    pub height: u32,
}

const RAW_EXTENSIONS: &[&str] =
    &["arw", "cr2", "cr3", "crw", "dng", "erf", "kdc", "mef", "mos", "mrw", "nef", "nrw", "orf", "pef", "raf", "raw", "rw2", "rwl", "sr2", "srf", "srw", "x3f"];

pub fn is_raw(ext: &str) -> bool {
    RAW_EXTENSIONS.contains(&ext)
}

fn to_bgra(img: RgbaImage) -> Bgra {
    let (width, height) = img.dimensions();
    let mut data = img.into_raw();
    for px in data.chunks_exact_mut(4) {
        px.swap(0, 2);
    }
    Bgra { width, height, data }
}

/// En uzun kenarı `max_side`'ı aşmayacak boyut.
fn fit(w: u32, h: u32, max_side: u32) -> (u32, u32) {
    let m = w.max(h);
    if m <= max_side || m == 0 {
        return (w, h);
    }
    let s = max_side as f64 / m as f64;
    (((w as f64 * s).round() as u32).max(1), ((h as f64 * s).round() as u32).max(1))
}

fn shrink(img: RgbaImage, max_side: u32) -> RgbaImage {
    let (w, h) = img.dimensions();
    let (nw, nh) = fit(w, h, max_side);
    if (nw, nh) == (w, h) { img } else { image::imageops::resize(&img, nw, nh, image::imageops::FilterType::Triangle) }
}

fn shrink_raw_preview(img: RgbaImage, max_side: u32) -> RgbaImage {
    use fast_image_resize::{FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer, images};

    let (w, h) = img.dimensions();
    let (nw, nh) = fit(w, h, max_side);
    if (nw, nh) == (w, h) {
        return img;
    }

    // Embedded JPEGs are opaque. Bilinear convolution uses the same kernel as image's Triangle.
    if let Ok(src) = images::ImageRef::new(w, h, img.as_raw(), PixelType::U8x4) {
        let mut dst = images::Image::new(nw, nh, PixelType::U8x4);
        let options = ResizeOptions::new().resize_alg(ResizeAlg::Convolution(FilterType::Bilinear)).use_alpha(false);
        if Resizer::new().resize(&src, &mut dst, &options).is_ok() {
            if let Some(resized) = RgbaImage::from_raw(nw, nh, dst.into_vec()) {
                return resized;
            }
        }
    }
    shrink(img, max_side)
}

fn exif_fields(raw: &[u8], default_orientation: u8) -> (u8, Vec<(String, String)>) {
    let Ok(ex) = exif::Reader::new().read_raw(raw.to_vec()) else {
        return (default_orientation, Vec::new());
    };
    let orientation =
        ex.get_field(exif::Tag::Orientation, exif::In::PRIMARY).and_then(|f| f.value.get_uint(0)).map_or(default_orientation, |v| v.clamp(1, 8) as u8);
    let fields = ex
        .fields()
        .filter(|f| !matches!(f.tag, exif::Tag::MakerNote | exif::Tag::UserComment) && f.tag.description().is_some())
        .map(|f| (f.tag.to_string(), f.display_value().with_unit(&ex).to_string().trim_matches('"').to_string()))
        .filter(|(_, v)| !v.is_empty() && v.len() < 200)
        .collect();
    (orientation, fields)
}

fn orient(img: DynamicImage, o: u8) -> DynamicImage {
    match o {
        2 => img.fliph(),
        3 => img.rotate180(),
        4 => img.flipv(),
        5 => img.rotate90().fliph(),
        6 => img.rotate90(),
        7 => img.rotate270().fliph(),
        8 => img.rotate270(),
        _ => img,
    }
}

fn frames_of<'a>(frames: image::Frames<'a>, max_side: u32) -> anyhow::Result<Vec<(Bgra, u32)>> {
    let mut out = Vec::new();
    for f in frames {
        let f = f?;
        let (n, d) = f.delay().numer_denom_ms();
        let ms = if d == 0 { 100 } else { (n / d).max(20) };
        out.push((to_bgra(shrink(f.into_buffer(), max_side)), ms));
    }
    Ok(out)
}

/// Animasyonlu GIF / APNG / WebP: birden çok kare varsa onları döner.
fn animated(bytes: &[u8], format: image::ImageFormat, max_side: u32) -> Option<Vec<(Bgra, u32)>> {
    use image::codecs::{gif::GifDecoder, png::PngDecoder, webp::WebPDecoder};
    let frames = match format {
        image::ImageFormat::Gif => frames_of(GifDecoder::new(Cursor::new(bytes)).ok()?.into_frames(), max_side).ok()?,
        image::ImageFormat::Png => {
            let d = PngDecoder::new(Cursor::new(bytes)).ok()?;
            if !d.is_apng().ok()? {
                return None;
            }
            frames_of(d.apng().ok()?.into_frames(), max_side).ok()?
        }
        image::ImageFormat::WebP => {
            let d = WebPDecoder::new(Cursor::new(bytes)).ok()?;
            if !d.has_animation() {
                return None;
            }
            frames_of(d.into_frames(), max_side).ok()?
        }
        _ => return None,
    };
    (frames.len() > 1).then_some(frames)
}

fn with_image_crate(bytes: &[u8], max_side: u32) -> anyhow::Result<Decoded> {
    with_image_crate_oriented(bytes, max_side, 1, shrink)
}

fn with_image_crate_oriented(
    bytes: &[u8],
    max_side: u32,
    default_orientation: u8,
    resize: fn(RgbaImage, u32) -> RgbaImage,
) -> anyhow::Result<Decoded> {
    let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format()?;
    let format = reader.format().ok_or_else(|| anyhow!("unknown format"))?;
    if let Some(frames) = animated(bytes, format, max_side) {
        let (width, height) = (frames[0].0.width, frames[0].0.height);
        return Ok(Decoded { source: DecodedSource::Image, frames, orientation: 1, exif: Vec::new(), width, height });
    }
    let mut dec = reader.into_decoder()?;
    let (orientation, exif) = dec.exif_metadata().ok().flatten().map(|r| exif_fields(&r, default_orientation)).unwrap_or((default_orientation, Vec::new()));
    let img = orient(DynamicImage::from_decoder(dec)?, orientation);
    let (width, height) = (img.width(), img.height());
    Ok(Decoded { source: DecodedSource::Image, frames: vec![(to_bgra(resize(img.into_rgba8(), max_side)), 0)], orientation, exif, width, height })
}

/// An SVG file's picture for a thumbnail, at most `size` on its long side (resvg, the reader the preview uses). `None` for a file
/// that is too big or does not read. Issue 1001: Windows has no thumbnail provider for SVG of its own, so the list showed a
/// generic icon for every SVG, while the preview drew it.
pub fn svg_thumbnail(path: &Path, size: u32) -> Option<Bgra> {
    // (a drawing of several megabytes is a map or a plot: left to the shell's icon rather than parsed for a thumbnail)
    if std::fs::metadata(path).ok()?.len() > 8 << 20 {
        return None;
    }
    let bytes = std::fs::read(path).ok()?;
    let decoded = std::panic::catch_unwind(|| svg(&bytes, size.max(16))).ok()?.ok()?;
    decoded.frames.into_iter().next().map(|(frame, _)| frame)
}

fn svg(bytes: &[u8], max_side: u32) -> anyhow::Result<Decoded> {
    use resvg::{tiny_skia, usvg};
    let mut opt = usvg::Options::default();
    // sistem yazı tipleri yalnız metin içeren SVG'de gerekir; yüklemesi pahalı, bir kez yapılır
    if bytes.windows(5).any(|w| w == b"<text") {
        static FONTS: std::sync::OnceLock<std::sync::Arc<usvg::fontdb::Database>> = std::sync::OnceLock::new();
        opt.fontdb = FONTS
            .get_or_init(|| {
                let mut db = usvg::fontdb::Database::new();
                db.load_system_fonts();
                std::sync::Arc::new(db)
            })
            .clone();
    }
    let tree = usvg::Tree::from_data(bytes, &opt)?;
    let size = tree.size();
    let (w, h) = (size.width().max(1.0), size.height().max(1.0));
    // küçük SVG'ler net görünsün diye en az 1024 piksele büyütülür
    let target = max_side.min(4096).max(1) as f32;
    let s = (target.min(w.max(h).max(1024.0)) / w.max(h)).max(0.01);
    let (pw, ph) = ((w * s).ceil() as u32, (h * s).ceil() as u32);
    let mut pix = tiny_skia::Pixmap::new(pw.max(1), ph.max(1)).ok_or_else(|| anyhow!("svg size"))?;
    resvg::render(&tree, tiny_skia::Transform::from_scale(s, s), &mut pix.as_mut());
    // tiny-skia önceden çarpılmış RGBA verir: düz alfaya çevir
    let mut data = pix.take();
    for px in data.chunks_exact_mut(4) {
        let a = px[3] as u32;
        if a > 0 && a < 255 {
            for c in &mut px[..3] {
                *c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
            }
        }
        px.swap(0, 2);
    }
    Ok(Decoded { source: DecodedSource::Image, frames: vec![(Bgra { width: pw, height: ph, data }, 0)], orientation: 1, exif: Vec::new(), width: w.round() as u32, height: h.round() as u32 })
}

/// Windows Imaging Component: kurulu codec'ler (HEIC, AVIF, JXL, JPEG XR, kamera RAW…).
fn wic(path: &Path, max_side: u32) -> anyhow::Result<Decoded> {
    use windows::Win32::Foundation::GENERIC_READ;
    use windows::Win32::Graphics::Imaging::*;
    use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};
    use windows::core::{Interface, PCWSTR};
    crate::shell::ensure_com();
    let w = crate::wide::wide(path);
    unsafe {
        let f: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
        let dec = f.CreateDecoderFromFilename(PCWSTR(w.as_ptr()), None, GENERIC_READ, WICDecodeMetadataCacheOnDemand)?;
        let frame = dec.GetFrame(0)?;
        let (mut fw, mut fh) = (0u32, 0u32);
        frame.GetSize(&mut fw, &mut fh)?;
        let (nw, nh) = fit(fw, fh, max_side);
        let mut src: IWICBitmapSource = frame.cast()?;
        if (nw, nh) != (fw, fh) {
            let sc = f.CreateBitmapScaler()?;
            sc.Initialize(&src, nw, nh, WICBitmapInterpolationModeFant)?;
            src = sc.cast()?;
        }
        let conv = f.CreateFormatConverter()?;
        conv.Initialize(&src, &GUID_WICPixelFormat32bppBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom)?;
        let stride = nw * 4;
        let mut data = vec![0u8; (stride * nh) as usize];
        conv.CopyPixels(std::ptr::null(), stride, &mut data)?;
        Ok(Decoded { source: DecodedSource::WindowsCodec, frames: vec![(Bgra { width: nw, height: nh, data }, 0)], orientation: 1, exif: Vec::new(), width: fw, height: fh })
    }
}

/// Kamera RAW dosyasının içine gömülü en büyük JPEG önizleme.
fn raw_embedded_jpeg(bytes: &[u8], max_side: u32, raw_orientation: u8) -> anyhow::Result<Decoded> {
    let mut candidates = Vec::new();
    let mut i = 0;
    while i + 3 < bytes.len() {
        if bytes[i] == 0xFF && bytes[i + 1] == 0xD8 && bytes[i + 2] == 0xFF {
            let r = image::ImageReader::with_format(Cursor::new(&bytes[i..]), image::ImageFormat::Jpeg);
            if let Ok((w, h)) = r.into_dimensions() {
                candidates.push((std::cmp::Reverse(u64::from(w) * u64::from(h)), i));
            }
        }
        i += 1;
    }
    candidates.sort_unstable();
    for (_, start) in candidates {
        if let Ok(mut decoded) = with_image_crate_oriented(&bytes[start..], max_side, raw_orientation, shrink) {
            decoded.source = DecodedSource::EmbeddedJpeg;
            return Ok(decoded);
        }
    }
    Err(anyhow!("no usable embedded JPEG"))
}

fn read_at(file: &mut std::fs::File, offset: u64, bytes: &mut [u8]) -> std::io::Result<()> {
    file.seek(SeekFrom::Start(offset))?;
    file.read_exact(bytes)
}

/// Read only the TIFF directories that can describe a standalone preview JPEG.
fn tiff_previews(file: &mut std::fs::File, header: &[u8; 16]) -> Option<(Vec<(u32, u32)>, Option<u8>)> {
    let little = match &header[..4] {
        b"II\x2a\0" | b"II\x55\0" => true,
        b"MM\0\x2a" => false,
        _ => return None,
    };
    let word = |b: &[u8]| {
        if little { u16::from_le_bytes([b[0], b[1]]) } else { u16::from_be_bytes([b[0], b[1]]) }
    };
    let long = |b: &[u8]| {
        let bytes = [b[0], b[1], b[2], b[3]];
        if little { u32::from_le_bytes(bytes) } else { u32::from_be_bytes(bytes) }
    };
    let mut directories = vec![long(&header[4..])];
    let mut previews = Vec::new();
    let mut orientation = None;
    for index in 0..16 {
        let Some(&offset) = directories.get(index) else {
            break;
        };
        if offset == 0 || directories[..index].contains(&offset) {
            continue;
        }
        let mut count = [0; 2];
        if read_at(file, u64::from(offset), &mut count).is_err() {
            continue;
        }
        let count = usize::from(word(&count));
        if count > 1024 {
            continue;
        }
        let mut entries = vec![0; count * 12 + 4];
        if read_at(file, u64::from(offset) + 2, &mut entries).is_err() {
            continue;
        }
        let (mut jpeg, mut jpeg_len, mut strip, mut strip_len) = (0, 0, 0, 0);
        let (mut compression, mut photometric) = (0, 0);
        for entry in entries[..count * 12].chunks_exact(12) {
            let tag = word(entry);
            let kind = word(&entry[2..]);
            let len = long(&entry[4..]);
            let data = &entry[8..];
            if tag == 330 && matches!(kind, 4 | 13) && (2..=16).contains(&len) {
                let mut offsets = vec![0; len as usize * 4];
                if read_at(file, u64::from(long(data)), &mut offsets).is_ok() {
                    directories.extend(offsets.chunks_exact(4).map(long));
                }
            } else if len == 1 {
                let value = match kind {
                    3 => u32::from(word(data)),
                    4 | 13 => long(data),
                    _ => continue,
                };
                match tag {
                    259 => compression = value,
                    262 => photometric = value,
                    273 => strip = value,
                    274 if index == 0 && (1..=8).contains(&value) => orientation = Some(value as u8),
                    279 => strip_len = value,
                    330 => directories.push(value),
                    513 => jpeg = value,
                    514 => jpeg_len = value,
                    _ => {}
                }
            }
        }
        if jpeg != 0 && jpeg_len != 0 {
            previews.push((jpeg, jpeg_len));
        }
        if matches!(compression, 6 | 7) && matches!(photometric, 2 | 6) && strip != 0 && strip_len != 0 {
            previews.push((strip, strip_len));
        }
        let next = long(&entries[count * 12..]);
        if next != 0 {
            directories.push(next);
        }
    }
    Some((previews, orientation))
}

/// Prefer a bounded read of the JPEG over developing the RAW for a screen preview.
pub fn decode_raw_preview(path: &Path, max_side: u32) -> Option<Decoded> {
    let mut file = std::fs::File::open(path).ok()?;
    let mut header = [0; 16];
    file.read_exact(&mut header).ok()?;
    let (ranges, raw_orientation) = if &header == b"FUJIFILMCCD-RAW " {
        let mut range = [0; 8];
        read_at(&mut file, 84, &mut range).ok()?;
        (vec![(u32::from_be_bytes(range[..4].try_into().ok()?), u32::from_be_bytes(range[4..].try_into().ok()?))], None)
    } else {
        tiff_previews(&mut file, &header)?
    };
    let file_len = file.metadata().ok()?.len();
    let mut candidates = Vec::new();
    for (offset, len) in ranges {
        if !(4..=32 * 1024 * 1024).contains(&len) || u64::from(offset) + u64::from(len) > file_len {
            continue;
        }
        let mut head = vec![0; (len as usize).min(128 * 1024)];
        if read_at(&mut file, u64::from(offset), &mut head).is_err() || !head.starts_with(&[0xff, 0xd8, 0xff]) {
            continue;
        }
        let reader = image::ImageReader::with_format(Cursor::new(head), image::ImageFormat::Jpeg);
        if let Ok((w, h)) = reader.into_dimensions() {
            if w.max(h) >= 1024 && u64::from(w) * u64::from(h) <= 100_000_000 {
                candidates.push((u64::from(w) * u64::from(h), offset, len));
            }
        }
    }
    // Some cameras embed a sensor-sized JPEG beside the screen preview. Decoding
    // the smaller usable image avoids allocating and resizing the larger one.
    candidates.sort_unstable();
    candidates.dedup();
    for (_, offset, len) in candidates {
        let mut bytes = vec![0; len as usize];
        if read_at(&mut file, u64::from(offset), &mut bytes).is_ok() {
            if let Ok(mut decoded) = with_image_crate_oriented(&bytes, max_side, raw_orientation.unwrap_or(1), shrink_raw_preview) {
                decoded.source = DecodedSource::EmbeddedJpeg;
                return Some(decoded);
            }
        }
    }
    None
}

/// A design file's own picture (see `crate::design`) is small (CorelDRAW saves 256 px on the
/// short side): the previewer shows it enlarged smoothly to at least this long side.
const DESIGN_SIDE: u32 = 720;

/// The size a design file's picture is shown at: enlarged to `DESIGN_SIDE`, within `max_side`.
fn design_size(w: u32, h: u32, max_side: u32) -> (u32, u32) {
    let long = w.max(h).max(1);
    let target = DESIGN_SIDE.max(long).min(max_side);
    let s = target as f64 / long as f64;
    (((w as f64 * s).round() as u32).max(1), ((h as f64 * s).round() as u32).max(1))
}

fn design(path: &Path, max_side: u32) -> Option<Decoded> {
    let img = crate::design::preview(path)?;
    let (w, h) = img.dimensions();
    let (dw, dh) = design_size(w, h, max_side);
    let img = if (dw, dh) == (w, h) { img } else { image::imageops::resize(&img, dw, dh, image::imageops::FilterType::CatmullRom) };
    Some(Decoded { source: DecodedSource::Image, frames: vec![(to_bgra(img), 0)], orientation: 1, exif: Vec::new(), width: dw, height: dh })
}

/// `img` in BGRA, its long side at most `max_side` (never enlarged).
pub(crate) fn bgra_within(img: RgbaImage, max_side: u32) -> Bgra {
    to_bgra(shrink(img, max_side))
}

fn psd(bytes: &[u8], max_side: u32) -> anyhow::Result<Decoded> {
    let p = psd::Psd::from_bytes(bytes).map_err(|e| anyhow!("psd: {e}"))?;
    let img = RgbaImage::from_raw(p.width(), p.height(), p.rgba()).context("psd pixels")?;
    let (width, height) = img.dimensions();
    Ok(Decoded { source: DecodedSource::Image, frames: vec![(to_bgra(shrink(img, max_side)), 0)], orientation: 1, exif: Vec::new(), width, height })
}

/// Resmin (EXIF yönüne göre döndürülmüş) boyutu; yalnız başlık okunur, hızlıdır.
pub fn dimensions(path: &Path) -> Option<(u32, u32)> {
    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
    if crate::design::is_design_ext(&ext) {
        if let Some(img) = crate::design::preview(path) {
            return Some(design_size(img.width(), img.height(), u32::MAX));
        }
    }
    if ext == "svg" || ext == "svgz" {
        let bytes = std::fs::read(path).ok()?;
        let tree = resvg::usvg::Tree::from_data(&bytes, &resvg::usvg::Options::default()).ok()?;
        return Some((tree.size().width().round() as u32, tree.size().height().round() as u32));
    }
    if !is_raw(&ext) {
        if let Ok(r) = image::ImageReader::open(path).and_then(|r| r.with_guessed_format()) {
            if let Ok(mut d) = r.into_decoder() {
                let (w, h) = d.dimensions();
                let o = d.exif_metadata().ok().flatten().map_or(1, |raw| exif_fields(&raw, 1).0);
                return Some(if (5..=8).contains(&o) { (h, w) } else { (w, h) });
            }
        }
    }
    use windows::Win32::Foundation::GENERIC_READ;
    use windows::Win32::Graphics::Imaging::*;
    use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};
    use windows::core::PCWSTR;
    crate::shell::ensure_com();
    let w = crate::wide::wide(path);
    unsafe {
        let f: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).ok()?;
        let dec = f.CreateDecoderFromFilename(PCWSTR(w.as_ptr()), None, GENERIC_READ, WICDecodeMetadataCacheOnDemand).ok()?;
        let frame = dec.GetFrame(0).ok()?;
        let (mut fw, mut fh) = (0u32, 0u32);
        frame.GetSize(&mut fw, &mut fh).ok()?;
        Some((fw, fh))
    }
}

/// Resmi tam çözünürlükte (en uzun kenar en çok `max_side`) çözer; sırayla dener.
pub fn decode_full(path: &Path, max_side: u32) -> anyhow::Result<Decoded> {
    decode_full_with_orientation(path, max_side, None, Some(crate::thumbs::Kind::Thumbnail))
}

/// The picture of `path` at its own size, for the converter: the same decoders as [`decode_full`], but never the shell's thumbnail
/// or icon in its place. A file nothing here can decode is an error: written out as a small thumbnail it would look like a
/// conversion that worked.
pub fn decode_whole(path: &Path) -> anyhow::Result<Decoded> {
    decode_full_with_orientation(path, u32::MAX, None, None)
}

pub fn decode_picture(path: &Path, max_side: u32) -> anyhow::Result<Decoded> {
    decode_full_with_orientation(path, max_side, None, Some(crate::thumbs::Kind::ThumbnailOnly))
}

pub fn decode_raw_detail(path: &Path, max_side: u32, preview_orientation: u8, preview_size: (u32, u32)) -> anyhow::Result<Decoded> {
    decode_full_with_orientation(path, max_side, Some((preview_orientation, preview_size)), None)
}

// Allow for the rounding and border pixels of camera-generated previews.
pub fn same_raw_aspect((w, h): (u32, u32), (nw, nh): (u32, u32)) -> bool {
    let a = u64::from(nw) * u64::from(h);
    let b = u64::from(w) * u64::from(nh);
    a != 0 && b != 0 && a.abs_diff(b) <= a.max(b) / 100
}

fn raw_container_orientation(path: &Path) -> Option<u8> {
    let mut file = std::fs::File::open(path).ok()?;
    let mut header = [0; 16];
    file.read_exact(&mut header).ok()?;
    tiff_previews(&mut file, &header)?.1
}

fn orient_raw_wic(mut decoded: Decoded, orientation: u8, preview_size: Option<(u32, u32)>) -> anyhow::Result<Decoded> {
    let swaps_axes = (5..=8).contains(&orientation);
    if orientation == 1
        || (swaps_axes && preview_size.is_some_and(|size| same_raw_aspect(size, (decoded.width, decoded.height))))
    {
        return Ok(decoded);
    }
    let (pixels, delay) = decoded.frames.pop().context("missing WIC frame")?;
    let image = RgbaImage::from_raw(pixels.width, pixels.height, pixels.data).context("invalid WIC frame")?;
    let image = orient(DynamicImage::ImageRgba8(image), orientation).into_rgba8();
    let (width, height) = image.dimensions();
    decoded.frames.push((Bgra { width, height, data: image.into_raw() }, delay));
    if swaps_axes {
        std::mem::swap(&mut decoded.width, &mut decoded.height);
    }
    decoded.orientation = orientation;
    Ok(decoded)
}

fn decode_full_with_orientation(
    path: &Path,
    max_side: u32,
    raw_preview: Option<(u8, (u32, u32))>,
    shell_fallback: Option<crate::thumbs::Kind>,
) -> anyhow::Result<Decoded> {
    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
    // (before reading the file: a CorelDRAW file is tens of MB, its picture one small entry)
    if crate::design::is_design_ext(&ext) {
        if let Some(d) = design(path, max_side) {
            return Ok(d);
        }
    }
    let raw = is_raw(&ext);
    let mut raw_orientation = 1;
    if raw {
        raw_orientation = raw_container_orientation(path).or(raw_preview.map(|(orientation, _)| orientation)).unwrap_or(1);
        let preview_size = raw_preview.map(|(_, size)| size);
        if let Ok(decoded) = wic(path, max_side).and_then(|decoded| orient_raw_wic(decoded, raw_orientation, preview_size))
            && preview_size.is_none_or(|size| same_raw_aspect(size, (decoded.width, decoded.height)))
        {
            return Ok(decoded);
        }
    }
    let bytes = std::fs::read(path).with_context(|| path.display().to_string())?;
    if ext == "svg" || ext == "svgz" {
        return svg(&bytes, max_side);
    }
    if !raw {
        if let Ok(d) = with_image_crate(&bytes, max_side) {
            return Ok(d);
        }
    }
    if !raw {
        if let Ok(d) = wic(path, max_side) {
            return Ok(d);
        }
    }
    if raw {
        if let Ok(d) = raw_embedded_jpeg(&bytes, max_side, raw_orientation) {
            return Ok(d);
        }
    }
    if ext == "psd" || ext == "psb" {
        if let Ok(d) = psd(&bytes, max_side) {
            return Ok(d);
        }
    }
    let Some(kind) = shell_fallback else {
        return Err(anyhow!("no decodable detail image"));
    };
    let t = crate::thumbs::get_image(path, max_side.min(1024), kind)?;
    let (width, height) = (t.width, t.height);
    let source = if matches!(kind, crate::thumbs::Kind::ThumbnailOnly) { DecodedSource::ShellThumbnail } else { DecodedSource::ShellImage };
    Ok(Decoded { source, frames: vec![(t, 0)], orientation: 1, exif: Vec::new(), width, height })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn data(name: &str) -> std::path::PathBuf {
        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data").join(name)
    }

    /// Issue 1001: an SVG gets a thumbnail of its own, fitted into the size asked for.
    #[test]
    fn an_svg_gets_a_thumbnail_of_its_size() {
        let b = svg_thumbnail(&data("look/a.svg"), 96).expect("a thumbnail");
        assert!(b.width.max(b.height) <= 96 && b.width.max(b.height) >= 48, "{}x{}", b.width, b.height);
        assert!(b.data.chunks_exact(4).any(|p| p[3] > 0), "something is drawn");
        assert!(svg_thumbnail(&data("look/a.png"), 96).is_none(), "a picture that is no SVG gives none");
    }

    #[test]
    fn decodes_common_formats() {
        for f in ["look/a.png", "look/a.jpg", "look/a.webp", "look/a.gif", "look/a.svg"] {
            let d = decode_full(&data(f), 4096).unwrap();
            assert!(d.frames[0].0.width > 0, "{f}");
        }
    }

    #[test]
    fn animated_gif_has_frames() {
        let d = decode_full(&data("look/anim.gif"), 4096).unwrap();
        assert_eq!(d.frames.len(), 3);
        assert_eq!(d.frames[0].1, 100);
    }

    #[test]
    fn exif_orientation_read() {
        let d = decode_full(&data("look/rot6.jpg"), 4096).unwrap();
        assert_eq!(d.orientation, 6);
        assert!(d.exif.iter().any(|(k, v)| k == "Model" && v.contains("Test Kamera")), "{:?}", d.exif);
    }

    #[test]
    fn raw_tiff_preview_prefers_the_smaller_usable_jpeg_and_uses_container_orientation() {
        use std::io::Write;
        let path = std::env::temp_dir().join(format!("rf-raw-preview-{}.dng", std::process::id()));
        let mut file = std::fs::File::create(&path).unwrap();
        file.write_all(b"II\x2a\0\x08\0\0\0").unwrap();
        for (ifd, next, jpeg_offset, width, height) in [(8_u32, 128_u32, 1024_u32, 1600, 1200), (128, 0, 65_536, 1200, 800)] {
            let mut jpeg = Vec::new();
            image::codecs::jpeg::JpegEncoder::new(&mut jpeg)
                .encode(&vec![64; (width * height * 3) as usize], width, height, image::ExtendedColorType::Rgb8)
                .unwrap();
            file.seek(SeekFrom::Start(u64::from(ifd))).unwrap();
            file.write_all(&3_u16.to_le_bytes()).unwrap();
            for (tag, kind, value) in [(274_u16, 3_u16, 6), (513, 4, jpeg_offset), (514, 4, jpeg.len() as u32)] {
                file.write_all(&tag.to_le_bytes()).unwrap();
                file.write_all(&kind.to_le_bytes()).unwrap();
                file.write_all(&1_u32.to_le_bytes()).unwrap();
                file.write_all(&value.to_le_bytes()).unwrap();
            }
            file.write_all(&next.to_le_bytes()).unwrap();
            file.seek(SeekFrom::Start(u64::from(jpeg_offset))).unwrap();
            file.write_all(&jpeg).unwrap();
        }
        drop(file);
        let decoded = decode_raw_preview(&path, 1024);
        assert_eq!(raw_container_orientation(&path), Some(6));
        std::fs::remove_file(path).unwrap();
        let decoded = decoded.unwrap();
        assert_eq!(decoded.source, DecodedSource::EmbeddedJpeg);
        assert_eq!((decoded.width, decoded.height, decoded.orientation), (800, 1200, 6));
        assert_eq!((decoded.frames[0].0.width, decoded.frames[0].0.height), (683, 1024));
    }

    #[test]
    fn raw_detail_rotates_landscape_codec_pixels_once_for_a_portrait_preview() {
        let pixel = |value| [value, value, value, 255];
        let landscape = Decoded {
            source: DecodedSource::WindowsCodec,
            frames: vec![(Bgra { width: 3, height: 2, data: (0..6).flat_map(pixel).collect() }, 0)],
            orientation: 1,
            exif: Vec::new(),
            width: 3,
            height: 2,
        };
        let portrait = orient_raw_wic(landscape, 8, Some((20, 30))).unwrap();
        assert_eq!((portrait.width, portrait.height), (2, 3));
        let expected: Vec<_> = [2, 5, 1, 4, 0, 3].into_iter().flat_map(pixel).collect();
        assert_eq!(portrait.frames[0].0.data, expected);
        let already_oriented = orient_raw_wic(portrait, 8, Some((20, 30))).unwrap();
        assert_eq!((already_oriented.width, already_oriented.height), (2, 3));
        assert_eq!(already_oriented.frames[0].0.data, expected);
    }

    #[test]
    fn invalid_raws_do_not_return_extension_icons_as_pictures() {
        let mut outside_file = b"II\x2a\0\x08\0\0\0\x02\0".to_vec();
        for tag in [513_u16, 514] {
            outside_file.extend(tag.to_le_bytes());
            outside_file.extend(4_u16.to_le_bytes());
            outside_file.extend(1_u32.to_le_bytes());
            outside_file.extend(4096_u32.to_le_bytes());
        }
        outside_file.extend(0_u32.to_le_bytes());
        let cases: &[&[u8]] = &[b"", b"II\x2a\0\x08\0\0\0\x02\0", &outside_file];
        for (index, bytes) in cases.iter().enumerate() {
            let path = std::env::temp_dir().join(format!("rf-invalid-raw-{}-{index}.dng", std::process::id()));
            std::fs::write(&path, bytes).unwrap();
            let preview = decode_raw_preview(&path, 2560);
            let picture = decode_picture(&path, 8192);
            let detail = decode_raw_detail(&path, 8192, 1, (1, 1));
            std::fs::remove_file(&path).unwrap();
            assert!(preview.is_none());
            assert!(picture.is_err());
            assert!(detail.is_err());
        }
    }

    #[test]
    fn raw_scan_recovers_from_a_broken_larger_jpeg_and_keeps_orientation() {
        let mut broken = Vec::new();
        image::codecs::jpeg::JpegEncoder::new(&mut broken).encode(&[90; 96 * 72], 96, 72, image::ExtendedColorType::L8).unwrap();
        // Strip the Huffman tables so the header still reports a size, but pixel decode fails.
        let mut marker = 2;
        while broken[marker + 1] != 0xda {
            let len = usize::from(u16::from_be_bytes([broken[marker + 2], broken[marker + 3]]));
            if broken[marker + 1] == 0xc4 {
                broken.drain(marker..marker + 2 + len);
            } else {
                marker += 2 + len;
            }
        }
        let header = image::ImageReader::with_format(Cursor::new(&broken), image::ImageFormat::Jpeg);
        assert_eq!(header.into_dimensions().unwrap(), (96, 72));
        assert!(with_image_crate(&broken, 8192).is_err());
        let intact = std::fs::read(data("look/a.jpg")).unwrap();
        let original = with_image_crate(&intact, 8192).unwrap();
        broken.extend(intact);

        let decoded = raw_embedded_jpeg(&broken, 8192, 6).unwrap();
        assert_eq!(decoded.source, DecodedSource::EmbeddedJpeg);
        assert_eq!((decoded.width, decoded.height, decoded.orientation), (original.height, original.width, 6));
    }

    #[test]
    fn large_images_are_scaled_down() {
        let d = decode_full(&data("look/a.png"), 32).unwrap();
        assert_eq!((d.frames[0].0.width, d.frames[0].0.height), (32, 24));
        assert_eq!((d.width, d.height), (64, 48));
    }

    #[test]
    fn header_dimensions() {
        assert_eq!(dimensions(&data("look/a.png")), Some((64, 48)));
        assert_eq!(dimensions(&data("look/rot6.jpg")), Some((40, 60)));
        assert_eq!(dimensions(&data("look/a.svg")), Some((80, 60)));
    }

    #[test]
    fn pixels_are_bgra() {
        let d = decode_full(&data("look/a.png"), 4096).unwrap();
        // sol üst köşe kırmızı (200, 30, 30) ama çapraz çizgi siyah; (60, 2) kırmızı
        let f = &d.frames[0].0;
        let i = ((2 * f.width + 60) * 4) as usize;
        assert_eq!(&f.data[i..i + 4], &[30, 30, 200, 255]);
    }
}