atagen

monolith

public
Star0
Watch0
df646f6621c6369ec1d1d533f9264fa1dd83e2fc
1
ssh://brewery@pls.lobotomise.me:33/atagen/monolith.git
crates/config/src/lib.rsRust1382 lines42.8 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`, or `nested` for the
117
    /// nested backend's window.
118
    #[serde(flatten)]
119
    pub named: std::collections::BTreeMap<String, OutputConfig>,
120
}
121
122
/// Transform, position and scale follow a reload. A new mode waits for a
123
/// restart or a replug, since it means a modeset.
124
#[derive(Deserialize, Debug, Clone, PartialEq, Default)]
125
#[serde(default, deny_unknown_fields)]
126
pub struct OutputConfig {
127
    pub transform: OutputTransform,
128
    /// Top left corner in the global layout. Outputs without one are placed
129
    /// to the right of the others.
130
    pub position: Option<[i32; 2]>,
131
    /// `WIDTHxHEIGHT` or `WIDTHxHEIGHT@HZ`. Without a rate the highest one
132
    /// for that size wins.
133
    pub mode: Option<String>,
134
    /// How many physical pixels make a logical one, `0.5` to `4.0` in steps of
135
    /// 1/120. Positions are in logical pixels.
136
    pub scale: Option<f64>,
137
}
138
139
impl OutputConfig {
140
    pub fn scale(&self) -> f64 {
141
        self.scale.unwrap_or(1.0)
142
    }
143
144
    fn validate(&mut self, name: &str, w: &mut Vec<String>) {
145
        let Some(s) = self.scale else {
146
            return;
147
        };
148
        if !(MIN_SCALE..=MAX_SCALE).contains(&s) {
149
            w.push(format!(
150
                "{name}.scale: {s} is outside {MIN_SCALE} to {MAX_SCALE}, ignored"
151
            ));
152
            self.scale = None;
153
        } else {
154
            self.scale = Some((s * 120.0).round() / 120.0);
155
        }
156
    }
157
}
158
159
const MIN_SCALE: f64 = 0.5;
160
const MAX_SCALE: f64 = 4.0;
161
162
/// Counterclockwise rotation, optionally after flipping horizontally.
163
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
164
#[serde(rename_all = "kebab-case")]
165
pub enum OutputTransform {
166
    #[default]
167
    Normal,
168
    #[serde(rename = "90")]
169
    Rotate90,
170
    #[serde(rename = "180")]
171
    Rotate180,
172
    #[serde(rename = "270")]
173
    Rotate270,
174
    Flipped,
175
    #[serde(rename = "flipped-90")]
176
    Flipped90,
177
    #[serde(rename = "flipped-180")]
178
    Flipped180,
179
    #[serde(rename = "flipped-270")]
180
    Flipped270,
181
}
182
183
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
184
#[serde(rename_all = "lowercase")]
185
pub enum Vrr {
186
    Off,
187
    On,
188
    /// Only while a fullscreen window is shown, where a game sets the pace.
189
    #[default]
190
    Fullscreen,
191
}
192
193
#[derive(Deserialize, Debug, Clone, PartialEq)]
194
#[serde(default, deny_unknown_fields)]
195
pub struct Decoration {
196
    /// Border width in logical pixels, drawn in the gap around each window.
197
    pub border: u32,
198
    pub radius: Corners,
199
    pub focused: Color,
200
    pub unfocused: Color,
201
    pub urgent: Color,
202
}
203
204
/// Corner radii in logical pixels, top left, top right, bottom right and
205
/// bottom left. One number rounds every corner alike.
206
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
207
#[serde(from = "CornersToml")]
208
pub struct Corners(pub [u32; 4]);
209
210
#[derive(Deserialize)]
211
#[serde(
212
    untagged,
213
    expecting = "expected a number or [top left, top right, bottom right, bottom left]"
214
)]
215
enum CornersToml {
216
    All(u32),
217
    Each([u32; 4]),
218
}
219
220
impl From<CornersToml> for Corners {
221
    fn from(c: CornersToml) -> Self {
222
        match c {
223
            CornersToml::All(r) => Self([r; 4]),
224
            CornersToml::Each(r) => Self(r),
225
        }
226
    }
227
}
228
229
impl Default for Decoration {
230
    fn default() -> Self {
231
        Self {
232
            border: 2,
233
            radius: Corners([0; 4]),
234
            focused: Color::rgb(0x88, 0xbf, 0xd1),
235
            unfocused: Color::rgb(0x3b, 0x42, 0x52),
236
            urgent: Color::rgb(0xeb, 0xcb, 0x8b),
237
        }
238
    }
239
}
240
241
/// Straight RGBA from `#rrggbb` or `#rrggbbaa`.
242
#[derive(Debug, Clone, Copy, PartialEq)]
243
pub struct Color(pub [f32; 4]);
244
245
impl Color {
246
    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
247
        Self([r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0])
248
    }
249
}
250
251
impl<'de> Deserialize<'de> for Color {
252
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
253
        let s = String::deserialize(d)?;
254
        let hex = s.strip_prefix('#').unwrap_or(&s);
255
        let bad =
256
            || serde::de::Error::custom(format!("bad colour {s:?}, use #rrggbb or #rrggbbaa"));
257
        if !matches!(hex.len(), 6 | 8) || !hex.is_ascii() {
258
            return Err(bad());
259
        }
260
        let mut c = [1.0f32; 4];
261
        for (i, v) in c.iter_mut().enumerate().take(hex.len() / 2) {
262
            let byte = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).map_err(|_| bad())?;
263
            *v = f32::from(byte) / 255.0;
264
        }
265
        Ok(Self(c))
266
    }
