atagen

monolith

public
Star0
Watch0
7a16cb5ea593e24d031fc31a6f465429e365d328
1
ssh://brewery@pls.lobotomise.me:33/atagen/monolith.git
crates/config/src/lib.rsRust903 lines27.4 KB
1
//! The TOML config. Parsing and validation only, the compositor applies it.
2
3
use monolith_ipc::Command;
4
use regex::Regex;
5
use serde::Deserialize;
6
use serde::de::DeserializeOwned;
7
use std::fmt;
8
use std::path::{Path, PathBuf};
9
10
pub const DEFAULT: &str = include_str!("../default.toml");
11
12
#[derive(Debug, Clone)]
13
pub struct Config {
14
    pub general: General,
15
    pub output: Outputs,
16
    pub decoration: Decoration,
17
    pub animation: Animation,
18
    pub keyboard: Keyboard,
19
    pub input: Input,
20
    pub idle: Idle,
21
    pub lid: Lid,
22
    pub xwayland: Xwayland,
23
    pub binds: Vec<Bind>,
24
    pub rules: Vec<Rule>,
25
    pub startup: Vec<Vec<String>>,
26
}
27
28
#[derive(Deserialize, Debug, Clone, PartialEq)]
29
#[serde(default, deny_unknown_fields)]
30
pub struct General {
31
    /// What `Mod` means in binds.
32
    #[serde(rename = "mod")]
33
    pub mod_key: Modifier,
34
    pub gaps: Gaps,
35
    /// A new window splits the one it opens beside along that window's
36
    /// longer side, instead of joining its container.
37
    pub autotile: bool,
38
    /// What a window move does when it meets a neighbour.
39
    #[serde(rename = "move")]
40
    pub move_mode: MoveMode,
41
    pub focus_follows_mouse: bool,
42
    pub mouse_follows_focus: bool,
43
    /// The first window to land on or move to an empty tag nobody is
44
    /// viewing brings that tag into view on its output.
45
    pub view_tag_on_first_window: bool,
46
}
47
48
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
49
#[serde(rename_all = "lowercase")]
50
pub enum MoveMode {
51
    /// Trade places with it.
52
    #[default]
53
    Swap,
54
    /// Join its lane, stacking with it if it is alone.
55
    Merge,
56
}
57
58
impl Default for General {
59
    fn default() -> Self {
60
        Self {
61
            mod_key: Modifier::Super,
62
            gaps: Gaps::default(),
63
            autotile: true,
64
            move_mode: MoveMode::Swap,
65
            focus_follows_mouse: false,
66
            mouse_follows_focus: false,
67
            view_tag_on_first_window: true,
68
        }
69
    }
70
}
71
72
#[derive(Deserialize, Debug, Clone, PartialEq)]
73
#[serde(default, deny_unknown_fields)]
74
pub struct Xwayland {
75
    /// Which X11 clients may read a Wayland-owned selection.
76
    pub selection_access: SelectionAccess,
77
}
78
79
impl Default for Xwayland {
80
    fn default() -> Self {
81
        Self {
82
            selection_access: SelectionAccess::Focused,
83
        }
84
    }
85
}
86
87
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
88
#[serde(rename_all = "lowercase")]
89
pub enum SelectionAccess {
90
    /// Only the X11 window holding keyboard focus.
91
    Focused,
92
    /// Every X11 client, which clipboard managers and headless tools need.
93
    Any,
94
}
95
96
#[derive(Deserialize, Debug, Clone, Copy, PartialEq)]
97
#[serde(default, deny_unknown_fields)]
98
pub struct Gaps {
99
    pub inner: f64,
100
    pub outer: f64,
101
}
102
103
impl Default for Gaps {
104
    fn default() -> Self {
105
        Self {
106
            inner: 8.0,
107
            outer: 8.0,
108
        }
109
    }
110
}
111
112
#[derive(Deserialize, Debug, Clone, PartialEq, Default)]
113
#[serde(default)]
114
pub struct Outputs {
115
    pub vrr: Vrr,
116
    /// Settings for one connector, by name, like `DP-1`.
117
    #[serde(flatten)]
118
    pub named: std::collections::BTreeMap<String, OutputConfig>,
119
}
120
121
/// Transform and position follow a reload. A new mode waits for a restart
122
/// or a replug, since it means a modeset.
123
#[derive(Deserialize, Debug, Clone, PartialEq, Default)]
124
#[serde(default, deny_unknown_fields)]
125
pub struct OutputConfig {
126
    pub transform: OutputTransform,
127
    /// Top left corner in the global layout. Outputs without one are placed
128
    /// to the right of the others.
129
    pub position: Option<[i32; 2]>,
130
    /// `WIDTHxHEIGHT` or `WIDTHxHEIGHT@HZ`. Without a rate the highest one
131
    /// for that size wins.
132
    pub mode: Option<String>,
133
}
134
135
/// Counterclockwise rotation, optionally after flipping horizontally.
136
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
137
#[serde(rename_all = "kebab-case")]
138
pub enum OutputTransform {
139
    #[default]
140
    Normal,
141
    #[serde(rename = "90")]
142
    Rotate90,
143
    #[serde(rename = "180")]
144
    Rotate180,
145
    #[serde(rename = "270")]
146
    Rotate270,
147
    Flipped,
148
    #[serde(rename = "flipped-90")]
149
    Flipped90,
150
    #[serde(rename = "flipped-180")]
151
    Flipped180,
152
    #[serde(rename = "flipped-270")]
153
    Flipped270,
154
}
155
156
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
157
#[serde(rename_all = "lowercase")]
158
pub enum Vrr {
159
    Off,
160
    On,
161
    /// Only while a fullscreen window is shown, where a game sets the pace.
162
    #[default]
163
    Fullscreen,
164
}
165
166
#[derive(Deserialize, Debug, Clone, PartialEq)]
167
#[serde(default, deny_unknown_fields)]
168
pub struct Decoration {
169
    /// Border width in logical pixels, drawn in the gap around each window.
170
    pub border: u32,
171
    pub radius: Corners,
172
    pub focused: Color,
173
    pub unfocused: Color,
174
    pub urgent: Color,
175
}
176
177
/// Corner radii in logical pixels, top left, top right, bottom right and
178
/// bottom left. One number rounds every corner alike.
179
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
180
#[serde(from = "CornersToml")]
181
pub struct Corners(pub [u32; 4]);
182
183
#[derive(Deserialize)]
184
#[serde(
185
    untagged,
