rosier 0.5.2

A fast picture and video viewer for large folders
//! Turns the list of shown files into what the grid draws: rows of `cols`
//! tiles, one continuous wall with no headers.

use std::path::Path;

use crate::db::Source;
use crate::media::Entry;

const NOT_SHOWN: (usize, usize) = (usize::MAX, usize::MAX);

#[derive(Default)]
pub struct Layout {
    /// Entry indices on each row, left to right.
    pub rows: Vec<Vec<usize>>,
    /// For every entry index: (row, column) of its tile, or NOT_SHOWN.
    place: Vec<(usize, usize)>,
    /// Entry indices in the order the grid shows them.
    pub order: Vec<usize>,
    /// Position of each entry in `order` (usize::MAX when not shown).
    order_pos: Vec<usize>,
}

/// How many tiles of about `target` px fit in `avail` px with `gap` between
/// them, and the resulting pitch (tile plus gap) so the row fills the width.
pub fn columns(avail: f32, target: f32, gap: f32) -> (usize, f32) {
    let cols = ((avail + gap) / (target + gap)).floor().max(1.0) as usize;
    (cols, ((avail + gap) / cols as f32).floor())
}

/// Splits a scroll position in pixels into a row index and the offset into
/// that row, for rows `row_h` px tall.
pub fn row_offset(top: f32, row_h: f32) -> (usize, f32) {
    let top = top.max(0.0);
    let ix = (top / row_h).floor();
    (ix as usize, top - ix * row_h)
}

/// The library's scrollbar: a thumb in a track `track` px tall, for a list
/// `content` px tall seen through `view` px and scrolled `top` px down.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Scrollbar {
    /// Height of the thumb: the part of the list on screen, but at least
    /// 32 px (or the whole track, when shorter) so it can be grabbed.
    pub thumb: f32,
    /// How far the thumb's top is below the track's.
    pub thumb_y: f32,
    /// How far the thumb can move.
    pub room: f32,
    /// How far the list can scroll.
    pub max_scroll: f32,
}

impl Scrollbar {
    /// None when the whole list fits and there is nothing to scroll.
    pub fn new(track: f32, view: f32, content: f32, top: f32) -> Option<Self> {
        if view <= 0.0 || content <= view + 1.0 {
            return None;
        }
        let max_scroll = content - view;
        let thumb = (track * view / content).clamp(32.0_f32.min(track), track.max(0.0));
        let room = (track - thumb).max(1.0);
        let thumb_y = room * top.clamp(0.0, max_scroll) / max_scroll;
        Some(Scrollbar { thumb, thumb_y, room, max_scroll })
    }

    /// The scroll position that puts the thumb's top at `y` (from the
    /// track's top) less `grab`, where the pointer holds the thumb.
    pub fn scroll_for(&self, y: f32, grab: f32) -> f32 {
        ((y - grab) / self.room).clamp(0.0, 1.0) * self.max_scroll
    }
}

/// Folder title as the user thinks of it: relative to its source, or the
/// source's own name for files at the source root.
pub fn folder_title(dir: &Path, sources: &[Source]) -> String {
    for s in sources {
        if let Ok(rel) = dir.strip_prefix(&s.path) {
            let name = source_name(s);
            return if rel.as_os_str().is_empty() { name } else { format!("{name} / {}", rel.display()) };
        }
    }
    dir.display().to_string()
}

pub fn source_name(s: &Source) -> String {
    s.path.file_name().map_or_else(|| s.path.display().to_string(), |n| n.to_string_lossy().into_owned())
}

/// Wraps `shown` (entry indices, already in display order) into rows of
/// `cols` tiles.
pub fn build(entries: &[Entry], shown: &[usize], cols: usize) -> Layout {
    let cols = cols.max(1);
    let mut layout = Layout {
        place: vec![NOT_SHOWN; entries.len()],
        order_pos: vec![usize::MAX; entries.len()],
        ..Default::default()
    };
    for chunk in shown.chunks(cols) {
        let r = layout.rows.len();
        for (c, &i) in chunk.iter().enumerate() {
            layout.place[i] = (r, c);
            layout.order_pos[i] = layout.order.len();
            layout.order.push(i);
        }
        layout.rows.push(chunk.to_vec());
    }
    layout
}

impl Layout {
    pub fn contains(&self, i: usize) -> bool {
        self.place.get(i).is_some_and(|p| *p != NOT_SHOWN)
    }

    pub fn row_of(&self, i: usize) -> Option<usize> {
        self.place.get(i).filter(|p| **p != NOT_SHOWN).map(|p| p.0)
    }

    pub fn position(&self, i: usize) -> Option<usize> {
        self.order_pos.get(i).copied().filter(|&p| p != usize::MAX)
    }

    /// The entry `step` rows away, keeping the column where the row is long
    /// enough (the last row may be short).
    fn vertical(&self, from: usize, step: isize) -> Option<usize> {
        let (r, c) = *self.place.get(from).filter(|p| **p != NOT_SHOWN)?;
        let r = r.checked_add_signed(step)?;
        let items = self.rows.get(r)?;
        items.get(c.min(items.len().checked_sub(1)?)).copied()
    }

    /// The entry at (`x`, `y`) in the list's viewport when the list is
    /// scrolled `top` px down and rows are `row_h` px square tiles, with
    /// where in its tile the point falls (fraction of the row height).
    pub fn hit(&self, top: f32, x: f32, y: f32, row_h: f32) -> Option<(usize, f32)> {
        let s = top + y;
        let row = (s / row_h).floor().max(0.0) as usize;
        let frac = (s - row as f32 * row_h) / row_h;
        let items = self.rows.get(row)?;
        let col = ((x / row_h).floor().max(0.0) as usize).min(items.len().checked_sub(1)?);
        Some((items[col], frac))
    }

