rosier 0.5.2

A fast picture and video viewer for large folders
//! Background workers that make grid thumbnails, nearest tiles first.
//!
//! The UI replaces the queue every frame with what is on screen (plus the
//! band just past it), so after a PageDown the workers move straight to the
//! new rows instead of finishing a backlog of rows the user already left.
//! Slow work (video frames, PNGs that must be decoded at full size) runs on
//! a few separate workers so it can never hold up cache hits and JPEGs.

use std::collections::{HashSet, VecDeque};
use std::sync::{Arc, Condvar, Mutex};

use crate::media::Entry;
use crate::thumb;
use crate::turbo::Bgra;

const HEAVY_WORKERS: usize = 4;

#[derive(Clone)]
pub struct Job {
    pub i: usize,
    pub entry: Entry,
    pub side: u32,
    pub epoch: u64,
}

impl Job {
    fn key(&self) -> (usize, u32, u64) {
        (self.i, self.side, self.epoch)
    }
}

pub struct Done {
    pub i: usize,
    pub side: u32,
    pub epoch: u64,
    /// None when the file could not be read.
    pub image: Option<Bgra>,
}

#[derive(Default)]
struct State {
    light: VecDeque<Job>,
    heavy: VecDeque<Job>,
    /// Keys the UI still wants; anything else is dropped when dequeued.
    wanted: HashSet<(usize, u32, u64)>,
    /// Keys a worker is working on, so they are not started twice.
    running: HashSet<(usize, u32, u64)>,
}

struct Shared {
    state: Mutex<State>,
    light_cv: Condvar,
    heavy_cv: Condvar,
}

pub struct Pool {
    shared: Arc<Shared>,
}

impl Pool {
    pub fn start(light_workers: usize) -> (Pool, async_channel::Receiver<Done>) {
        let shared = Arc::new(Shared {
            state: Mutex::new(State::default()),
            light_cv: Condvar::new(),
            heavy_cv: Condvar::new(),
        });
        let (tx, rx) = async_channel::unbounded();
        // One worker for everything: thumbnails then reach the GPU in the
        // same order every run, which screenshot tests need (see serial()).
        let (light_workers, heavy_workers) = if serial() { (1, 0) } else { (light_workers, HEAVY_WORKERS) };
        for k in 0..light_workers.max(1) {
            let (shared, tx) = (shared.clone(), tx.clone());
            let _ = std::thread::Builder::new()
                .name(format!("rosier-thumb-{k}"))
                .spawn(move || worker(&shared, &tx, false));
        }
        for k in 0..heavy_workers {
            let (shared, tx) = (shared.clone(), tx.clone());
            let _ = std::thread::Builder::new()
                .name(format!("rosier-thumb-heavy-{k}"))
                .spawn(move || worker(&shared, &tx, true));
        }
        (Pool { shared }, rx)
    }

    /// Replaces all pending work with `jobs` (highest priority first).
    pub fn set_wanted(&self, jobs: Vec<Job>) {
        let mut st = self.shared.state.lock().unwrap_or_else(|e| e.into_inner());
        st.wanted = jobs.iter().map(Job::key).collect();
        st.light = jobs.into_iter().collect();
        // Heavy work waiting for a slot is kept only if still wanted.
        let State { heavy, wanted, .. } = &mut *st;
        heavy.retain(|j| wanted.contains(&j.key()));
        drop(st);
        self.shared.light_cv.notify_all();
        self.shared.heavy_cv.notify_all();
    }
}

fn next(shared: &Shared, heavy: bool) -> Job {
    let mut st = shared.state.lock().unwrap_or_else(|e| e.into_inner());
    loop {
        let job = if heavy { st.heavy.pop_front() } else { st.light.pop_front() };
        match job {
            Some(j) if st.wanted.contains(&j.key()) && !st.running.contains(&j.key()) => {
                st.running.insert(j.key());
                return j;
            }
            Some(_) => continue,
            None => {
                let cv = if heavy { &shared.heavy_cv } else { &shared.light_cv };
                st = cv.wait(st).unwrap_or_else(|e| e.into_inner());
            }
        }
    }
}

fn finish(shared: &Shared, key: (usize, u32, u64)) {
    let mut st = shared.state.lock().unwrap_or_else(|e| e.into_inner());
    st.running.remove(&key);
}

/// Screenshot tests (ROSIER_SERIAL_THUMBS, devtools builds) make every
/// thumbnail on one thread. gpui packs images into its texture atlas in the
/// order they arrive and samples a scaled image's edges together with its
/// neighbors there, so a different arrival order shifts a few edge pixels.
fn serial() -> bool {
    #[cfg(feature = "devtools")]
    {
        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
        *ON.get_or_init(|| std::env::var_os("ROSIER_SERIAL_THUMBS").is_some())
    }
    #[cfg(not(feature = "devtools"))]
    false
}

fn worker(shared: &Shared, tx: &async_channel::Sender<Done>, heavy: bool) {
    loop {
        let job = next(shared, heavy);
        let key = job.key();
        let done = |image: Option<Bgra>| Done { i: job.i, side: job.side, epoch: job.epoch, image };
        if !heavy {
            if let Some(b) = thumb::cached(&job.entry, job.side) {
                finish(shared, key);
                if tx.send_blocking(done(Some(b))).is_err() {
                    return;
                }
                continue;
            }
            if thumb::is_heavy(&job.entry) && !serial() {
                // Hand slow formats to the heavy workers and move on.
                let mut st = shared.state.lock().unwrap_or_else(|e| e.into_inner());
                st.running.remove(&key);
                if !st.heavy.iter().any(|j| j.key() == key) {
                    st.heavy.push_back(job);
                }
                drop(st);
                shared.heavy_cv.notify_one();
                continue;
            }
        }
        let image = thumb::make(&job.entry, job.side).ok();
        finish(shared, key);
        if tx.send_blocking(done(image)).is_err() {
            return;
        }
    }
}