ezpn 0.11.1

Dead simple terminal pane splitting — ezpn 2 3 gives you a 2x3 grid of shells
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
505
506
507
508
509
510
511
512
513
514
515
516
517
use crate::daemon::hooks::HookDef;
use crate::render::BorderStyle;
use crate::settings::Settings;
use std::path::PathBuf;

/// Runtime config merged from: defaults < config file < CLI args.
pub struct EzpnConfig {
    pub border: BorderStyle,
    pub shell: String,
    /// Default scrollback line count applied to every pane unless overridden.
    /// Mapped from either the flat `scrollback = N` (back-compat) or the new
    /// `[scrollback] default_lines = N` (SPEC 02).
    pub scrollback: usize,
    /// Hard ceiling enforced when applying per-pane overrides or runtime
    /// `set-scrollback` requests. Defaults to 100_000.
    pub scrollback_max_lines: usize,
    /// Estimated-bytes threshold above which the daemon emits a one-shot
    /// per-pane warning. Defaults to 50 MiB. Hint, not a hard cap.
    pub scrollback_warn_bytes: usize,
    pub show_status_bar: bool,
    pub show_tab_bar: bool,
    /// Prefix key character (default: 'b' for Ctrl+B).
    pub prefix_key: char,
    /// Whether to persist pane scrollback into auto-saved snapshots.
    /// Off by default (snapshots stay small); enable to restore terminal
    /// contents on reattach. May be overridden per-project via `.ezpn.toml`'s
    /// `[workspace] persist_scrollback`.
    pub persist_scrollback: bool,
    /// Theme name (resolved against `~/.config/ezpn/themes/<name>.toml`
    /// then the embedded built-in palettes).  Defaults to `"default"`.
    pub theme: String,
    /// SPEC 08 hooks. Loaded from `[[hooks]]` blocks via the real `toml`
    /// crate (the legacy hand-rolled parser cannot handle TOML arrays).
    /// Empty vec when no hooks block is present.
    pub hooks: Vec<HookDef>,
}

impl Default for EzpnConfig {
    fn default() -> Self {
        Self {
            border: BorderStyle::Rounded,
            shell: std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".into()),
            scrollback: 10_000,
            scrollback_max_lines: 100_000,
            scrollback_warn_bytes: 50 * 1024 * 1024,
            show_status_bar: true,
            show_tab_bar: true,
            prefix_key: 'b',
            persist_scrollback: false,
            theme: "default".to_string(),
            hooks: Vec::new(),
        }
    }
}

/// Helper — `toml`-deserialize just the `[[hooks]]` blocks out of a
/// config file. Anything unknown to this view is silently ignored, so it
/// coexists with the legacy hand-rolled key=value parser.
#[derive(serde::Deserialize, Default)]
struct HooksOnlyView {
    #[serde(default)]
    hooks: Vec<HookDef>,
}

/// Parse SPEC 08 `[[hooks]]` blocks from a config file's full text,
/// validate each, and drop invalid entries with a warn line. Returns
/// only the well-formed hooks so daemon startup never aborts on a bad
/// hook definition (matches the existing tolerance for malformed
/// optional sections).
pub fn parse_hooks_section(contents: &str) -> Vec<HookDef> {
    let view: HooksOnlyView = match toml::from_str(contents) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("ezpn: hooks parse failed, ignoring: {e}");
            return Vec::new();
        }
    };
    let mut out = Vec::with_capacity(view.hooks.len());
    for (i, def) in view.hooks.into_iter().enumerate() {
        match crate::daemon::hooks::validate(&def, i) {
            Ok(()) => out.push(def),
            Err(e) => eprintln!("ezpn: {e}; skipping"),
        }
    }
    out
}

/// Load config from ~/.config/ezpn/config.toml (simple key=value, no toml dep).
/// Format:
///   border = rounded
///   shell = /bin/zsh
///   scrollback = 10000
///   status_bar = true
///   tab_bar = true
///   theme = tokyo-night
///
/// `[ui]` section headers are accepted but ignored — every key is global.
pub fn load_config() -> EzpnConfig {
    let mut config = EzpnConfig::default();
    if let Some(path) = existing_config_path() {
        if let Ok(contents) = std::fs::read_to_string(&path) {
            parse_config_into(&contents, &mut config);
            // SPEC 08: parse the `[[hooks]]` array via the real toml crate;
            // the hand-rolled parser above can't handle TOML tables/arrays.
            config.hooks = parse_hooks_section(&contents);
        }
    }
    config
}

