bmrk 0.3.0

A fast TUI for directory navigation and bookmark management
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use anyhow::{Context, Result};
use crossterm::event::KeyCode;
use ratatui::style::Color;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

use crate::theme::ThemeConfig;

/// Appearance configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppearanceConfig {
    /// Theme name (can be expanded later for preset themes)
    #[serde(default = "default_theme")]
    pub theme: String,

    /// Maximum filename length before middle-truncation (0 = disabled)
    #[serde(default = "default_max_name_length")]
    pub max_name_length: usize,

    /// Icon set for the tree: "unicode" (▼/▶) or "ascii" (v/>)
    #[serde(default = "default_icons")]
    pub icons: String,

    /// Custom theme colors
    #[serde(default)]
    pub colors: ThemeConfig,
}

impl Default for AppearanceConfig {
    fn default() -> Self {
        Self {
            theme: default_theme(),
            max_name_length: default_max_name_length(),
            icons: default_icons(),
            colors: ThemeConfig::default(),
        }
    }
}

fn default_theme() -> String {
    "default".to_string()
}
fn default_max_name_length() -> usize {
    80
}
fn default_icons() -> String {
    "unicode".to_string()
}

/// Behavior configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BehaviorConfig {
    /// Show hidden files (dotfiles)
    #[serde(default = "default_show_hidden")]
    pub show_hidden: bool,

    /// Follow symbolic links
    #[serde(default = "default_follow_symlinks")]
    pub follow_symlinks: bool,

    /// Double-click timeout in milliseconds
    #[serde(default = "default_double_click_timeout")]
    pub double_click_timeout_ms: u64,

    /// Number of lines to scroll with mouse wheel
    #[serde(default = "default_mouse_scroll_lines")]
    pub mouse_scroll_lines: usize,
}

impl Default for BehaviorConfig {
    fn default() -> Self {
        Self {
            show_hidden: default_show_hidden(),
            follow_symlinks: default_follow_symlinks(),
            double_click_timeout_ms: default_double_click_timeout(),
            mouse_scroll_lines: default_mouse_scroll_lines(),
        }
    }
}

fn default_show_hidden() -> bool {
    true
}
fn default_follow_symlinks() -> bool {
    true
}
fn default_double_click_timeout() -> u64 {
    800
}
fn default_mouse_scroll_lines() -> usize {
    1
}

/// Keybindings configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeybindingsConfig {
    /// Keys to enter search mode
    #[serde(default = "default_search_keys")]
    pub search: Vec<String>,

    /// Keys to create bookmark
    #[serde(default = "default_create_bookmark_keys")]
    pub create_bookmark: Vec<String>,

    /// Keys to select bookmark
    #[serde(default = "default_select_bookmark_keys")]
    pub select_bookmark: Vec<String>,

    /// Keys to open disk selection panel
    #[serde(default = "default_select_disk_keys")]
    pub select_disk: Vec<String>,

    /// Keys to go to parent directory (change root up one level)
    #[serde(default = "default_go_to_parent_keys")]
    pub go_to_parent: Vec<String>,

    /// Keys to go back (undo last navigation)
    #[serde(default = "default_go_back_keys")]
    pub go_back: Vec<String>,

    /// Keys to quit and output the selected path (navigate the shell)
    #[serde(default = "default_quit_keys")]
    pub quit: Vec<String>,

    /// Keys to exit without output (cancel)
    #[serde(default = "default_exit_keys")]
    pub exit: Vec<String>,
}

impl Default for KeybindingsConfig {
    fn default() -> Self {
        Self {
            search: default_search_keys(),
            create_bookmark: default_create_bookmark_keys(),
            select_bookmark: default_select_bookmark_keys(),
            select_disk: default_select_disk_keys(),
            go_to_parent: default_go_to_parent_keys(),
            go_back: default_go_back_keys(),
            quit: default_quit_keys(),
            exit: default_exit_keys(),
        }
    }
}

