ratty 0.4.1

A GPU-rendered terminal emulator that supports inline 3D graphics
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
//! Application configuration types.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::Context;
use bevy::prelude::Resource;
use etcetera::{BaseStrategy, choose_base_strategy};
use serde::{Deserialize, Deserializer};

use crate::paths::expand_path;

/// Application name used for config discovery.
pub const APP_NAME: &str = "ratty";
/// Local fallback config path.
pub const CONFIG_PATH: &str = "config/ratty.toml";
/// Label used for the terminal render target.
pub const TERMINAL_TEXTURE_LABEL: &str = "ratty.parley_ratatui";
/// Z depth used for the cursor model root.
pub const CURSOR_DEPTH: f32 = 10.0;

/// Application configuration.
#[derive(Resource, Debug, Clone, Deserialize, Default)]
#[serde(default)]
pub struct AppConfig {
    /// Window settings.
    pub window: WindowConfig,
    /// Terminal grid settings.
    pub terminal: TerminalConfig,
    /// Shell spawning settings.
    pub shell: ShellConfig,
    /// Extra environment variables.
    pub env: BTreeMap<String, String>,
    /// User-defined key bindings.
    pub bindings: BindingsConfig,
    /// Font settings.
    pub font: FontConfig,
    /// Theme settings.
    pub theme: ThemeConfig,
    /// Cursor settings.
    pub cursor: CursorConfig,
}

impl AppConfig {
    /// Loads the application configuration.
    ///
    /// System config is preferred over the local fallback file when both exist.
    ///
    /// # Errors
    ///
    /// Returns an error if the selected config file cannot be read or parsed.
    pub fn load() -> anyhow::Result<Self> {
        Self::load_from_path(None)
    }

    /// Loads the application configuration from an explicit path or the default search paths.
    ///
    /// # Errors
    ///
    /// Returns an error if the selected config file cannot be read or parsed.
    pub fn load_from_path(path: Option<&Path>) -> anyhow::Result<Self> {
        let selected_path = if let Some(path) = path {
            Some(expand_path(path))
        } else {
            Self::default_config_path()?
        };

        let Some(path) = selected_path else {
            return Ok(Self::default());
        };

        let contents = fs::read_to_string(&path)
            .with_context(|| format!("failed to read {}", path.display()))?;
        let mut config: Self = toml::from_str(&contents)
            .with_context(|| format!("failed to parse {}", path.display()))?;
        config.resolve_relative_paths(&path);
        Ok(config)
    }

    fn default_config_path() -> anyhow::Result<Option<PathBuf>> {
        let strategy =
            choose_base_strategy().context("failed to determine system config directory")?;
        let system_path = strategy.config_dir().join(APP_NAME).join("ratty.toml");
        let local_path = PathBuf::from(CONFIG_PATH);
        Ok(if system_path.exists() {
            Some(system_path)
        } else if local_path.exists() {
            Some(local_path)
        } else {
            None
        })
    }

    fn resolve_relative_paths(&mut self, path: &Path) {
        let config_dir = path.parent().unwrap_or_else(|| Path::new("."));
        self.cursor.model.path = resolve_config_path(config_dir, &self.cursor.model.path);
        if let Some(program) = self.shell.program.as_mut() {
            *program = resolve_config_path(config_dir, program);
        }
    }
}

fn resolve_config_path(config_dir: &Path, path: &Path) -> PathBuf {
    let expanded = expand_path(path);
    if !expanded.is_relative() {
        return expanded;
    }

    let config_relative = config_dir.join(&expanded);
    if expanded
        .parent()
        .is_some_and(|parent| !parent.as_os_str().is_empty())
        || config_relative.exists()
    {
        config_relative
    } else {
        expanded
    }
}

/// Window configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct WindowConfig {
    /// Window width in logical pixels.
    pub width: u32,
    /// Window height in logical pixels.
    pub height: u32,
    /// Window scale-factor override.
    pub scale_factor: f32,
    /// Window opacity from `0.0` to `1.0`.
    pub opacity: f32,
}

impl Default for WindowConfig {
    fn default() -> Self {
        Self {
            width: 960,
            height: 620,
            scale_factor: 1.0,
            opacity: 1.0,
        }
    }
}

/// Terminal grid configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct TerminalConfig {
    /// Default terminal column count.
    pub default_cols: u16,
    /// Default terminal row count.
    pub default_rows: u16,
    /// Scrollback line count.
    pub scrollback: usize,
}

impl Default for TerminalConfig {
    fn default() -> Self {
        Self {
            default_cols: 104,
            default_rows: 32,
            scrollback: 2_000,
        }
    }
}