fn parse_config_into(contents: &str, config: &mut EzpnConfig) {
    // Section state: `Some("scrollback")` while inside `[scrollback]`, etc.
    // Other section names (e.g. `[ui]`) are accepted but their keys are still
    // routed through the global key table — preserves legacy behaviour where
    // `[ui]\ntheme = "..."` worked.
    let mut section: Option<String> = None;
    for line in contents.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if let Some(name) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
            section = Some(name.trim().to_string());
            continue;
        }
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        let key = key.trim();
        let value = normalize_value(value);

        // `[scrollback]` table — per SPEC 02. Keys here populate the new
        // EzpnConfig fields; values are capped against `scrollback_max_lines`
        // when applied, not here, so users can lower the cap at runtime.
        if section.as_deref() == Some("scrollback") {
            match key {
                "default_lines" => {
                    if let Ok(n) = value.parse::<usize>() {
                        config.scrollback = n;
                    }
                }
                "max_lines" => {
                    if let Ok(n) = value.parse::<usize>() {
                        config.scrollback_max_lines = n;
                    }
                }
                "warn_bytes" => {
                    if let Ok(n) = value.parse::<usize>() {
                        config.scrollback_warn_bytes = n;
                    }
                }
                _ => {}
            }
            continue;
        }

        match key {
            "border" => {
                if let Some(style) = BorderStyle::from_str(value) {
                    config.border = style;
                }
            }
            "shell" => config.shell = value.to_string(),
            "scrollback" => {
                // Flat key — keep back-compat. Users mixing `scrollback = N`
                // with `[scrollback] default_lines = M` get last-write-wins.
                if let Ok(n) = value.parse::<usize>() {
                    config.scrollback = n;
                }
            }
            "status_bar" => config.show_status_bar = value == "true",
            "tab_bar" => config.show_tab_bar = value == "true",
            "persist_scrollback" => {
                config.persist_scrollback = value == "true";
            }
            "prefix" => {
                let ch = value.to_lowercase();
                if let Some(c) = ch.chars().next() {
                    if c.is_ascii_lowercase() {
                        config.prefix_key = c;
                    }
                }
            }
            "theme" if !value.is_empty() => {
                config.theme = value.to_string();
            }
            _ => {} // ignore unknown keys
        }
    }

    // Apply max-lines cap to whichever default value won. Do this once at the
    // end so the `[scrollback] max_lines` key can lower the effective default
    // even when listed after `default_lines`.
    if config.scrollback > config.scrollback_max_lines {
        config.scrollback = config.scrollback_max_lines;
    }
}

fn normalize_value(value: &str) -> &str {
    let value = value.trim();
    if value.len() >= 2 {
        let first = value.as_bytes()[0];
        let last = value.as_bytes()[value.len() - 1];
        if (first == b'"' && last == b'"') || (first == b'\'' && last == b'\'') {
            return &value[1..value.len() - 1];
        }
    }
    value
}

/// Resolve the config file path, regardless of whether it currently exists.
/// Used for both reads and writes.
pub fn config_path() -> anyhow::Result<PathBuf> {
    let dir = std::env::var("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            let mut home = dirs_fallback();
            home.push(".config");
            home
        });
    Ok(dir.join("ezpn").join("config.toml"))
}

/// Convenience for callers that only care about an *existing* config.
pub fn existing_config_path() -> Option<PathBuf> {
    let p = config_path().ok()?;
    if p.exists() {
        Some(p)
    } else {
        None
    }
}

/// User-friendly display path for the config file (with leading "~/" when
/// inside $HOME). Used by the settings panel header to show users where
/// their changes are saved.
pub fn display_config_path() -> String {
    let path = match config_path() {
        Ok(p) => p,
        Err(_) => return "~/.config/ezpn/config.toml".to_string(),
    };
    if let Ok(home) = std::env::var("HOME") {
        if let Ok(stripped) = path.strip_prefix(&home) {
            return format!("~/{}", stripped.display());
        }
    }
    path.display().to_string()
}

