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.

21.2 KB
Raw Blame
//! rustyfiles' converter (plan: a ring of target formats while dragging, "Convert" in the right-click menu, a command line; the
//! idea of Filee, with no outside program: every format is code of ours or a pure Rust crate).
//!
//! This crate is the part that is the same on every system: which files the converter takes, which targets a selection has, the
//! encoding of a decoded picture into a target format, and the writing of the result without ever replacing a file. DECODING is
//! the platform's (on Windows `rf_win::look::decode`, which also asks Windows' codecs for HEIC and AVIF): a picture arrives here
//! as 8-bit RGBA.
//!
//! Step 1 is pictures. What it does not do yet, on purpose and said in the interface where it matters:
//! * camera RAW files are not taken (their full picture needs the system's raw codec; the preview inside may be small);
//! * an animated GIF or WebP gives its first frame;
//! * 8 bits a channel: a 16-bit or HDR picture loses depth, and colour profiles and EXIF are not carried over (the platform hands
//!   the picture upright, so nothing ends up turned);
//! * WebP is written without loss only: there is no lossy WebP encoder in pure Rust.

use std::io::{Cursor, Write};
use std::path::{Path, PathBuf};

use anyhow::{Context, ensure};
use image::{ExtendedColorType, ImageEncoder};

/// A picture format the converter writes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PictureFormat {
    Png,
    Jpeg,
    Webp,
    Jxl,
    Bmp,
    Tiff,
    Gif,
    Ico,
    Qoi,
}

impl PictureFormat {
    /// Every target, in the order the interface shows them: the ones asked for most first.
    pub const ALL: [PictureFormat; 9] = [Self::Jpeg, Self::Png, Self::Webp, Self::Jxl, Self::Tiff, Self::Bmp, Self::Gif, Self::Ico, Self::Qoi];

    /// The extension a file of this format gets, without the dot.
    pub fn ext(self) -> &'static str {
        match self {
            Self::Png => "png",
            Self::Jpeg => "jpg",
            Self::Webp => "webp",
            Self::Jxl => "jxl",
            Self::Bmp => "bmp",
            Self::Tiff => "tif",
            Self::Gif => "gif",
            Self::Ico => "ico",
            Self::Qoi => "qoi",
        }
    }

    /// The name in the interface (a format's name is the same in every language).
    pub fn label(self) -> &'static str {
        match self {
            Self::Png => "PNG",
            Self::Jpeg => "JPEG",
            Self::Webp => "WebP",
            Self::Jxl => "JPEG XL",
            Self::Bmp => "BMP",
            Self::Tiff => "TIFF",
            Self::Gif => "GIF",
            Self::Ico => "ICO",
            Self::Qoi => "QOI",
        }
    }

    /// The format a file with this extension (lower case, no dot) IS, when it is one of the targets.
    pub fn of_ext(ext: &str) -> Option<Self> {
        Some(match ext {
            "png" => Self::Png,
            "jpg" | "jpeg" | "jpe" | "jfif" => Self::Jpeg,
            "webp" => Self::Webp,
            "jxl" => Self::Jxl,
            "bmp" | "dib" => Self::Bmp,
            "tif" | "tiff" => Self::Tiff,
            "gif" => Self::Gif,
            "ico" => Self::Ico,
            "qoi" => Self::Qoi,
            _ => return None,
        })
    }

    /// Whether the format throws detail away to be small ([`PictureOptions::quality`] matters for these only).
    pub fn lossy(self) -> bool {
        matches!(self, Self::Jpeg | Self::Jxl)
    }

    /// Whether a file of this format can be see-through. The others get the picture on [`PictureOptions::background`].
    pub fn keeps_transparency(self) -> bool {
        !matches!(self, Self::Jpeg | Self::Bmp)
    }

    /// The longest side the format (or its use) allows; a bigger picture is fitted into it.
    fn max_side(self) -> Option<u32> {
        match self {
            // an icon file holds pictures of up to 256 pixels
            Self::Ico => Some(256),
            Self::Gif | Self::Jpeg => Some(65_535),
            Self::Webp => Some(16_383),
            _ => None,
        }
    }
}

/// The extensions (lower case, no dot) of pictures the converter takes, beside the targets' own. Camera RAW files are not among
/// them yet (see the top of this file).
const OTHER_PICTURES: &[&str] = &["heic", "heif", "avif", "tga", "dds", "exr", "hdr", "pnm", "pbm", "pgm", "ppm", "svg", "psd"];

