fux 0.11.0

Minimal persistent terminal multiplexer built on bevy_ecs
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Typed, validated user configuration. Small on purpose: shell/program default, prefix and
//! bindings, bounded history, clipboard policy and resource limits.

use crate::commands::{Action, Key};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::env;
use std::ffi::OsString;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};

pub const MAX_CONFIG_BYTES: u64 = 1024 * 1024;
pub const MAX_COMMAND_ARGS: usize = 128;
pub const MAX_COMMAND_ARG_BYTES: usize = 4096;
pub const MAX_COMMAND_BYTES: usize = 16 * 1024;
pub const MAX_SCROLLBACK_LINES: u32 = 100_000;
pub const MAX_PANES: usize = crate::view::MAX_PANES;
pub const MAX_TABS: usize = crate::view::MAX_TABS;
pub const MAX_WORKSPACES: usize = 64;

/// A sparse TOML document deserializes over the defaults: every key is optional, unknown keys
/// are errors, and `[bindings]` merges with the default bindings instead of replacing them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields, default)]
pub struct Config {
    pub prefix: Key,
    #[serde(deserialize_with = "merged_bindings")]
    pub bindings: BTreeMap<Key, Action>,
    pub default_command: Command,
    pub clipboard: ClipboardPolicy,
    pub history: HistoryLimits,
    pub limits: Limits,
    /// `[final]`: retention of the final records of panes fux creates itself.
    #[serde(rename = "final")]
    pub final_records: FinalRecords,
    pub style: Style,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            prefix: Key(crate::commands::DEFAULT_PREFIX),
            bindings: default_bindings(),
            default_command: default_shell(),
            clipboard: ClipboardPolicy::Disabled,
            history: HistoryLimits::default(),
            limits: Limits::default(),
            final_records: FinalRecords::default(),
            style: Style::default(),
        }
    }
}

impl Config {
    /// Parses a sparse TOML document over the built-in defaults.
    pub fn from_toml(input: &str) -> Result<Self, ConfigError> {
        let candidate: Self = toml::from_str(input).map_err(ConfigError::Toml)?;
        candidate.validate()?;
        Ok(candidate)
    }

    /// Loads a sparse configuration file. A missing file means built-in defaults.
    pub fn load_from_path(path: &Path) -> Result<Self, ConfigError> {
        match fs::File::open(path) {
            Ok(file) => {
                let mut bytes = Vec::new();
                file.take(MAX_CONFIG_BYTES + 1)
                    .read_to_end(&mut bytes)
                    .map_err(|error| ConfigError::Io {
                        path: path.to_owned(),
                        error,
                    })?;
                if bytes.len() as u64 > MAX_CONFIG_BYTES {
                    return invalid(
                        "config file",
                        format!("may use at most {MAX_CONFIG_BYTES} bytes"),
                    );
                }
                let input = String::from_utf8(bytes).map_err(|_| ConfigError::Invalid {
                    field: "config file",
                    reason: "must be UTF-8".to_owned(),
                })?;
                Self::from_toml(&input)
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(error) => Err(ConfigError::Io {
                path: path.to_owned(),
                error,
            }),
        }
    }

    /// Loads the configuration from [`default_path`].
    pub fn load() -> Result<Self, ConfigError> {
        Self::load_from_path(&default_path()?)
    }

    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.bindings.len() > 256 {
            return invalid("bindings", "at most 256 entries are allowed");
        }
        let mut seen = std::collections::BTreeSet::new();
        for key in self.bindings.keys() {
            let byte = crate::commands::canonical_key(key.0);
            if !seen.insert(byte) {
                return invalid(
                    "bindings",
                    "two bindings use the same key with and without Shift",
                );
            }
            if byte == crate::commands::canonical_key(self.prefix.0) {
                return invalid("bindings", "a binding cannot be the prefix key");
            }
        }
        self.default_command.validate("default-command")?;
        self.history.validate()?;
        self.limits.validate()?;
        self.final_records.validate()
    }
}

