omnyssh 1.0.2

TUI SSH dashboard & server manager
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use anyhow::Context;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{Deserialize, Serialize};

/// Main application configuration, loaded from
/// `~/.config/omnyssh/config.toml`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct AppConfig {
    pub general: GeneralConfig,
    pub ui: UiConfig,
    pub keybindings: KeybindingsConfig,
    pub smart_context: SmartContextConfig,
    pub auto_key_setup: AutoKeySetupConfig,
    pub update: UpdateConfig,
}

/// General / runtime settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GeneralConfig {
    /// Seconds between automatic metric refreshes.
    pub refresh_interval: u64,
    pub default_shell: String,
    /// Path to the system SSH binary.
    pub ssh_command: String,
    pub max_concurrent_connections: usize,
}

impl Default for GeneralConfig {
    fn default() -> Self {
        Self {
            refresh_interval: 30,
            default_shell: String::from("/bin/bash"),
            ssh_command: String::from("ssh"),
            max_concurrent_connections: 10,
        }
    }
}

/// Visual / theme settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct UiConfig {
    /// One of: `default`, `dracula`, `nord`, `gruvbox`.
    pub theme: String,
    // TODO(future-stage): these fields are parsed from user config but not yet
    // wired up to the renderer.  They are kept in the struct so existing config
    // files are accepted without error; the renderer will consume them once the
    // corresponding UI features land.
    pub show_ip: bool,
    pub show_uptime: bool,
    /// One of: `grid`, `list`.
    pub card_layout: String,
    /// One of: `rounded`, `plain`, `double`.
    pub border_style: String,
}

impl UiConfig {
    /// Returns the list of all available built-in theme names.
    ///
    /// These names correspond to themes defined in [`crate::ui::theme::Theme`].
    pub fn available_themes() -> &'static [&'static str] {
        &["default", "dracula", "nord", "gruvbox"]
    }

    /// Checks if the given theme name is valid.
    ///
    /// # Examples
    /// ```
    /// # use omnyssh::config::app_config::UiConfig;
    /// assert!(UiConfig::is_valid_theme("dracula"));
    /// assert!(!UiConfig::is_valid_theme("unknown"));
    /// ```
    pub fn is_valid_theme(name: &str) -> bool {
        Self::available_themes().contains(&name)
    }
}

impl Default for UiConfig {
    fn default() -> Self {
        Self {
            theme: String::from("default"),
            show_ip: true,
            show_uptime: true,
            card_layout: String::from("grid"),
            border_style: String::from("rounded"),
        }
    }
}

/// Keyboard shortcut overrides (all values are key name strings).
///
/// Supports plain key names (`"Tab"`, `"q"`, `"F1"`) and `"Ctrl+<char>"` format
/// (e.g. `"Ctrl+T"`, `"Ctrl+W"`) for modifiers.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct KeybindingsConfig {
    pub quit: String,
    pub search: String,
    pub connect: String,
    pub dashboard: String,
    pub file_manager: String,
    pub snippets: String,
    /// Key to cycle to the next app screen (dashboard → files → snippets →
    /// terminal).  Also used to switch panels in File Manager.
    /// Default: `"Tab"`.
    pub next_screen: String,
    /// Key to cycle terminal tabs / split panes.
    /// Default: `"Tab"`.
    pub next_tab: String,
}

/// Smart Server Context configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SmartContextConfig {
    /// Enable automatic service discovery and monitoring.
    pub enabled: bool,
    /// Seconds between deep probe scans (set to 0 to disable periodic scans).
    pub scan_interval: u64,
}

impl Default for SmartContextConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            scan_interval: 300, // 5 minutes
        }
    }
}

/// Auto SSH Key Setup configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AutoKeySetupConfig {
    /// Enable the auto key setup feature.
    pub enabled: bool,
    /// Show suggestion banner when password authentication is detected.
    pub suggest_on_password_auth: bool,
    /// Automatically disable password authentication after key setup (requires sudo).
    pub disable_password_auth: bool,
    /// SSH key type to generate (ed25519 | rsa-4096).
    pub key_type: String,
    /// Directory where SSH keys are stored (default: ~/.ssh).
    pub key_directory: String,
    /// Always create a backup of sshd_config before modification.
    pub backup_sshd_config: bool,
    /// Ask for confirmation before disabling password authentication.
    pub confirm_before_disable: bool,
}

