rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

pub type Rgba = [f32; 4];

#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(default)]
pub struct Config {
    /// Font family name (falls back to system fonts for missing glyphs).
    pub font_family: String,
    /// Font size in points (12pt == 16px at 100% scaling).
    pub font_size: f32,
    /// Line height as a multiple of the font size.
    pub line_height: f32,
    /// Shell executable. Empty means "find Git Bash".
    pub shell: String,
    pub shell_args: Vec<String>,
    /// Inner padding of each pane, in logical pixels.
    pub padding: f32,
    /// Gap between panes and around the window edge, in logical pixels.
    pub gap: f32,
    /// Corner radius of panes, in logical pixels.
    pub radius: f32,
    pub scrollback: usize,
    pub cursor_blink: bool,
    /// Multiplier for every animation. 0 disables animations.
    pub animation_speed: f32,
    pub copy_on_select: bool,
    /// Minimal prompt, folder tracking and the Claude session picker (bash only).
    pub shell_integration: bool,
    /// See-through window with a blurred desktop behind it, and glass panes.
    pub glass: bool,
    /// How solid glass panes are, 0..1. Lower shows more of the desktop.
    pub glass_opacity: f32,
    /// Flash the taskbar when a command, or Claude's reply, finishes in the background
    /// after at least this many seconds. 0 turns it off.
    pub notify_after_secs: f32,
    /// Links (URLs, files and folders in the output) need Ctrl+click. Off by default: a plain
    /// click opens them.
    pub links_need_ctrl: bool,
    /// Command that opens a place in a file (a click on `src/main.rs:12:5` in a compiler error).
    /// `{file}`, `{line}` and `{col}` are filled in; empty means the default app.
    pub editor: String,
    /// Reopen the panes and folders of the last session when started without a folder.
    pub restore_session: bool,
    /// A global key that shows and hides rustimal from anywhere, like `ctrl+alt+space`. Empty: none.
    pub hotkey: String,
    /// When the hotkey shows rustimal, dock it across the top of the screen like a drop-down terminal.
    pub dropdown: bool,
    /// How tall the docked window is, as a fraction of the screen (0.2 to 1).
    pub dropdown_height: f32,
    /// Key bindings that replace the defaults, by action name (see `keys.rs`).
    pub keys: std::collections::BTreeMap<String, crate::keys::KeyList>,
    pub theme: Theme,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(default)]
pub struct Theme {
    pub background: String,
    pub surface: String,
    pub border: String,
    pub foreground: String,
    pub cursor: String,
    pub accent: String,
    pub selection: String,
    pub ansi: [String; 16],
}

impl Default for Config {
    fn default() -> Self {
        Self {
            font_family: "Cascadia Mono".into(),
            font_size: 11.0,
            line_height: 1.3,
            shell: String::new(),
            shell_args: vec!["--login".into(), "-i".into()],
            padding: 12.0,
            gap: 6.0,
            radius: 10.0,
            scrollback: 20_000,
            cursor_blink: true,
            animation_speed: 1.0,
            copy_on_select: false,
            shell_integration: true,
            glass: true,
            glass_opacity: 0.66,
            notify_after_secs: 10.0,
            links_need_ctrl: false,
            editor: r#"code -g "{file}:{line}:{col}""#.into(),
            restore_session: true,
            hotkey: String::new(),
            dropdown: false,
            dropdown_height: 0.45,
            keys: Default::default(),
            theme: Theme::default(),
        }
    }
}

impl Default for Theme {
    fn default() -> Self {
        let s = |v: &str| v.to_string();
        Self {
            background: s("#08090b"),
            surface: s("#101216"),
            border: s("#1b1f26"),
            foreground: s("#d5d9e0"),
            cursor: s("#e6e9ee"),
            accent: s("#52b6cc"),
            selection: s("#2b4a5a"),
            ansi: [
                s("#1d2128"), // black
                s("#ef7a7f"), // red
                s("#a3cf8c"), // green
                s("#e6c27f"), // yellow
                s("#78a3f2"), // blue
                s("#c49ae6"), // magenta
                s("#5ccbe0"), // cyan
                s("#c4c9d1"), // white
                s("#5d6573"), // bright black
                s("#ff9196"), // bright red
                s("#b9e3a2"), // bright green
                s("#f2d49a"), // bright yellow
                s("#9bbcff"), // bright blue
                s("#d8b2f5"), // bright magenta
                s("#8be0f0"), // bright cyan
                s("#eef0f4"), // bright white
            ],
        }
    }
}