    /// Like `vertical`, but stops at the first or last row instead of
    /// failing, for PageUp/PageDown.
    pub fn vertical_clamped(&self, from: usize, step: isize) -> usize {
        let Some((r, _)) = self.place.get(from).filter(|p| **p != NOT_SHOWN) else { return from };
        let last = self.rows.len().saturating_sub(1) as isize;
        let target = (*r as isize + step).clamp(0, last) - *r as isize;
        self.vertical(from, target).unwrap_or(from)
    }
}

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

    #[test]
    fn the_scrollbar_thumb_shows_the_part_on_screen() {
        // Everything fits: no scrollbar.
        assert_eq!(Scrollbar::new(400.0, 500.0, 500.0, 0.0), None);
        assert_eq!(Scrollbar::new(400.0, 0.0, 900.0, 0.0), None);
        // A quarter on screen: a quarter-long thumb, at the bottom at the end.
        let s = Scrollbar::new(400.0, 500.0, 2000.0, 1500.0).unwrap();
        assert_eq!((s.thumb, s.thumb_y, s.room, s.max_scroll), (100.0, 300.0, 300.0, 1500.0));
        // A long list keeps a thumb big enough to grab.
        assert_eq!(Scrollbar::new(400.0, 500.0, 1_000_000.0, 0.0).unwrap().thumb, 32.0);
        // A track shorter than that: the thumb fills it.
        assert_eq!(Scrollbar::new(20.0, 500.0, 2000.0, 0.0).unwrap().thumb, 20.0);
        // Scrolled past the end (the list shrank): the thumb stays in the track.
        assert_eq!(Scrollbar::new(400.0, 500.0, 2000.0, 9999.0).unwrap().thumb_y, 300.0);
    }

    #[test]
    fn dragging_the_thumb_scrolls_in_step_and_stops_at_the_ends() {
        let s = Scrollbar::new(400.0, 500.0, 2000.0, 0.0).unwrap();
        // Held 10 px below its top, moved to 160: the thumb's top at 150.
        assert_eq!(s.scroll_for(160.0, 10.0), 750.0);
        assert_eq!(s.scroll_for(-50.0, 10.0), 0.0);
        assert_eq!(s.scroll_for(900.0, 10.0), 1500.0);
    }
    use crate::media::Kind;
    use std::path::PathBuf;

    fn e(p: &str) -> Entry {
        Entry { id: 0, path: PathBuf::from(p), kind: Kind::Image, size: 0, mtime: 0 }
    }

    fn entries(n: usize) -> Vec<Entry> {
        (0..n).map(|i| e(&format!("/s/{i}.jpg"))).collect()
    }

    #[test]
    fn wraps_rows_and_moves_between_them() {
        let l = build(&entries(5), &[0, 1, 2, 3, 4], 2);
        // [0,1], [2,3], [4]
        assert_eq!(l.rows, vec![vec![0, 1], vec![2, 3], vec![4]]);
        assert_eq!(l.row_of(4), Some(2));
        assert_eq!(l.order, vec![0, 1, 2, 3, 4]);
        assert_eq!(l.vertical(1, 1), Some(3));
        // The short last row keeps the nearest column.
        assert_eq!(l.vertical(3, 1), Some(4));
        assert_eq!(l.vertical(4, 1), None);
        assert_eq!(l.vertical(0, -1), None);
        assert_eq!(l.vertical_clamped(1, 10), 4);
        assert_eq!(l.vertical_clamped(4, -10), 0);
    }

    #[test]
    fn hidden_entries_are_not_placed() {
        let l = build(&entries(2), &[1], 4);
        assert!(!l.contains(0));
        assert!(l.contains(1));
        assert_eq!(l.rows.len(), 1);
        assert_eq!(l.vertical(0, 1), None);
        assert_eq!(l.position(1), Some(0));
        assert_eq!(l.position(0), None);
    }

    #[test]
    fn columns_fill_the_width() {
        assert_eq!(columns(1000.0, 200.0, 8.0), (4, 252.0));
        assert_eq!(columns(50.0, 200.0, 8.0), (1, 58.0), "always at least one column");
    }

    #[test]
    fn scroll_positions_split_into_row_and_offset() {
        assert_eq!(row_offset(250.0, 100.0), (2, 50.0));
        assert_eq!(row_offset(-5.0, 100.0), (0, 0.0));
    }

    #[test]
    fn hit_finds_the_tile_under_a_point() {
        let l = build(&entries(5), &[0, 1, 2, 3, 4], 2);
        // Rows are 100 px; scrolled 150 px down.
        assert_eq!(l.hit(150.0, 120.0, 10.0, 100.0), Some((3, 0.6)));
        // Past the short last row's end: its last tile.
        assert_eq!(l.hit(0.0, 150.0, 250.0, 100.0), Some((4, 0.5)));
        assert_eq!(l.hit(0.0, 0.0, 400.0, 100.0), None);
    }

    #[test]
    fn folder_titles_are_relative_to_their_source() {
        let s = vec![Source { id: 1, path: PathBuf::from("/media/Pictures") }];
        assert_eq!(folder_title(Path::new("/media/Pictures"), &s), "Pictures");
        assert_eq!(folder_title(Path::new("/media/Pictures/2024/Trip"), &s), "Pictures / 2024/Trip");
        assert_eq!(folder_title(Path::new("/elsewhere"), &s), "/elsewhere");
    }
}