/// Shell configuration.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(default)]
pub struct ShellConfig {
    /// Shell program path.
    pub program: Option<PathBuf>,
    /// Shell arguments.
    pub args: Vec<String>,
}

/// Key binding configuration.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(default)]
pub struct BindingsConfig {
    /// Configured key bindings.
    pub keys: Vec<KeyBindingConfig>,
}

/// Single key binding entry.
#[derive(Debug, Clone, Deserialize)]
pub struct KeyBindingConfig {
    /// Key name.
    pub key: String,
    /// Modifier expression.
    #[serde(default)]
    pub with: String,
    /// Bound action.
    pub action: BindingAction,
}

/// Terminal binding action.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum BindingAction {
    /// Disables a binding.
    #[serde(rename = "none")]
    None,
    /// Toggles between the flat and warped terminal views.
    #[serde(rename = "Toggle3DMode")]
    Toggle3DMode,
    /// Toggles the Mobius-strip terminal view.
    #[serde(rename = "ToggleMobiusMode")]
    ToggleMobiusMode,
    /// Scrolls one page up through scrollback.
    #[serde(rename = "ScrollPageUp")]
    ScrollPageUp,
    /// Scrolls one page down through scrollback.
    #[serde(rename = "ScrollPageDown")]
    ScrollPageDown,
    /// Scrolls one line up through scrollback.
    #[serde(rename = "ScrollUp")]
    ScrollUp,
    /// Scrolls one line down through scrollback.
    #[serde(rename = "ScrollDown")]
    ScrollDown,
    /// Increases plane warp.
    #[serde(rename = "IncreaseWarp")]
    IncreaseWarp,
    /// Decreases plane warp.
    #[serde(rename = "DecreaseWarp")]
    DecreaseWarp,
    /// Copies the current selection.
    #[serde(rename = "Copy")]
    Copy,
    /// Pastes clipboard contents.
    #[serde(rename = "Paste")]
    Paste,
    /// Increases the font size.
    #[serde(rename = "IncreaseFontSize")]
    IncreaseFontSize,
    /// Decreases the font size.
    #[serde(rename = "DecreaseFontSize")]
    DecreaseFontSize,
    /// Resets the font size.
    #[serde(rename = "ResetFontSize")]
    ResetFontSize,
}

/// Font configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct FontConfig {
    /// Font family name.
    pub family: String,
    /// Font style override.
    pub style: FontStyleConfig,
    /// Font size in logical pixels.
    pub size: i32,
}

impl Default for FontConfig {
    fn default() -> Self {
        Self {
            family: "DejaVu Sans Mono".to_string(),
            style: FontStyleConfig::Regular,
            size: 18,
        }
    }
}

/// Font style override.
#[derive(Debug, Clone, Copy, Deserialize, Default)]
pub enum FontStyleConfig {
    /// Regular font style.
    #[serde(rename = "Regular")]
    #[default]
    Regular,
    /// Bold font style.
    #[serde(rename = "Bold")]
    Bold,
    /// Italic font style.
    #[serde(rename = "Italic")]
    Italic,
    /// Bold italic font style.
    #[serde(rename = "BoldItalic")]
    BoldItalic,
}

/// Terminal theme configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct ThemeConfig {
    /// Default foreground color.
    #[serde(deserialize_with = "deserialize_hex_color")]
    pub foreground: [u8; 3],
    /// Default background color.
    #[serde(deserialize_with = "deserialize_hex_color")]
    pub background: [u8; 3],
    /// Cursor color.
    #[serde(deserialize_with = "deserialize_hex_color")]
    pub cursor: [u8; 3],
    /// ANSI 0..7 colors.
    #[serde(default = "ThemePaletteConfig::default_normal")]
    pub normal: ThemePaletteConfig,
    /// ANSI 8..15 colors.
    #[serde(default = "ThemePaletteConfig::default_bright")]
    pub bright: ThemePaletteConfig,
}

impl Default for ThemeConfig {
    fn default() -> Self {
        Self {
            foreground: [220, 215, 186],
            background: [31, 31, 40],
            cursor: [126, 156, 216],
            normal: ThemePaletteConfig::default_normal(),
            bright: ThemePaletteConfig::default_bright(),
        }
    }
}

impl ThemeConfig {
    /// Returns the ANSI 0..15 palette.
    pub fn palette(&self) -> [[u8; 3]; 16] {
        [
            self.normal.black,
            self.normal.red,
            self.normal.green,
            self.normal.yellow,
            self.normal.blue,
            self.normal.magenta,
            self.normal.cyan,
            self.normal.white,
            self.bright.black,
            self.bright.red,
            self.bright.green,
            self.bright.yellow,
            self.bright.blue,
            self.bright.magenta,
            self.bright.cyan,
            self.bright.white,
        ]
    }
}