/// Theme with colors parsed into floats (sRGB, 0..1).
#[derive(Clone, Debug)]
pub struct Palette {
    pub background: Rgba,
    pub surface: Rgba,
    pub border: Rgba,
    pub foreground: Rgba,
    pub cursor: Rgba,
    pub accent: Rgba,
    pub selection: Rgba,
    pub ansi: [Rgba; 16],
}

impl Palette {
    pub fn from_theme(t: &Theme) -> Self {
        let d = Theme::default();
        let p = |v: &str, fallback: &str| parse_hex(v).or_else(|| parse_hex(fallback)).unwrap();
        let mut ansi = [[0.0; 4]; 16];
        for (i, c) in ansi.iter_mut().enumerate() {
            *c = p(&t.ansi[i], &d.ansi[i]);
        }
        Self {
            background: p(&t.background, &d.background),
            surface: p(&t.surface, &d.surface),
            border: p(&t.border, &d.border),
            foreground: p(&t.foreground, &d.foreground),
            cursor: p(&t.cursor, &d.cursor),
            accent: p(&t.accent, &d.accent),
            selection: p(&t.selection, &d.selection),
            ansi,
        }
    }

    /// xterm 256-color palette lookup.
    pub fn indexed(&self, idx: u8) -> Rgba {
        match idx {
            0..=15 => self.ansi[idx as usize],
            16..=231 => {
                let i = idx - 16;
                let step = |v: u8| if v == 0 { 0.0 } else { (55.0 + v as f32 * 40.0) / 255.0 };
                [step(i / 36), step((i / 6) % 6), step(i % 6), 1.0]
            }
            _ => {
                let v = (8.0 + (idx - 232) as f32 * 10.0) / 255.0;
                [v, v, v, 1.0]
            }
        }
    }
}

pub fn parse_hex(s: &str) -> Option<Rgba> {
    let s = s.trim().trim_start_matches('#');
    let byte = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|b| b as f32 / 255.0);
    match s.len() {
        6 => Some([byte(0)?, byte(2)?, byte(4)?, 1.0]),
        8 => Some([byte(0)?, byte(2)?, byte(4)?, byte(6)?]),
        _ => None,
    }
}

pub fn config_path() -> Option<PathBuf> {
    dirs::config_dir().map(|d| d.join("rustimal").join("config.toml"))
}

impl Config {
    pub fn load() -> Self {
        match Self::load_checked() {
            Ok(config) => config,
            Err(e) => {
                log::error!("{e}");
                Self::default()
            }
        }
    }

    /// Read the config file. A missing file is created with commented defaults; one that
    /// can't be read is an error, so a typo doesn't silently reset everything.
    pub fn load_checked() -> Result<Self, String> {
        let Some(path) = config_path() else { return Ok(Self::default()) };
        match std::fs::read_to_string(&path) {
            Ok(text) => toml::from_str(&text).map_err(|e| format!("invalid config {}: {e}", path.display())),
            Err(_) => {
                if let Some(dir) = path.parent() {
                    let _ = std::fs::create_dir_all(dir);
                    let _ = std::fs::write(&path, DEFAULT_CONFIG);
                }
                Ok(Self::default())
            }
        }
    }

    /// Every setting as a TOML table, for the settings screen.
    pub fn to_table(&self) -> toml::Table {
        toml::Table::try_from(self).unwrap_or_default()
    }

    pub fn from_table(table: toml::Table) -> Result<Self, String> {
        table.try_into().map_err(|e: toml::de::Error| e.to_string())
    }

