use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::db::{Source, Watch};
use crate::media::{self, Entry, Kind};
use crate::pane::PaneSource;
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Scope {
All,
Favorites,
Rated,
Continue,
Folder(PathBuf),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum KindFilter {
All,
Photos,
Videos,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SortBy {
Name,
Date,
Size,
Taken,
}
const RATED_MIN: u8 = 3;
const HEAT_BINS: usize = 100;
const RESUME_MARGIN: f64 = 10.0;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Counts {
pub all: usize,
pub photos: usize,
pub videos: usize,
}
impl Counts {
pub fn of(&self, kind: KindFilter) -> usize {
match kind {
KindFilter::All => self.all,
KindFilter::Photos => self.photos,
KindFilter::Videos => self.videos,
}
}
fn add(&mut self, kind: Kind) {
self.all += 1;
match kind {
Kind::Image => self.photos += 1,
Kind::Video => self.videos += 1,
Kind::Book => {}
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct SideFolder {
pub name: String,
pub path: PathBuf,
pub count: Counts,
}
#[derive(Default)]
pub struct Index {
entries: Arc<Vec<Entry>>,
id_index: HashMap<i64, usize>,
dirs: HashMap<PathBuf, Vec<usize>>,
source_counts: Vec<Counts>,
side_folders: Vec<Vec<SideFolder>>,
}
impl Index {
pub fn build(sources: &[Source], items: Vec<Entry>) -> Self {
let id_index = items.iter().enumerate().map(|(i, e)| (e.id, i)).collect();
let mut dirs: HashMap<PathBuf, Vec<usize>> = HashMap::new();
let mut run: Option<(&Path, Vec<usize>)> = None;
for (i, e) in items.iter().enumerate() {
let parent = e.path.parent().unwrap_or(Path::new(""));
match &mut run {
Some((dir, files)) if *dir == parent => files.push(i),
_ => {
if let Some((dir, files)) = run.replace((parent, vec![i])) {
dirs.entry(dir.to_path_buf()).or_default().extend(files);
}
}
}
}
if let Some((dir, files)) = run {
dirs.entry(dir.to_path_buf()).or_default().extend(files);
}
for files in dirs.values_mut() {
if !files.is_sorted() {
files.sort_unstable();
}
}
let (source_counts, side_folders) = sidebar(sources, &dirs, &items);
Index { entries: Arc::new(items), id_index, dirs, source_counts, side_folders }
}
}
fn sidebar(
sources: &[Source],
dirs: &HashMap<PathBuf, Vec<usize>>,
items: &[Entry],
) -> (Vec<Counts>, Vec<Vec<SideFolder>>) {
let mut counts = vec![Counts::default(); sources.len()];
let mut folders: Vec<HashMap<String, Counts>> = vec![HashMap::new(); sources.len()];
for (dir, files) in dirs {
let Some((si, rel)) =
sources.iter().enumerate().find_map(|(si, s)| Some((si, dir.strip_prefix(&s.path).ok()?)))
else {
continue;
};
let first = rel.components().next().map(|c| c.as_os_str().to_string_lossy().into_owned());
for &f in files {
counts[si].add(items[f].kind);
if let Some(first) = &first {
folders[si].entry(first.clone()).or_default().add(items[f].kind);
}
}
}
let side = folders
.into_iter()
.zip(sources)
.map(|(m, src)| {
let mut v: Vec<SideFolder> =
m.into_iter().map(|(name, count)| SideFolder { path: src.path.join(&name), name, count }).collect();
v.sort_by(|a, b| media::natural_cmp(&a.path, &b.path));
v
})
.collect();
(counts, side)
}
#[derive(Default)]
pub struct Library {
pub sources: Vec<Source>,
pub entries: Arc<Vec<Entry>>,
id_index: HashMap<i64, usize>,
dirs: HashMap<PathBuf, Vec<usize>>,
pub favorites: Vec<i64>,
favorite_set: HashSet<i64>,
pub excluded: Vec<PathBuf>,
pub ratings: HashMap<i64, u8>,
pub taken: HashMap<i64, i64>,
pub watch: HashMap<i64, Watch>,
pub heat: HashMap<i64, Vec<f32>>,
pub source_counts: Vec<Counts>,
pub side_folders: Vec<Vec<SideFolder>>,
}
impl Library {
pub fn replace(&mut self, sources: Vec<Source>, index: Index, favorites: Vec<i64>, excluded: Vec<PathBuf>) {
self.sources = sources;
self.favorites = favorites;
self.excluded = excluded;
self.set_index(index);
}
pub fn set_index(&mut self, index: Index) {
let Index { entries, id_index, dirs, source_counts, side_folders } = index;
self.entries = entries;
self.id_index = id_index;
self.dirs = dirs;
self.source_counts = source_counts;
self.side_folders = side_folders;
self.favorite_set = self.favorites.iter().copied().collect();
}
pub fn find(&self, path: &Path) -> Option<usize> {
self.entries.binary_search_by(|e| media::natural_cmp(&e.path, path)).ok()
}
pub fn path(&self, i: usize) -> Option<&Path> {
self.entries.get(i).map(|e| e.path.as_path())
}
pub fn is_favorite(&self, i: usize) -> bool {
self.entries.get(i).is_some_and(|e| self.favorite_set.contains(&e.id))
}
pub fn toggle_favorite(&mut self, i: usize) -> Option<(i64, bool)> {
let id = self.entries.get(i)?.id;
let on = self.favorite_set.insert(id);
if on {
self.favorites.push(id);
} else {
self.favorite_set.remove(&id);
self.favorites.retain(|&f| f != id);
}
Some((id, on))
}
pub fn count_kind(&self, v: &[usize], kind: KindFilter) -> usize {
match kind {
KindFilter::All => v.len(),
KindFilter::Photos => v.iter().filter(|&&i| self.entries[i].kind == Kind::Image).count(),
KindFilter::Videos => v.iter().filter(|&&i| self.entries[i].kind == Kind::Video).count(),
}
}
pub fn favorite_entries(&self) -> Vec<usize> {
self.favorites.iter().filter_map(|id| self.id_index.get(id).copied()).collect()
}
pub fn rating(&self, i: usize) -> u8 {
self.entries.get(i).and_then(|e| self.ratings.get(&e.id)).copied().unwrap_or(0)
}
pub fn set_rating(&mut self, i: usize, stars: u8) -> Option<(i64, u8)> {
let id = self.entries.get(i)?.id;
let stars = stars.min(5);
if stars == 0 {
self.ratings.remove(&id);
} else {
self.ratings.insert(id, stars);
}
Some((id, stars))
}
pub fn rated_entries(&self) -> Vec<usize> {
let mut v: Vec<usize> = self
.ratings
.iter()
.filter(|&(_, &s)| s >= RATED_MIN)
.filter_map(|(id, _)| self.id_index.get(id).copied())
.collect();
v.sort_unstable();
v
}
pub fn without_taken(&self) -> Vec<Entry> {
self.entries.iter().filter(|e| e.kind == Kind::Image && !self.taken.contains_key(&e.id)).cloned().collect()
}
fn taken_or_modified(&self, i: usize) -> i64 {
let e = &self.entries[i];
self.taken.get(&e.id).copied().filter(|&t| t != 0).unwrap_or(e.mtime as i64)
}
pub fn duration(&self, i: usize) -> Option<f64> {
self.watch.get(&self.entries.get(i)?.id)?.duration
}
pub fn resume_at(&self, i: usize) -> Option<f64> {
let w = self.watch.get(&self.entries.get(i)?.id)?;
(w.position > 0.0).then_some(w.position)
}
pub fn progress(&self, i: usize) -> Option<f32> {
let w = self.watch.get(&self.entries.get(i)?.id)?;
let d = w.duration.filter(|d| *d > 0.0)?;
(w.position > 0.0).then(|| (w.position / d).clamp(0.0, 1.0) as f32)
}
pub fn record(&mut self, i: usize, pos: f64, dur: f64, now: i64) -> Option<(i64, Watch)> {
let id = self.entries.get(i)?.id;
let w = self.watch.entry(id).or_default();
if dur > 0.0 {
w.duration = Some(dur);
}
let near_end = dur > 0.0 && (pos >= dur - RESUME_MARGIN || pos >= dur * 0.95);
let position = if pos < RESUME_MARGIN || near_end { 0.0 } else { pos };
if position == 0.0 && w.position == 0.0 {
return None;
}
w.position = position;
w.at = now;
Some((id, *w))
}
pub fn add_watched(&mut self, i: usize, pos: f64, dur: f64, secs: f64) -> Option<i64> {
if dur <= 0.0 || secs <= 0.0 || !(0.0..dur).contains(&pos) {
return None;
}
let id = self.entries.get(i)?.id;
let bins = self.heat.entry(id).or_insert_with(|| vec![0.0; HEAT_BINS]);
let b = ((pos * HEAT_BINS as f64 / dur) as usize).min(HEAT_BINS - 1);
bins[b] += secs as f32;
Some(id)
}
pub fn heat_profile(&self, i: usize) -> Option<Vec<f32>> {
let e = self.entries.get(i)?;
let bins = self.heat.get(&e.id)?;
let per_bin = (self.watch.get(&e.id)?.duration? / HEAT_BINS as f64) as f32;
let smooth: Vec<f32> = (0..bins.len())
.map(|k| {
let lo = k.saturating_sub(1);
let hi = (k + 2).min(bins.len());
bins[lo..hi].iter().sum::<f32>() / (hi - lo) as f32
})
.collect();
let max = smooth.iter().copied().fold(0.0, f32::max);
if per_bin <= 0.0 || max < 1.8 * per_bin {
return None;
}
Some(smooth.iter().map(|b| b / max).collect())
}
pub fn set_duration(&mut self, id: i64, dur: f64) {
self.watch.entry(id).or_default().duration = Some(dur);
}
pub fn without_duration(&self) -> Vec<Entry> {
self.entries
.iter()
.filter(|e| e.kind == Kind::Video && self.watch.get(&e.id).is_none_or(|w| w.duration.is_none()))
.cloned()
.collect()
}
pub fn continue_entries(&self) -> Vec<usize> {
let mut v: Vec<(i64, usize)> = self
.watch
.iter()
.filter(|(_, w)| w.position > 0.0)
.filter_map(|(id, w)| Some((w.at, *self.id_index.get(id)?)))
.collect();
v.sort_unstable_by(|a, b| b.cmp(a));
v.into_iter().map(|(_, i)| i).collect()
}
pub fn shown(&self, scope: &Scope, kind: KindFilter, sort: SortBy) -> Vec<usize> {
let e = &self.entries;
let mut shown: Vec<usize> = match scope {
Scope::All => (0..e.len()).collect(),
Scope::Favorites => self.favorite_entries(),
Scope::Rated => self.rated_entries(),
Scope::Continue => self.continue_entries(),
Scope::Folder(p) => self
.dirs
.iter()
.filter(|(d, _)| d.starts_with(p))
.flat_map(|(_, files)| files.iter().copied())
.collect(),
};
shown.retain(|&i| match kind {
KindFilter::All => true,
KindFilter::Photos => e[i].kind == Kind::Image,
KindFilter::Videos => e[i].kind == Kind::Video,
});
match sort {
SortBy::Name if *scope == Scope::Rated => {
shown.sort_unstable_by_key(|&i| (std::cmp::Reverse(self.rating(i)), i))
}
SortBy::Name if !matches!(scope, Scope::Favorites | Scope::Continue) => shown.sort_unstable(),
SortBy::Name => {}
SortBy::Date => shown.sort_by_key(|&i| std::cmp::Reverse(e[i].mtime)),
SortBy::Size => shown.sort_by_key(|&i| std::cmp::Reverse(e[i].size)),
SortBy::Taken => shown.sort_by_key(|&i| std::cmp::Reverse(self.taken_or_modified(i))),
}
shown
}
pub fn items_for(&self, source: &PaneSource) -> Vec<usize> {
match source {
PaneSource::Favorites => self.favorite_entries(),
PaneSource::Folder(dir) => self.dirs.get(dir).cloned().unwrap_or_default(),
}
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub fn entry(id: i64, path: &str, kind: Kind, size: u64, mtime: u64) -> Entry {
Entry { id, path: PathBuf::from(path), kind, size, mtime }
}
fn sample() -> Library {
let mut items = vec![
entry(1, "/p/a.jpg", Kind::Image, 10, 3),
entry(2, "/p/trip/b.jpg", Kind::Image, 30, 1),
entry(3, "/p/trip/c.mp4", Kind::Video, 20, 2),
entry(4, "/p/trip/day2/d.jpg", Kind::Image, 5, 5),
entry(5, "/v/clip.mkv", Kind::Video, 50, 4),
];
items.sort_by(|a, b| media::natural_cmp(&a.path, &b.path));
let sources = vec![Source { id: 1, path: "/p".into() }, Source { id: 2, path: "/v".into() }];
let index = Index::build(&sources, items);
let mut lib = Library::default();
lib.replace(sources, index, vec![5, 2], Vec::new());
lib
}
fn ids(lib: &Library, v: &[usize]) -> Vec<i64> {
v.iter().map(|&i| lib.entries[i].id).collect()
}
#[test]
fn videos_resume_where_they_stopped_unless_at_either_end() {
let mut lib = sample();
let clip = lib.find(Path::new("/v/clip.mkv")).unwrap();
let c = lib.find(Path::new("/p/trip/c.mp4")).unwrap();
assert_eq!(lib.record(clip, 3.0, 600.0, 1), None, "the first seconds are not kept");
assert_eq!(lib.resume_at(clip), None);
assert_eq!(lib.duration(clip), Some(600.0), "the length is kept anyway");
let (id, w) = lib.record(clip, 120.0, 600.0, 2).unwrap();
assert_eq!((id, w.position, w.at), (5, 120.0, 2));
assert_eq!(lib.resume_at(clip), Some(120.0));
assert_eq!(lib.progress(clip), Some(0.2));
lib.record(c, 50.0, 100.0, 3);
assert_eq!(ids(&lib, &lib.shown(&Scope::Continue, KindFilter::All, SortBy::Name)), vec![3, 5]);
let (_, w) = lib.record(clip, 595.0, 600.0, 4).unwrap();
assert_eq!(w.position, 0.0);
assert_eq!(lib.resume_at(clip), None);
assert_eq!(ids(&lib, &lib.continue_entries()), vec![3]);
assert_eq!(lib.record(clip, 0.5, 600.0, 5), None, "nothing new to save");
}
#[test]
fn parts_watched_again_stand_out() {
let mut lib = sample();
let clip = lib.find(Path::new("/v/clip.mkv")).unwrap();
lib.set_duration(5, 100.0);
for s in 0..100 {
lib.add_watched(clip, s as f64, 100.0, 1.0);
}
assert_eq!(lib.heat_profile(clip), None);
for _ in 0..2 {
for s in 40..50 {
lib.add_watched(clip, s as f64, 100.0, 1.0);
}
}
let p = lib.heat_profile(clip).unwrap();
assert_eq!(p.len(), HEAT_BINS);
assert_eq!(p[45], 1.0);
assert!((p[10] - 1.0 / 3.0).abs() < 1e-6);
assert!(p[40] > p[30] && p[40] < 1.0, "the edges of the stretch are smoothed");
assert_eq!(lib.add_watched(clip, 120.0, 100.0, 1.0), None, "past the end");
assert_eq!(lib.add_watched(clip, 10.0, 0.0, 1.0), None, "length unknown");
}
#[test]
fn video_lengths_are_read_once() {
let mut lib = sample();
let ids_missing = |lib: &Library| lib.without_duration().iter().map(|e| e.id).collect::<Vec<_>>();
assert_eq!(ids_missing(&lib), vec![3, 5], "only videos");
lib.set_duration(5, 42.0);
assert_eq!(ids_missing(&lib), vec![3]);
assert_eq!(lib.duration(lib.find(Path::new("/v/clip.mkv")).unwrap()), Some(42.0));
}
#[test]
fn scope_kind_and_sort_pick_the_grid() {
let lib = sample();
let all = lib.shown(&Scope::All, KindFilter::All, SortBy::Name);
assert_eq!(ids(&lib, &all), vec![1, 2, 3, 4, 5]);
let trip = lib.shown(&Scope::Folder("/p/trip".into()), KindFilter::All, SortBy::Name);
assert_eq!(ids(&lib, &trip), vec![2, 3, 4], "a folder includes its subfolders");
let videos = lib.shown(&Scope::All, KindFilter::Videos, SortBy::Name);
assert_eq!(ids(&lib, &videos), vec![3, 5]);
let photos = lib.shown(&Scope::All, KindFilter::Photos, SortBy::Size);
assert_eq!(ids(&lib, &photos), vec![2, 1, 4], "largest first");
let newest = lib.shown(&Scope::All, KindFilter::All, SortBy::Date);
assert_eq!(ids(&lib, &newest), vec![4, 5, 1, 3, 2], "newest first");
let favs = lib.shown(&Scope::Favorites, KindFilter::All, SortBy::Name);
assert_eq!(ids(&lib, &favs), vec![5, 2], "favorites keep the order they were added");
}
#[test]
fn a_folder_pane_plays_only_that_folder() {
let lib = sample();
let items = lib.items_for(&PaneSource::Folder("/p/trip".into()));
assert_eq!(ids(&lib, &items), vec![2, 3]);
assert_eq!(ids(&lib, &lib.items_for(&PaneSource::Favorites)), vec![5, 2]);
}
#[test]
fn rated_lists_three_stars_and_up_with_the_most_first() {
let mut lib = sample();
let at = |lib: &Library, p: &str| lib.find(Path::new(p)).unwrap();
let (a, b, d, clip) =
(at(&lib, "/p/a.jpg"), at(&lib, "/p/trip/b.jpg"), at(&lib, "/p/trip/day2/d.jpg"), at(&lib, "/v/clip.mkv"));
assert_eq!(lib.set_rating(a, 3), Some((1, 3)));
lib.set_rating(b, 5);
lib.set_rating(d, 2);
lib.set_rating(clip, 9);
assert_eq!((lib.rating(a), lib.rating(d), lib.rating(clip)), (3, 2, 5), "capped at 5");
let rated = lib.shown(&Scope::Rated, KindFilter::All, SortBy::Name);
assert_eq!(ids(&lib, &rated), vec![2, 5, 1], "2 stars are left out; 5 before 3, path order within");
assert_eq!(ids(&lib, &lib.shown(&Scope::Rated, KindFilter::Photos, SortBy::Name)), vec![2, 1]);
assert_eq!(lib.set_rating(b, 0), Some((2, 0)));
assert_eq!(lib.rating(b), 0);
assert_eq!(ids(&lib, &lib.rated_entries()), vec![1, 5]);
assert_eq!(lib.set_rating(99, 3), None);
}
#[test]
fn sorting_by_date_taken_falls_back_to_the_file_time() {
let mut lib = sample();
lib.taken = HashMap::from([(1, 100), (2, 900), (4, 0)]);
let order = lib.shown(&Scope::All, KindFilter::All, SortBy::Taken);
assert_eq!(ids(&lib, &order), vec![2, 1, 4, 5, 3]);
assert_eq!(ids(&lib, &lib.shown(&Scope::All, KindFilter::Photos, SortBy::Taken)), vec![2, 1, 4]);
lib.taken.remove(&4);
let todo: Vec<i64> = lib.without_taken().iter().map(|e| e.id).collect();
assert_eq!(todo, vec![4]);
}
#[test]
fn favorites_toggle_and_ignore_files_no_longer_indexed() {
let mut lib = sample();
let a = lib.find(Path::new("/p/a.jpg")).unwrap();
assert!(!lib.is_favorite(a));
assert_eq!(lib.toggle_favorite(a), Some((1, true)));
assert!(lib.is_favorite(a));
assert_eq!(lib.favorites, vec![5, 2, 1]);
assert_eq!(lib.toggle_favorite(a), Some((1, false)));
assert_eq!(lib.favorites, vec![5, 2]);
assert_eq!(lib.toggle_favorite(99), None);
let kept: Vec<Entry> = lib.entries.iter().filter(|e| e.id != 5).cloned().collect();
lib.set_index(Index::build(&lib.sources, kept));
assert_eq!(ids(&lib, &lib.favorite_entries()), vec![2]);
assert_eq!(lib.favorites, vec![5, 2]);
}
#[test]
fn sidebar_counts_files_per_source_and_top_folder() {
let lib = sample();
assert_eq!(
lib.source_counts,
vec![Counts { all: 4, photos: 3, videos: 1 }, Counts { all: 1, photos: 0, videos: 1 }]
);
let trip = Counts { all: 3, photos: 2, videos: 1 };
assert_eq!(lib.side_folders[0], vec![SideFolder { name: "trip".into(), path: "/p/trip".into(), count: trip }]);
assert_eq!((trip.of(KindFilter::Photos), trip.of(KindFilter::Videos), trip.of(KindFilter::All)), (2, 1, 3));
let all: Vec<usize> = (0..lib.entries.len()).collect();
assert_eq!(lib.count_kind(&all, KindFilter::Videos), 2);
assert!(lib.side_folders[1].is_empty(), "files at a source's root make no folder row");
}
#[test]
fn folders_whose_files_interleave_still_play_in_order() {
let mut items = vec![
entry(1, "/s/A/1.jpg", Kind::Image, 1, 1),
entry(2, "/s/a/2.jpg", Kind::Image, 1, 1),
entry(3, "/s/A/3.jpg", Kind::Image, 1, 1),
entry(4, "/s/a/4.jpg", Kind::Image, 1, 1),
];
items.sort_by(|a, b| media::natural_cmp(&a.path, &b.path));
let sources = vec![Source { id: 1, path: "/s".into() }];
let mut lib = Library::default();
lib.replace(sources.clone(), Index::build(&sources, items), vec![], vec![]);
assert_eq!(ids(&lib, &lib.items_for(&PaneSource::Folder("/s/A".into()))), vec![1, 3]);
assert_eq!(ids(&lib, &lib.items_for(&PaneSource::Folder("/s/a".into()))), vec![2, 4]);
assert_eq!(lib.source_counts[0].all, 4);
assert!(lib.items_for(&PaneSource::Folder("/nowhere".into())).is_empty());
}
#[test]
fn find_locates_entries_by_path() {
let lib = sample();
assert_eq!(lib.path(lib.find(Path::new("/p/trip/c.mp4")).unwrap()), Some(Path::new("/p/trip/c.mp4")));
assert_eq!(lib.find(Path::new("/p/zzz.jpg")), None);
assert_eq!(lib.path(99), None);
}
}