fn dirs_fallback() -> PathBuf {
    std::env::var("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("/tmp"))
}

/// Serialize the live settings panel state to the same key=value format
/// `load_config` understands. Only the knobs the panel can change are
/// emitted; other keys (shell, scrollback, prefix) are not present here
/// since the panel does not expose them.
fn serialize_settings(s: &Settings) -> String {
    let border = match s.border_style {
        BorderStyle::Single => "single",
        BorderStyle::Rounded => "rounded",
        BorderStyle::Heavy => "heavy",
        BorderStyle::Double => "double",
        BorderStyle::None => "none",
    };
    let mut out = String::new();
    out.push_str("# Written by ezpn settings panel.\n");
    out.push_str("# Edit by hand or via Ctrl+B Shift+, — reload with Ctrl+B r.\n");
    out.push_str(&format!("border = {border}\n"));
    out.push_str(&format!("status_bar = {}\n", s.show_status_bar));
    out.push_str(&format!("tab_bar = {}\n", s.show_tab_bar));
    out
}

/// Persist settings panel state to `~/.config/ezpn/config.toml` using an
/// atomic write (tmp file + rename). Creates the parent directory if it
/// doesn't exist. The temp filename includes the current pid so concurrent
/// daemons don't clobber each other's tmp files.
pub fn save_settings(s: &Settings) -> anyhow::Result<()> {
    let path = config_path()?;
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let pid = std::process::id();
    let tmp_name = format!(
        "{}.tmp.{pid}",
        path.file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "config.toml".to_string())
    );
    let tmp = path.with_file_name(tmp_name);
    let contents = serialize_settings(s);
    if let Err(e) = std::fs::write(&tmp, contents) {
        // Best-effort cleanup; rename never happened.
        let _ = std::fs::remove_file(&tmp);
        return Err(e.into());
    }
    if let Err(e) = std::fs::rename(&tmp, &path) {
        let _ = std::fs::remove_file(&tmp);
        return Err(e.into());
    }
    Ok(())
}

