hyprcorrect-core 0.2.3

Core logic for hyprcorrect: configuration, the keystroke buffer, and correction providers.
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
//! Configuration: loading and saving `config.toml`, plus the hotkey,
//! provider, behavior, and privacy settings it holds.
//!
//! Cross-platform: paths resolve via the `directories` crate so the
//! file lives at the OS-conventional location (`~/.config/hyprcorrect/`
//! on Linux, `~/Library/Application Support/io.hyprcorrect.hyprcorrect/`
//! on macOS, `%APPDATA%\hyprcorrect\hyprcorrect\config\` on Windows).
//!
//! Every field has a default — a missing file or partial TOML still
//! produces a valid [`Config`]. See the "Configuration & GUI" section
//! of `DESIGN.md`.

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

use directories::ProjectDirs;
use serde::{Deserialize, Serialize};

/// An error loading or saving the config.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// No suitable OS config dir was found (extremely rare — happens
    /// in restricted sandboxes with no `$HOME`).
    #[error("no OS config directory is available")]
    NoConfigDir,
    /// The config file could not be read or written.
    #[error("config I/O: {0}")]
    Io(String),
    /// The TOML on disk could not be parsed.
    #[error("config TOML: {0}")]
    Parse(String),
    /// The config could not be serialized.
    #[error("could not serialize config: {0}")]
    Serialize(String),
}

/// The full hyprcorrect configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Config {
    pub hotkeys: Hotkeys,
    pub providers: Providers,
    pub behavior: Behavior,
    pub privacy: Privacy,
}

/// Hotkey settings. Each action is fully configurable — pick any
/// combination of modifiers plus a single non-modifier key. Stored
/// as `+`-separated accelerator strings (see [`crate::Chord`]) so
/// the file stays human-readable. An empty string means "unbound".
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Hotkeys {
    /// Accelerator for `fix-last-word`. Example: `"CTRL+SHIFT+ALT+SUPER+F"`.
    pub fix_word: String,
    /// Accelerator for `fix-last-sentence`. Empty = unbound.
    pub fix_sentence: String,
    /// Accelerator for the review popup — shows the proposed
    /// correction in a small egui window and waits for Apply / Cancel
    /// before emitting. Empty = unbound.
    pub review: String,
    /// Accelerator that, while the review popup is open, re-processes the
    /// original sentence through the LLM and reloads the popup with its
    /// suggestions — for escalating past a weak LanguageTool/spellbook
    /// correction without calling the LLM on every fix. Empty = unbound.
    pub review_llm: String,
}
impl Default for Hotkeys {
    fn default() -> Self {
        Self {
            fix_word: "CTRL+SHIFT+ALT+SUPER+F".into(),
            fix_sentence: "CTRL+SHIFT+ALT+SUPER+S".into(),
            review: "CTRL+SHIFT+ALT+SUPER+R".into(),
            review_llm: "CTRL+SHIFT+ALT+SUPER+L".into(),
        }
    }
}

/// Most LLM provider tabs the prefs UI lets you configure. Each is a
/// distinct hosted backend (Anthropic, OpenAI, …) with its own model and
/// keychain entry. The prefs UI enforces this cap and one-tab-per-backend
/// uniqueness when adding providers.
pub const MAX_LLM_PROVIDERS: usize = 5;

/// Provider routing settings.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Providers {
    /// Provider used for `fix-last-word` (instant, ideally local).
    pub default: ProviderId,
    /// Provider used for `fix-last-sentence` and the review popup.
    pub smart: ProviderId,
    /// Configured LLM providers, one per hosted backend (max
    /// [`MAX_LLM_PROVIDERS`]). When [`ProviderId::Llm`] is selected the
    /// daemon uses the first entry whose backend is wired and keyed. The
    /// field-level `#[serde(default)]` makes an absent `llms` deserialize
    /// to an empty list, so the prefs UI can persist "no providers".
    #[serde(default)]
    pub llms: Vec<LlmConfig>,
    pub languagetool: LanguageToolConfig,
}
impl Default for Providers {
    fn default() -> Self {
        Self {
            default: ProviderId::Spellbook,
            smart: ProviderId::Llm,
            llms: vec![LlmConfig::default()],
            languagetool: LanguageToolConfig::default(),
        }
    }
}