267
}
268
269
#[derive(Deserialize, Debug, Clone, PartialEq)]
270
#[serde(default, deny_unknown_fields)]
271
pub struct Animation {
272
    pub enabled: bool,
273
    pub style: AnimationStyle,
274
    /// Every phase of a planned transition lasts this long.
275
    pub phase_ms: u64,
276
    /// A cubic bezier, as in CSS.
277
    pub curve: [f64; 4],
278
}
279
280
impl Default for Animation {
281
    fn default() -> Self {
282
        Self {
283
            enabled: true,
284
            style: AnimationStyle::Orthogonal,
285
            phase_ms: 160,
286
            curve: [0.45, 0.0, 0.2, 1.0],
287
        }
288
    }
289
}
290
291
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
292
#[serde(rename_all = "lowercase")]
293
pub enum AnimationStyle {
294
    Orthogonal,
295
    Direct,
296
}
297
298
#[derive(Deserialize, Debug, Clone, PartialEq, Default)]
299
#[serde(default, deny_unknown_fields)]
300
pub struct Idle {
301
    /// Seconds without input before every output is switched off, 0 for
302
    /// never.
303
    pub blank_after: u64,
304
}
305
306
#[derive(Deserialize, Debug, Clone, PartialEq, Default)]
307
#[serde(default, deny_unknown_fields)]
308
pub struct Lid {
309
    /// What closing the lid does while no other output is connected.
310
    pub close: LidAction,
311
}
312
313
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
314
#[serde(rename_all = "lowercase")]
315
pub enum LidAction {
316
    #[default]
317
    Suspend,
318
    Poweroff,
319
    /// Leave it to logind or whatever else watches the switch.
320
    Ignore,
321
}
322
323
#[derive(Deserialize, Debug, Clone, PartialEq)]
324
#[serde(default, deny_unknown_fields)]
325
pub struct Keyboard {
326
    pub rules: String,
327
    pub model: String,
328
    pub layout: String,
329
    pub variant: String,
330
    pub options: Option<String>,
331
    pub repeat_delay: i32,
332
    pub repeat_rate: i32,
333
}
334
335
impl Default for Keyboard {
336
    fn default() -> Self {
337
        Self {
338
            rules: String::new(),
339
            model: String::new(),
340
            layout: String::new(),
341
            variant: String::new(),
342
            options: None,
343
            repeat_delay: 200,
344
            repeat_rate: 25,
345
        }
346
    }
347
}
348
349
/// libinput settings for pointing devices. Unset options keep libinput's
350
/// default for the device.
351
#[derive(Debug, Clone, PartialEq, Default)]
352
pub struct Input {
353
    pub pointer: DeviceSettings,
354
    /// Devices that can tap, which libinput only offers on touchpads.
355
    pub touchpad: DeviceSettings,
356
    /// Overrides for devices by name, later entries winning.
357
    pub device: Vec<NamedDevice>,
358
}
359
360
#[derive(Debug, Clone, PartialEq)]
361
pub struct NamedDevice {
362
    pub name: String,
363
    pub settings: DeviceSettings,
364
}
365
366
#[derive(Deserialize, Debug, Clone, PartialEq, Default)]
367
#[serde(default, deny_unknown_fields)]
368
pub struct DeviceSettings {
369
    pub accel_profile: Option<AccelProfile>,
370
    pub accel_speed: Option<f64>,
371
    /// The custom profile's curve, pointer speed sampled every `accel_step`
372
    /// device units per millisecond.
373
    pub accel_points: Option<Vec<f64>>,
374
    pub accel_step: Option<f64>,
375
    pub natural_scroll: Option<bool>,
376
    pub left_handed: Option<bool>,
377
    pub tap: Option<bool>,
378
    pub tap_drag: Option<bool>,
379
    pub tap_drag_lock: Option<bool>,
380
    pub dwt: Option<bool>,
381
    pub middle_emulation: Option<bool>,
382
    pub scroll_method: Option<ScrollMethod>,
383
    pub scroll_button: Option<u32>,
384
    pub click_method: Option<ClickMethod>,
385
    /// Applied by the compositor, libinput has no such setting.
386
    pub scroll_factor: Option<f64>,
387
}
388
389
impl DeviceSettings {
390
    /// `self` with every option `over` sets replaced.
391
    pub fn overlay(&self, over: &Self) -> Self {
392
        Self {
393
            accel_profile: over.accel_profile.or(self.accel_profile),
394
            accel_speed: over.accel_speed.or(self.accel_speed),
395
            accel_points: over
396
                .accel_points
397
                .clone()
398
                .or_else(|| self.accel_points.clone()),
399
            accel_step: over.accel_step.or(self.accel_step),
400
            natural_scroll: over.natural_scroll.or(self.natural_scroll),
401
            left_handed: over.left_handed.or(self.left_handed),
402
            tap: over.tap.or(self.tap),
403
            tap_drag: over.tap_drag.or(self.tap_drag),
404
            tap_drag_lock: over.tap_drag_lock.or(self.tap_drag_lock),
405
            dwt: over.dwt.or(self.dwt),
406
            middle_emulation: over.middle_emulation.or(self.middle_emulation),
407
            scroll_method: over.scroll_method.or(self.scroll_method),
408
            scroll_button: over.scroll_button.or(self.scroll_button),
409
            click_method: over.click_method.or(self.click_method),
410
            scroll_factor: over.scroll_factor.or(self.scroll_factor),
411
        }
412
    }
413
414
    fn validate(&mut self, name: &str, w: &mut Vec<String>) {
415
        if let Some(s) = self.accel_speed
416
            && !(-1.0..=1.0).contains(&s)
417
        {
418
            w.push(format!(
419
                "{name}.accel_speed: {s} is outside -1 to 1, ignored"
420
            ));
421
            self.accel_speed = None;
422
        }
423
        if let Some(f) = self.scroll_factor
424
            && !(f.is_finite() && f >= 0.0)
425
        {
426
            w.push(format!(
427
                "{name}.scroll_factor: {f} must be zero or more, ignored"
428
            ));
429
            self.scroll_factor = None;
430
        }
431
        if self.accel_points.is_some() != self.accel_step.is_some() {
432
            w.push(format!(
433
                "{name}: accel_points needs accel_step and the other way round, both ignored"
434
            ));
435
            self.accel_points = None;
436
            self.accel_step = None;
437
        }
438
    }
439
}
440
441
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
442
#[serde(rename_all = "lowercase")]
443
pub enum AccelProfile {
444
    Flat,
445
    Adaptive,
446
    Custom,
447
}
448
449
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
450
#[serde(rename_all = "kebab-case")]
451
pub enum ScrollMethod {
452
    None,
453
    TwoFinger,
454
    Edge,
455
    OnButtonDown,
456
}
457
458
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
459
#[serde(rename_all = "kebab-case")]
460
pub enum ClickMethod {
461
    ButtonAreas,
462
    Clickfinger,
463
}
464
465
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
466
#[serde(rename_all = "lowercase")]
467
pub enum Modifier {
468
    Super,
469
    Alt,
470
    Ctrl,
471
    Shift,
472
}
473
474
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
475
pub struct Mods {
476
    pub logo: bool,
477
    pub alt: bool,
478
    pub ctrl: bool,
479
    pub shift: bool,
480
}
481
482
impl Mods {
483
    pub fn has(&self, m: Modifier) -> bool {
484
        match m {
485
            Modifier::Super => self.logo,
486
            Modifier::Alt => self.alt,
487
            Modifier::Ctrl => self.ctrl,
488
            Modifier::Shift => self.shift,
489
        }
490
    }
491
492
    fn set(&mut self, m: Modifier) {
493
        match m {
494
            Modifier::Super => self.logo = true,
495
            Modifier::Alt => self.alt = true,
496
            Modifier::Ctrl => self.ctrl = true,
497
            Modifier::Shift => self.shift = true,
498
        }
499
    }
500
}
501
502
#[derive(Debug, Clone, PartialEq)]
503
pub struct Bind {
504
    pub mods: Mods,
505
    /// An xkb keysym name, resolved by the compositor.
506
    pub key: String,
507
    pub command: Command,
508
}
509
510
#[derive(Debug, Clone)]
511
pub struct Rule {
512
    pub when: Matcher,
513
    pub set: Placement,
514
}
515
516
/// What a rule asks of a window. Every matcher given must hit.
517
#[derive(Debug, Clone, Default)]
518
pub struct Matcher {
519
    pub app_id: Option<Regex>,
520
    pub title: Option<Regex>,
521
    pub initial_title: Option<Regex>,
522
    pub class: Option<Regex>,
523
    pub instance: Option<Regex>,
524
    pub xwayland: Option<bool>,
525
    pub dialog: Option<bool>,
526
    pub parent_app_id: Option<Regex>,
527
}
528
529
/// What the rules can see of a window. `class` and `instance` are None for
530
/// windows that are not X11, and `parent_app_id` for those without a parent.
531
#[derive(Debug, Clone, Copy, Default)]
532
pub struct Subject<'a> {
533
    pub app_id: &'a str,