    /// Resolve the shell program, preferring Git Bash.
    pub fn shell_program(&self) -> (String, Vec<String>) {
        if !self.shell.is_empty() {
            return (self.shell.clone(), self.shell_args.clone());
        }
        let mut candidates: Vec<PathBuf> =
            vec![r"C:\Program Files\Git\bin\bash.exe".into(), r"C:\Program Files (x86)\Git\bin\bash.exe".into()];
        if let Some(local) = dirs::data_local_dir() {
            candidates.push(local.join(r"Programs\Git\bin\bash.exe"));
        }
        if let Some(home) = dirs::home_dir() {
            candidates.push(home.join(r"scoop\apps\git\current\bin\bash.exe"));
        }
        for c in candidates {
            if c.exists() {
                return (c.to_string_lossy().into_owned(), self.shell_args.clone());
            }
        }
        ("powershell.exe".into(), vec!["-NoLogo".into()])
    }
}

const DEFAULT_CONFIG: &str = r##"# rustimal configuration. Delete a line to use the default.

# font_family = "Cascadia Mono"
# font_size = 11.0          # points
# line_height = 1.3
# shell = ""                # empty = Git Bash
# shell_args = ["--login", "-i"]
# padding = 12.0
# gap = 6.0
# radius = 10.0
# scrollback = 20000
# cursor_blink = true
# animation_speed = 1.0     # 0 disables animations
# copy_on_select = false
# shell_integration = true  # minimal prompt + Claude session picker
# glass = true             # see-through, blurred window and glass panes
# glass_opacity = 0.66      # 0..1, how solid the panes are
# notify_after_secs = 10    # flash the taskbar when a background command or Claude finishes after this long; 0 = off
# links_need_ctrl = false   # true: files, folders and URLs in the output open on Ctrl+click instead of a plain click
# editor = 'code -g "{file}:{line}:{col}"'   # opens src/main.rs:12:5 from errors; empty = default app

# hotkey = "ctrl+alt+space" # a global key that shows and hides rustimal from anywhere; empty = none
# dropdown = false          # dock the window across the top of the screen when the hotkey shows it
# dropdown_height = 0.45    # how tall the docked window is, 0.2..1 of the screen
# restore_session = true    # reopen the panes and folders of the last session (not when started with a folder)

# [keys]                     # rebind any action; one chord or a list. See the README for the names.
# split_right = "ctrl+alt+right"
# paste = ["ctrl+v", "shift+insert"]

# [theme]
# background = "#08090b"
# surface = "#101216"
# border = "#1b1f26"
# foreground = "#d5d9e0"
# cursor = "#e6e9ee"
# accent = "#52b6cc"
# selection = "#2b4a5a"
# ansi = ["#1d2128", "#ef7a7f", "#a3cf8c", "#e6c27f", "#78a3f2", "#c49ae6", "#5ccbe0", "#c4c9d1",
#         "#5d6573", "#ff9196", "#b9e3a2", "#f2d49a", "#9bbcff", "#d8b2f5", "#8be0f0", "#eef0f4"]
"##;

const SHELL_INTEGRATION: &str = include_str!("shell/rustimal.bash");