impl Default for AutoKeySetupConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            suggest_on_password_auth: true,
            disable_password_auth: true,
            key_type: String::from("ed25519"),
            key_directory: String::from("~/.ssh"),
            backup_sshd_config: true,
            confirm_before_disable: true,
        }
    }
}

/// Update checker configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct UpdateConfig {
    /// Check GitHub Releases for a newer version on startup.
    pub check_on_startup: bool,
    /// A version the user chose to skip; it is never offered again.
    pub skip_version: String,
}

impl Default for UpdateConfig {
    fn default() -> Self {
        Self {
            check_on_startup: true,
            skip_version: String::new(),
        }
    }
}

impl Default for KeybindingsConfig {
    fn default() -> Self {
        Self {
            quit: String::from("q"),
            search: String::from("/"),
            connect: String::from("Enter"),
            dashboard: String::from("F1"),
            file_manager: String::from("F2"),
            snippets: String::from("F3"),
            next_screen: String::from("Tab"),
            next_tab: String::from("Tab"),
        }
    }
}

// ---------------------------------------------------------------------------
// Parsed keybindings — config strings resolved to crossterm KeyCodes
// ---------------------------------------------------------------------------

/// A resolved key binding that may optionally require the `Ctrl` modifier.
#[derive(Debug, Clone, Copy)]
pub struct KeyBind {
    pub code: KeyCode,
    /// If true, the `Ctrl` modifier must be pressed for this binding to match.
    pub ctrl: bool,
}

impl KeyBind {
    pub fn matches(&self, key: KeyEvent) -> bool {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        key.code == self.code && ctrl == self.ctrl
    }
}

/// Keybindings resolved from [`KeybindingsConfig`] into concrete
/// [`crossterm::event::KeyCode`] values used by the event loop.
#[derive(Debug, Clone)]
pub struct ParsedKeybindings {
    /// Key that exits the application (default: `q`).
    pub quit: KeyCode,
    /// Key that activates fuzzy search (default: `/`).
    pub search: KeyCode,
    /// Key that confirms / connects (default: `Enter`).
    pub connect: KeyCode,
    /// Key that switches to the Dashboard screen (default: `F1`).
    pub dashboard: KeyCode,
    /// Key that switches to the File Manager screen (default: `F2`).
    pub file_manager: KeyCode,
    /// Key that switches to the Snippets screen (default: `F3`).
    pub snippets: KeyCode,
    /// Key that cycles to the next screen / switches FM panels (default: `Tab`).
    pub next_screen: KeyBind,
    /// Key that cycles terminal tabs / split panes (default: `Tab`).
    pub next_tab: KeyBind,
}

impl ParsedKeybindings {
    /// Parses a [`KeybindingsConfig`] into concrete key codes.
    ///
    /// Unknown key names fall back to the default binding so the application
    /// never becomes unusable due to a misconfiguration.
    pub fn from_config(cfg: &KeybindingsConfig) -> Self {
        let defaults = KeybindingsConfig::default();
        Self {
            quit: parse_keycode(&cfg.quit)
                .unwrap_or_else(|| parse_keycode(&defaults.quit).expect("default quit")),
            search: parse_keycode(&cfg.search)
                .unwrap_or_else(|| parse_keycode(&defaults.search).expect("default search")),
            connect: parse_keycode(&cfg.connect)
                .unwrap_or_else(|| parse_keycode(&defaults.connect).expect("default connect")),
            dashboard: parse_keycode(&cfg.dashboard)
                .unwrap_or_else(|| parse_keycode(&defaults.dashboard).expect("default dashboard")),
            file_manager: parse_keycode(&cfg.file_manager).unwrap_or_else(|| {
                parse_keycode(&defaults.file_manager).expect("default file_manager")
            }),
            snippets: parse_keycode(&cfg.snippets)
                .unwrap_or_else(|| parse_keycode(&defaults.snippets).expect("default snippets")),
            next_screen: parse_keybind(&cfg.next_screen).unwrap_or_else(|| {
                parse_keybind(&defaults.next_screen).expect("default next_screen")
            }),
            next_tab: parse_keybind(&cfg.next_tab)
                .unwrap_or_else(|| parse_keybind(&defaults.next_tab).expect("default next_tab")),
        }
    }
}