fn default_search_keys() -> Vec<String> {
    vec!["/".to_string()]
}
fn default_create_bookmark_keys() -> Vec<String> {
    vec!["m".to_string()]
}
fn default_select_bookmark_keys() -> Vec<String> {
    vec!["'".to_string()]
}
fn default_select_disk_keys() -> Vec<String> {
    vec!["d".to_string()]
}
fn default_go_to_parent_keys() -> Vec<String> {
    vec!["u".to_string()]
}
fn default_go_back_keys() -> Vec<String> {
    vec!["Backspace".to_string()]
}
fn default_quit_keys() -> Vec<String> {
    vec!["q".to_string()]
}
fn default_exit_keys() -> Vec<String> {
    vec!["Esc".to_string()]
}

impl KeybindingsConfig {
    fn matches_key(&self, key: KeyCode, configured_keys: &[String]) -> bool {
        let key_str = match key {
            KeyCode::Char(c) => c.to_string(),
            KeyCode::Esc => "Esc".to_string(),
            KeyCode::Enter => "Enter".to_string(),
            KeyCode::Backspace => "Backspace".to_string(),
            KeyCode::Left => "Left".to_string(),
            KeyCode::Right => "Right".to_string(),
            KeyCode::Up => "Up".to_string(),
            KeyCode::Down => "Down".to_string(),
            KeyCode::Tab => "Tab".to_string(),
            KeyCode::Delete => "Delete".to_string(),
            KeyCode::Home => "Home".to_string(),
            KeyCode::End => "End".to_string(),
            KeyCode::PageUp => "PageUp".to_string(),
            KeyCode::PageDown => "PageDown".to_string(),
            _ => return false,
        };
        configured_keys
            .iter()
            .any(|k| k.eq_ignore_ascii_case(&key_str))
    }

    pub fn is_search(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.search)
    }

    pub fn is_create_bookmark(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.create_bookmark)
    }

    pub fn is_select_bookmark(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.select_bookmark)
    }

    pub fn is_select_disk(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.select_disk)
    }

    /// Returns true if `key` is bound to "go to parent directory".
    pub fn is_go_to_parent(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.go_to_parent)
    }

    /// Returns true if `key` is bound to "go back" (undo last navigation).
    pub fn is_go_back(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.go_back)
    }

    /// Returns true if `key` is bound to "quit" (exit and output selected path).
    pub fn is_quit(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.quit)
    }

    /// Returns true if `key` is bound to "exit" (cancel/quit without output).
    pub fn is_exit(&self, key: KeyCode) -> bool {
        self.matches_key(key, &self.exit)
    }
}

/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Config {
    #[serde(default)]
    pub appearance: AppearanceConfig,

    #[serde(default)]
    pub behavior: BehaviorConfig,

    #[serde(default)]
    pub keybindings: KeybindingsConfig,
}

impl Config {
    /// Parse a color string to ratatui Color
    pub fn parse_color(color_str: &str) -> Color {
        ThemeConfig::parse_color(color_str)
    }

    /// Get a color value (guaranteed to be Some after load())
    pub fn get_color(opt: &Option<String>) -> &str {
        opt.as_ref()
            .expect("Color should be resolved after config load")
    }

    /// Load configuration from a file
    pub fn from_file(path: &Path) -> Result<Self> {
        let content = fs::read_to_string(path)
            .with_context(|| format!("Failed to read config file: {}", path.display()))?;

        let config: Config = toml::from_str(&content)
            .with_context(|| format!("Failed to parse config file: {}", path.display()))?;

        Ok(config)
    }

    /// Get the global config file path
    /// Unix: ~/.config/bmrk/config.toml
    /// Windows: %APPDATA%\bmrk\config.toml
    pub fn global_config_path() -> Option<PathBuf> {
        dirs::config_dir().map(|p| p.join("bmrk").join("config.toml"))
    }

