1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
//! Configuration that affects Pager behaviors.

use std::sync::Arc;
use std::time::Duration;

use serde::Deserialize;

use crate::bindings::Keymap;
use crate::error::Result;

/// Specify what interface to use.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize)]
#[serde(from = "&str")]
pub enum InterfaceMode {
    /// The full screen terminal interface.
    ///
    /// Support text search and other operations.
    ///
    /// Use the alternate screen. The pager UI will disappear completely at
    /// exit (except for terminals without alternate screen support).
    ///
    /// Similar to external command `less` without flags. This is the default.
    FullScreen,

    /// The minimal interface. Output goes to the terminal directly.
    ///
    /// Does not support text search or other fancy operations.
    ///
    /// Does not use the alternate screen. Content will be kept in the terminal
    /// at exit.
    ///
    /// Error messages and progress messages are printed after
    /// outputs.
    ///
    /// Similar to shell command `cat` without buffering.
    Direct,

    /// Hybrid: `Direct` first, `FullScreen` next.
    ///
    /// `Direct` is used initially. When content exceeds one screen, switch to the
    /// `FullScreen` interface.
    ///
    /// Unlike `FullScreen` or `Delayed`, skip initializing the alternate
    /// screen. This is because the initial `Direct` might have "polluted"
    /// the terminal.
    ///
    /// Similar to external command `less -F -X`.
    Hybrid,

    /// Wait to decide.
    ///
    /// If output completes in the delayed time, and is within one screen, print
    /// the output and exit. Otherwise, enter the `FullScreen` interface.
    ///
    /// Unlike `Hybrid`, output is buffered in memory. So the terminal is not
    /// "polluted" and the alternate screen is used for the `FullScreen`
    /// interface.
    ///
    /// If duration is set to infinite, similar to external command `less -F`.
    /// If duration is set to 0, similar to `FullScreen`.
    Delayed(Duration),
}

impl Default for InterfaceMode {
    fn default() -> Self {
        Self::FullScreen
    }
}

impl From<&str> for InterfaceMode {
    fn from(value: &str) -> InterfaceMode {
        match value.to_lowercase().as_ref() {
            "full" | "fullscreen" | "" => InterfaceMode::FullScreen,
            "direct" => InterfaceMode::Direct,
            "hybrid" => InterfaceMode::Hybrid,
            s if s.starts_with("delayed") => {
                let duration = s.rsplit(':').next().unwrap_or("inf");
                let duration = if duration.ends_with("ms") {
                    // ex. delayed:100ms
                    Duration::from_millis(duration.trim_end_matches("ms").parse().unwrap_or(0))
                } else {
                    // ex. delayed:1s, delayed:1, delayed
                    Duration::from_secs(duration.trim_end_matches('s').parse().unwrap_or(1 << 30))
                };
                InterfaceMode::Delayed(duration)
            }
            _ => InterfaceMode::default(),
        }
    }
}

/// Specify the default line wrapping mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize)]
pub enum WrappingMode {
    /// Lines are not wrapped.
    #[serde(rename = "none")]
    Unwrapped,
    /// Lines are wrapped on grapheme boundaries.
    #[serde(rename = "line")]
    GraphemeBoundary,
    /// Lines are wrapped on word boundaries.
    #[serde(rename = "word")]
    WordBoundary,
}

impl WrappingMode {
    pub(crate) fn next_mode(self) -> WrappingMode {
        match self {
            WrappingMode::Unwrapped => WrappingMode::GraphemeBoundary,
            WrappingMode::GraphemeBoundary => WrappingMode::WordBoundary,
            WrappingMode::WordBoundary => WrappingMode::Unwrapped,
        }
    }
}

impl Default for WrappingMode {
    fn default() -> Self {
        Self::Unwrapped
    }
}

/// Keymap Configuration
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(from = "&str")]
pub enum KeymapConfig {
    /// A keymap name to be loaded.
    Name(String),

    /// An already-loaded keymap.
    Keymap(Arc<Keymap>),
}

impl KeymapConfig {
    pub(crate) fn load(&self) -> Result<Arc<Keymap>> {
        match self {
            Self::Name(name) => Ok(Arc::new(crate::keymaps::load(name)?)),
            Self::Keymap(keymap) => Ok(keymap.clone()),
        }
    }
}

impl Default for KeymapConfig {
    fn default() -> Self {
        Self::Name(String::from("default"))
    }
}

impl From<&str> for KeymapConfig {
    fn from(value: &str) -> Self {
        Self::Name(String::from(value))
    }
}

/// A group of configurations.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct Config {
    /// Specify when to use fullscreen.
    pub interface_mode: InterfaceMode,

    /// Specify whether scrolling down can past end of file.
    pub scroll_past_eof: bool,

    /// Specify how many lines to read ahead.
    pub read_ahead_lines: usize,

    /// Specify default wrapping move.
    pub wrapping_mode: WrappingMode,

    /// Specify the name of the default key map.
    pub keymap: KeymapConfig,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            interface_mode: Default::default(),
            scroll_past_eof: true,
            read_ahead_lines: crate::file::DEFAULT_NEEDED_LINES,
            wrapping_mode: Default::default(),
            keymap: Default::default(),
        }
    }
}

impl Config {
    /// Create [`Config`] from the user's default config file.
    pub fn from_config_file() -> Self {
        if let Some(mut path) = dirs::config_dir() {
            path.push("streampager");
            path.push("streampager.toml");
            if let Ok(config) = std::fs::read_to_string(&path) {
                match toml::from_str(&config) {
                    Ok(config) => return config,
                    Err(e) => eprintln!(
                        "streampager: failed to parse config at {:?}, using defaults: {}",
                        path, e
                    ),
                }
            }
        }
        Self::default()
    }

    /// Modify [`Config`] using environment variables.
    pub fn with_env(mut self) -> Self {
        use std::env::var;
        if let Ok(s) = var("SP_INTERFACE_MODE") {
            self.interface_mode = InterfaceMode::from(s.as_ref());
        }
        if let Ok(s) = var("SP_SCROLL_PAST_EOF") {
            if let Some(b) = parse_bool(&s) {
                self.scroll_past_eof = b;
            }
        }
        if let Ok(s) = var("SP_READ_AHEAD_LINES") {
            if let Ok(n) = s.parse::<usize>() {
                self.read_ahead_lines = n;
            }
        }
        self
    }
}

fn parse_bool(value: &str) -> Option<bool> {
    match value.to_ascii_lowercase().as_ref() {
        "1" | "yes" | "true" | "on" | "always" => Some(true),
        "0" | "no" | "false" | "off" | "never" => Some(false),
        _ => None,
    }
}