halley-config 0.3.2

Configuration loading and parsing for the Halley Wayland compositor.
Documentation
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
use crate::layout::{
    InitialWindowClusterParticipation, InitialWindowOverlapPolicy, InitialWindowSpawnPlacement,
    RuntimeTuning, WindowRule, WindowRulePattern,
};

#[derive(Default)]
struct PartialWindowRule {
    app_ids: Vec<WindowRulePattern>,
    titles: Vec<WindowRulePattern>,
    width: Option<u32>,
    height: Option<u32>,
    opacity: Option<f32>,
    overlap_policy: Option<InitialWindowOverlapPolicy>,
    spawn_placement: Option<InitialWindowSpawnPlacement>,
    cluster_participation: Option<InitialWindowClusterParticipation>,
}

pub(crate) fn load_rules_section(raw: &str, out: &mut RuntimeTuning) -> Result<(), String> {
    out.window_rules.clear();
    let mut in_rules = false;
    let mut current_rule: Option<PartialWindowRule> = None;

    for (line_no, raw_line) in raw.lines().enumerate() {
        let line_no = line_no + 1;
        let trimmed = strip_rule_comment(raw_line);
        if trimmed.is_empty() {
            continue;
        }

        if !in_rules {
            if trimmed == "rules:" {
                in_rules = true;
            }
            continue;
        }

        if let Some(rule) = current_rule.as_mut() {
            if trimmed == "end" {
                out.window_rules.push(finalize_window_rule(rule, line_no)?);
                current_rule = None;
                continue;
            }
            parse_rule_entry(rule, trimmed, line_no)?;
            continue;
        }

        if trimmed == "rule:" {
            current_rule = Some(PartialWindowRule::default());
            continue;
        }
        if trimmed == "end" {
            return Ok(());
        }
        return Err(format!(
            "line {line_no}: expected `rule:` or `end` inside `rules:` block, got `{trimmed}`"
        ));
    }

    if current_rule.is_some() {
        return Err("unterminated `rule:` block in `rules:` section".to_string());
    }

    Ok(())
}

fn strip_rule_comment(line: &str) -> &str {
    let mut in_quotes = false;
    for (idx, ch) in line.char_indices() {
        if ch == '"' {
            in_quotes = !in_quotes;
        } else if ch == '#' && !in_quotes {
            return line[..idx].trim();
        }
    }
    line.trim()
}

fn finalize_window_rule(rule: &PartialWindowRule, line_no: usize) -> Result<WindowRule, String> {
    if rule.app_ids.is_empty() && rule.titles.is_empty() {
        return Err(format!(
            "line {line_no}: rule is missing required matcher; add `app-id` and/or `title`"
        ));
    }
    let initial_size = match (rule.width, rule.height) {
        (Some(width), Some(height)) => Some((width.max(1), height.max(1))),
        (Some(_), None) => {
            return Err(format!(
                "line {line_no}: rule has `width` without matching `height`"
            ));
        }
        (None, Some(_)) => {
            return Err(format!(
                "line {line_no}: rule has `height` without matching `width`"
            ));
        }
        (None, None) => None,
    };
    Ok(WindowRule {
        app_ids: rule.app_ids.clone(),
        titles: rule.titles.clone(),
        initial_size,
        opacity: rule.opacity,
        overlap_policy: rule
            .overlap_policy
            .unwrap_or(InitialWindowOverlapPolicy::None),
        spawn_placement: rule
            .spawn_placement
            .unwrap_or(InitialWindowSpawnPlacement::Default),
        cluster_participation: rule
            .cluster_participation
            .unwrap_or(InitialWindowClusterParticipation::Layout),
    })
}

fn parse_rule_entry(
    rule: &mut PartialWindowRule,
    line: &str,
    line_no: usize,
) -> Result<(), String> {
    let Some((key, rest)) = line.split_once(char::is_whitespace) else {
        return Err(format!(
            "line {line_no}: expected `<key> <value>` inside rule"
        ));
    };
    let value = rest.trim();
    if value.is_empty() {
        return Err(format!("line {line_no}: missing value for `{key}`"));
    }

    match key {
        "app-id" | "app_id" => {
            rule.app_ids = parse_rule_app_ids(value, line_no)?;
        }
        "title" => {
            rule.titles = parse_rule_match_strings(value, line_no, "title")?;
        }
        "width" => {
            rule.width = Some(parse_rule_dimension(value, line_no, "width")?);
        }
        "height" => {
            rule.height = Some(parse_rule_dimension(value, line_no, "height")?);
        }
        "opacity" => {
            rule.opacity = Some(parse_rule_opacity(value, line_no)?);
        }
        "overlap-policy" | "overlap_policy" => {
            // Deprecated: expanded windows always allow overlap with other expanded
            // windows now. Keep accepting old configs during migration, but do not
            // preserve the old configurable no-overlap/overlap-policy model.
            let _ = parse_rule_overlap_policy(value, line_no)?;
            rule.overlap_policy = Some(InitialWindowOverlapPolicy::None);
        }
        "spawn-placement" | "spawn_placement" => {
            rule.spawn_placement = Some(parse_rule_spawn_placement(value, line_no)?);
        }
        "cluster-participation" | "cluster_participation" => {
            rule.cluster_participation = Some(parse_rule_cluster_participation(value, line_no)?);
        }
        _ => {
            return Err(format!("line {line_no}: unknown rule key `{key}`"));
        }
    }

    Ok(())
}

