plannotator-tui 0.9.10

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
//! User configuration: one small TOML file, strict about what it accepts.
//!
//! `$PLANNOTATOR_TUI_CONFIG` → `$XDG_CONFIG_HOME/plannotator-tui/config.toml` →
//! `~/.config/plannotator-tui/config.toml`. A missing file means defaults. An unknown key is an
//! error that names the key, so a typo never silently falls back to a default.

use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

use crate::keys::Keymap;
use crate::theme::{Colors, ThemeSetting};

#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub(crate) struct Config {
    pub(crate) herdr: HerdrConfig,
    pub(crate) rex: RexConfig,
    pub(crate) ui: UiConfig,
    pub(crate) last: LastConfig,
    pub(crate) keys: Keymap,
    pub(crate) colors: Colors,
}

/// Which palette the app starts from; `[colors]` adjusts individual roles of it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub(crate) struct UiConfig {
    /// `auto` asks the terminal for its background colour; `light` and `dark` skip the
    /// question. `PLANNOTATOR_TUI_THEME` overrides whatever is written here.
    pub(crate) theme: ThemeSetting,
    /// Blank columns kept on each side of the app; yields before the app drops below 80.
    pub(crate) horizontal_margin: u16,
    /// Widest the app gets, centered in the terminal. Zero fills the terminal.
    pub(crate) max_width: u16,
    /// Widest the document's text gets; spare columns sit between it and the rail. Zero
    /// lets the document take every column the rail leaves.
    pub(crate) doc_width: u16,
    /// Copy a mouse selection to the clipboard on release. Off leaves the clipboard alone
    /// until `copy` (`y`) on the waiting selection.
    pub(crate) copy_on_select: bool,
}

impl Default for UiConfig {
    fn default() -> Self {
        Self {
            theme: ThemeSetting::default(),
            horizontal_margin: 0,
            max_width: 0,
            doc_width: 0,
            copy_on_select: true,
        }
    }
}

/// How `plannotator-tui last` finds a session.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub(crate) struct LastConfig {
    /// Claude Code config dirs to also search for a known session id, in order, for agents
    /// whose `CLAUDE_CONFIG_DIR` does not reach this process. `~/` means the home directory.
    pub(crate) claude_profile_dirs: Vec<String>,
}

/// How plannotator-tui opens inside Herdr.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub(crate) struct HerdrConfig {
    pub(crate) placement: Placement,
    /// Split only.
    pub(crate) split_direction: SplitDirection,
    /// Popup only; cells or a percentage like `90%`.
    pub(crate) popup_width: String,
    pub(crate) popup_height: String,
}

impl Default for HerdrConfig {
    fn default() -> Self {
        Self {
            placement: Placement::Overlay,
            split_direction: SplitDirection::Right,
            popup_width: "90%".to_owned(),
            popup_height: "85%".to_owned(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum Placement {
    /// A real pane zoomed over the whole tab; Herdr restores focus and zoom on exit.
    #[default]
    Overlay,
    /// Beside the target pane.
    Split,
    /// A modal floating box.
    Popup,
}

impl Placement {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Overlay => "overlay",
            Self::Split => "split",
            Self::Popup => "popup",
        }
    }
}

impl fmt::Display for Placement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for Placement {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "overlay" => Ok(Self::Overlay),
            "split" => Ok(Self::Split),
            "popup" => Ok(Self::Popup),
            other => anyhow::bail!("unknown placement {other:?}; expected overlay, split or popup"),
        }
    }
}

/// How plannotator-tui opens inside Rex.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub(crate) struct RexConfig {
    pub(crate) placement: RexPlacement,
}

/// Where a Rex review opens. Rex has no overlay; a popup is a floating layer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum RexPlacement {
    /// A split to the right of the agent's block, so the agent stays in view.
    #[default]
    Split,
    /// A floating layer over the agent's window.
    Popup,
}

impl FromStr for RexPlacement {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "split" => Ok(Self::Split),
            "popup" => Ok(Self::Popup),
            other => anyhow::bail!("unknown Rex placement {other:?}; expected split or popup"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum SplitDirection {
    #[default]
    Right,
    Down,
}

impl SplitDirection {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Right => "right",
            Self::Down => "down",
        }
    }
}