/// Whether a file with this extension (lower case, no dot) is a picture the converter takes.
pub fn is_picture(ext: &str) -> bool {
    PictureFormat::of_ext(ext).is_some() || OTHER_PICTURES.contains(&ext)
}

/// The extension of `path` as the functions here want it: lower case, no dot; empty when there is none.
pub fn ext_of(path: &Path) -> String {
    path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase()
}

/// The targets to offer for a selection of files with these extensions (lower case, no dot). Nothing when the selection is empty
/// or one of the files is no picture: the entry is for a selection that converts whole, not for a part of it. A format that every
/// file already is, is left out (PNG to PNG is not a conversion).
pub fn picture_targets<'a>(exts: impl IntoIterator<Item = &'a str>) -> Vec<PictureFormat> {
    let mut all_are: Option<Option<PictureFormat>> = None;
    for ext in exts {
        if !is_picture(ext) {
            return Vec::new();
        }
        let this = PictureFormat::of_ext(ext);
        all_are = Some(match all_are {
            None => this,
            Some(so_far) if so_far == this => so_far,
            Some(_) => None,
        });
    }
    let Some(all_are) = all_are else { return Vec::new() };
    PictureFormat::ALL.into_iter().filter(|f| Some(*f) != all_are).collect()
}

/// How a picture is written.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PictureOptions {
    /// 1 to 100, for the formats that are [`PictureFormat::lossy`]. 90 is the usual "looks the same" setting.
    pub quality: u8,
    /// The longest side of the result; a bigger picture is made smaller, a smaller one is left as it is. `None`: the picture's own.
    pub max_side: Option<u32>,
    /// What shows through where the picture is see-through, for a format that cannot be (JPEG, BMP).
    pub background: [u8; 3],
}

impl Default for PictureOptions {
    fn default() -> Self {
        Self { quality: 90, max_side: None, background: [255, 255, 255] }
    }
}

/// A decoded picture: 8-bit RGBA, rows from the top, not premultiplied.
#[derive(Clone, Copy)]
pub struct Picture<'a> {
    pub width: u32,
    pub height: u32,
    pub rgba: &'a [u8],
}

impl Picture<'_> {
    fn check(&self) -> anyhow::Result<()> {
        ensure!(self.width > 0 && self.height > 0, "the picture is empty");
        let want = (self.width as u64) * (self.height as u64) * 4;
        ensure!(self.rgba.len() as u64 == want, "the picture's data is {} bytes, {}x{} needs {want}", self.rgba.len(), self.width, self.height);
        Ok(())
    }
}

/// Whether no pixel of the picture is see-through.
fn opaque(rgba: &[u8]) -> bool {
    rgba.chunks_exact(4).all(|p| p[3] == 255)
}

/// The picture on a plain background, as RGB.
fn flattened(rgba: &[u8], bg: [u8; 3]) -> Vec<u8> {
    let mut out = Vec::with_capacity(rgba.len() / 4 * 3);
    for p in rgba.chunks_exact(4) {
        let a = p[3] as u32;
        for c in 0..3 {
            // (rounded: a fully covered pixel stays exactly its colour, an empty one exactly the background)
            out.push(((p[c] as u32 * a + bg[c] as u32 * (255 - a) + 127) / 255) as u8);
        }
    }
    out
}

/// The picture without its alpha channel (for one that is [`opaque`]).
fn rgb_of(rgba: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(rgba.len() / 4 * 3);
    for p in rgba.chunks_exact(4) {
        out.extend_from_slice(&p[..3]);
    }
    out
}

/// The size of a `w` x `h` picture fitted into `max` on its longest side (never bigger than it was, never zero on a side).
fn fitted(w: u32, h: u32, max: u32) -> (u32, u32) {
    let long = w.max(h);
    if long <= max {
        return (w, h);
    }
    let scale = |v: u32| ((v as u64 * max as u64 + long as u64 / 2) / long as u64).max(1) as u32;
    (scale(w), scale(h))
}

