Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

146 KB
Raw Blame
//! Persistent user settings (%APPDATA%\rustyfiles\settings.toml) as a GPUI global.

use std::path::PathBuf;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU8, Ordering};

use gpui_kit::*;
use serde::{Deserialize, Serialize};

use crate::i18n::Lang;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ThemePref {
    #[default]
    System,
    Light,
    Dark,
    /// Pure black for OLED screens: black surfaces, white text, no see-through material (issue 45: "A true black background
    /// (#000000). Pure white text (#FFFFFF)").
    Black,
}

/// Generic file icons: the shell's current pictures or a freedesktop pack in `icon-themes/`.
/// Old settings have no key and stay on `Windows`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum IconThemePref {
    #[default]
    Windows,
    Freedesktop,
    /// Value written by the discarded local XP build. Kept so that settings file still loads; behaves like `Windows`.
    #[serde(other)]
    Legacy,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum DefaultView {
    Details,
    Grid,
    Columns,
    /// The List view (names in columns, filled top to bottom; issue 465).
    List,
    /// The Cards view (wide tiles with type and size beside the picture; issue 893).
    Cards,
    /// Picks per folder, like Explorer's folder types: mostly pictures/videos → grid, Pictures
    /// and Videos → grid, Downloads → newest first in date groups, otherwise details.
    #[default]
    Adaptive,
}

/// Checking copies after they are written (our engine).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum CopyVerify {
    #[default]
    Off,
    /// Size and modification time.
    Quick,
    /// Every byte, read back from the disk.
    Full,
}

impl CopyVerify {
    pub fn engine(self) -> rf_win::fastcopy::Verify {
        match self {
            CopyVerify::Off => rf_win::fastcopy::Verify::Off,
            CopyVerify::Quick => rf_win::fastcopy::Verify::Quick,
            CopyVerify::Full => rf_win::fastcopy::Verify::Full,
        }
    }
}

/// Where the progress of a running copy, move or delete is shown besides the Status Center
/// (whose button always has a progress ring).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum TransferProgress {
    /// A strip in the status bar of every window.
    #[default]
    StatusBar,
    /// A card at the bottom right corner of the window's content.
    #[serde(rename = "card")]
    FloatingCard,
    /// Only in the Status Center (how it was before).
    #[serde(rename = "statuscenter")]
    StatusCenter,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum DatePref {
    /// "5 dakika önce" for recent items.
    #[default]
    Application,
    System,
    Universal,
}

/// A window's tabs saved under a name, to open again later in a window of their own (issue 41: "a feature to save or load sessions
/// (similar to the Lister feature in Directory Opus)"). Written as the last session is: `session_tabs`, `session_panes`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct NamedSession {
    pub name: String,
    pub tabs: Vec<String>,
    pub panes: Vec<SessionPane>,
    pub active: usize,
}

/// The second pane of a tab in the saved session (issue 20: a window split in two came back with one pane, at the left pane's
/// folder; only the left pane of each tab was written).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SessionPane {
    /// The tab it belongs to: an index into `session_tabs`.
    pub tab: usize,
    /// Where it was, written the way a tab of `session_tabs` is ("" = Home).
    pub location: String,
    /// It was the pane with the focus (the toolbar, the sidebar and the status bar acted on it).
    pub active: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum StartupPref {
    /// Reopen last session's tabs.
    #[default]
    Continue,
    /// One Home tab.
    NewTab,
    /// The folders in `startup_pages`.
    Pages,
}

/// Settings → Appearance → Animations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum AnimPref {
    /// Follow Windows (Settings → Accessibility → Visual effects → Animation effects).
    #[default]
    System,
    On,
    Off,
}

/// Settings -> Dock: how much the dock's icons grow under the pointer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum DockMagnify {
    /// They stay as they are.
    Off,
    /// The icon under the pointer grows to 1.25 times.
    Subtle,
    /// To 1.55 times, like the Mac's dock.
    #[default]
    Full,
}

impl DockMagnify {
    /// What the dock's magnification takes.
    pub fn strength(self) -> rf_win::dock::magnify::Strength {
        use rf_win::dock::magnify::Strength;
        match self {
            DockMagnify::Off => Strength::Off,
            DockMagnify::Subtle => Strength::Subtle,
            DockMagnify::Full => Strength::Full,
        }
    }
}

/// Settings -> Dock: the left island's search, as Windows 11's taskbar offers it (issue 41: "Add an option to show/hide search bar
/// on taskbar"). `Icon` is the button a narrow secondary monitor already gets; `Hidden` leaves the Start logo (and, on the primary
/// monitor, the weather).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum DockSearch {
    #[default]
    Field,
    Icon,
    Hidden,
}

/// The edge on which the dock is placed. Older settings keep the bottom dock.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum DockPosition {
    #[default]
    Bottom,
    Right,
}

impl DockPosition {
    pub fn edge(self) -> rf_win::dock::layout::DockEdge {
        match self {
            Self::Bottom => rf_win::dock::layout::DockEdge::Bottom,
            Self::Right => rf_win::dock::layout::DockEdge::Right,
        }
    }
}

/// Settings -> Dock: which dock shows which running app when there is a dock on every monitor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum DockAppsWhere {
    /// Every dock shows the pinned apps and every running app.
    #[default]
    All,
    /// The pins are on every dock; a running app that is not pinned is only on the dock of the monitor its window is on, and a pinned
    /// app's running mark only there.
    Window,
}

impl DockAppsWhere {
    /// The rule `rf_win::dock::monitors` works with.
    pub fn rule(self) -> rf_win::dock::monitors::AppsWhere {
        match self {
            DockAppsWhere::All => rf_win::dock::monitors::AppsWhere::Everywhere,
            DockAppsWhere::Window => rf_win::dock::monitors::AppsWhere::WindowMonitor,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum BackdropPref {
    /// Default, like Explorer: a quiet desktop tint.
    #[default]
    Mica,
    /// Files' default: a more colorful variant of Mica.
    MicaAlt,
    Acrylic,
    Solid,
    /// Experimental: the screen behind the window, bent and frosted like glass (rf_win::glass).
    /// An older version does not know this value and reads the field as the default (Mica);
    /// the other settings are kept (see `parse_lenient`).
    Glass,
}

/// The material for the app's popup menus. Colors come from the theme.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum MenuMaterial {
    #[default]
    #[serde(alias = "auto")]
    Automatic,
    Mica,
    Solid,
    MicaAlt,
    Acrylic,
    Glass,
}

/// The size of the command bar's pictures (issue 248).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ToolbarIconSize {
    Small,
    #[default]
    Medium,
    Large,
}

impl MenuMaterial {
    /// For the popups that are not menus (the View flyout, the Status Center: issue 380, they did not follow the setting): what a
    /// popup that would draw `auto_liquid` glass, and an opaque card in the Explorer look (`explorer`), gets with this material.
    /// Automatic keeps each one as it was (`None`); another choice gives (glass, backdrop, opaque card).
    pub fn for_panel(self, auto_liquid: bool, explorer: bool, materials: bool, glass: bool) -> Option<(bool, WindowBackgroundAppearance, bool)> {
        if self == Self::Automatic {
            return None;
        }
        let (liquid, bg) = self.resolve(auto_liquid, explorer, materials, glass);
        Some((liquid, bg, bg == WindowBackgroundAppearance::Opaque))
    }

    /// Whether to draw HyperGlass and what backdrop the popup requests before OS fallback.
    pub fn resolve(self, auto_liquid: bool, auto_opaque: bool, materials: bool, glass: bool) -> (bool, WindowBackgroundAppearance) {
        use WindowBackgroundAppearance::{Blurred, MicaAltBackdrop, MicaBackdrop, Opaque, Transparent};
        match self {
            Self::Automatic if auto_opaque => (false, Opaque),
            Self::Automatic if auto_liquid => (true, Transparent),
            // Keep the legacy popup fill on systems that fall back from Acrylic.
            Self::Automatic => (false, Blurred),
            Self::Mica if materials => (false, MicaBackdrop),
            Self::MicaAlt if materials => (false, MicaAltBackdrop),
            Self::Acrylic if materials => (false, Blurred),
            Self::Glass if glass => (true, Transparent),
            _ => (false, Opaque),
        }
    }
}

/// Hızlı Bakış penceresinin arka planı.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum LookBackdrop {
    #[default]
    Mica,
    Acrylic,
    Tabbed,
    /// Düz renk (tema rengi ya da `look_backdrop_color`).
    None,
}

/// Hızlı Bakış resim görüntüleyicisinin zemini.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum LookImageTheme {
    #[default]
    Dark,
    Light,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum DeletePref {
    Always,
    /// Only for permanent deletes (the Recycle Bin can undo the rest) — Explorer's behaviour.
    #[default]
    PermanentOnly,
    Never,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ClickPref {
    #[default]
    Never,
    Folders,
    Always,
}

/// Settings › Files & folders › "Windows' icons while pictures load": which items show Windows' icon for their type (a folder's, a
/// file type's, a custom one) until their own picture comes, and in the preview pane when they have none (issue 695).
///
/// Backwards-compatible with the original boolean setting: `false` loads as [`Self::Off`] and `true` loads as [`Self::All`], and those
/// two save back as booleans so older builds keep reading the file unchanged.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PlaceholderIconsPref {
    #[default]
    Off,
    Folders,
    Files,
    All,
}

impl PlaceholderIconsPref {
    /// Whether an item (`is_dir`: folder vs file/image) uses Windows' icon while its own picture loads.
    pub fn applies(self, is_dir: bool) -> bool {
        match self {
            Self::Off => false,
            Self::Folders => is_dir,
            Self::Files => !is_dir,
            Self::All => true,
        }
    }

    pub fn as_u8(self) -> u8 {
        match self {
            Self::Off => 0,
            Self::Folders => 1,
            Self::Files => 2,
            Self::All => 3,
        }
    }

    pub fn from_u8(v: u8) -> Self {
        match v {
            1 => Self::Folders,
            2 => Self::Files,
            3 => Self::All,
            _ => Self::Off,
        }
    }
}

impl Serialize for PlaceholderIconsPref {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Off => serializer.serialize_bool(false),
            Self::Folders => serializer.serialize_str("folders"),
            Self::Files => serializer.serialize_str("files"),
            Self::All => serializer.serialize_bool(true),
        }
    }
}

impl<'de> Deserialize<'de> for PlaceholderIconsPref {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct Visitor;
        impl serde::de::Visitor<'_> for Visitor {
            type Value = PlaceholderIconsPref;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a boolean or one of \"off\", \"folders\", \"files\", \"all\"")
            }

            fn visit_bool<E: serde::de::Error>(self, v: bool) -> Result<Self::Value, E> {
                Ok(if v { PlaceholderIconsPref::All } else { PlaceholderIconsPref::Off })
            }

            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
                match v.trim().to_ascii_lowercase().as_str() {
                    "off" | "none" | "never" | "false" => Ok(PlaceholderIconsPref::Off),
                    "folders" | "folder" => Ok(PlaceholderIconsPref::Folders),
                    "files" | "file" => Ok(PlaceholderIconsPref::Files),
                    "all" | "both" | "always" | "true" => Ok(PlaceholderIconsPref::All),
                    _ => Err(E::invalid_value(serde::de::Unexpected::Str(v), &self)),
                }
            }
        }
        deserializer.deserialize_any(Visitor)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum IdePref {
    #[default]
    GitRepos,
    Always,
    Never,
}

/// Which of our own entries the context menu shows (Settings → General → Context menu).
/// Where an archive opens when it is opened like a folder.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ArchiveOpen {
    /// In the same tab, as a folder does.
    #[default]
    Here,
    NewTab,
    NewWindow,
}

/// What a drag without Ctrl or Shift does to files (issue 466).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum PlainDrag {
    /// As Windows does: a move on the same drive, a copy to another.
    #[default]
    Auto,
    Move,
    Copy,
}

/// What a click on "Çıkar" itself does (Discord, 2026-11-29, after hearing that a click on Compress compresses at once: "It'd also be
/// cool to do the same with the Extract option").
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum QuickExtract {
    /// A click only opens the submenu.
    Menu,
    /// Into a new folder named after the archive ("Klasöre çıkar").
    #[default]
    Named,
    /// Its own folder when everything is under one folder, else a new one ("Akıllı çıkar").
    Smart,
    /// Into the archive's own folder ("Buraya çıkar").
    Here,
}

/// The format a click on "Sıkıştır" compresses in (Discord, 2026-11-20: "a default zipping method setting in settings").
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum QuickCompress {
    /// A click only opens the submenu, as before.
    Menu,
    #[default]
    Zip,
    SevenZ,
    TarZst,
    TarGz,
    Tar,
    /// WinRAR's format, through its Rar.exe (only when WinRAR is installed).
    Rar,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct MenuPrefs {
    pub open_in_new_tab: bool,
    /// Show "Open in new tab in background": a tab that opens without switching to it, whatever the
    /// "always switch to a new tab" setting says. Off by default: while it is shown, "Open in new tab" becomes a row of its own.
    pub open_in_background_tab: bool,
    pub open_in_new_window: bool,
    pub copy_path: bool,
    pub create_shortcut: bool,
    pub pin: bool,
    pub compress: bool,
    /// "Dönüştür": pictures into another format, next to the originals (the converter).
    pub convert: bool,
    pub tags: bool,
    /// "Seç": select all, none, invert (Discord, 2026-11-29: "a new context sub menu that gives you options to quickly select/de-select
    /// items without having to rely on keyboard shortcuts").
    pub select: bool,
    pub shelf: bool,
    pub terminal: bool,
    /// Explorer's "Send to" (the SendTo folder's entries and the drives) in the first menu. Issue 117.
    pub send_to: bool,
    /// "Yazdır" in the first menu for files Windows can print (issue 1125: "a print shop"). Off by default: it is otherwise under
    /// "Show more options", and most people print from the program.
    pub print: bool,
    /// Shell extensions under "Show more options" (off = listed at the bottom of the menu).
    pub shell_submenu: bool,
    /// A program that puts the same command into Windows 11's new menu and into the classic one (NanaZip does) is listed once: with
    /// this on the classic entry is the one kept, else the new one, as Windows' own first menu shows it. A user on Discord,
    /// 2026-11-24: "Only one item should be present, and we need a switch to select the preference (classic vs. modern)".
    pub prefer_classic_commands: bool,
    /// A right click opens Windows' classic menu (the one Shift+right-click gives) instead of ours: for those who set Windows 11 to
    /// the classic menu everywhere (Discord, 2026-11-29).
    pub always_classic: bool,
    /// A right click on Home's recent items opens rustyfiles' own menu, as on any file, instead of Windows' (issue 594).
    pub home_recent_own_menu: bool,
    /// An item's menu is built in the background once the pointer rests on it, so that a right click on it opens at once (the
    /// shell's handlers then run for items never right-clicked too).
    pub prepare_on_hover: bool,
    /// Show the "Open" item in the context menu.
    pub open: bool,
    /// Show the "Properties" item in the context menu.
    pub properties: bool,
    /// Show the "Refresh" item in the context menu.
    pub refresh: bool,
    /// Show the "Show hidden items" item in the context menu.
    pub show_hidden: bool,
}

impl Default for MenuPrefs {
    fn default() -> Self {
        Self {
            open_in_new_tab: true,
            open_in_background_tab: false,
            open_in_new_window: true,
            copy_path: true,
            create_shortcut: true,
            pin: true,
            compress: true,
            convert: true,
            tags: true,
            select: true,
            shelf: true,
            terminal: true,
            send_to: true,
            print: false,
            shell_submenu: true,
            prefer_classic_commands: false,
            always_classic: false,
            home_recent_own_menu: false,
            prepare_on_hover: false,
            open: true,
            properties: true,
            refresh: true,
            show_hidden: true,
        }
    }
}

/// Details-view columns that can be hidden (name is always shown).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ColumnPrefs {
    /// The order of the Details columns after Name, by name (`folder_view::ColKey`), as dragged by their headers. A column it does
    /// not name stands in its default place after the named ones; empty: the default order.
    pub order: Vec<String>,
    pub modified: bool,
    pub created: bool,
    pub kind: bool,
    pub size: bool,
    /// Widths (px) of modified, created, type, size; dragged in the header.
    pub widths: [u16; 4],
    /// Files' "File tag", "Git status" and "Sync status" columns. Git shows only inside a
    /// repository, sync only in folders with cloud files.
    pub tags: bool,
    pub git: bool,
    pub sync: bool,
    /// Widths of tags, git, sync.
    pub extra_widths: [u16; 3],
    /// Files' commit columns (inside a repository): last commit message, author, date, hash.
    pub git_message: bool,
    pub git_author: bool,
    pub git_date: bool,
    pub git_hash: bool,
    pub git_widths: [u16; 4],
    /// Columns for Windows properties the user added ("Diğer sütunlar…"): `System.Media.Duration:140`
    /// (canonical name, width), in the order they show after the fixed columns. Empty = none, and
    /// then nothing of the property columns runs and the file has no such key.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub properties: Vec<String>,
    /// The Name column's width once a divider was dragged (issue 135: dividers work as in Explorer, the columns stand from the left
    /// and the room left over is at the right end). 0: the Name column takes whatever the others leave, as before any drag.
    #[serde(skip_serializing_if = "is_zero_u16")]
    pub name_width: u16,
}

fn is_hundred(v: &u16) -> bool {
    *v == 100
}

