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
|
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<String>,
pub cwd: PathBuf,
pub env: HashMap<String, String>,
pub bindings: HashMap<String, String>,
pub palette: Vec<u32>,
pub startup: Option<String>,
}
pub fn directory() -> PathBuf {
dirs::config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("ducky")
}
pub fn color(s: &str) -> Result<u32> {
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<Self> {
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<Self> {
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::<String, mlua::Value>() {
let (key, value) = pair.map_err(|e| anyhow::anyhow!(e.to_string()))?;
if t.get::<mlua::Value>(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<String> = 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::<String>("background")
.map_err(|e| anyhow::anyhow!(e.to_string()))?,
)?,
foreground: color(
&t.get::<String>("foreground")
.map_err(|e| anyhow::anyhow!(e.to_string()))?,
)?,
accent: color(
&t.get::<String>("accent")
.map_err(|e| anyhow::anyhow!(e.to_string()))?,
)?,
surface: color(
&t.get::<String>("surface")
.map_err(|e| anyhow::anyhow!(e.to_string()))?,
)?,
muted: color(
&t.get::<String>("muted")
.map_err(|e| anyhow::anyhow!(e.to_string()))?,
)?,
border: color(
&t.get::<String>("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::<String>("cwd")
.map_err(|e| anyhow::anyhow!(e.to_string()))?,
),
env: get!("env"),
bindings: get!("bindings"),
palette: palette.iter().map(|v| color(v)).collect::<Result<_>>()?,
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());
}
}
|