    /// Load configuration with fallback to defaults.
    /// If config file doesn't exist, it will be created automatically.
    /// If config file has parse errors, returns an error with details.
    pub fn load() -> anyhow::Result<Self> {
        let mut config = Config::default();

        if let Some(global_path) = Self::global_config_path() {
            if !global_path.exists() {
                let _ = Self::create_default_file(&global_path);
            }

            if global_path.exists() {
                match Self::from_file(&global_path) {
                    Ok(global_config) => {
                        config = global_config;
                    }
                    Err(e) => {
                        anyhow::bail!(
                            "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\
                            Configuration file error!\n\
                            ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\
                            \n\
                            Config file: {}\n\
                            \n\
                            Error details:\n\
                            {:#}\n\
                            \n\
                            To fix:\n\
                              1. Edit the config file and fix the syntax error\n\
                              2. Or delete the file - it will be recreated with defaults\n\
                            \n\
                            ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
                            global_path.display(),
                            e
                        );
                    }
                }
            }
        }

        // Resolve color values from preset theme + fallbacks
        let preset = ThemeConfig::get_preset_theme(&config.appearance.theme);
        let fallback = ThemeConfig::fallback_colors();

        macro_rules! resolve_color {
            ($field:ident) => {
                config.appearance.colors.$field = config
                    .appearance
                    .colors
                    .$field
                    .or_else(|| preset.as_ref().and_then(|p| p.$field.clone()))
                    .or_else(|| fallback.$field.clone());
            };
        }

        resolve_color!(selected_color);
        resolve_color!(directory_color);
        resolve_color!(file_color);
        resolve_color!(error_color);
        resolve_color!(highlight_color);
        resolve_color!(cursor_color);
        resolve_color!(tree_cursor_color);
        resolve_color!(tree_cursor_bg_color);
        resolve_color!(header_path_color);
        resolve_color!(header_hints_color);

        Ok(config)
    }

    /// Create a default config file with comments
    pub fn create_default_file(path: &Path) -> Result<()> {
        let default_config = r#"# bmrk configuration file
# This file uses TOML format: https://toml.io

[appearance]
# Theme name - preset color schemes
# Available themes:
#   "default"    - Classic terminal colors (blue dirs, cyan selection)
#   "gruvbox"    - Warm, high contrast theme inspired by Gruvbox
#   "nord"       - Cold, muted colors inspired by Nord theme
#   "tokyonight" - Modern dark theme with vibrant colors
#   "dracula"    - Popular dark theme with high contrast
#   "obsidian"   - Dark theme inspired by Obsidian app with subtle cursor
theme = "default"

# Maximum filename length in the tree before middle-truncation
# Example (with max_name_length = 20): "very_long_project_name.rs" -> "very_long..._name.rs"
# Set to 0 to disable truncation
max_name_length = 80

# Icon set used for the directory tree
# "unicode" - filled triangles: ▼ (expanded)  ▶ (collapsed)
# "ascii"   - plain characters: v (expanded)  > (collapsed)
icons = "unicode"

# Custom theme colors (override preset theme)
[appearance.colors]
# Color formats: name (red, blue...), #RRGGBB hex, 0-255 indexed
#
# selected_color = "cyan"
# directory_color = "gray"
# file_color = "white"
# error_color = "gray"
# highlight_color = "yellow"
# cursor_color = "yellow"
# tree_cursor_color = "dim"
# tree_cursor_bg_color = "dim"
# header_path_color = "cyan"
# header_hints_color = "darkgray"

[behavior]
# Show hidden files (dotfiles)
show_hidden = true

# Follow symbolic links
follow_symlinks = true

# Double-click timeout in milliseconds
double_click_timeout_ms = 800

# Number of lines to scroll with mouse wheel
mouse_scroll_lines = 1

[keybindings]
# Key bindings — each entry is a list; multiple keys can trigger the same action.
# Supported key names: letters (a-z), symbols, Esc, Enter, Backspace, Tab,
#   Up, Down, Left, Right, Home, End, PageUp, PageDown, Delete
search = ["/"]
create_bookmark = ["m"]
select_bookmark = ["'"]
select_disk = ["d"]
go_to_parent = ["u"]
go_back = ["Backspace"]
quit = ["q"]
exit = ["Esc"]
"#;

        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).with_context(|| {
                format!("Failed to create config directory: {}", parent.display())
            })?;
        }

        fs::write(path, default_config)
            .with_context(|| format!("Failed to write config file: {}", path.display()))?;

        Ok(())
    }
}

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.appearance.max_name_length, 80);
        assert!(config.behavior.show_hidden);
    }

    #[test]
    fn test_color_parsing() {
        assert!(matches!(ThemeConfig::parse_color("red"), Color::Red));
        assert!(matches!(ThemeConfig::parse_color("blue"), Color::Blue));
        assert!(matches!(
            ThemeConfig::parse_color("#FF0000"),
            Color::Rgb(255, 0, 0)
        ));
    }
}