/// The base size (rem) for a text size of `percent`, within 75 % and 125 % of the usual 16 px.
pub fn rem_for(percent: u16) -> f32 {
    16.0 * f32::from(percent.clamp(75, 125)) / 100.0
}

fn is_zero_u16(v: &u16) -> bool {
    *v == 0
}

impl Default for ColumnPrefs {
    fn default() -> Self {
        Self {
            order: Vec::new(),
            modified: true,
            created: false,
            kind: true,
            size: true,
            widths: [150, 150, 150, 100],
            tags: true,
            git: true,
            sync: true,
            extra_widths: [130, 120, 150],
            git_message: false,
            git_author: false,
            git_date: false,
            git_hash: false,
            git_widths: [240, 130, 140, 90],
            properties: Vec::new(),
            name_width: 0,
        }
    }
}

/// Where the quick search's "search the web" row sends the query.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum WebSearch {
    #[default]
    Google,
    Bing,
    DuckDuckGo,
    Yandex,
}

/// The renderer mode a process runs in. The dock (a process of its own, three small windows) is kept on the graphics card when the
/// setting is Auto: under Auto a card that another program keeps busy (a video render) makes the renderer build a software device and
/// move the islands to it, which costs seconds of CPU for windows that are a few hundred pixels wide. A user who chose the software
/// renderer on purpose keeps it.
pub(crate) fn renderer_mode(pref: RendererPref, dock: bool) -> gpui_windows::hybrid::RendererMode {
    use gpui_windows::hybrid::RendererMode;
    match pref {
        RendererPref::Auto if dock => RendererMode::Gpu,
        RendererPref::Auto => RendererMode::Auto,
        RendererPref::Gpu => RendererMode::Gpu,
        RendererPref::Cpu => RendererMode::Cpu,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum RendererPref {
    #[default]
    Auto,
    Gpu,
    Cpu,
}

fn is_true(b: &bool) -> bool {
    *b
}

fn is_default_preview_height(h: &f32) -> bool {
    *h == rf_core::previewpane::BOTTOM_DEFAULT_H
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
    pub theme: ThemePref,
    /// UI language (`system` follows the Windows UI language).
    pub language: Lang,
    pub default_view: DefaultView,
    /// The size a folder without a layout of its own opens at (Discussion 730): the row size of Details and List, and the tile size
    /// of the grid, as indexes of their size steps (0 the smallest, 4 the largest).
    pub default_row_size: u8,
    pub default_grid_size: u8,
    pub show_hidden: bool,
    pub preview_open: bool,
    /// The preview pane of the Open/Save dialogs, kept apart from the main windows' (shown until it is closed once: issue 87).
    pub picker_preview_open: bool,
    /// The Open/Save dialogs' sidebar starts as the strip of icons (it opens over the list while hovered); dragged wider in a dialog,
    /// the next dialogs start with it open (issue 473: "keep the sidebar expanded while saving a file").
    pub picker_sidebar_rail: bool,
    /// The Open / Save window shows the main window's material even when it is HyperGlass or Acrylic (off: matte, so the program
    /// it opens over does not show through; a Discord request of 2026-11-30, "hyperglass theme" in the upload window).
    pub picker_see_through: bool,
    /// The Open/Save dialog's size as the user left it (logical px), as Windows' own dialogs remember theirs. Issue 89: "the size of
    /// the file selection window ... is too large for a standard 1920x1080 px laptop screen".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub picker_size: Option<[u16; 2]>,
    pub sidebar_open: bool,
    /// The sidebar as a narrow strip of icons (drag it narrow to get there).
    pub sidebar_rail: bool,
    /// Pane widths (drag the pane edge to resize).
    pub sidebar_width: f32,
    /// Width used only while the Windows File Explorer look is enabled.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub explorer_sidebar_width: Option<f32>,
    /// Sidebar sections the user turned off ("drives", "cloud", "libraries", "network", "tags").
    pub sidebar_hidden: Vec<String>,
    /// The sidebar's text size, percent of the usual like `text_percent` (87, 93, 100, 112 or 125); 0 = the same as the window's
    /// (issue 266: the sidebar denser without the rest of the window changing).
    #[serde(skip_serializing_if = "is_zero_u16")]
    pub sidebar_text_percent: u16,
    /// Thinner sidebar rows (32 → 24, 36 → 28 in the Windows File Explorer look), for more places without scrolling (issue 266).
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub sidebar_compact: bool,
    /// Folders of the user's own listed in the sidebar's Drives section after the drives (issue 408: a folder a phone is synced to,
    /// a share used every day).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub drive_places: Vec<std::path::PathBuf>,
    /// The picture chosen for such a folder (issue 408: "set an icon (or glyph) for each folder that is added to the list as a
    /// Drive"), by its key in `places::DRIVE_PLACE_ICONS`; a folder not named here has the folder's.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub drive_place_icons: Vec<(std::path::PathBuf, String)>,
    /// Sections of the Home page that are hidden: "quick", "drives", "devices", "tags",
    /// "network", "recent".
    pub home_hidden: Vec<String>,
    /// The Home page's drives are three groups, as in This PC: local disks, removable drives (USB, discs) and network drives (off: one list).
    /// A group can be hidden on its own with `home_hidden` ("drives_local", "drives_removable", "drives_network").
    pub home_split_drives: bool,
    /// "Clear" on Home's recent items: only items used after this moment are listed (Windows'
    /// own list of recent items is left alone).
    pub recent_cleared_ms: i64,
    /// The last searches run with Enter (newest first, ten at most): offered under the empty
    /// search box.
    pub search_history: Vec<String>,
    /// Buttons of the command bar that are hidden ("new", "cut", "copy", "paste", "rename",
    /// "share", "delete", "props", "filter", "sort", "view", "preview").
    pub toolbar_hidden: Vec<String>,
    /// Buttons of the command bar that are off unless asked for ("newfolder", "terminal",
    /// "hidden", "refresh").
    pub toolbar_extra: Vec<String>,
    /// The order of the command bar's left group, with "sep" for a line (`toolbar_layout`; issues 373, 248, 258). Empty: the
    /// default order.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub toolbar_order: Vec<String>,
    /// The order of the bar's right group (filter, sort, view, preview: `toolbar_layout::right_order`, issue 405). Empty: the default.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub toolbar_right_order: Vec<String>,
    /// How each command bar button is shown, "name=icon|text|both" (`toolbar_layout::Look`, issue 374). A button not named here is
    /// drawn as it always was.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub toolbar_look: Vec<String>,
    /// The size of the command bar's pictures (issue 248).
    pub toolbar_icon_size: ToolbarIconSize,
    /// The command bar's pictures are Windows' own (the Explorer look's) in the other look too (issue 382). Off.
    pub toolbar_windows_icons: bool,
    /// The command bar's pictures in the accent colour, as Files draws them (issue 413). Off.
    pub toolbar_accent_icons: bool,
    /// Windows File Explorer's pictures in the context menus without the rest of its look (issue 407). Off.
    pub menu_windows_icons: bool,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub toolbar_commands: Vec<crate::quick_commands::QuickCommand>,
    pub preview_width: f32,
    /// Where the preview pane sits: at the right of the list (the default) or under it. The key is written only for "bottom".
    #[serde(skip_serializing_if = "rf_core::previewpane::PreviewPos::is_right")]
    pub preview_position: rf_core::previewpane::PreviewPos,
    /// The Properties window's size (logical px) as the user last left it; `None`: the default size (`properties_view::DEFAULT_SIZE`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub props_size: Option<[f32; 2]>,
    /// The icon file of rustyfiles' own shortcuts (Start menu, desktop, taskbar pin); `None`: the program's own (`rf_win::app_icon`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_icon: Option<String>,
    /// The pane's height at the bottom (drag its top edge). Written only once the user has moved it.
    #[serde(skip_serializing_if = "is_default_preview_height")]
    pub preview_height: f32,
    /// The file's details under its preview (type, size, dates, location, the hash button). Asked for on the rustyfiles Discord: "Hope
    /// the Properties can have an option to hide".
    pub preview_details: bool,
    pub renderer: RendererPref,
    pub restore_session: bool,
    /// Last session's tab locations ("" = Home).
    pub session_tabs: Vec<String>,
    pub session_active: usize,
    /// The tabs of the last session that were split in two: the second pane of each (see [`SessionPane`]). A tab that is not named
    /// here had one pane.
    pub session_panes: Vec<SessionPane>,
    /// Sessions saved by name (the tab strip's menu: "Save session…", "Open session").
    pub saved_sessions: Vec<NamedSession>,
    /// User pins. `None` = the default known folders.
    pub pinned: Option<Vec<PathBuf>>,
    /// Folder aliases: `@name` in the address box (Files' folder aliases).
    pub folder_aliases: std::collections::BTreeMap<String, PathBuf>,
    /// The drives that are not listed (the sidebar, the Home page, the address bar's list of drives), as letters ("V"). A drive
    /// Explorer hides by its own policy is hidden too, without being named here (`rf_win::drives::visible_drives`).
    pub hidden_drives: Vec<String>,
    /// Cloud and WSL places taken off the sidebar one by one (their paths). Issue 141: "a way to hide a single entry in that section
    /// (right click > Hide), like "Hidden drives"".
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub hidden_places: Vec<String>,
    /// The accent colour of rustyfiles as "#RRGGBB"; empty: Windows' own accent (Settings > Appearance).
    pub accent_color: String,
    /// The user's own programs for kinds of files (Settings > File types; `rf_core::openrules`): the first program of a list opens
    /// such a file on a double click, all of them stand first under "Open with". Only rustyfiles follows them.
    pub open_rules: Vec<rf_core::openrules::OpenRule>,
    /// Closing the last window keeps rustyfiles in the notification area (Files' "leave app
    /// running in the background"): the next window opens instantly.
    pub run_in_background: bool,
    /// Status bar: listing time and the GPU/CPU renderer badge (developer info).
    pub show_perf_info: bool,
    /// A notification when a long operation finishes while rustyfiles is not in front.
    pub notify_long_ops: bool,
    /// Updates (GitHub Releases) are looked for and downloaded in the background.
    pub auto_update: bool,
    /// Beta versions (GitHub pre-releases) are taken as updates too. Off by default: a copy never moves to a beta by itself. A copy
    /// that IS a beta takes the next betas whatever this says (`installer::takes_betas`): whoever installed one by hand is in the
    /// beta program until a release arrives, which is newer than its betas.
    pub beta_updates: bool,
    /// The one-time "star it on GitHub" strip: first start (Unix ms), starts so far, and
    /// whether it was answered (starred or dismissed).
    pub first_start_ms: i64,
    pub starts: u32,
    pub star_asked: bool,
    /// The "buy me a coffee" strip, now and then: not before this time (Unix ms; 0 = by the
    /// first-start rule), never again once turned off, and how many times it was answered (its
    /// message changes each time).
    pub donate_next_ms: i64,
    pub donate_never: bool,
    pub donate_seen: u32,
    /// The one-time move from "details" to "adaptive" (0.3.3) has been made.
    pub adaptive_offered: bool,
    pub show_extensions: bool,
    /// Custom shortcuts: keystroke → action, e.g. `"ctrl-k" = "NewFolder"` (names as in the
    /// command palette's actions; `rustyfiles::` prefix optional). Applied at startup.
    pub keybindings: std::collections::BTreeMap<String, String>,
    /// The folder an app's Open / Save window always starts in, whatever folder the app asks for: the app's program name in lower
    /// case ("firefox.exe") to the folder. Set and cleared with the pin button of the dialog itself; listed in Settings › Advanced.
    /// A user on Discord, 2026-11-21: "per program default ... Say I use firefox ... open default storage location where i set it".
    pub dialog_folders: std::collections::BTreeMap<String, String>,
    /// The folder each app's Open / Save window was last finished in (its program name in lower case to the folder): the next one
    /// starts there unless the app names a folder itself or one is pinned (`dialog_folders`). See `picker::start_folders`.
    pub dialog_last_folders: std::collections::BTreeMap<String, String>,
    /// Programs (lower-case names, "myapp.exe") whose Open / Save windows stay Windows' own (issue 371). Added with the dialog's
    /// own button, removed in Settings › Advanced; mirrored to the file the dialog DLL reads (`rf_dialog::proto::windows_apps_path`).
    pub dialog_windows_apps: Vec<String>,
    /// Last window placement: [x, y, width, height, maximized (0/1)].
    pub window: Option<[f32; 5]>,
    /// Display UUID and the normal window's origin relative to that display.
    pub window_display: Option<(String, [f32; 2])>,

    // ---- General
    pub date_format: DatePref,
    pub startup: StartupPref,
    pub startup_pages: Vec<String>,
    /// Switch to tabs opened with Ctrl+click / middle click / "Open in new tab".
    pub focus_new_tab: bool,
    /// What a new tab opens (Ctrl+T, the "+" button, the tab menu): Home (the default) or the folder of the tab in front (a Reddit
    /// suggestion, 2026-11-18). Duplicating a tab keeps its folder either way.
    pub new_tab_opens: NewTabOpens,
    /// The folder a new tab opens with `NewTabOpens::Folder`; Home when it is empty or gone.
    pub new_tab_folder: String,
    /// What closing the window's only tab does (issue 456: a browser's "keep the window, open the new tab page").
    pub last_tab_close: LastTabClose,
    /// The x on the tabs (a discussion of 2026-11-30: off, the room goes to the title; a middle click or Ctrl+W still closes a tab).
    pub tab_close_buttons: bool,
    /// With the window maximized, the room above the tabs belongs to them: the pointer thrown to the top of the screen lands on a tab
    /// (Discord, 2026-12-01: "toss the mouse up ... and hover over tabs", as browsers do). Off: that strip stays the title bar, to grab
    /// the window by.
    pub tabs_reach_top: bool,
    /// A variant of a menu command (as administrator, in a new tab, to the left, move instead of copy) is a small button at the side
    /// of its row (on, the user's choice of 2026-11-30); off, it is a row of its own as before.
    pub menu_side_buttons: bool,
    /// Every command in the right-click menu without Shift (off: the seldom needed ones come with Shift+right click).
    pub menu_show_all: bool,
    /// A new tab (Ctrl+T, the + button) puts the keyboard in the address bar, ready for a typed or pasted path (issue 240).
    pub new_tab_address: bool,
    /// Switch to tabs 1–9 with Ctrl+1..9 (like Firefox). On by default.
    pub ctrl_number_tabs: bool,
    /// When `ctrl_number_tabs` is on, Ctrl+9 jumps to the last tab (like Firefox); off: jumps to the 9th tab.
    pub ctrl_9_last_tab: bool,
    /// Settings and the Recycle Bin open in a tab of their own instead of the tab in front, so its folder is not left (issue 386). Off.
    pub pages_in_new_tab: bool,
    /// The details shown when the pointer rests on an item (size, dates, a picture's size). Issue 264: some find them in the way.
    pub item_hover_details: bool,
    /// A folder opened from outside (Win+E, the desktop, another program) gets a window of its own instead of a tab in the newest
    /// window (issue 77). Off by default.
    pub launch_in_new_window: bool,
    /// A saved session opened from the tab menu takes the place of this window's tabs (they can be reopened, Ctrl+Shift+T) instead of
    /// opening a new window (issue 41). Off by default.
    pub sessions_in_this_window: bool,
    /// New tabs start split in two panes.
    pub dual_pane_new_tabs: bool,
    /// Dual pane side by side (true) or stacked (false).
    pub dual_pane_vertical: bool,
    /// In dual pane, each pane shows its own folder's path above it (on): the address bar shows only the active pane's, and to see
    /// where the other one is one had to switch to it (Discussion 732).
    pub dual_pane_paths: bool,
    /// A dual-pane tab shows both panes' folders in its title, left pane first ("ebooks | Children of Time"), instead of only the
    /// focused pane's (issue 915). Works together with `tab_shows_path`: then both panes' paths are shown, cut at the end.
    /// The focused pane's part is highlighted, so the title still tells which pane is active.
    pub dual_pane_tab_titles: bool,
    /// The share of the tab the first pane takes (the left one, or the upper one when stacked): the divider between the two panes is
    /// dragged (issue 284: "I kept trying to drag the middle divider, but I cannot"). 0.5 is the middle.
    pub dual_pane_split: f32,
    pub menu: MenuPrefs,
    pub smooth_scroll: bool,

    // ---- Appearance
    /// A scrollbar over the Details and Grid lists.
    pub show_scrollbar: bool,
    /// That scrollbar is shown all the time, not only while scrolling (issue 628: without a mouse wheel there was nothing to
    /// grab). Windows' own "Always show scrollbars" does the same for every program.
    pub scrollbar_always: bool,
    /// Generic file icons. `Windows` uses the shell, as before.
    pub icon_theme: IconThemePref,
    /// Folder name of a freedesktop pack under `%APPDATA%\rustyfiles\icon-themes` (empty = none).
    pub icon_theme_pack: String,
    pub animations: AnimPref,
    /// Extend the Windows File Explorer look to the navigation, toolbar, and file-list appearance.
    pub windows_file_explorer_theme: bool,
    pub menu_material: MenuMaterial,
    /// "Compact window": the tab row, the address bar and the command bar are thinner and the content card has no margin or round
    /// corners at its right and bottom; icons and text keep their size (a Discord request, 2026-11-22: room on small laptop screens).
    #[serde(default)]
    pub compact_window: bool,
    /// With the Windows File Explorer look, File Explorer's own measures (issue 693): Segoe UI at 12 px (9 pt) in the list and the
    /// sidebar, black in the light theme, Details rows 28 px apart at the default size, the sidebar's rows 32.
    pub explorer_metrics: bool,
    /// With the Windows File Explorer look, menus at the size of Windows' own: rows 24 px apart (Windows' classic menu: 22), 12 px
    /// text, narrower (issue 693).
    pub compact_menus: bool,
    /// With the Windows File Explorer look, the command bar stands over the list only, as without that look, instead of across the
    /// window over the sidebar too (issue 693).
    pub commandbar_over_list: bool,
    /// The command bar's height in pixels: 0 the look's own (58 with the Windows look, 44 without, 38 in a compact window), or 48,
    /// 44 or 36 (its buttons 28 high then) (issue 693).
    pub command_bar_height: u8,
    /// "Compact items", Explorer's "Compact view": every folder's Details rows are thinner (30 → 22 at the default size) and the grid's
    /// tiles closer, the name nearer its picture (a Discord request, 2026-11-23).
    #[serde(default)]
    pub compact_items: bool,
    /// "Alternating row colors": every other row of Details and Columns, and every other line of the grid's List, is lightly shaded so that
    /// rows next to each other are told apart.
    #[serde(default)]
    pub alternating_rows: bool,
    /// Lines of a name under a tile in the grid (2 to 4; issue 452: two cut long names short). The row grows by a line each.
    pub tile_name_lines: u8,
    /// A small play mark on a video's thumbnail in the grid, so that it is told from a picture (issue 452).
    pub video_badge: bool,
    pub backdrop: BackdropPref,
    /// "ClearType text" with the Solid material: its windows are opaque, and so are solid menus' windows, so that GPUI draws their
    /// text with ClearType (it does only in an opaque window). Off: Mica under the palette's opaque colour, as Solid always had.
    pub solid_cleartype: bool,
    /// Background tint color (0xRRGGBB), `None` = the backdrop as is.
    pub tint: Option<u32>,
    pub background_image: Option<PathBuf>,
    /// 0.05 … 0.6
    pub background_opacity: f32,
    /// HyperGlass look (Settings > Appearance, shown while the backdrop is Glass), each 0..=100; a value outside is cut to that when it is
    /// used. See `rf_win::glass::LookParams` for what the first four do; the surface value is the app's own two washes over the glass.
    pub hg_frost: u8,
    pub hg_tint: u8,
    pub hg_refraction: u8,
    pub hg_saturation: u8,
    pub hg_surface: u8,
    /// Freeze the glass of this app's windows while they are not in front: the last picture stays and nothing is captured or drawn for
    /// the window until it is in front again or the pointer is over it (`rf_win::glass::set_freeze_when_behind`). Off by default.
    pub hg_freeze_behind: bool,
    /// UI font family; `None` = Segoe UI Variable / system.
    pub font: Option<String>,
    /// The text size of the file manager's windows, percent of the usual (87, 100 or 112). Issue 89: "For lower resolution screens,
    /// the current font size is too large". It sets the windows' base size, which the texts are measured in.
    #[serde(skip_serializing_if = "is_hundred")]
    pub text_percent: u16,
    pub show_toolbar: bool,
    pub show_statusbar: bool,

    // ---- Layout
    /// One layout/sort for every folder (off = each folder remembers its own).
    pub sync_layout: bool,
    pub default_sort: rf_core::SortKey,
    pub default_sort_desc: bool,
    pub default_group: String,
    pub folders_first: bool,
    /// Files before folders (ignored while `folders_first` is on).
    pub files_first: bool,
    pub columns: ColumnPrefs,

    // ---- Files & folders
    pub show_system_files: bool,
    /// Names starting with "." count as hidden when off.
    pub show_dot_files: bool,
    pub show_thumbnails: bool,
    /// With thumbnails on, the List layout shows them too; off, its small rows keep the file type's icon while Tiles and Cards
    /// still show pictures (where an icon says more than a 16 px picture).
    pub list_thumbnails: bool,
    /// Until an item's own picture comes, Windows' icon for its type (a folder's, a file type's, a custom one) instead of ours;
    /// while Windows' icon is on its way, nothing (issue 695).
    pub windows_placeholder_icons: PlaceholderIconsPref,
    /// Independent override for Windows' icons in the preview pane (items without a thumbnail). `None` follows
    /// [`Self::windows_placeholder_icons`] so existing configurations keep their behaviour unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub windows_preview_icons: Option<PlaceholderIconsPref>,
    /// The bookmarks bar under the address bar (`bookmarks`, issue 694).
    pub bookmarks_bar: bool,
    /// A bookmark dragged along the bar takes its new place while it is dragged, the others making room, as tabs do in a browser,
    /// instead of a line where it will go.
    pub bookmarks_live_drag: bool,
    /// The bookmarks bar as high as the tab row, its buttons as the tabs; off, as high as its text needs.
    pub bookmarks_bar_tab_height: bool,
    /// The marks sync and version-control programs put on icons in Explorer (Google Drive, OneDrive, TortoiseGit, Dropbox), drawn
    /// over ours. A user on Discord, 2026-11-20.
    pub show_overlays: bool,
    pub show_checkboxes: bool,
    /// Settings › Advanced › "Let scripts read the open folders": `rustyfiles --state` answers with the open windows' tabs, folders
    /// and selection (issue 690). Off by default.
    pub state_api: bool,
    pub single_click: ClickPref,
    pub open_folders_in_new_tab: bool,
    pub confirm_delete: DeletePref,
    /// Delete (the key, the menu, the toolbar) sends to the Recycle Bin; off, it deletes permanently, as Shift+Delete always does
    /// (issue 458: to free the space at once). The question before a permanent delete follows `confirm_delete`.
    pub delete_to_bin: bool,
    pub warn_extension_change: bool,
    /// A name typed with characters Windows does not allow is tidied on Enter (`rf_core::rename::tidy_name`) instead of refused with
    /// what was typed lost (issue 370). On by default.
    pub fix_name_characters: bool,
    /// F2 on several items edits their names in place, all at once (issue 435); off: the bulk rename window opens.
    pub rename_several_in_place: bool,
    pub select_on_hover: bool,
    /// Each tab as wide as its name (within the usual limits) instead of all tabs equally wide. Issue 119.
    pub tabs_fit_names: bool,
    /// The List layout fills each column from top to bottom and scrolls sideways, as Explorer's List does (issue 170).
    pub list_columns_first: bool,
    /// Ctrl+wheel steps through the layouts (Details, List, Cards, Grid, Columns) and Ctrl+Shift+wheel through the sizes of the one
    /// shown (issue 333). Off: Ctrl+wheel zooms as in Explorer, from the details list into the grid and through its sizes.
    pub ctrl_wheel_layouts: bool,
    /// Home's recent list also shows the files that arrived lately: new in Downloads, or copied onto this PC (issue 421); off, only
    /// what was opened (issue 563).
    pub recent_arrivals: bool,
    /// A folder's tab shows its whole path (smaller, cut at the end) instead of its name (issue 162).
    pub tab_shows_path: bool,
    /// Explorer windows that other programs open are closed and their place opened here (issue 37). Off by default.
    pub catch_explorer_windows: bool,
    /// A theme folder's name in `<settings folder>\themes` (colours and icons, issues 93 and 94); empty: none.
    pub theme_folder: String,
    /// The terminal button on each folder's tab. Issue 119: it was in the way of clicks on narrow tabs.
    pub tab_terminal_button: bool,
    /// Typing in a folder's list filters it by name (the filter bar opens with the letters); off: typing selects the item whose
    /// name starts with them. Issue 106.
    pub type_to_filter: bool,
    /// Typing in a folder's list goes into the search box instead (Discord, 2026-11-30: "like File Pilot, start typing and it
    /// searches"): the folder is filtered live by the letters and Enter searches its subfolders too, as the search box always does.
    /// Wins over `type_to_filter`; Settings shows the two as one three-way choice.
    pub type_to_search: bool,
    pub double_click_up: bool,
    /// In the Details and Columns views a press on the empty space of a row starts a selection box, as in Explorer (issue 239). Off:
    /// the item is dragged from anywhere on its row, as before 0.9.9 (asked for on Discord, 2026-11-24: "It feels off").
    pub row_selection_box: bool,
    pub select_previous_on_up: bool,
    pub decimal_sizes: bool,
    /// With binary sizes: KiB, MiB, GiB instead of Explorer's KB, MB, GB (a request on Discord, 2026-11-23).
    pub binary_prefixes: bool,
    pub calculate_folder_sizes: bool,
    /// Folder sizes also on network drives and shares (a discussion of 2026-11-30: off keeps the network quiet while local folders
    /// are measured). Only counts while `calculate_folder_sizes` is on.
    pub folder_sizes_on_network: bool,
    /// Folder sizes from Everything's index (voidtools), when it is running and indexes folder sizes: every folder of a listing at
    /// once, in a few milliseconds, without walking the disk (`rf_win::everything`). A folder it does not know is walked only with
    /// `calculate_folder_sizes` on, or when its size is asked for by hand.
    pub folder_sizes_everything: bool,
    /// Folders show their size on disk (files rounded up to whole clusters) instead of the sum
    /// of their file sizes.
    pub folder_size_on_disk: bool,
    /// Our own parallel engine for copies, moves to other drives and permanent deletes
    /// (off: Windows' engine for everything, like Explorer).
    pub fast_file_ops: bool,
    /// Disk kinds chosen by hand for the copy engine, by drive ("E:"): they win over what Windows reports (Settings › Advanced ›
    /// Disk kinds for copying). A drive not named here is detected.
    #[serde(default)]
    pub copy_disk_kinds: std::collections::BTreeMap<String, rf_win::drives::DiskKind>,
    /// To the Recycle Bin by renaming each item into it on NTFS drives (`rf_win::fastrecycle`), instead of Windows' engine, which
    /// takes ~47 s for 20,000 files. Its own switch, so it can be turned off by itself if it ever misbehaves on a PC.
    pub fast_recycle: bool,
    /// Check copies after writing them.
    pub copy_verify: CopyVerify,
    /// A copy into a WSL distribution leaves no "file:Zone.Identifier" file beside it (the download mark Windows writes there as a
    /// file of its own). A user on Discord, 2026-11-20.
    pub wsl_drop_zone: bool,
    /// Copy speed limit in MB/s (0 = none).
    pub copy_speed_limit: u32,
    /// Where a running operation's progress is shown (see [`TransferProgress`]).
    pub transfer_progress: TransferProgress,
    /// Finished operations leave the Status Center this many hours after they ended; 0: they stay until cleared (discussion 700).
    pub status_clear_hours: u32,
    /// The thumbnail cache's limit in MB (the cache is in memory); `None` = the default, 64 MB, and no key in the file.
    pub thumb_cache_mb: Option<u32>,
    pub show_libraries: bool,
    /// HyperDownload's row stands with the pinned folders, at the top of the sidebar, instead of above the Recycle Bin.
    pub hd_pinned_top: bool,
    /// Each drive in the sidebar says how much of it is used, in numbers ("238 GB / 500 GB"), under its bar. Issue 167.
    pub sidebar_drive_space: bool,
    /// A "Klasörler" section in the sidebar: the folder tree (drives and the profile folder as roots). Off by default.
    pub sidebar_tree: bool,
    /// The tree opens the branch to the open folder, marks it and scrolls it into view after every navigation.
    pub sidebar_tree_follow: bool,
    /// Text typed into the address field that names no place that exists is tried as a program (`cmd`, `wt`, `"C:\Tools\x.exe" /s`) and
    /// started in the open folder, as Explorer does (see `workspace/address_cmd.rs`). On by default, as in Explorer (the issue that asked
    /// for it expects it to work); only a name that IS a program on the search path starts anything, and the switch turns it off.
    pub address_commands: bool,
    /// The path in the address bar shows the folders' names on the disk (`C:\Users\me\Documents`) instead of the names Windows
    /// translates them to (`C:\Kullanıcılar\me\Belgeler`), as typed or used by programs (issue 442). Off: Explorer's look.
    pub address_real_names: bool,
    /// Double-clicking a ZIP/7z/tar opens it like a folder (read-only).
    pub browse_archives: bool,
    /// Where an archive opened like a folder goes (Discord, 2026-11-20: "an option/toggle to make zips open separately from the
    /// normal window").
    pub archives_open_in: ArchiveOpen,
    /// What a click on "Sıkıştır" in the right-click menu does: compress at once in this format, or (`Menu`) only open its submenu.
    pub quick_compress: QuickCompress,
    /// What a click on "Çıkar" in the right-click menu does: extract at once, or (`Menu`) only open its submenu.
    pub quick_extract: QuickExtract,
    /// What a drag without Ctrl or Shift does (issue 466).
    pub plain_drag: PlainDrag,
    /// Thumbnails of camera JPEGs and RAW files from the preview inside the file (`rf_win::embedded_thumb`) instead of the shell's
    /// decode of the whole picture. On unless the settings file says `own_thumbnails = false` (no switch in Settings: it is the
    /// way back to the shell's thumbnails should a camera's files come out wrong).
    #[serde(skip_serializing_if = "is_true")]
    pub own_thumbnails: bool,
    /// After extracting an archive into a new folder, that folder opens in a tab.
    pub open_after_extract: bool,
    /// Search through the Windows Search index (contents, AQS) where the folder is indexed.
    pub search_index: bool,
    /// Our own name index of the local drives: searching in subfolders takes milliseconds.
    pub name_index: bool,
    /// Folders left out of the name index (searching inside them walks the disk).
    pub index_excluded: Vec<String>,
    /// Hard drives (disks with a seek penalty) in the name index too: off by default, walking one is minutes of audible seeking.
    pub index_hard_drives: bool,
    /// The drive letters the name index covers, when the user chose them one by one ("C", "Z:").
    /// Empty: the automatic set — every local fixed NTFS/ReFS drive (plus hard drives per
    /// [`Self::index_hard_drives`]); network drives are indexed only when picked here (issue 736:
    /// a share is walked, and not everyone wants that traffic).
    pub index_drives: Vec<String>,
    /// The cloud sync folders (OneDrive, Proton Drive, …) the name index covers, as paths.
    /// Empty: none — a cloud folder is walked only when picked here (issue 885), and an
    /// unpicked one is left out of its drive's walk like a folder the user excluded.
    pub index_clouds: Vec<String>,

    // ---- Developer tools
    pub ide_button: IdePref,
    /// Editor to open folders with ("code" when empty and VS Code is installed).
    pub ide_path: String,
    /// "Open in Terminal" starts this program (a path or a name such as `cmd.exe`); empty: Windows Terminal, else PowerShell (issue 224).
    pub terminal_path: String,
    /// The program "Edit" (F4) opens files with: empty is Notepad (Discord, 2026-11-23: "select an alternative editor (e.g. Sublime
    /// Text, Notepad++, VS Code)").
    pub text_editor_path: String,
    /// The program every Git command runs (another Git, or `wslgit.exe`); empty: `git` from the PATH.
    pub git_path: String,
    /// Git status in the list (the column, the mark after a name, the commit columns) inside repositories (on). Off: no Git command
    /// is run for the list at all (Discussion 734: a Downloads folder inside a repository showed marks its owner never wanted).
    pub git_integration: bool,

    // ---- Advanced
    pub show_flatten: bool,

    // ---- DirectLook (Hızlı Bakış, ayrı program): ayarları kendi dosyasında (`look::config`)
    /// DirectLook kullanılsın mı (kapalıyken rustyfiles onu başlatmaz, Boşluk bir şey yapmaz).
    pub directlook_enabled: bool,
    /// Space hands the file to QuickLook (QL-Win) instead of DirectLook (`quicklook`).
    pub space_quicklook: bool,

    // ---- Quick search (quick_search.rs)
    /// A global shortcut opens the quick search: apps, files, bookmarks, the web.
    pub quick_search: bool,
    /// Its shortcut, in GPUI's syntax ("alt-space").
    pub quick_search_keys: String,
    pub web_search: WebSearch,
    /// Chrome's and Edge's bookmarks are searched too (read on this PC only).
    pub quick_search_bookmarks: bool,
    /// With nothing typed, HyperSearch lists what was opened lately; off: it shows nothing until something is typed (issue 41:
    /// "Add an option to show/hide recent searches").
    pub quick_search_recent: bool,
    /// The command palette (Ctrl+Shift+P) lists past folders among the commands once something is typed (`folder_history`). Off:
    /// commands only; Ctrl+P still searches past folders.
    pub palette_folder_history: bool,

    // ---- Dock (dock/: `rustyfiles --dock`, a separate process; experimental)
    /// The dock runs: started with rustyfiles and when this is switched on, stopped when it is switched off.
    pub dock_enabled: bool,
    /// The dock keeps other windows from going under it (it registers as an application desktop toolbar).
    pub dock_reserve: bool,
    /// Place the dock on the bottom or right edge.
    pub dock_position: DockPosition,
    /// The city the dock's weather is for. Empty: no weather and no network request.
    pub dock_weather_city: String,
    /// The dock's weather is for the PC's approximate position from Windows' location service (off by default). The order: the position
    /// when this is on and Windows gives it, else the city above, else no weather (see `rf_win::weather_location`). The position is
    /// never stored here or anywhere else.
    pub dock_weather_location: bool,
    /// The dock's logo opens our own Start panel and its search field our own search (on). Off: the old behaviour, the logo sends the
    /// Windows key and the field opens the quick search window.
    pub dock_own_start: bool,
    /// The dock's network and volume symbols open our own control centre (on). Off: the old behaviour, they send Win+A (Windows' quick
    /// settings).
    pub dock_own_control_centre: bool,
    /// The parts of our control centre the user hid (Settings > Dock): names of `dock::cc_model::PARTS` (a tile, a card, the row of
    /// quick buttons) and of single quick buttons (`Quick::key`). Empty: everything the machine has is shown.
    pub dock_cc_hidden: Vec<String>,
    /// The dock's clock opens our own calendar panel (on). Off: the old behaviour, it sends Win+N (Windows' notification centre and calendar).
    pub dock_own_calendar: bool,
    /// The dock's bell opens our own notification panel and wears a dot while there are notifications (on). Off: the old behaviour,
    /// it sends Win+N.
    pub dock_own_notifications: bool,
    /// The order of the right island's own buttons, as keys ("eject", "security", "network", "volume"); empty: the usual order. A list
    /// that names only some, or names a key this version does not know, is completed (`rf_win::dock::status_order`).
    pub dock_status_order: Vec<String>,
    /// Which of those buttons the user hid (the same keys); empty: all are shown.
    pub dock_status_hidden: Vec<String>,
    /// The left and the right island are as tall as the middle one (off: they are lower, as they always were). While the dock is thin
    /// under a maximised window all three are the thin height either way.
    pub dock_side_tall: bool,
    /// The dock hides at the bottom of the screen and comes up when the pointer reaches the edge (off; issue 112). It reserves no
    /// band then: windows use the whole screen.
    pub dock_autohide: bool,
    /// With auto-hide on: the dock hides only while a window lies where it stands, and comes back up when that window is minimised,
    /// closed or moved away (off: it hides whenever the pointer leaves it). A user on Discord, 2026-11-20.
    pub dock_autohide_windows: bool,
    /// The dock's islands on a solid fill instead of the glass (off; issue 113).
    pub dock_opaque: bool,
    /// The glass's tone follows what is behind it (on): light glass with dark text over a bright page. Off: the theme alone decides,
    /// glass or not (issue 388: "the dark theme randomly resets to light" over a bright window).
    pub dock_adaptive_tone: bool,
    /// The Dock without its motions and on a solid fill: less work while a game keeps the graphics card busy (issue 133).
    pub dock_performance: bool,
    /// A thin "Show desktop" strip at the right end of the primary monitor's right island, after the bell, as on Windows' taskbar (off;
    /// issue 127).
    pub dock_show_desktop: bool,
    /// The Dock's clock shows the seconds, and is then drawn again every second (off by default).
    pub dock_clock_seconds: bool,
    /// The app's name under each icon of the middle island (off). Issue 137: "would really like to see app names under the icon".
    pub dock_labels: bool,
    /// Pinned apps that are not running stand in the left island, as launchers; the middle one holds the running apps (off). Issue 137:
    /// "I would like to see apps pinned appearing on the left dock when they are not open".
    pub dock_pins_left: bool,
    /// The middle island without the Recycle Bin and Downloads (off; a Discord request, 2026-11-28).
    pub dock_hide_places: bool,
    /// A line between the pinned apps and the running ones that are not pinned (off; the same request).
    pub dock_running_divider: bool,
    /// The badges programs put on their taskbar buttons (a chat's unread count) are shown on their icons in the dock (off; issue 705).
    /// They come through the tray host (`rf_win::dock::badges`), so only while it runs.
    pub dock_app_badges: bool,
    /// The dock's springs swing a little past their target and back (off): the icons' growth as the pointer comes in, an icon's
    /// slide into its new place.
    pub dock_lively: bool,
    /// The dock's icons stay where they are: a drag does not move them (off; a Discord request, 2026-11-28: "fixing the icon
    /// position").
    pub dock_lock_icons: bool,
    /// The islands' corner radius in logical px (0 to 32; issue 463). 24 is the dock's own.
    pub dock_corner_radius: u8,
    /// The size of the window previews over the Dock's icons, in percent of the normal (issue 463): 80, 100, 130 or 160.
    pub dock_preview_size: u8,
    /// Apps never shown in the dock: program file names or app names, separated by commas (the same request).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub dock_ignored_apps: String,
    /// The left island's search: a field, its button only, or none (`DockSearch`).
    pub dock_search: DockSearch,
    /// A click on the dock's search field or button opens HyperSearch instead of the Start panel (issue 41). Off by default.
    pub dock_search_hypersearch: bool,
    /// The tray icons of the right island stand closer together (18 px a cell instead of 24; off). Issue 34.
    pub dock_tray_compact: bool,
    /// The tray icons in two rows at their usual size (off). Issue 34: compact was too small on a wide screen.
    pub dock_tray_two_rows: bool,
    /// Turning the mouse wheel over a running app's icon in the dock turns that app's own sound level up or down (on; issue 21).
    pub dock_scroll_volume: bool,
    /// How much the dock's icons grow under the pointer (off / subtle / full).
    pub dock_magnify: DockMagnify,
    /// Resting the pointer on a running app's icon in the dock shows a preview of its windows (on; the dock itself is opt-in). Off: nothing.
    pub dock_hover_previews: bool,
    /// A right click on an app's icon in the dock opens the dock's own app menu (on). Off: it does nothing, as before.
    pub dock_app_menu: bool,
    /// While a window is maximised on the dock's monitor the middle island drops to the side islands' height, the band it reserves
    /// shrinks with it, and it grows back when the pointer comes near (on; the dock itself is opt-in). Off: the dock of before.
    pub dock_thin_when_maximized: bool,
    /// The Start panel shows "Önerilenler" (the documents opened most recently) under the pinned apps (on). Off: the section is not
    /// drawn and the pinned grid takes its room.
    pub dock_start_recommended: bool,
    /// The Start panel grows out of the left island: the island's glass widens upwards into the panel and shrinks back into the island
    /// when it closes (`dock/grow_host.rs`). On by default; off: the panel opens above the island as a window of its own, as it always did.
    pub dock_start_grow: bool,
    /// How big the whole dock is (small / medium / large / extra large; medium is the dock as it always was).
    pub dock_size: crate::dock::size_pref::DockSizePref,
    /// A dock on every monitor, not only the primary one (on by default; the dock itself is opt-in). The other
    /// monitors' docks hold the Start logo and search, the apps, and the clock and bell. Off, or with one monitor: the single dock of before.
    pub dock_all_monitors: bool,
    /// With a dock on every monitor: whether every dock shows every running app, or an app only where its window is.
    pub dock_apps_where: DockAppsWhere,

    // ---- The dock's parts (shell/: `rustyfiles --shell`, the dock's process). ONE switch starts them all: `dock_enabled` (Settings ->
    // Dock). These five are the parts' own values, kept in the file under their old names as TROUBLESHOOTING OVERRIDES that the page
    // shows no switch for: a part runs when `dock_enabled` is on AND its own value is not false (`dock/parts.rs` is the rule). Their
    // default is true. Files written before the one switch hold `false` here (the old default was written into every saved file):
    // a false is read as "held off", the Dock page says so in one line and "Hepsini aç" clears it.
    /// Our desktop (the wallpaper, the icons) is drawn over Explorer's, one window per monitor, while the shell host runs. Explorer's
    /// desktop stays underneath and is visible again when the host stops.
    pub shell_desktop_cover: bool,
    /// A tap of the Windows key alone opens rustyfiles' Start panel instead of Windows' (the shell host listens to the keyboard with a
    /// system-wide hook while this or `shell_own_switcher` runs; see `shell/keylayer.rs`).
    pub shell_win_key: bool,
    /// Alt+Tab opens rustyfiles' window switcher instead of Windows' (same hook).
    pub shell_own_switcher: bool,
    /// The shell host owns a window of class `Shell_TrayWnd` in front of Explorer's, takes the icons programs send to the notification
    /// area, and passes every message on to Explorer's own window unchanged (see `shell/trayhost.rs`, `docs/design/tray-host.md`).
    pub shell_tray_host: bool,
    /// Explorer's taskbar windows (and with them its notification icons) are hidden while the dock runs and shown again when it stops;
    /// only with rustyfiles-shellguard.exe running as the safety net (see `shell/taskbar_hide.rs`).
    pub shell_hide_taskbar: bool,
    /// Every screen snip is also saved to Pictures\Screenshots without asking (off: it is only copied to the clipboard, and the
    /// notice's Kaydet button saves it by hand). See `snip/`.
    pub snip_autosave: bool,
    /// Set once a build with the one switch has read the file (`dock/parts.rs`, FILES FROM BEFORE). While the file does not have it and
    /// has the dock on, the parts it does not name are held off (see [`Settings::migrate`]); the first save writes it, together with the
    /// held values, so that the hold survives the marker.
    pub dock_one_switch: bool,
    /// Not in the file. The parts' own values the file did not name, when it came from before the one switch with the dock on: what
    /// [`Settings::migrate`] turns into held-off values. Empty for every other file.
    #[serde(skip)]
    pub parts_unnamed_in_old_file: Vec<String>,

    // ---- Desktop (shell/desktop/; Settings -> "Masaüstü"; experimental, it only matters while the desktop part runs)
    // Each system icon of the desktop (and "show desktop icons" as a whole) follows Windows' own setting by default; "show" and "hide"
    // are this app's own choice and are never written to Windows' settings (see `rf_core::desktop::virtuals`).
    pub desktop_icon_this_pc: rf_core::desktop::virtuals::IconChoice,
    pub desktop_icon_user_files: rf_core::desktop::virtuals::IconChoice,
    pub desktop_icon_network: rf_core::desktop::virtuals::IconChoice,
    pub desktop_icon_recycle_bin: rf_core::desktop::virtuals::IconChoice,
    pub desktop_icon_control_panel: rf_core::desktop::virtuals::IconChoice,
    /// "Show desktop icons" as a whole: follow Windows, always show, or hide every icon (files included).
    pub desktop_show_icons: rf_core::desktop::virtuals::IconChoice,
    /// The desktop's wallpaper is drawn with rounded corners of this radius (logical px; 0, the default: square, as it always was).
    /// All four corners of every monitor, black behind them (`rf_core::desktop::corners` for the bottom pixel row). An experiment
    /// to go with the dock's round islands.
    pub desktop_corner_radius: u8,
    /// A request, taken once: the next time rustyfiles' own desktop starts, it takes the icon positions of Windows' desktop again (as the
    /// first start does) and clears this. Off by itself afterwards.
    pub desktop_copy_windows: bool,

    // ---- Ferry (sending files to rustyfiles on the network's other devices; Settings -> "Ferry"; crates/rf-nearby and ferry.rs)
    /// Ferry runs in the main process (off by default: it listens on a network port, and Windows' firewall may ask about that).
    pub ferry_enabled: bool,
    /// Who sees this PC: nobody, its trusted devices (the default), or everyone. "Everyone" lasts ten minutes and a start reads it as
    /// trusted devices.
    pub ferry_visibility: FerryVisibility,
    /// The name the other devices show for this PC; empty: the PC's own name.
    pub ferry_name: String,
    /// Where received files go; empty: the Downloads folder.
    pub ferry_inbox: String,
    /// Where HyperDownload puts what the browsers hand it; empty: the Downloads folder (HyperDownload issues 1 and 3).
    pub hd_downloads: String,
    /// Files from a trusted device are taken without asking, into the folder above (on).
    pub ferry_auto_accept_trusted: bool,
}

/// Settings -> General: closing the window's only tab.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum LastTabClose {
    /// The window closes with it, as in Explorer.
    #[default]
    Window,
    /// The window stays and the tab goes to Home (on Home already: nothing happens).
    Home,
}

/// Settings -> General: what a new tab opens.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum NewTabOpens {
    #[default]
    Home,
    Current,
    /// The folder in `new_tab_folder` (a discussion of 2026-11-25: "a folder of your choice for what the + button opens").
    Folder,
}