/// Resolves `$XDG_CONFIG_HOME/fux/config.toml`, falling back to `$HOME/.config/fux/config.toml`.
pub fn default_path() -> Result<PathBuf, ConfigError> {
    default_path_from(env::var_os("XDG_CONFIG_HOME"), env::var_os("HOME"))
}

pub fn default_path_from(
    xdg_config_home: Option<OsString>,
    home: Option<OsString>,
) -> Result<PathBuf, ConfigError> {
    let base = xdg_config_home
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
        .filter(|value| value.is_absolute())
        .or_else(|| {
            home.filter(|value| !value.is_empty())
                .map(PathBuf::from)
                .filter(|value| value.is_absolute())
                .map(|value| value.join(".config"))
        })
        .ok_or(ConfigError::NoConfigHome)?;
    Ok(base.join("fux").join("config.toml"))
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct Command {
    pub argv: Vec<String>,
}

impl Command {
    pub fn new(argv: Vec<String>) -> Result<Self, ConfigError> {
        let command = Self { argv };
        command.validate("command")?;
        Ok(command)
    }

    fn validate(&self, field: &'static str) -> Result<(), ConfigError> {
        if self.argv.is_empty() || self.argv.len() > MAX_COMMAND_ARGS {
            return invalid(
                field,
                format!("argv must contain 1-{MAX_COMMAND_ARGS} entries"),
            );
        }
        let mut total = 0usize;
        for (index, argument) in self.argv.iter().enumerate() {
            if (index == 0 && argument.is_empty())
                || argument.len() > MAX_COMMAND_ARG_BYTES
                || argument.contains('\0')
            {
                return invalid(
                    field,
                    "executable must be non-empty; arguments must be bounded UTF-8 without NUL",
                );
            }
            total = total.saturating_add(argument.len());
        }
        if total > MAX_COMMAND_BYTES {
            return invalid(
                field,
                format!("argv may use at most {MAX_COMMAND_BYTES} bytes"),
            );
        }
        Ok(())
    }
}

/// One of the sixteen ANSI colours, the terminal's default foreground, or no colour at all.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum StyleColor {
    Black,
    Red,
    Green,
    Yellow,
    Blue,
    Magenta,
    Cyan,
    White,
    BrightBlack,
    BrightRed,
    BrightGreen,
    BrightYellow,
    BrightBlue,
    BrightMagenta,
    BrightCyan,
    BrightWhite,
    #[default]
    Default,
    None,
}

/// Colours of the bar and separators. Defaults are muted and work on dark and light terminals.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields, default)]
pub struct Style {
    /// Workspace name, inactive tabs and the focused pane's `id: title`.
    pub bar: StyleColor,
    /// Background of the whole bar row.
    pub bar_background: StyleColor,
    /// The current tab (drawn reversed).
    pub tab_active: StyleColor,
    /// Separators not touching the focused pane.
    pub separator: StyleColor,
    /// Separators touching the focused pane (also bold).
    pub separator_focused: StyleColor,
    /// Transient notices in the bar; errors always use red.
    pub notice: StyleColor,
}