186
    expecting = "expected a number or [top left, top right, bottom right, bottom left]"
187
)]
188
enum CornersToml {
189
    All(u32),
190
    Each([u32; 4]),
191
}
192
193
impl From<CornersToml> for Corners {
194
    fn from(c: CornersToml) -> Self {
195
        match c {
196
            CornersToml::All(r) => Self([r; 4]),
197
            CornersToml::Each(r) => Self(r),
198
        }
199
    }
200
}
201
202
impl Default for Decoration {
203
    fn default() -> Self {
204
        Self {
205
            border: 2,
206
            radius: Corners([0; 4]),
207
            focused: Color::rgb(0x88, 0xbf, 0xd1),
208
            unfocused: Color::rgb(0x3b, 0x42, 0x52),
209
            urgent: Color::rgb(0xeb, 0xcb, 0x8b),
210
        }
211
    }
212
}
213
214
/// Straight RGBA from `#rrggbb` or `#rrggbbaa`.
215
#[derive(Debug, Clone, Copy, PartialEq)]
216
pub struct Color(pub [f32; 4]);
217
218
impl Color {
219
    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
220
        Self([r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0])
221
    }
222
}
223
224
impl<'de> Deserialize<'de> for Color {
225
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
226
        let s = String::deserialize(d)?;
227
        let hex = s.strip_prefix('#').unwrap_or(&s);
228
        let bad =
229
            || serde::de::Error::custom(format!("bad colour {s:?}, use #rrggbb or #rrggbbaa"));
230
        if !matches!(hex.len(), 6 | 8) || !hex.is_ascii() {
231
            return Err(bad());
232
        }
233
        let mut c = [1.0f32; 4];
234
        for (i, v) in c.iter_mut().enumerate().take(hex.len() / 2) {
235
            let byte = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).map_err(|_| bad())?;
236
            *v = f32::from(byte) / 255.0;
237
        }