/// Settings -> Ferry: who sees this PC.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum FerryVisibility {
    Off,
    #[default]
    Trusted,
    Everyone,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            theme: ThemePref::System,
            language: Lang::System,
            default_view: DefaultView::Adaptive,
            default_row_size: 1,
            default_grid_size: 2,
            show_hidden: false,
            preview_open: true,
            picker_preview_open: true,
            picker_sidebar_rail: true,
            picker_see_through: false,
            picker_size: None,
            sidebar_open: true,
            sidebar_rail: false,
            sidebar_width: DEFAULT_SIDEBAR_WIDTH,
            sidebar_text_percent: 0,
            sidebar_compact: false,
            explorer_sidebar_width: None,
            sidebar_hidden: Vec::new(),
            drive_places: Vec::new(),
            drive_place_icons: Vec::new(),
            home_hidden: Vec::new(),
            home_split_drives: false,
            recent_cleared_ms: 0,
            search_history: Vec::new(),
            toolbar_hidden: Vec::new(),
            toolbar_order: Vec::new(),
            toolbar_right_order: Vec::new(),
            toolbar_look: Vec::new(),
            toolbar_icon_size: ToolbarIconSize::Medium,
            toolbar_windows_icons: false,
            toolbar_accent_icons: false,
            menu_windows_icons: false,
            toolbar_extra: Vec::new(),
            toolbar_commands: Vec::new(),
            preview_width: 300.,
            preview_position: rf_core::previewpane::PreviewPos::Right,
            preview_height: rf_core::previewpane::BOTTOM_DEFAULT_H,
            renderer: RendererPref::Auto,
            restore_session: true,
            session_tabs: Vec::new(),
            session_panes: Vec::new(),
            session_active: 0,
            saved_sessions: Vec::new(),
            pinned: None,
            folder_aliases: Default::default(),
            hidden_drives: Vec::new(),
            hidden_places: Vec::new(),
            accent_color: String::new(),
            open_rules: Vec::new(),
            run_in_background: false,
            show_perf_info: false,
            notify_long_ops: true,
            auto_update: true,
            beta_updates: false,
            first_start_ms: 0,
            starts: 0,
            star_asked: false,
            donate_next_ms: 0,
            donate_never: false,
            donate_seen: 0,
            adaptive_offered: false,
            show_extensions: true,
            keybindings: Default::default(),
            dialog_folders: Default::default(),
            dialog_last_folders: Default::default(),
            dialog_windows_apps: Vec::new(),
            window: None,
            window_display: None,
            date_format: DatePref::Application,
            startup: StartupPref::Continue,
            startup_pages: Vec::new(),
            focus_new_tab: false,
            new_tab_opens: NewTabOpens::Home,
            new_tab_folder: String::new(),
            last_tab_close: LastTabClose::Window,
            tab_close_buttons: true,
            tabs_reach_top: true,
            menu_side_buttons: true,
            menu_show_all: false,
            new_tab_address: false,
            ctrl_number_tabs: true,
            ctrl_9_last_tab: true,
            pages_in_new_tab: false,
            item_hover_details: true,
            launch_in_new_window: false,
            sessions_in_this_window: false,
            dual_pane_new_tabs: false,
            dual_pane_vertical: true,
            dual_pane_paths: true,
            dual_pane_tab_titles: false,
            dual_pane_split: 0.5,
            menu: MenuPrefs::default(),
            smooth_scroll: true,
            show_scrollbar: true,
            scrollbar_always: false,
            icon_theme: IconThemePref::Windows,
            icon_theme_pack: String::new(),
            animations: AnimPref::System,
            windows_file_explorer_theme: false,
            menu_material: MenuMaterial::default(),
            compact_window: false,
            explorer_metrics: false,
            compact_menus: false,
            commandbar_over_list: false,
            command_bar_height: 0,
            compact_items: false,
            alternating_rows: false,
            tile_name_lines: 2,
            video_badge: true,
            props_size: None,
            app_icon: None,
            backdrop: BackdropPref::Mica,
            solid_cleartype: false,
            tint: None,
            background_image: None,
            background_opacity: 0.2,
            hg_frost: HG_DEFAULT[0],
            hg_tint: HG_DEFAULT[1],
            hg_refraction: HG_DEFAULT[2],
            hg_saturation: HG_DEFAULT[3],
            hg_surface: HG_DEFAULT[4],
            hg_freeze_behind: false,
            font: None,
            text_percent: 100,
            show_toolbar: true,
            show_statusbar: true,
            sync_layout: false,
            default_sort: rf_core::SortKey::Name,
            default_sort_desc: false,
            default_group: "none".into(),
            folders_first: true,
            files_first: false,
            columns: ColumnPrefs::default(),
            show_system_files: false,
            show_dot_files: true,
            show_thumbnails: true,
            list_thumbnails: true,
            windows_placeholder_icons: PlaceholderIconsPref::Off,
            windows_preview_icons: None,
            bookmarks_bar: false,
            bookmarks_live_drag: true,
            bookmarks_bar_tab_height: false,
            show_overlays: true,
            show_checkboxes: false,
            state_api: false,
            single_click: ClickPref::Never,
            open_folders_in_new_tab: false,
            confirm_delete: DeletePref::PermanentOnly,
            delete_to_bin: true,
            warn_extension_change: true,
            fix_name_characters: true,
            rename_several_in_place: false,
            select_on_hover: false,
            tabs_fit_names: false,
            list_columns_first: false,
            ctrl_wheel_layouts: false,
            recent_arrivals: true,
            tab_shows_path: false,
            catch_explorer_windows: false,
            theme_folder: String::new(),
            tab_terminal_button: true,
            preview_details: true,
            type_to_filter: false,
            type_to_search: false,
            double_click_up: true,
            row_selection_box: true,
            select_previous_on_up: true,
            decimal_sizes: false,
            binary_prefixes: false,
            calculate_folder_sizes: false,
            folder_sizes_on_network: true,
            folder_sizes_everything: false,
            folder_size_on_disk: false,
            fast_file_ops: true,
            copy_disk_kinds: Default::default(),
            fast_recycle: true,
            copy_verify: CopyVerify::Off,
            wsl_drop_zone: false,
            copy_speed_limit: 0,
            status_clear_hours: 0,
            transfer_progress: TransferProgress::StatusBar,
            thumb_cache_mb: None,
            show_libraries: false,
            hd_pinned_top: false,
            sidebar_drive_space: false,
            sidebar_tree: false,
            sidebar_tree_follow: true,
            address_commands: true,
            address_real_names: false,
            browse_archives: true,
            quick_compress: QuickCompress::Zip,
            quick_extract: QuickExtract::Named,
            plain_drag: PlainDrag::Auto,
            own_thumbnails: true,
            archives_open_in: ArchiveOpen::Here,
            open_after_extract: false,
            search_index: true,
            name_index: true,
            index_excluded: Vec::new(),
            index_hard_drives: false,
            index_drives: Vec::new(),
            index_clouds: Vec::new(),
            ide_button: IdePref::GitRepos,
            ide_path: String::new(),
            terminal_path: String::new(),
            text_editor_path: String::new(),
            git_path: String::new(),
            git_integration: true,
            show_flatten: false,
            space_quicklook: false,
            directlook_enabled: true,
            quick_search: true,
            quick_search_keys: "alt-space".into(),
            web_search: WebSearch::Google,
            quick_search_bookmarks: true,
            quick_search_recent: true,
            palette_folder_history: true,
            dock_enabled: false,
            dock_reserve: true,
            dock_position: DockPosition::Bottom,
            dock_weather_city: String::new(),
            dock_weather_location: false,
            dock_own_start: true,
            dock_own_control_centre: true,
            dock_cc_hidden: Vec::new(),
            dock_own_calendar: true,
            dock_own_notifications: true,
            dock_status_order: Vec::new(),
            dock_status_hidden: Vec::new(),
            dock_side_tall: false,
            dock_autohide: false,
            dock_autohide_windows: false,
            dock_opaque: false,
            dock_adaptive_tone: true,
            dock_performance: false,
            dock_show_desktop: false,
            dock_clock_seconds: false,
            dock_labels: false,
            dock_pins_left: false,
            dock_hide_places: false,
            dock_running_divider: false,
            dock_app_badges: false,
            dock_lively: false,
            dock_lock_icons: false,
            dock_corner_radius: 24,
            dock_preview_size: 100,
            dock_ignored_apps: String::new(),
            dock_search: DockSearch::Field,
            dock_search_hypersearch: false,
            dock_tray_compact: false,
            dock_tray_two_rows: false,
            dock_scroll_volume: true,
            dock_magnify: DockMagnify::Full,
            dock_hover_previews: true,
            dock_app_menu: true,
            dock_thin_when_maximized: true,
            dock_start_recommended: true,
            // on: the Start panel grows out of the island; the switch on the Dock page turns it off
            dock_start_grow: true,
            dock_size: Default::default(),
            dock_all_monitors: true,
            dock_apps_where: DockAppsWhere::All,
            // (the parts' own values: true, so the one switch `dock_enabled` brings them all; see `dock/parts.rs`)
            shell_desktop_cover: true,
            shell_win_key: true,
            shell_own_switcher: true,
            shell_tray_host: true,
            shell_hide_taskbar: true,
            snip_autosave: false,
            dock_one_switch: false,
            parts_unnamed_in_old_file: Vec::new(),
            desktop_icon_this_pc: Default::default(),
            desktop_icon_user_files: Default::default(),
            desktop_icon_network: Default::default(),
            desktop_icon_recycle_bin: Default::default(),
            desktop_icon_control_panel: Default::default(),
            desktop_show_icons: Default::default(),
            desktop_corner_radius: 0,
            desktop_copy_windows: false,
            ferry_enabled: false,
            ferry_visibility: FerryVisibility::Trusted,
            ferry_name: String::new(),
            ferry_inbox: String::new(),
            hd_downloads: String::new(),
            ferry_auto_accept_trusted: true,
        }
    }
}