/// Apply file-loaded config knobs to a live `Settings` value. Only the
/// fields the settings panel manages are touched.
pub fn apply_config_to_settings(cfg: &EzpnConfig, s: &mut Settings) {
    s.border_style = cfg.border;
    s.show_status_bar = cfg.show_status_bar;
    s.show_tab_bar = cfg.show_tab_bar;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::render::BorderStyle;
    use crate::settings::Settings;
    use std::sync::Mutex;

    /// Serializes tests that mutate the `XDG_CONFIG_HOME` env var so they
    /// don't race when cargo runs them in parallel within the same process.
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn normalize_value_trims_quotes() {
        assert_eq!(normalize_value("rounded"), "rounded");
        assert_eq!(normalize_value(" \"rounded\" "), "rounded");
        assert_eq!(normalize_value(" '/bin/zsh' "), "/bin/zsh");
    }

    #[test]
    fn save_then_parse_roundtrips_panel_state() {
        let mut s = Settings::new(BorderStyle::Heavy);
        s.show_status_bar = false;
        s.show_tab_bar = true;

        let serialized = serialize_settings(&s);
        let mut cfg = EzpnConfig::default();
        parse_config_into(&serialized, &mut cfg);

        assert_eq!(cfg.border, BorderStyle::Heavy);
        assert!(!cfg.show_status_bar);
        assert!(cfg.show_tab_bar);
    }

    #[test]
    fn save_settings_writes_atomically_and_leaves_no_tmp() {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let tmpdir = tempfile::tempdir().expect("tempdir");
        // Point XDG_CONFIG_HOME at our scratch dir for the duration of this test.
        let prev = std::env::var("XDG_CONFIG_HOME").ok();
        std::env::set_var("XDG_CONFIG_HOME", tmpdir.path());

        let mut s = Settings::new(BorderStyle::Double);
        s.show_status_bar = true;
        s.show_tab_bar = false;

        save_settings(&s).expect("save should succeed");

        let path = tmpdir.path().join("ezpn").join("config.toml");
        assert!(path.exists(), "config.toml should exist after save");

        // No leftover *.tmp.* siblings.
        let dir = path.parent().unwrap();
        let leftovers: Vec<_> = std::fs::read_dir(dir)
            .expect("read_dir")
            .flatten()
            .filter(|e| e.file_name().to_string_lossy().contains("config.toml.tmp."))
            .collect();
        assert!(
            leftovers.is_empty(),
            "expected no .tmp.* files, found {leftovers:?}"
        );

        // Round-trip via the public loader.
        let loaded = std::fs::read_to_string(&path).expect("read");
        let mut cfg = EzpnConfig::default();
        parse_config_into(&loaded, &mut cfg);
        assert_eq!(cfg.border, BorderStyle::Double);
        assert!(cfg.show_status_bar);
        assert!(!cfg.show_tab_bar);

        // Restore env.
        match prev {
            Some(v) => std::env::set_var("XDG_CONFIG_HOME", v),
            None => std::env::remove_var("XDG_CONFIG_HOME"),
        }
    }

    #[test]
    fn parse_hooks_section_round_trip() {
        let toml_src = r#"
[[hooks]]
event = "pane-died"
command = "notify-send 'pane died'"
shell = true
timeout_ms = 2000

[[hooks]]
event = "client-attached"
command = ["echo", "hi"]
"#;
        let hooks = parse_hooks_section(toml_src);
        assert_eq!(hooks.len(), 2);
        assert_eq!(hooks[0].event, crate::daemon::hooks::HookEvent::PaneDied);
        assert!(hooks[0].shell);
        assert_eq!(hooks[0].timeout_ms, 2000);
        assert_eq!(
            hooks[1].event,
            crate::daemon::hooks::HookEvent::ClientAttached
        );
        // Default timeout when omitted.
        assert_eq!(
            hooks[1].timeout_ms,
            crate::daemon::hooks::HOOK_DEFAULT_TIMEOUT_MS
        );
    }

    #[test]
    fn parse_hooks_section_drops_invalid_entries() {
        // Entry 0 is valid; entry 1 has out-of-range timeout; entry 2 has
        // shell metachars without shell=true. Loader should keep entry 0
        // and drop the rest with warn lines.
        let toml_src = r#"
[[hooks]]
event = "pane-died"
command = ["true"]

[[hooks]]
event = "pane-exited"
command = ["true"]
timeout_ms = 999999

[[hooks]]
event = "tab-created"
command = "echo hi | tee out"
shell = false
"#;
        let hooks = parse_hooks_section(toml_src);
        assert_eq!(hooks.len(), 1, "only the first valid hook should survive");
        assert_eq!(hooks[0].event, crate::daemon::hooks::HookEvent::PaneDied);
    }

    #[test]
    fn parse_hooks_section_empty_when_no_blocks() {
        let hooks = parse_hooks_section("shell = \"/bin/zsh\"\nscrollback = 1000\n");
        assert!(hooks.is_empty());
    }

    #[test]
    fn flat_scrollback_back_compat() {
        let mut cfg = EzpnConfig::default();
        parse_config_into("scrollback = 7777\n", &mut cfg);
        assert_eq!(cfg.scrollback, 7777);
        assert_eq!(cfg.scrollback_max_lines, 100_000);
    }

    #[test]
    fn scrollback_section_parses_all_keys() {
        let mut cfg = EzpnConfig::default();
        parse_config_into(
            "[scrollback]\n\
             default_lines = 5000\n\
             max_lines = 50000\n\
             warn_bytes = 1048576\n",
            &mut cfg,
        );
        assert_eq!(cfg.scrollback, 5000);
        assert_eq!(cfg.scrollback_max_lines, 50_000);
        assert_eq!(cfg.scrollback_warn_bytes, 1_048_576);
    }

    #[test]
    fn scrollback_section_caps_default_above_max() {
        // default_lines 200_000 with max_lines 100_000 should clamp to 100_000.
        let mut cfg = EzpnConfig::default();
        parse_config_into(
            "[scrollback]\ndefault_lines = 200000\nmax_lines = 100000\n",
            &mut cfg,
        );
        assert_eq!(cfg.scrollback, 100_000);
        assert_eq!(cfg.scrollback_max_lines, 100_000);
    }

    #[test]
    fn unknown_section_does_not_swallow_global_keys() {
        // Legacy `[ui]` header followed by a global key should still parse.
        let mut cfg = EzpnConfig::default();
        parse_config_into("[ui]\nshell = /bin/zsh\n", &mut cfg);
        assert_eq!(cfg.shell, "/bin/zsh");
    }

    #[test]
    fn save_settings_creates_missing_parent_dir() {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let tmpdir = tempfile::tempdir().expect("tempdir");
        let prev = std::env::var("XDG_CONFIG_HOME").ok();
        std::env::set_var("XDG_CONFIG_HOME", tmpdir.path().join("does-not-exist-yet"));

        let s = Settings::new(BorderStyle::Single);
        save_settings(&s).expect("save should create parent dir");

        let path = tmpdir
            .path()
            .join("does-not-exist-yet")
            .join("ezpn")
            .join("config.toml");
        assert!(path.exists());

        match prev {
            Some(v) => std::env::set_var("XDG_CONFIG_HOME", v),
            None => std::env::remove_var("XDG_CONFIG_HOME"),
        }
    }
}