Repository navigation
Expand file tree
/
Copy pathconfig.rs
More file actions
347 lines (326 loc) · 12.1 KB
/
Copy pathconfig.rs
File metadata and controls
347 lines (326 loc) · 12.1 KB
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
use std::{env, ffi::OsString, fs, io, path::PathBuf, time::Duration};
use crate::rules::Rule;
use anyhow::{Context, Result, ensure};
use serde::Deserialize;
#[derive(Debug, PartialEq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub(crate) struct Config {
pub(crate) opacity: u8,
pub(crate) fade_ms: u16,
pub(crate) blur_radius: u8,
/// How far a shadow spreads beyond its window, in pixels; zero draws none.
pub(crate) shadow_radius: u8,
pub(crate) shadow_offset_x: i8,
pub(crate) shadow_offset_y: i8,
/// How dark a shadow is where it is darkest, as a percentage.
pub(crate) shadow_opacity: u8,
/// The radius of rounded window corners, in pixels; zero leaves them square.
pub(crate) corner_radius: u8,
pub(crate) max_fps: u16,
pub(crate) vsync: bool,
pub(crate) backend: Backend,
/// Stop compositing while one opaque window covers the whole screen.
pub(crate) unredirect_fullscreen: bool,
/// Per-window rules, from `[[rules]]` tables in order.
pub(crate) rules: Vec<Rule>,
}
/// What draws the frames.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum Backend {
/// The X server, through `XRender`.
#[default]
Xrender,
/// OpenGL ES on the X server's GPU, sharing buffers through DRI3; it falls back to
/// `XRender` when the server or driver cannot.
Gl,
}
impl Default for Config {
fn default() -> Self {
Self {
opacity: 100,
fade_ms: 180,
blur_radius: 4,
shadow_radius: 0,
shadow_offset_x: 0,
shadow_offset_y: 0,
shadow_opacity: 50,
corner_radius: 0,
max_fps: 120,
vsync: true,
backend: Backend::Xrender,
unredirect_fullscreen: false,
rules: Vec::new(),
}
}
}
/// Where the configuration comes from: the `--config` file, or else the first
/// `compust/compust.toml` in the XDG configuration directories. The search runs again on every
/// load, so a reload reads what a restart would.
pub(crate) struct Source(Option<PathBuf>);
impl Source {
pub(crate) fn new(explicit: Option<PathBuf>) -> Self {
Self(explicit)
}
/// The configuration and the file it was read from; no file means built-in defaults.
pub(crate) fn load(&self) -> Result<(Config, Option<PathBuf>)> {
let path = match &self.0 {
Some(path) => Some(path.clone()),
None => discover(&searched())?,
};
let config = match &path {
Some(path) => fs::read_to_string(path)
.map_err(anyhow::Error::from)
.and_then(|text| Config::parse(&text))
.with_context(|| format!("loading {}", path.display()))?,
None => Config::default(),
};
Ok((config, path))
}
/// The files whose change can change what `load` reads: the `--config` file, or every
/// candidate of the search, and the file that each one that is a symbolic link points to.
pub(crate) fn files(&self) -> Vec<PathBuf> {
let mut files = match &self.0 {
Some(path) => vec![path.clone()],
None => searched(),
};
let targets: Vec<_> = files
.iter()
.filter(|file| fs::symlink_metadata(file).is_ok_and(|meta| meta.is_symlink()))
.filter_map(|file| fs::canonicalize(file).ok())
.collect();
files.extend(targets);
files
}
}
/// The configuration files the search looks for, from the environment as it is now.
fn searched() -> Vec<PathBuf> {
candidates(
env::var_os("XDG_CONFIG_HOME"),
env::var_os("HOME"),
env::var_os("XDG_CONFIG_DIRS"),
)
}
/// Configuration files in XDG search order: `$XDG_CONFIG_HOME` (default `~/.config`), then each
/// `$XDG_CONFIG_DIRS` entry (default `/etc/xdg`). Relative directories are ignored, as the
/// base directory specification requires.
fn candidates(
config_home: Option<OsString>,
home: Option<OsString>,
config_dirs: Option<OsString>,
) -> Vec<PathBuf> {
let set = |value: Option<OsString>| value.filter(|value| !value.is_empty());
let user = set(config_home)
.map(PathBuf::from)
.filter(|dir| dir.is_absolute())
.or_else(|| set(home).map(|home| PathBuf::from(home).join(".config")));
let system = set(config_dirs).unwrap_or_else(|| "/etc/xdg".into());
user.into_iter()
.chain(env::split_paths(&system))
.filter(|dir| dir.is_absolute())
.map(|dir| dir.join("compust").join("compust.toml"))
.collect()
}
/// The first candidate present. A dangling link counts as present, so reading it fails instead
/// of falling back to a later file or to the defaults; an inaccessible directory is an error too.
fn discover(candidates: &[PathBuf]) -> Result<Option<PathBuf>> {
for path in candidates {
match fs::symlink_metadata(path) {
Ok(_) => return Ok(Some(path.clone())),
Err(error) if error.kind() == io::ErrorKind::NotFound => (),
Err(error) => {
return Err(error).with_context(|| format!("looking for {}", path.display()));
}
}
}
Ok(None)
}
impl Config {
fn parse(text: &str) -> Result<Self> {
let config: Self = toml::from_str(text).context("parsing compositor configuration")?;
ensure!(config.opacity <= 100, "opacity must be between 0 and 100");
ensure!(
config.blur_radius <= 16,
"blur_radius must be between 0 and 16"
);
ensure!(
config.shadow_radius <= 64,
"shadow_radius must be between 0 and 64"
);
for (name, offset) in [
("shadow_offset_x", config.shadow_offset_x),
("shadow_offset_y", config.shadow_offset_y),
] {
ensure!(
(-64..=64).contains(&offset),
"{name} must be between -64 and 64"
);
}
ensure!(
config.shadow_opacity <= 100,
"shadow_opacity must be between 0 and 100"
);
ensure!(
config.corner_radius <= 64,
"corner_radius must be between 0 and 64"
);
ensure!(
(1..=1000).contains(&config.max_fps),
"max_fps must be between 1 and 1000"
);
for (index, rule) in config.rules.iter().enumerate() {
rule.validate(index + 1)?;
}
Ok(config)
}
pub(crate) fn frame_interval(&self) -> Duration {
Duration::from_nanos(1_000_000_000 / u64::from(self.max_fps))
}
pub(crate) fn fade_duration(&self) -> Duration {
Duration::from_millis(u64::from(self.fade_ms))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_invalid_configuration_at_boundary() {
// Given invalid external values, when parsed, then none enters the runtime.
for input in [
"opacity = 101",
"opacity = -1",
"blur_radius = 17",
"shadow_radius = 65",
"shadow_radius = -1",
"shadow_offset_x = 65",
"shadow_offset_y = -65",
"shadow_opacity = 101",
"corner_radius = 65",
"corner_radius = -1",
"max_fps = 0",
"max_fps = 1001",
"fade_ms = -1",
"opactiy = 80",
"backend = \"vulkan\"",
"backend = \"GL\"",
"unredirect_fullscreen = 1",
] {
assert!(Config::parse(input).is_err(), "accepted {input}");
}
}
#[test]
fn searches_xdg_directories_in_order() {
// Given the XDG variables, when candidates are listed, then the user directory comes
// first and relative or empty entries fall back as the specification requires.
let os = |value: &str| Some(OsString::from(value));
let file = |dir: &str| PathBuf::from(dir).join("compust/compust.toml");
assert_eq!(
candidates(os("/xdg"), os("/home/me"), os("/a:relative:/b")),
[file("/xdg"), file("/a"), file("/b")]
);
assert_eq!(
candidates(os(""), os("/home/me"), None),
[file("/home/me/.config"), file("/etc/xdg")]
);
assert_eq!(
candidates(os("relative"), os("/home/me"), os("")),
[file("/home/me/.config"), file("/etc/xdg")]
);
assert_eq!(candidates(None, None, os("relative")), [] as [PathBuf; 0]);
}
#[test]
fn discovery_takes_first_present_file_and_reports_dangling_links() {
// Given candidates in temporary directories, when discovered, then the first present
// file wins and a dangling link is reported instead of skipped.
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("missing.toml");
let present = dir.path().join("present.toml");
let later = dir.path().join("later.toml");
fs::write(&present, "").unwrap();
fs::write(&later, "").unwrap();
assert_eq!(
discover(&[missing.clone(), present.clone(), later]).unwrap(),
Some(present)
);
assert_eq!(discover(std::slice::from_ref(&missing)).unwrap(), None);
let dangling = dir.path().join("dangling.toml");
std::os::unix::fs::symlink(&missing, &dangling).unwrap();
let found = discover(std::slice::from_ref(&dangling)).unwrap();
assert_eq!(found, Some(dangling.clone()));
assert!(
Source::new(found)
.load()
.is_err_and(|error| format!("{error:#}").contains("dangling.toml"))
);
}
#[test]
fn watched_files_include_where_links_point() {
// Given a `--config` file, it is the file watched, along with its target when it is a
// link.
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("plain.toml");
fs::write(&file, "").unwrap();
assert_eq!(
Source::new(Some(file.clone())).files(),
std::slice::from_ref(&file)
);
let link = dir.path().join("link.toml");
std::os::unix::fs::symlink(&file, &link).unwrap();
assert_eq!(
Source::new(Some(link.clone())).files(),
[link, fs::canonicalize(&file).unwrap()]
);
}
#[test]
fn partial_configuration_preserves_defaults() {
// Given a single setting, when parsed, then other settings retain defaults.
let config = Config::parse("opacity = 73").unwrap();
assert_eq!(config.opacity, 73);
assert_eq!(config.fade_ms, 180);
assert_eq!(config.shadow_radius, 0);
assert_eq!(config.shadow_opacity, 50);
assert_eq!(config.corner_radius, 0);
assert_eq!(
Config::parse("corner_radius = 64").unwrap().corner_radius,
64
);
assert!(config.vsync);
assert!(!config.unredirect_fullscreen);
assert!(
Config::parse("unredirect_fullscreen = true")
.unwrap()
.unredirect_fullscreen
);
assert_eq!(config.backend, Backend::Xrender);
assert_eq!(
Config::parse("backend = \"gl\"").unwrap().backend,
Backend::Gl
);
assert!(config.rules.is_empty());
}
#[test]
fn rules_parse_in_order_and_an_invalid_one_rejects_the_file() {
let config = Config::parse(
"[[rules]]\nwindow_type = \"menu\"\nblur = false\n\n[[rules]]\nwm_class = \"Alacritty\"\nopacity = 90\n",
)
.unwrap();
assert_eq!(config.rules.len(), 2);
let shadows = Config::parse(
"shadow_radius = 64\nshadow_offset_x = -64\nshadow_offset_y = 64\nshadow_opacity = 0\n",
)
.unwrap();
assert_eq!(
(
shadows.shadow_radius,
shadows.shadow_offset_x,
shadows.shadow_offset_y
),
(64, -64, 64)
);
let error = Config::parse("[[rules]]\nblur = false\n").unwrap_err();
assert!(
format!("{error:#}").contains("rule 1 needs wm_class"),
"{error:#}"
);
}
}