rosier 0.4.0

A fast picture and video viewer for large folders
//! What rosier remembers between runs: how the library was shown and what
//! each pane was showing. Kept as a small text file beside the database,
//! one "key value" per line, so an unknown or broken line costs only that
//! setting.

use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::library::{KindFilter, Scope, SortBy};
use crate::pane::PaneSource;

#[derive(Clone, Debug, PartialEq)]
pub struct Session {
    pub scope: Scope,
    pub kind: KindFilter,
    pub sort: SortBy,
    pub tile_size: f32,
    pub sidebar: bool,
    /// Pictures cross-fade into the next one.
    pub fade: bool,
    /// Zooming or panning one pane does the same in the others.
    pub sync_view: bool,
    pub split: usize,
    pub split_side: bool,
    /// The player was on screen (not the library).
    pub in_player: bool,
    pub focused: usize,
    /// One per pane; None for a pane showing nothing.
    pub panes: Vec<Option<PaneState>>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct PaneState {
    pub source: PaneSource,
    /// The file on screen.
    pub file: Option<PathBuf>,
    pub shuffle: bool,
    pub lock_view: bool,
    pub fit: crate::pane::Fit,
    pub muted: bool,
    pub interval: Duration,
    pub volume: f64,
    pub speed: f64,
}

/// Where the session is kept: beside the library database.
pub fn file(db_path: &Path) -> PathBuf {
    db_path.with_file_name("session")
}

/// A path as one line, or None when it cannot be (not UTF-8, or holding a
/// line break); that setting is then not remembered.
fn line_path(p: &Path) -> Option<&str> {
    p.to_str().filter(|s| !s.contains(['\n', '\r']))
}

impl Session {
    pub fn to_text(&self) -> String {
        let mut out = String::new();
        let mut put = |k: &str, v: &str| {
            out.push_str(k);
            out.push(' ');
            out.push_str(v);
            out.push('\n');
        };
        match &self.scope {
            Scope::All => put("scope", "all"),
            Scope::Favorites => put("scope", "favorites"),
            Scope::Rated => put("scope", "rated"),
            Scope::Continue => put("scope", "continue"),
            Scope::Folder(p) => {
                if let Some(p) = line_path(p) {
                    put("scope-folder", p);
                }
            }
        }
        put("kind", ["all", "photos", "videos"][self.kind as usize]);
        put("sort", ["name", "date", "size", "taken"][self.sort as usize]);
        put("tile", &self.tile_size.round().to_string());
        put("sidebar", if self.sidebar { "1" } else { "0" });
        put("fade", if self.fade { "1" } else { "0" });
        if self.sync_view {
            put("sync-view", "1");
        }
        put("split", &self.split.to_string());
        put("side", if self.split_side { "1" } else { "0" });
        put("player", if self.in_player { "1" } else { "0" });
        put("focused", &self.focused.to_string());
        for p in &self.panes {
            // A pane block starts with its source; the lines after it
            // belong to it.
            let Some(p) = p else {
                put("pane", "empty");
                continue;
            };
            match &p.source {
                PaneSource::Favorites => put("pane", "favorites"),
                PaneSource::Folder(dir) => match line_path(dir) {
                    Some(dir) => put("pane-folder", dir),
                    None => {
                        put("pane", "empty");
                        continue;
                    }
                },
            }
            if let Some(f) = p.file.as_deref().and_then(line_path) {
                put("file", f);
            }
            put("shuffle", if p.shuffle { "1" } else { "0" });
            if p.muted {
                put("muted", "1");
            }
            if p.fit != crate::pane::Fit::Contain {
                put("fit", p.fit.key());
            }
            if p.lock_view {
                put("lock-view", "1");
            }
            put("interval", &p.interval.as_secs().to_string());
            put("volume", &format!("{:.0}", p.volume));
            put("speed", &p.speed.to_string());
        }
        out
    }