impl Global for Settings {}

/// The HyperGlass defaults in the order frost, tint, refraction, saturation, surface. The first four are the engine's own defaults
/// (`LookParams::DEFAULT`, a test keeps them equal); the surface default is the wash the app shipped with over glass.
pub const HG_DEFAULT: [u8; 5] = [52, 50, 67, 62, 50];

static THEME: AtomicU8 = AtomicU8::new(0);
static WINDOWS_FILE_EXPLORER_THEME: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static COMPACT_WINDOW: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static COMPACT_ITEMS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static ICON_THEME: AtomicU8 = AtomicU8::new(0);
/// The selected freedesktop pack's folder name, read by the icon cache without a `Settings` global.
static ICON_PACK: std::sync::OnceLock<parking_lot::RwLock<String>> = std::sync::OnceLock::new();
/// The surface value (0..=100) the palette reads on every call, cheaper than the settings struct.
static HG_SURFACE: AtomicU8 = AtomicU8::new(HG_DEFAULT[4]);
static SOLID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static HOME_RECENT_OWN_MENU: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static WINDOWS_PLACEHOLDER_ICONS: AtomicU8 = AtomicU8::new(0);
static SOLID_CLEARTYPE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static EXPLORER_METRICS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static COMPACT_MENUS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static COMMAND_BAR_HEIGHT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
/// The chosen material is one a Windows without materials can still give the MAIN window (Acrylic, HyperGlass): see
/// [`main_window_only`].
static MAIN_ONLY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

