rosier 0.3.0

A fast picture and video viewer for large folders
//! rosier: a fast viewer for large picture and video libraries.

mod anim;
mod app;
mod assets;
#[cfg(feature = "devtools")]
mod bench;
mod db;
mod desktop;
mod glass;
mod grid;
mod i18n;
mod keys;
mod library;
mod media;
mod mpv;
mod orient;
mod pane;
mod pip;
mod session;
mod theme;
mod thumb;
mod thumbcache;
mod thumbpool;
mod turbo;
mod ui;
mod ui_browse;
mod ui_help;
mod ui_onboard;
mod ui_split;
mod ui_sponsor;
#[cfg(test)]
mod ui_tests;
mod video;
mod watch;

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

use gpui::{App, Application, Bounds, TitlebarOptions, WindowBounds, WindowOptions, prelude::*, px, size};

use app::Rosier;

// Many threads decode images at once; glibc's per-thread arenas kept ~1 GB
// after a cold scroll through big PNGs. mimalloc hands memory back.
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

const USAGE: &str = "\
Usage:
  rosier [FOLDER...]         open rosier, adding each FOLDER to the library
  rosier install-desktop     add rosier to the app menu (Linux) or Start menu (Windows)
  rosier --version";

/// What the command line asks for.
#[derive(Debug, PartialEq, Eq)]
enum Command {
    Help,
    Version,
    InstallDesktop,
    #[cfg(feature = "devtools")]
    Bench(String, Vec<String>),
    /// Open the window, adding these folders to the library.
    Open(Vec<PathBuf>),
}

fn parse_args(args: Vec<String>) -> Command {
    match args.first().map(String::as_str) {
        Some("-h" | "--help") => Command::Help,
        Some("-V" | "--version") => Command::Version,
        Some("install-desktop") => Command::InstallDesktop,
        #[cfg(feature = "devtools")]
        Some(cmd) if bench::COMMANDS.contains(&cmd) => Command::Bench(cmd.to_string(), args[1..].to_vec()),
        // Folders on the command line (or from "Open with" in a file
        // manager) are added to the library; for a file, its folder is.
        _ => Command::Open(
            args.into_iter()
                .map(PathBuf::from)
                .filter_map(|p| if p.is_dir() { Some(p) } else { p.parent().map(Path::to_path_buf) })
                .collect(),
        ),
    }
}

fn main() -> anyhow::Result<()> {
    env_logger::init();
    mpv::init_quiet_logging();
    let initial = match parse_args(std::env::args().skip(1).collect()) {
        Command::Help => {
            println!("rosier {}\n\n{USAGE}", env!("CARGO_PKG_VERSION"));
            return Ok(());
        }
        Command::Version => {
            println!("rosier {}", env!("CARGO_PKG_VERSION"));
            return Ok(());
        }
        Command::InstallDesktop => {
            for p in desktop::install()? {
                println!("installed {}", p.display());
            }
            return Ok(());
        }
        #[cfg(feature = "devtools")]
        Command::Bench(cmd, args) => return bench::run_command(&cmd, args),
        Command::Open(folders) => folders,
    };
    let db_path = std::env::var_os("ROSIER_DB").map(PathBuf::from).unwrap_or_else(db::default_path);

    i18n::init(std::fs::read_to_string(app::lang_file(&db_path)).ok().as_deref());
    // The menu entry's program is gone (moved or deleted): point it here.
    std::thread::spawn(desktop::refresh);
    std::thread::spawn(thumb::remove_old_cache);
    Application::new().with_assets(assets::Assets).run(move |cx: &mut App| {
        let bounds = Bounds::centered(None, size(px(1440.0), px(920.0)), cx);
        cx.open_window(
            WindowOptions {
                window_bounds: Some(WindowBounds::Windowed(bounds)),
                titlebar: Some(TitlebarOptions { title: Some(i18n::t("app.title").into()), ..Default::default() }),
                window_decorations: Some(ui::decorations()),
                app_id: Some("rosier".into()),
                window_background: if theme::glass_window() {
                    gpui::WindowBackgroundAppearance::Blurred
                } else {
                    gpui::WindowBackgroundAppearance::Opaque
                },
                ..Default::default()
            },
            |window, cx| {
                let handle = window.window_handle();
                let view = cx.new(|cx| {
                    let mut r = Rosier::new(db_path.clone(), initial.clone(), cx);
                    r.main_window = Some(handle);
                    r
                });
                window.focus(&view.read(cx).focus);
                view
            },
        )
        .expect("open window");
        cx.activate(true);
    });
    Ok(())
}

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

    fn args(v: &[&str]) -> Vec<String> {
        v.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn command_line() {
        assert_eq!(parse_args(args(&["--help"])), Command::Help);
        assert_eq!(parse_args(args(&["-V"])), Command::Version);
        assert_eq!(parse_args(args(&["install-desktop"])), Command::InstallDesktop);
        assert_eq!(parse_args(args(&[])), Command::Open(vec![]));
        let dir = std::env::temp_dir();
        let file = dir.join("rosier-args-test-file.jpg");
        assert_eq!(
            parse_args(vec![dir.display().to_string(), file.display().to_string()]),
            Command::Open(vec![dir.clone(), dir]),
            "a file opens its folder"
        );
    }
}