/// Encodes `picture` as a file of `format`. The bytes are the whole file.
pub fn encode_picture(picture: Picture<'_>, format: PictureFormat, options: &PictureOptions) -> anyhow::Result<Vec<u8>> {
    picture.check()?;
    // the size: what was asked for, inside what the format allows
    let limit = match (options.max_side, format.max_side()) {
        (Some(a), Some(b)) => Some(a.min(b)),
        (a, b) => a.or(b),
    };
    let (w, h) = limit.map_or((picture.width, picture.height), |m| fitted(picture.width, picture.height, m.max(1)));
    let resized;
    let rgba: &[u8] = if (w, h) == (picture.width, picture.height) {
        picture.rgba
    } else {
        let src = image::RgbaImage::from_raw(picture.width, picture.height, picture.rgba.to_vec()).context("the picture's data does not fit its size")?;
        resized = image::imageops::resize(&src, w, h, image::imageops::FilterType::CatmullRom).into_raw();
        &resized
    };
    let solid = opaque(rgba);
    // three channels where the format has no transparency or the picture has none; four otherwise
    let (pixels, color): (std::borrow::Cow<'_, [u8]>, ExtendedColorType) = if !format.keeps_transparency() {
        (flattened(rgba, options.background).into(), ExtendedColorType::Rgb8)
    } else if solid && !matches!(format, PictureFormat::Ico | PictureFormat::Gif) {
        (rgb_of(rgba).into(), ExtendedColorType::Rgb8)
    } else {
        (rgba.into(), ExtendedColorType::Rgba8)
    };
    let mut out = Vec::new();
    match format {
        PictureFormat::Png => {
            use image::codecs::png::{CompressionType, FilterType, PngEncoder};
            PngEncoder::new_with_quality(&mut out, CompressionType::Default, FilterType::Adaptive).write_image(&pixels, w, h, color)?
        }
        PictureFormat::Jpeg => image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, options.quality.clamp(1, 100)).write_image(&pixels, w, h, color)?,
        PictureFormat::Webp => image::codecs::webp::WebPEncoder::new_lossless(&mut out).write_image(&pixels, w, h, color)?,
        PictureFormat::Jxl => {
            // (our own encoder takes RGBA and is told whether the alpha means anything)
            out = rf_jxl::encode(w, h, rgba, !solid, options.quality.clamp(1, 100) as f32).map_err(|e| anyhow::anyhow!("JPEG XL: {e:?}"))?
        }
        PictureFormat::Bmp => image::codecs::bmp::BmpEncoder::new(&mut out).write_image(&pixels, w, h, color)?,
        PictureFormat::Tiff => {
            // (the TIFF writer goes back to patch offsets: it needs a seekable sink)
            let mut sink = Cursor::new(Vec::new());
            image::codecs::tiff::TiffEncoder::new(&mut sink).write_image(&pixels, w, h, color)?;
            out = sink.into_inner();
        }
        PictureFormat::Gif => image::codecs::gif::GifEncoder::new(&mut out).encode(&pixels, w, h, color)?,
        PictureFormat::Ico => image::codecs::ico::IcoEncoder::new(&mut out).write_image(&pixels, w, h, color)?,
        PictureFormat::Qoi => image::codecs::qoi::QoiEncoder::new(&mut out).write_image(&pixels, w, h, color)?,
    }
    ensure!(!out.is_empty(), "the {} encoder wrote nothing", format.label());
    Ok(out)
}

/// The name a converted file is first tried under: the source's name with the target's extension.
pub fn target_name(source: &Path, ext: &str) -> String {
    let stem = source.file_stem().map(|s| s.to_string_lossy().into_owned()).filter(|s| !s.is_empty()).unwrap_or_else(|| "file".into());
    format!("{stem}.{ext}")
}

