Skip to main content

tsu_editor/
config.rs

1use std::{collections::HashMap, path::PathBuf};
2
3use serde::{Deserialize, Serialize};
4
5use crate::action::Action;
6
7#[derive(Debug, Serialize, Deserialize, Clone)]
8#[serde(untagged)]
9/// Representation of the types of key actions
10pub enum KeyAction {
11    /// No key action
12    None,
13    /// A single key action corresponding to an `Action`
14    Single(Action),
15    /// Multiple key actions corresponding to multiple `Action`s
16    Multiple(Vec<Action>),
17    /// Key actions wrapped inside other key actions
18    Nested(HashMap<String, KeyAction>),
19    /// A single key action repeated n times
20    Repeating(u16, Box<KeyAction>),
21}
22
23#[derive(Debug, Serialize, Deserialize, Default)]
24/// Maps keys to `KeyAction`s
25pub struct Keys {
26    #[serde(default)]
27    pub normal: HashMap<String, KeyAction>,
28    #[serde(default)]
29    pub insert: HashMap<String, KeyAction>,
30    #[serde(default)]
31    pub command: HashMap<String, KeyAction>,
32}
33
34#[derive(Debug, Serialize, Deserialize, Default)]
35/// Pseudo-schema for the configuration file format
36pub struct Config {
37    /// Mapping of keys to their corresponding key actions
38    pub keys: Keys,
39    /// Path to theme file to use
40    pub theme: String,
41    /// Optional path to log file
42    pub log_file: Option<String>,
43    /// Optionally increase the amount of lines scrolled per mouse scroll
44    pub mouse_scroll_lines: Option<usize>,
45    #[serde(default = "default_false")]
46    pub window_borders_ascii: bool,
47}
48
49impl Config {
50    #[must_use]
51    /// Construct the path to the configuration file
52    ///
53    /// # Arguments
54    /// - `p`: Name of the configuration file
55    ///
56    /// # Panics
57    /// This function might panic if querying the home directory returns an `Err`
58    pub fn path(p: &str) -> PathBuf {
59        std::env::home_dir()
60            .unwrap()
61            .join(".config")
62            .join("tsu")
63            .join(p)
64    }
65}
66
67#[must_use]
68/// Serde function for setting the default value of a Boolean to `false`
69///
70/// # Returns
71/// - `false` always
72pub fn default_false() -> bool {
73    false
74}
75
76#[cfg(test)]
77mod test {
78    use super::*;
79    use std::fs;
80
81    #[test]
82    fn test_parse_config() {
83        let toml = fs::read_to_string("default_config.toml").unwrap();
84        let config: Config = toml::from_str(&toml).unwrap();
85        println!("{config:#?}");
86    }
87}