534
    pub title: &'a str,
535
    pub initial_title: &'a str,
536
    pub class: Option<&'a str>,
537
    pub instance: Option<&'a str>,
538
    pub xwayland: bool,
539
    pub dialog: bool,
540
    pub parent_app_id: Option<&'a str>,
541
}
542
543
impl Matcher {
544
    fn hits(&self, s: &Subject) -> bool {
545
        fn re(re: &Option<Regex>, s: Option<&str>) -> bool {
546
            re.as_ref()
547
                .is_none_or(|re| s.is_some_and(|s| re.is_match(s)))
548
        }
549
        re(&self.app_id, Some(s.app_id))
550
            && re(&self.title, Some(s.title))
551
            && re(&self.initial_title, Some(s.initial_title))
552
            && re(&self.class, s.class)
553
            && re(&self.instance, s.instance)
554
            && re(&self.parent_app_id, s.parent_app_id)
555
            && self.xwayland.is_none_or(|x| x == s.xwayland)
556
            && self.dialog.is_none_or(|d| d == s.dialog)
557
    }
558
}
559
560
/// Where a rule puts a floating window.
561
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
562
pub enum At {
563
    /// From the top left of the output's area.
564
    Position(i32, i32),
565
    Center,
566
}
567
568
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
569
#[serde(rename_all = "lowercase")]
570
pub enum IdleInhibit {
571
    /// While the window is on screen.
572
    Visible,
573
    Fullscreen,
574
}
575
576
/// Everything the matching rules say about a window, later rules winning.
577
#[derive(Debug, Clone, Default, PartialEq)]
578
pub struct Placement {
579
    pub tag: Option<String>,
580
    pub output: Option<String>,
581
    pub floating: Option<bool>,
582
    pub sticky: Option<bool>,
583
    pub scratchpad: Option<String>,
584
    pub size: Option<(u32, u32)>,
585
    pub at: Option<At>,
586
    /// A zero axis puts no lower bound on it.
587
    pub min_size: Option<(u32, u32)>,
588
    /// A zero axis puts no upper bound on it.
589
    pub max_size: Option<(u32, u32)>,
590
    pub fullscreen: Option<bool>,
591
    pub focus: Option<bool>,
592
    pub opacity: Option<f32>,
593
    pub idle_inhibit: Option<IdleInhibit>,
594
    pub vrr: Option<bool>,
595
    /// Inert until tearing presentation exists.
596
    pub tearing: Option<bool>,
597
}
598
599
impl Placement {
600
    fn over(&mut self, r: &Placement) {
601
        self.tag = r.tag.clone().or(self.tag.take());
602
        self.output = r.output.clone().or(self.output.take());
603
        self.floating = r.floating.or(self.floating);
604
        self.sticky = r.sticky.or(self.sticky);
605
        self.scratchpad = r.scratchpad.clone().or(self.scratchpad.take());
606
        self.size = r.size.or(self.size);
607
        self.at = r.at.or(self.at);
608
        self.min_size = r.min_size.or(self.min_size);
609
        self.max_size = r.max_size.or(self.max_size);
610
        self.fullscreen = r.fullscreen.or(self.fullscreen);
611
        self.focus = r.focus.or(self.focus);
612
        self.opacity = r.opacity.or(self.opacity);
613
        self.idle_inhibit = r.idle_inhibit.or(self.idle_inhibit);
614
        self.vrr = r.vrr.or(self.vrr);
615
        self.tearing = r.tearing.or(self.tearing);
616
    }
617
618
    /// Bounds `(w, h)` by `min_size` and `max_size`.
619
    pub fn clamp_size(&self, w: f64, h: f64) -> (f64, f64) {
620
        let axis = |v: f64, min: Option<u32>, max: Option<u32>| {
621
            let v = min.map_or(v, |m| v.max(f64::from(m)));
622
            max.filter(|&m| m > 0).map_or(v, |m| v.min(f64::from(m)))
623
        };
624
        let (min, max) = (self.min_size, self.max_size);
625
        (
626
            axis(w, min.map(|s| s.0), max.map(|s| s.0)),
627
            axis(h, min.map(|s| s.1), max.map(|s| s.1)),
628
        )
629
    }
630
}
631
632
#[derive(Debug)]
633
pub enum Error {
634
    Io(PathBuf, std::io::Error),
635
    Toml(toml::de::Error),
636
}
637
638
impl fmt::Display for Error {
639
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
640
        match self {
641
            Error::Io(p, e) => write!(f, "{}: {e}", p.display()),
642
            Error::Toml(e) => write!(f, "{e}"),
643
        }
644
    }