    /// Reads what `to_text` wrote. Settings it cannot read keep `base`'s.
    pub fn parse(text: &str, base: Session) -> Session {
        let mut s = base;
        s.panes.clear();
        for line in text.lines() {
            let Some((k, v)) = line.split_once(' ') else { continue };
            let pane = s.panes.last_mut().and_then(Option::as_mut);
            match (k, v) {
                ("scope", "all") => s.scope = Scope::All,
                ("scope", "favorites") => s.scope = Scope::Favorites,
                ("scope", "rated") => s.scope = Scope::Rated,
                ("scope", "continue") => s.scope = Scope::Continue,
                ("scope-folder", p) => s.scope = Scope::Folder(PathBuf::from(p)),
                ("kind", "all") => s.kind = KindFilter::All,
                ("kind", "photos") => s.kind = KindFilter::Photos,
                ("kind", "videos") => s.kind = KindFilter::Videos,
                ("sort", "name") => s.sort = SortBy::Name,
                ("sort", "date") => s.sort = SortBy::Date,
                ("sort", "taken") => s.sort = SortBy::Taken,
                ("sort", "size") => s.sort = SortBy::Size,
                ("tile", v) => s.tile_size = v.parse().unwrap_or(s.tile_size),
                ("sidebar", v) => s.sidebar = v == "1",
                ("fade", v) => s.fade = v == "1",
                ("sync-view", v) => s.sync_view = v == "1",
                ("split", v) => s.split = v.parse().ok().filter(|n| [1, 2, 4].contains(n)).unwrap_or(s.split),
                ("side", v) => s.split_side = v == "1",
                ("player", v) => s.in_player = v == "1",
                ("focused", v) => s.focused = v.parse().unwrap_or(0),
                ("pane", "favorites") => s.panes.push(Some(PaneState::new(PaneSource::Favorites))),
                ("pane", "empty") => s.panes.push(None),
                ("pane-folder", p) => s.panes.push(Some(PaneState::new(PaneSource::Folder(PathBuf::from(p))))),
                ("file", f) => {
                    if let Some(p) = pane {
                        p.file = Some(PathBuf::from(f));
                    }
                }
                ("muted", v) => {
                    if let Some(p) = pane {
                        p.muted = v == "1";
                    }
                }
                ("fit", v) => {
                    if let (Some(p), Some(f)) = (pane, crate::pane::Fit::from_key(v)) {
                        p.fit = f;
                    }
                }
                ("lock-view", v) => {
                    if let Some(p) = pane {
                        p.lock_view = v == "1";
                    }
                }
                ("shuffle", v) => {
                    if let Some(p) = pane {
                        p.shuffle = v == "1";
                    }
                }
                ("interval", v) => {
                    if let Some(p) = pane
                        && let Ok(secs) = v.parse::<u64>()
                    {
                        p.interval = Duration::from_secs(secs.clamp(1, 60));
                    }
                }
                ("volume", v) => {
                    if let Some(p) = pane
                        && let Ok(vol) = v.parse::<f64>()
                    {
                        p.volume = vol.clamp(0.0, 100.0);
                    }
                }
                ("speed", v) => {
                    if let Some(p) = pane
                        && let Ok(speed) = v.parse::<f64>()
                    {
                        p.speed = speed.clamp(0.25, 4.0);
                    }
                }
                _ => {}
            }
        }
        s.panes.truncate(s.split);
        s.focused = s.focused.min(s.split - 1);
        s
    }

    pub fn load(path: &Path, base: Session) -> Option<Session> {
        std::fs::read_to_string(path).ok().map(|t| Session::parse(&t, base))
    }
}

impl PaneState {
    pub fn new(source: PaneSource) -> Self {
        PaneState {
            source,
            file: None,
            shuffle: false,
            lock_view: false,
            fit: crate::pane::Fit::Contain,
            muted: false,
            interval: crate::pane::DEFAULT_INTERVAL,
            volume: 80.0,
            speed: 1.0,
        }
    }
}

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

    fn base() -> Session {
        Session {
            scope: Scope::All,
            kind: KindFilter::All,
            sort: SortBy::Name,
            tile_size: 180.0,
            sidebar: true,
            fade: true,
            sync_view: false,
            split: 1,
            split_side: false,
            in_player: false,
            focused: 0,
            panes: Vec::new(),
        }
    }

    #[test]
    fn round_trips_through_text() {
        let s = Session {
            scope: Scope::Folder("/pics/trip 2026".into()),
            kind: KindFilter::Videos,
            sort: SortBy::Date,
            tile_size: 240.0,
            sidebar: false,
            fade: false,
            sync_view: true,
            split: 2,
            split_side: true,
            in_player: true,
            focused: 1,
            panes: vec![
                Some(PaneState {
                    source: PaneSource::Folder("/pics/trip 2026".into()),
                    file: Some("/pics/trip 2026/a b.jpg".into()),
                    shuffle: true,
                    lock_view: true,
                    fit: crate::pane::Fit::Cover,
                    muted: true,
                    interval: Duration::from_secs(9),
                    volume: 35.0,
                    speed: 1.5,
                }),
                Some(PaneState { file: Some("/pics/x.mp4".into()), ..PaneState::new(PaneSource::Favorites) }),
            ],
        };
        assert_eq!(Session::parse(&s.to_text(), base()), s);
    }

    #[test]
    fn broken_lines_keep_the_defaults() {
        let text = "tile wide\nsplit 3\nkind music\nfile /orphan.jpg\nvolume 400\nfocused 9\nnonsense\n\
                    pane-folder /a\nvolume 400\nspeed 99\ninterval 0\n";
        let s = Session::parse(text, base());
        assert_eq!((s.tile_size, s.split, s.kind), (180.0, 1, KindFilter::All));
        assert_eq!(s.focused, 0, "within the panes");
        assert_eq!(s.panes.len(), 1);
        let p = s.panes[0].as_ref().unwrap();
        assert_eq!((p.file.as_ref(), p.volume, p.speed, p.interval.as_secs()), (None, 100.0, 4.0, 1));
    }

    #[test]
    fn paths_that_cannot_be_a_line_are_left_out() {
        let mut s = base();
        s.scope = Scope::Folder("/a\nb".into());
        s.split = 2;
        s.panes =
            vec![Some(PaneState::new(PaneSource::Folder("/x\ny".into()))), Some(PaneState::new(PaneSource::Favorites))];
        let text = s.to_text();
        assert!(!text.contains("/a"));
        let back = Session::parse(&text, base());
        assert_eq!(back.scope, Scope::All);
        assert_eq!(back.panes[0], None, "the unwritable pane is empty");
        assert_eq!(back.panes[1].as_ref().unwrap().source, PaneSource::Favorites, "the next stays in its place");
    }
}