1// Package config reads the flat `key = value` config file (ADR 012).
2package config
3
4import (
5 "bufio"
6 "fmt"
7 "io"
8 "math"
9 "os"
10 "path/filepath"
11 "regexp"
12 "slices"
13 "sort"
14 "strconv"
15 "strings"
16 "time"
17 "unicode"
18
19 "github.com/bnema/neferwl/internal/ports"
20)
21
22// maxVRRFlipGap bounds render.vrr-flip-gap below one refresh of a slow
23// VRR panel (48 Hz: 20.8 ms).
24const maxVRRFlipGap = 10 * time.Millisecond
25
26// maxCursorHideAfter bounds cursor.hide-after.
27const maxCursorHideAfter = time.Hour
28
29// defaultBinds use the config syntax and go through the same parser as user binds.
30var defaultBinds = []struct{ combo, action string }{
31 {"cmd+return", "spawn-terminal"},
32 {"cmd+left", "focus-column-left"},
33 {"cmd+right", "focus-column-right"},
34 {"cmd+up", "focus-window-up"},
35 {"cmd+down", "focus-window-down"},
36 {"cmd+shift+left", "move-column-left"},
37 {"cmd+shift+right", "move-column-right"},
38 {"cmd+bracketleft", "consume-or-expel-window-left"},
39 {"cmd+bracketright", "consume-or-expel-window-right"},
40 {"cmd+r", "cycle-column-width"},
41 {"cmd+f", "maximize-column"},
42 {"cmd+shift+f", "toggle-fullscreen"},
43 {"cmd+s", "toggle-stash-visible"},
44 {"cmd+shift+s", "toggle-window-stash"},
45 {"cmd+o", "toggle-overview"},
46 {"cmd+q", "close-window"},
47 {"ctrl+alt+backspace", "quit"},
48 {"ctrl+cmd+space", "spawn fuzzel"},
49 {"cmd+pageup", "focus-workspace-up"},
50 {"cmd+pagedown", "focus-workspace-down"},
51 {"cmd+shift+pageup", "move-column-to-workspace-up"},
52 {"cmd+shift+pagedown", "move-column-to-workspace-down"},
53 {"cmd+ctrl+left", "focus-monitor-left"},
54 {"cmd+ctrl+right", "focus-monitor-right"},
55 {"cmd+ctrl+up", "focus-monitor-up"},
56 {"cmd+ctrl+down", "focus-monitor-down"},
57 {"cmd+ctrl+shift+left", "move-workspace-to-monitor-left"},
58 {"cmd+ctrl+shift+right", "move-workspace-to-monitor-right"},
59 {"cmd+shift+up", "move-window-up"},
60 {"cmd+shift+down", "move-window-down"},
61 {"cmd+alt+left", "set-column-width -10%"},
62 {"cmd+alt+right", "set-column-width +10%"},
63 {"cmd+alt+up", "set-window-height -10%"},
64 {"cmd+alt+down", "set-window-height +10%"},
65 {"cmd+ctrl+shift+up", "move-workspace-up"},
66 {"cmd+ctrl+shift+down", "move-workspace-down"},
67 {"cmd+shift+space", "toggle-floating"},
68}
69var actions = map[string]bool{
70 "focus-monitor-left": true,
71 "focus-monitor-right": true,
72 "move-workspace-to-monitor-left": true,
73 "move-workspace-to-monitor-right": true,
74 "focus-monitor-up": true,
75 "focus-monitor-down": true,
76 "move-workspace-to-monitor-up": true,
77 "move-workspace-to-monitor-down": true,
78 "scale-up": true,
79 "scale-down": true,
80 "focus-workspace-up": true,
81 "focus-workspace-down": true,
82 "move-column-to-workspace-up": true,
83 "move-column-to-workspace-down": true,
84 "move-window-to-workspace-up": true,
85 "move-window-to-workspace-down": true,
86 "none": true,
87 "consume-or-expel-window-left": true,
88 "consume-or-expel-window-right": true,
89 "spawn-terminal": true,
90 "focus-column-left": true,
91 "focus-column-right": true,
92 "focus-window-up": true,
93 "focus-window-down": true,
94 "move-column-left": true,
95 "move-column-right": true,
96 "cycle-column-width": true,
97 "maximize-column": true,
98 "toggle-fullscreen": true,
99 "toggle-window-stash": true,
100 "toggle-stash-visible": true,
101 "toggle-overview": true,
102 "close-window": true,
103 "quit": true,
104 "move-window-up": true,
105 "move-window-down": true,
106 "move-workspace-up": true,
107 "move-workspace-down": true,
108 "toggle-floating": true,
109}
110var components = map[string]bool{"core": true, "wayland": true, "input": true, "drm": true, "seat": true, "render": true, "sync": true, "config": true, "app": true}
111var color = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
112
113// resizeStep is the +N% or -N% step of set-column-width and
114// set-window-height, N from 1 to 100.
115var resizeStep = regexp.MustCompile(`^[+-]([1-9][0-9]?|100)%$`)
116
117// namedKeys maps lowercase names to xkb keysym names so binds are case-insensitive.
118var namedKeys = map[string]string{
119 "return": "Return", "enter": "Return", "space": "space", "tab": "Tab", "escape": "Escape", "esc": "Escape",
120 "backspace": "BackSpace", "delete": "Delete", "insert": "Insert", "home": "Home", "end": "End",
121 "pageup": "Prior", "prior": "Prior", "pagedown": "Next", "next": "Next", "print": "Print",
122 "left": "Left", "right": "Right", "up": "Up", "down": "Down",
123}
124
125// Warning is a non-fatal problem at one line; the key keeps its default.
126type Warning struct {
127 Line int
128 Msg string
129}
130
131func (w Warning) String() string { return fmt.Sprintf("line %d: %s", w.Line, w.Msg) }
132
133func DefaultPath() string {
134 base := os.Getenv("XDG_CONFIG_HOME")
135 if base == "" {
136 home, err := os.UserHomeDir()
137 if err == nil {
138 base = filepath.Join(home, ".config")
139 }
140 }
141 return filepath.Join(base, "neferwl", "config")
142}
143
144func Defaults() ports.Config {
145 var c ports.Config
146 c.Keyboard.RepeatRate = 25
147 c.Keyboard.RepeatDelay = 600
148 c.Keyboard.CmdKey = "super"
149 c.Terminal.Command = strings.Fields(os.Getenv("TERMINAL"))
150 if len(c.Terminal.Command) == 0 {
151 c.Terminal.Command = []string{"foot"}
152 }
153 c.Terminal.AutoOpen = "first"
154 c.Xwayland = "xwayland-satellite"
155 c.Background.Color = "#111111"
156 c.Floating.Dim = 0.3
157 c.Stash.Width = 80
158 c.Stash.Gap = 2
159 c.Stash.Dim = 0.5
160 c.Stash.Capture = true
161 c.Border.Width = 2
162 c.Border.Active = "#808080"
163 c.Border.Inactive = "#111111"
164 c.Layout.MaxColumns = 2
165 c.Layout.Presets = []string{"1/3", "1/2", "2/3", "1"}
166 c.Layout.Overflow = "scroll"
167 c.Touchpad.Tap = true
168 c.Touchpad.AccelProfile = ports.AccelAdaptive
169 c.Touchpad.ScrollFactor = 1
170 c.Mouse.AccelProfile = ports.AccelAdaptive
171 c.Cursor.HideAfter = 5 * time.Second
172 c.Focus.Animation = ports.FocusAnimationPulse
173 c.Focus.Effect = ports.FocusEffectScreen
174 c.Focus.Strength = 0.04
175 c.Binds = map[string]string{}
176 for _, b := range defaultBinds {
177 combos := []string{b.combo}
178 // Every arrow bind has a vim twin: h j k l.
179 for arrow, vim := range map[string]string{"left": "h", "down": "j", "up": "k", "right": "l"} {
180 if base, ok := strings.CutSuffix(b.combo, "+"+arrow); ok {
181 combos = append(combos, base+"+"+vim)
182 }
183 }
184 for _, s := range combos {
185 combo, err := parseCombo(s)
186 if err != nil {
187 panic(err)
188 }
189 c.Binds[combo] = b.action
190 }
191 }
192 // Digits and zoom use physical keys (evdev codes 2-10, 12, 13), so they
193 // work the same on AZERTY, QWERTZ or Dvorak.
194 for combo, action := range map[string]string{"cmd+code:13": "scale-up", "cmd+code:12": "scale-down"} {
195 canon, _ := parseCombo(combo)
196 c.Binds[canon] = action
197 }
198 for n := 1; n <= 9; n++ {
199 focus, _ := parseCombo(fmt.Sprintf("cmd+code:%d", n+1))
200 move, _ := parseCombo(fmt.Sprintf("cmd+shift+code:%d", n+1))
201 c.Binds[focus] = fmt.Sprintf("focus-workspace %d", n)
202 c.Binds[move] = fmt.Sprintf("move-column-to-workspace %d", n)
203 }
204 c.Render.DirectScanout = true
205 c.Render.Tearing = true
206 c.Render.VRR = true
207 c.Render.VRRFlipGap = time.Millisecond
208 c.Performance.Realtime = true
209 c.Log.Level = "info"
210 c.Log.Debug = []string{}
211 return c
212}
213
214// LoadDefault loads DefaultPath; a missing file means defaults.
215func LoadDefault() (ports.Config, []Warning, error) {
216 c, w, err := Load(DefaultPath())
217 if os.IsNotExist(err) {
218 return Defaults(), nil, nil
219 }
220 return c, w, err
221}
222
223// Load reads a config file. The error is only for I/O; bad lines become warnings.
224func Load(path string) (ports.Config, []Warning, error) {
225 f, err := os.Open(path)
226 if err != nil {
227 return Defaults(), nil, err
228 }
229 defer f.Close()
230 return Parse(f)
231}
232
233// maxOutputOffset bounds output.<name>.offset (logical px), far beyond any
234// real layout but small enough that placement arithmetic cannot overflow.
235const maxOutputOffset = 65536
236
237// outputRelations lists the relation suffixes, tried in order.
238var outputRelations = [...]struct {
239 suffix string
240 rel ports.OutputRelation
241}{
242 {".right-of", ports.RelationRightOf},
243 {".left-of", ports.RelationLeftOf},
244 {".above", ports.RelationAbove},
245 {".below", ports.RelationBelow},
246}
247
248// outputRelation splits "<output>.right-of" (left-of, above, below) into the
249// relation and the output name.
250func outputRelation(name string) (ports.OutputRelation, string, bool) {
251 for _, r := range outputRelations {
252 if base, ok := strings.CutSuffix(name, r.suffix); ok {
253 return r.rel, base, true
254 }
255 }
256 return ports.RelationNone, "", false
257}
258
259// checkOutputAnchors warns about an offset without a relation, then drops the
260// relations that form a cycle (every output of the cycle, one warning each),
261// and warns about outputs sharing the same relation, reference and offset.
262// Core places a cycle automatically anyway; runtime overrides never create
263// relations, so this is the only place to detect them.
264func checkOutputAnchors(outputs []ports.OutputConfig, relKeys map[string]string, offsetLines, seen map[string]int) []Warning {
265 var warnings []Warning
266 for _, o := range outputs {
267 if line, ok := offsetLines[o.Name]; ok && o.Anchor.Relation == ports.RelationNone {
268 warnings = append(warnings, Warning{Line: line, Msg: fmt.Sprintf("output.%s.offset: ignored without a relation (right-of, left-of, above, below)", o.Name)})
269 }
270 }
271 byName := make(map[string]*ports.OutputConfig, len(outputs))
272 for i := range outputs {
273 byName[outputs[i].Name] = &outputs[i]
274 }
275 var cycle []*ports.OutputConfig
276 for i := range outputs {
277 for cur, steps := &outputs[i], 0; steps <= len(outputs); steps++ {
278 if cur.Anchor.Relation == ports.RelationNone {
279 break
280 }
281 if cur = byName[cur.Anchor.To]; cur == nil {
282 break
283 }
284 if cur == &outputs[i] {
285 cycle = append(cycle, cur)
286 break
287 }
288 }
289 }
290 for _, o := range cycle {
291 key := relKeys[o.Name]
292 warnings = append(warnings, Warning{Line: seen[key], Msg: fmt.Sprintf("%s: relation cycle, ignored", key)})
293 o.Anchor.Relation, o.Anchor.To = ports.RelationNone, ""
294 }
295 // Two outputs with the same relation, reference and offset overlap.
296 for i, o := range outputs {
297 if o.Anchor.Relation == ports.RelationNone {
298 continue
299 }
300 for _, prev := range outputs[:i] {
301 if prev.Anchor == o.Anchor {
302 warnings = append(warnings, Warning{Line: seen[relKeys[o.Name]], Msg: fmt.Sprintf("output.%s: same relation as output.%s; both get the same position", o.Name, prev.Name)})
303 break
304 }
305 }
306 }
307 return warnings
308}
309
310// Parse reads `key = value` lines on top of the defaults.
311func Parse(r io.Reader) (ports.Config, []Warning, error) {
312 c, _, w, err := parse(r)
313 return c, w, err
314}
315
316// parse also returns the effective key/value pairs, used to log what changed on reload.
317func parse(r io.Reader) (ports.Config, map[string]string, []Warning, error) {
318 c := Defaults()
319 var warnings []Warning
320 raw := map[string]string{}
321 seen := map[string]int{}
322 outputs := map[string]int{}
323 relKeys := map[string]string{} // output -> key of its relation
324 offsetLines := map[string]int{} // output -> line of its offset
325 workspaces := map[string]int{}
326 scanner := bufio.NewScanner(r)
327 for n := 1; scanner.Scan(); n++ {
328 line := strings.TrimSpace(scanner.Text())
329 if line == "" || strings.HasPrefix(line, "#") {
330 continue
331 }
332 warn := func(format string, a ...any) {
333 warnings = append(warnings, Warning{Line: n, Msg: fmt.Sprintf(format, a...)})
334 }
335 key, value, ok := strings.Cut(line, "=")
336 key, value = strings.TrimSpace(key), stripComment(strings.TrimSpace(value))
337 if !ok || key == "" {
338 warn("expected key = value")
339 continue
340 }
341 if combo, ok := strings.CutPrefix(key, "bind."); ok {
342 if strings.HasSuffix(combo, "+") && strings.HasPrefix(value, "=") {
343 warn("%s: write %sequal instead of %s=", key, combo, combo)
344 continue
345 }
346 canon, err := parseCombo(combo)
347 if err != nil {
348 warn("%s: %v", key, err)
349 continue
350 }
351 if err := checkAction(value); err != nil {
352 warn("%s: %v", key, err)
353 continue
354 }
355 key = "bind." + canon
356 if prev, dup := seen[key]; dup {
357 warn("%s: overrides line %d", key, prev)
358 }
359 seen[key] = n
360 raw[key] = value
361 c.Binds[canon] = value
362 continue
363 }
364 override := func() {
365 if prev, dup := seen[key]; dup {
366 warn("%s: overrides line %d", key, prev)
367 }
368 seen[key] = n
369 raw[key] = value
370 }
371 if name, ok := strings.CutPrefix(key, "output."); ok {
372 entry := func() *ports.OutputConfig {
373 if i, ok := outputs[name]; ok {
374 return &c.Outputs[i]
375 }
376 outputs[name] = len(c.Outputs)
377 c.Outputs = append(c.Outputs, ports.OutputConfig{Name: name, ScaleOnly: true, SDRBrightness: ports.DefaultSDRBrightness})
378 return &c.Outputs[len(c.Outputs)-1]
379 }
380 if base, ok := strings.CutSuffix(name, ".primary"); ok {
381 name = base
382 b, err := onOff(value)
383 if err != nil {
384 warn("%s: %v", key, err)
385 continue
386 }
387 override()
388 entry().Primary = b
389 continue
390 }
391 if base, ok := strings.CutSuffix(name, ".hdr"); ok {
392 name = base
393 b, err := onOff(value)
394 if err != nil {
395 warn("%s: %v", key, err)
396 continue
397 }
398 override()
399 entry().HDR = b
400 continue
401 }
402 if base, ok := strings.CutSuffix(name, ".sdr-brightness"); ok {
403 name = base
404 nits, err := strconv.Atoi(value)
405 if err != nil || nits < 80 || nits > 1000 {
406 warn("%s: must be between 80 and 1000", key)
407 continue
408 }
409 override()
410 entry().SDRBrightness = nits
411 continue
412 }
413 if base, ok := strings.CutSuffix(name, ".offset"); ok {
414 name = base
415 off, err := strconv.Atoi(value)
416 if err != nil || off < -maxOutputOffset || off > maxOutputOffset {
417 warn("%s: must be an integer between -%d and %d", key, maxOutputOffset, maxOutputOffset)
418 continue
419 }
420 override()
421 entry().Anchor.Offset = off
422 offsetLines[name] = n
423 continue
424 }
425 if rel, base, ok := outputRelation(name); ok {
426 name = base
427 if value == "" {
428 warn("%s: expected an output name", key)
429 continue
430 }
431 if value == name {
432 warn("%s: an output cannot be placed relative to itself", key)
433 continue
434 }
435 if prev, ok := relKeys[name]; ok && prev != key {
436 warn("%s: overrides line %d (%s)", key, seen[prev], prev)
437 delete(raw, prev)
438 // Stale lines of the other relation keys must not trigger a
439 // second override warning from override() or a later switch.
440 delete(seen, prev)
441 delete(seen, key)
442 }
443 override()
444 relKeys[name] = key
445 a := &entry().Anchor
446 a.Relation, a.To = rel, value
447 continue
448 }
449 if base, ok := strings.CutSuffix(name, ".scale"); ok {
450 name = base
451 s, err := parseScale(value)
452 if err != nil {
453 warn("%s: %v", key, err)
454 continue
455 }
456 override()
457 entry().Scale = s
458 continue
459 }
460 o := ports.OutputConfig{Name: name}
461 if value == "off" {
462 o.Off = true
463 } else if _, _, _, err := ParseMode(value); err != nil {
464 warn("%s: %v", key, err)
465 continue
466 } else if value != "preferred" {
467 o.Mode = value
468 }
469 override()
470 e := entry()
471 o.Scale, o.Primary, o.HDR, o.SDRBrightness, o.Anchor = e.Scale, e.Primary, e.HDR, e.SDRBrightness, e.Anchor
472 *e = o
473 continue
474 }
475 if rest, ok := strings.CutPrefix(key, "workspace."); ok {
476 name, field, _ := strings.Cut(rest, ".")
477 if !workspaceName.MatchString(name) {
478 warn("%s: workspace name must be letters, digits, - or _", key)
479 continue
480 }
481 var ws ports.WorkspaceConfig
482 if i, ok := workspaces[name]; ok {
483 ws = c.Workspaces[i]
484 }
485 if err := setWorkspace(&ws, field, value); err != nil {
486 warn("%s: %v", key, err)
487 continue
488 }
489 override()
490 if i, ok := workspaces[name]; ok {
491 c.Workspaces[i] = ws
492 } else {
493 ws.Name = name
494 workspaces[name] = len(c.Workspaces)
495 c.Workspaces = append(c.Workspaces, ws)
496 }
497 continue
498 }
499 if err := set(&c, key, value); err != nil {
500 warn("%s: %v", key, err)
501 continue
502 }
503 if key == "startup" {
504 // Repeatable: each line adds a command.
505 raw[fmt.Sprintf("startup.%d", len(c.Startup))] = value
506 continue
507 }
508 override()
509 }
510 if err := scanner.Err(); err != nil {
511 return c, raw, warnings, err
512 }
513 warnings = append(warnings, checkOutputAnchors(c.Outputs, relKeys, offsetLines, seen)...)
514 warnings = append(warnings, checkWorkspaceBinds(c, seen)...)
515 sort.SliceStable(warnings, func(i, j int) bool { return warnings[i].Line < warnings[j].Line })
516 // A user bind on a digit (cmd+1, even "none") replaces the default bound
517 // to the same physical key (cmd+code:2), so older configs keep working.
518 for combo := range c.Binds {
519 if seen["bind."+combo] == 0 {
520 continue
521 }
522 parts := strings.Split(combo, "+")
523 key := parts[len(parts)-1]
524 if len(key) != 1 || key[0] < '0' || key[0] > '9' {
525 continue
526 }
527 code := int(key[0]-'0') + 1
528 if key == "0" {
529 code = 11
530 }
531 parts[len(parts)-1] = "code:" + strconv.Itoa(code)
532 if physical := strings.Join(parts, "+"); seen["bind."+physical] == 0 {
533 delete(c.Binds, physical)
534 }
535 }
536 // "none" only removes a default bind.
537 for combo, a := range c.Binds {
538 if a == "none" {
539 delete(c.Binds, combo)
540 }
541 }
542 // Cmd resolves to a real modifier; drop binds that then collide. As for any key,
543 // the later line wins; defaults (no line) lose to every user line.
544 combos := make([]string, 0, len(c.Binds))
545 for combo := range c.Binds {
546 combos = append(combos, combo)
547 }
548 order := func(combo string) int {
549 if n := seen["bind."+combo]; n > 0 {
550 return -n
551 }
552 return math.MaxInt
553 }
554 sort.Slice(combos, func(i, j int) bool {
555 a, b := order(combos[i]), order(combos[j])
556 return a < b || a == b && combos[i] < combos[j]
557 })
558 resolved := map[string]string{}
559 for _, combo := range combos {
560 r, err := expandCmd(combo, c.Keyboard.CmdKey)
561 if prev, dup := resolved[r]; err == nil && dup {
562 err = fmt.Errorf("overridden by bind.%s (same keys with keyboard.cmd = %s)", prev, c.Keyboard.CmdKey)
563 }
564 if err != nil {
565 if n := seen["bind."+combo]; n > 0 {
566 warnings = append(warnings, Warning{Line: n, Msg: fmt.Sprintf("bind.%s: %v", combo, err)})
567 }
568 delete(c.Binds, combo)
569 delete(raw, "bind."+combo)
570 continue
571 }
572 resolved[r] = combo
573 }
574 return c, raw, warnings, nil
575}
576
577// expandCmd replaces Cmd with the configured modifier and re-sorts.
578func expandCmd(combo, cmd string) (string, error) {
579 parts := strings.Split(combo, "+")
580 key := parts[len(parts)-1]
581 // cmd is super, alt or ctrl; its modifier name is the capitalized form.
582 cmdName := strings.ToUpper(cmd[:1]) + cmd[1:]
583 seen := map[string]bool{}
584 for _, m := range parts[:len(parts)-1] {
585 if m == "Cmd" {
586 m = cmdName
587 }
588 if seen[m] {
589 return "", fmt.Errorf("%s is already cmd (keyboard.cmd = %s)", strings.ToLower(m), cmd)
590 }
591 seen[m] = true
592 }
593 mods := make([]string, 0, len(seen))
594 for m := range seen {
595 mods = append(mods, m)
596 }
597 sort.Strings(mods)
598 return strings.Join(append(mods, key), "+"), nil
599}
600
601// set applies one scalar key. Unknown keys and invalid values are errors.
602func set(c *ports.Config, key, v string) error {
603 switch key {
604 case "keyboard.layout":
605 c.Keyboard.Layout = v
606 case "keyboard.variant":
607 c.Keyboard.Variant = v
608 case "keyboard.options":
609 c.Keyboard.Options = v
610 case "keyboard.repeat-rate":
611 return positive(&c.Keyboard.RepeatRate, v, 1000)
612 case "keyboard.repeat-delay":
613 return positive(&c.Keyboard.RepeatDelay, v, 10000)
614 case "keyboard.cmd":
615 if v != "super" && v != "alt" && v != "ctrl" {
616 return fmt.Errorf("must be super, alt or ctrl")
617 }
618 c.Keyboard.CmdKey = v
619 case "startup":
620 argv := strings.Fields(v)
621 if len(argv) == 0 {
622 return fmt.Errorf("must not be empty")
623 }
624 c.Startup = append(c.Startup, argv)
625 case "terminal":
626 argv := strings.Fields(v)
627 if len(argv) == 0 {
628 return fmt.Errorf("must not be empty")
629 }
630 c.Terminal.Command = argv
631 case "terminal.auto-open":
632 if v != "first" && v != "all" && v != "off" {
633 return fmt.Errorf("must be first, all or off")
634 }
635 c.Terminal.AutoOpen = v
636 case "xwayland":
637 switch {
638 case v == "off":
639 c.Xwayland = ""
640 case v == "" || strings.ContainsAny(v, " \t"):
641 return fmt.Errorf("must be off or the xwayland-satellite program")
642 default:
643 c.Xwayland = v
644 }
645 case "background":
646 if !color.MatchString(v) {
647 return fmt.Errorf("must be #rrggbb")
648 }
649 c.Background.Color = v
650 case "floating.dim":
651 dim, err := strconv.ParseFloat(v, 64)
652 if err != nil || !(dim >= 0 && dim <= 1) {
653 return fmt.Errorf("must be between 0 and 1")
654 }
655 c.Floating.Dim = dim
656 case "stash.width":
657 n, err := strconv.Atoi(strings.TrimSuffix(v, "%"))
658 if err != nil || n < 10 || n > 90 {
659 return fmt.Errorf("must be between 10 and 90")
660 }
661 c.Stash.Width = n
662 case "stash.gap":
663 n, err := strconv.Atoi(v)
664 if err != nil || n < 0 || n > 10 {
665 return fmt.Errorf("must be between 0 and 10")
666 }
667 c.Stash.Gap = n
668 case "stash.dim":
669 dim, err := strconv.ParseFloat(v, 64)
670 if err != nil || !(dim >= 0 && dim <= 1) {
671 return fmt.Errorf("must be between 0 and 1")
672 }
673 c.Stash.Dim = dim
674 case "stash.capture":
675 b, err := onOff(v)
676 if err != nil {
677 return err
678 }
679 c.Stash.Capture = b
680 case "border.width":
681 n, err := strconv.Atoi(v)
682 if err != nil || n < 0 || n > 32 {
683 return fmt.Errorf("must be between 0 and 32")
684 }
685 c.Border.Width = n
686 case "border.active":
687 if !color.MatchString(v) {
688 return fmt.Errorf("must be #rrggbb")
689 }
690 c.Border.Active = v
691 case "border.inactive":
692 if v != "" && !color.MatchString(v) {
693 return fmt.Errorf("must be #rrggbb or empty (none)")
694 }
695 c.Border.Inactive = v
696 case "layout.gaps":
697 n, err := strconv.Atoi(v)
698 if err != nil || n < 0 || n > 200 {
699 return fmt.Errorf("must be between 0 and 200")
700 }
701 c.Layout.Gaps = n
702 case "layout.default-width":
703 return fmt.Errorf("replaced by layout.max-columns (columns share the width equally)")
704 case "layout.max-columns":
705 return setLayoutRule(&c.Layout.LayoutRules, "max-columns", v)
706 case "layout.overflow":
707 return setLayoutRule(&c.Layout.LayoutRules, "overflow", v)
708 case "layout.presets":
709 list := splitList(v)
710 if len(list) == 0 {
711 return fmt.Errorf("must not be empty")
712 }
713 for _, s := range list {
714 if !width(s) {
715 return fmt.Errorf("%q: must be a fraction like 1/2, a percentage like 50%%, 1, or pixels like 800px", s)
716 }
717 }
718 c.Layout.Presets = list
719 case "touchpad.tap":
720 b, err := onOff(v)
721 if err != nil {
722 return err
723 }
724 c.Touchpad.Tap = b
725 case "touchpad.scroll-factor":
726 f, err := strconv.ParseFloat(v, 64)
727 if err != nil || !(f > 0 && f <= 10) {
728 return fmt.Errorf("must be above 0 and at most 10")
729 }
730 c.Touchpad.ScrollFactor = f
731 case "cursor.hide-after":
732 if v == "off" {
733 c.Cursor.HideAfter = 0
734 return nil
735 }
736 d, err := time.ParseDuration(v)
737 if err != nil || d < 100*time.Millisecond || d > maxCursorHideAfter {
738 return fmt.Errorf("must be off or a duration between 100ms and %s, e.g. 5s", maxCursorHideAfter)
739 }
740 c.Cursor.HideAfter = d
741 case "focus.follow-move":
742 b, err := onOff(v)
743 if err != nil {
744 return err
745 }
746 c.Focus.FollowMove = b
747 case "focus.animation":
748 if v != ports.FocusAnimationPulse && v != ports.FocusAnimationOff {
749 return fmt.Errorf("must be pulse or off")
750 }
751 c.Focus.Animation = v
752 case "focus.effect":
753 if v != ports.FocusEffectScreen {
754 return fmt.Errorf("must be screen")
755 }
756 c.Focus.Effect = v
757 case "focus.strength":
758 // Capped low: the focus indicator must never flash.
759 f, err := strconv.ParseFloat(v, 64)
760 if err != nil || !(f >= 0.01 && f <= 0.2) {
761 return fmt.Errorf("must be between 0.01 and 0.2")
762 }
763 c.Focus.Strength = f
764 case "render.direct-scanout":
765 b, err := onOff(v)
766 if err != nil {
767 return err
768 }
769 c.Render.DirectScanout = b
770 case "render.tearing":
771 b, err := onOff(v)
772 if err != nil {
773 return err
774 }
775 c.Render.Tearing = b
776 case "render.vrr":
777 b, err := onOff(v)
778 if err != nil {
779 return err
780 }
781 c.Render.VRR = b
782 case "render.vrr-flip-gap":
783 d, err := time.ParseDuration(v)
784 if v == "0" {
785 d, err = 0, nil
786 }
787 if err != nil || d < 0 || d > maxVRRFlipGap {
788 return fmt.Errorf("must be a duration between 0 and %s, e.g. 1ms", maxVRRFlipGap)
789 }
790 c.Render.VRRFlipGap = d
791 case "performance.realtime":
792 b, err := onOff(v)
793 if err != nil {
794 return err
795 }
796 c.Performance.Realtime = b
797 case "log.level":
798 if v != "debug" && v != "info" && v != "warn" && v != "error" {
799 return fmt.Errorf("must be debug, info, warn or error")
800 }
801 c.Log.Level = v
802 case "log.debug":
803 list := splitList(v)
804 for _, s := range list {
805 if !components[s] && s != "all" {
806 return fmt.Errorf("unknown component %q", s)
807 }
808 }
809 c.Log.Debug = list
810 default:
811 if rest, ok := strings.CutPrefix(key, "touchpad."); ok {
812 return parsePointerKey(rest, v, &c.Touchpad.PointerConfig)
813 }
814 if rest, ok := strings.CutPrefix(key, "mouse."); ok {
815 return parsePointerKey(rest, v, &c.Mouse)
816 }
817 if rest, ok := strings.CutPrefix(key, "layout."); ok {
818 if i := strings.LastIndex(rest, "."); i > 0 {
819 return setOutputLayout(c, rest[:i], rest[i+1:], v)
820 }
821 }
822 return fmt.Errorf("unknown key")
823 }
824 return nil
825}
826
827// parsePointerKey applies one pointer key shared by touchpads and mice, with
828// the touchpad. or mouse. prefix already removed. Touchpad-only keys are
829// handled before; anything else is unknown. On an error p is left unchanged.
830func parsePointerKey(key, v string, p *ports.PointerConfig) error {
831 switch key {
832 case "natural-scroll":
833 b, err := onOff(v)
834 if err != nil {
835 return err
836 }
837 p.NaturalScroll = b
838 case "left-handed":
839 b, err := onOff(v)
840 if err != nil {
841 return err
842 }
843 p.LeftHanded = b
844 case "accel-speed":
845 s, err := strconv.ParseFloat(v, 64)
846 if err != nil || !(s >= -1 && s <= 1) {
847 return fmt.Errorf("must be between -1 and 1")
848 }
849 p.AccelSpeed = s
850 case "accel-profile":
851 if v != ports.AccelAdaptive && v != ports.AccelFlat {
852 return fmt.Errorf("must be adaptive or flat")
853 }
854 p.AccelProfile = v
855 default:
856 return fmt.Errorf("unknown key")
857 }
858 return nil
859}
860
861// setOutputLayout applies one layout.<output>.<field> key.
862func setOutputLayout(c *ports.Config, output, field, v string) error {
863 i := slices.IndexFunc(c.Layout.Outputs, func(o ports.OutputLayout) bool { return o.Output == output })
864 o := ports.OutputLayout{Output: output}
865 if i >= 0 {
866 o = c.Layout.Outputs[i]
867 }
868 if err := setLayoutRule(&o.LayoutRules, field, v); err != nil {
869 return err
870 }
871 if i < 0 {
872 c.Layout.Outputs = append(c.Layout.Outputs, o)
873 } else {
874 c.Layout.Outputs[i] = o
875 }
876 return nil
877}
878
879// setLayoutRule applies max-columns or overflow, for layout.*,
880// layout.<output>.* and workspace.<name>.*.
881func setLayoutRule(r *ports.LayoutRules, field, v string) error {
882 switch field {
883 case "max-columns":
884 return positive(&r.MaxColumns, v, 16)
885 case "overflow":
886 if v != "scroll" && v != "fixed" {
887 return fmt.Errorf("must be scroll or fixed")
888 }
889 r.Overflow = v
890 return nil
891 }
892 return fmt.Errorf("unknown key (max-columns, overflow)")
893}
894
895// checkWorkspaceBinds warns about a `workspace <name>` bind to an undeclared
896// workspace (it does nothing) and a named workspace no bind reaches.
897func checkWorkspaceBinds(c ports.Config, seen map[string]int) []Warning {
898 declared := map[string]bool{}
899 for _, w := range c.Workspaces {
900 declared[w.Name] = true
901 }
902 bound := map[string]bool{}
903 var warnings []Warning
904 for combo, a := range c.Binds {
905 name, ok := strings.CutPrefix(a, "workspace ")
906 if !ok {
907 continue
908 }
909 name = strings.TrimSpace(name)
910 bound[name] = true
911 if !declared[name] {
912 warnings = append(warnings, Warning{Line: seen["bind."+combo], Msg: fmt.Sprintf("bind.%s: no workspace.%s.* declared", combo, name)})
913 }
914 }
915 for _, w := range c.Workspaces {
916 // The config only knows the monitor as written: a connector home
917 // does not match a key rule, and the reverse.
918 rules := c.Layout.LayoutRules
919 for _, o := range c.Layout.Outputs {
920 if w.Monitor != "" && o.Output == w.Monitor {
921 rules = o.Over(rules)
922 }
923 }
924 if w.Over(rules).Overflow == "fixed" && len(w.Slots) > 0 {
925 line := seen["workspace."+w.Name+".column."+strconv.Itoa(w.Slots[0].Index)]
926 warnings = append(warnings, Warning{Line: line, Msg: fmt.Sprintf("workspace.%s: column widths are ignored with overflow = fixed (columns share the width)", w.Name)})
927 }
928 if !bound[w.Name] {
929 line := 0
930 for key, n := range seen {
931 if strings.HasPrefix(key, "workspace."+w.Name+".") && (line == 0 || n < line) {
932 line = n
933 }
934 }
935 warnings = append(warnings, Warning{Line: line, Msg: fmt.Sprintf("workspace.%s: no bind shows it (add bind.<keys> = workspace %s)", w.Name, w.Name)})
936 }
937 }
938 sort.Slice(warnings, func(i, j int) bool { return warnings[i].Line < warnings[j].Line })
939 return warnings
940}
941
942var workspaceName = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
943
944// setWorkspace applies one workspace.<name>.<field> key.
945func setWorkspace(w *ports.WorkspaceConfig, field, v string) error {
946 switch field {
947 case "monitor":
948 if v == "" {
949 return fmt.Errorf("needs a connector (DP-2) or a monitor key")
950 }
951 w.Monitor = v
952 case "size":
953 if v == "inherit" {
954 w.Size = [2]int{}
955 return nil
956 }
957 width, height, _, err := ParseMode(v)
958 if err != nil || width == 0 || strings.Contains(v, "@") {
959 return fmt.Errorf("must be inherit or WxH in logical pixels")
960 }
961 w.Size = [2]int{width, height}
962 case "max-columns", "overflow":
963 return setLayoutRule(&w.LayoutRules, field, v)
964 default:
965 n, ok := strings.CutPrefix(field, "column.")
966 if !ok {
967 return fmt.Errorf("unknown key (monitor, size, max-columns, overflow, column.N)")
968 }
969 index, err := strconv.Atoi(n)
970 if err != nil || index < 1 || index > 16 {
971 return fmt.Errorf("column number must be between 1 and 16")
972 }
973 size, cmd, _ := strings.Cut(v, ",")
974 size = strings.TrimSpace(size)
975 argv := strings.Fields(cmd)
976 if !width(size) || len(argv) == 0 {
977 return fmt.Errorf("must be <width>, <command> like 67%%, foot")
978 }
979 slot := ports.SlotConfig{Index: index, Width: size, Argv: argv}
980 i := sort.Search(len(w.Slots), func(i int) bool { return w.Slots[i].Index >= index })
981 if i < len(w.Slots) && w.Slots[i].Index == index {
982 w.Slots[i] = slot
983 } else {
984 w.Slots = slices.Insert(w.Slots, i, slot)
985 }
986 }
987 return nil
988}
989
990func positive(dst *int, v string, max int) error {
991 n, err := strconv.Atoi(v)
992 if err != nil || n <= 0 || n > max {
993 return fmt.Errorf("must be between 1 and %d", max)
994 }
995 *dst = n
996 return nil
997}
998
999func onOff(v string) (bool, error) {
1000 switch v {
1001 case "on":
1002 return true, nil
1003 case "off":
1004 return false, nil
1005 }
1006 return false, fmt.Errorf("must be on or off")
1007}
1008
1009func splitList(v string) []string {
1010 list := []string{}
1011 for _, s := range strings.Split(v, ",") {
1012 if s = strings.TrimSpace(s); s != "" {
1013 list = append(list, s)
1014 }
1015 }
1016 return list
1017}
1018
1019// stripComment drops a trailing ` # comment` from a value. A # that starts the
1020// value is kept, so colors like #1e1e2e need no quotes.
1021func stripComment(value string) string {
1022 for i := 1; i < len(value); i++ {
1023 if value[i] == '#' && (value[i-1] == ' ' || value[i-1] == '\t') {
1024 return strings.TrimSpace(value[:i])
1025 }
1026 }
1027 return value
1028}
1029
1030func checkAction(v string) error {
1031 if rest, ok := strings.CutPrefix(v, "spawn "); ok {
1032 if len(strings.Fields(rest)) == 0 {
1033 return fmt.Errorf("spawn needs a command")
1034 }
1035 return nil
1036 }
1037 if rest, ok := strings.CutPrefix(v, "workspace "); ok {
1038 if !workspaceName.MatchString(strings.TrimSpace(rest)) {
1039 return fmt.Errorf("workspace needs a name (letters, digits, - or _)")
1040 }
1041 return nil
1042 }
1043 for _, prefix := range []string{"focus-workspace ", "move-column-to-workspace ", "move-window-to-workspace "} {
1044 if rest, ok := strings.CutPrefix(v, prefix); ok {
1045 if n, err := strconv.Atoi(strings.TrimSpace(rest)); err != nil || n < 1 || n > 99 {
1046 return fmt.Errorf("%snumber must be between 1 and 99", prefix)
1047 }
1048 return nil
1049 }
1050 }
1051 for _, prefix := range []string{"set-column-width ", "set-window-height "} {
1052 if rest, ok := strings.CutPrefix(v, prefix); ok {
1053 if !resizeStep.MatchString(strings.TrimSpace(rest)) {
1054 return fmt.Errorf("%sneeds +N%% or -N%% (1-100)", prefix)
1055 }
1056 return nil
1057 }
1058 }
1059 if !actions[v] {
1060 return fmt.Errorf(`unknown action %q (or "spawn <command>", "workspace <name>")`, v)
1061 }
1062 return nil
1063}
1064
1065// parseCombo turns `ctrl+cmd+é` into the canonical `Cmd+Ctrl+eacute`:
1066// modifiers sorted, the key as an xkb keysym name.
1067func parseCombo(s string) (string, error) {
1068 parts := strings.Split(s, "+")
1069 key := parts[len(parts)-1]
1070 if len(parts) > 1 && key == "" {
1071 // "cmd++" means the + key.
1072 if len(parts) > 2 && parts[len(parts)-2] == "" {
1073 parts, key = parts[:len(parts)-1], "+"
1074 } else {
1075 return "", fmt.Errorf("missing key")
1076 }
1077 }
1078 if key == "" {
1079 return "", fmt.Errorf("missing key")
1080 }
1081 seen := map[string]bool{}
1082 for _, m := range parts[:len(parts)-1] {
1083 var name string
1084 switch strings.ToLower(m) {
1085 case "cmd":
1086 name = "Cmd"
1087 case "shift":
1088 name = "Shift"
1089 case "ctrl":
1090 name = "Ctrl"
1091 case "alt":
1092 name = "Alt"
1093 case "super":
1094 name = "Super"
1095 default:
1096 return "", fmt.Errorf("unknown modifier %q", m)
1097 }
1098 if seen[name] {
1099 return "", fmt.Errorf("duplicate modifier %q", m)
1100 }
1101 seen[name] = true
1102 }
1103 mods := make([]string, 0, len(seen))
1104 for m := range seen {
1105 mods = append(mods, m)
1106 }
1107 sort.Strings(mods)
1108 name, err := keysym(key)
1109 if err != nil {
1110 return "", err
1111 }
1112 return strings.Join(append(mods, name), "+"), nil
1113}
1114
1115// keysym maps a written key to its xkb keysym name.
1116func keysym(k string) (string, error) {
1117 // code:N is the physical key (evdev code), the same on every layout.
1118 if rest, ok := strings.CutPrefix(strings.ToLower(k), "code:"); ok {
1119 if n, err := strconv.Atoi(rest); err == nil && n > 0 && n < 768 {
1120 return "code:" + rest, nil
1121 }
1122 return "", fmt.Errorf("code must be an evdev key code like code:2")
1123 }
1124 if r := []rune(k); len(r) == 1 {
1125 // Binds match the unshifted keysym, so É means é.
1126 if name, ok := runeKeysyms[unicode.ToLower(r[0])]; ok {
1127 return name, nil
1128 }
1129 if r[0] > unicode.MaxASCII {
1130 return "", fmt.Errorf("write %q by its xkb keysym name", k)
1131 }
1132 return strings.ToLower(k), nil
1133 }
1134 if name, ok := namedKeys[strings.ToLower(k)]; ok {
1135 return name, nil
1136 }
1137 if len(k) <= 3 && (k[0] == 'f' || k[0] == 'F') {
1138 if n, err := strconv.Atoi(k[1:]); err == nil && n >= 1 && n <= 24 {
1139 return "F" + k[1:], nil
1140 }
1141 }
1142 return k, nil
1143}
1144
1145// parseScale accepts a decimal (1.5) or a fraction (4/3) between 1 and 4.
1146func parseScale(v string) (float64, error) {
1147 var s float64
1148 var err error
1149 if num, den, ok := strings.Cut(v, "/"); ok {
1150 var n, d float64
1151 n, err = strconv.ParseFloat(strings.TrimSpace(num), 64)
1152 if err == nil {
1153 d, err = strconv.ParseFloat(strings.TrimSpace(den), 64)
1154 }
1155 if err == nil && d != 0 {
1156 s = n / d
1157 }
1158 } else {
1159 s, err = strconv.ParseFloat(v, 64)
1160 }
1161 if err != nil || !(s >= 1 && s <= 4) {
1162 return 0, fmt.Errorf("must be between 1 and 4, like 1.5 or 4/3")
1163 }
1164 return s, nil
1165}
1166
1167// ParseMode parses "WxH" or "WxH@Hz" ("preferred" is accepted); hz is 0 when omitted.
1168func ParseMode(s string) (w, h int, hz float64, err error) {
1169 if s == "preferred" {
1170 return 0, 0, 0, nil
1171 }
1172 size, rate, hasRate := strings.Cut(s, "@")
1173 ws, hs, ok := strings.Cut(size, "x")
1174 w, e1 := strconv.Atoi(ws)
1175 h, e2 := strconv.Atoi(hs)
1176 if !ok || e1 != nil || e2 != nil || w <= 0 || h <= 0 {
1177 return 0, 0, 0, fmt.Errorf("must be off, preferred, WxH or WxH@Hz, got %q", s)
1178 }
1179 if hasRate {
1180 if hz, err = strconv.ParseFloat(rate, 64); err != nil || hz <= 0 {
1181 return 0, 0, 0, fmt.Errorf("invalid refresh rate in %q", s)
1182 }
1183 }
1184 return w, h, hz, nil
1185}
1186
1187func width(s string) bool {
1188 if s == "1" {
1189 return true
1190 }
1191 if n, ok := strings.CutSuffix(s, "%"); ok {
1192 v, e := strconv.Atoi(n)
1193 return e == nil && v > 0 && v <= 100
1194 }
1195 if strings.HasSuffix(s, "px") {
1196 n, e := strconv.Atoi(strings.TrimSuffix(s, "px"))
1197 return e == nil && n > 0
1198 }
1199 p := strings.Split(s, "/")
1200 if len(p) != 2 {
1201 return false
1202 }
1203 a, e1 := strconv.Atoi(p[0])
1204 b, e2 := strconv.Atoi(p[1])
1205 return e1 == nil && e2 == nil && a > 0 && a <= b
1206}