static ANIM: AtomicU8 = AtomicU8::new(0);

/// [`Settings::scrollbar_always`], for the scrollbars' mode (`folder_view::scrollbar_mode`).
pub static SCROLLBAR_ALWAYS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Whether UI animations play (Settings → Appearance → Animations; "System" follows Windows'
/// Animation effects, read each time: it's one cheap call and may change while we run).
pub fn animations() -> bool {
    match ANIM.load(Ordering::Relaxed) {
        x if x == AnimPref::On as u8 => true,
        x if x == AnimPref::Off as u8 => false,
        _ => rf_win::sysparams::client_area_animation(),
    }
}

/// "Solid" background material: the palette paints an opaque window background. Also on a Windows without materials, whatever the
/// setting says and in every process (a side process that never loads these settings asks too).
/// Settings › Right-click menu › "rustyfiles' menu on Recent items", read by the list's selection (where there is no `App`).
pub fn home_recent_own_menu() -> bool {
    HOME_RECENT_OWN_MENU.load(Ordering::Relaxed)
}

/// Settings › "Windows' icons while pictures load", read where there is no `App` at hand.
pub fn windows_placeholder_icons() -> PlaceholderIconsPref {
    PlaceholderIconsPref::from_u8(WINDOWS_PLACEHOLDER_ICONS.load(Ordering::Relaxed))
}

/// Whether Windows' placeholder icons are enabled for an item of this kind (`is_dir`: folder vs file/image).
pub fn windows_placeholder_icons_for(is_dir: bool) -> bool {
    windows_placeholder_icons().applies(is_dir)
}

/// The picture of an item whose own (Windows') icon has not come yet: ours, or when `windows_placeholder_icons` applies to this item
/// kind an empty box of its size, so that nothing of ours shows for a moment before Windows' icon.
pub fn loading_icon(icon: gpui_kit::assets::IconName, size: Pixels, color: Hsla, is_dir: bool) -> AnyElement {
    if windows_placeholder_icons_for(is_dir) {
        div().size(size).flex_shrink_0().into_any_element()
    } else {
        gpui_kit::component::Icon::new(icon).size(size).flex_shrink_0().text_color(color).into_any_element()
    }
}

/// Settings › Appearance › "ClearType text" (shown with the Solid material), read where there is no `App` at hand.
pub fn solid_cleartype() -> bool {
    SOLID_CLEARTYPE.load(Ordering::Relaxed)
}

/// Settings › "File Explorer's measures", with the Windows look on, read where there is no `App` at hand.
pub fn explorer_metrics() -> bool {
    EXPLORER_METRICS.load(Ordering::Relaxed)
}

/// The size of the list's text: Explorer's 12 px with its measures, else `text_sm`.
pub fn list_text_px(window: &Window) -> Pixels {
    if explorer_metrics() { px(12.) } else { px(f32::from(window.rem_size()) * 0.875) }
}

/// Settings › "Compact menus", with the Windows look on: read by the menus' measures, where there is no `App` at hand.
pub fn compact_menus() -> bool {
    COMPACT_MENUS.load(Ordering::Relaxed)
}

/// Settings › "Command bar height" (0: the look's own), read by the bar's measures.
pub fn command_bar_height() -> u8 {
    COMMAND_BAR_HEIGHT.load(Ordering::Relaxed)
}

pub fn solid_backdrop() -> bool {
    SOLID.load(Ordering::Relaxed) || (!materials_available() && !MAIN_ONLY.load(Ordering::Relaxed))
}

/// The materials a Windows without Windows 11's materials (Windows 10) still gives the MAIN window: Acrylic, as the old blur behind
/// it, and HyperGlass, which rustyfiles draws itself. Menus and popups stay plain there, since the blur-behind of a popup covered its
/// whole frame (issue 24). Mica is not among them: there it left the window see-through. Issue 78: a Windows 10 user found Acrylic
/// right on their PC and asked for it and HyperGlass back.
pub fn main_window_only(b: BackdropPref) -> bool {
    matches!(b, BackdropPref::Acrylic | BackdropPref::Glass)
}

/// Whether Windows gives windows a material (Mica, Mica Alt, Acrylic): from Windows 11 22H2 on (`rf_win::osver`, issue 24). Where it
/// does not, every window is the "Solid" look and every popup paints itself: see `theme::window_material` and `theme::popup_fill`.
/// `RUSTYFILES_NO_BACKDROP=1` answers "no" on any Windows, to look at that state on a developer's PC. Read once.
pub fn materials_available() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| std::env::var_os("RUSTYFILES_NO_BACKDROP").is_none() && rf_win::osver::system_backdrops())
}

/// Whether rustyfiles's own HyperGlass (D3D11 + DirectComposition) may attach to the dock and glass popups.
/// Unlike Windows's Mica and Acrylic (`materials_available`, Windows 11 22H2+), HyperGlass does not use
/// `DWMWA_SYSTEMBACKDROP_TYPE` and runs on Windows 10 via Desktop Duplication (as the main window already
/// does, issue 78). `RUSTYFILES_NO_BACKDROP=1` still turns it off for testing the plain fallback.
pub fn glass_available() -> bool {
    static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *V.get_or_init(|| glass_available_for(std::env::var_os("RUSTYFILES_NO_BACKDROP").is_some()))
}

/// Pure check behind [`glass_available`].
fn glass_available_for(no_backdrop_env: bool) -> bool {
    !no_backdrop_env
}

/// How strongly the app's own washes lie over the glass, 0..=100 (Settings > HyperGlass > Surface wash).
pub fn hg_surface() -> u8 {
    HG_SURFACE.load(Ordering::Relaxed)
}

/// Read by `Palette::for_window` without needing an `App`.
pub fn theme_override() -> ThemePref {
    match THEME.load(Ordering::Relaxed) {
        1 => ThemePref::Light,
        2 => ThemePref::Dark,
        3 => ThemePref::Black,
        _ => ThemePref::System,
    }
}

/// Read by the window palette without needing an `App`.
/// The setting "Compact window", read without an `App` (the bars' heights, see `theme::titlebar_h`).
pub fn compact_window() -> bool {
    COMPACT_WINDOW.load(Ordering::Relaxed)
}

/// The setting "Compact items", read without an `App` (the lists' row heights, see `FolderView::row_h`).
/// Lines of a name under a grid tile (`Settings::tile_name_lines`), read where there is no `App` at hand like `compact_items`.
pub fn tile_name_lines() -> u8 {
    TILE_NAME_LINES.load(std::sync::atomic::Ordering::Relaxed)
}

static TILE_NAME_LINES: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2);

pub fn compact_items() -> bool {
    COMPACT_ITEMS.load(Ordering::Relaxed)
}

pub fn windows_file_explorer_theme() -> bool {
    WINDOWS_FILE_EXPLORER_THEME.load(Ordering::Relaxed)
}

/// Effective light/dark appearance without needing an `App`. Kept in an atomic: rows ask for it on every frame,
/// and `ThemePref::System` would otherwise read the registry for every row. Icon packs use it to pick a matching variant.
/// The light / dark the app shows now. One cell for [`effective_dark`] and [`set_effective_dark`]: each had a `static` of its own, so a
/// change of Windows' appearance was written where nothing read it and the icon caches stayed on the start's.
static EFFECTIVE_DARK: OnceLock<std::sync::atomic::AtomicBool> = OnceLock::new();

pub fn effective_dark() -> bool {
    EFFECTIVE_DARK.get_or_init(|| std::sync::atomic::AtomicBool::new(compute_effective_dark())).load(Ordering::Relaxed)
}

fn compute_effective_dark() -> bool {
    match theme_override() {
        ThemePref::Light => false,
        ThemePref::Dark | ThemePref::Black => true,
        ThemePref::System => rf_win::accent::system_is_dark(),
    }
}

/// The OS appearance changed while the app was open. Only `System` follows it; a fixed choice stays.
pub fn system_appearance_changed(dark: bool) {
    if theme_override() == ThemePref::System {
        set_effective_dark(dark);
    }
}

fn set_effective_dark(dark: bool) {
    EFFECTIVE_DARK.get_or_init(|| std::sync::atomic::AtomicBool::new(dark)).store(dark, Ordering::Relaxed);
}

/// Read without a `Settings` global, for the shared icon cache.
pub fn icon_theme() -> IconThemePref {
    match ICON_THEME.load(Ordering::Relaxed) {
        2 => IconThemePref::Freedesktop,
        _ => IconThemePref::Windows,
    }
}

/// The selected freedesktop pack's folder name.
pub fn icon_theme_pack() -> String {
    ICON_PACK.get_or_init(|| parking_lot::RwLock::new(String::new())).read().clone()
}

pub fn path() -> Option<PathBuf> {
    app_dir().map(|d| d.join("settings.toml"))
}

/// What reading the settings file gave.
enum FileRead {
    /// There is no file (or no folder to keep one in): the defaults apply.
    Missing,
    /// The file could not be read or understood.
    Bad,
    Read(Box<Settings>),
}

const DEFAULT_SIDEBAR_WIDTH: f32 = 232.;
const DEFAULT_EXPLORER_SIDEBAR_WIDTH: f32 = 366.;

impl Settings {
    /// Keep a user's existing single sidebar width when first enabling the separate Explorer width.
    pub(crate) fn sidebar_width_for_explorer_look(&self) -> f32 {
        self.explorer_sidebar_width.unwrap_or_else(|| {
            if self.sidebar_width == DEFAULT_SIDEBAR_WIDTH {
                DEFAULT_EXPLORER_SIDEBAR_WIDTH
            } else {
                self.sidebar_width
            }
        })
    }

    /// Reads the file. With `set_aside_bad` an unreadable or broken file is moved aside (so the next save does not overwrite what
    /// the user may want to repair); a reader that is not the owner of the file leaves it where it is.
    fn read_file(set_aside_bad: bool) -> FileRead {
        let Some(p) = path() else { return FileRead::Missing };
        let text = match rf_core::read_config(&p) {
            Ok(t) => t,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return FileRead::Missing,
            Err(e) => {
                // unreadable (not UTF-8, locked): keep it aside rather than overwrite it
                log::warn!("settings: {e}");
                if set_aside_bad {
                    rf_core::backup_corrupt(&p);
                }
                return FileRead::Bad;
            }
        };
        match Self::parse_lenient(text.trim_start_matches('\u{feff}')) {
            Ok(s) => FileRead::Read(Box::new(s)),
            Err(e) => {
                // a typo while hand-editing must not cost the user every setting:
                // keep the file aside, start with defaults
                log::warn!("settings: {e}");
                if set_aside_bad {
                    rf_core::backup_corrupt(&p);
                }
                FileRead::Bad
            }
        }
    }

    pub fn load() -> Self {
        let mut s = match Self::read_file(true) {
            FileRead::Read(s) => *s,
            FileRead::Missing | FileRead::Bad => Settings::default(),
        };
        // what the file held, as a save would write it: the base of every later save's "what did THIS process change" (settings_merge.rs).
        // Taken before the migration, so a migrated value counts as this process's change and is written.
        *BASELINE.lock() = toml::Table::try_from(&s).ok();
        s.migrate();
        s.apply_side_effects();
        s
    }

    /// For a process that only follows the file (the dock): the settings as the file has them now, brought up to date but with no
    /// side effects yet (call [`Settings::apply_side_effects`] on the thread that wants them) and without touching the file. `None`
    /// when the file is there but cannot be read or understood right now (locked, mid-edit): the caller keeps what it has.
    /// Blocks briefly (the read retries a locked file): not for the UI thread.
    pub fn load_readonly() -> Option<Self> {
        Self::load_followed().map(|(s, _)| s)
    }