645
}
646
647
impl std::error::Error for Error {}
648
649
#[derive(Deserialize)]
650
#[serde(untagged)]
651
enum Words {
652
    Line(String),
653
    List(Vec<String>),
654
}
655
656
#[derive(Deserialize)]
657
#[serde(deny_unknown_fields)]
658
struct RawRule {
659
    app_id: Option<String>,
660
    title: Option<String>,
661
    initial_title: Option<String>,
662
    class: Option<String>,
663
    instance: Option<String>,
664
    xwayland: Option<bool>,
665
    dialog: Option<bool>,
666
    parent_app_id: Option<String>,
667
    tag: Option<String>,
668
    output: Option<String>,
669
    floating: Option<bool>,
670
    sticky: Option<bool>,
671
    scratchpad: Option<String>,
672
    size: Option<[u32; 2]>,
673
    position: Option<[i32; 2]>,
674
    center: Option<bool>,
675
    min_size: Option<[u32; 2]>,
676
    max_size: Option<[u32; 2]>,
677
    fullscreen: Option<bool>,
678
    focus: Option<bool>,
679
    opacity: Option<f32>,
680
    idle_inhibit: Option<IdleInhibit>,
681
    vrr: Option<bool>,
682
    tearing: Option<bool>,
683
}
684
685
impl RawRule {
686
    /// A pattern that does not compile drops the rule, since without it the
687
    /// rule would hit every window. A bad effect only drops itself.
688
    fn build(self, name: &str, warn: &mut Vec<String>) -> Result<Rule, regex::Error> {
689
        let regex = |p: Option<String>| p.map(|p| Regex::new(&p)).transpose();
690
        let when = Matcher {
691
            app_id: regex(self.app_id)?,
692
            title: regex(self.title)?,
693
            initial_title: regex(self.initial_title)?,
694
            class: regex(self.class)?,
695
            instance: regex(self.instance)?,
696
            xwayland: self.xwayland,
697
            dialog: self.dialog,
698
            parent_app_id: regex(self.parent_app_id)?,
699
        };
700
        let mut set = Placement {
701
            tag: self.tag,
702
            output: self.output,
703
            floating: self.floating,
704
            sticky: self.sticky,
705
            scratchpad: self.scratchpad,
706
            size: self.size.map(|[a, b]| (a, b)),
707
            at: self.position.map(|[x, y]| At::Position(x, y)),
708
            min_size: self.min_size.map(|[a, b]| (a, b)),
709
            max_size: self.max_size.map(|[a, b]| (a, b)),
710
            fullscreen: self.fullscreen,
711
            focus: self.focus,
712
            opacity: self.opacity,
713
            idle_inhibit: self.idle_inhibit,
714
            vrr: self.vrr,
715
            tearing: self.tearing,
716
        };
717
        if self.center == Some(true) {
718
            if set.at.is_some() {
719
                warn.push(format!("{name}: position and center both set, center wins"));
720
            }
721
            set.at = Some(At::Center);
722
        }
723
        if set.size.is_some_and(|(w, h)| w == 0 || h == 0) {
724
            warn.push(format!("{name}.size: must be above zero, ignored"));
725
            set.size = None;
726
        }
727
        if let (Some(min), Some(max)) = (set.min_size, set.max_size)
728
            && [(min.0, max.0), (min.1, max.1)]
729
                .iter()
730
                .any(|&(lo, hi)| hi > 0 && lo > hi)
731
        {
732
            warn.push(format!(
733
                "{name}: min_size is larger than max_size, both ignored"
734
            ));
735
            set.min_size = None;
736
            set.max_size = None;
737
        }
738
        if let Some(o) = set.opacity
739
            && !(0.0..=1.0).contains(&o)
740
        {
741
            warn.push(format!("{name}.opacity: {o} is outside 0 to 1, ignored"));
742
            set.opacity = None;
743
        }
744
        Ok(Rule { when, set })
745
    }
746
}
747
748
impl Config {
749
    /// `$MONOLITH_CONFIG`, else `$XDG_CONFIG_HOME/monolith/config.toml`.
750
    pub fn path() -> Option<PathBuf> {
751
        if let Some(p) = std::env::var_os("MONOLITH_CONFIG") {
752
            return Some(p.into());
753
        }
754
        let base = std::env::var_os("XDG_CONFIG_HOME")
755
            .map(PathBuf::from)
756
            .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?;
757
        Some(base.join("monolith/config.toml"))
758
    }
759
760
    /// Loads `path`, or the built-in default when it does not exist.
761
    pub fn load(path: Option<&Path>) -> Result<Loaded, Error> {
762
        match path {
763
            Some(p) => match std::fs::read_to_string(p) {
764
                Ok(text) => Self::parse(&text),
765
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::parse(DEFAULT),
766
                Err(e) => Err(Error::Io(p.to_owned(), e)),
767
            },
768
            None => Self::parse(DEFAULT),
769
        }
770
    }
771
772
    /// Only TOML too broken to repair line by line fails. A bad option, bind
773
    /// or rule is left out with a warning, so one typo does not throw away the
774
    /// rest of the file.
775
    pub fn parse(text: &str) -> Result<Loaded, Error> {
776
        let mut warnings = Vec::new();
777
        let mut table = lenient_table(text, &mut warnings)?;
778
        let w = &mut warnings;
779
        let general: General = section("general", table.remove("general"), w);
780
        let keyboard = section("keyboard", table.remove("keyboard"), w);
781
        let input = input(table.remove("input"), w);
782
        let idle = section("idle", table.remove("idle"), w);
783
        let lid = section("lid", table.remove("lid"), w);
784
        let animation = section("animation", table.remove("animation"), w);
785
        let xwayland = section("xwayland", table.remove("xwayland"), w);
786
        let decoration = section("decoration", table.remove("decoration"), w);
787
        let mut output: Outputs = section("output", table.remove("output"), w);
788
        for name in output
789
            .named
790
            .keys()
791
            .filter(|n| *n != "nested" && !connector_like(n))
792
        {
793
            w.push(format!(
794
                "output.{name}: not a connector name like DP-1 or HDMI-A-1, matches nothing"
795
            ));
796
        }
797
        for (name, config) in &mut output.named {
798
            config.validate(&format!("output.{name}"), w);
799
        }
800
        let startup = items("startup", table.remove("startup"), w);
801
        let mut binds = Vec::new();
802
        if let Some(value) = table.remove("binds") {
803
            let entries: toml::Table = entry("binds", value, w).unwrap_or_default();
804
            for (combo, value) in entries {
805
                let name = format!("binds.{combo:?}");
806
                let bind = entry::<Words>(&name, value, w)
807
                    .map(|words| parse_bind(&combo, words, general.mod_key));
808
                match bind {
809
                    Some(Ok(b)) => binds.push(b),
810
                    Some(Err(e)) => w.push(format!("{name}: {e}, left out")),
811
                    None => {}
812
                }
813
            }
814
        }
815
        let mut rules = Vec::new();
816
        for (i, raw) in items::<RawRule>("rules", table.remove("rules"), w)
817
            .into_iter()
818
            .enumerate()
819
        {
820
            let name = format!("rules[{i}]");
821
            match raw.build(&name, w) {
822
                Ok(rule) => rules.push(rule),
823
                Err(e) => {
824
                    let e = e
825
                        .to_string()
826
                        .split_whitespace()
827
                        .collect::<Vec<_>>()
828
                        .join(" ");
829
                    w.push(format!("{name}: {e}, left out"));
830
                }
831
            }
832
        }
833
        for key in table.keys() {
834
            w.push(format!("unknown section [{key}], ignored"));
835
        }
836
        let config = Self {
837
            general,
838
            animation,
839
            decoration,
840
            output,
841
            keyboard,
842
            input,
843
            idle,
844
            lid,
845
            xwayland,
846
            binds,
847
            rules,
848
            startup,
849
        };
850
        Ok(Loaded { config, warnings })
851
    }
852
853
    pub fn placement(&self, window: &Subject) -> Placement {
854
        let mut p = Placement::default();
855
        for r in self.rules.iter().filter(|r| r.when.hits(window)) {
856
            p.over(&r.set);
857
        }
858
        p
859
    }
860
}
861
862
fn parse_bind(combo: &str, words: Words, mod_key: Modifier) -> Result<Bind, String> {
863
    let parts: Vec<&str> = combo.split('+').map(str::trim).collect();
864
    let Some((&key, mods)) = parts.split_last().filter(|(k, _)| !k.is_empty()) else {
865
        return Err("no key".into());
866
    };
867
    let mut set = Mods::default();
868
    for m in mods {
869
        let m = match m.to_ascii_lowercase().as_str() {
870
            "mod" => mod_key,
871
            "super" | "logo" | "win" => Modifier::Super,
872
            "alt" => Modifier::Alt,
873
            "ctrl" | "control" => Modifier::Ctrl,
874
            "shift" => Modifier::Shift,
875
            other => return Err(format!("unknown modifier {other}")),
876
        };
877
        set.set(m);
878
    }
879
    let words: Vec<String> = match words {
880
        Words::Line(s) => s.split_whitespace().map(str::to_owned).collect(),
881
        Words::List(v) => v,
882
    };
883
    let command = Command::parse(&words).map_err(|e| e.0)?;
884
    Ok(Bind {
885
        mods: set,
886
        key: key.to_owned(),
887
        command,
888
    })
889
}
890
891
/// A config and what had to be left out of it.
892
pub struct Loaded {
893
    pub config: Config,
894
    pub warnings: Vec<String>,
895
}
896
897
/// Parses TOML, dropping each line the parser rejects and trying again, so a
898
/// syntax error costs its own line rather than the whole file. An unclosed
899
/// table or array is reported lines after the mistake, so the culprit is
900
/// the nearby line whose removal clears that error, or else gets furthest.
901
fn lenient_table(text: &str, w: &mut Vec<String>) -> Result<toml::Table, Error> {
902
    const MAX_BAD_LINES: usize = 32;
903
    const LOOK_BACK: usize = 4;
904
    let mut lines: Vec<(usize, &str)> = text.lines().enumerate().map(|(i, l)| (i + 1, l)).collect();
905
    let join =
906
        |lines: &[(usize, &str)]| lines.iter().map(|(_, l)| *l).collect::<Vec<_>>().join("\n");
907
    let failing_line = |lines: &[(usize, &str)], e: &toml::de::Error| -> Option<usize> {
908
        let at = e.span()?.start;
909
        let text = join(lines);
910
        let index = text[..at.min(text.len())].matches('\n').count();
911
        Some(index.min(lines.len().saturating_sub(1)))
912
    };
913
    for _ in 0..MAX_BAD_LINES {
914
        let e = match toml::from_str(&join(&lines)) {
915
            Ok(table) => return Ok(table),
916
            Err(e) => e,
917
        };
918
        let Some(at) = failing_line(&lines, &e) else {
919
            return Err(Error::Toml(e));
920
        };
921
        let progress = |drop: usize| {
922
            let mut rest = lines.clone();
923
            rest.remove(drop);
924
            match toml::from_str::<toml::Table>(&join(&rest)) {
925
                Ok(_) => (true, usize::MAX),
926
                Err(next) => (
927
                    next.message() != e.message(),
928
                    failing_line(&rest, &next).map_or(0, |i| rest[i].0),
929
                ),
930
            }
931
        };
932
        let culprit = (at.saturating_sub(LOOK_BACK)..=at)
933
            .filter(|&i| !lines[i].1.trim().is_empty())
934
            .max_by_key(|&i| progress(i))
935
            .unwrap_or(at);
936
        let (line, _) = lines.remove(culprit);
937
        w.push(format!("line {line}: {}, left out", e.message().trim()));
938
    }
939
    toml::from_str(&join(&lines)).map_err(Error::Toml)
940
}
941
942
fn entry<T: DeserializeOwned>(name: &str, value: toml::Value, w: &mut Vec<String>) -> Option<T> {
943
    value
944
        .try_into()
945
        .map_err(|e| w.push(format!("{name}: {}, left out", one_line(&e))))
946
        .ok()
947
}
948
949
fn input(value: Option<toml::Value>, w: &mut Vec<String>) -> Input {
950
    let mut table = match value {
951
        None => toml::Table::new(),
952
        Some(toml::Value::Table(t)) => t,
953
        Some(_) => {
954
            w.push("[input] is not a table, using the defaults".into());
955
            toml::Table::new()
956
        }
957
    };
958
    let mut input = Input {
959
        pointer: section("input.pointer", table.remove("pointer"), w),
960
        touchpad: section("input.touchpad", table.remove("touchpad"), w),
961
        device: Vec::new(),
962
    };
963
    for (i, mut entry) in items::<toml::Table>("input.device", table.remove("device"), w)
964
        .into_iter()
965
        .enumerate()
966
    {
967
        let name = format!("input.device[{i}]");
968
        let Some(toml::Value::String(device)) = entry.remove("name") else {
969
            w.push(format!("{name}: no name, left out"));
970
            continue;
971
        };
972
        input.device.push(NamedDevice {
973
            name: device,
974
            settings: section(&name, Some(toml::Value::Table(entry)), w),
975
        });
976
    }
977
    for key in table.keys() {
978
        w.push(format!("input.{key}: unknown option, ignored"));
979
    }
980
    input.pointer.validate("input.pointer", w);
981
    input.touchpad.validate("input.touchpad", w);
982
    for (i, d) in input.device.iter_mut().enumerate() {
983
        d.settings.validate(&format!("input.device[{i}]"), w);
984
    }
985
    input
986
}
987
988
fn connector_like(name: &str) -> bool {
989
    name.rsplit_once('-').is_some_and(|(kind, n)| {
990
        !kind.is_empty() && !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())
991
    })