/// Eight-color theme palette.
#[derive(Debug, Clone, Deserialize)]
pub struct ThemePaletteConfig {
    /// Black color.
    #[serde(deserialize_with = "deserialize_hex_color")]
    pub black: [u8; 3],
    /// Red color.
    #[serde(deserialize_with = "deserialize_hex_color")]
    pub red: [u8; 3],
    /// Green color.
    #[serde(deserialize_with = "deserialize_hex_color")]
    pub green: [u8; 3],
    /// Yellow color.
    #[serde(deserialize_with = "deserialize_hex_color")]
    pub yellow: [u8; 3],
    /// Blue color.
    #[serde(deserialize_with = "deserialize_hex_color")]
    pub blue: [u8; 3],
    /// Magenta color.
    #[serde(deserialize_with = "deserialize_hex_color")]
    pub magenta: [u8; 3],
    /// Cyan color.
    #[serde(deserialize_with = "deserialize_hex_color")]
    pub cyan: [u8; 3],
    /// White color.
    #[serde(deserialize_with = "deserialize_hex_color")]
    pub white: [u8; 3],
}

impl ThemePaletteConfig {
    /// Returns the default ANSI 0..7 palette.
    pub fn default_normal() -> Self {
        Self {
            black: [0, 0, 0],
            red: [205, 49, 49],
            green: [13, 188, 121],
            yellow: [229, 229, 16],
            blue: [36, 114, 200],
            magenta: [188, 63, 188],
            cyan: [17, 168, 205],
            white: [229, 229, 229],
        }
    }

    /// Returns the default ANSI 8..15 palette.
    pub fn default_bright() -> Self {
        Self {
            black: [102, 102, 102],
            red: [241, 76, 76],
            green: [35, 209, 139],
            yellow: [245, 245, 67],
            blue: [59, 142, 234],
            magenta: [214, 112, 214],
            cyan: [41, 184, 219],
            white: [255, 255, 255],
        }
    }
}

/// Cursor configuration.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(default)]
pub struct CursorConfig {
    /// Cursor model settings.
    pub model: CursorModelConfig,
    /// Cursor animation settings.
    pub animation: CursorAnimationConfig,
}

/// Cursor model configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct CursorModelConfig {
    /// Enables the custom cursor model.
    pub visible: bool,
    /// Model scale multiplier.
    pub scale_factor: f32,
    /// Horizontal model offset.
    pub x_offset: f32,
    /// Plane distance in 3D mode.
    pub plane_offset: f32,
    /// Cursor model brightness.
    pub brightness: f32,
    /// Cursor model base color.
    #[serde(deserialize_with = "deserialize_hex_color")]
    pub color: [u8; 3],
    /// Cursor asset path.
    pub path: PathBuf,
}

impl Default for CursorModelConfig {
    fn default() -> Self {
        Self {
            visible: true,
            scale_factor: 6.0,
            x_offset: 0.1,
            plane_offset: 18.0,
            brightness: 1.0,
            color: [255, 255, 255],
            path: PathBuf::from("CairoSpinyMouse.obj"),
        }
    }
}

/// Cursor animation configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct CursorAnimationConfig {
    /// Spin speed.
    pub spin_speed: f32,
    /// Bob speed.
    pub bob_speed: f32,
    /// Bob amplitude.
    pub bob_amplitude: f32,
}

impl Default for CursorAnimationConfig {
    fn default() -> Self {
        Self {
            spin_speed: 1.4,
            bob_speed: 2.2,
            bob_amplitude: 0.08,
        }
    }
}

fn deserialize_hex_color<'de, D>(deserializer: D) -> Result<[u8; 3], D::Error>
where
    D: Deserializer<'de>,
{
    let value = String::deserialize(deserializer)?;
    parse_hex_color(&value).map_err(serde::de::Error::custom)
}

fn parse_hex_color(value: &str) -> anyhow::Result<[u8; 3]> {
    let hex = value.strip_prefix('#').unwrap_or(value);
    if hex.len() != 6 {
        anyhow::bail!("expected hex color in #RRGGBB format, got {value}");
    }

    let r = u8::from_str_radix(&hex[0..2], 16)
        .with_context(|| format!("invalid red component in {value}"))?;
    let g = u8::from_str_radix(&hex[2..4], 16)
        .with_context(|| format!("invalid green component in {value}"))?;
    let b = u8::from_str_radix(&hex[4..6], 16)
        .with_context(|| format!("invalid blue component in {value}"))?;
    Ok([r, g, b])
}