    /// [`Settings::load_readonly`] and the file as it was read (in the table form a save produces, before the migration): for a process
    /// that REPLACES its settings with the reload and so also has to move its baseline to this table ([`Settings::follow_file`]).
    pub fn load_followed() -> Option<(Self, toml::Table)> {
        let mut s = match Self::read_file(false) {
            FileRead::Read(s) => *s,
            FileRead::Missing => Settings::default(),
            FileRead::Bad => return None,
        };
        let file = toml::Table::try_from(&s).unwrap_or_default();
        s.migrate();
        Some((s, file))
    }

    /// The process has replaced its settings with a [`Settings::load_followed`]: what the file held then is what it now knows. Without
    /// this its next save would take every value the file got from another writer since start-up for its own change and write it back
    /// over whatever the file has become meanwhile (see `settings_merge::follow`).
    pub fn follow_file(file: toml::Table) {
        crate::settings_merge::follow(&BASELINE, file);
    }

    /// The material the windows really have: the chosen one, or "Solid" on a Windows without materials. The setting itself is left
    /// as it is (the same file may be read on a Windows 11 later).
    pub fn backdrop_in_use(&self) -> BackdropPref {
        if materials_available() || main_window_only(self.backdrop) { self.backdrop } else { BackdropPref::Solid }
    }

    /// Brings settings written by older versions up to date.
    fn migrate(&mut self) {
        // older files: "restore_session = false" means "start with a new tab"
        if !self.restore_session && self.startup == StartupPref::Continue {
            self.startup = StartupPref::NewTab;
            self.restore_session = true;
        }
        // "details" was the default before 0.3.3, so it says nothing about a choice: move it
        // once to "adaptive" (plain folders still open as details). Grid and columns stay.
        if !self.adaptive_offered {
            if self.default_view == DefaultView::Details {
                self.default_view = DefaultView::Adaptive;
            }
            self.adaptive_offered = true;
        }
        // The one dock switch (`dock/parts.rs`): a file with the dock on that came from before it and does not name a part cannot be
        // told from "the user chose this" (a save writes only what changed, so the old `false` defaults were often never written), and
        // nobody is given a keyboard hook or a hidden taskbar by an update: the parts it does not name are held off, the Dock page
        // says so, and "Hepsini aç" clears it. The marker makes this happen once; the first save writes it and the held values.
        if !self.dock_one_switch {
            for field in std::mem::take(&mut self.parts_unnamed_in_old_file) {
                if let Some(part) = crate::dock::parts::Part::from_field(&field) {
                    part.set_own_value(self, false);
                }
            }
            self.dock_one_switch = true;
        }
        self.parts_unnamed_in_old_file.clear();
    }

    /// Field by field: a value this version doesn't understand (a newer build's theme, a
    /// mistyped enum) falls back to its default instead of resetting every setting. Only a
    /// TOML syntax error fails.
    fn parse_lenient(text: &str) -> Result<Settings, toml::de::Error> {
        let table: toml::Table = toml::from_str(text)?;
        // (before the loop takes the table apart) a file from before the one switch that has the dock on: which parts does it not name?
        let unnamed: Vec<String> = if matches!(table.get("dock_enabled"), Some(toml::Value::Boolean(true))) && !table.contains_key("dock_one_switch") {
            crate::dock::parts::Part::ALL.iter().map(|p| p.field()).filter(|f| !table.contains_key(*f)).map(str::to_string).collect()
        } else {
            Vec::new()
        };
        let mut base = toml::Table::try_from(Settings::default()).unwrap_or_default();
        for (k, v) in table {
            let mut trial = base.clone();
            trial.insert(k.clone(), v);
            if Settings::deserialize(toml::Value::Table(trial.clone())).is_ok() {
                base = trial;
            } else {
                log::warn!("settings: ignoring invalid value for '{k}'");
                // A part's own value that cannot be read holds the part OFF, not on: the default of these is true, and a typo must not
                // install a keyboard hook or hide the taskbar. The Dock page lists it among the parts the file holds off.
                if crate::dock::parts::Part::from_field(&k).is_some() {
                    base.insert(k, toml::Value::Boolean(false));
                }
            }
        }
        let mut s = Settings::deserialize(toml::Value::Table(base)).unwrap_or_default();
        s.parts_unnamed_in_old_file = unnamed;
        Ok(s)
    }

    /// What `load` makes of a file's text (parsed, then brought up to date): for the tests of what an old file becomes.
    #[cfg(test)]
    pub(crate) fn parse_migrated(text: &str) -> Result<Settings, toml::de::Error> {
        let mut s = Self::parse_lenient(text)?;
        s.migrate();
        Ok(s)
    }

    /// The four values the engine takes, cut to 0..=100.
    pub fn hyperglass_look(&self) -> rf_win::glass::LookParams {
        rf_win::glass::LookParams {
            frost: f32::from(self.hg_frost.min(100)),
            tint: f32::from(self.hg_tint.min(100)),
            refraction: f32::from(self.hg_refraction.min(100)),
            saturation: f32::from(self.hg_saturation.min(100)),
        }
    }

    /// Back to the shipped look (the "Reset to defaults" button).
    pub fn reset_hyperglass(&mut self) {
        [self.hg_frost, self.hg_tint, self.hg_refraction, self.hg_saturation, self.hg_surface] = HG_DEFAULT;
    }

    /// Which items use Windows' icons in the preview pane: the independent override when set, otherwise [`Self::windows_placeholder_icons`].
    pub fn effective_windows_preview_icons(&self) -> PlaceholderIconsPref {
        self.windows_preview_icons.unwrap_or(self.windows_placeholder_icons)
    }

    /// For "Import settings".
    pub fn parse_lenient_pub(text: &str) -> Result<Settings, toml::de::Error> {
        Self::parse_lenient(text)
    }

    pub(crate) fn apply_side_effects(&self) {
        rf_win::dock::layout::set_radius(self.dock_corner_radius as f32);
        rf_win::dock::preview::set_size(self.dock_preview_size.max(1) as f32 / 100.0);
        sync_name_index(self.name_index, &self.index_excluded, self.index_hard_drives, &self.index_drives, &self.index_clouds);
        crate::i18n::set(self.language);
        crate::aliases::set(self.folder_aliases.clone());
        rf_win::openrules::set(self.open_rules.clone());
        rf_win::shell::set_terminal(&self.terminal_path);
        rf_win::git_program::set(&self.git_path);
        rf_win::drives::set_hidden(rf_win::drives::mask_of_letters(&self.hidden_drives));
        // (a text that is no colour is no colour: Windows' accent)
        rf_win::accent::set_override(rf_win::accent::parse_hex(&self.accent_color));
        crate::background::sync_tray(self.run_in_background);
        crate::background::sync_explorer_catch(self.catch_explorer_windows);
        crate::themes::set(&self.theme_folder);
        crate::quick_search::sync(self);
        // (the system's own short date and time for the "System" style and older dates, issue 59; set once)
        rf_core::format::set_system_format(rf_win::datefmt::short_date_time);
        rf_core::format::set_system_date(rf_win::datefmt::short_date);
        rf_core::format::set_date_style(match self.date_format {
            DatePref::Application => rf_core::format::DateStyle::Relative,
            DatePref::System => rf_core::format::DateStyle::Local,
            DatePref::Universal => rf_core::format::DateStyle::Universal,
        });
        rf_core::format::set_decimal_sizes(self.decimal_sizes);
        rf_core::format::set_binary_prefixes(self.binary_prefixes);
        SOLID.store(self.backdrop == BackdropPref::Solid, Ordering::Relaxed);
        HOME_RECENT_OWN_MENU.store(self.menu.home_recent_own_menu, Ordering::Relaxed);
        WINDOWS_PLACEHOLDER_ICONS.store(self.windows_placeholder_icons.as_u8(), Ordering::Relaxed);
        SOLID_CLEARTYPE.store(self.solid_cleartype, Ordering::Relaxed);
        EXPLORER_METRICS.store(self.windows_file_explorer_theme && self.explorer_metrics, Ordering::Relaxed);
        COMPACT_MENUS.store(self.windows_file_explorer_theme && self.compact_menus, Ordering::Relaxed);
        COMMAND_BAR_HEIGHT.store(self.command_bar_height, Ordering::Relaxed);
        MAIN_ONLY.store(main_window_only(self.backdrop), Ordering::Relaxed);
        // (the Dock's performance mode: no motion in the Dock's process, whatever the app's own setting)
        let dock_still = self.dock_performance && crate::background::DOCK_PROCESS.load(Ordering::Relaxed);
        ANIM.store(if dock_still { AnimPref::Off as u8 } else { self.animations as u8 }, Ordering::Relaxed);
        SCROLLBAR_ALWAYS.store(self.scrollbar_always, Ordering::Relaxed);
        // HyperGlass: the engine redraws every glass window once when the look changes, and does nothing for the same look again
        HG_SURFACE.store(self.hg_surface.min(100), Ordering::Relaxed);
        rf_win::glass::set_look(self.hyperglass_look());
        rf_win::glass::set_freeze_when_behind(self.hg_freeze_behind);
        gpui_windows::SMOOTH_SCROLL.store(self.smooth_scroll, Ordering::Relaxed);
        WINDOWS_FILE_EXPLORER_THEME.store(self.windows_file_explorer_theme, Ordering::Relaxed);
        COMPACT_WINDOW.store(self.compact_window, Ordering::Relaxed);
        COMPACT_ITEMS.store(self.compact_items, Ordering::Relaxed);
        TILE_NAME_LINES.store(self.tile_name_lines.clamp(2, 4), Ordering::Relaxed);
        crate::places::RECENT_ARRIVALS.store(self.recent_arrivals, Ordering::Relaxed);
        rf_win::dnd::set_plain_drag(match self.plain_drag {
            PlainDrag::Auto => 0,
            PlainDrag::Move => 1,
            PlainDrag::Copy => 2,
        });
        rf_win::embedded_thumb::set_enabled(self.own_thumbnails);
        let wanted_dark = match self.theme {
            ThemePref::System => None,
            ThemePref::Light => Some(false),
            ThemePref::Dark | ThemePref::Black => Some(true),
        };
        // (Windows' own menus shown by this process: the classic context menu, issue 211)
        rf_win::menu_theme::set_wanted(wanted_dark);
        // every GPUI window's frame and material from its first frame: a light app on a dark Windows opened its menus black and kept
        // them dark-tinted
        gpui_windows::set_frame_dark(wanted_dark);
        THEME.store(
            match self.theme {
                ThemePref::System => 0,
                ThemePref::Light => 1,
                ThemePref::Dark => 2,
                ThemePref::Black => 3,
            },
            Ordering::Relaxed,
        );
        set_effective_dark(compute_effective_dark());
        ICON_THEME.store(match self.icon_theme {
            IconThemePref::Freedesktop => 2,
            IconThemePref::Windows | IconThemePref::Legacy => 0,
        }, Ordering::Relaxed);
        *ICON_PACK.get_or_init(|| parking_lot::RwLock::new(String::new())).write() = self.icon_theme_pack.clone();
        // An explicit RUSTYFILES_RENDERER env var wins (debugging).
        if std::env::var_os("RUSTYFILES_RENDERER").is_none() {
            gpui_windows::hybrid::set_mode(renderer_mode(self.renderer, crate::background::DOCK_PROCESS.load(Ordering::Relaxed)));
        }
    }

    /// Writes the settings file: only what THIS process changed since it read the file, on top of what the file holds now (a change
    /// another writer made meanwhile survives, a key this build does not know survives, a process that changed nothing writes nothing).
    /// The rule and its tests are in `settings_merge.rs`.
    pub fn save(&self) {
        // One writer at a time inside this process (saves come from several threads); other processes are kept apart by the file lock.
        static LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
        let _one = LOCK.lock();
        let Some(p) = path() else { return };
        let mine = match toml::Table::try_from(self) {
            Ok(t) => t,
            Err(e) => {
                log::warn!("settings save: {e}");
                return;
            }
        };
        // (the baseline moves to what we hold once the save went through or needed no write; a save that did not happen keeps it, so the
        // next one carries the same changes again)
        crate::settings_merge::save_tracked(&BASELINE, &p, mine, || toml::Table::try_from(Settings::default()).unwrap_or_default());
    }
}

/// What this process last knew the settings file to hold (see [`Settings::save`]); `None` before the first `load`.
static BASELINE: crate::settings_merge::BaselineCell = parking_lot::Mutex::new(None);

/// Windows switched between light and dark. With the system's theme the toolkit's widgets (the tooltips' card, menus, inputs) must
/// follow as our palette does: their colours were set once, by [`apply_component_theme`] at start, and a hover tooltip kept the
/// old background under the new text (issue 954).
pub fn follow_system_appearance(cx: &mut App) {
    if matches!(cx.global::<Settings>().theme, ThemePref::System) {
        apply_component_theme(cx);
    }
}

/// Keeps gpui-component widgets (inputs, menus) in the same light/dark mode as our palette.
pub fn apply_component_theme(cx: &mut App) {
    use gpui_kit::component::theme::{Theme, ThemeMode};
    match cx.global::<Settings>().theme {
        ThemePref::Light => Theme::change(ThemeMode::Light, None, cx),
        ThemePref::Dark | ThemePref::Black => Theme::change(ThemeMode::Dark, None, cx),
        ThemePref::System => Theme::sync_system_appearance(None, cx),
    }
    // The component root paints the theme background under every window; keep it clear so
    // the Mica backdrop shows through (our own surfaces bring their own fills).
    Theme::update(cx, |t| t.background = gpui_kit::transparent_black());
    // Selected text in the inputs (the address bar, rename, search) in the accent: the toolkit's own light selection was all but
    // invisible on our light surfaces (issue 726).
    Theme::update(cx, |t| {
        let dark = t.mode.is_dark();
        let p = if dark { crate::theme::Palette::dark() } else { crate::theme::Palette::light() };
        t.selection = p.accent.opacity(if dark { 0.45 } else { 0.32 });
    });
    // the chosen font, else Windows 11's own typeface (optical sizes) when present
    let explorer_font = {
        let s = cx.global::<Settings>();
        s.windows_file_explorer_theme && s.explorer_metrics
    };
    if let Some(f) = cx.global::<Settings>().font.clone() {
        Theme::update(cx, |t| t.font_family = f.into());
    } else if explorer_font {
        // with Explorer's measures, its typeface too: the classic File Explorer writes in Segoe UI, not in Windows 11's Segoe UI
        // Variable (other shapes, side by side)
        Theme::update(cx, |t| t.font_family = "Segoe UI".into());
    } else if std::path::Path::new(r"C:\Windows\Fonts\SegUIVar.ttf").exists() {
        Theme::update(cx, |t| t.font_family = "Segoe UI Variable Text".into());
    }
}

/// Rasterize the common pack icons before the next paint. A new pack (or a new light/dark variant)
/// would otherwise make the first folder render parse every SVG on the UI thread.
pub fn prewarm_icon_pack(cx: &mut App) {
    let s = cx.global::<Settings>();
    if s.icon_theme != IconThemePref::Freedesktop || s.icon_theme_pack.is_empty() {
        return;
    }
    // COM known-folder lookups happen once here, before rows ask for their icon names.
    crate::icon_theme::prewarm_known_folders();
    let pack = s.icon_theme_pack.clone();
    cx.spawn(async move |cx| {
        cx.background_executor().spawn(async move { crate::icon_theme::prewarm(&pack) }).await;
        cx.update(|cx| cx.refresh_windows());
    })
    .detach();
}

/// Mutates the global settings, applies side effects, saves in the background and refreshes windows.
pub fn update(cx: &mut App, f: impl FnOnce(&mut Settings)) {
    let old = cx.global::<Settings>().clone();
    let explorer_theme_before = old.windows_file_explorer_theme;
    cx.update_global::<Settings, _>(|s, _| f(s));
    let s = cx.global::<Settings>().clone();
    // (DirectLook reads both from the file: the explorer theme, and background mode for whether it shows its own tray icon)
    let directlook_reload = s.windows_file_explorer_theme != explorer_theme_before || s.run_in_background != old.run_in_background;
    // the dialog DLL reads its per-app list from a file of its own (issue 371)
    if s.dialog_windows_apps != old.dialog_windows_apps {
        crate::picker::mirror_windows_apps(s.dialog_windows_apps.clone());
    }
    if s.state_api != old.state_api {
        crate::state_api::apply(s.state_api, cx);
    }
    s.apply_side_effects();
    apply_component_theme(cx);
    let icon_pack_changed = s.icon_theme != old.icon_theme || s.icon_theme_pack != old.icon_theme_pack;
    let theme_changed = s.theme != old.theme;
    std::thread::spawn(move || {
        s.save();
        // after the save, or DirectLook reads the old value (two tray icons once background mode was turned on)
        if directlook_reload {
            crate::look::ipc::send(crate::look::ipc::Msg::Reload, false);
        }
        // after the save: the dock process reads the file when it is told to reload
        crate::dock::control::sync_process(&s);
    });
    // (Ferry follows its settings: started, stopped, started anew, or shown to others differently)
    crate::ferry::apply(cx);
    if icon_pack_changed || theme_changed {
        // A newly installed pack must be visible without a restart, and a system-theme switch must pick the other variant.
        crate::icon_theme::clear_caches();
        crate::image_cache::clear_for_pack_change(cx);
    }
    if icon_pack_changed {
        crate::icon_theme::refresh_packs();
        prewarm_icon_pack(cx);
    }
    cx.refresh_windows();
}