impl fmt::Display for SplitDirection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Where the config file lives, given an environment lookup and the home directory.
pub(crate) fn config_path(env: impl Fn(&str) -> Option<String>, home: &Path) -> PathBuf {
    if let Some(explicit) = env("PLANNOTATOR_TUI_CONFIG").filter(|s| !s.is_empty()) {
        return PathBuf::from(explicit);
    }
    #[cfg(windows)]
    if let Some(appdata) = env("APPDATA").map(PathBuf::from).filter(|p| p.is_absolute()) {
        return appdata.join("plannotator-tui").join("config.toml");
    }
    let xdg = env("XDG_CONFIG_HOME").map(PathBuf::from).filter(|p| p.is_absolute());
    xdg.unwrap_or_else(|| home.join(".config")).join("plannotator-tui").join("config.toml")
}

impl Config {
    pub(crate) fn parse(text: &str) -> Result<Self> {
        toml::from_str(text).map_err(|e| anyhow::anyhow!("{}", e.message().trim()))
    }

    /// Read the config file for this process; a missing file is the default config.
    pub(crate) fn load() -> Result<Self> {
        let home = std::env::home_dir().unwrap_or_else(|| PathBuf::from("/"));
        let path = config_path(|k| std::env::var(k).ok(), &home);
        Self::load_from(&path)
    }

    pub(crate) fn load_from(path: &Path) -> Result<Self> {
        match std::fs::read_to_string(path) {
            Ok(text) => Self::parse(&text).with_context(|| format!("in {}", path.display())),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
        }
    }

    /// The effective config as TOML, for `plannotator-tui config`.
    pub(crate) fn to_toml(&self) -> Result<String> {
        Ok(toml::to_string(self)?)
    }
}