impl Default for Style {
    fn default() -> Self {
        Self {
            bar: StyleColor::White,
            bar_background: StyleColor::BrightBlack,
            tab_active: StyleColor::Default,
            separator: StyleColor::BrightBlack,
            separator_focused: StyleColor::Default,
            notice: StyleColor::Yellow,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ClipboardPolicy {
    /// Never write to the enclosing terminal's clipboard.
    #[default]
    Disabled,
    /// Copies and application OSC 52 writes reach the terminal clipboard (bounded, once).
    WriteOnly,
}

impl ClipboardPolicy {
    #[must_use]
    pub const fn writes(self) -> bool {
        matches!(self, Self::WriteOnly)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields, default)]
pub struct HistoryLimits {
    /// Retained history rows per pane.
    pub scrollback_lines: u32,
}

impl Default for HistoryLimits {
    fn default() -> Self {
        Self {
            scrollback_lines: 10_000,
        }
    }
}

impl HistoryLimits {
    fn validate(&self) -> Result<(), ConfigError> {
        if self.scrollback_lines == 0 || self.scrollback_lines > MAX_SCROLLBACK_LINES {
            return invalid(
                "history.scrollback-lines",
                format!("must be 1-{MAX_SCROLLBACK_LINES}"),
            );
        }
        Ok(())
    }
}

/// `[final] retain-ms`: how long the final record of a pane fux creates on its own (the initial
/// pane of a workspace, a new tab's pane, the viewer's and CLI's splits) stays readable through
/// the manager's `final` after the pane closes. Automation chooses per pane on `split`
/// (`final_retain_ms`); this default only covers panes nobody launched over the protocol.
pub const DEFAULT_FINAL_RETAIN_MS: u64 = 60_000;

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields, default)]
pub struct FinalRecords {
    /// Milliseconds, 1 through `MAX_FINAL_RETENTION_MS` (four hours).
    pub retain_ms: u64,
}

impl Default for FinalRecords {
    fn default() -> Self {
        Self {
            retain_ms: DEFAULT_FINAL_RETAIN_MS,
        }
    }
}

impl FinalRecords {
    fn validate(&self) -> Result<(), ConfigError> {
        let ceiling = crate::proto::control::MAX_FINAL_RETENTION_MS;
        if self.retain_ms == 0 || self.retain_ms > ceiling {
            return invalid("final.retain-ms", format!("must be 1-{ceiling}"));
        }
        Ok(())
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields, default)]
pub struct Limits {
    pub max_panes: usize,
    pub max_tabs: usize,
    pub max_workspaces: usize,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_panes: MAX_PANES,
            max_tabs: MAX_TABS,
            max_workspaces: MAX_WORKSPACES,
        }
    }
}

