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.

7.7 KB
Raw Blame
//! The converter's work on this system: a picture file is decoded here (the image crate, then Windows' own codecs for HEIC, AVIF
//! and the like: `look::decode`) and written by `rf_convert` next to the original. Nothing is ever replaced, and the shell's
//! thumbnail is never taken for the picture (`decode_whole`).
//!
//! Many files run side by side on a few threads of their own: a decoded 24-megapixel photo is about 100 MB, and one thread a core
//! would ask for gigabytes at once.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};

use rayon::prelude::*;
use rf_convert::{Picture, PictureFormat, PictureOptions};

/// One picture: `source` decoded, written as `format` into the folder it is in. Gives the new file.
pub fn picture(source: &Path, format: PictureFormat, options: &PictureOptions) -> anyhow::Result<PathBuf> {
    crate::shell::ensure_com();
    let decoded = crate::look::decode::decode_whole(source)?;
    let (frame, _) = decoded.frames.into_iter().next().ok_or_else(|| anyhow::anyhow!("the picture has no frame"))?;
    let mut rgba = frame.data;
    // (the decoders here give BGRA)
    for px in rgba.chunks_exact_mut(4) {
        px.swap(0, 2);
    }
    let bytes = rf_convert::encode_picture(Picture { width: frame.width, height: frame.height, rgba: &rgba }, format, options)?;
    drop(rgba);
    let dir = source.parent().ok_or_else(|| anyhow::anyhow!("{} has no folder", source.display()))?;
    Ok(rf_convert::write_new(dir, &rf_convert::target_name(source, format.ext()), &bytes)?)
}

/// What became of one file of a batch.
pub struct Outcome {
    pub source: PathBuf,
    /// The new file, or why there is none.
    pub result: anyhow::Result<PathBuf>,
}

/// How many pictures are worked on at once (see the top of this file).
fn workers() -> usize {
    (std::thread::available_parallelism().map_or(2, |n| n.get()) / 2).clamp(1, 6)
}

/// Converts `sources` to `format`, a few at a time. `progress(done, total, name)` is called from the workers as each file ends.
/// `cancel` stops the files not yet begun (one in work is finished: a half-written file is never left). The outcomes come in the
/// order of `sources`; a file that was not begun is not among them.
pub fn pictures(sources: &[PathBuf], format: PictureFormat, options: &PictureOptions, cancel: &AtomicBool, progress: &(dyn Fn(u32, u32, &str) + Sync)) -> Vec<Outcome> {
    let total = sources.len() as u32;
    let done = AtomicU32::new(0);
    let run = || {
        sources
            .par_iter()
            .filter_map(|source| {
                if cancel.load(Ordering::Relaxed) {
                    return None;
                }
                // (a decoder that panics on a broken file ends this file, not the batch. Only where panics unwind: the released
                // build aborts on a panic, here as for every picture decoder in the app; the lasting answer is a helper process)
                let result = std::panic::catch_unwind(|| picture(source, format, options)).unwrap_or_else(|_| Err(anyhow::anyhow!("the file could not be read as a picture")));
                let name = source.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
                progress(done.fetch_add(1, Ordering::Relaxed) + 1, total, &name);
                Some(Outcome { source: source.clone(), result })
            })
            .collect()
    };
    match rayon::ThreadPoolBuilder::new().num_threads(workers().min(sources.len().max(1))).thread_name(|i| format!("convert-{i}")).build() {
        Ok(pool) => pool.install(run),
        // (no threads to be had: one after the other on this one)
        Err(_) => run(),
    }
}

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

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

    /// A folder of this test's own with copies of the sample pictures.
    fn folder(name: &str, files: &[&str]) -> (PathBuf, Vec<PathBuf>) {
        let dir = std::env::temp_dir().join(format!("rf-convert-win-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let copies = files
            .iter()
            .map(|f| {
                let to = dir.join(Path::new(f).file_name().unwrap());
                std::fs::copy(data(f), &to).unwrap();
                to
            })
            .collect();
        (dir, copies)
    }

    #[test]
    fn a_picture_is_written_next_to_its_original_and_the_original_stays() {
        let (dir, files) = folder("one", &["look/a.jpg"]);
        let before = std::fs::read(&files[0]).unwrap();
        let out = picture(&files[0], PictureFormat::Png, &PictureOptions::default()).unwrap();
        assert_eq!(out, dir.join("a.png"));
        assert_eq!(std::fs::read(&files[0]).unwrap(), before, "the original is not touched");
        let (a, b) = (image::open(&files[0]).unwrap(), image::open(&out).unwrap());
        assert_eq!((a.width(), a.height()), (b.width(), b.height()), "the whole picture, not a thumbnail of it");
        // a second run keeps the first result
        let again = picture(&files[0], PictureFormat::Png, &PictureOptions::default()).unwrap();
        assert_eq!(again, dir.join("a (2).png"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_batch_reports_every_file_and_a_broken_one_does_not_stop_the_rest() {
        let (dir, mut files) = folder("batch", &["look/a.png", "look/a.jpg", "look/a.webp", "look/a.gif"]);
        let broken = dir.join("broken.png");
        std::fs::write(&broken, b"this is no picture").unwrap();
        files.push(broken.clone());
        let calls = AtomicU32::new(0);
        let out = pictures(&files, PictureFormat::Jpeg, &PictureOptions::default(), &AtomicBool::new(false), &|done, total, _| {
            assert!(done >= 1 && done <= total && total == 5);
            calls.fetch_add(1, Ordering::Relaxed);
        });
        assert_eq!(calls.load(Ordering::Relaxed), 5);
        assert_eq!(out.len(), 5);
        for o in &out {
            if o.source == broken {
                assert!(o.result.is_err(), "a file that is no picture is an error, not a small thumbnail");
            } else {
                let made = o.result.as_ref().unwrap_or_else(|e| panic!("{}: {e:#}", o.source.display()));
                assert!(image::open(made).is_ok(), "{}", made.display());
            }
        }
        // a.jpg was a JPEG already: its copy got a number, the original stayed
        assert!(dir.join("a (2).jpg").is_file() || dir.join("a (3).jpg").is_file());
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The result carries no EXIF, so a photo taken with the camera turned has to be written the way it is seen.
    #[test]
    fn a_photo_the_camera_marked_as_turned_is_written_upright() {
        let (dir, files) = folder("turned", &["look/rot6.jpg"]);
        let stored = image::open(&files[0]).unwrap();
        let out = picture(&files[0], PictureFormat::Png, &PictureOptions::default()).unwrap();
        let made = image::open(&out).unwrap();
        assert_ne!(stored.width(), stored.height(), "the sample has to be oblong for this to say anything");
        assert_eq!((made.width(), made.height()), (stored.height(), stored.width()), "orientation 6 is a quarter turn");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_cancelled_batch_begins_nothing() {
        let (dir, files) = folder("cancel", &["look/a.png", "look/a.jpg"]);
        let out = pictures(&files, PictureFormat::Bmp, &PictureOptions::default(), &AtomicBool::new(true), &|_, _, _| panic!("nothing was to run"));
        assert!(out.is_empty());
        assert!(!dir.join("a.bmp").exists());
        let _ = std::fs::remove_dir_all(&dir);
    }
}