#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
    use super::*;

    #[test]
    fn empty_file_is_the_default_config() {
        assert_eq!(Config::parse("").expect("parses"), Config::default());
        assert_eq!(Config::default().herdr.placement, Placement::Overlay);
    }

    #[test]
    fn unknown_key_error_names_the_key() {
        let err = Config::parse("[herdr]\nplacment = \"popup\"\n").expect_err("rejected");
        assert!(err.to_string().contains("placment"), "{err}");
    }

    #[test]
    fn invalid_placement_error_names_the_value() {
        let err = Config::parse("[herdr]\nplacement = \"floating\"\n").expect_err("rejected");
        assert!(err.to_string().contains("floating"), "{err}");
    }

    #[test]
    fn rex_opens_in_a_split_unless_a_popup_is_asked_for_and_has_no_overlay() {
        assert_eq!(Config::default().rex.placement, RexPlacement::Split);
        let popup = Config::parse("[rex]\nplacement = \"popup\"\n").expect("parses");
        assert_eq!(popup.rex.placement, RexPlacement::Popup);
        assert_eq!(popup.herdr, HerdrConfig::default());
        let err = Config::parse("[rex]\nplacement = \"overlay\"\n").expect_err("rejected");
        assert!(err.to_string().contains("overlay"), "{err}");
        assert!("overlay".parse::<RexPlacement>().is_err());
    }

    #[test]
    fn partial_file_keeps_other_defaults() {
        let config = Config::parse("[herdr]\nplacement = \"split\"\n").expect("parses");
        assert_eq!(config.herdr.placement, Placement::Split);
        assert_eq!(config.herdr.split_direction, SplitDirection::Right);
        assert_eq!(config.herdr.popup_width, "90%");
    }

    #[cfg(windows)]
    #[test]
    fn config_lives_under_appdata_on_windows() {
        let lookup = |k: &str| (k == "APPDATA").then(|| r"C:\Users\u\AppData\Roaming".to_owned());
        assert_eq!(
            config_path(lookup, Path::new(r"C:\Users\u")),
            PathBuf::from(r"C:\Users\u\AppData\Roaming\plannotator-tui\config.toml")
        );
    }

    #[cfg(unix)]
    #[test]
    fn config_path_precedence() {
        let home = Path::new("/home/u");
        let lookup = |vars: &'static [(&'static str, &'static str)]| {
            move |k: &str| vars.iter().find(|(name, _)| *name == k).map(|(_, v)| (*v).to_owned())
        };
        assert_eq!(
            config_path(
                lookup(&[("PLANNOTATOR_TUI_CONFIG", "/etc/p.toml"), ("XDG_CONFIG_HOME", "/x")]),
                home
            ),
            PathBuf::from("/etc/p.toml")
        );
        assert_eq!(
            config_path(lookup(&[("XDG_CONFIG_HOME", "/x")]), home),
            PathBuf::from("/x/plannotator-tui/config.toml")
        );
        // A relative XDG_CONFIG_HOME is ignored, as the spec requires.
        assert_eq!(
            config_path(lookup(&[("XDG_CONFIG_HOME", "rel")]), home),
            PathBuf::from("/home/u/.config/plannotator-tui/config.toml")
        );
        assert_eq!(
            config_path(lookup(&[]), home),
            PathBuf::from("/home/u/.config/plannotator-tui/config.toml")
        );
    }

    #[test]
    fn the_theme_defaults_to_asking_the_terminal() {
        assert_eq!(Config::default().ui.theme, ThemeSetting::Auto);
        assert_eq!(Config::parse("").expect("parses").ui.theme, ThemeSetting::Auto);
    }

    #[test]
    fn a_configured_theme_is_read_and_leaves_the_rest_alone() {
        let config = Config::parse("[ui]\ntheme = \"light\"\n").expect("parses");
        assert_eq!(config.ui.theme, ThemeSetting::Light);
        assert_eq!(config.herdr.placement, Placement::Overlay);
    }

    #[test]
    fn an_unknown_theme_error_names_the_value() {
        let err = Config::parse("[ui]\ntheme = \"solarized\"\n").expect_err("rejected");
        assert!(err.to_string().contains("solarized"), "{err}");
    }

    #[test]
    fn widths_default_to_filling_the_terminal_and_roundtrip() {
        assert_eq!(Config::default().ui.horizontal_margin, 0);
        assert_eq!(Config::default().ui.max_width, 0);
        assert_eq!(Config::default().ui.doc_width, 0);
        let config =
            Config::parse("[ui]\nhorizontal_margin = 2\nmax_width = 168\ndoc_width = 120\n").expect("parses");
        assert_eq!((config.ui.horizontal_margin, config.ui.max_width, config.ui.doc_width), (2, 168, 120));
        assert_eq!(Config::parse(&config.to_toml().expect("serializes")).expect("parses"), config);
    }

    #[test]
    fn claude_profile_dirs_default_to_none_and_are_listed_in_order() {
        assert_eq!(Config::default().last.claude_profile_dirs, Vec::<String>::new());
        let config = Config::parse("[last]\nclaude_profile_dirs = [\"~/b\", \"/a\"]\n").expect("parses");
        assert_eq!(config.last.claude_profile_dirs, ["~/b", "/a"]);
    }

    #[test]
    fn copy_on_select_defaults_on_and_turns_off() {
        assert!(Config::default().ui.copy_on_select);
        assert!(!Config::parse("[ui]\ncopy_on_select = false\n").expect("parses").ui.copy_on_select);
    }

    #[test]
    fn roundtrips_through_toml() {
        let text = Config::default().to_toml().expect("serializes");
        assert_eq!(Config::parse(&text).expect("parses"), Config::default());
    }

    #[test]
    fn colors_are_read_by_role_and_roundtrip() {
        let config =
            Config::parse("[colors]\naccent = \"magenta\"\nlooks-good-bg = \"#a6e3a1\"\nblock = \"236\"\n")
                .expect("parses");
        assert_eq!(config.colors.accent.map(|c| c.0), Some(ratatui::style::Color::Magenta));
        assert_eq!(config.colors.looks_good_bg.map(|c| c.0), Some(ratatui::style::Color::Rgb(166, 227, 161)));
        assert_eq!(config.colors.heading, None);
        let text = config.to_toml().expect("serializes");
        assert_eq!(Config::parse(&text).expect("reparses"), config);
    }

    #[test]
    fn a_color_may_be_a_bare_index() {
        let config = Config::parse("[colors]\nheading = 238\n").expect("parses");
        assert_eq!(config.colors.heading.map(|c| c.0), Some(ratatui::style::Color::Indexed(238)));
        let err = Config::parse("[colors]\nheading = 256\n").expect_err("out of range");
        assert!(err.to_string().contains("256"), "{err}");
    }

    #[test]
    fn an_unknown_color_role_error_names_the_role() {
        let err = Config::parse("[colors]\nbackground = \"black\"\n").expect_err("rejected");
        assert!(err.to_string().contains("background"), "{err}");
    }

    #[test]
    fn an_unreadable_color_error_names_the_value() {
        let err = Config::parse("[colors]\nheading = \"chartreuse\"\n").expect_err("rejected");
        assert!(err.to_string().contains("chartreuse"), "{err}");
    }
}