impl Default for ParsedKeybindings {
    fn default() -> Self {
        Self::from_config(&KeybindingsConfig::default())
    }
}

/// Parses a key name string (from config TOML) into a [`KeyCode`].
///
/// Supported formats:
/// - Single printable character: `"q"`, `"/"`, `" "` → `KeyCode::Char(_)`
/// - `"Enter"` → `KeyCode::Enter`
/// - `"Esc"` / `"Escape"` → `KeyCode::Esc`
/// - `"Tab"` → `KeyCode::Tab`
/// - `"Backspace"` / `"BS"` → `KeyCode::Backspace`
/// - `"F1"` … `"F12"` → `KeyCode::F(_)`
/// - `"Up"`, `"Down"`, `"Left"`, `"Right"` → directional keys
///
/// Returns `None` for unrecognised strings.
pub fn parse_keycode(s: &str) -> Option<KeyCode> {
    match s {
        "Enter" => Some(KeyCode::Enter),
        "Esc" | "Escape" => Some(KeyCode::Esc),
        "Tab" => Some(KeyCode::Tab),
        "Backtab" | "BackTab" | "ShiftTab" => Some(KeyCode::BackTab),
        "Backspace" | "BS" => Some(KeyCode::Backspace),
        "Delete" | "Del" => Some(KeyCode::Delete),
        "Up" => Some(KeyCode::Up),
        "Down" => Some(KeyCode::Down),
        "Left" => Some(KeyCode::Left),
        "Right" => Some(KeyCode::Right),
        "Home" => Some(KeyCode::Home),
        "End" => Some(KeyCode::End),
        "PageUp" => Some(KeyCode::PageUp),
        "PageDown" => Some(KeyCode::PageDown),
        f if f.starts_with('F') || f.starts_with('f') => f[1..].parse::<u8>().ok().map(KeyCode::F),
        c if c.chars().count() == 1 => c.chars().next().map(KeyCode::Char),
        _ => None,
    }
}

/// Parses a key binding string into a [`KeyBind`].
///
/// Supports two formats:
/// - `"Ctrl+<key>"` — requires the `Ctrl` modifier (e.g. `"Ctrl+T"`, `"Ctrl+W"`).
///   For printable characters the key portion is lower-cased automatically.
/// - Plain key names — passed through to [`parse_keycode`] with `ctrl: false`.
///
/// # Examples
/// ```
/// # use omnyssh::config::app_config::parse_keybind;
/// // Ctrl+T for screen cycling, freeing Tab for shell completion.
/// let kb = parse_keybind("Ctrl+T").unwrap();
/// assert!(kb.ctrl);
/// ```
pub fn parse_keybind(s: &str) -> Option<KeyBind> {
    // "Ctrl+<key>" format (case-insensitive prefix).
    if let Some(rest) = s
        .strip_prefix("Ctrl+")
        .or_else(|| s.strip_prefix("ctrl+"))
        .or_else(|| s.strip_prefix("CTRL+"))
    {
        // Ctrl+<char>: always lower-case so "Ctrl+T" and "Ctrl+t" both work.
        if rest.chars().count() == 1 {
            return rest.chars().next().map(|c| KeyBind {
                code: KeyCode::Char(c.to_ascii_lowercase()),
                ctrl: true,
            });
        }
        // Named key e.g. "Ctrl+Enter", "Ctrl+Tab".
        if let Some(code) = parse_keycode(rest) {
            return Some(KeyBind { code, ctrl: true });
        }
        return None;
    }
    // Plain key name — no modifier required.
    parse_keycode(s).map(|code| KeyBind { code, ctrl: false })
}

// ---------------------------------------------------------------------------
// Config file loading
// ---------------------------------------------------------------------------

/// Loads the application config from `path`, or from the default location
/// (`~/.config/omnyssh/config.toml`) when `path` is `None`.
///
/// A missing config file is silently ignored and [`AppConfig::default`] is
/// returned.  Parse errors are propagated so the user sees them at startup.
///
/// # Errors
/// Returns an error only if the file exists but cannot be read or parsed.
pub fn load_app_config(path: Option<&std::path::Path>) -> anyhow::Result<AppConfig> {
    use crate::utils::platform;

    let config_path = match path {
        Some(p) => p.to_path_buf(),
        None => match platform::app_config_path() {
            Some(p) => p,
            None => return Ok(AppConfig::default()),
        },
    };

    if !config_path.exists() {
        return Ok(AppConfig::default());
    }

    let content = std::fs::read_to_string(&config_path)
        .with_context(|| format!("Failed to read config: {}", config_path.display()))?;

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

    Ok(config)
}