238
        Ok(Self(c))
239
    }
240
}
241
242
#[derive(Deserialize, Debug, Clone, PartialEq)]
243
#[serde(default, deny_unknown_fields)]
244
pub struct Animation {
245
    pub enabled: bool,
246
    pub style: AnimationStyle,
247
    /// Every phase of a planned transition lasts this long.
248
    pub phase_ms: u64,
249
    /// A cubic bezier, as in CSS.
250
    pub curve: [f64; 4],
251
}
252
253
impl Default for Animation {
254
    fn default() -> Self {
255
        Self {
256
            enabled: true,
257
            style: AnimationStyle::Orthogonal,
258
            phase_ms: 160,
259
            curve: [0.45, 0.0, 0.2, 1.0],
260
        }
261
    }
262
}
263
264
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
265
#[serde(rename_all = "lowercase")]
266
pub enum AnimationStyle {
267
    Orthogonal,
268
    Direct,
269
}
270
271
#[derive(Deserialize, Debug, Clone, PartialEq, Default)]
272
#[serde(default, deny_unknown_fields)]
273
pub struct Idle {
274
    /// Seconds without input before every output is switched off, 0 for
275
    /// never.
276
    pub blank_after: u64,
277
}
278
279
#[derive(Deserialize, Debug, Clone, PartialEq, Default)]
280
#[serde(default, deny_unknown_fields)]
281
pub struct Lid {
282
    /// What closing the lid does while no other output is connected.
283
    pub close: LidAction,
284
}
285
286
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
287
#[serde(rename_all = "lowercase")]
288
pub enum LidAction {
289
    #[default]
290
    Suspend,
291
    Poweroff,
292
    /// Leave it to logind or whatever else watches the switch.
293
    Ignore,
294
}
295
296
#[derive(Deserialize, Debug, Clone, PartialEq)]
297
#[serde(default, deny_unknown_fields)]
298
pub struct Keyboard {
299
    pub rules: String,
300
    pub model: String,
301
    pub layout: String,
302
    pub variant: String,
303
    pub options: Option<String>,
304
    pub repeat_delay: i32,
305
    pub repeat_rate: i32,
306
}
307
308
impl Default for Keyboard {
309
    fn default() -> Self {
310
        Self {
311
            rules: String::new(),
312
            model: String::new(),
313
            layout: String::new(),
314
            variant: String::new(),
315
            options: None,
316
            repeat_delay: 200,
317
            repeat_rate: 25,
318
        }
319
    }
320
}
321
322
/// libinput settings for pointing devices. Unset options keep libinput's
323
/// default for the device.
324
#[derive(Debug, Clone, PartialEq, Default)]
325
pub struct Input {
326
    pub pointer: DeviceSettings,
327
    /// Devices that can tap, which libinput only offers on touchpads.
328
    pub touchpad: DeviceSettings,
329
    /// Overrides for devices by name, later entries winning.
330
    pub device: Vec<NamedDevice>,
331
}
332
333
#[derive(Debug, Clone, PartialEq)]
334
pub struct NamedDevice {
335
    pub name: String,
336
    pub settings: DeviceSettings,
337
}
338
339
#[derive(Deserialize, Debug, Clone, PartialEq, Default)]
340
#[serde(default, deny_unknown_fields)]
341
pub struct DeviceSettings {
342
    pub accel_profile: Option<AccelProfile>,
343
    pub accel_speed: Option<f64>,
344
    /// The custom profile's curve, pointer speed sampled every `accel_step`
345
    /// device units per millisecond.
346
    pub accel_points: Option<Vec<f64>>,
347
    pub accel_step: Option<f64>,
348
    pub natural_scroll: Option<bool>,
349
    pub left_handed: Option<bool>,
350
    pub tap: Option<bool>,
351
    pub tap_drag: Option<bool>,
352
    pub tap_drag_lock: Option<bool>,
353
    pub dwt: Option<bool>,
354
    pub middle_emulation: Option<bool>,
355
    pub scroll_method: Option<ScrollMethod>,
356
    pub scroll_button: Option<u32>,
357
    pub click_method: Option<ClickMethod>,
358
    /// Applied by the compositor, libinput has no such setting.
359
    pub scroll_factor: Option<f64>,
360
}
361
362
impl DeviceSettings {
363
    /// `self` with every option `over` sets replaced.
364
    pub fn overlay(&self, over: &Self) -> Self {
365
        Self {
366
            accel_profile: over.accel_profile.or(self.accel_profile),
367
            accel_speed: over.accel_speed.or(self.accel_speed),
368
            accel_points: over
369
                .accel_points
370
                .clone()
371
                .or_else(|| self.accel_points.clone()),
372
            accel_step: over.accel_step.or(self.accel_step),
373
            natural_scroll: over.natural_scroll.or(self.natural_scroll),
374
            left_handed: over.left_handed.or(self.left_handed),
375
            tap: over.tap.or(self.tap),
376
            tap_drag: over.tap_drag.or(self.tap_drag),
377
            tap_drag_lock: over.tap_drag_lock.or(self.tap_drag_lock),
378
            dwt: over.dwt.or(self.dwt),
379
            middle_emulation: over.middle_emulation.or(self.middle_emulation),
380
            scroll_method: over.scroll_method.or(self.scroll_method),
381
            scroll_button: over.scroll_button.or(self.scroll_button),
382
            click_method: over.click_method.or(self.click_method),
383
            scroll_factor: over.scroll_factor.or(self.scroll_factor),
384
        }
385
    }
386
387
    fn validate(&mut self, name: &str, w: &mut Vec<String>) {
388
        if let Some(s) = self.accel_speed
389
            && !(-1.0..=1.0).contains(&s)
390
        {
391
            w.push(format!(
392
                "{name}.accel_speed: {s} is outside -1 to 1, ignored"
393
            ));
394
            self.accel_speed = None;
395
        }
396
        if let Some(f) = self.scroll_factor
397
            && !(f.is_finite() && f >= 0.0)
398
        {
399
            w.push(format!(
400
                "{name}.scroll_factor: {f} must be zero or more, ignored"
401
            ));
402
            self.scroll_factor = None;
403
        }
404
        if self.accel_points.is_some() != self.accel_step.is_some() {
405
            w.push(format!(
406
                "{name}: accel_points needs accel_step and the other way round, both ignored"
407
            ));
408
            self.accel_points = None;
409
            self.accel_step = None;
410
        }
411
    }
412
}
413
414
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
415
#[serde(rename_all = "lowercase")]
416
pub enum AccelProfile {
417
    Flat,
418
    Adaptive,
419
    Custom,
420
}
421
422
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
423
#[serde(rename_all = "kebab-case")]
424
pub enum ScrollMethod {
425
    None,
426
    TwoFinger,
427
    Edge,
428
    OnButtonDown,
429
}
430
431
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
432
#[serde(rename_all = "kebab-case")]
433
pub enum ClickMethod {
434
    ButtonAreas,
435
    Clickfinger,
436
}
437
438
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
439
#[serde(rename_all = "lowercase")]
440
pub enum Modifier {
441
    Super,
442
    Alt,
443
    Ctrl,
444
    Shift,
445
}
446
447
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
448
pub struct Mods {
449
    pub logo: bool,
450
    pub alt: bool,
451
    pub ctrl: bool,
452
    pub shift: bool,
453
}
454
455
impl Mods {
456
    pub fn has(&self, m: Modifier) -> bool {
457
        match m {
458
            Modifier::Super => self.logo,
459
            Modifier::Alt => self.alt,
460
            Modifier::Ctrl => self.ctrl,
461
            Modifier::Shift => self.shift,
462
        }
463
    }
464
465
    fn set(&mut self, m: Modifier) {
466
        match m {
467
            Modifier::Super => self.logo = true,
468
            Modifier::Alt => self.alt = true,
469
            Modifier::Ctrl => self.ctrl = true,
470
            Modifier::Shift => self.shift = true,
471
        }
472
    }
473
}
474
475
#[derive(Debug, Clone, PartialEq)]
476
pub struct Bind {
477
    pub mods: Mods,
478
    /// An xkb keysym name, resolved by the compositor.
479
    pub key: String,
480
    pub command: Command,
481
}
482
483
#[derive(Debug, Clone)]
484
pub struct Rule {
485
    pub app_id: Option<Regex>,
486
    pub title: Option<Regex>,
487
    pub tag: Option<String>,
488
    pub output: Option<String>,
489
    pub floating: Option<bool>,
490
    pub sticky: Option<bool>,
491
    pub scratchpad: Option<String>,
492
}
493
494
/// Everything the matching rules say about a window, later rules winning.
495
#[derive(Debug, Clone, Default, PartialEq)]
496
pub struct Placement {
497
    pub tag: Option<String>,
498
    pub output: Option<String>,
499
    pub floating: Option<bool>,
500
    pub sticky: Option<bool>,
501
    pub scratchpad: Option<String>,
502
}
503
504
#[derive(Debug)]
505
pub enum Error {
506
    Io(PathBuf, std::io::Error),
507
    Toml(toml::de::Error),
508
}
509
510
impl fmt::Display for Error {
511
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512
        match self {
513
            Error::Io(p, e) => write!(f, "{}: {e}", p.display()),
514
            Error::Toml(e) => write!(f, "{e}"),
515
        }
516
    }