/// The set of correction providers the UI lets the user choose between.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ProviderId {
    /// Offline pure-Rust spell checker (Hunspell-compatible).
    #[default]
    Spellbook,
    /// Network LLM (model and backend per [`LlmConfig`]).
    Llm,
    /// Self-hosted LanguageTool over HTTP. Serialized as
    /// `"languagetool"` (one word) so the TOML enum value matches
    /// the `[providers.languagetool]` section header and the
    /// product's own one-word branding — overriding the
    /// container-level snake_case default that would otherwise
    /// produce `"language_tool"`.
    #[serde(rename = "languagetool")]
    LanguageTool,
}

/// LLM provider settings. The API key lives in the OS keychain — see
/// [`crate::secrets`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct LlmConfig {
    /// LLM vendor: one of `anthropic`, `openai`, `gemini`, `openrouter`,
    /// `mistral`, `groq`, `deepseek`, `xai`, or `openai-compatible` for a
    /// custom/local OpenAI-style endpoint (see `base_url`). See
    /// [`crate::llm::is_backend_wired`].
    pub backend: String,
    /// Model name passed to the vendor API.
    pub model: String,
    /// Base URL for the `openai-compatible` backend — a local
    /// Ollama / LM Studio server or any other OpenAI-style endpoint, up
    /// to but not including `/chat/completions`
    /// (e.g. `http://localhost:11434/v1`). The named cloud backends
    /// ignore it and use their own built-in URLs, so it's `None` for
    /// them and omitted from the TOML.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_url: Option<String>,
}
impl Default for LlmConfig {
    fn default() -> Self {
        Self {
            backend: "anthropic".into(),
            model: "claude-haiku-4-5".into(),
            base_url: None,
        }
    }
}

/// LanguageTool HTTP settings. Off by default — the user supplies their
/// own self-hosted URL.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct LanguageToolConfig {
    pub enabled: bool,
    pub url: String,
    /// Host folder of LanguageTool's n-gram dataset (the unzipped
    /// directory that contains an `en/` subfolder). When set, the
    /// Install-with-Docker convenience mounts it and points the server at
    /// it so real-word confusions (wear/where) get caught. `None` = the
    /// server runs without n-grams.
    pub ngram_dir: Option<String>,
}
impl Default for LanguageToolConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            url: "http://localhost:8081".into(),
            ngram_dir: None,
        }
    }
}

/// Where the review popup's per-option word definitions come from.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DefinitionSource {
    /// Don't show definitions.
    Off,
    /// Bundled offline WordNet glosses — the privacy-preserving default.
    #[default]
    Local,
    /// Online dictionary API (`api.dictionaryapi.dev`). Sends the
    /// looked-up word to a third party, so it's opt-in.
    Online,
}