992
}
993
994
/// A section with every option that does not fit left at its default.
995
fn section<T: DeserializeOwned + Default>(
996
    name: &str,
997
    value: Option<toml::Value>,
998
    w: &mut Vec<String>,
999
) -> T {
1000
    let Some(value) = value else {
1001
        return T::default();
1002
    };
1003
    if let Ok(t) = value.clone().try_into() {
1004
        return t;
1005
    }
1006
    let toml::Value::Table(options) = value else {
1007
        w.push(format!("[{name}] is not a table, using the defaults"));
1008
        return T::default();
1009
    };
1010
    let mut kept = toml::Table::new();
1011
    for (key, v) in options {
1012
        let alone = toml::Table::from_iter([(key.clone(), v.clone())]);
1013
        match toml::Value::Table(alone).try_into::<T>() {
1014
            Ok(_) => {
1015
                kept.insert(key, v);
1016
            }
1017
            Err(e) => {
1018
                let e = one_line(&e);
1019
                let fallback = if e.starts_with("unknown field") {
1020
                    "ignored"
1021
                } else {
1022
                    "using the default"
1023
                };
1024
                w.push(format!("{name}.{key}: {e}, {fallback}"));
1025
            }
1026
        }
1027
    }
1028
    toml::Value::Table(kept).try_into().unwrap_or_default()
1029
}
1030
1031
/// An array with the elements that do not fit left out.
1032
fn items<T: DeserializeOwned>(
1033
    name: &str,
1034
    value: Option<toml::Value>,
1035
    w: &mut Vec<String>,
1036
) -> Vec<T> {
1037
    match value {
1038
        None => Vec::new(),
1039
        Some(toml::Value::Array(a)) => a
1040
            .into_iter()
1041
            .enumerate()
1042
            .filter_map(|(i, v)| entry(&format!("{name}[{i}]"), v, w))
1043
            .collect(),
1044
        Some(_) => {
1045
            w.push(format!("{name} is not an array, left out"));
1046
            Vec::new()
1047
        }
1048
    }
1049
}
1050
1051
fn one_line(e: &toml::de::Error) -> String {
1052
    e.message().trim().replace('\n', " ")
1053
}
1054
#[cfg(test)]
1055
mod tests {
1056
    use super::*;
1057
1058
    /// default.toml documents the defaults for users, and the Default impls
1059
    /// apply them to sections a user config leaves out. They must agree.
1060
    #[test]
1061
    fn default_toml_states_the_defaults() {
1062
        let loaded = Config::parse(DEFAULT).unwrap();
1063
        assert_eq!(loaded.warnings, Vec::<String>::new());
1064
        let c = loaded.config;
1065
        assert_eq!(c.general, General::default());
1066
        assert_eq!(c.output, Outputs::default());
1067
        assert_eq!(c.decoration, Decoration::default());
1068
        assert_eq!(c.animation, Animation::default());
1069
        assert_eq!(c.keyboard, Keyboard::default());
1070
        assert_eq!(c.input, Input::default());
1071
        assert_eq!(c.idle, Idle::default());
1072
        assert_eq!(c.lid, Lid::default());
1073
        assert_eq!(c.xwayland, Xwayland::default());
1074
        assert!(c.binds.len() > 40);
1075
    }
1076
1077
    #[test]
1078
    fn output_scale_is_snapped_and_range_checked() {
1079
        let loaded = Config::parse(
1080
            r#"
1081
            [output.DP-1]
1082
            scale = 1.5
1083
            [output.DP-2]
1084
            scale = 1.3333
1085
            [output.DP-3]
1086
            scale = 9.0
1087
            [output.nested]
1088
            scale = 2.0
1089
            "#,
1090
        )
1091
        .unwrap();
1092
        let named = &loaded.config.output.named;
1093
        assert_eq!(named["DP-1"].scale(), 1.5);
1094
        assert_eq!(named["DP-2"].scale(), 160.0 / 120.0);
1095
        assert_eq!(named["DP-3"].scale(), 1.0);
1096
        assert_eq!(loaded.warnings.len(), 1, "{:#?}", loaded.warnings);
1097
    }
1098
1099
    #[test]
1100
    fn a_bad_option_costs_only_itself() {
1101
        let loaded = Config::parse(
1102
            r##"
1103
            [general]
1104
            gaps = { inner = 3, outer = 3 }
1105
            focus_follows_mouse = "yes"
1106
            typo = 1
1107
            [decoration]
1108
            radius = [1, 2, 3, 4]
1109
            focused = "#zzzzzz"
1110
            [binds]
1111
            "Mod+Return" = "spawn beer"
1112
            "Hyper+x" = "close"
1113
            [output.DP-1]
1114
            transform = "90"
1115
            position = [0, 0]
1116
            [output.DP-2]
1117
            transform = "sideways"
1118
            [output.DP1]
1119
            [[rules]]
1120
            app_id = "("
1121
            [[rules]]
1122
            app_id = "^mpv$"
1123
            floating = true
1124
            "##,
1125
        )
1126
        .unwrap();
1127
        let c = loaded.config;
1128
        assert_eq!(c.general.gaps.inner, 3.0);
1129
        assert!(!c.general.focus_follows_mouse);
1130
        assert_eq!(c.decoration.radius, Corners([1, 2, 3, 4]));
1131
        assert_eq!(c.decoration.focused, Decoration::default().focused);
1132
        assert_eq!((c.binds.len(), c.rules.len()), (1, 1));
1133
        assert_eq!(c.output.named["DP-1"].transform, OutputTransform::Rotate90);
1134
        assert!(!c.output.named.contains_key("DP-2"));
1135
        assert_eq!(loaded.warnings.len(), 7, "{:#?}", loaded.warnings);
1136
    }
1137
1138
    #[test]
1139
    fn broken_toml_costs_only_its_line() {
1140
        let loaded = Config::parse(
1141
            r##"
1142
            [general]
1143
            gaps = { inner = 3, outer = 3
1144
            focus_follows_mouse = true
1145
            focus_follows_mouse = false
1146
            [binds]
1147
            "Mod+Return" = "spawn beer
1148
            "Mod+q" = "close"
1149
            "##,
1150
        )
1151
        .unwrap();
1152
        let c = loaded.config;
1153
        assert_eq!(c.general.gaps, General::default().gaps);
1154
        assert_eq!(c.binds.len(), 1);
1155
        assert_eq!(loaded.warnings.len(), 3, "{:#?}", loaded.warnings);
1156
        assert!(
1157
            loaded.warnings[0].starts_with("line 3:"),
1158
            "{:#?}",
1159
            loaded.warnings
1160
        );
1161
    }
1162
1163
    #[test]
1164
    fn a_bad_device_option_costs_only_itself() {
1165
        let loaded = Config::parse(
1166
            r#"
1167
            [input.pointer]
1168
            accel_speed = 2.0
1169
            scroll_method = "two-finger"
1170
            [[input.device]]
1171
            name = "Mouse"
1172
            accel_profile = "flat"
1173
            [[input.device]]
1174
            name = "Typo"
1175
            tapp = true
1176
            [[input.device]]
1177
            name = "Half"
1178
            accel_points = [0.0, 1.0]
1179
            "#,
1180
        )
1181
        .unwrap();
1182
        let input = loaded.config.input;
1183
        assert_eq!(input.pointer.accel_speed, None);
1184
        assert_eq!(input.pointer.scroll_method, Some(ScrollMethod::TwoFinger));
1185
        let names: Vec<_> = input.device.iter().map(|d| d.name.as_str()).collect();
1186
        assert_eq!(names, ["Mouse", "Typo", "Half"]);
1187
        assert_eq!(
1188
            input.device[0].settings.accel_profile,
1189
            Some(AccelProfile::Flat)
1190
        );
1191
        assert_eq!(input.device[1].settings, DeviceSettings::default());
1192
        assert_eq!(input.device[2].settings.accel_points, None);
1193
        assert_eq!(loaded.warnings.len(), 3, "{:#?}", loaded.warnings);
1194
    }
1195
1196
    fn subject<'a>(app_id: &'a str, title: &'a str) -> Subject<'a> {
1197
        Subject {
1198
            app_id,
1199
            title,
1200
            initial_title: title,
1201
            ..Subject::default()
1202
        }
1203
    }
1204
1205
    #[test]
1206
    fn rules_match_every_given_matcher_and_later_ones_win() {
1207
        let loaded = Config::parse(
1208
            r#"
1209
            [[rules]]
1210
            app_id = "^mpv$"
1211
            size = [800, 600]
1212
            opacity = 0.5
1213
            idle_inhibit = "visible"
1214
            [[rules]]
1215
            title = "Picture"
1216
            opacity = 0.8
1217
            focus = false
1218
            vrr = true
1219
            tearing = true
1220
            [[rules]]
1221
            class = "^Steam$"
1222
            instance = "steam"
1223
            xwayland = true
1224
            fullscreen = true
1225
            [[rules]]
1226
            dialog = true
1227
            parent_app_id = "^firefox$"
1228
            center = true
1229
            min_size = [300, 0]
1230
            max_size = [0, 500]
1231
            "#,
1232
        )
1233
        .unwrap();
1234
        assert_eq!(loaded.warnings, Vec::<String>::new());
1235
        let c = loaded.config;
1236
        let p = c.placement(&subject("mpv", "Picture in picture"));
1237
        assert_eq!(p.size, Some((800, 600)));
1238
        assert_eq!(p.opacity, Some(0.8));
1239
        assert_eq!(p.idle_inhibit, Some(IdleInhibit::Visible));
1240
        assert_eq!(
1241
            (p.focus, p.vrr, p.tearing),
1242
            (Some(false), Some(true), Some(true))
1243
        );
1244
        assert_eq!(c.placement(&subject("foot", "sh")), Placement::default());
1245
1246
        let x11 = Subject {
1247
            class: Some("Steam"),
1248
            instance: Some("steam"),
1249
            xwayland: true,
1250
            ..subject("Steam", "Steam")
1251
        };
1252
        assert_eq!(c.placement(&x11).fullscreen, Some(true));
1253
        let wayland = Subject {
1254
            xwayland: false,
1255
            ..subject("Steam", "Steam")
1256
        };
1257
        assert_eq!(c.placement(&wayland).fullscreen, None);
1258
1259
        let dialog = Subject {
1260
            dialog: true,
1261
            parent_app_id: Some("firefox"),
1262
            ..subject("firefox", "Save")
1263
        };
1264
        let p = c.placement(&dialog);
1265
        assert_eq!(p.at, Some(At::Center));
1266
        assert_eq!(p.clamp_size(100.0, 900.0), (300.0, 500.0));
1267
        let orphan = Subject {
1268
            parent_app_id: None,
1269
            ..dialog
1270
        };
1271
        assert_eq!(c.placement(&orphan), Placement::default());
1272
    }
1273
1274
    #[test]
1275
    fn initial_title_holds_when_the_title_changes() {
1276
        let loaded = Config::parse(
1277
            r#"
1278
            [[rules]]
1279
            initial_title = "^Untitled$"
1280
            floating = true
1281
            "#,
1282
        )
1283
        .unwrap();
1284
        let later = Subject {
1285
            title: "notes.txt",
1286
            initial_title: "Untitled",
1287
            ..subject("gedit", "")
1288
        };
1289
        assert_eq!(loaded.config.placement(&later).floating, Some(true));
1290
        let other = Subject {
1291
            initial_title: "notes.txt",
1292
            ..later
1293
        };
1294
        assert_eq!(loaded.config.placement(&other).floating, None);
1295
    }
1296
1297
    #[test]
1298
    fn bad_rule_values_are_warned_about_and_cost_little() {
1299
        let loaded = Config::parse(
1300
            r#"
1301
            [[rules]]
1302
            app_id = "a"
1303
            opacity = 1.5
1304
            size = [0, 100]
1305
            min_size = [500, 500]
1306
            max_size = [400, 0]
1307
            position = [10, 10]
1308
            center = true
1309
            floating = true
1310
            [[rules]]
1311
            app_id = "b"
1312
            idle_inhibit = "always"
1313
            [[rules]]
1314
            class = "("
1315
            [[rules]]
1316
            parent_app_id = "["
1317
            [[rules]]
1318
            app_id = "c"
1319
            size = [-1, 10]
1320
            [[rules]]
1321
            app_id = "d"
1322
            focus = "no"
1323
            [[rules]]
1324
            app_id = "e"
1325
            vrr = false
1326
            "#,
1327
        )
1328
        .unwrap();
1329
        let c = loaded.config;
1330
        assert_eq!(c.rules.len(), 2, "{:#?}", loaded.warnings);
1331
        let a = c.placement(&subject("a", ""));
1332
        assert_eq!(a.floating, Some(true));
1333
        assert_eq!(
1334
            (a.opacity, a.size, a.min_size, a.max_size),
1335
            (None, None, None, None)
1336
        );
1337
        assert_eq!(a.at, Some(At::Center));
1338
        assert_eq!(c.placement(&subject("e", "")).vrr, Some(false));
1339
        assert_eq!(loaded.warnings.len(), 9, "{:#?}", loaded.warnings);
1340
    }
1341
1342
    #[test]
1343
    fn a_title_set_after_mapping_brings_its_rules_in() {
1344
        let loaded = Config::parse(
1345
            r#"
1346
            [[rules]]
1347
            app_id = "^gimp$"
1348
            tag = "art"
1349
            [[rules]]
1350
            app_id = "^gimp$"
1351
            title = "^Tool Options$"
1352
            floating = true
1353
            opacity = 0.9
1354
            "#,
1355
        )
1356
        .unwrap();
1357
        let before = loaded
1358
            .config
1359
            .placement(&subject("gimp", "GNU Image Manipulation Program"));
1360
        let after = Subject {
1361
            title: "Tool Options",
1362
            initial_title: "GNU Image Manipulation Program",
1363
            ..subject("gimp", "")
1364
        };
1365
        let after = loaded.config.placement(&after);
1366
        assert_eq!((before.floating, before.opacity), (None, None));
1367
        assert_eq!((after.floating, after.opacity), (Some(true), Some(0.9)));
1368
        assert_eq!(before.tag, after.tag);
1369
    }
1370
1371
    #[test]
1372
    fn size_bounds_treat_zero_as_open() {
1373
        let p = Placement {
1374
            min_size: Some((200, 0)),
1375
            max_size: Some((0, 300)),
1376
            ..Placement::default()
1377
        };
1378
        assert_eq!(p.clamp_size(50.0, 900.0), (200.0, 300.0));
1379
        assert_eq!(p.clamp_size(4000.0, 10.0), (4000.0, 10.0));
1380
        assert_eq!(Placement::default().clamp_size(7.0, 9.0), (7.0, 9.0));
1381
    }
1382
}