pub mod keys;
pub mod themes;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
pub type Rgba = [f32; 4];
#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(default)]
pub struct Config {
pub font_family: String,
pub font_size: f32,
pub line_height: f32,
pub shell: String,
pub shell_args: Vec<String>,
pub padding: f32,
pub gap: f32,
pub radius: f32,
pub scrollback: usize,
pub cursor_blink: bool,
pub animation_speed: f32,
pub copy_on_select: bool,
pub shell_integration: bool,
pub glass: bool,
pub glass_opacity: f32,
pub notify_after_secs: f32,
pub links_need_ctrl: bool,
pub editor: String,
pub restore_session: bool,
pub hotkey: String,
pub dropdown: bool,
pub dropdown_height: f32,
pub keys: std::collections::BTreeMap<String, crate::config::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: crate::terminal::links::BUILT_IN_EDITOR.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"), s("#ef7a7f"), s("#a3cf8c"), s("#e6c27f"), s("#78a3f2"), s("#c49ae6"), s("#5ccbe0"), s("#c4c9d1"), s("#5d6573"), s("#ff9196"), s("#b9e3a2"), s("#f2d49a"), s("#9bbcff"), s("#d8b2f5"), s("#8be0f0"), s("#eef0f4"), ],
}
}
}
#[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,
}
}
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()
}
}
}
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())
}
}
}
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())
}
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 = "rustimal" # opens files in VS Code in the pane; or a command such as 'code -g "{file}:{line}:{col}"'; 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 {
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)))];
if let Ok(exe) = std::env::current_exe() {
env.push(("RUSTIMAL_EXE".into(), fwd(&exe)));
}
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 {
pub fn take_install_hint(&self) -> bool {
if self.shell_env().is_empty() {
return false; }
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");
pub fn state_dir() -> Option<PathBuf> {
config_path().and_then(|p| p.parent().map(|d| d.join("state")))
}
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();
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";
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);
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()))
}
pub fn watch(proxy: winit::event_loop::EventLoopProxy<crate::terminal::events::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;
std::thread::sleep(std::time::Duration::from_millis(250));
if proxy.send_event(crate::terminal::events::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();
assert!(merge_changes(&toml::Table::new(), &defaults, &defaults).is_empty());
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"));
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"); 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");
}
}