/// Behavior knobs.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Behavior {
    /// Wait time per backspace, applied as a single pause between
    /// the backspace burst and the replacement-text burst. Total
    /// pause = `pause_per_backspace_ms` × backspace count.
    ///
    /// The only emit-side knob most users need. The reason behind
    /// it: Wayland delivers all dispatched backspaces reliably, but
    /// the focused app drains them through its own event loop at
    /// its own pace — if the daemon's next `wtype` (the typing
    /// burst) starts before the app has finished applying the
    /// backspaces, those text events queue behind the still-
    /// processing deletes and visually leave a prefix of the
    /// original on screen. This pause covers that drain time.
    /// Raise it if you still see leftover prefix characters.
    pub pause_per_backspace_ms: u32,

    /// Which keys clear the per-window typing buffer when pressed.
    /// Useful trade-off: a reset is the safest response to a key
    /// we can't precisely track (so fix-word never lands at the
    /// wrong spot), but disabling some resets lets the buffer
    /// survive an autocomplete (Tab), a mode switch (Esc), and so
    /// on so a subsequent fix-word can still operate on the
    /// already-typed text.
    pub reset_keys: ResetKeys,

    /// Open the review popup straight into vim mode instead of the
    /// word-edit (Tab) mode. `Ctrl+E` still toggles between the two — so
    /// when this is on, `Ctrl+E` flips *to* word-edit mode.
    pub review_starts_in_vim: bool,

    /// When a fix routed to the LLM can't run — no API key, an
    /// unsupported/unwired backend, or the network call itself fails —
    /// try a configured LanguageTool server before dropping to the
    /// offline Spellbook. Only has an effect when LanguageTool is
    /// enabled with a URL; otherwise the fix falls straight through to
    /// Spellbook either way. On by default so a configured LanguageTool
    /// is preferred over the offline dictionary.
    pub fallback_to_languagetool: bool,

    /// Source for the per-option word definitions under the review
    /// popup's suggestion dropdown. Defaults to the bundled offline
    /// dictionary; can be turned off or pointed at an online API.
    pub definitions: DefinitionSource,
}
impl Default for Behavior {
    fn default() -> Self {
        Self {
            pause_per_backspace_ms: 8,
            reset_keys: ResetKeys::default(),
            review_starts_in_vim: false,
            fallback_to_languagetool: true,
            definitions: DefinitionSource::Local,
        }
    }
}

/// Per-key toggles for "this key clears the typing buffer." See
/// [`Behavior::reset_keys`]. Defaults match what the daemon needs
/// to stay safe — Enter, the arrow keys above/below, Page Up/Down,
/// forward Delete, and Insert all reset; Tab and Escape do not
/// because they typically don't change typed text and resetting
/// drops the buffer for no gain.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct ResetKeys {
    pub enter: bool,
    pub tab: bool,
    pub escape: bool,
    pub up: bool,
    pub down: bool,
    pub page_up: bool,
    pub page_down: bool,
    pub delete: bool,
    pub insert: bool,
}

impl Default for ResetKeys {
    fn default() -> Self {
        Self {
            enter: true,
            tab: false,
            escape: false,
            up: true,
            down: true,
            page_up: true,
            page_down: true,
            delete: true,
            insert: true,
        }
    }
}

/// Privacy settings.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Privacy {
    /// Window classes (lowercase, exact match) for which the daemon
    /// will not buffer keystrokes. Useful for password managers.
    pub app_blocklist: Vec<String>,
}

impl Config {
    /// The OS-conventional path to `config.toml`.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::NoConfigDir`] when the platform exposes
    /// no usable config directory (e.g. a sandbox with no `$HOME`).
    pub fn path() -> Result<PathBuf, ConfigError> {
        let dirs = ProjectDirs::from("io", "hyprcorrect", "hyprcorrect")
            .ok_or(ConfigError::NoConfigDir)?;
        Ok(dirs.config_dir().join("config.toml"))
    }
}

/// The OS-conventional data folder where prefs downloads the LanguageTool
/// n-gram dataset (`<data_dir>/ngrams`). `None` when no data directory is
/// available (e.g. a sandbox with no `$HOME`).
pub fn ngram_data_dir() -> Option<PathBuf> {
    ProjectDirs::from("io", "hyprcorrect", "hyprcorrect").map(|dirs| dirs.data_dir().join("ngrams"))
}

impl Config {
    /// Load from the OS-conventional path. A missing file yields a
    /// default [`Config`] (not an error).
    ///
    /// # Errors
    ///
    /// See [`ConfigError`].
    pub fn load() -> Result<Self, ConfigError> {
        Self::load_from(&Self::path()?)
    }

    /// Load from a specific path. A missing file is not an error.
    ///
    /// # Errors
    ///
    /// See [`ConfigError`].
    pub fn load_from(path: &Path) -> Result<Self, ConfigError> {
        match fs::read_to_string(path) {
            Ok(text) => toml::from_str(&text).map_err(|e| ConfigError::Parse(e.to_string())),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(e) => Err(ConfigError::Io(e.to_string())),
        }
    }