fn parse_rule_app_ids(value: &str, line_no: usize) -> Result<Vec<WindowRulePattern>, String> {
    parse_rule_match_strings(value, line_no, "app-id")
}

fn parse_rule_match_strings(
    value: &str,
    line_no: usize,
    field_name: &str,
) -> Result<Vec<WindowRulePattern>, String> {
    let trimmed = value.trim();
    if trimmed.starts_with('[') {
        return parse_string_array_literal(value, line_no, field_name);
    }
    Ok(vec![parse_rule_match_pattern(
        trimmed, line_no, field_name,
    )?])
}

fn parse_rule_overlap_policy(
    value: &str,
    line_no: usize,
) -> Result<InitialWindowOverlapPolicy, String> {
    match parse_quoted_string_literal(value, line_no)?.as_str() {
        "none" => Ok(InitialWindowOverlapPolicy::None),
        "parent-only" => Ok(InitialWindowOverlapPolicy::ParentOnly),
        "all" => Ok(InitialWindowOverlapPolicy::All),
        other => Err(format!(
            "line {line_no}: unknown overlap-policy `{other}`; expected `none`, `parent-only`, or `all`"
        )),
    }
}

fn parse_rule_dimension(value: &str, line_no: usize, field_name: &str) -> Result<u32, String> {
    value.trim().parse::<u32>().map_err(|err| {
        format!(
            "line {line_no}: invalid {field_name} `{}`: {err}",
            value.trim()
        )
    })
}

fn parse_rule_opacity(value: &str, line_no: usize) -> Result<f32, String> {
    let trimmed = value.trim();
    let opacity = trimmed
        .parse::<f32>()
        .map_err(|err| format!("line {line_no}: invalid opacity `{trimmed}`: {err}"))?;
    if !(0.0..=1.0).contains(&opacity) {
        return Err(format!(
            "line {line_no}: opacity `{trimmed}` is out of range; expected 0.0 through 1.0"
        ));
    }
    Ok(opacity)
}

fn parse_rule_spawn_placement(
    value: &str,
    line_no: usize,
) -> Result<InitialWindowSpawnPlacement, String> {
    match parse_quoted_string_literal(value, line_no)?.as_str() {
        "center" => Ok(InitialWindowSpawnPlacement::Center),
        "adjacent" => Ok(InitialWindowSpawnPlacement::Adjacent),
        "viewport-center" => Ok(InitialWindowSpawnPlacement::ViewportCenter),
        "cursor" => Ok(InitialWindowSpawnPlacement::Cursor),
        "app" => Ok(InitialWindowSpawnPlacement::App),
        other => Err(format!(
            "line {line_no}: unknown spawn-placement `{other}`; expected `center`, `adjacent`, `viewport-center`, `cursor`, or `app`"
        )),
    }
}

fn parse_rule_cluster_participation(
    value: &str,
    line_no: usize,
) -> Result<InitialWindowClusterParticipation, String> {
    match parse_quoted_string_literal(value, line_no)?.as_str() {
        "layout" => Ok(InitialWindowClusterParticipation::Layout),
        "float" => Ok(InitialWindowClusterParticipation::Float),
        other => Err(format!(
            "line {line_no}: unknown cluster-participation `{other}`; expected `layout` or `float`"
        )),
    }
}

fn parse_quoted_string_literal(value: &str, line_no: usize) -> Result<String, String> {
    let trimmed = value.trim();
    if !trimmed.starts_with('"') || !trimmed.ends_with('"') || trimmed.len() < 2 {
        return Err(format!(
            "line {line_no}: expected quoted string, got `{trimmed}`"
        ));
    }
    Ok(trimmed[1..trimmed.len() - 1].to_string())
}

fn parse_regex_literal(value: &str, line_no: usize) -> Result<String, String> {
    let trimmed = value.trim();
    if !trimmed.starts_with("r\"") || !trimmed.ends_with('"') || trimmed.len() < 3 {
        return Err(format!(
            "line {line_no}: expected regex literal, got `{trimmed}`"
        ));
    }
    Ok(trimmed[2..trimmed.len() - 1].to_string())
}