517
}
518
519
impl std::error::Error for Error {}
520
521
#[derive(Deserialize)]
522
#[serde(untagged)]
523
enum Words {
524
    Line(String),
525
    List(Vec<String>),
526
}
527
528
#[derive(Deserialize)]
529
#[serde(deny_unknown_fields)]
530
struct RawRule {
531
    app_id: Option<String>,
532
    title: Option<String>,
533
    tag: Option<String>,
534
    output: Option<String>,
535
    floating: Option<bool>,
536
    sticky: Option<bool>,
537
    scratchpad: Option<String>,
538
}
539
540
impl Config {
541
    /// `$MONOLITH_CONFIG`, else `$XDG_CONFIG_HOME/monolith/config.toml`.
542
    pub fn path() -> Option<PathBuf> {
543
        if let Some(p) = std::env::var_os("MONOLITH_CONFIG") {
544
            return Some(p.into());
545
        }
546
        let base = std::env::var_os("XDG_CONFIG_HOME")
547
            .map(PathBuf::from)
548
            .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?;
549
        Some(base.join("monolith/config.toml"))
550
    }
551
552
    /// Loads `path`, or the built-in default when it does not exist.
553
    pub fn load(path: Option<&Path>) -> Result<Loaded, Error> {
554
        match path {
555
            Some(p) => match std::fs::read_to_string(p) {
556
                Ok(text) => Self::parse(&text),
557
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::parse(DEFAULT),
558
                Err(e) => Err(Error::Io(p.to_owned(), e)),
559
            },
560
            None => Self::parse(DEFAULT),
561
        }
562
    }
563
564
    /// Only broken TOML fails. A bad option, bind or rule is left out with a
565
    /// warning, so one typo does not throw away the rest of the file.
566
    pub fn parse(text: &str) -> Result<Loaded, Error> {
567
        let mut table: toml::Table = toml::from_str(text).map_err(Error::Toml)?;
568
        let mut warnings = Vec::new();
569
        let w = &mut warnings;
570
        let general: General = section("general", table.remove("general"), w);
571
        let keyboard = section("keyboard", table.remove("keyboard"), w);
572
        let input = input(table.remove("input"), w);
573
        let idle = section("idle", table.remove("idle"), w);
574
        let lid = section("lid", table.remove("lid"), w);
575
        let animation = section("animation", table.remove("animation"), w);
576
        let xwayland = section("xwayland", table.remove("xwayland"), w);
577
        let decoration = section("decoration", table.remove("decoration"), w);
578
        let output: Outputs = section("output", table.remove("output"), w);
579
        for name in output.named.keys().filter(|n| !connector_like(n)) {
580
            w.push(format!(
581
                "output.{name}: not a connector name like DP-1 or HDMI-A-1, matches nothing"
582
            ));
583
        }
584
        let startup = items("startup", table.remove("startup"), w);
585
        let mut binds = Vec::new();
586
        if let Some(value) = table.remove("binds") {
587
            let entries: toml::Table = entry("binds", value, w).unwrap_or_default();
588
            for (combo, value) in entries {
589
                let name = format!("binds.{combo:?}");
590
                let bind = entry::<Words>(&name, value, w)
591
                    .map(|words| parse_bind(&combo, words, general.mod_key));
592
                match bind {
593
                    Some(Ok(b)) => binds.push(b),
594
                    Some(Err(e)) => w.push(format!("{name}: {e}, left out")),
595
                    None => {}
596
                }
597
            }
598
        }
599
        let regex = |p: Option<String>| p.map(|p| Regex::new(&p)).transpose();
600
        let mut rules = Vec::new();
601
        for (i, raw) in items::<RawRule>("rules", table.remove("rules"), w)
602
            .into_iter()
603
            .enumerate()
604
        {
605
            match (regex(raw.app_id), regex(raw.title)) {
606
                (Ok(app_id), Ok(title)) => rules.push(Rule {
607
                    app_id,
608
                    title,
609
                    tag: raw.tag,
610
                    output: raw.output,
611
                    floating: raw.floating,
612
                    sticky: raw.sticky,
613
                    scratchpad: raw.scratchpad,
614
                }),
615
                (Err(e), _) | (_, Err(e)) => {
616
                    let e = e
617
                        .to_string()
618
                        .split_whitespace()
619
                        .collect::<Vec<_>>()
620
                        .join(" ");
621
                    w.push(format!("rules[{i}]: {e}, left out"));
622
                }
623
            }
624
        }
625
        for key in table.keys() {
626
            w.push(format!("unknown section [{key}], ignored"));
627
        }
628
        let config = Self {
629
            general,
630
            animation,
631
            decoration,
632
            output,
633
            keyboard,
634
            input,
635
            idle,
636
            lid,
637
            xwayland,
638
            binds,
639
            rules,
640
            startup,
641
        };
642
        Ok(Loaded { config, warnings })
643
    }
644
645
    pub fn placement(&self, app_id: &str, title: &str) -> Placement {
646
        let mut p = Placement::default();
647
        let hit = |re: &Option<Regex>, s: &str| re.as_ref().is_none_or(|re| re.is_match(s));
648
        for r in &self.rules {
649
            if !hit(&r.app_id, app_id) || !hit(&r.title, title) {
650
                continue;
651
            }
652
            p.tag = r.tag.clone().or(p.tag);
653
            p.output = r.output.clone().or(p.output);
654
            p.floating = r.floating.or(p.floating);
655
            p.sticky = r.sticky.or(p.sticky);
656
            p.scratchpad = r.scratchpad.clone().or(p.scratchpad);
657
        }
658
        p
659
    }
660
}
661
662
fn parse_bind(combo: &str, words: Words, mod_key: Modifier) -> Result<Bind, String> {
663
    let parts: Vec<&str> = combo.split('+').map(str::trim).collect();
664
    let Some((&key, mods)) = parts.split_last().filter(|(k, _)| !k.is_empty()) else {
665
        return Err("no key".into());
666
    };
667
    let mut set = Mods::default();
668
    for m in mods {
669
        let m = match m.to_ascii_lowercase().as_str() {
670
            "mod" => mod_key,
671
            "super" | "logo" | "win" => Modifier::Super,
672
            "alt" => Modifier::Alt,
673
            "ctrl" | "control" => Modifier::Ctrl,
674
            "shift" => Modifier::Shift,
675
            other => return Err(format!("unknown modifier {other}")),
676
        };
677
        set.set(m);
678
    }
679
    let words: Vec<String> = match words {
680
        Words::Line(s) => s.split_whitespace().map(str::to_owned).collect(),
681
        Words::List(v) => v,
682
    };
683
    let command = Command::parse(&words).map_err(|e| e.0)?;
684
    Ok(Bind {
685
        mods: set,
686
        key: key.to_owned(),
687
        command,
688
    })
689
}
690
691
/// A config and what had to be left out of it.
692
pub struct Loaded {
693
    pub config: Config,
694
    pub warnings: Vec<String>,
695
}
696
697
fn entry<T: DeserializeOwned>(name: &str, value: toml::Value, w: &mut Vec<String>) -> Option<T> {
698
    value
699
        .try_into()
700
        .map_err(|e| w.push(format!("{name}: {}, left out", one_line(&e))))
701
        .ok()
702
}
703
704
fn input(value: Option<toml::Value>, w: &mut Vec<String>) -> Input {
705
    let mut table = match value {
706
        None => toml::Table::new(),
707
        Some(toml::Value::Table(t)) => t,
708
        Some(_) => {
709
            w.push("[input] is not a table, using the defaults".into());
710
            toml::Table::new()
711
        }
712
    };
713
    let mut input = Input {
714
        pointer: section("input.pointer", table.remove("pointer"), w),
715
        touchpad: section("input.touchpad", table.remove("touchpad"), w),
716
        device: Vec::new(),
717
    };
718
    for (i, mut entry) in items::<toml::Table>("input.device", table.remove("device"), w)
719
        .into_iter()
720
        .enumerate()
721
    {
722
        let name = format!("input.device[{i}]");
723
        let Some(toml::Value::String(device)) = entry.remove("name") else {
724
            w.push(format!("{name}: no name, left out"));
725
            continue;
726
        };
727
        input.device.push(NamedDevice {
728
            name: device,
729
            settings: section(&name, Some(toml::Value::Table(entry)), w),
730
        });
731
    }
732
    for key in table.keys() {
733
        w.push(format!("input.{key}: unknown option, ignored"));
734
    }
735
    input.pointer.validate("input.pointer", w);
736
    input.touchpad.validate("input.touchpad", w);
737
    for (i, d) in input.device.iter_mut().enumerate() {
738
        d.settings.validate(&format!("input.device[{i}]"), w);
739
    }
740
    input
741
}
742
743
fn connector_like(name: &str) -> bool {
744
    name.rsplit_once('-').is_some_and(|(kind, n)| {
745
        !kind.is_empty() && !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())
746
    })