/// Like [`update`] for a control that changes on every step of a drag (a slider): the change is applied and drawn at once, the file is
/// written once the changes have settled (the pane resize does the same), so a drag is not hundreds of writes.
pub fn update_live(cx: &mut App, f: impl FnOnce(&mut Settings)) {
    static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let old = cx.global::<Settings>().clone();
    cx.update_global::<Settings, _>(|s, _| f(s));
    cx.global::<Settings>().apply_side_effects();
    let look_changed = old.theme != cx.global::<Settings>().theme;
    if look_changed {
        crate::icon_theme::clear_caches();
        crate::image_cache::clear_for_pack_change(cx);
        prewarm_icon_pack(cx);
    }
    cx.refresh_windows();
    let mine = SERIAL.fetch_add(1, Ordering::Relaxed) + 1;
    cx.spawn(async move |cx| {
        cx.background_executor().timer(std::time::Duration::from_millis(400)).await;
        // a later step has its own timer: only the last one writes
        if SERIAL.load(Ordering::Relaxed) == mine {
            cx.update(|cx| {
                let snapshot = cx.global::<Settings>().clone();
                std::thread::spawn(move || {
                    snapshot.save();
                    // the running dock takes the look from the file: tell it, or it hears of a slider only at its next look at the file
                    crate::dock::control::sync_process(&snapshot);
                });
            });
        }
    })
    .detach();
}

#[cfg(test)]
mod tests {
    #[test]
    fn the_dock_stays_on_the_graphics_card_unless_the_user_chose_the_software_renderer() {
        use super::{RendererPref as P, renderer_mode};
        use gpui_windows::hybrid::RendererMode as M;
        assert_eq!(renderer_mode(P::Auto, false), M::Auto, "the file manager keeps the automatic switch");
        assert_eq!(renderer_mode(P::Auto, true), M::Gpu, "the dock never builds a software device on its own");
        assert_eq!(renderer_mode(P::Cpu, true), M::Cpu, "a choice made on purpose is kept");
        assert_eq!(renderer_mode(P::Gpu, true), M::Gpu);
        assert_eq!(renderer_mode(P::Gpu, false), M::Gpu);
        assert_eq!(renderer_mode(P::Cpu, false), M::Cpu);
    }

    #[test]
    fn details_moves_to_adaptive_once() {
        // a file from before the move: details becomes adaptive
        let mut s = super::Settings::parse_lenient("default_view = \"details\"\n").unwrap();
        s.migrate();
        assert_eq!(s.default_view, super::DefaultView::Adaptive);
        assert!(s.adaptive_offered);
        // chosen afterwards: stays
        let mut s = super::Settings::parse_lenient("default_view = \"details\"\nadaptive_offered = true\n").unwrap();
        s.migrate();
        assert_eq!(s.default_view, super::DefaultView::Details);
        // grid was a real choice
        let mut s = super::Settings::parse_lenient("default_view = \"grid\"\n").unwrap();
        s.migrate();
        assert_eq!(s.default_view, super::DefaultView::Grid);
    }

    use super::{Settings, ThemePref};

    #[test]
    fn roundtrip_and_defaults() {
        let s = Settings { show_hidden: true, session_tabs: vec!["C:\\".into()], ..Default::default() };
        let t = toml::to_string_pretty(&s).unwrap();
        let back: Settings = toml::from_str(&t).unwrap();
        assert!(back.show_hidden);
        assert_eq!(back.session_tabs, vec!["C:\\".to_string()]);
        // unknown/missing keys fall back to defaults
        let partial: Settings = toml::from_str("theme = \"dark\"").unwrap();
        assert_eq!(partial.theme, ThemePref::Dark);
        // a settings file written before icon themes keeps the shell icons
        assert_eq!(partial.icon_theme, super::IconThemePref::Windows);
        let legacy: Settings = toml::from_str("icon_theme = \"xp\"").unwrap();
        assert_eq!(legacy.icon_theme, super::IconThemePref::Legacy);
        assert!(partial.restore_session);
    }

    /// The Freedesktop choice and its pack survive the file; an unknown choice is inert, a bad pack is dropped.
    #[test]
    fn icon_theme_choice_and_pack_roundtrip() {
        let s = Settings { icon_theme: super::IconThemePref::Freedesktop, icon_theme_pack: "Papirus".into(), ..Default::default() };
        let back: Settings = toml::from_str(&toml::to_string_pretty(&s).unwrap()).unwrap();
        assert_eq!(back.icon_theme, super::IconThemePref::Freedesktop);
        assert_eq!(back.icon_theme_pack, "Papirus");
        let modern: Settings = toml::from_str("icon_theme = \"freedesktop\"\nicon_theme_pack = \"Adwaita\"\n").unwrap();
        assert_eq!(modern.icon_theme, super::IconThemePref::Freedesktop);
        assert_eq!(modern.icon_theme_pack, "Adwaita");
        let bad = Settings::parse_lenient("icon_theme = \"nope\"\nicon_theme_pack = 7\n").unwrap();
        assert_eq!(bad.icon_theme, super::IconThemePref::Legacy, "an unknown older value stays inert");
        assert!(bad.icon_theme_pack.is_empty(), "a non-string pack is ignored");
    }

    /// The second panes of the session survive the settings file, and a file from before them has none.
    #[test]
    fn the_sessions_second_panes_survive_the_file() {
        use super::SessionPane;
        let panes = vec![SessionPane { tab: 0, location: "D:\\Yedek".into(), active: true }, SessionPane { tab: 2, location: String::new(), active: false }];
        let s = Settings { session_tabs: vec!["C:\\".into(), "E:\\".into(), "F:\\".into()], session_panes: panes.clone(), ..Default::default() };
        let back: Settings = toml::from_str(&toml::to_string_pretty(&s).unwrap()).unwrap();
        assert_eq!(back.session_panes, panes);
        assert_eq!(back.session_tabs.len(), 3);
        let old: Settings = toml::from_str("session_tabs = [\"C:\\\\\"]").unwrap();
        assert!(old.session_panes.is_empty());
        // an entry that names only its tab reads with the rest at their defaults
        let part: Settings = toml::from_str("[[session_panes]]\ntab = 1").unwrap();
        assert_eq!(part.session_panes, [SessionPane { tab: 1, location: String::new(), active: false }]);
    }

    #[test]
    fn the_preview_position_leaves_no_key_until_it_is_asked_for() {
        use rf_core::previewpane::{BOTTOM_DEFAULT_H, PreviewPos};
        let d = Settings::default();
        assert_eq!((d.preview_position, d.preview_height), (PreviewPos::Right, BOTTOM_DEFAULT_H));
        let text = toml::to_string_pretty(&d).unwrap();
        assert!(!text.contains("preview_position") && !text.contains("preview_height"), "default settings must not gain keys");
        let bottom = Settings { preview_position: PreviewPos::Bottom, preview_height: 260., ..Default::default() };
        let text = toml::to_string_pretty(&bottom).unwrap();
        assert!(text.contains("preview_position = \"bottom\"") && text.contains("preview_height = 260.0"), "{text}");
        let back: Settings = toml::from_str(&text).unwrap();
        assert_eq!((back.preview_position, back.preview_height), (PreviewPos::Bottom, 260.));
        // an unknown word does not break the file
        let odd: Settings = toml::from_str("preview_position = \"left\"
show_hidden = true").unwrap();
        assert_eq!(odd.preview_position, PreviewPos::Right);
        assert!(odd.show_hidden);
    }

    #[test]
    fn menu_prefs_default_to_true() {
        use crate::settings::MenuPrefs;
        let prefs = MenuPrefs::default();
        assert!(prefs.open, "Open should be visible by default");
        assert!(prefs.properties, "Properties should be visible by default");
        assert!(prefs.refresh, "Refresh should be visible by default");
        assert!(prefs.show_hidden, "Show hidden items should be visible by default");
        assert!(!prefs.open_in_background_tab, "Open in new tab in background is off by default: \"Open in new tab\" stays a side button");
    }
}

/// Where data that can be rebuilt lives (remembered folder sizes): `%LOCALAPPDATA%\rustyfiles`,
/// or `RUSTYFILES_CONFIG_DIR` when set, so test copies keep their data apart.
pub fn local_data_dir() -> Option<std::path::PathBuf> {
    if let Some(d) = std::env::var_os("RUSTYFILES_CONFIG_DIR").filter(|d| !d.is_empty()) {
        return Some(std::path::PathBuf::from(d));
    }
    // the portable copy keeps everything in its own folder (issue 71)
    if let Some(d) = rf_win::portable::data_dir() {
        return Some(d);
    }
    dirs::data_local_dir().map(|d| d.join("rustyfiles"))
}

/// `%APPDATA%\rustyfiles`, or `RUSTYFILES_CONFIG_DIR` when set (portable use, tests).
pub fn app_dir() -> Option<std::path::PathBuf> {
    if let Some(d) = std::env::var_os("RUSTYFILES_CONFIG_DIR").filter(|d| !d.is_empty()) {
        return Some(std::path::PathBuf::from(d));
    }
    // the portable copy: its own `data` folder (`rf_win::portable`, issue 71)
    if let Some(d) = rf_win::portable::data_dir() {
        return Some(d);
    }
    dirs::config_dir().map(|d| d.join("rustyfiles"))
}

#[cfg(test)]
mod lenient_tests {
    use super::{DEFAULT_EXPLORER_SIDEBAR_WIDTH, DEFAULT_SIDEBAR_WIDTH, Settings};

    #[test]
    fn popup_material_defaults_to_automatic_and_parses_saved_choices() {
        use super::MenuMaterial;
        assert_eq!(Settings::parse_lenient("").unwrap().menu_material, MenuMaterial::Automatic);
        for (stored, expected) in [
            ("auto", MenuMaterial::Automatic),
            ("automatic", MenuMaterial::Automatic),
            ("mica", MenuMaterial::Mica),
            ("micaalt", MenuMaterial::MicaAlt),
            ("acrylic", MenuMaterial::Acrylic),
            ("solid", MenuMaterial::Solid),
            ("glass", MenuMaterial::Glass),
        ] {
            assert_eq!(Settings::parse_lenient(&format!("menu_material = \"{stored}\"")).unwrap().menu_material, expected);
        }
    }

    #[test]
    fn popup_material_automatic_preserves_host_and_explorer_appearance() {
        use super::MenuMaterial::{Automatic, Glass, Mica, Solid};
        use super::WindowBackgroundAppearance::{Blurred, MicaBackdrop, Opaque, Transparent};

        assert_eq!(Automatic.resolve(false, false, true, true), (false, Blurred));
        assert_eq!(Automatic.resolve(true, false, true, true), (true, Transparent));
        assert_eq!(Automatic.resolve(true, true, true, true), (false, Opaque));
        assert_eq!(Automatic.resolve(false, true, false, true), (false, Opaque));
        assert_eq!(Automatic.resolve(false, false, false, true), (false, Blurred));
        assert_eq!(Mica.resolve(true, true, true, true), (false, MicaBackdrop));
        assert_eq!(Mica.resolve(true, true, false, true), (false, Opaque));
        assert_eq!(Solid.resolve(true, false, true, true), (false, Opaque));
        assert_eq!(Glass.resolve(false, true, true, true), (true, Transparent));
        assert_eq!(Glass.resolve(false, true, false, true), (true, Transparent));
        assert_eq!(Glass.resolve(true, false, false, false), (false, Opaque));
    }

    #[test]
    fn windows_file_explorer_theme_defaults_off_and_round_trips() {
        assert!(!Settings::default().windows_file_explorer_theme);
        assert_eq!(Settings::default().sidebar_width, DEFAULT_SIDEBAR_WIDTH);
        assert_eq!(Settings::default().explorer_sidebar_width, None);
        assert_eq!(Settings::default().sidebar_width_for_explorer_look(), DEFAULT_EXPLORER_SIDEBAR_WIDTH);
        assert_eq!(
            Settings { sidebar_width: 420., ..Default::default() }.sidebar_width_for_explorer_look(),
            420.
        );
        assert!(!Settings::parse_lenient("theme = \"dark\"\n").unwrap().windows_file_explorer_theme, "older settings files omit the new option");

        let enabled = Settings { windows_file_explorer_theme: true, explorer_sidebar_width: Some(410.), ..Default::default() };
        let text = toml::to_string_pretty(&enabled).unwrap();
        assert!(text.contains("windows_file_explorer_theme = true"));
        let back = Settings::parse_lenient(&text).unwrap();
        assert!(back.windows_file_explorer_theme);
        assert_eq!(back.explorer_sidebar_width, Some(410.));
        assert_eq!(back.sidebar_width_for_explorer_look(), 410.);
    }