impl Limits {
    fn validate(&self) -> Result<(), ConfigError> {
        validate_limit("limits.max-panes", self.max_panes, MAX_PANES)?;
        validate_limit("limits.max-tabs", self.max_tabs, MAX_TABS)?;
        validate_limit("limits.max-workspaces", self.max_workspaces, MAX_WORKSPACES)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("neither XDG_CONFIG_HOME nor HOME is set")]
    NoConfigHome,
    #[error("failed to read {}: {error}", path.display())]
    Io {
        path: PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("invalid configuration TOML: {0}")]
    Toml(#[source] toml::de::Error),
    #[error("invalid `{field}`: {reason}")]
    Invalid { field: &'static str, reason: String },
}

fn default_shell() -> Command {
    let shell = default_shell_from(
        env::var_os("SHELL"),
        env::var_os("PREFIX"),
        cfg!(target_os = "android"),
    );
    Command {
        argv: vec![shell, "-l".to_owned()],
    }
}

pub fn default_shell_from(
    shell: Option<OsString>,
    prefix: Option<OsString>,
    android: bool,
) -> String {
    shell
        .filter(|value| !value.is_empty())
        .map(|value| value.to_string_lossy().into_owned())
        .or_else(|| {
            prefix.map(|prefix| {
                PathBuf::from(prefix)
                    .join("bin/sh")
                    .to_string_lossy()
                    .into_owned()
            })
        })
        .unwrap_or_else(|| {
            if android {
                "/system/bin/sh".to_owned()
            } else {
                "/bin/sh".to_owned()
            }
        })
}

fn merged_bindings<'de, D>(deserializer: D) -> Result<BTreeMap<Key, Action>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let mut bindings = default_bindings();
    bindings.extend(BTreeMap::<Key, Action>::deserialize(deserializer)?);
    Ok(bindings)
}

fn default_bindings() -> BTreeMap<Key, Action> {
    crate::commands::DEFAULT_BINDINGS
        .iter()
        .map(|spec| (Key(spec.key), spec.action))
        .collect()
}

fn validate_limit(field: &'static str, value: usize, maximum: usize) -> Result<(), ConfigError> {
    if value == 0 || value > maximum {
        return invalid(field, format!("must be 1-{maximum}"));
    }
    Ok(())
}

fn invalid<T>(field: &'static str, reason: impl Into<String>) -> Result<T, ConfigError> {
    Err(ConfigError::Invalid {
        field,
        reason: reason.into(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn style_table_parses_named_colours_and_rejects_unknown_ones() {
        let config = Config::from_toml(
            "[style]\nbar = \"blue\"\ntab-active = \"none\"\nseparator-focused = \"bright-white\"\n",
        )
        .unwrap_or_default();
        assert_eq!(config.style.bar, StyleColor::Blue);
        assert_eq!(config.style.tab_active, StyleColor::None);
        assert_eq!(config.style.separator_focused, StyleColor::BrightWhite);
        assert_eq!(
            config.style.separator,
            StyleColor::BrightBlack,
            "defaults fill the rest"
        );
        assert_eq!(config.style.bar_background, StyleColor::BrightBlack);
        assert!(Config::from_toml("[style]\nbar = \"teal\"\n").is_err());
        assert!(Config::from_toml("[style]\naccent = \"red\"\n").is_err());
    }

    #[test]
    fn defaults_round_trip_and_sparse_documents_merge() {
        let config = Config::default();
        assert!(config.validate().is_ok());
        let text = toml::to_string_pretty(&config).unwrap_or_default();
        let parsed = Config::from_toml(&text).unwrap_or_default();
        assert_eq!(parsed, config);
        let sparse = Config::from_toml("prefix = 'C-b'\n[history]\nscrollback-lines = 5\n")
            .unwrap_or_default();
        assert_eq!(sparse.prefix, Key(2));
        assert_eq!(sparse.history.scrollback_lines, 5);
        assert_eq!(sparse.bindings, config.bindings);
    }

    #[test]
    fn invalid_documents_are_rejected() {
        assert!(Config::from_toml("prefix = 'ab'").is_err());
        assert!(Config::from_toml("[bindings]\n'C-a' = 'detach'").is_err());
        assert!(Config::from_toml("[bindings]\n'x' = 'nonexistent-action'").is_err());
        assert!(Config::from_toml("zor-path = '/bin/true'").is_err());
        assert!(Config::from_toml("[hints]\ndelay-ms = 0").is_err());
        assert!(Config::from_toml("[history]\nscrollback-lines = 0").is_err());
        assert!(Config::from_toml("[limits]\nmax-panes = 100000").is_err());
        assert!(Config::from_toml("[final]\nretain-ms = 0").is_err());
        assert!(Config::from_toml("[final]\nretain-ms = 14400001").is_err());
        assert_eq!(
            Config::from_toml("[final]\nretain-ms = 5000")
                .map(|config| config.final_records.retain_ms)
                .ok(),
            Some(5000)
        );
        assert!(Config::from_toml("default-command = { argv = [] }").is_err());
        assert!(Config::from_toml("clipboard = 'read-write'").is_err());
    }

    #[test]
    fn shell_default_prefers_env_then_platform() {
        assert_eq!(
            default_shell_from(Some("/usr/bin/fish".into()), None, false),
            "/usr/bin/fish"
        );
        assert_eq!(default_shell_from(Some("".into()), None, false), "/bin/sh");
        assert_eq!(default_shell_from(None, None, true), "/system/bin/sh");
        assert_eq!(
            default_shell_from(None, Some("/data/usr".into()), true),
            "/data/usr/bin/sh"
        );
    }

    #[test]
    fn config_path_prefers_xdg_then_home() {
        assert_eq!(
            default_path_from(Some("/x".into()), Some("/h".into())).ok(),
            Some(PathBuf::from("/x/fux/config.toml"))
        );
        assert_eq!(
            default_path_from(Some("".into()), Some("/h".into())).ok(),
            Some(PathBuf::from("/h/.config/fux/config.toml"))
        );
        assert!(default_path_from(None, None).is_err());
    }
}