impl Config {
    /// Install the bash integration script and return the env vars that load it.
    pub fn shell_env(&self) -> Vec<(String, String)> {
        let (program, _) = self.shell_program();
        if !self.shell_integration || !program.to_ascii_lowercase().contains("bash") {
            return Vec::new();
        }
        let Some(dir) = config_path().and_then(|p| p.parent().map(|d| d.to_path_buf())) else { return Vec::new() };
        let path = dir.join("rustimal.bash");
        let _ = std::fs::create_dir_all(&dir);
        if let Err(e) = std::fs::write(&path, SHELL_INTEGRATION.replace("\r\n", "\n")) {
            log::error!("could not write {}: {e}", path.display());
            return Vec::new();
        }
        let fwd = |p: &std::path::Path| p.to_string_lossy().replace('\\', "/");
        let mut env = vec![("PROMPT_COMMAND".into(), format!("[ -z \"$__RUSTIMAL\" ] && . '{}'", fwd(&path)))];
        // So the shell's `open file:12` can ask this exe to open the file in the editor.
        if let Ok(exe) = std::env::current_exe() {
            env.push(("RUSTIMAL_EXE".into(), fwd(&exe)));
        }

        // Claude integration: a status line script that hands session data to rustimal,
        // passed to `claude` via --settings so the user's own Claude config is untouched.
        let state = state_dir();
        let script = dir.join("statusline.sh");
        let settings = dir.join("claude-settings.json");
        let claude_settings = serde_json::json!({
            "statusLine": { "type": "command", "command": format!("bash \"{}\"", fwd(&script)), "padding": 0 },
            "spinnerTipsEnabled": false,
        });
        let ok = state.as_ref().is_some_and(|s| std::fs::create_dir_all(s).is_ok())
            && std::fs::write(&script, STATUSLINE.replace("\r\n", "\n")).is_ok()
            && std::fs::write(&settings, claude_settings.to_string()).is_ok();
        if let (true, Some(state)) = (ok, state) {
            env.push(("RUSTIMAL_STATE".into(), fwd(&state)));
            env.push(("RUSTIMAL_CLAUDE_SETTINGS".into(), fwd(&settings)));
        }
        env
    }
}

impl Config {
    /// True once, on the first run that has nothing installed yet: the first shell
    /// then prints a tip about `rustimal --install`. `cargo install` can't register
    /// the Start menu entry itself, so this is how people find out about it.
    pub fn take_install_hint(&self) -> bool {
        if self.shell_env().is_empty() {
            return false; // the tip is printed by the bash integration
        }
        let Some(state) = state_dir() else { return false };
        let marker = state.join("install-hint-shown");
        let from_source_tree = std::env::current_exe().is_ok_and(|e| e.components().any(|c| c.as_os_str() == "target"));
        let installed = dirs::config_dir()
            .is_some_and(|d| d.join(r"Microsoft\Windows\Start Menu\Programs\rustimal.lnk").exists());
        if from_source_tree || installed || marker.exists() {
            return false;
        }
        let _ = std::fs::create_dir_all(&state);
        std::fs::write(&marker, "").is_ok()
    }
}

const STATUSLINE: &str = include_str!("shell/statusline.sh");

/// Where Claude sessions drop their status for rustimal to read.
pub fn state_dir() -> Option<PathBuf> {
    config_path().and_then(|p| p.parent().map(|d| d.join("state")))
}

/// The config file with `current` applied: values equal to the defaults are left out, so the
/// file only holds what was changed. Keys it doesn't know are kept; for a table like `[keys]`
/// where every entry is known (`drop_missing`), entries that are gone from `current` go too.
pub fn merge_changes(existing: &toml::Table, current: &toml::Table, defaults: &toml::Table) -> toml::Table {
    fn merge(
        existing: &toml::Table,
        current: &toml::Table,
        defaults: &toml::Table,
        drop_missing: bool,
    ) -> toml::Table {
        let mut out = if drop_missing { toml::Table::new() } else { existing.clone() };
        for (key, value) in current {
            match (value, defaults.get(key)) {
                (toml::Value::Table(sub), default) => {
                    let default = default.and_then(toml::Value::as_table).cloned().unwrap_or_default();
                    let old = existing.get(key).and_then(toml::Value::as_table).cloned().unwrap_or_default();
                    // Entries of [keys] are all known; the other tables keep what they don't know.
                    let merged = merge(&old, sub, &default, key == "keys");
                    if merged.is_empty() {
                        out.remove(key);
                    } else {
                        out.insert(key.clone(), toml::Value::Table(merged));
                    }
                }
                (v, Some(d)) if v == d => {
                    out.remove(key);
                }
                (v, _) => {
                    out.insert(key.clone(), v.clone());
                }
            }
        }
        out
    }
    merge(existing, current, defaults, false)
}

const SAVED_HEADER: &str = "# rustimal configuration. The settings screen writes only what differs from the defaults.\n# Every option is described in the README; delete a line to use its default.\n\n";