/// Loads the on-disk config (or a default), applies `mutator`, and writes it
/// back. Reading fresh from disk avoids clobbering unrelated edits.
///
/// # Errors
/// Returns an error if the config file cannot be read, parsed, or written.
fn persist_config<F: FnOnce(&mut AppConfig)>(mutator: F) -> anyhow::Result<()> {
    use crate::utils::platform;

    let config_path = match platform::app_config_path() {
        Some(p) => p,
        None => anyhow::bail!("Cannot determine config path for this platform"),
    };

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

    let mut config = if config_path.exists() {
        let content = std::fs::read_to_string(&config_path)
            .with_context(|| format!("Failed to read config: {}", config_path.display()))?;
        toml::from_str::<AppConfig>(&content)
            .with_context(|| format!("Failed to parse config: {}", config_path.display()))?
    } else {
        AppConfig::default()
    };

    mutator(&mut config);

    let content = toml::to_string_pretty(&config).context("Failed to serialize config")?;
    std::fs::write(&config_path, content)
        .with_context(|| format!("Failed to write config: {}", config_path.display()))?;

    Ok(())
}

/// Saves the theme selection to the config file's `[ui]` section.
///
/// # Errors
/// Returns an error if the config file cannot be written or parsed.
pub fn save_theme_to_config(theme_name: &str) -> anyhow::Result<()> {
    persist_config(|config| config.ui.theme = theme_name.to_string())
}

/// Saves the update-checker preferences to the config file's `[update]`
/// section.
///
/// # Errors
/// Returns an error if the config file cannot be written or parsed.
pub fn save_update_config(update: &UpdateConfig) -> anyhow::Result<()> {
    let update = update.clone();
    persist_config(move |config| config.update = update)
}

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

    /// Verifies that every hard-coded default key string parses successfully.
    /// This converts a potential runtime panic in `.expect("default …")` into a
    /// compile-time-visible test failure.
    #[test]
    fn default_keybindings_parse() {
        let _kb = ParsedKeybindings::default();
    }

    #[test]
    fn parse_ctrl_combo() {
        let kb = parse_keybind("Ctrl+T").unwrap();
        assert!(kb.ctrl);
        assert_eq!(kb.code, KeyCode::Char('t'));

        let kb = parse_keybind("ctrl+w").unwrap();
        assert!(kb.ctrl);
        assert_eq!(kb.code, KeyCode::Char('w'));

        let kb = parse_keybind("CTRL+q").unwrap();
        assert!(kb.ctrl);
        assert_eq!(kb.code, KeyCode::Char('q'));
    }

    #[test]
    fn parse_plain_key() {
        let kb = parse_keybind("Tab").unwrap();
        assert!(!kb.ctrl);
        assert_eq!(kb.code, KeyCode::Tab);

        let kb = parse_keybind("F5").unwrap();
        assert!(!kb.ctrl);
    }

    #[test]
    fn update_config_defaults_to_enabled() {
        let cfg = UpdateConfig::default();
        assert!(cfg.check_on_startup);
        assert!(cfg.skip_version.is_empty());
    }

    /// A config file written by an older release (no `[update]` section)
    /// must still parse, falling back to the default update settings.
    #[test]
    fn config_without_update_section_parses() {
        let cfg: AppConfig = toml::from_str("[ui]\ntheme = \"nord\"\n").unwrap();
        assert_eq!(cfg.ui.theme, "nord");
        assert!(cfg.update.check_on_startup);
    }

    #[test]
    fn update_config_round_trips_through_toml() {
        let mut cfg = AppConfig::default();
        cfg.update.check_on_startup = false;
        cfg.update.skip_version = "1.2.3".to_string();

        let serialized = toml::to_string_pretty(&cfg).unwrap();
        let parsed: AppConfig = toml::from_str(&serialized).unwrap();
        assert!(!parsed.update.check_on_startup);
        assert_eq!(parsed.update.skip_version, "1.2.3");
    }
}