747
}
748
749
/// A section with every option that does not fit left at its default.
750
fn section<T: DeserializeOwned + Default>(
751
    name: &str,
752
    value: Option<toml::Value>,
753
    w: &mut Vec<String>,
754
) -> T {
755
    let Some(value) = value else {
756
        return T::default();
757
    };
758
    if let Ok(t) = value.clone().try_into() {
759
        return t;
760
    }
761
    let toml::Value::Table(options) = value else {
762
        w.push(format!("[{name}] is not a table, using the defaults"));
763
        return T::default();
764
    };
765
    let mut kept = toml::Table::new();
766
    for (key, v) in options {
767
        let alone = toml::Table::from_iter([(key.clone(), v.clone())]);
768
        match toml::Value::Table(alone).try_into::<T>() {
769
            Ok(_) => {
770
                kept.insert(key, v);
771
            }
772
            Err(e) => {
773
                let e = one_line(&e);
774
                let fallback = if e.starts_with("unknown field") {
775
                    "ignored"
776
                } else {
777
                    "using the default"
778
                };
779
                w.push(format!("{name}.{key}: {e}, {fallback}"));
780
            }
781
        }
782
    }
783
    toml::Value::Table(kept).try_into().unwrap_or_default()
784
}
785
786
/// An array with the elements that do not fit left out.
787
fn items<T: DeserializeOwned>(
788
    name: &str,
789
    value: Option<toml::Value>,
790
    w: &mut Vec<String>,
791
) -> Vec<T> {
792
    match value {
793
        None => Vec::new(),
794
        Some(toml::Value::Array(a)) => a
795
            .into_iter()
796
            .enumerate()
797
            .filter_map(|(i, v)| entry(&format!("{name}[{i}]"), v, w))
798
            .collect(),
799
        Some(_) => {
800
            w.push(format!("{name} is not an array, left out"));
801
            Vec::new()
802
        }
803
    }
804
}
805
806
fn one_line(e: &toml::de::Error) -> String {
807
    e.message().trim().replace('\n', " ")
808
}
809
#[cfg(test)]
810
mod tests {
811
    use super::*;
812
813
    /// default.toml documents the defaults for users, and the Default impls
814
    /// apply them to sections a user config leaves out. They must agree.
815
    #[test]
816
    fn default_toml_states_the_defaults() {
817
        let loaded = Config::parse(DEFAULT).unwrap();
818
        assert_eq!(loaded.warnings, Vec::<String>::new());
819
        let c = loaded.config;
820
        assert_eq!(c.general, General::default());
821
        assert_eq!(c.output, Outputs::default());
822
        assert_eq!(c.decoration, Decoration::default());
823
        assert_eq!(c.animation, Animation::default());
824
        assert_eq!(c.keyboard, Keyboard::default());
825
        assert_eq!(c.input, Input::default());
826
        assert_eq!(c.idle, Idle::default());
827
        assert_eq!(c.lid, Lid::default());
828
        assert_eq!(c.xwayland, Xwayland::default());
829
        assert!(c.binds.len() > 40);
830
    }
831
832
    #[test]
833
    fn a_bad_option_costs_only_itself() {
834
        let loaded = Config::parse(
835
            r##"
836
            [general]
837
            gaps = { inner = 3, outer = 3 }
838
            focus_follows_mouse = "yes"
839
            typo = 1
840
            [decoration]
841
            radius = [1, 2, 3, 4]
842
            focused = "#zzzzzz"
843
            [binds]
844
            "Mod+Return" = "spawn beer"
845
            "Hyper+x" = "close"
846
            [output.DP-1]
847
            transform = "90"
848
            position = [0, 0]
849
            [output.DP-2]
850
            transform = "sideways"
851
            [output.DP1]
852
            [[rules]]
853
            app_id = "("
854
            [[rules]]
855
            app_id = "^mpv$"
856
            floating = true
857
            "##,
858
        )
859
        .unwrap();
860
        let c = loaded.config;
861
        assert_eq!(c.general.gaps.inner, 3.0);
862
        assert!(!c.general.focus_follows_mouse);
863
        assert_eq!(c.decoration.radius, Corners([1, 2, 3, 4]));
864
        assert_eq!(c.decoration.focused, Decoration::default().focused);
865
        assert_eq!((c.binds.len(), c.rules.len()), (1, 1));
866
        assert_eq!(c.output.named["DP-1"].transform, OutputTransform::Rotate90);
867
        assert!(!c.output.named.contains_key("DP-2"));
868
        assert_eq!(loaded.warnings.len(), 7, "{:#?}", loaded.warnings);
869
    }
870
871
    #[test]
872
    fn a_bad_device_option_costs_only_itself() {
873
        let loaded = Config::parse(
874
            r#"
875
            [input.pointer]
876
            accel_speed = 2.0
877
            scroll_method = "two-finger"
878
            [[input.device]]
879
            name = "Mouse"
880
            accel_profile = "flat"
881
            [[input.device]]
882
            name = "Typo"
883
            tapp = true
884
            [[input.device]]
885
            name = "Half"
886
            accel_points = [0.0, 1.0]
887
            "#,
888
        )
889
        .unwrap();
890
        let input = loaded.config.input;
891
        assert_eq!(input.pointer.accel_speed, None);
892
        assert_eq!(input.pointer.scroll_method, Some(ScrollMethod::TwoFinger));
893
        let names: Vec<_> = input.device.iter().map(|d| d.name.as_str()).collect();
894
        assert_eq!(names, ["Mouse", "Typo", "Half"]);
895
        assert_eq!(
896
            input.device[0].settings.accel_profile,
897
            Some(AccelProfile::Flat)
898
        );
899
        assert_eq!(input.device[1].settings, DeviceSettings::default());
900
        assert_eq!(input.device[2].settings.accel_points, None);
901
        assert_eq!(loaded.warnings.len(), 3, "{:#?}", loaded.warnings);
902
    }
903
}