    #[test]
    fn unknown_values_fall_back_per_field() {
        let s = Settings::parse_lenient("theme = \"mor\"
show_hidden = true
sidebar_width = \"geniş\"
yeni_alan = 3").unwrap();
        assert!(s.show_hidden, "valid fields survive");
        assert_eq!(s.sidebar_width, Settings::default().sidebar_width);
        assert!(Settings::parse_lenient("[[[bozuk").is_err(), "syntax errors still fail");
    }

    #[test]
    fn glass_backdrop_round_trips() {
        use super::BackdropPref;
        let s = Settings { backdrop: BackdropPref::Glass, ..Default::default() };
        let text = toml::to_string_pretty(&s).unwrap();
        assert!(text.contains("backdrop = \"glass\""), "serialized as \"glass\": {text}");
        let back: Settings = toml::from_str(&text).unwrap();
        assert_eq!(back.backdrop, BackdropPref::Glass);
        // through the loader the app uses
        assert_eq!(Settings::parse_lenient(&text).unwrap().backdrop, BackdropPref::Glass);
        // the default stays Mica
        assert_eq!(Settings::default().backdrop, BackdropPref::Mica);
    }

    #[test]
    fn hyperglass_defaults_match_the_engine_and_the_shipped_look() {
        let d = Settings::default();
        let engine = rf_win::glass::LookParams::DEFAULT;
        assert_eq!(d.hyperglass_look(), engine, "the settings default is the engine's default");
        assert_eq!(super::HG_DEFAULT.map(f32::from)[..4], [engine.frost, engine.tint, engine.refraction, engine.saturation]);
        assert_eq!(d.hg_surface, 50);
        assert_eq!(super::hg_surface(), 50, "the palette's atomic starts at the default as well");
    }

    #[test]
    fn hyperglass_values_round_trip() {
        let s = Settings { hg_frost: 0, hg_tint: 100, hg_refraction: 13, hg_saturation: 77, hg_surface: 5, ..Default::default() };
        let text = toml::to_string_pretty(&s).unwrap();
        let back = Settings::parse_lenient(&text).unwrap();
        assert_eq!((back.hg_frost, back.hg_tint, back.hg_refraction, back.hg_saturation, back.hg_surface), (0, 100, 13, 77, 5));
        // an old file has none of them: every one is the default
        let old = Settings::parse_lenient("theme = \"dark\"
").unwrap();
        assert_eq!(super::HG_DEFAULT, [old.hg_frost, old.hg_tint, old.hg_refraction, old.hg_saturation, old.hg_surface]);
    }

    #[test]
    fn a_bad_hyperglass_value_costs_only_that_field() {
        // a negative number, a word, a float and a number too big for the field: each falls back alone, the neighbours and the other
        // settings survive
        let s = Settings::parse_lenient(
            "hg_frost = -3
hg_tint = \"cok\"
hg_refraction = 12.5
hg_saturation = 9999
hg_surface = 80
show_hidden = true
",
        )
        .unwrap();
        assert_eq!(s.hg_frost, super::HG_DEFAULT[0]);
        assert_eq!(s.hg_tint, super::HG_DEFAULT[1]);
        assert_eq!(s.hg_refraction, super::HG_DEFAULT[2]);
        assert_eq!(s.hg_saturation, super::HG_DEFAULT[3]);
        assert_eq!(s.hg_surface, 80, "the good value next to the bad ones is kept");
        assert!(s.show_hidden);
    }

    #[test]
    fn a_hyperglass_value_above_100_is_cut_when_used() {
        let s = Settings::parse_lenient("hg_frost = 200
hg_tint = 101
").unwrap();
        assert_eq!((s.hg_frost, s.hg_tint), (200, 101), "the file's number is kept as it is");
        let look = s.hyperglass_look();
        assert_eq!((look.frost, look.tint), (100.0, 100.0));
    }

    #[test]
    fn resetting_hyperglass_leaves_the_rest_alone() {
        let mut s = Settings { hg_frost: 1, hg_tint: 2, hg_refraction: 3, hg_saturation: 4, hg_surface: 5, show_hidden: true, ..Default::default() };
        s.reset_hyperglass();
        assert_eq!(super::HG_DEFAULT, [s.hg_frost, s.hg_tint, s.hg_refraction, s.hg_saturation, s.hg_surface]);
        assert!(s.show_hidden);
    }

    #[test]
    fn unknown_backdrop_value_costs_only_that_field() {
        // what a version without Glass meets after the user picked it and went back: the value
        // is dropped (Mica), every other setting of the file survives
        use super::BackdropPref;
        let s = Settings::parse_lenient("backdrop = \"cam\"
show_hidden = true
theme = \"dark\"
").unwrap();
        assert_eq!(s.backdrop, BackdropPref::Mica);
        assert!(s.show_hidden);
        assert_eq!(s.theme, super::ThemePref::Dark);
    }

    #[test]
    fn placeholder_icons_applies_by_item_kind() {
        use super::PlaceholderIconsPref as P;
        assert!(!P::Off.applies(true) && !P::Off.applies(false));
        assert!(P::Folders.applies(true) && !P::Folders.applies(false));
        assert!(!P::Files.applies(true) && P::Files.applies(false));
        assert!(P::All.applies(true) && P::All.applies(false));
        for pref in [P::Off, P::Folders, P::Files, P::All] {
            assert_eq!(P::from_u8(pref.as_u8()), pref);
        }
        assert_eq!(P::from_u8(99), P::Off);
    }

    #[test]
    fn placeholder_icons_round_trip_and_legacy_booleans() {
        use super::PlaceholderIconsPref as P;
        // legacy booleans still load and save as booleans
        assert_eq!(Settings::parse_lenient("windows_placeholder_icons = false\n").unwrap().windows_placeholder_icons, P::Off);
        assert_eq!(Settings::parse_lenient("windows_placeholder_icons = true\n").unwrap().windows_placeholder_icons, P::All);
        assert!(toml::to_string_pretty(&Settings { windows_placeholder_icons: P::Off, ..Default::default() }).unwrap().contains("windows_placeholder_icons = false"));
        assert!(toml::to_string_pretty(&Settings { windows_placeholder_icons: P::All, ..Default::default() }).unwrap().contains("windows_placeholder_icons = true"));
        // string modes round-trip cleanly
        for (pref, expected) in [(P::Folders, "windows_placeholder_icons = \"folders\""), (P::Files, "windows_placeholder_icons = \"files\"")] {
            let text = toml::to_string_pretty(&Settings { windows_placeholder_icons: pref, ..Default::default() }).unwrap();
            assert!(text.contains(expected), "{text}");
            assert_eq!(Settings::parse_lenient(&text).unwrap().windows_placeholder_icons, pref);
        }
        assert_eq!(Settings::parse_lenient("windows_placeholder_icons = \"off\"\n").unwrap().windows_placeholder_icons, P::Off);
        assert_eq!(Settings::parse_lenient("windows_placeholder_icons = \"all\"\n").unwrap().windows_placeholder_icons, P::All);
        // unknown value falls back to Off without losing neighbouring fields
        let bad = Settings::parse_lenient("windows_placeholder_icons = \"bogus\"\nshow_hidden = true\n").unwrap();
        assert_eq!(bad.windows_placeholder_icons, P::Off);
        assert!(bad.show_hidden);
        // preview pane override defaults to following windows_placeholder_icons and leaves no key until set
        let legacy_on = Settings::parse_lenient("windows_placeholder_icons = true\n").unwrap();
        assert_eq!(legacy_on.windows_preview_icons, None);
        assert_eq!(legacy_on.effective_windows_preview_icons(), P::All);
        assert!(!toml::to_string_pretty(&legacy_on).unwrap().contains("windows_preview_icons"));
        let split = Settings { windows_placeholder_icons: P::Folders, windows_preview_icons: Some(P::Off), ..Default::default() };
        assert_eq!(split.effective_windows_preview_icons(), P::Off);
        let split_text = toml::to_string_pretty(&split).unwrap();
        assert!(split_text.contains("windows_preview_icons = false"), "{split_text}");
        let split_back = Settings::parse_lenient(&split_text).unwrap();
        assert_eq!((split_back.windows_placeholder_icons, split_back.windows_preview_icons), (P::Folders, Some(P::Off)));
    }
}

/// Starts or stops the name index when the setting changes. The first start waits a few seconds
/// so it never competes with opening the window.
fn sync_name_index(on: bool, excluded: &[String], hard_drives: bool, drives: &[String], clouds: &[String]) {
    use std::sync::atomic::{AtomicU8, Ordering};
    // DirectLook reads these settings too: the index is rustyfiles' (a second indexer would walk
    // every drive again and write the same index files)
    if crate::background::side_process() {
        return;
    }
    // 0 = not decided yet, 1 = off, 2 = on
    static STATE: AtomicU8 = AtomicU8::new(0);
    static EXCLUDED: parking_lot::Mutex<Option<Vec<String>>> = parking_lot::Mutex::new(None);
    static HARD_DRIVES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
    static DRIVES: parking_lot::Mutex<Option<Vec<String>>> = parking_lot::Mutex::new(None);
    static CLOUDS: parking_lot::Mutex<Option<Vec<String>>> = parking_lot::Mutex::new(None);
    let list_changed = {
        let mut e = EXCLUDED.lock();
        let excluded_changed = e.as_deref() != Some(excluded);
        let mut c = CLOUDS.lock();
        let clouds_changed = c.as_deref() != Some(clouds);
        if clouds_changed {
            *c = Some(clouds.to_vec());
        }
        // the cloud folders not picked for the index are left out of their drive's walk like
        // folders the user excluded (the walk does enter cloud folders, issue 885); the skip
        // list is rebuilt only when one of its two sources changed
        if excluded_changed || clouds_changed {
            let picked: Vec<String> = clouds.iter().map(|s| s.trim_end_matches('\\').to_lowercase()).collect();
            let mut skip: Vec<std::path::PathBuf> = excluded.iter().map(std::path::PathBuf::from).collect();
            for r in rf_win::syncroots::list() {
                let p = r.path.to_string_lossy().trim_end_matches('\\').to_lowercase();
                if !picked.iter().any(|k| *k == p) {
                    skip.push(r.path.clone());
                }
            }
            rf_win::nameindex::set_excluded(&skip);
        }
        if excluded_changed {
            *e = Some(excluded.to_vec());
        }
        // (hard drives in or out: another set of roots, started anew like a changed list)
        let mut changed = HARD_DRIVES.swap(hard_drives, Ordering::Relaxed) != hard_drives || excluded_changed || clouds_changed;
        let mut d = DRIVES.lock();
        if d.as_deref() != Some(drives) {
            *d = Some(drives.to_vec());
            // a letter taken in or out is another set of roots, started anew like a changed list
            changed = true;
        }
        changed
    };
    let want = if on { 2 } else { 1 };
    let was = STATE.swap(want, Ordering::Relaxed);
    // a changed exclusion list rebuilds a running index (the fresh walk leaves the folders out); so do hard drives taken in or out
    if was == want && !(on && list_changed && was != 0) {
        return;
    }
    if !on {
        std::thread::spawn(rf_win::indexer::stop);
        return;
    }
    let delay = if was == 0 { 5 } else { 0 };
    let drives = drives.to_vec();
    let clouds = clouds.to_vec();
    std::thread::spawn(move || {
        std::thread::sleep(std::time::Duration::from_secs(delay));
        // extra instances (tests, the speed test's) leave it to the main one
        // (RUSTYFILES_INDEX=1 indexes there too, for testing)
        let extra = (std::env::var_os("RUSTYFILES_MULTI_INSTANCE").is_some() || std::env::var_os("RUSTYFILES_INSTANCE").is_some()) && std::env::var_os("RUSTYFILES_INDEX").is_none();
        if STATE.load(Ordering::Relaxed) != 2 || std::env::var_os("RUSTYFILES_NO_INDEX").is_some() || extra {
            return;
        }
        // a copy with its own settings folder (tests, portable) keeps its index there too
        let dir = match std::env::var_os("RUSTYFILES_CONFIG_DIR").map(std::path::PathBuf::from).or_else(rf_win::portable::data_dir) {
            Some(cfg) => cfg.join("index"),
            None => std::env::var_os("LOCALAPPDATA").map_or_else(std::env::temp_dir, std::path::PathBuf::from).join("rustyfiles").join("index"),
        };
        // RUSTYFILES_INDEX_ROOTS="E:\;F:\" picks the roots (testing)
        let roots = match std::env::var("RUSTYFILES_INDEX_ROOTS") {
            Ok(v) => v.split(';').filter(|s| !s.is_empty()).map(std::path::PathBuf::from).collect(),
            // the drives picked one by one (empty: the automatic set — every local fixed
            // NTFS/ReFS drive, plus hard drives per the setting; network drives only when
            // picked) and the cloud folders picked on top (issue 885)
            Err(_) => {
                let mut roots = if drives.is_empty() { rf_win::indexer::local_roots(HARD_DRIVES.load(Ordering::Relaxed)) } else { rf_win::indexer::roots_for_letters(&drives) };
                roots.extend(clouds.iter().map(std::path::PathBuf::from));
                roots
            }
        };
        rf_win::indexer::start(roots, dir);
    });
}

#[cfg(test)]
mod dock_tests {
    use super::Settings;

    #[test]
    fn the_dock_is_off_keeps_windows_out_from_under_it_and_has_no_city() {
        let s = Settings::default();
        assert!(!s.dock_enabled, "experimental: off until asked for");
        assert!(s.dock_reserve);
        assert!(s.dock_weather_city.is_empty(), "no city, so no weather request");
        // a settings file from before the dock has none of the keys: the same defaults
        let old = Settings::parse_lenient("theme = \"dark\"\n").unwrap();
        assert!(!old.dock_enabled && old.dock_reserve && old.dock_weather_city.is_empty());
    }

    #[test]
    fn the_dock_opens_our_own_control_centre_unless_told_not_to() {
        assert!(Settings::default().dock_own_control_centre);
        assert!(Settings::parse_lenient("theme = \"dark\"
").unwrap().dock_own_control_centre, "a file from before it: on");
        let off = Settings { dock_own_control_centre: false, ..Default::default() };
        let back = Settings::parse_lenient(&toml::to_string_pretty(&off).unwrap()).unwrap();
        assert!(!back.dock_own_control_centre);
        assert!(Settings::parse_lenient("dock_own_control_centre = 3
").unwrap().dock_own_control_centre, "a wrong value falls back to the default");
    }

    #[test]
    fn the_dock_opens_our_own_calendar_and_notification_panels_unless_told_not_to() {
        let d = Settings::default();
        assert!(d.dock_own_calendar && d.dock_own_notifications);
        // a settings file from before them has neither key: both on
        let old = Settings::parse_lenient("theme = \"dark\"
").unwrap();
        assert!(old.dock_own_calendar && old.dock_own_notifications, "a file from before them: on");
        let off = Settings { dock_own_calendar: false, dock_own_notifications: false, ..Default::default() };
        let back = Settings::parse_lenient(&toml::to_string_pretty(&off).unwrap()).unwrap();
        assert!(!back.dock_own_calendar && !back.dock_own_notifications, "off survives a save and a load");
        let wrong = Settings::parse_lenient("dock_own_calendar = \"nein\"
dock_own_notifications = 3
").unwrap();
        assert!(wrong.dock_own_calendar && wrong.dock_own_notifications, "wrong values fall back to the default");
    }

    /// The weather from the PC's position is a mode nobody gets without asking: off by default, off for a file from before it, and a
    /// wrong value costs nothing.
    #[test]
    fn the_weather_from_the_position_is_off_unless_asked_for() {
        assert!(!Settings::default().dock_weather_location);
        assert!(!Settings::parse_lenient("theme = \"dark\"\n").unwrap().dock_weather_location, "a file from before it: off");
        let on = Settings { dock_weather_location: true, ..Default::default() };
        let text = toml::to_string_pretty(&on).unwrap();
        assert!(Settings::parse_lenient(&text).unwrap().dock_weather_location);
        assert!(!Settings::parse_lenient("dock_weather_location = \"yes\"\n").unwrap().dock_weather_location, "a wrong value falls back to off");
        // and no coordinates are ever part of the settings file
        assert!(!text.to_lowercase().contains("latitude") && !text.to_lowercase().contains("longitude"));
    }

    #[test]
    fn the_dock_opens_our_own_start_unless_told_not_to() {
        assert!(Settings::default().dock_own_start);
        assert!(Settings::parse_lenient("theme = \"dark\"\n").unwrap().dock_own_start, "a file from before it: on");
        let off = Settings { dock_own_start: false, ..Default::default() };
        let back = Settings::parse_lenient(&toml::to_string_pretty(&off).unwrap()).unwrap();
        assert!(!back.dock_own_start);
        assert!(Settings::parse_lenient("dock_own_start = \"nein\"\n").unwrap().dock_own_start, "a wrong value falls back to the default");
    }

    #[test]
    fn the_dock_settings_round_trip() {
        use super::DockPosition;
        assert_eq!(Settings::default().dock_position, DockPosition::Bottom);
        let s = Settings { dock_enabled: true, dock_reserve: false, dock_position: DockPosition::Right, dock_weather_city: "Erzincan".into(), ..Default::default() };
        let text = toml::to_string_pretty(&s).unwrap();
        let back = Settings::parse_lenient(&text).unwrap();
        assert!(back.dock_enabled);
        assert!(!back.dock_reserve);
        assert_eq!(back.dock_weather_city, "Erzincan");
        assert_eq!(back.dock_position, DockPosition::Right);
        assert_eq!(back.dock_position.edge(), rf_win::dock::layout::DockEdge::Right);
    }

    #[test]
    fn the_magnification_is_full_by_default_and_round_trips() {
        use super::DockMagnify;
        use rf_win::dock::magnify::Strength;
        assert_eq!(Settings::default().dock_magnify, DockMagnify::Full);
        // the user's own programs for a kind of file: none at first, and a list comes back from the file as it was written
        assert!(Settings::default().open_rules.is_empty());
        // the accent: Windows' own until the user writes a colour, and a text that is no colour is none
        assert!(Settings::default().accent_color.is_empty());
        assert_eq!(Settings::parse_lenient("accent_color = '#F7630C'\n").unwrap().accent_color, "#F7630C");
        assert_eq!(rf_win::accent::parse_hex(&Settings::parse_lenient("accent_color = 'turuncu'\n").unwrap().accent_color), None);
        let rule = rf_core::openrules::OpenRule { exts: vec!["dll".into(), "sys".into()], programs: vec![r"C:\Araçlar\dnSpy.exe".into()], double_click: false };
        let text = toml::to_string_pretty(&Settings { open_rules: vec![rule.clone()], ..Default::default() }).unwrap();
        assert!(text.contains("[[open_rules]]"), "{text}");
        assert_eq!(Settings::parse_lenient(&text).unwrap().open_rules, vec![rule]);
        let by_hand = Settings::parse_lenient("[[open_rules]]\nexts = [\"js\"]\nprograms = ['C:\\x.exe']\n").unwrap();
        assert!(by_hand.open_rules[0].double_click, "a list written by hand without the switch opens on a double click");
        // the wheel over an icon: on, also for a file from before, and it can be switched off
        assert!(Settings::default().dock_scroll_volume);
        assert!(Settings::parse_lenient("theme = \"dark\"\n").unwrap().dock_scroll_volume);
        assert!(!Settings::parse_lenient("dock_scroll_volume = false\n").unwrap().dock_scroll_volume);
        assert_eq!(Settings::parse_lenient("theme = \"dark\"\n").unwrap().dock_magnify, DockMagnify::Full, "a file from before has none: the default");
        for (m, s, name) in [(DockMagnify::Off, Strength::Off, "off"), (DockMagnify::Subtle, Strength::Subtle, "subtle"), (DockMagnify::Full, Strength::Full, "full")] {
            assert_eq!(m.strength(), s);
            let text = toml::to_string_pretty(&Settings { dock_magnify: m, ..Default::default() }).unwrap();
            assert!(text.contains(&format!("dock_magnify = \"{name}\"")), "{text}");
            assert_eq!(Settings::parse_lenient(&text).unwrap().dock_magnify, m);
        }
        // a value this version does not know falls back to the default, the rest of the file is kept
        let s = Settings::parse_lenient("dock_magnify = \"huge\"\nshow_hidden = true\n").unwrap();
        assert_eq!(s.dock_magnify, DockMagnify::Full);
        assert!(s.show_hidden);
    }

    #[test]
    fn a_wrong_dock_value_falls_back_without_costing_the_other_settings() {
        let s = Settings::parse_lenient("dock_enabled = \"evet\"\ndock_reserve = false\nshow_hidden = true\n").unwrap();
        assert!(!s.dock_enabled);
        assert!(!s.dock_reserve);
        assert!(s.show_hidden);
    }

    #[test]
    fn ctrl_number_tab_settings_default_on_and_round_trip() {
        let d = Settings::default();
        assert!(d.ctrl_number_tabs);
        assert!(d.ctrl_9_last_tab);

        let older = Settings::parse_lenient("theme = \"dark\"\n").unwrap();
        assert!(older.ctrl_number_tabs);
        assert!(older.ctrl_9_last_tab);

        let custom = Settings { ctrl_number_tabs: false, ctrl_9_last_tab: false, ..Default::default() };
        let text = toml::to_string_pretty(&custom).unwrap();
        let parsed = Settings::parse_lenient(&text).unwrap();
        assert!(!parsed.ctrl_number_tabs);
        assert!(!parsed.ctrl_9_last_tab);
    }

    #[test]
    fn glass_availability_only_depends_on_the_no_backdrop_override() {
        assert!(super::glass_available_for(false));
        assert!(!super::glass_available_for(true));
    }
}