fn parse_rule_match_pattern(
    value: &str,
    line_no: usize,
    field_name: &str,
) -> Result<WindowRulePattern, String> {
    let trimmed = value.trim();
    if trimmed.starts_with("r\"") {
        let raw = parse_regex_literal(trimmed, line_no)?;
        let compiled = regex::Regex::new(&raw)
            .map_err(|err| format!("line {line_no}: invalid {field_name} regex `{raw}`: {err}"))?;
        Ok(WindowRulePattern::Regex(compiled))
    } else {
        Ok(WindowRulePattern::Exact(parse_quoted_string_literal(
            trimmed, line_no,
        )?))
    }
}

fn parse_string_array_literal(
    value: &str,
    line_no: usize,
    field_name: &str,
) -> Result<Vec<WindowRulePattern>, String> {
    let trimmed = value.trim();
    if !trimmed.starts_with('[') || !trimmed.ends_with(']') {
        return Err(format!(
            "line {line_no}: expected string array literal, got `{trimmed}`"
        ));
    }
    let mut out = Vec::new();
    let mut rest = &trimmed[1..trimmed.len() - 1];
    while !rest.trim().is_empty() {
        rest = rest.trim_start();
        if !rest.starts_with('"') && !rest.starts_with("r\"") {
            return Err(format!(
                "line {line_no}: expected string or regex literal inside array, got `{rest}`"
            ));
        }
        let regex_prefix = rest.starts_with("r\"");
        let start = if regex_prefix { 2 } else { 1 };
        let mut escaped = false;
        let mut end_idx = None;
        for (idx, ch) in rest.char_indices().skip(start) {
            if escaped {
                escaped = false;
                continue;
            }
            if ch == '\\' && !regex_prefix {
                escaped = true;
                continue;
            }
            if ch == '"' {
                end_idx = Some(idx);
                break;
            }
        }
        let Some(end_idx) = end_idx else {
            return Err(format!(
                "line {line_no}: unterminated {field_name} matcher in array"
            ));
        };
        out.push(parse_rule_match_pattern(
            &rest[..=end_idx],
            line_no,
            field_name,
        )?);
        rest = rest[end_idx + 1..].trim_start();
        if rest.is_empty() {
            break;
        }
        if let Some(next) = rest.strip_prefix(',') {
            rest = next;
        } else {
            return Err(format!(
                "line {line_no}: expected `,` between {field_name} matchers, got `{rest}`"
            ));
        }
    }
    if out.is_empty() {
        return Err(format!(
            "line {line_no}: {field_name} array must not be empty"
        ));
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use crate::layout::RuntimeTuning;

    #[test]
    fn rule_width_and_height_parse_as_initial_size() {
        let tuning = RuntimeTuning::from_rune_str(
            r#"
rules:
  rule:
    app-id "pavucontrol"
    width 420
    height 640
    spawn-placement "center"
    cluster-participation "float"
  end
end
"#,
        )
        .expect("config should parse");

        assert_eq!(tuning.window_rules.len(), 1);
        assert_eq!(tuning.window_rules[0].initial_size, Some((420, 640)));
    }

    #[test]
    fn rule_opacity_parses() {
        let tuning = RuntimeTuning::from_rune_str(
            r#"
rules:
  rule:
    app-id "kitty"
    opacity 0.85
  end
end
"#,
        )
        .expect("config should parse");

        assert_eq!(tuning.window_rules.len(), 1);
        assert_eq!(tuning.window_rules[0].opacity, Some(0.85));
    }

    #[test]
    fn rule_opacity_rejects_percent_values() {
        let tuning = RuntimeTuning::from_rune_str(
            r#"
rules:
  rule:
    app-id "kitty"
    opacity 85%
  end
end
"#,
        );

        assert!(tuning.is_none());
    }

    #[test]
    fn rule_opacity_rejects_out_of_range_values() {
        let tuning = RuntimeTuning::from_rune_str(
            r#"
rules:
  rule:
    app-id "kitty"
    opacity 1.2
  end
end
"#,
        );

        assert!(tuning.is_none());
    }

    #[test]
    fn rule_width_requires_height() {
        let tuning = RuntimeTuning::from_rune_str(
            r#"
rules:
  rule:
    app-id "pavucontrol"
    width 420
  end
end
"#,
        );

        assert!(tuning.is_none());
    }

    #[test]
    fn rule_height_requires_width() {
        let tuning = RuntimeTuning::from_rune_str(
            r#"
rules:
  rule:
    app-id "pavucontrol"
    height 640
  end
end
"#,
        );

        assert!(tuning.is_none());
    }
}