Skip to main content

kimun_notes/settings/
mod.rs

1use crate::keys::action_shortcuts::{ActionShortcuts, TextAction};
2use crate::keys::key_strike::KeyStrike;
3use crate::settings::config_dir::get_or_create_config_dir;
4use crate::settings::themes::Theme;
5use crate::settings::workspace_config::WorkspaceConfig;
6use std::io::{Read, Write};
7use std::path::{Path, PathBuf};
8use std::sync::{Arc, RwLock};
9
10use std::fs::{self, File};
11
12use color_eyre::eyre;
13
14/// Shared settings handle — all screens and components reference the same instance.
15pub type SharedSettings = Arc<RwLock<AppSettings>>;
16use kimun_core::nfs::VaultPath;
17
18use crate::keys::KeyBindings;
19mod config_dir;
20pub mod config_migration;
21pub mod history;
22pub mod icons;
23pub mod themes;
24pub mod workspace_config;
25
26// ---------------------------------------------------------------------------
27// Sort settings types (shared between AppSettings and sorting UI)
28// ---------------------------------------------------------------------------
29
30#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
31#[serde(rename_all = "lowercase")]
32pub enum SortFieldSetting {
33    Name,
34    Title,
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
38#[serde(rename_all = "lowercase")]
39pub enum SortOrderSetting {
40    Ascending,
41    Descending,
42}
43
44#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
45#[serde(rename_all = "lowercase")]
46pub enum EditorBackendSetting {
47    #[default]
48    Textarea,
49    Nvim,
50    Vim,
51}
52
53// pub mod theme;
54
55#[cfg(debug_assertions)]
56const CONFIG_DIR: &str = "kimun_debug";
57#[cfg(not(debug_assertions))]
58const CONFIG_DIR: &str = "kimun";
59
60const BASE_CONFIG_FILE: &str = "config.toml";
61const THEMES_DIR: &str = "themes";
62const CACHE_FILE_EXT: &str = "kimuncache";
63const HISTORY_FILE_EXT: &str = "txt";
64
65const CONFIG_HEADER: &str = "\
66# ─── Kimün configuration ────────────────────────────────────────────────────
67#
68# KEY BINDINGS
69# ────────────
70# Supported combinations:
71#   - ctrl and/or alt (with optional shift) + a letter (a-z)
72#   - bare F-key (F1–F12, no modifier required)
73# Any combo that does not follow these rules is silently ignored when loaded.
74#
75# Format per action:
76#   ActionName = [\"<modifiers> & <letter>\", ...]
77#
78# Available modifiers (combine with +):  ctrl   alt   shift
79#
80# Examples:
81#   Quit         = [\"ctrl&Q\"]            # Ctrl+Q
82#   SearchNotes  = [\"ctrl&K\"]            # Ctrl+K
83#   OpenNote     = [\"ctrl&O\"]            # Ctrl+O  (fuzzy file finder)
84#   OpenSettings = [\"ctrl&,\"]            # Ctrl+,
85#   NewJournal   = [\"ctrl&J\"]            # Ctrl+J
86#   FileOperations = [\"F2\"]              # F2  (open file-ops menu: delete/rename/move)
87#   Leader       = [\"ctrl&G\"]            # Ctrl+G  (leader gateway: Ctrl+G f f, ...)
88#   OpenCommandPalette = [\"ctrl&P\"]      # Ctrl+P  (every leader command, fuzzy)
89#
90# OTHER SETTINGS
91# ──────────────
92#   theme             = \"Gruvbox Dark\"   # or any built-in / custom theme name
93#   leader_timeout_ms = 400               # hesitation before the which-key menu
94#
95# LEADER TREE OVERRIDES
96# ─────────────────────
97#   Remap, add, or remove leader sequences ([leader.bind]) and rename group
98#   captions ([leader.labels]). Keys are the sequence AFTER the gateway;
99#   bind values are action ids (see the cheatsheet) or \"none\" to unbind.
100#   [leader.bind]
101#   \"o f\" = \"find.files\"     # remap: leader o f now opens the file picker
102#   \"x\"   = \"note.daily\"     # add:   leader x opens today's journal
103#   \"g p\" = \"none\"           # remove the git-sync stub binding
104#   [leader.labels]
105#   \"f\"   = \"+search\"        # rename the +find group caption
106#
107# ─────────────────────────────────────────────────────────────────────────────
108";
109
110#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq)]
111pub struct AppSettings {
112    // Phase 2 config
113    #[serde(default)]
114    pub config_version: u32,
115    #[serde(flatten, skip_serializing_if = "Option::is_none")]
116    pub workspace_config: Option<WorkspaceConfig>,
117
118    // Legacy Phase 1 fields — only kept for migration detection/deserialization.
119    // Never written back: workspace_dir is taken by migration, last_paths is
120    // moved into workspace_config entries.
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub workspace_dir: Option<PathBuf>,
123    #[serde(default, skip_serializing)]
124    pub last_paths: Vec<VaultPath>,
125
126    // Preserved fields
127    #[serde(default)]
128    pub theme: String,
129    #[serde(default = "default_cache_dir")]
130    pub cache_dir: PathBuf,
131    #[serde(skip)]
132    cache_dir_resolved: Option<PathBuf>,
133
134    #[serde(default = "default_history_dir")]
135    pub history_dir: PathBuf,
136    #[serde(skip)]
137    history_dir_resolved: Option<PathBuf>,
138    #[serde(skip, default = "yes")]
139    needs_indexing: bool,
140    #[serde(default = "default_keybindings")]
141    pub key_bindings: KeyBindings,
142    #[serde(default = "default_autosave_interval")]
143    pub autosave_interval_secs: u64,
144    /// Hesitation timeout (ms) before the which-key overlay reveals itself
145    /// during a pending leader sequence. Sequences typed faster never wait.
146    #[serde(default = "default_leader_timeout_ms")]
147    pub leader_timeout_ms: u64,
148    /// Leader-tree customization: `[leader.bind]` sequence→action-id
149    /// overrides and `[leader.labels]` group captions. Applied over the
150    /// built-in tree.
151    #[serde(default)]
152    pub leader: LeaderConfig,
153    #[serde(default = "default_use_nerd_fonts")]
154    pub use_nerd_fonts: bool,
155    #[serde(default)]
156    pub editor_backend: EditorBackendSetting,
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub nvim_path: Option<std::path::PathBuf>,
159    #[serde(default = "default_sort_field")]
160    pub default_sort_field: SortFieldSetting,
161    #[serde(default = "default_sort_order")]
162    pub default_sort_order: SortOrderSetting,
163    #[serde(default = "default_journal_sort_field")]
164    pub journal_sort_field: SortFieldSetting,
165    #[serde(default = "default_journal_sort_order")]
166    pub journal_sort_order: SortOrderSetting,
167    #[serde(default)]
168    pub group_directories: bool,
169    /// Custom config file path. `None` means use the default location.
170    /// Not serialized — it's a runtime-only override.
171    #[serde(skip)]
172    pub config_file: Option<PathBuf>,
173}
174
175fn default_keybindings() -> KeyBindings {
176    let mut kb = KeyBindings::empty();
177    kb.batch_add()
178        .with_ctrl()
179        .add(KeyStrike::KeyK, ActionShortcuts::SearchNotes)
180        .add(KeyStrike::KeyO, ActionShortcuts::OpenNote)
181        .add(KeyStrike::KeyB, ActionShortcuts::Text(TextAction::Bold))
182        .add(KeyStrike::KeyI, ActionShortcuts::Text(TextAction::Italic))
183        .add(
184            KeyStrike::KeyU,
185            ActionShortcuts::Text(TextAction::Underline),
186        )
187        .add(
188            KeyStrike::KeyS,
189            ActionShortcuts::Text(TextAction::Strikethrough),
190        )
191        .add(KeyStrike::KeyL, ActionShortcuts::Text(TextAction::Link))
192        .add(
193            KeyStrike::KeyT,
194            ActionShortcuts::Text(TextAction::ToggleHeader),
195        )
196        // =============================
197        // We add shift to the modifiers
198        // =============================
199        .with_shift()
200        .add(KeyStrike::KeyL, ActionShortcuts::Text(TextAction::Image));
201
202    // TUI navigation shortcuts (always Ctrl — terminal apps don't use Cmd/Meta).
203    // NOTE: the `Quit` entry must match `crate::keys::default_quit_combo()`,
204    // which the deserialize safety net uses to recover an unreachable app.
205    kb.batch_add()
206        .with_ctrl()
207        // Ctrl-P is the command palette (decision 2026-06-05); settings
208        // live on Ctrl+Shift+P.
209        .add(KeyStrike::KeyP, ActionShortcuts::OpenCommandPalette)
210        .add(KeyStrike::KeyQ, ActionShortcuts::Quit)
211        .add(KeyStrike::KeyJ, ActionShortcuts::NewJournal)
212        // Drawer toggle. Deliberate spec deviation: the spec's Tier-0 puts
213        // this on Ctrl-B, but Ctrl-B stays Bold (decision 2026-06-05) — the
214        // drawer toggle lives on Ctrl-T.
215        .add(KeyStrike::KeyT, ActionShortcuts::ToggleSidebar)
216        .add(KeyStrike::KeyR, ActionShortcuts::OpenSortDialog)
217        // Leader gateway. Spec deviation: spec says Ctrl-K, which stays the
218        // note browser; the gateway lives on Ctrl-G (decision 2026-06-05).
219        .add(KeyStrike::KeyG, ActionShortcuts::Leader)
220        // FollowLink's always-works binding; Ctrl+Enter also follows on
221        // kitty-protocol terminals (hardcoded in the editor screen).
222        .add(KeyStrike::KeyN, ActionShortcuts::FollowLink)
223        .add(KeyStrike::KeyH, ActionShortcuts::FocusSidebar)
224        .add(KeyStrike::KeyL, ActionShortcuts::FocusEditor)
225        .add(KeyStrike::KeyW, ActionShortcuts::QuickNote)
226        // Ctrl-E opens (or switches the drawer to) the file browser; the
227        // pure drawer toggle is Ctrl-T above. ToggleQueryPanel has no
228        // default binding — FIND stays reachable via the rail and leader.
229        .add(KeyStrike::KeyE, ActionShortcuts::OpenFileBrowser)
230        .add(KeyStrike::KeyF, ActionShortcuts::FindInBuffer);
231
232    // Settings — the classic Ctrl+, (Ctrl+Shift+P collides with kitty's
233    // default hints-kitten chord prefix, which holds the screen mid-chord).
234    kb.batch_add()
235        .with_ctrl()
236        .add(KeyStrike::Comma, ActionShortcuts::OpenPreferences);
237
238    // File operations menu (F2 — no modifier, reliable in all terminals).
239    kb.batch_add()
240        .add(KeyStrike::F2, ActionShortcuts::FileOperations);
241
242    kb.batch_add()
243        .add(KeyStrike::F3, ActionShortcuts::OpenSavedSearches);
244
245    kb.batch_add()
246        .add(KeyStrike::F4, ActionShortcuts::SwitchWorkspace);
247
248    // Ctrl+D — save the current query to saved searches. Ctrl-only by design:
249    // Ctrl+Shift is unreliable on some terminals, Ctrl+S is taken by
250    // Strikethrough, and Ctrl+{A,C,X,Z} are claimed by the editor. Ctrl+D is
251    // the only free, terminal-safe Ctrl combo.
252    kb.batch_add()
253        .with_ctrl()
254        .add(KeyStrike::KeyD, ActionShortcuts::SaveCurrentQuery);
255
256    kb
257}
258
259fn yes() -> bool {
260    true
261}
262
263fn default_autosave_interval() -> u64 {
264    5
265}
266
267fn default_leader_timeout_ms() -> u64 {
268    400
269}
270
271/// The `[leader]` config section: binding overrides + group captions.
272#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
273pub struct LeaderConfig {
274    /// `[leader.bind]`: sequence (after the gateway, e.g. `"o f"` / `"x"`) →
275    /// action id (see the cheatsheet) or `"none"` to unbind.
276    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
277    pub bind: std::collections::BTreeMap<String, String>,
278    /// `[leader.labels]`: group sequence (e.g. `"f"`) → caption shown in the
279    /// which-key overlay and cheatsheet.
280    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
281    pub labels: std::collections::BTreeMap<String, String>,
282}
283
284impl AppSettings {
285    /// The leader tree with this config's `[leader]` overrides applied — the
286    /// ONE constructor every surface (engine, which-key, cheatsheet, palette)
287    /// must use, so they can never disagree.
288    pub fn leader_tree(&self) -> crate::keys::leader::LeaderNode {
289        let tree = crate::keys::leader::apply_overrides(
290            crate::keys::leader::leader_tree(),
291            self.leader
292                .bind
293                .iter()
294                .map(|(k, v)| (k.as_str(), v.as_str())),
295        );
296        crate::keys::leader::apply_labels(
297            tree,
298            self.leader
299                .labels
300                .iter()
301                .map(|(k, v)| (k.as_str(), v.as_str())),
302        )
303    }
304}
305
306fn default_cache_dir() -> PathBuf {
307    PathBuf::from(".")
308}
309
310fn default_history_dir() -> PathBuf {
311    PathBuf::from("history")
312}
313
314fn default_use_nerd_fonts() -> bool {
315    false
316}
317
318fn default_sort_field() -> SortFieldSetting {
319    SortFieldSetting::Name
320}
321
322fn default_sort_order() -> SortOrderSetting {
323    SortOrderSetting::Ascending
324}
325
326fn default_journal_sort_field() -> SortFieldSetting {
327    SortFieldSetting::Name
328}
329
330fn default_journal_sort_order() -> SortOrderSetting {
331    SortOrderSetting::Descending
332}
333
334impl Default for AppSettings {
335    fn default() -> Self {
336        Self {
337            config_version: 0,
338            workspace_config: None,
339            last_paths: vec![],
340            workspace_dir: None,
341            theme: Default::default(),
342            cache_dir: default_cache_dir(),
343            cache_dir_resolved: None,
344            history_dir: default_history_dir(),
345            history_dir_resolved: None,
346            needs_indexing: true,
347            key_bindings: default_keybindings(),
348            autosave_interval_secs: default_autosave_interval(),
349            leader_timeout_ms: default_leader_timeout_ms(),
350            leader: LeaderConfig::default(),
351            use_nerd_fonts: false,
352            editor_backend: EditorBackendSetting::Textarea,
353            nvim_path: None,
354            default_sort_field: default_sort_field(),
355            default_sort_order: default_sort_order(),
356            journal_sort_field: default_journal_sort_field(),
357            journal_sort_order: default_journal_sort_order(),
358            group_directories: false,
359            config_file: None,
360        }
361    }
362}
363
364impl AppSettings {
365    pub fn theme_list(&self) -> Vec<Theme> {
366        let mut list = Theme::builtins();
367        list.append(&mut Self::load_custom_themes());
368        // Merge the user's default.toml override if present.
369        if let Ok(custom_default) = Self::load_default_theme() {
370            list.push(custom_default);
371        }
372        list.sort_by(|a, b| a.name.cmp(&b.name));
373        list
374    }
375
376    fn default_config_file_path() -> eyre::Result<PathBuf> {
377        let config_home = get_or_create_config_dir(CONFIG_DIR)?;
378        Ok(config_home.join(BASE_CONFIG_FILE))
379    }
380
381    fn get_config_file_path(&self) -> eyre::Result<PathBuf> {
382        if let Some(ref path) = self.config_file {
383            Ok(path.clone())
384        } else {
385            Self::default_config_file_path()
386        }
387    }
388
389    fn get_themes_path() -> eyre::Result<PathBuf> {
390        let config_home = get_or_create_config_dir(CONFIG_DIR)?;
391        Ok(config_home.join(THEMES_DIR))
392    }
393
394    fn load_theme_from_path(path: &std::path::Path) -> eyre::Result<Theme> {
395        let theme_string = fs::read_to_string(path)?;
396        match toml::from_str::<Theme>(&theme_string) {
397            Ok(theme) => Ok(theme),
398            Err(e) => {
399                // Never delete a user-authored file over a typo — warn and
400                // skip, exactly like load_custom_themes does.
401                tracing::warn!("Skipping unparsable theme file {:?}: {}", path, e);
402                Err(eyre::eyre!("corrupt theme file: {}", e))
403            }
404        }
405    }
406
407    fn load_default_theme() -> eyre::Result<Theme> {
408        let theme_path = AppSettings::get_themes_path()?.join("default.toml");
409        Self::load_theme_from_path(&theme_path)
410    }
411
412    fn load_custom_themes() -> Vec<Theme> {
413        let mut themes = Vec::new();
414
415        // Get themes directory, return empty vec if it fails
416        let themes_path = match Self::get_themes_path() {
417            Ok(path) => path,
418            Err(_) => return themes,
419        };
420
421        // Read directory entries, return empty vec if it fails
422        let entries = match fs::read_dir(&themes_path) {
423            Ok(entries) => entries,
424            Err(_) => return themes,
425        };
426
427        // Iterate through all entries in the themes directory
428        for entry in entries.flatten() {
429            let path = entry.path();
430
431            // Skip if not a file
432            if !path.is_file() {
433                continue;
434            }
435
436            // Skip if not a .toml file
437            if path.extension().and_then(|s| s.to_str()) != Some("toml") {
438                continue;
439            }
440
441            // Skip default.toml
442            if path.file_name().and_then(|s| s.to_str()) == Some("default.toml") {
443                continue;
444            }
445
446            // Try to read and deserialize the theme file
447            match fs::read_to_string(&path)
448                .and_then(|s| toml::from_str::<Theme>(&s).map_err(std::io::Error::other))
449            {
450                Ok(theme) => themes.push(theme),
451                Err(e) => tracing::warn!("Skipping theme file {:?}: {}", path, e),
452            }
453        }
454
455        themes
456    }
457
458    pub fn save_to_disk(&self) -> eyre::Result<()> {
459        tracing::debug!("Saving settings to disk");
460        let settings_file_path = self.get_config_file_path()?;
461        let mut file = File::create(settings_file_path)?;
462        file.write_all(CONFIG_HEADER.as_bytes())?;
463        let toml = toml::to_string(&self)?;
464        file.write_all(toml.as_bytes())?;
465        Ok(())
466    }
467
468    pub fn load_from_disk() -> eyre::Result<Self> {
469        let settings_file_path = Self::default_config_file_path()?;
470
471        if !settings_file_path.exists() {
472            let default_settings = Self::default();
473            default_settings.save_to_disk()?;
474            Ok(default_settings)
475        } else {
476            let mut settings_file = File::open(&settings_file_path)?;
477
478            let mut toml = String::new();
479            settings_file.read_to_string(&mut toml)?;
480
481            match toml::from_str::<AppSettings>(toml.as_ref()) {
482                Ok(mut setting) => {
483                    setting.config_file = Some(settings_file_path.clone());
484                    let config_dir = settings_file_path
485                        .parent()
486                        .unwrap_or(std::path::Path::new("."));
487                    setting.resolve_paths(config_dir);
488                    if config_migration::ConfigMigration::run(&mut setting)? {
489                        setting.save_to_disk()?;
490                    }
491                    setting.merge_missing_default_bindings();
492                    Ok(setting)
493                }
494                Err(e) => {
495                    tracing::warn!(
496                        "Config file at {:?} could not be parsed ({}). \
497                         Renaming to .corrupt and starting with defaults.",
498                        settings_file_path,
499                        e
500                    );
501                    let corrupt_path = settings_file_path.with_extension("toml.corrupt");
502                    let _ = fs::rename(&settings_file_path, &corrupt_path);
503                    let defaults = Self::default();
504                    defaults.save_to_disk()?;
505                    Ok(defaults)
506                }
507            }
508        }
509    }
510
511    pub fn load_from_file(path: PathBuf) -> eyre::Result<Self> {
512        if let Some(parent) = path.parent() {
513            fs::create_dir_all(parent)?;
514        }
515        if !path.exists() {
516            let default_settings = Self {
517                config_file: Some(path),
518                ..Self::default()
519            };
520            default_settings.save_to_disk()?;
521            return Ok(default_settings);
522        }
523        let mut toml_str = String::new();
524        File::open(&path)?.read_to_string(&mut toml_str)?;
525        match toml::from_str::<AppSettings>(&toml_str) {
526            Ok(mut setting) => {
527                setting.config_file = Some(path.clone());
528
529                // Resolve ~ and relative paths against the config file's directory.
530                let config_dir = path.parent().unwrap_or(std::path::Path::new("."));
531                setting.resolve_paths(config_dir);
532
533                // Run config migrations (e.g. Phase 1 → Phase 2 workspace_dir).
534                if config_migration::ConfigMigration::run(&mut setting)? {
535                    setting.save_to_disk()?;
536                }
537
538                setting.merge_missing_default_bindings();
539                Ok(setting)
540            }
541            Err(e) => {
542                tracing::warn!(
543                    "Config file at {:?} could not be parsed ({}). \
544                     Renaming to .corrupt and starting with defaults.",
545                    path,
546                    e
547                );
548                let corrupt_path = path.with_extension("toml.corrupt");
549                let _ = fs::rename(&path, &corrupt_path);
550                let defaults = Self {
551                    config_file: Some(path),
552                    ..Self::default()
553                };
554                defaults.save_to_disk()?;
555                Ok(defaults)
556            }
557        }
558    }
559
560    /// Fills in defaults from `default_keybindings()` that are absent in the
561    /// loaded config: actions with no binding at all, plus default combos
562    /// added in newer versions (e.g. Ctrl-B for the drawer toggle) — as long
563    /// as the combo is not already bound to *any* action. Existing
564    /// user-customised bindings are never overwritten.
565    fn merge_missing_default_bindings(&mut self) {
566        let defaults = default_keybindings().to_hashmap();
567        let mut current = self.key_bindings.to_hashmap();
568        let mut bound: std::collections::HashSet<_> = current.values().flatten().cloned().collect();
569        for (action, combos) in defaults {
570            match current.entry(action) {
571                std::collections::hash_map::Entry::Vacant(e) => {
572                    // Never steal a combo the user has bound to something
573                    // else — insert only the free ones, and claim them so a
574                    // later default in this pass cannot double-bind.
575                    let free: Vec<_> = combos.into_iter().filter(|c| !bound.contains(c)).collect();
576                    if !free.is_empty() {
577                        bound.extend(free.iter().copied());
578                        e.insert(free);
579                    }
580                }
581                std::collections::hash_map::Entry::Occupied(mut e) => {
582                    for combo in combos {
583                        if !bound.contains(&combo) && !e.get().contains(&combo) {
584                            bound.insert(combo);
585                            e.get_mut().push(combo);
586                        }
587                    }
588                }
589            }
590        }
591        self.key_bindings = KeyBindings::from_hashmap(current);
592    }
593
594    // We set a new workspace to work with, remember to save the data
595    // to persist it in disk
596    pub fn set_workspace(&mut self, workspace_path: &PathBuf) {
597        if let Some(current_workspace_dir) = &self.workspace_dir
598            && workspace_path != current_workspace_dir
599        {
600            self.needs_indexing = true;
601        }
602
603        self.workspace_dir = Some(workspace_path.to_owned());
604    }
605
606    /// Removes the active workspace path so the user is prompted to choose a new one.
607    /// Handles both Phase 1 (workspace_dir) and Phase 2 (workspace_config) config formats.
608    ///
609    /// For Phase 2: only the currently active workspace entry is removed; other workspace
610    /// entries in the config are preserved. After this call, `workspace_config` remains
611    /// `Some` but `get_current_workspace()` returns `None`.
612    pub fn clear_workspace(&mut self) {
613        // Phase 1
614        if self.workspace_dir.is_some() {
615            self.workspace_dir = None;
616            self.needs_indexing = true;
617        }
618        // Phase 2
619        if let Some(wc) = &mut self.workspace_config {
620            let key = wc.global.current_workspace.clone();
621            if !key.is_empty() {
622                wc.workspaces.remove(&key);
623            }
624            wc.global.current_workspace = String::new();
625        }
626    }
627
628    /// Resolve the active workspace path from Phase 2 (workspace_config) or
629    /// Phase 1 (workspace_dir). Returns `None` if no workspace is configured.
630    pub fn resolve_workspace_path(&self) -> Option<PathBuf> {
631        self.workspace_config
632            .as_ref()
633            .and_then(|wc| wc.get_current_workspace())
634            .map(|entry| entry.effective_path().clone())
635            .or_else(|| self.workspace_dir.clone())
636    }
637
638    /// Resolve `~` and relative paths in workspace entries.
639    /// Relative paths are resolved against `base` (typically the config file's
640    /// parent directory). Called once after deserialization.
641    fn resolve_paths(&mut self, base: &std::path::Path) {
642        // Legacy workspace_dir — resolve in place (it's a legacy field that
643        // gets consumed by migration anyway).
644        if let Some(ref mut p) = self.workspace_dir {
645            *p = Self::expand_path(p, base);
646        }
647        // Phase 2 workspace entries — populate resolved_path, keep original path intact.
648        if let Some(ref mut wc) = self.workspace_config {
649            for entry in wc.workspaces.values_mut() {
650                let resolved = Self::expand_path(&entry.path, base);
651                if resolved != entry.path {
652                    entry.resolved_path = Some(resolved);
653                }
654            }
655        }
656        self.cache_dir_resolved = Some(Self::expand_path(&self.cache_dir, base));
657        self.history_dir_resolved = Some(Self::expand_path(&self.history_dir, base));
658    }
659
660    /// Expand `~` to the home directory and resolve relative paths against `base`.
661    /// Returns an absolute path. If the resolved path exists on disk, it is
662    /// canonicalized to remove `.` and `..` components.
663    fn expand_path(path: &std::path::Path, base: &std::path::Path) -> PathBuf {
664        let s = path.to_string_lossy();
665        let expanded = if s.starts_with("~/") || s == "~" {
666            if let Ok(home) = config_dir::get_home_dir() {
667                home.join(s.strip_prefix("~/").unwrap_or(""))
668            } else {
669                path.to_path_buf()
670            }
671        } else {
672            path.to_path_buf()
673        };
674        let absolute = if expanded.is_relative() {
675            base.join(expanded)
676        } else {
677            expanded
678        };
679        // Canonicalize if the path exists, otherwise return as-is.
680        absolute.canonicalize().unwrap_or(absolute)
681    }
682
683    pub fn set_theme(&mut self, theme: String) {
684        self.theme = theme;
685    }
686
687    pub fn report_indexed(&mut self) {
688        self.needs_indexing = false;
689    }
690
691    pub fn needs_indexing(&self) -> bool {
692        self.needs_indexing
693    }
694
695    pub fn add_path_history(&mut self, note_path: &VaultPath) {
696        if !note_path.is_note() {
697            return;
698        }
699        let Some(workspace_name) = self.current_workspace_name() else {
700            return;
701        };
702        let file_path = self.history_path_for(&workspace_name);
703        if let Err(e) = history::push_history(&file_path, note_path) {
704            tracing::warn!("failed to write history {:?}: {}", file_path, e);
705        }
706    }
707
708    pub fn current_workspace_name(&self) -> Option<String> {
709        self.workspace_config
710            .as_ref()
711            .map(|wc| wc.global.current_workspace.clone())
712            .filter(|s| !s.is_empty())
713    }
714
715    pub fn cache_dir_resolved(&self) -> Option<&Path> {
716        self.cache_dir_resolved.as_deref()
717    }
718
719    pub fn history_dir_resolved(&self) -> Option<&Path> {
720        self.history_dir_resolved.as_deref()
721    }
722
723    /// Path to the SQLite cache file for the named workspace.
724    /// Caller must have already validated `workspace_name` via
725    /// `kimun_core::nfs::filename::validate_filename`.
726    pub fn cache_path_for(&self, workspace_name: &str) -> PathBuf {
727        Self::workspace_file(
728            self.cache_dir_resolved.as_ref().unwrap_or(&self.cache_dir),
729            workspace_name,
730            CACHE_FILE_EXT,
731        )
732    }
733
734    /// Path to the history file for the named workspace.
735    /// Caller must have already validated `workspace_name`.
736    pub fn history_path_for(&self, workspace_name: &str) -> PathBuf {
737        Self::workspace_file(
738            self.history_dir_resolved
739                .as_ref()
740                .unwrap_or(&self.history_dir),
741            workspace_name,
742            HISTORY_FILE_EXT,
743        )
744    }
745
746    fn workspace_file(dir: &Path, workspace_name: &str, ext: &str) -> PathBuf {
747        dir.join(format!("{workspace_name}.{ext}"))
748    }
749
750    /// Returns the last-visited paths for the current workspace.
751    pub fn current_last_paths(&self) -> Vec<VaultPath> {
752        let Some(name) = self.current_workspace_name() else {
753            return Vec::new();
754        };
755        let file_path = self.history_path_for(&name);
756        history::load_history(&file_path)
757    }
758
759    /// Build the icon set for the current `use_nerd_fonts` setting.
760    pub fn icons(&self) -> icons::Icons {
761        icons::Icons::new(self.use_nerd_fonts)
762    }
763
764    /// Resolve the active theme by name, falling back to the default.
765    ///
766    /// The resolved theme is adapted to the terminal's color depth (truecolor
767    /// themes are quantized on 256-color terminals and mapped to role-semantic
768    /// ANSI slots on 16-color terminals).
769    pub fn get_theme(&self) -> Theme {
770        let theme = if self.theme.is_empty() {
771            Theme::default()
772        } else {
773            self.theme_list()
774                .into_iter()
775                .find(|t| t.name == self.theme)
776                .unwrap_or_default()
777        };
778        theme.adapt_to_terminal()
779    }
780}
781
782#[cfg(test)]
783#[allow(clippy::field_reassign_with_default)]
784mod tests {
785    use super::*;
786
787    #[test]
788    fn load_theme_from_nonexistent_path_returns_err_without_creating_file() {
789        // RED: fails to compile because load_theme_from_path doesn't exist.
790        // GREEN: method exists, returns Err, and does NOT create the file.
791        let path = std::env::temp_dir().join("kimun_tdd_test_theme_absent.toml");
792        let _ = std::fs::remove_file(&path); // ensure clean state
793
794        let result = AppSettings::load_theme_from_path(&path);
795
796        assert!(result.is_err(), "should return Err when file is absent");
797        assert!(!path.exists(), "must not create the file as a side effect");
798    }
799
800    #[test]
801    fn load_theme_from_corrupt_path_returns_err_without_recreating_file() {
802        // After a corrupt file is removed, no replacement must be written.
803        let path = std::env::temp_dir().join("kimun_tdd_test_theme_corrupt.toml");
804        std::fs::write(&path, b"not valid toml {{{{").unwrap();
805
806        let result = AppSettings::load_theme_from_path(&path);
807
808        assert!(result.is_err(), "should return Err for corrupt TOML");
809        // The user's file must SURVIVE a parse error (a typo must never
810        // delete a hand-authored theme).
811        assert!(path.exists(), "corrupt theme file must not be deleted");
812        std::fs::remove_file(&path).ok();
813    }
814
815    #[test]
816    fn default_keybindings_quit_matches_canonical_combo() {
817        let kb = default_keybindings();
818        let combo = crate::keys::default_quit_combo();
819        assert_eq!(
820            kb.get_action(&combo),
821            Some(ActionShortcuts::Quit),
822            "default_keybindings() must bind default_quit_combo() to Quit so the \
823             deserialize safety net can recover an unreachable app"
824        );
825    }
826
827    #[test]
828    fn autosave_interval_defaults_to_five() {
829        let settings = AppSettings::default();
830        assert_eq!(settings.autosave_interval_secs, 5);
831    }
832
833    #[test]
834    fn autosave_interval_deserializes_from_toml() {
835        let toml = "autosave_interval_secs = 30\n";
836        let settings: AppSettings = toml::from_str(toml).unwrap();
837        assert_eq!(settings.autosave_interval_secs, 30);
838    }
839
840    #[test]
841    fn autosave_interval_defaults_when_missing_from_toml() {
842        let toml = ""; // no autosave_interval_secs key
843        let settings: AppSettings = toml::from_str(toml).unwrap();
844        assert_eq!(settings.autosave_interval_secs, 5);
845    }
846
847    /// Verify the full load path: TOML with FileOperations = ["F2"] → keybinding lookup.
848    #[test]
849    fn f2_file_operations_survives_toml_deserialize() {
850        use crate::keys::key_combo::{KeyCombo, KeyModifiers};
851        use crate::keys::key_strike::KeyStrike;
852
853        let toml = r#"
854[key_bindings]
855FileOperations = ["F2"]
856"#;
857        let settings: AppSettings = toml::from_str(toml).unwrap();
858        let f2 = KeyCombo::new(KeyModifiers::default(), KeyStrike::F2);
859        let action = settings.key_bindings.get_action(&f2);
860        assert_eq!(
861            action,
862            Some(ActionShortcuts::FileOperations),
863            "F2 should survive deserialization and map to FileOperations"
864        );
865    }
866
867    /// Verify merge_missing_default_bindings adds F2 when absent from config.
868    #[test]
869    fn merge_adds_f2_when_absent() {
870        use crate::keys::key_combo::{KeyCombo, KeyModifiers};
871        use crate::keys::key_strike::KeyStrike;
872
873        // Settings with no FileOperations binding
874        let toml = r#"
875[key_bindings]
876Quit = ["ctrl&Q"]
877"#;
878        let mut settings: AppSettings = toml::from_str(toml).unwrap();
879        settings.merge_missing_default_bindings();
880
881        let f2 = KeyCombo::new(KeyModifiers::default(), KeyStrike::F2);
882        let action = settings.key_bindings.get_action(&f2);
883        assert_eq!(
884            action,
885            Some(ActionShortcuts::FileOperations),
886            "merge_missing_default_bindings should add F2 → FileOperations"
887        );
888    }
889
890    #[test]
891    fn clear_workspace_phase1_clears_workspace_dir() {
892        let mut settings = AppSettings::default();
893        settings.workspace_dir = Some(PathBuf::from("/tmp/vault"));
894        settings.needs_indexing = false;
895        settings.clear_workspace();
896        assert!(
897            settings.workspace_dir.is_none(),
898            "workspace_dir should be None"
899        );
900        assert!(
901            settings.needs_indexing,
902            "needs_indexing should be reset to true"
903        );
904    }
905
906    #[test]
907    fn clear_workspace_phase2_removes_current_workspace_entry() {
908        let mut settings = AppSettings::default();
909        let mut wc = WorkspaceConfig::new_empty();
910        wc.add_workspace("vault1".to_string(), PathBuf::from("/tmp/vault1"))
911            .unwrap();
912        settings.workspace_config = Some(wc);
913        // Assert precondition: add_workspace auto-selects the first workspace
914        assert_eq!(
915            settings
916                .workspace_config
917                .as_ref()
918                .unwrap()
919                .global
920                .current_workspace,
921            "vault1"
922        );
923        settings.clear_workspace();
924        let wc = settings.workspace_config.as_ref().unwrap();
925        assert!(
926            wc.workspaces.is_empty(),
927            "workspace entry should be removed"
928        );
929        assert!(
930            wc.global.current_workspace.is_empty(),
931            "current_workspace should be empty"
932        );
933    }
934
935    #[test]
936    fn clear_workspace_both_phases_active() {
937        // When Phase 1 and Phase 2 fields are both populated (e.g. during migration),
938        // clear_workspace must clear both independently.
939        let mut settings = AppSettings::default();
940        settings.workspace_dir = Some(PathBuf::from("/tmp/vault"));
941        let mut wc = WorkspaceConfig::new_empty();
942        wc.add_workspace("vault1".to_string(), PathBuf::from("/tmp/vault1"))
943            .unwrap();
944        settings.workspace_config = Some(wc);
945        settings.clear_workspace();
946        assert!(
947            settings.workspace_dir.is_none(),
948            "phase1 workspace_dir should be cleared"
949        );
950        let wc = settings.workspace_config.as_ref().unwrap();
951        assert!(
952            wc.workspaces.is_empty(),
953            "phase2 workspace entry should be removed"
954        );
955        assert!(
956            wc.global.current_workspace.is_empty(),
957            "phase2 current_workspace should be empty"
958        );
959    }
960
961    #[test]
962    fn clear_workspace_phase2_preserves_other_workspaces() {
963        let mut settings = AppSettings::default();
964        let mut wc = WorkspaceConfig::new_empty();
965        wc.add_workspace("vault1".to_string(), PathBuf::from("/tmp/vault1"))
966            .unwrap();
967        wc.add_workspace("vault2".to_string(), PathBuf::from("/tmp/vault2"))
968            .unwrap();
969        wc.global.current_workspace = "vault1".to_string();
970        settings.workspace_config = Some(wc);
971        settings.clear_workspace();
972        let wc = settings.workspace_config.as_ref().unwrap();
973        assert!(
974            !wc.workspaces.contains_key("vault1"),
975            "active workspace should be removed"
976        );
977        assert!(
978            wc.workspaces.contains_key("vault2"),
979            "other workspaces should be preserved"
980        );
981        assert!(
982            wc.global.current_workspace.is_empty(),
983            "current_workspace should be empty"
984        );
985    }
986}
987
988#[cfg(test)]
989mod backend_tests {
990    use super::*;
991
992    #[test]
993    fn default_backend_is_textarea() {
994        let settings = AppSettings::default();
995        assert!(matches!(
996            settings.editor_backend,
997            EditorBackendSetting::Textarea
998        ));
999    }
1000
1001    #[test]
1002    fn nvim_backend_round_trips_toml() {
1003        let toml = "editor_backend = \"nvim\"\n";
1004        let parsed: AppSettings = toml::from_str(toml).unwrap();
1005        assert!(matches!(parsed.editor_backend, EditorBackendSetting::Nvim));
1006    }
1007
1008    #[test]
1009    fn editor_backend_vim_roundtrips_through_toml() {
1010        #[derive(serde::Serialize, serde::Deserialize)]
1011        struct W {
1012            editor_backend: EditorBackendSetting,
1013        }
1014        let w = W {
1015            editor_backend: EditorBackendSetting::Vim,
1016        };
1017        let s = toml::to_string(&w).unwrap();
1018        assert!(s.contains("editor_backend = \"vim\""), "serialized: {s}");
1019        let back: W = toml::from_str(&s).unwrap();
1020        assert_eq!(back.editor_backend, EditorBackendSetting::Vim);
1021    }
1022
1023    // ── expand_path tests ──────────────────────────────────────────────
1024
1025    #[test]
1026    fn expand_path_absolute_unchanged() {
1027        let base = PathBuf::from("/config/dir");
1028        let result = AppSettings::expand_path(std::path::Path::new("/absolute/path/notes"), &base);
1029        assert!(result.is_absolute());
1030        assert!(result.to_string_lossy().contains("absolute"));
1031    }
1032
1033    #[test]
1034    fn expand_path_relative_resolved_against_base() {
1035        let base = tempfile::TempDir::new().unwrap();
1036        let notes = base.path().join("notes");
1037        std::fs::create_dir_all(&notes).unwrap();
1038
1039        let result = AppSettings::expand_path(std::path::Path::new("notes"), base.path());
1040        assert!(result.is_absolute());
1041        assert_eq!(result, notes.canonicalize().unwrap());
1042    }
1043
1044    #[test]
1045    fn expand_path_relative_with_dotdot() {
1046        let base = tempfile::TempDir::new().unwrap();
1047        let sibling = base.path().join("sibling");
1048        std::fs::create_dir_all(&sibling).unwrap();
1049        let sub = base.path().join("sub");
1050        std::fs::create_dir_all(&sub).unwrap();
1051
1052        let result = AppSettings::expand_path(std::path::Path::new("../sibling"), &sub);
1053        assert!(result.is_absolute());
1054        assert_eq!(result, sibling.canonicalize().unwrap());
1055    }
1056
1057    #[test]
1058    fn expand_path_nonexistent_relative_still_absolute() {
1059        let base = PathBuf::from("/some/config/dir");
1060        let result = AppSettings::expand_path(std::path::Path::new("my-notes"), &base);
1061        assert!(result.is_absolute());
1062        assert_eq!(result, PathBuf::from("/some/config/dir/my-notes"));
1063    }
1064
1065    #[test]
1066    #[cfg(unix)]
1067    fn expand_path_tilde_uses_home_unix() {
1068        let home = std::env::var("HOME").expect("HOME must be set on Unix");
1069        let base = PathBuf::from("/irrelevant");
1070        let result = AppSettings::expand_path(std::path::Path::new("~/Documents/notes"), &base);
1071        assert!(result.is_absolute());
1072        assert!(
1073            result.starts_with(&home),
1074            "expected path to start with HOME={}, got {:?}",
1075            home,
1076            result
1077        );
1078        assert!(result.to_string_lossy().contains("Documents/notes"));
1079    }
1080
1081    #[test]
1082    #[cfg(unix)]
1083    fn expand_path_tilde_alone_is_home_unix() {
1084        let home = std::env::var("HOME").expect("HOME must be set on Unix");
1085        let base = PathBuf::from("/irrelevant");
1086        let result = AppSettings::expand_path(std::path::Path::new("~"), &base);
1087        assert!(result.is_absolute());
1088        // canonicalize may resolve symlinks, so compare canonicalized forms
1089        let expected = PathBuf::from(&home)
1090            .canonicalize()
1091            .unwrap_or(PathBuf::from(&home));
1092        assert_eq!(result, expected);
1093    }
1094
1095    #[test]
1096    #[cfg(windows)]
1097    fn expand_path_tilde_uses_userprofile_windows() {
1098        let home = std::env::var("USERPROFILE").expect("USERPROFILE must be set on Windows");
1099        let base = PathBuf::from("C:\\irrelevant");
1100        let result = AppSettings::expand_path(std::path::Path::new("~/Documents/notes"), &base);
1101        assert!(result.is_absolute());
1102        assert!(
1103            result.starts_with(&home),
1104            "expected path to start with USERPROFILE={}, got {:?}",
1105            home,
1106            result
1107        );
1108    }
1109
1110    #[test]
1111    fn resolve_paths_populates_resolved_path() {
1112        let base = tempfile::TempDir::new().unwrap();
1113        let notes = base.path().join("notes");
1114        std::fs::create_dir_all(&notes).unwrap();
1115
1116        let toml = r#"
1117config_version = 2
1118[global]
1119current_workspace = "test"
1120[workspaces.test]
1121path = "notes"
1122last_paths = []
1123created = "2026-01-01T00:00:00Z"
1124"#
1125        .to_string();
1126        let mut settings: AppSettings = toml::from_str(&toml).unwrap();
1127        settings.resolve_paths(base.path());
1128
1129        let wc = settings.workspace_config.as_ref().unwrap();
1130        let entry = wc.workspaces.get("test").unwrap();
1131        // Original path preserved
1132        assert_eq!(entry.path, PathBuf::from("notes"));
1133        // Resolved path is absolute
1134        assert!(entry.resolved_path.is_some());
1135        assert!(entry.effective_path().is_absolute());
1136    }
1137
1138    #[test]
1139    fn resolve_paths_absolute_no_resolved_path() {
1140        let toml = r#"
1141config_version = 2
1142[global]
1143current_workspace = "test"
1144[workspaces.test]
1145path = "/absolute/notes"
1146last_paths = []
1147created = "2026-01-01T00:00:00Z"
1148"#;
1149        let mut settings: AppSettings = toml::from_str(toml).unwrap();
1150        settings.resolve_paths(std::path::Path::new("/config"));
1151
1152        let wc = settings.workspace_config.as_ref().unwrap();
1153        let entry = wc.workspaces.get("test").unwrap();
1154        // No resolved_path needed for already-absolute paths
1155        assert!(entry.resolved_path.is_none());
1156        assert_eq!(*entry.effective_path(), PathBuf::from("/absolute/notes"));
1157    }
1158}
1159
1160#[cfg(test)]
1161mod sort_settings_tests {
1162    use super::*;
1163
1164    #[test]
1165    fn group_directories_defaults_off() {
1166        let s = AppSettings::default();
1167        assert!(!s.group_directories);
1168    }
1169
1170    #[test]
1171    fn open_sort_dialog_is_bound_by_default() {
1172        let s = AppSettings::default();
1173        let map = s.key_bindings.to_hashmap();
1174        assert!(
1175            map.contains_key(&ActionShortcuts::OpenSortDialog),
1176            "OpenSortDialog must have a default binding"
1177        );
1178    }
1179}