    /// Save to the OS-conventional path, creating parent dirs as needed.
    ///
    /// # Errors
    ///
    /// See [`ConfigError`].
    pub fn save(&self) -> Result<(), ConfigError> {
        self.save_to(&Self::path()?)
    }

    /// Save to a specific path.
    ///
    /// # Errors
    ///
    /// See [`ConfigError`].
    pub fn save_to(&self, path: &Path) -> Result<(), ConfigError> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|e| ConfigError::Io(e.to_string()))?;
        }
        let text =
            toml::to_string_pretty(self).map_err(|e| ConfigError::Serialize(e.to_string()))?;
        fs::write(path, text).map_err(|e| ConfigError::Io(e.to_string()))
    }
}

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

    #[test]
    fn defaults_roundtrip_through_toml() {
        let cfg = Config::default();
        let text = toml::to_string_pretty(&cfg).unwrap();
        let back: Config = toml::from_str(&text).unwrap();
        assert_eq!(cfg, back);
    }

    #[test]
    fn empty_file_yields_defaults() {
        let cfg: Config = toml::from_str("").unwrap();
        assert_eq!(cfg, Config::default());
    }

    #[test]
    fn partial_file_fills_missing_with_defaults() {
        let cfg: Config = toml::from_str(
            r#"[hotkeys]
fix_word = "CTRL+J"
"#,
        )
        .unwrap();
        assert_eq!(cfg.hotkeys.fix_word, "CTRL+J");
        // Untouched sections still hold defaults.
        assert_eq!(cfg.behavior.pause_per_backspace_ms, 8);
        assert_eq!(cfg.providers.default, ProviderId::Spellbook);
        assert!(cfg.privacy.app_blocklist.is_empty());
    }

    #[test]
    fn save_then_load_round_trips_through_disk() {
        let dir = unique_tempdir();
        let path = dir.join("config.toml");
        let mut cfg = Config::default();
        cfg.hotkeys.fix_word = "CTRL+ALT+K".into();
        cfg.privacy.app_blocklist = vec!["1password".into(), "keepassxc".into()];
        cfg.save_to(&path).unwrap();
        let loaded = Config::load_from(&path).unwrap();
        assert_eq!(loaded, cfg);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_from_missing_path_yields_defaults() {
        let path = unique_tempdir().join("does-not-exist.toml");
        let cfg = Config::load_from(&path).unwrap();
        assert_eq!(cfg, Config::default());
    }

    #[test]
    fn llms_list_round_trips_through_toml() {
        let mut cfg = Config::default();
        // Active provider is first in the list (index 0).
        cfg.providers.llms = vec![
            LlmConfig {
                backend: "anthropic".into(),
                model: "claude-haiku-4-5".into(),
                base_url: None,
            },
            LlmConfig {
                backend: "openai".into(),
                model: "gpt-4o-mini".into(),
                base_url: None,
            },
            // A custom OpenAI-compatible endpoint carries its base URL.
            LlmConfig {
                backend: "openai-compatible".into(),
                model: "llama3.1".into(),
                base_url: Some("http://localhost:11434/v1".into()),
            },
        ];
        let text = toml::to_string_pretty(&cfg).unwrap();
        let back: Config = toml::from_str(&text).unwrap();
        assert_eq!(back.providers.llms, cfg.providers.llms);

        // Deleting every provider persists as an empty list (doesn't
        // silently resurrect the default).
        cfg.providers.llms.clear();
        let text = toml::to_string_pretty(&cfg).unwrap();
        let back: Config = toml::from_str(&text).unwrap();
        assert!(back.providers.llms.is_empty());
    }

    fn unique_tempdir() -> PathBuf {
        let nano = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let dir = std::env::temp_dir().join(format!("hyprcorrect-cfg-{nano}"));
        fs::create_dir_all(&dir).unwrap();
        dir
    }
}