/// Writes `bytes` as a NEW file in `dir`, named `name`, or `name (2)`, `name (3)`... when that is taken (the number goes before the
/// extension). Never replaces a file: the name is taken with create-new, so two conversions running at once cannot pick the same
/// one, and a file that appears between the look and the write is not written over. A write that fails leaves no half file.
pub fn write_new(dir: &Path, name: &str, bytes: &[u8]) -> std::io::Result<PathBuf> {
    let (stem, ext) = match name.rfind('.') {
        Some(i) if i > 0 => (&name[..i], &name[i..]),
        _ => (name, ""),
    };
    for n in 1u32.. {
        let path = if n == 1 { dir.join(name) } else { dir.join(format!("{stem} ({n}){ext}")) };
        match std::fs::OpenOptions::new().write(true).create_new(true).open(&path) {
            Ok(mut file) => {
                if let Err(e) = file.write_all(bytes).and_then(|_| file.flush()) {
                    drop(file);
                    let _ = std::fs::remove_file(&path);
                    return Err(e);
                }
                return Ok(path);
            }
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(e),
        }
    }
    unreachable!("the loop over names only ends by returning")
}

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

    /// A picture with a gradient, and a see-through quarter when `alpha`.
    fn sample(w: u32, h: u32, alpha: bool) -> Vec<u8> {
        let mut v = Vec::with_capacity((w * h * 4) as usize);
        for y in 0..h {
            for x in 0..w {
                let a = if alpha && x < w / 2 && y < h / 2 { 0 } else { 255 };
                v.extend_from_slice(&[(x * 255 / w.max(1)) as u8, (y * 255 / h.max(1)) as u8, 128, a]);
            }
        }
        v
    }

    fn tmp(name: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("rf-convert-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn a_selection_gets_targets_only_when_every_file_is_a_picture() {
        assert!(picture_targets([]).is_empty());
        assert!(picture_targets(["png", "txt"]).is_empty(), "one file that is no picture: no entry");
        assert!(picture_targets(["arw"]).is_empty(), "camera RAW is not taken yet");
        let mixed = picture_targets(["png", "jpg", "heic"]);
        assert_eq!(mixed, PictureFormat::ALL);
    }

    #[test]
    fn the_format_every_file_already_is_is_not_offered() {
        let t = picture_targets(["jpg", "jpeg", "jfif"]);
        assert!(!t.contains(&PictureFormat::Jpeg));
        assert_eq!(t.len(), PictureFormat::ALL.len() - 1);
        // a format that is no target (HEIC) takes nothing away
        assert_eq!(picture_targets(["heic", "heic"]), PictureFormat::ALL);
        // two different ones: both stay
        assert!(picture_targets(["png", "jpg"]).contains(&PictureFormat::Png));
    }

    #[test]
    fn every_target_is_written_and_read_back_at_its_size() {
        let (w, h) = (40, 24);
        let rgba = sample(w, h, true);
        for f in PictureFormat::ALL {
            let bytes = encode_picture(Picture { width: w, height: h, rgba: &rgba }, f, &PictureOptions::default()).unwrap_or_else(|e| panic!("{}: {e:#}", f.label()));
            if f == PictureFormat::Jxl {
                let img = jxl_oxide::JxlImage::builder().read(Cursor::new(&bytes)).expect("our JPEG XL file opens in the reference decoder");
                assert_eq!((img.width(), img.height()), (w, h));
                continue;
            }
            let back = image::load_from_memory(&bytes).unwrap_or_else(|e| panic!("{} does not read back: {e}", f.label()));
            assert_eq!((back.width(), back.height()), (w, h), "{}", f.label());
            let px = back.to_rgba8();
            // the see-through corner stays see-through where the format can; on white where it cannot
            let corner = px.get_pixel(2, 2).0;
            if f.keeps_transparency() {
                assert_eq!(corner[3], 0, "{}", f.label());
            } else {
                assert_eq!(corner[3], 255, "{}", f.label());
                assert!(corner[..3].iter().all(|c| *c > 240), "{}: {corner:?} is not the white background", f.label());
            }
        }
    }

    #[test]
    fn the_formats_without_loss_give_the_same_pixels_back() {
        let (w, h) = (33, 17);
        let rgba = sample(w, h, false);
        for f in [PictureFormat::Png, PictureFormat::Webp, PictureFormat::Bmp, PictureFormat::Tiff, PictureFormat::Qoi] {
            let bytes = encode_picture(Picture { width: w, height: h, rgba: &rgba }, f, &PictureOptions::default()).unwrap();
            assert_eq!(image::load_from_memory(&bytes).unwrap().to_rgba8().into_raw(), rgba, "{}", f.label());
        }
    }

    #[test]
    fn a_picture_is_fitted_into_what_was_asked_for_and_what_the_format_allows() {
        assert_eq!(fitted(4000, 3000, 2000), (2000, 1500));
        assert_eq!(fitted(100, 50, 2000), (100, 50), "never made bigger");
        assert_eq!(fitted(10_000, 1, 100), (100, 1), "never zero on a side");
        let (w, h) = (600, 300);
        let rgba = sample(w, h, false);
        let ico = encode_picture(Picture { width: w, height: h, rgba: &rgba }, PictureFormat::Ico, &PictureOptions::default()).unwrap();
        let back = image::load_from_memory(&ico).unwrap();
        assert_eq!((back.width(), back.height()), (256, 128), "an icon file holds 256 pixels at most");
        let small = encode_picture(Picture { width: w, height: h, rgba: &rgba }, PictureFormat::Png, &PictureOptions { max_side: Some(60), ..Default::default() }).unwrap();
        let back = image::load_from_memory(&small).unwrap();
        assert_eq!((back.width(), back.height()), (60, 30));
    }

    #[test]
    fn a_bigger_photo_goes_through_our_jpeg_xl_encoder() {
        // (rf-jxl was made for thumbnails: a picture of several groups each way is the case to hold it to)
        let (w, h) = (1500, 1100);
        let rgba = sample(w, h, false);
        let bytes = encode_picture(Picture { width: w, height: h, rgba: &rgba }, PictureFormat::Jxl, &PictureOptions::default()).unwrap();
        let img = jxl_oxide::JxlImage::builder().read(Cursor::new(&bytes)).unwrap();
        assert_eq!((img.width(), img.height()), (w, h));
        let frame = img.render_frame(0).expect("the reference decoder renders it");
        let fb = frame.image_all_channels();
        let buf = fb.buf();
        let ch = fb.channels();
        // the gradient comes back close: red rises along x, green along y
        let at = |x: usize, y: usize, c: usize| buf[(y * w as usize + x) * ch + c];
        assert!((at(1400, 10, 0) - at(100, 10, 0)) > 0.5, "red rises along the row");
        assert!((at(10, 1000, 1) - at(10, 100, 1)) > 0.5, "green rises down the column");
    }

    /// How long each target takes for a photo of a camera's size, and how big the file is:
    /// `cargo test -p rf-convert --release -- --ignored --nocapture a_24_megapixel`
    #[test]
    #[ignore = "a measurement: a few seconds in a release build, minutes in a debug one"]
    fn a_24_megapixel_photo_in_every_target() {
        let (w, h) = (6000u32, 4000u32);
        // a gradient with fine noise on it, so that the encoders have a photo's kind of work
        let mut rgba = Vec::with_capacity((w * h * 4) as usize);
        let mut seed = 0x2545_F491u32;
        for y in 0..h {
            for x in 0..w {
                seed ^= seed << 13;
                seed ^= seed >> 17;
                seed ^= seed << 5;
                let n = (seed & 15) as u32;
                rgba.extend_from_slice(&[((x * 240 / w) + n) as u8, ((y * 240 / h) + n) as u8, (((x + y) * 120 / (w + h)) + n) as u8, 255]);
            }
        }
        for f in PictureFormat::ALL {
            let t = std::time::Instant::now();
            let bytes = encode_picture(Picture { width: w, height: h, rgba: &rgba }, f, &PictureOptions::default()).unwrap();
            println!("{:<8} {:>7.0} ms {:>8.1} MB", f.label(), t.elapsed().as_secs_f64() * 1000.0, bytes.len() as f64 / 1_048_576.0);
        }
    }

    #[test]
    fn wrong_data_is_refused_not_written() {
        let bad = Picture { width: 10, height: 10, rgba: &[0u8; 12] };
        assert!(encode_picture(bad, PictureFormat::Png, &PictureOptions::default()).is_err());
        let empty = Picture { width: 0, height: 10, rgba: &[] };
        assert!(encode_picture(empty, PictureFormat::Png, &PictureOptions::default()).is_err());
    }

    #[test]
    fn a_file_is_never_replaced_the_name_counts_up() {
        let d = tmp("names");
        std::fs::write(d.join("photo.png"), b"the user's own file").unwrap();
        let a = write_new(&d, "photo.png", b"one").unwrap();
        let b = write_new(&d, "photo.png", b"two").unwrap();
        assert_eq!(a.file_name().unwrap(), "photo (2).png");
        assert_eq!(b.file_name().unwrap(), "photo (3).png");
        assert_eq!(std::fs::read(d.join("photo.png")).unwrap(), b"the user's own file");
        assert_eq!(std::fs::read(&b).unwrap(), b"two");
        // a name with no extension, and one that begins with a dot
        std::fs::write(d.join("LICENSE"), b"x").unwrap();
        assert_eq!(write_new(&d, "LICENSE", b"y").unwrap().file_name().unwrap(), "LICENSE (2)");
        std::fs::write(d.join(".env"), b"x").unwrap();
        assert_eq!(write_new(&d, ".env", b"y").unwrap().file_name().unwrap(), ".env (2)");
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn the_target_name_is_the_sources_name_with_the_new_extension() {
        assert_eq!(target_name(Path::new(r"C:\p\IMG_0001.HEIC"), "jpg"), "IMG_0001.jpg");
        assert_eq!(target_name(Path::new("a.b.png"), "webp"), "a.b.webp");
        assert_eq!(ext_of(Path::new(r"C:\p\IMG_0001.HEIC")), "heic");
        assert_eq!(ext_of(Path::new("noext")), "");
    }
}