Skip to main content

ratasm/config/
settings.rs

1//! User settings, loaded from a configuration file.
2
3use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7
8use crate::ui::theme::ThemeKind;
9
10/// Editor preferences.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(default, deny_unknown_fields)]
13pub struct EditorSettings {
14    /// Spaces inserted by one indent.
15    pub indent_width: usize,
16    /// Whether to show line numbers.
17    pub line_numbers: bool,
18    /// Whether to highlight the line the cursor is on.
19    pub highlight_current_line: bool,
20    /// Whether to show a marker on the matching bracket.
21    pub match_brackets: bool,
22    /// Whether typing an opening bracket or quote inserts its partner.
23    pub auto_close_pairs: bool,
24}
25
26impl Default for EditorSettings {
27    fn default() -> Self {
28        Self {
29            indent_width: 4,
30            line_numbers: true,
31            highlight_current_line: true,
32            match_brackets: true,
33            auto_close_pairs: true,
34        }
35    }
36}
37
38/// Debugger preferences.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(default, deny_unknown_fields)]
41pub struct DebuggerSettings {
42    /// The debugger executable.
43    pub gdb: String,
44    /// How long to wait for a command before giving up.
45    pub timeout_ms: u64,
46    /// How many bytes the memory panel reads at a time.
47    pub memory_window: usize,
48    /// How many stack slots to show around the stack pointer.
49    pub stack_depth: usize,
50    /// Record execution so it can be stepped backwards.
51    pub record: bool,
52}
53
54impl Default for DebuggerSettings {
55    fn default() -> Self {
56        Self {
57            gdb: "gdb".to_owned(),
58            timeout_ms: 10_000,
59            memory_window: 256,
60            stack_depth: 16,
61            record: true,
62        }
63    }
64}
65
66/// Appearance preferences.
67#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
68#[serde(default, deny_unknown_fields)]
69pub struct AppearanceSettings {
70    /// The colour theme.
71    pub theme: ThemeKind,
72    /// Force Unicode glyphs on or off.
73    pub unicode: Option<bool>,
74}
75
76/// Everything a user can configure.
77#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
78#[serde(default, deny_unknown_fields)]
79pub struct Settings {
80    /// Appearance.
81    pub appearance: AppearanceSettings,
82    /// Editor behaviour.
83    pub editor: EditorSettings,
84    /// Debugger behaviour.
85    pub debugger: DebuggerSettings,
86    /// Key binding overrides, keyed by chord.
87    pub keys: BTreeMap<String, String>,
88}
89
90/// Errors from loading settings.
91#[derive(Debug, thiserror::Error)]
92pub enum SettingsError {
93    /// The file could not be read.
94    #[error("cannot read {path}: {source}")]
95    Read {
96        /// The file involved.
97        path: PathBuf,
98        /// The underlying error.
99        #[source]
100        source: std::io::Error,
101    },
102    /// The file is not valid TOML, or names a field that does not exist.
103    #[error("{path}: {message}")]
104    Parse {
105        /// The file involved.
106        path: PathBuf,
107        /// What the parser objected to.
108        message: String,
109    },
110    /// The file could not be written.
111    #[error("cannot write {path}: {source}")]
112    Write {
113        /// The file involved.
114        path: PathBuf,
115        /// The underlying error.
116        #[source]
117        source: std::io::Error,
118    },
119}
120
121impl Settings {
122    /// The file name settings are stored in.
123    pub const FILE_NAME: &'static str = "config.toml";
124
125    /// Parses settings from TOML text.
126    pub fn from_toml(path: &Path, text: &str) -> Result<Self, SettingsError> {
127        toml::from_str(text).map_err(|error| SettingsError::Parse {
128            path: path.to_path_buf(),
129            message: error.message().to_owned(),
130        })
131    }
132
133    /// Loads settings from `path`, or the defaults when it does not exist.
134    pub fn load(path: &Path) -> Result<Self, SettingsError> {
135        if !path.exists() {
136            return Ok(Self::default());
137        }
138        let text = std::fs::read_to_string(path).map_err(|source| SettingsError::Read {
139            path: path.to_path_buf(),
140            source,
141        })?;
142        Self::from_toml(path, &text)
143    }
144
145    /// Loads settings from the default location.
146    pub fn load_default() -> Result<Self, SettingsError> {
147        match default_path() {
148            Some(path) => Self::load(&path),
149            None => Ok(Self::default()),
150        }
151    }
152
153    /// Writes settings to `path`, creating parent directories.
154    pub fn save(&self, path: &Path) -> Result<(), SettingsError> {
155        let text = toml::to_string_pretty(self).map_err(|error| SettingsError::Parse {
156            path: path.to_path_buf(),
157            message: error.to_string(),
158        })?;
159
160        if let Some(parent) = path.parent() {
161            std::fs::create_dir_all(parent).map_err(|source| SettingsError::Write {
162                path: path.to_path_buf(),
163                source,
164            })?;
165        }
166        std::fs::write(path, text).map_err(|source| SettingsError::Write {
167            path: path.to_path_buf(),
168            source,
169        })
170    }
171
172    /// The indent width, clamped to something usable.
173    pub fn indent_width(&self) -> usize {
174        self.editor.indent_width.clamp(1, 16)
175    }
176
177    /// The debugger command timeout.
178    pub fn debugger_timeout(&self) -> std::time::Duration {
179        let millis = if self.debugger.timeout_ms == 0 {
180            DebuggerSettings::default().timeout_ms
181        } else {
182            self.debugger.timeout_ms
183        };
184        std::time::Duration::from_millis(millis)
185    }
186
187    /// How many bytes the memory panel should read, clamped to a sane range.
188    pub fn memory_window(&self) -> usize {
189        self.debugger.memory_window.clamp(16, 4096)
190    }
191
192    /// How many stack slots to show, clamped to a sane range.
193    pub fn stack_depth(&self) -> usize {
194        self.debugger.stack_depth.clamp(4, 128)
195    }
196
197    /// Builds the theme these settings describe.
198    pub fn theme(&self) -> crate::ui::Theme {
199        match self.appearance.unicode {
200            Some(unicode) => crate::ui::Theme::new(self.appearance.theme, unicode),
201            None => crate::ui::Theme::detect(self.appearance.theme),
202        }
203    }
204
205    /// Builds the keymap these settings describe.
206    pub fn keymap(&self) -> (super::Keymap, Vec<super::KeymapError>) {
207        let mut keymap = super::Keymap::defaults();
208        let errors = keymap.apply_overrides(&self.keys);
209        (keymap, errors)
210    }
211}
212
213/// The default settings file location.
214pub fn default_path() -> Option<PathBuf> {
215    let base = std::env::var_os("XDG_CONFIG_HOME")
216        .map(PathBuf::from)
217        .filter(|path| !path.as_os_str().is_empty())
218        .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))?;
219    Some(base.join("ratasm").join(Settings::FILE_NAME))
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    fn parse(text: &str) -> Result<Settings, SettingsError> {
227        Settings::from_toml(Path::new("test.toml"), text)
228    }
229
230    #[test]
231    fn an_empty_file_gives_the_defaults() {
232        let settings = parse("").expect("parses");
233        assert_eq!(settings, Settings::default());
234        assert_eq!(settings.appearance.theme, ThemeKind::Dark);
235        assert_eq!(settings.editor.indent_width, 4);
236        assert_eq!(settings.debugger.gdb, "gdb");
237    }
238
239    #[test]
240    fn a_partial_file_keeps_the_other_defaults() {
241        let settings = parse("[appearance]\ntheme = \"light\"\n").expect("parses");
242        assert_eq!(settings.appearance.theme, ThemeKind::Light);
243        assert_eq!(settings.editor.indent_width, 4, "untouched field");
244    }
245
246    #[test]
247    fn every_section_parses() {
248        let settings = parse(
249            r#"
250[appearance]
251theme = "colorblind"
252unicode = false
253
254[editor]
255indent_width = 8
256line_numbers = false
257
258[debugger]
259gdb = "gdb-multiarch"
260timeout_ms = 30000
261stack_depth = 32
262
263[keys]
264"ctrl+b" = "build.build"
265"#,
266        )
267        .expect("parses");
268
269        assert_eq!(settings.appearance.theme, ThemeKind::Colorblind);
270        assert_eq!(settings.appearance.unicode, Some(false));
271        assert_eq!(settings.editor.indent_width, 8);
272        assert!(!settings.editor.line_numbers);
273        assert_eq!(settings.debugger.gdb, "gdb-multiarch");
274        assert_eq!(settings.debugger.stack_depth, 32);
275        assert_eq!(
276            settings.keys.get("ctrl+b").map(String::as_str),
277            Some("build.build")
278        );
279    }
280
281    #[test]
282    fn a_misspelled_field_is_rejected_rather_than_ignored() {
283        let error = parse("[editor]\nindent_with = 8\n").expect_err("must fail");
284        assert!(matches!(error, SettingsError::Parse { .. }));
285    }
286
287    #[test]
288    fn malformed_toml_is_reported_not_panicked() {
289        assert!(parse("[appearance\ntheme =").is_err());
290    }
291
292    #[test]
293    fn an_unknown_theme_name_is_rejected() {
294        assert!(parse("[appearance]\ntheme = \"solarized\"\n").is_err());
295    }
296
297    #[test]
298    fn a_missing_file_is_not_an_error() {
299        let dir = tempfile::tempdir().expect("temp dir");
300        let settings = Settings::load(&dir.path().join("absent.toml")).expect("defaults");
301        assert_eq!(settings, Settings::default());
302    }
303
304    #[test]
305    fn a_present_but_broken_file_is_an_error() {
306        let dir = tempfile::tempdir().expect("temp dir");
307        let path = dir.path().join("config.toml");
308        std::fs::write(&path, "[editor]\nnonsense = 1\n").expect("write");
309        assert!(Settings::load(&path).is_err());
310    }
311
312    #[test]
313    fn settings_round_trip_through_a_file() {
314        let dir = tempfile::tempdir().expect("temp dir");
315        let path = dir.path().join("nested/config.toml");
316
317        let mut settings = Settings::default();
318        settings.appearance.theme = ThemeKind::Light;
319        settings.editor.indent_width = 2;
320        settings
321            .keys
322            .insert("ctrl+b".to_owned(), "build.build".to_owned());
323
324        settings.save(&path).expect("save");
325        let reloaded = Settings::load(&path).expect("load");
326        assert_eq!(reloaded, settings);
327    }
328
329    #[test]
330    fn out_of_range_values_are_clamped_rather_than_rejected() {
331        let settings = parse(
332            "[editor]\nindent_width = 0\n\n[debugger]\nmemory_window = 1\nstack_depth = 9999\n",
333        )
334        .expect("parses");
335
336        assert_eq!(settings.indent_width(), 1);
337        assert_eq!(settings.memory_window(), 16);
338        assert_eq!(settings.stack_depth(), 128);
339    }
340
341    #[test]
342    fn a_zero_debugger_timeout_falls_back_to_the_default() {
343        let settings = parse("[debugger]\ntimeout_ms = 0\n").expect("parses");
344        assert_eq!(
345            settings.debugger_timeout(),
346            std::time::Duration::from_millis(DebuggerSettings::default().timeout_ms)
347        );
348    }
349
350    #[test]
351    fn the_theme_honours_an_explicit_unicode_choice() {
352        let settings = parse("[appearance]\nunicode = false\n").expect("parses");
353        assert!(settings.theme().symbols().breakpoint.is_ascii());
354
355        let settings = parse("[appearance]\nunicode = true\n").expect("parses");
356        assert!(!settings.theme().symbols().breakpoint.is_ascii());
357    }
358
359    #[test]
360    fn key_overrides_are_applied_and_problems_reported() {
361        let settings =
362            parse("[keys]\n\"ctrl+b\" = \"build.build\"\n\"ctrl+j\" = \"no.such.command\"\n")
363                .expect("parses");
364
365        let (keymap, errors) = settings.keymap();
366        assert_eq!(errors.len(), 1, "the bad binding is reported");
367        assert_eq!(
368            keymap.command_for(super::super::parse_binding("ctrl+b").expect("parses")),
369            Some(&crate::command::Command::Build),
370            "the good binding took effect"
371        );
372    }
373
374    #[test]
375    fn the_default_path_follows_the_xdg_specification() {
376        let path = default_path().expect("a path");
377        let text = path.display().to_string();
378        assert!(text.ends_with("ratasm/config.toml"), "{text}");
379    }
380}