/// Save `current` (all settings, as `Config::to_table`) to the config file.
pub fn save_table(current: &toml::Table) -> Result<(), String> {
    let path = config_path().ok_or("no config folder")?;
    let existing = match std::fs::read_to_string(&path) {
        Ok(text) => text.parse::<toml::Table>().map_err(|e| format!("config.toml has an error, fix it first: {e}"))?,
        Err(_) => toml::Table::new(),
    };
    let merged = merge_changes(&existing, current, &Config::default().to_table());
    let text = toml::to_string_pretty(&merged).map_err(|e| e.to_string())?;
    if let Some(dir) = path.parent() {
        let _ = std::fs::create_dir_all(dir);
        // Keep the hand-written file (with its comments) once, before the first save replaces it.
        let backup = dir.join("config.toml.bak");
        if path.exists() && !backup.exists() {
            let _ = std::fs::copy(&path, backup);
        }
    }
    std::fs::write(&path, format!("{SAVED_HEADER}{text}")).map_err(|e| format!("could not write {}: {e}", path.display()))
}

/// Tell the app when the config file changes, so edits apply without a restart.
pub fn watch(proxy: winit::event_loop::EventLoopProxy<crate::pane::UserEvent>) {
    let Some(path) = config_path() else { return };
    let modified = move || std::fs::metadata(&path).and_then(|m| m.modified()).ok();
    let spawned = std::thread::Builder::new().name("config-watch".into()).spawn(move || {
        let mut last = modified();
        loop {
            std::thread::sleep(std::time::Duration::from_millis(1000));
            let now = modified();
            if now != last {
                last = now;
                // Editors save in steps; let them finish.
                std::thread::sleep(std::time::Duration::from_millis(250));
                if proxy.send_event(crate::pane::UserEvent::ConfigChanged).is_err() {
                    return;
                }
            }
        }
    });
    if let Err(e) = spawned {
        log::warn!("could not watch the config file: {e}");
    }
}

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

    fn table(text: &str) -> toml::Table {
        text.parse().unwrap()
    }

    #[test]
    fn the_defaults_round_trip_through_a_table() {
        let t = Config::default().to_table();
        assert!(t.contains_key("font_size") && t.contains_key("theme") && t.contains_key("keys"));
        let back = Config::from_table(t.clone()).unwrap();
        assert_eq!(back.to_table(), t);
        assert!(Config::from_table(table("font_size = \"big\"")).is_err());
    }

    #[test]
    fn only_changes_are_saved() {
        let defaults = Config::default().to_table();
        // Nothing changed: an empty file stays empty.
        assert!(merge_changes(&toml::Table::new(), &defaults, &defaults).is_empty());
        // One setting and one theme color changed.
        let mut config = Config { font_size: 14.0, ..Config::default() };
        config.theme.accent = "#ff8800".into();
        let merged = merge_changes(&toml::Table::new(), &config.to_table(), &defaults);
        assert_eq!(merged, table("font_size = 14.0\n[theme]\naccent = \"#ff8800\"\n"));
        // Changing it back removes it again.
        let back = merge_changes(&merged, &Config::default().to_table(), &defaults);
        assert!(back.is_empty(), "{back:?}");
    }

    #[test]
    fn unknown_keys_survive_but_reset_shortcuts_go() {
        let defaults = Config::default().to_table();
        let existing = table("my_note = 1\nfont_size = 14.0\n[keys]\nfind = \"ctrl+f\"\nzoom = \"f11\"\n");
        let mut config = Config::from_table(existing.clone()).unwrap();
        config.keys.remove("find"); // reset to its default in the settings screen
        let merged = merge_changes(&existing, &config.to_table(), &defaults);
        assert_eq!(merged, table("my_note = 1\nfont_size = 14.0\n[keys]\nzoom = \"f11\"\n"));
        config.keys.remove("zoom");
        let merged = merge_changes(&merged, &config.to_table(), &defaults);
        assert_eq!(merged, table("my_note = 1\nfont_size = 14.0\n"), "an empty [keys] is dropped");
    }
}