use anyhow::{Context, Result, bail}; use mlua::{Lua, Table}; use std::{collections::HashMap, path::PathBuf}; pub const DEFAULT: &str = include_str!("../assets/config.lua"); #[derive(Clone)] pub struct Config { pub font: String, pub font_size: f32, pub line_height: f32, pub padding: f32, pub background: u32, pub foreground: u32, pub accent: u32, pub surface: u32, pub muted: u32, pub border: u32, pub show_status_bar: bool, pub status_bar_toggle: String, pub width: f32, pub height: f32, pub scrollback: usize, pub shell: String, pub args: Vec, pub cwd: PathBuf, pub env: HashMap, pub bindings: HashMap, pub palette: Vec, pub startup: Option, } pub fn directory() -> PathBuf { dirs::config_dir() .unwrap_or_else(|| PathBuf::from(".")) .join("ducky") } pub fn color(s: &str) -> Result { let s = s.strip_prefix('#').unwrap_or(s); if s.len() != 6 { bail!("colors must have six hexadecimal digits"); } Ok(u32::from_str_radix(s, 16)?) } impl Config { pub fn load() -> Result { let dir = directory(); std::fs::create_dir_all(&dir)?; let prompt = dir.join("shell.bash"); if !prompt.exists() { std::fs::write(&prompt, include_str!("../assets/shell.bash"))?; } let path = dir.join("config.lua"); if !path.exists() { std::fs::write(&path, DEFAULT)?; } Self::parse(&std::fs::read_to_string(&path)?, &dir) .with_context(|| format!("loading {}", path.display())) } pub(crate) fn parse(source: &str, dir: &std::path::Path) -> Result { let lua = Lua::new(); let package: Table = lua .globals() .get("package") .map_err(|e| anyhow::anyhow!(e.to_string()))?; let old: String = package.get("path").unwrap_or_default(); package .set( "path", format!( "{}/?.lua;{}/?/init.lua;{}", dir.display(), dir.display(), old ), ) .map_err(|e| anyhow::anyhow!(e.to_string()))?; let defaults: Table = lua .load(DEFAULT) .eval() .map_err(|e| anyhow::anyhow!(e.to_string()))?; let t: Table = lua .load(source) .set_name("config.lua") .eval() .map_err(|e| anyhow::anyhow!(e.to_string()))?; for pair in defaults.pairs::() { let (key, value) = pair.map_err(|e| anyhow::anyhow!(e.to_string()))?; if t.get::(key.as_str()) .unwrap_or(mlua::Value::Nil) .is_nil() { t.set(key, value) .map_err(|e| anyhow::anyhow!(e.to_string()))?; } } macro_rules! get { ($key:literal) => { t.get($key).map_err(|e| anyhow::anyhow!(e.to_string()))? }; } let palette: Vec = get!("palette"); let c = Self { font: get!("font"), font_size: get!("font_size"), line_height: get!("line_height"), padding: get!("padding"), background: color( &t.get::("background") .map_err(|e| anyhow::anyhow!(e.to_string()))?, )?, foreground: color( &t.get::("foreground") .map_err(|e| anyhow::anyhow!(e.to_string()))?, )?, accent: color( &t.get::("accent") .map_err(|e| anyhow::anyhow!(e.to_string()))?, )?, surface: color( &t.get::("surface") .map_err(|e| anyhow::anyhow!(e.to_string()))?, )?, muted: color( &t.get::("muted") .map_err(|e| anyhow::anyhow!(e.to_string()))?, )?, border: color( &t.get::("border") .map_err(|e| anyhow::anyhow!(e.to_string()))?, )?, show_status_bar: get!("show_status_bar"), status_bar_toggle: get!("status_bar_toggle"), width: get!("width"), height: get!("height"), scrollback: get!("scrollback"), shell: get!("shell"), args: get!("args"), cwd: PathBuf::from( t.get::("cwd") .map_err(|e| anyhow::anyhow!(e.to_string()))?, ), env: get!("env"), bindings: get!("bindings"), palette: palette.iter().map(|v| color(v)).collect::>()?, startup: get!("startup"), }; if !(8.0..=48.0).contains(&c.font_size) || !(c.font_size..=80.0).contains(&c.line_height) || !(0.0..=100.0).contains(&c.padding) || !(400.0..=4000.0).contains(&c.width) || !(300.0..=3000.0).contains(&c.height) || c.palette.len() != 16 || c.scrollback > 1_000_000 { bail!( "invalid font, spacing, window dimensions, scrollback, or palette (requires 16 colors)" ); } Ok(c) } } #[cfg(test)] mod tests { use super::*; #[test] fn defaults_and_lua_evaluation() { let c = Config::parse( "return {font_size=16, accent='#abcdef', bindings={['alt-g']='echo hello\\r'}}", std::path::Path::new("/tmp"), ) .unwrap(); assert_eq!(c.font_size, 16.); assert_eq!(c.accent, 0xabcdef); assert_eq!(c.palette.len(), 16); } #[test] fn rejects_bad_config() { assert!(Config::parse("return {font_size=0}", std::path::Path::new("/tmp")).is_err()); assert!(color("#ff").is_err()); assert!(Config::parse("return {accent=false}", std::path::Path::new("/tmp")).is_err()); assert!(Config::parse("return {palette={}}", std::path::Path::new("/tmp")).is_err()); } }