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.

252 KB
Raw Blame
//! Settings page (Location::Settings), laid out like Files: a navigation column on the left,
//! one page of cards on the right. Every card is one setting: icon, title, optional
//! description, and its control (a switch, a drop-down that opens our Acrylic menu, buttons) —
//! or an expander with child settings.

use std::collections::HashSet;

use gpui_kit::assets::IconName as L;
use gpui_kit::component::{Icon, h_flex, v_flex};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use gpui_windows::hybrid;

use crate::fluent_menu::{self, Item, Menu, MenuIcon};
use crate::select_box::{Choice, select_box};
use crate::i18n::Lang;
use crate::settings::{
    self, AnimPref, BackdropPref, ClickPref, DatePref, DefaultView, DeletePref, IconThemePref, IdePref, PlaceholderIconsPref, RendererPref, Settings, StartupPref,
    ThemePref,
};
use crate::t;
use crate::look::config::LookSettings;
use crate::theme::{self, Palette};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Page {
    General,
    Appearance,
    Dock,
    Desktop,
    Layout,
    Files,
    FileTypes,
    Actions,
    Tags,
    Look,
    Ferry,
    Search,
    Addons,
    Advanced,
    Speed,
    Organizer,
    About,
}

const PAGES: [(Page, L, &str); 17] = [
    (Page::General, L::Settings, "Genel"),
    (Page::Appearance, L::Palette, "Görünüm"),
    (Page::Dock, L::PanelBottom, "Dock"),
    (Page::Desktop, L::Monitor, "Masaüstü"),
    (Page::Layout, L::LayoutGrid, "Sayfa düzeni"),
    (Page::Files, L::Folder, "Dosyalar ve klasörler"),
    (Page::FileTypes, L::FileType, "Dosya türleri"),
    (Page::Actions, L::Keyboard, "Eylemler"),
    (Page::Tags, L::Tag, "Etiketler"),
    (Page::Look, L::Eye, "DirectLook"),
    (Page::Search, L::Search, "HyperSearch"),
    (Page::Ferry, L::Send, "Ferry"),
    (Page::Addons, L::Package, "Eklentiler"),
    (Page::Advanced, L::Wrench, "Gelişmiş"),
    (Page::Speed, L::Gauge, "Hız testi"),
    (Page::Organizer, L::WandSparkles, "Dosya düzenleyici"),
    (Page::About, L::Info, "Hakkında"),
];

/// The pages that are experimental: marked with a small "Deneysel" pill in the page list and "(deneysel)" in their title. The mark is
/// NOT part of the page name in [`PAGES`], so the search and the translations still know the pages as "Dock" and "Masaüstü".
fn experimental(page: Page) -> bool {
    // (the Dock and the desktop are no longer experimental since 1.0.7)
    matches!(page, Page::Ferry)
}

/// The heading of a page: its name, and "(deneysel)" after it for an experimental page.
fn page_title(page: Page, name: &str) -> String {
    if experimental(page) { format!("{name} ({})", t!("deneysel")) } else { name.to_string() }
}

/// The quiet pill next to an experimental page's name in the page list (the same for every such page).
fn experimental_pill(p: &Palette) -> Div {
    div().flex_shrink_0().whitespace_nowrap().px(px(6.)).py(px(1.)).rounded_full().border_1().border_color(p.border).text_size(px(10.)).text_color(p.text_secondary).child(t!("Deneysel"))
}

/// Which page is shown and which expanders are open (kept while the app runs).
struct Ui {
    page: Page,
    open: HashSet<&'static str>,
    /// The search box above the pages (made at the first draw: it needs a window).
    search: Option<Entity<gpui_kit::component::input::InputState>>,
    /// One focus handle per HyperGlass slider (made at the first draw, kept so the arrow keys have something to be focused on).
    hg_focus: Vec<FocusHandle>,
    /// How wide the Settings pane was at its last paint, logical px (0: not painted yet). The list of pages is drawn as a strip of
    /// icons when the pane is narrow ([`nav_is_strip`]).
    pane_w: f32,
}
impl Global for Ui {}

/// The pane's width under which the list of pages is a strip of icons, and the widths of the list in its two forms.
const NAV_STRIP_BELOW: f32 = 640.0;
const NAV_W: f32 = 232.0;
const NAV_STRIP_W: f32 = 60.0;

/// Whether the list of pages is drawn as a strip of icons: the pane is narrow, and the full list (232 px) would leave the settings
/// themselves a column too thin to read (the user's pictures: the app's sidebar and this list took 464 px of a 736 px window, and the
/// settings had 200). A pane that has not been measured yet gets the full list.
pub(crate) fn nav_is_strip(pane_w: f32) -> bool {
    pane_w > 0.0 && pane_w < NAV_STRIP_BELOW
}

fn ui(cx: &mut App) -> &mut Ui {
    if !cx.has_global::<Ui>() {
        cx.set_global(Ui { page: Page::General, open: HashSet::new(), search: None, hg_focus: Vec::new(), pane_w: 0.0 });
    }
    cx.global_mut::<Ui>()
}

/// A setting found while every page is built for the search: its texts and where it is.
#[derive(Debug, Clone, PartialEq)]
struct Found {
    title: String,
    desc: Option<String>,
    page: Page,
    /// The expander it is inside (opened when the result is picked).
    expander: Option<&'static str>,
}

thread_local! {
    /// Some while the pages are being built to list their settings (see [`collect`]).
    static COLLECT: std::cell::RefCell<Option<Vec<Found>>> = const { std::cell::RefCell::new(None) };
    static COLLECT_AT: std::cell::Cell<(Page, Option<&'static str>)> = const { std::cell::Cell::new((Page::General, None)) };
}

thread_local! {
    /// The setting a search result was picked for (issue 126): its row is marked, and the page is scrolled to it once.
    static FIND: std::cell::RefCell<Option<FindTarget>> = const { std::cell::RefCell::new(None) };
    /// The settings page's scroll, for that one scroll (set by every [`render`]).
    static PAGE_SCROLL: std::cell::RefCell<Option<ScrollHandle>> = const { std::cell::RefCell::new(None) };
}

struct FindTarget {
    title: String,
    scrolled: bool,
}

/// How long the picked setting's row stays marked.
const FIND_MARK_FOR: std::time::Duration = std::time::Duration::from_millis(1600);

/// A setting's row as drawn: when a search result was picked for it, with a soft accent wash, and the page scrolled (at its first paint)
/// so that the row stands near the top.
fn found_mark(title: &str, p: &Palette, row: Div) -> Div {
    if collecting() || !FIND.with(|f| f.borrow().as_ref().is_some_and(|t| t.title == title)) {
        return row;
    }
    row.relative().rounded(theme::RADIUS).bg(p.accent.opacity(0.18)).child(
        canvas(
            |_, _, _| (),
            |bounds, _, window, _| {
                let first = FIND.with(|f| f.borrow_mut().as_mut().is_some_and(|t| !std::mem::replace(&mut t.scrolled, true)));
                if let (true, Some(scroll)) = (first, PAGE_SCROLL.with(|s| s.borrow().clone())) {
                    let (view, offset) = (scroll.bounds(), scroll.offset());
                    let y = offset.y - (bounds.top() - view.top() - px(24.));
                    scroll.set_offset(point(offset.x, y.min(px(0.))));
                    window.refresh();
                }
            },
        )
        .absolute()
        .size_full(),
    )
}

fn collecting() -> bool {
    COLLECT.with(|c| c.borrow().is_some())
}

/// Notes a setting's texts (the card and row builders call it; a no-op outside a search).
fn note_setting(title: &str, desc: Option<&str>) {
    COLLECT.with(|c| {
        if let Some(list) = c.borrow_mut().as_mut() {
            let (page, expander) = COLLECT_AT.with(|a| a.get());
            list.push(Found { title: title.to_string(), desc: desc.map(str::to_string), page, expander });
        }
    });
}

/// The settings whose title or description has every word of `query` (case-insensitive).
fn matching(all: Vec<Found>, query: &str) -> Vec<Found> {
    let words: Vec<String> = query.split_whitespace().map(rf_core::entry::fold_case).collect();
    let mut seen = HashSet::new();
    all.into_iter()
        .filter(|f| {
            // (the English name too, in any other language: issue 381, a setting known from an English issue or changelog)
            let desc = f.desc.as_deref().unwrap_or("");
            let english = [crate::i18n::english_of(&f.title), crate::i18n::english_of(desc)];
            let text = rf_core::entry::fold_case(&format!("{} {} {}", f.title, desc, english.iter().flatten().copied().collect::<Vec<_>>().join(" ")));
            !words.is_empty() && words.iter().all(|w| text.contains(w.as_str()))
        })
        // (a setting drawn twice on a page is one result)
        .filter(|f| seen.insert((f.title.clone(), f.page as u8)))
        .collect()
}

/// Every setting of every page: the pages are built once with the builders noting their texts.
fn collect(p: &Palette, s: &Settings, cx: &mut App) -> Vec<Found> {
    COLLECT.with(|c| *c.borrow_mut() = Some(Vec::new()));
    for (page, _, _) in PAGES {
        COLLECT_AT.with(|a| a.set((page, None)));
        let _ = build_page(page, p, s, cx);
    }
    COLLECT.with(|c| c.borrow_mut().take()).unwrap_or_default()
}

fn build_page(page: Page, p: &Palette, s: &Settings, cx: &mut App) -> Vec<AnyElement> {
    match page {
        Page::General => general(p, s, cx),
        Page::Appearance => appearance(p, s, cx),
        Page::Dock => {
            let size = crate::dock::size_slider::control(p, s, cx);
            // a part of the dock that could not start tells the page so (a look in the background; not while the search builds pages)
            if !collecting() {
                crate::dock::parts_status::poll(cx);
            }
            // (the weather-from-position card is part of the page, directly under the weather city's row: `dock_page::page`)
            crate::dock_page::page(p, s, Some(size))
        }
        Page::Desktop => crate::desktop_page::page(p, s),
        Page::Layout => layout(p, s, cx),
        Page::Files => files(p, s, cx),
        Page::FileTypes => crate::open_rules_page::page(p, s),
        Page::Actions => actions(p, s, cx),
        Page::Tags => tags(p, cx),
        Page::Look => look(p, s, cx),
        Page::Ferry => crate::ferry::page(p, s, cx),
        Page::Search => quick_search_cards(p, s, cx),
        Page::Addons => crate::addons_page::page(p, cx),
        // the developer tools are a part of Gelişmiş (they had a page of their own)
        Page::Advanced => {
            let mut v = advanced(p, s, cx);
            v.push(section(p, t!("Geliştirici araçları")));
            v.extend(dev(p, s, cx));
            v
        }
        Page::Speed => crate::bench_view::page(p, cx),
        Page::Organizer => crate::organizer::page::page(p, cx),
        Page::About => about(p, cx),
    }
}

pub fn open_page(page: Page, cx: &mut App) {
    if ui(cx).page != page {
        // Each page starts at its top (issue 335: the page picked next stood where the last one had been scrolled to). A setting
        // picked from the search is scrolled to afterwards, at its first paint.
        PAGE_SCROLL.with(|s| {
            if let Some(scroll) = s.borrow().as_ref() {
                scroll.set_offset(Point::default());
            }
        });
    }
    ui(cx).page = page;
}

// ---------------------------------------------------------------- controls

/// A Windows 11 switch with its state word ("Açık"/"Kapalı") on the left. Over glass the track and the thumb are the liquid ones
/// (`liquid::switch_track`); the word and the click are the same.
pub(crate) fn switch(id: impl Into<ElementId>, p: &Palette, on: bool, toggle: impl Fn(&mut Window, &mut App) + 'static) -> AnyElement {
    let id: ElementId = id.into();
    let track: AnyElement = if p.liquid {
        crate::liquid::switch_track(id, p, on, false, toggle)
    } else {
        let knob = if on { p.accent_text } else { p.text_secondary };
        h_flex()
            .id(id)
            .w(px(40.))
            .h(px(20.))
            .px(px(3.))
            .items_center()
            .rounded_full()
            .border_1()
            // Tab reaches the switch, Enter / Space flips it
            .tab_index(0)
            .when(on, |d| d.bg(p.accent).border_color(p.accent).justify_end())
            .when(!on, |d| d.border_color(p.text_secondary).hover(|s| s.bg(p.hover)))
            .child(div().size(px(12.)).rounded_full().bg(knob))
            .on_click(move |_, window, cx| toggle(window, cx))
            .into_any_element()
    };
    h_flex()
        .gap_3()
        .items_center()
        .child(div().text_sm().text_color(p.text_secondary).child(if on { t!("Açık") } else { t!("Kapalı") }))
        .child(track)
        .into_any_element()
}

/// Switch bound to a boolean setting.
pub(crate) fn sw(id: &'static str, p: &Palette, on: bool, set: fn(&mut Settings, bool)) -> AnyElement {
    switch(id, p, on, move |_, cx| settings::update(cx, |s| set(s, !on)))
}

/// A button showing the current value; clicking opens the choices in our menu.
/// The size steps of the list's rows or of the grid's tiles, by their height in pixels (names like "Medium" read as other
/// things in some languages: "Orta" had become "Fair"); the default step is marked.
fn size_steps<const N: usize>(px: [f32; N], default: u8) -> Vec<(u8, String)> {
    (0..N as u8)
        .map(|i| {
            let mut label = format!("{} px", px[i as usize] as u32);
            if i == default {
                label = format!("{label} ({})", t!("varsayılan"));
            }
            (i, label)
        })
        .collect()
}

pub(crate) fn dropdown<T: Copy + PartialEq + 'static>(id: &'static str, p: &Palette, current: T, options: Vec<(T, String)>, set: fn(&mut Settings, T)) -> AnyElement {
    let label = options.iter().find(|(v, _)| *v == current).map(|(_, l)| l.clone()).unwrap_or_default();
    select_box(id, p, label, move |_| {
        options.iter().map(|(v, l)| {
            let v = *v;
            Choice::new(l.clone(), v == current, move |_, cx| settings::update(cx, |s| set(s, v)))
        }).collect()
    })
}

/// Picks a freedesktop pack from `%APPDATA%\rustyfiles\icon-themes`. Picking one switches the icon theme to it; "None" goes back
/// to the system pictures. The pack list is read when the menu opens, so a newly installed pack shows without a restart.
fn icon_pack_dropdown(p: &Palette) -> AnyElement {
    let current = settings::icon_theme_pack();
    let label: SharedString = if current.is_empty() {
        t!("Yerel (varsayılan)").into()
    } else {
        current.clone().into()
    };
    select_box("icon-theme-pack", p, label, move |_| {
        crate::icon_theme::refresh_packs();
        let none_label: SharedString = t!("Yerel (varsayılan)").into();
        let mut out = vec![Choice::new(none_label, current.is_empty(), |_, cx| {
            settings::update(cx, |s| {
                s.icon_theme = IconThemePref::Windows;
                s.icon_theme_pack.clear();
            });
        })];
        for name in crate::icon_theme::available_packs() {
            let selected = name == current;
            let pack = name.clone();
            out.push(Choice::new(name, selected, move |_, cx| {
                settings::update(cx, |s| {
                    s.icon_theme = IconThemePref::Freedesktop;
                    s.icon_theme_pack = pack.clone();
                });
            }));
        }
        out
    })
}

/// Helper to open the themes folder using the OpenIconThemesFolder action.
fn open_icon_themes_folder(window: &mut Window, cx: &mut App) {
    if let Some(d) = settings::app_dir() {
        let d = d.join("icon-themes");
        let _ = std::fs::create_dir_all(&d);
        window.dispatch_action(Box::new(crate::actions::OpenIconThemesFolder), cx);
    }
}

/// Variant picker for theme families such as Papirus / Papirus-Dark. Hidden when the selected
/// pack has no installed siblings. The pack name itself is the stored variant.
fn icon_variant_dropdown(p: &Palette) -> Option<AnyElement> {
    let current = settings::icon_theme_pack();
    let variants = crate::icon_theme::theme_variants(&current);
    if variants.len() < 2 {
        return None;
    }
    let selected_label: SharedString = variants
        .iter()
        .find(|(_, pack)| pack == &current)
        .map(|(label, _)| label.clone())
        .unwrap_or_else(|| current.clone())
        .into();
    let label: SharedString = format!("{}: {}", t!("Varyasyon"), selected_label).into();
    Some(select_box("icon-theme-variant", p, label, move |_| {
        crate::icon_theme::refresh_packs();
        variants
            .iter()
            .map(|(label, pack)| {
                let selected = pack == &current;
                let pack = pack.clone();
                let label: SharedString = label.clone().into();
                Choice::new(label, selected, move |_, cx| {
                    settings::update(cx, |s| {
                        s.icon_theme = IconThemePref::Freedesktop;
                        s.icon_theme_pack = pack.clone();
                    });
                })
            })
            .collect()
    }))
}

pub(crate) fn button(id: impl Into<ElementId>, p: &Palette, label: impl Into<SharedString>, run: impl Fn(&mut Window, &mut App) + 'static) -> AnyElement {
    div()
        .id(id)
        .h(px(32.))
        .px_4()
        .flex()
        .items_center()
        .rounded(theme::RADIUS_SM)
        .bg(p.hover)
        .border_1()
        .border_color(p.border)
        .text_sm()
        .cursor_pointer()
        // Tab reaches the button, Enter / Space presses it
        .tab_index(0)
        .hover(|s| s.bg(p.pressed))
        .active(|s| s.opacity(0.8))
        .child(label.into())
        .on_click(move |_, window, cx| run(window, cx))
        .into_any_element()
}

fn icon_button(id: impl Into<ElementId>, p: &Palette, icon: L, tip: impl Into<SharedString>, run: impl Fn(&mut Window, &mut App) + 'static) -> AnyElement {
    let tip: SharedString = tip.into();
    let dark = p.dark;
    let base = div()
        .id(id)
        .size(px(32.))
        .flex()
        .items_center()
        .justify_center()
        .cursor_pointer()
        .tab_index(0)
        .active(|s| s.opacity(0.8));
    let styled = if p.liquid {
        base.rounded_full()
            .bg(crate::liquid::dropdown_fill(dark, false))
            .hover(move |s| s.bg(crate::liquid::dropdown_fill(dark, true)))
    } else {
        base.rounded(theme::RADIUS_SM)
            .bg(p.hover)
            .border_1()
            .border_color(p.border)
            .hover(|s| s.bg(p.pressed))
    };
    styled
        .tooltip(move |w, cx| gpui_kit::component::tooltip::Tooltip::new(tip.clone()).build(w, cx))
        .child(Icon::new(icon).size(px(16.)).text_color(p.text_secondary))
        .on_click(move |_, window, cx| run(window, cx))
        .into_any_element()
}

// ---------------------------------------------------------------- layout pieces

/// The narrowest a setting's words (its title and the line under it) are drawn, logical px.
///
/// WHY (the General page in a narrow window looked broken). A setting's row was: picture, words, control, side by side, and the words were what gave way: the
/// control kept its width (a list is never narrower than 180 px), so in a narrow window the words were pressed into a column one
/// letter wide and a title stood letter under letter. Now the words never go under this width. When the row has no room for the words
/// and the control side by side, the CONTROL goes to a line of its own under them ([`beside`]), as a form does on a narrow page.
pub(crate) const WORDS_MIN: f32 = 120.0;

/// A setting's control, placed after its words: it keeps its own width, stays at the right end, and wraps to a line of its own when
/// the row is too narrow for both (the row is a wrapping one). It is never wider than the row.
pub(crate) fn beside(control: AnyElement) -> Div {
    h_flex().flex_shrink_0().max_w_full().ml_auto().child(control)
}

pub(crate) fn card_body(p: &Palette, icon: L, title: SharedString, desc: Option<SharedString>, control: Option<AnyElement>) -> Div {
    note_setting(&title, desc.as_deref());
    let marked = title.clone();
    let row = h_flex()
        .min_h(px(64.))
        .px_4()
        .py_3()
        .gap_x_4()
        .gap_y_2()
        .items_center()
        .flex_wrap()
        .child(
            // (the picture and the words stay together: it is the control that wraps)
            h_flex()
                .flex_1()
                .min_w(px(WORDS_MIN + 34.))
                .gap_4()
                .items_center()
                .child(Icon::new(icon).size(px(18.)).flex_shrink_0().text_color(p.text))
                .child(
                    v_flex()
                        .flex_1()
                        .min_w_0()
                        .gap_0p5()
                        .child(div().text_sm().child(title))
                        .children(desc.map(|d| div().text_xs().text_color(p.text_secondary).child(d))),
                ),
        )
        .children(control.map(beside));
    found_mark(&marked, p, row)
}

pub(crate) fn shell(p: &Palette) -> Div {
    v_flex().w_full().rounded(theme::RADIUS).bg(p.hover).border_1().border_color(p.border)
}

/// One setting row.
pub(crate) fn card(p: &Palette, icon: L, title: &str, desc: Option<&str>, control: AnyElement) -> AnyElement {
    shell(p)
        .child(card_body(p, icon, title.to_string().into(), desc.map(|d| d.to_string().into()), Some(control)))
        .into_any_element()
}

/// A disk kind's name, as Settings shows it.
fn disk_kind_name(kind: rf_win::drives::DiskKind) -> &'static str {
    use rf_win::drives::DiskKind::*;
    match kind {
        Hdd => t!("Sabit disk (HDD)"),
        SataSsd => t!("SATA SSD"),
        NvmeSsd => t!("NVMe SSD"),
        DramlessSsd => t!("DRAM'siz NVMe SSD"),
        UsbStick => t!("USB bellek, hafıza kartı"),
        Network => t!("Ağ"),
        Unknown => t!("Bilinmiyor"),
    }
}

/// What to say when the kind chosen by hand is not the one Windows reports: what the choice costs.
fn disk_kind_warning(detected: rf_win::drives::DiskKind, chosen: rf_win::drives::DiskKind) -> Option<&'static str> {
    use rf_win::drives::DiskKind::*;
    if detected == chosen || detected == Unknown {
        return None;
    }
    Some(match (detected, chosen) {
        (Hdd, _) => t!("Windows bunu dönen bir disk olarak bildiriyor: aynı anda birden çok dosya kopyalamak kafayı dosyalar arasında gezdirir ve kopyaları çok yavaşlatabilir."),
        (DramlessSsd, NvmeSsd) => t!("Windows bunu DRAM'siz bir SSD olarak bildiriyor: büyük kopyalarda diskin önbelleği dolunca hız düşebilir."),
        (_, Hdd) => t!("Windows bunu dönen bir disk olarak bildirmiyor: dosyalar tek tek kopyalanır, kopyalar gereğinden yavaş olur."),
        _ => t!("Windows bu sürücüyü başka bir tür olarak bildiriyor; kopyalama hızı seçtiğiniz türe göre ayarlanır."),
    })
}

/// The drives the copy engine sizes its work for, each with what Windows reports (read once a minute at most: a query per drive is
/// a few device calls, not something to do on every frame).
fn detected_disks() -> Vec<(String, String, rf_win::drives::DiskKind)> {
    use std::sync::Mutex;
    use std::time::{Duration, Instant};
    static SEEN: Mutex<Option<(Instant, Vec<(String, String, rf_win::drives::DiskKind)>)>> = Mutex::new(None);
    let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
    if let Some((when, list)) = seen.as_ref()
        && when.elapsed() < Duration::from_secs(60)
    {
        return list.clone();
    }
    let list: Vec<(String, String, rf_win::drives::DiskKind)> = rf_win::drives::list_drives()
        .into_iter()
        .filter(|d| matches!(d.kind, rf_win::drives::DriveKind::Fixed | rf_win::drives::DriveKind::Removable))
        .map(|d| {
            let info = rf_win::drives::disk_info(&d.root);
            let name = info.model.clone().unwrap_or_else(|| d.label.clone());
            (format!("{}:", d.letter.to_ascii_uppercase()), name, rf_win::drives::kind_from(&info))
        })
        .collect();
    *seen = Some((Instant::now(), list.clone()));
    list
}

/// Settings › Advanced › Disk kinds for copying: each drive, what Windows reports, and the kind the copy engine uses (Automatic, or
/// one chosen by hand, with a warning when it is not what Windows reports).
fn disk_kinds(p: &Palette, s: &Settings, cx: &mut App) -> AnyElement {
    let chosen = s.copy_disk_kinds.clone();
    let pp = *p;
    expander(
        "disk-kinds",
        p,
        L::HardDrive,
        t!("Kopyalamada disk türleri"),
        Some(t!("Kopyalama motoru her sürücüde aynı anda kaç dosya kopyalayacağını diskin türüne göre seçer: dönen diskte tek tek, SSD'de birçoğunu birden. Otomatik, Windows'un bildirdiğini kullanır.")),
        None,
        move || {
            detected_disks()
                .into_iter()
                .map(|(drive, model, detected)| {
                    let current = chosen.get(&drive).copied();
                    let label: SharedString = match current {
                        None => format!("{} ({})", t!("Otomatik"), disk_kind_name(detected)).into(),
                        Some(k) => disk_kind_name(k).into(),
                    };
                    let key = drive.clone();
                    let picker = select_box(SharedString::from(format!("disk-kind-{drive}")), &pp, label, move |_| {
                        let mut out = vec![{
                            let key = key.clone();
                            Choice::new(format!("{} ({})", t!("Otomatik"), disk_kind_name(detected)), current.is_none(), move |_, cx| {
                                let key = key.clone();
                                settings::update(cx, move |s| {
                                    s.copy_disk_kinds.remove(&key);
                                })
                            })
                        }];
                        for kind in rf_win::drives::DiskKind::CHOICES {
                            let key = key.clone();
                            out.push(Choice::new(disk_kind_name(kind).to_string(), current == Some(kind), move |_, cx| {
                                let key = key.clone();
                                settings::update(cx, move |s| {
                                    s.copy_disk_kinds.insert(key, kind);
                                })
                            }));
                        }
                        out
                    });
                    let mut desc = format!("{model} · {}: {}", t!("Windows'un bildirdiği"), disk_kind_name(detected));
                    if let Some(w) = current.and_then(|c| disk_kind_warning(detected, c)) {
                        desc = format!("{desc}\n⚠ {w}");
                    }
                    card(&pp, L::HardDrive, &drive, Some(&desc), picker)
                })
                .collect()
        },
        cx,
    )
}

/// A card that opens to show `children` (state kept per `key`).
fn expander(key: &'static str, p: &Palette, icon: L, title: &str, desc: Option<&str>, control: Option<AnyElement>, children: impl FnOnce() -> Vec<AnyElement>, cx: &mut App) -> AnyElement {
    let open = ui(cx).open.contains(key);
    let chevron = div()
        .id(SharedString::from(format!("exp-chev-{key}")))
        .size(px(28.))
        .flex()
        .items_center()
        .justify_center()
        .rounded(theme::RADIUS_SM)
        .child(Icon::new(if open { L::ChevronUp } else { L::ChevronDown }).size(px(14.)));
    // The whole header opens and closes the card, as Windows 11's own Settings do (issue 392: only the small arrow did). A control
    // in the header (a switch, a list) keeps its press to itself, or using it would also open or close the card.
    let control = control.map(|c| div().on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()).child(c));
    let header_control = h_flex().gap_2().items_center().children(control).child(chevron).into_any_element();
    let body = div()
        .id(SharedString::from(format!("exp-head-{key}")))
        .rounded(theme::RADIUS)
        .cursor_pointer()
        .hover(|s| s.bg(p.pressed))
        .on_click(move |_, window, cx| {
            let u = ui(cx);
            if !u.open.remove(key) {
                u.open.insert(key);
            }
            window.refresh();
        })
        .child(card_body(p, icon, title.to_string().into(), desc.map(|d| d.to_string().into()), Some(header_control)));
    // (a search looks inside closed expanders too)
    let kids = if open || collecting() {
        let at = COLLECT_AT.with(|a| a.get());
        COLLECT_AT.with(|a| a.set((at.0, Some(key))));
        let kids = children();
        COLLECT_AT.with(|a| a.set(at));
        Some(kids)
    } else {
        None
    };
    shell(p).child(body).when_some(kids.filter(|_| open), |d, kids| d.child(div().h(px(1.)).bg(p.divider)).child(v_flex().py_1().children(kids))).into_any_element()
}

/// A child row inside an expander (no icon, indented like Files).
fn sub(p: &Palette, title: &str, desc: Option<&str>, control: AnyElement) -> AnyElement {
    note_setting(title, desc);
    let row = h_flex()
        .min_h(px(48.))
        .pl(px(56.))
        .pr_4()
        .py_2()
        .gap_x_4()
        .gap_y_2()
        .items_center()
        .flex_wrap()
        .child(
            v_flex()
                .flex_1()
                .min_w(px(WORDS_MIN))
                .child(div().text_sm().child(title.to_string()))
                .children(desc.map(|d| div().text_xs().text_color(p.text_secondary).child(d.to_string()))),
        )
        .child(beside(control));
    found_mark(title, p, row).into_any_element()
}

/// [`sub`] with the picture of what it is about in front of its words (the toolbar's buttons, discussion 676: "show each command's
/// actual toolbar icon to the left of its name").
fn sub_icon(p: &Palette, icon: L, title: &str, desc: Option<&str>, control: AnyElement) -> AnyElement {
    note_setting(title, desc);
    let row = h_flex()
        .min_h(px(48.))
        .pl(px(30.))
        .pr_4()
        .py_2()
        .gap_x_4()
        .gap_y_2()
        .items_center()
        .flex_wrap()
        .child(div().w(px(16.)).flex_shrink_0().child(Icon::new(icon).size(px(16.)).text_color(p.text_secondary)))
        .child(
            v_flex()
                .flex_1()
                .min_w(px(WORDS_MIN))
                .child(div().text_sm().child(title.to_string()))
                .children(desc.map(|d| div().text_xs().text_color(p.text_secondary).child(d.to_string()))),
        )
        .child(beside(control));
    found_mark(title, p, row).into_any_element()
}

/// The picture a toolbar button has on the bar, by its key (Settings › Toolbar buttons lists them with it).
fn toolbar_icon_of(key: &str) -> L {
    match key {
        "new" => L::CirclePlus,
        "newfolder" => L::FolderPlus,
        "cut" => L::Scissors,
        "copy" => L::Copy,
        "paste" => L::ClipboardPaste,
        "rename" => L::TextCursorInput,
        "share" => L::Share2,
        "delete" => L::Trash,
        "props" => L::Wrench,
        "edit" => L::FilePen,
        "terminal" => L::SquareTerminal,
        "terminaladmin" => L::ShieldCheck,
        "hidden" => L::Eye,
        "extensions" => L::FileType,
        "dual" => L::Columns2,
        "shelf" => L::Inbox,
        "refresh" => L::RotateCw,
        "undo" => L::Undo2,
        "redo" => L::Redo2,
        "selectall" => L::SquareCheck,
        "selectnone" => L::Square,
        "invertsel" => L::ArrowLeftRight,
        "compress" => L::Archive,
        "extract" => L::FolderOutput,
        "more" => L::Ellipsis,
        "filter" => L::ListFilter,
        "sort" => L::ArrowUpDown,
        "view" => L::LayoutGrid,
        "preview" => L::PanelRight,
        _ => L::Settings,
    }
}

pub(crate) fn section(p: &Palette, title: &str) -> AnyElement {
    div().pt_5().pb_1().text_sm().font_weight(FontWeight::SEMIBOLD).text_color(p.text).child(title.to_string()).into_any_element()
}

fn link_row(p: &Palette, id: &'static str, icon: L, title: &str, desc: Option<&str>, run: impl Fn(&mut Window, &mut App) + 'static) -> AnyElement {
    shell(p)
        .id(id)
        .hover(|s| s.bg(p.pressed))
        .on_click(move |_, window, cx| run(window, cx))
        .child(card_body(
            p,
            icon,
            title.to_string().into(),
            desc.map(|d| d.to_string().into()),
            Some(Icon::new(L::SquareArrowOutUpRight).size(px(14.)).text_color(p.text_secondary).into_any_element()),
        ))
        .into_any_element()
}

// ---------------------------------------------------------------- page

/// `lens_owner`: this page owns the window's settings lens (see `FolderView::lens_owner`); only then is the selected entry glass.
pub fn render(p: &Palette, window: &mut Window, cx: &mut App, lens_owner: bool, scroll: &ScrollHandle) -> AnyElement {
    use gpui_kit::component::input::InputState;
    let page = ui(cx).page;
    PAGE_SCROLL.with(|h| *h.borrow_mut() = Some(scroll.clone()));
    let s = cx.global::<Settings>().clone();
    let search = match ui(cx).search.clone() {
        Some(e) => e,
        None => {
            let e = cx.new(|cx| InputState::new(window, cx).placeholder(t!("Ayarlarda ara")));
            // typing redraws the page (the box is not part of a view of its own)
            cx.observe(&e, |_, cx| cx.refresh_windows()).detach();
            ui(cx).search = Some(e.clone());
            e
        }
    };
    let query = search.read(cx).value().trim().to_string();
    // In a narrow pane the list of pages is a strip of icons (each with its name as a tip), so that the settings keep a readable
    // width; the title and the search box are the full list's.
    let strip = nav_is_strip(ui(cx).pane_w);
    // (scrolls: the 13 entries need more than the 420 px the window may be as low as)
    let mut nav = v_flex().id("settings-nav").w(px(if strip { NAV_STRIP_W } else { NAV_W })).flex_shrink_0().h_full().overflow_y_scroll().px_3().pt_5().gap_0p5();
    if !strip {
        nav = nav.child(div().px_2().pb_3().text_xl().font_weight(FontWeight::SEMIBOLD).child(t!("Ayarlar"))).child(
            h_flex()
                .h(px(32.))
                .mb_2()
                .px_2()
                .gap_1()
                .items_center()
                .rounded(theme::RADIUS_SM)
                .bg(p.hover)
                .border_1()
                .border_color(p.border)
                .child(Icon::new(L::Search).size(px(14.)).flex_shrink_0().text_color(p.text_secondary))
                .child(crate::text_menu::input(&search).appearance(false).cleanable(true)),
        );
    }
    // Over glass the selected entry is a lens the engine draws behind the scene (slot 1): no fill and no accent bar, a probe that
    // reports the row's place on every paint instead. The page is only built for the active tab; the workspace names the one pane that
    // owns the lens and takes the lens out when no pane does.
    let lens = lens_owner && crate::glass::shown(crate::look::window::hwnd_of(window));
    for (i, (pg, icon, label)) in PAGES.iter().copied().enumerate() {
        let on = pg == page;
        nav = nav.child(
            h_flex()
                .id(("set-nav", i))
                .h(px(36.))
                .when(!strip, |d| d.px_3())
                .when(strip, |d| {
                    let tip: SharedString = crate::i18n::t(label).into();
                    d.justify_center().tooltip(move |w, cx| gpui_kit::component::tooltip::Tooltip::new(tip.clone()).build(w, cx))
                })
                .gap_3()
                .items_center()
                .relative()
                .rounded(theme::RADIUS_SM)
                .text_sm()
                .when(on && !lens, |d| d.bg(p.selection).child(theme::selection_pill(p)))
                .when(on && lens && crate::glass::lens_phase(crate::look::window::hwnd_of(window), crate::glass::SLOT_SETTINGS) != crate::glass::LensPhase::Rest, |d| {
                    d.child(crate::glass::lens_stand_in(p.dark, 36.))
                })
                .when(on && lens, |d| d.child(crate::glass::lens_probe(crate::glass::SLOT_SETTINGS, crate::glass::key_of(&i))))
                .when(!on, |d| d.hover(|s| s.bg(p.hover)))
                .child(Icon::new(icon).size(px(16.)).text_color(if on { p.accent } else { p.text_secondary }))
                .when(!strip, |d| {
                    // (the pill never shrinks; a long page name gives way, with "…": the Russian pill was cut, a Discord report)
                    d.child(
                        h_flex()
                            .min_w_0()
                            .gap_2()
                            .items_center()
                            .child(div().min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis().child(crate::i18n::t(label)))
                            .when(experimental(pg), |d| d.child(experimental_pill(p))),
                    )
                })
                .on_click({
                    let search = search.clone();
                    move |_, window, cx| {
                        open_page(pg, cx);
                        // (a page picked by hand ends the search)
                        search.update(cx, |s, cx| s.set_value("", window, cx));
                        window.refresh();
                    }
                }),
        );
    }
    // (Ferry's page on screen shows this PC to everyone while it is: `ferry::page_seen`)
    if query.is_empty() && page == Page::Ferry {
        crate::ferry::page_seen(window.window_handle(), cx);
    }
    let (title, body): (String, Vec<AnyElement>) = if query.is_empty() {
        (PAGES.iter().find(|x| x.0 == page).map(|x| page_title(x.0, crate::i18n::t(x.2))).unwrap_or_default(), build_page(page, p, &s, cx))
    } else {
        let found = matching(collect(p, &s, cx), &query);
        let mut rows: Vec<AnyElement> = Vec::new();
        if found.is_empty() {
            rows.push(div().py_4().text_sm().text_color(p.text_secondary).child(t!("Eşleşen ayar yok")).into_any_element());
        }
        for (i, f) in found.into_iter().enumerate() {
            let (pg, key, target) = (f.page, f.expander, f.title.clone());
            let page_label = PAGES.iter().find(|x| x.0 == pg).map(|x| crate::i18n::t(x.2)).unwrap_or_default();
            let search = search.clone();
            rows.push(
                shell(p)
                    .id(("set-found", i))
                    .cursor_pointer()
                    .hover(|s| s.bg(p.pressed))
                    .on_click(move |_, window, cx| {
                        open_page(pg, cx);
                        if let Some(k) = key {
                            ui(cx).open.insert(k);
                        }
                        // the page opens scrolled to the setting, which is marked for a moment (issue 126)
                        FIND.with(|f| *f.borrow_mut() = Some(FindTarget { title: target.clone(), scrolled: false }));
                        window
                            .spawn(cx, async move |cx| {
                                cx.background_executor().timer(FIND_MARK_FOR).await;
                                let _ = cx.update(|window, _| {
                                    FIND.with(|f| *f.borrow_mut() = None);
                                    window.refresh();
                                });
                            })
                            .detach();
                        search.update(cx, |s, cx| s.set_value("", window, cx));
                        window.refresh();
                    })
                    .child(
                        h_flex()
                            .min_h(px(52.))
                            .px_4()
                            .py_2()
                            .gap_4()
                            .items_center()
                            .child(
                                v_flex()
                                    .flex_1()
                                    .min_w_0()
                                    .gap_0p5()
                                    .child(div().text_sm().child(f.title))
                                    .children(f.desc.map(|d| div().text_xs().text_color(p.text_secondary).child(d))),
                            )
                            .child(div().flex_shrink_0().text_xs().text_color(p.text_secondary).child(page_label))
                            .child(Icon::new(L::ChevronRight).size(px(14.)).flex_shrink_0().text_color(p.text_secondary)),
                    )
                    .into_any_element(),
            );
        }
        (t!("Arama sonuçları").to_string(), rows)
    };
    h_flex()
        .size_full()
        .relative()
        // (the pane's own width, measured at paint: when it crosses the limit the pane is drawn again with the other form of the list)
        .child(
            canvas(
                move |bounds, _, cx| {
                    let w = f32::from(bounds.size.width);
                    let u = ui(cx);
                    if (u.pane_w - w).abs() > 0.5 {
                        let was = nav_is_strip(u.pane_w);
                        u.pane_w = w;
                        if nav_is_strip(w) != was {
                            // (after this paint: a window that is being drawn does not take a request to be drawn again)
                            cx.defer(|cx| cx.refresh_windows());
                        }
                    }
                },
                |_, _, _, _| {},
            )
            .absolute()
            .top_0()
            .left_0()
            .size_full(),
        )
        .child(nav)
        .child(
            // the page scrolls with a scrollbar over its right edge (issue 86: on Windows 10 nothing showed there was more below)
            div()
                .relative()
                .flex_1()
                .min_w_0()
                .h_full()
                .child(
                    div().id("settings-page").size_full().overflow_y_scroll().track_scroll(scroll).child(
                        v_flex()
                            .w_full()
                            .max_w(px(980.))
                            .px_6()
                            .pt_5()
                            .pb_8()
                            .gap_2()
                            .child(div().pb_2().text_xl().font_weight(FontWeight::SEMIBOLD).child(title))
                            .children(body),
                    ),
                )
                .child(
                    gpui_kit::component::scroll::Scrollbar::vertical(scroll)
                        .id("settings-scrollbar")
                        .mode(crate::folder_view::scrollbar_mode()),
                ),
        )
        .into_any_element()
}

/// Quick search: on/off, its shortcut (recorded like the keyboard shortcuts), web engine,
/// bookmarks.
fn quick_search_cards(p: &Palette, s: &Settings, cx: &mut App) -> Vec<AnyElement> {
    let capture = crate::quick_search::CAPTURE_ACTION;
    let waiting = crate::keymap_editor::capturing(cx).as_deref() == Some(capture);
    let shown: SharedString = if waiting { t!("Tuşlara basın…").into() } else { crate::keymap_editor::pretty(&s.quick_search_keys).into() };
    let keys_desc = match crate::quick_search::problem() {
        Some(rf_win::hotkey::HotkeyError::Taken) if s.quick_search => t!("Bu kısayolu başka bir uygulama kullanıyor (ChatGPT, Gemini, PowerToys…): başka bir kısayol seçin"),
        Some(rf_win::hotkey::HotkeyError::Invalid) if s.quick_search => t!("Bu kısayol kullanılamıyor: Ctrl, Alt, Shift ya da Win ile bir tuş seçin"),
        _ => t!("Değiştirmek için tıklayıp yeni tuşlara basın"),
    };
    let warn = s.quick_search && crate::quick_search::problem().is_some();
    let pill = div()
        .id("qs-keys")
        .px_3()
        .py_1()
        .rounded(px(4.))
        .border_1()
        .border_color(if warn { p.danger } else { p.border })
        .text_sm()
        .cursor_pointer()
        .text_color(if waiting { p.accent } else { p.text })
        .hover(|d| d.bg(p.pressed))
        .when(waiting, |d| d.bg(p.selection))
        .child(shown)
        .on_click(move |_, window, cx| {
            crate::keymap_editor::start(capture.to_string(), cx);
            window.refresh();
        })
        .into_any_element();
    vec![
        card(
            p,
            L::Search,
            "HyperSearch",
            Some(if s.run_in_background {
                t!("Her yerden kısayolla: uygulamalar, dosyalar, klasörler, yer imleri ve web")
            } else {
                t!("Her yerden kısayolla: uygulamalar, dosyalar, klasörler, yer imleri ve web. Pencere kapalıyken de çalışması için Gelişmiş'te arka planda çalışmayı açın")
            }),
            sw("quick-search", p, s.quick_search, |s, v| s.quick_search = v),
        ),
        card(p, L::Keyboard, t!("Kısayol"), Some(keys_desc), pill),
        card(
            p,
            L::Globe,
            t!("Web araması"),
            None,
            dropdown(
                "web-search",
                p,
                s.web_search,
                vec![
                    (crate::settings::WebSearch::Google, "Google".into()),
                    (crate::settings::WebSearch::Bing, "Bing".into()),
                    (crate::settings::WebSearch::DuckDuckGo, "DuckDuckGo".into()),
                    (crate::settings::WebSearch::Yandex, "Yandex".into()),
                ],
                |s, v| s.web_search = v,
            ),
        ),
        card(
            p,
            L::Bookmark,
            t!("Chrome ve Edge yer imlerini de ara"),
            Some(t!("Yer imleri bu bilgisayarda okunur, hiçbir yere gönderilmez")),
            sw("qs-bookmarks", p, s.quick_search_bookmarks, |s, v| s.quick_search_bookmarks = v),
        ),
        card(
            p,
            L::Clock,
            t!("Boşken son kullanılanları göster"),
            Some(t!("Kapalıyken HyperSearch bir şey yazılana kadar boş açılır")),
            sw("qs-recent", p, s.quick_search_recent, |s, v| s.quick_search_recent = v),
        ),
    ]
}

fn general(p: &Palette, s: &Settings, cx: &mut App) -> Vec<AnyElement> {
    let mut v = vec![
        card(
            p,
            L::Languages,
            t!("Dil"),
            None,
            dropdown(
                "lang",
                p,
                s.language,
                std::iter::once((Lang::System, t!("Sistem ayarını kullan").to_string()))
                    .chain(Lang::all().into_iter().map(|l| (l, l.native_name().to_string())))
                    .collect(),
                |s, v| s.language = v,
            ),
        ),
        card(
            p,
            L::CalendarClock,
            t!("Tarih biçimi"),
            Some(t!("Uygulama: yakın zamanlar \"5 dakika önce\", eskileri Windows'un biçiminde; Sistem: her zaman Windows'un tarih ve saat biçimi; Evrensel: 2026-11-05 13:45")),
            dropdown(
                "datefmt",
                p,
                s.date_format,
                vec![
                    (DatePref::Application, t!("Uygulama").into()),
                    (DatePref::System, t!("Sistem").into()),
                    (DatePref::Universal, t!("Evrensel").into()),
                ],
                |s, v| s.date_format = v,
            ),
        ),
    ];
    let startup_dd = dropdown(
        "startup",
        p,
        s.startup,
        vec![
            (StartupPref::Continue, t!("Kaldığınız yerden devam edin").into()),
            (StartupPref::NewTab, t!("Yeni sekme aç").into()),
            (StartupPref::Pages, t!("Belirli sayfaları aç").into()),
        ],
        |s, v| s.startup = v,
    );
    let pages = s.startup_pages.clone();
    let pp = *p;
    v.push(expander(
        "startup",
        p,
        L::Power,
        t!("Başlangıç ayarları"),
        None,
        Some(startup_dd),
        move || {
            let mut rows: Vec<AnyElement> = pages
                .iter()
                .enumerate()
                .map(|(i, page)| {
                    let shown = if page.is_empty() { t!("Ana Sayfa").to_string() } else { page.clone() };
                    sub(
                        &pp,
                        &shown,
                        None,
                        button(("sp-del", i), &pp, t!("Kaldır"), move |_, cx| settings::update(cx, |s| {
                            if i < s.startup_pages.len() {
                                s.startup_pages.remove(i);
                            }
                        })),
                    )
                })
                .collect();
            rows.push(sub(
                &pp,
                t!("Belirli sayfalar"),
                Some(t!("\"Belirli sayfaları aç\" seçiliyken açılır.")),
                button("sp-use", &pp, t!("Şu an açık sekmeleri kullan"), |_, cx| {
                    settings::update(cx, |s| {
                        s.startup_pages = s.session_tabs.clone();
                        s.startup = StartupPref::Pages;
                    })
                }),
            ));
            rows
        },
        cx,
    ));
    v.push(card(
        p,
        L::Plus,
        t!("Yeni sekme şunu açar"),
        Some(t!("Ctrl+T, + düğmesi ve sekme menüsü. Sekmeyi çoğalt (Ctrl+Shift+K) her zaman aynı klasörü açar.")),
        dropdown(
            "new-tab-opens",
            p,
            s.new_tab_opens,
            vec![
                (crate::settings::NewTabOpens::Home, t!("Ana sayfa").to_string()),
                (crate::settings::NewTabOpens::Current, t!("Açık olan klasör").to_string()),
                (crate::settings::NewTabOpens::Folder, t!("Seçtiğim klasör").to_string()),
            ],
            |s, v| s.new_tab_opens = v,
        ),
    ));
    // the folder of "Seçtiğim klasör" (D532 on GitHub Discussions)
    if s.new_tab_opens == crate::settings::NewTabOpens::Folder {
        let shown = if s.new_tab_folder.is_empty() { t!("Henüz seçilmedi: yeni sekmeler Ana sayfayı açar").to_string() } else { s.new_tab_folder.clone() };
        v.push(card(
            p,
            L::FolderOpen,
            t!("Yeni sekmenin klasörü"),
            Some(&shown),
            button("new-tab-folder", p, t!("Klasör seç…"), |_, cx| {
                // (on the shell thread, never inside the click: see the index's "Klasör ekle…")
                let (tx, rx) = futures::channel::oneshot::channel::<Option<std::path::PathBuf>>();
                let title = t!("Yeni sekmenin klasörü").to_string();
                rf_win::sta::run(move |owner| {
                    let _ = tx.send(rf_win::dialogs::pick(owner, &title, rf_win::dialogs::Pick::Folder));
                });
                cx.spawn(async move |cx| {
                    let Ok(Some(dir)) = rx.await else { return };
                    let d = dir.to_string_lossy().to_string();
                    cx.update(|cx| settings::update(cx, |s| s.new_tab_folder = d));
                })
                .detach();
            }),
        ));
    }
    v.push(card(
        p,
        L::X,
        t!("Son sekme kapatılınca"),
        Some(t!("Ctrl+W ya da sekmenin X düğmesi, pencerede tek sekme kalmışken")),
        dropdown(
            "last-tab-close",
            p,
            s.last_tab_close,
            vec![(crate::settings::LastTabClose::Window, t!("Pencereyi kapat").to_string()), (crate::settings::LastTabClose::Home, t!("Ana sayfaya dön").to_string())],
            |s, v| s.last_tab_close = v,
        ),
    ));
    v.push(card(p, L::SquarePlus, t!("Her zaman yeni açılan sekmeye geç"), None, sw("focus-tab", p, s.focus_new_tab, |s, v| s.focus_new_tab = v)));
    v.push(card(
        p,
        L::PanelLeftOpen,
        t!("Benzer komutlar satırın yanında düğme olarak"),
        Some(t!("Sağ tık menüsünde yönetici olarak çalıştırma, yeni sekmede açma, sola döndürme ve diğer panele taşıma, ana komutun satırının solunda küçük bir düğmedir. Kapalıyken her biri ayrı bir satırdır.")),
        sw("menu-side", p, s.menu_side_buttons, |s, v| s.menu_side_buttons = v),
    ));
    v.push(card(
        p,
        L::ListPlus,
        t!("Sağ tık menüsünde her zaman tüm komutlar"),
        Some(t!("Kapalıyken seyrek kullanılan komutlar (Çoğalt, Kullanan programlar, Kalıcı olarak sil, Kısayol oluştur, takma ad, disk kullanımı…) Shift basılıyken gelir: Shift+sağ tık ya da Shift+F10.")),
        sw("menu-all", p, s.menu_show_all, |s, v| s.menu_show_all = v),
    ));
    v.push(card(
        p,
        L::X,
        t!("Sekmelerde kapatma düğmesi"),
        Some(t!("Kapalıyken yer sekmenin adına kalır; sekme orta tıkla ya da Ctrl+W ile kapanır")),
        sw("tab-close-btn", p, s.tab_close_buttons, |s, v| s.tab_close_buttons = v),
    ));
    v.push(card(
        p,
        L::ArrowUpToLine,
        t!("Pencere büyükken sekmeler ekranın üst kenarına kadar"),
        Some(t!("İmleci ekranın en üstüne atıp sekmeye tıklayabilirsiniz. Kapalıyken sekmelerin üstündeki şerit pencereyi tutup çekmek için kalır.")),
        sw("tabs-reach-top", p, s.tabs_reach_top, |s, v| s.tabs_reach_top = v),
    ));
    v.push(card(
        p,
        L::TextCursorInput,
        t!("Yeni sekmede adres çubuğuna yaz"),
        Some(t!("Ctrl+T ve + düğmesi: bir yolu hemen yazabilir ya da yapıştırabilirsiniz")),
        sw("new-tab-address", p, s.new_tab_address, |s, v| s.new_tab_address = v),
    ));
    v.push(card(
        p,
        L::Keyboard,
        t!("Ctrl+1–9 ile sekmeler arasında geç"),
        Some(t!("Ctrl+1–8 ilgili sekmeye geçer; Ctrl+9 son ya da 9. sekmeye geçer.")),
        sw("ctrl-number-tabs", p, s.ctrl_number_tabs, |s, v| s.ctrl_number_tabs = v),
    ));
    if s.ctrl_number_tabs {
        v.push(card(
            p,
            L::ArrowRight,
            t!("Ctrl+9 son sekmeye geçsin"),
            Some(t!("Kapalıyken Ctrl+9, 9. sekmeye geçer.")),
            sw("ctrl-9-last-tab", p, s.ctrl_9_last_tab, |s, v| s.ctrl_9_last_tab = v),
        ));
    }
    v.push(card(
        p,
        L::Settings,
        t!("Ayarlar ve Geri Dönüşüm Kutusu yeni sekmede açılsın"),
        Some(t!("Açık klasör yerinde kalır. Giriş sayfasından ya da bu iki sayfadan birinden açılınca aynı sekmede açılırlar.")),
        sw("pages-new-tab", p, s.pages_in_new_tab, |s, v| s.pages_in_new_tab = v),
    ));
    v.push(card(
        p,
        L::AppWindow,
        t!("Diğer programlardan açılan klasörler yeni pencerede açılsın"),
        Some(t!("Win+E, masaüstü ya da başka bir program bir klasör açtığında açık pencerede yeni sekme yerine yeni bir pencere açılır.")),
        sw("launch-newwin", p, s.launch_in_new_window, |s, v| s.launch_in_new_window = v),
    ));
    v.push(card(
        p,
        L::Save,
        t!("Kayıtlı oturumlar bu pencerede açılsın"),
        Some(t!("Sekme menüsünden açılan oturum, yeni pencere yerine bu penceredeki sekmelerin yerini alır (kapanan sekmeler Ctrl+Shift+T ile geri gelir).")),
        sw("session-here", p, s.sessions_in_this_window, |s, v| s.sessions_in_this_window = v),
    ));

    v.push(section(p, t!("Çift bölme")));
    v.push(card(p, L::Columns2, t!("Yeni sekmeleri çift bölmeyle aç"), None, sw("dual-new", p, s.dual_pane_new_tabs, |s, v| s.dual_pane_new_tabs = v)));
    v.push(card(
        p,
        L::FolderOpen,
        t!("Çift bölmede her bölmenin yolu"),
        Some(t!("Her bölmenin üstünde kendi klasörünün yolu durur; adres çubuğu yalnızca etkin bölmeninkini gösterir")),
        sw("dual-paths", p, s.dual_pane_paths, |s, v| s.dual_pane_paths = v),
    ));
    v.push(card(
        p,
        L::Columns2,
        t!("Çift bölmede sekmede iki bölmenin klasörü"),
        Some(t!("Çift bölmeli sekme başlığında her iki bölmenin klasörünü gösterir (sol bölme önce); etkin bölmenin kısmı vurgulanır")),
        sw("dual-tab-titles", p, s.dual_pane_tab_titles, |s, v| s.dual_pane_tab_titles = v),
    ));
    v.push(card(
        p,
        L::SquareSplitHorizontal,
        t!("Çift bölme yönü"),
        None,
        dropdown(
            "dual-dir",
            p,
            s.dual_pane_vertical,
            vec![(true, t!("Yan yana").into()), (false, t!("Alt alta").into())],
            |s, v| s.dual_pane_vertical = v,
        ),
    ));

    v.push(section(p, t!("Sağ tık menüsü")));
    let m = s.menu.clone();
    let pp = *p;
    v.push(expander(
        "ctx",
        p,
        L::SquareMenu,
        t!("Bağlam menüsü seçenekleri"),
        Some(t!("Menüde hangi komutların görüneceği")),
        None,
        move || {
            type Set = fn(&mut Settings, bool);
            let rows: [(&str, bool, Set); 18] = [
                (t!("Yeni sekmede aç"), m.open_in_new_tab, |s, v| s.menu.open_in_new_tab = v),
                (t!("Yeni sekmede arka planda aç"), m.open_in_background_tab, |s, v| s.menu.open_in_background_tab = v),
                (t!("Yeni pencerede aç"), m.open_in_new_window, |s, v| s.menu.open_in_new_window = v),
                (t!("Öğe yolunu kopyala"), m.copy_path, |s, v| s.menu.copy_path = v),
                (t!("Kısayol oluştur"), m.create_shortcut, |s, v| s.menu.create_shortcut = v),
                (t!("Kenar çubuğuna sabitle"), m.pin, |s, v| s.menu.pin = v),
                (t!("Sıkıştır / Çıkar"), m.compress, |s, v| s.menu.compress = v),
                (t!("Dönüştür"), m.convert, |s, v| s.menu.convert = v),
                (t!("Etiketler"), m.tags, |s, v| s.menu.tags = v),
                (t!("Seç"), m.select, |s, v| s.menu.select = v),
                (t!("Rafa ekle"), m.shelf, |s, v| s.menu.shelf = v),
                (t!("Terminalde aç"), m.terminal, |s, v| s.menu.terminal = v),
                (t!("Gönder"), m.send_to, |s, v| s.menu.send_to = v),
                (t!("Yazdır"), m.print, |s, v| s.menu.print = v),
                (t!("Aç"), m.open, |s, v| s.menu.open = v),
                (t!("Özellikler"), m.properties, |s, v| s.menu.properties = v),
                (t!("Yenile"), m.refresh, |s, v| s.menu.refresh = v),
                (t!("Gizli öğeleri göster"), m.show_hidden, |s, v| s.menu.show_hidden = v),
            ];
            rows.into_iter()
                .enumerate()
                .map(|(i, (label, on, set))| sub(&pp, label, None, switch(("ctx-sw", i), &pp, on, move |_, cx| settings::update(cx, |s| set(s, !on)))))
                .collect()
        },
        cx,
    ));
    v.push(card(
        p,
        L::Ellipsis,
        t!("Kabuk uzantılarını alt menüye taşı"),
        Some(t!("Kapalıyken diğer uygulamaların öğeleri menünün sonunda listelenir.")),
        sw("shell-sub", p, s.menu.shell_submenu, |s, v| s.menu.shell_submenu = v),
    ));
    // Windows' pictures in the menus without the rest of the Explorer look (issue 407); in that look they are there already
    if !s.windows_file_explorer_theme {
        v.push(card(
            p,
            L::Image,
            t!("Menülerde Windows simgeleri"),
            Some(t!("Sağ tık menülerinde Windows Dosya Gezgini'nin simgeleri, görünümün geri kalanı değişmeden")),
            sw("menu-win-icons", p, s.menu_windows_icons, |s, v| s.menu_windows_icons = v),
        ));
    }
    v.push(card(
        p,
        L::ListFilter,
        t!("Aynı komut iki menüde de varsa klasik olanı göster"),
        Some(t!("Bazı uygulamalar (NanaZip gibi) komutlarını hem Windows 11'in yeni menüsüne hem klasik menüye ekler; menüde yalnızca biri gösterilir. Kapalıyken yeni menüdeki, açıkken klasik menüdeki kalır.")),
        sw("classic-cmds", p, s.menu.prefer_classic_commands, |s, v| s.menu.prefer_classic_commands = v),
    ));
    v.push(card(
        p,
        L::Menu,
        t!("Her zaman klasik Windows menüsü"),
        Some(t!("Sağ tık, rustyfiles'ın menüsü yerine Windows'un klasik menüsünü açar (Shift+sağ tıkın açtığı)")),
        sw("always-classic", p, s.menu.always_classic, |s, v| s.menu.always_classic = v),
    ));
    v.push(card(
        p,
        L::Clock,
        t!("Son kullanılanlarda rustyfiles menüsü"),
        Some(t!("Giriş sayfasındaki son kullanılan öğelere sağ tıklayınca Windows'un menüsü yerine rustyfiles'ın menüsü açılır")),
        sw("home-recent-menu", p, s.menu.home_recent_own_menu, |s, v| s.menu.home_recent_own_menu = v),
    ));
    v.push(card(
        p,
        L::Zap,
        t!("Menüyü önceden hazırla"),
        Some(t!("İşaretçi bir öğenin üzerinde durunca menüsü arka planda hazırlanır; sağ tık onu hemen açar. Windows'un kabuk uzantıları sağ tıklanmayan öğeler için de çalışır.")),
        sw("prepare-menu", p, s.menu.prepare_on_hover, |s, v| s.menu.prepare_on_hover = v),
    ));

    v.push(section(p, t!("Kaydırma")));
    v.push(card(p, L::ChevronsUpDown, t!("Akıcı kaydırma"), None, sw("smooth", p, s.smooth_scroll, |s, v| s.smooth_scroll = v)));
    v.extend(crate::snip::settings_cards(p, s));
    v
}

/// Background tint presets (Files' "Background color").
const TINTS: [(&str, u32); 15] = [
    ("Altın sarısı", 0xC19C00),
    ("Turuncu", 0xCA5010),
    ("Tuğla kırmızısı", 0xA4262C),
    ("Kırmızı", 0xD13438),
    ("Gül", 0xE3008C),
    ("Mor", 0x881798),
    ("İris", 0x8764B8),
    ("Mavi", 0x0078D4),
    ("Deniz", 0x038387),
    ("Nane", 0x00B294),
    ("Yeşil", 0x107C10),
    ("Kamuflaj", 0x486860),
    ("Fırtına", 0x4C4A48),
    ("Mavi gri", 0x515C6B),
    ("Gri", 0x7A7574),
];

/// The background material card. While Glass is in use (chosen, or forced for this run) a note under it says what the material
/// costs; if the engine gave up on a window, another note says why that window is on Mica.
/// The letter of a drive's root ("V:" or "V:\"), in capitals; `None` for any other path.
pub(crate) fn drive_letter(path: &std::path::Path) -> Option<char> {
    let s = path.to_string_lossy();
    let rest = s.strip_suffix(['\\', '/']).unwrap_or(&s);
    let mut c = rest.chars();
    match (c.next(), c.next(), c.next()) {
        (Some(l), Some(':'), None) if l.is_ascii_alphabetic() => Some(l.to_ascii_uppercase()),
        _ => None,
    }
}

/// Hides a drive from the lists of places, or shows it again: the setting's letters, each once, in order.
pub(crate) fn set_drive_hidden(s: &mut Settings, letter: char, hide: bool) {
    let mut mask = rf_win::drives::mask_of_letters(&s.hidden_drives);
    if let Some(bit) = rf_win::drives::letter_bit(letter) {
        if hide { mask |= bit } else { mask &= !bit }
    }
    s.hidden_drives = rf_win::drives::letters_of_mask(mask).into_iter().map(String::from).collect();
}

/// Which drives are listed: a button per drive letter that is there now (and per letter the setting names, there or not), pressed
/// in while the drive is hidden.
fn hidden_drives_card(p: &Palette, s: &Settings) -> AnyElement {
    let hidden = rf_win::drives::mask_of_letters(&s.hidden_drives);
    let by_explorer = rf_win::drives::policy_hidden();
    let present = rf_win::drives::drive_mask();
    let mut row = h_flex().flex_wrap().gap_2().items_center().justify_end();
    for (i, letter) in rf_win::drives::letters_of_mask(present | hidden).into_iter().enumerate() {
        let bit = rf_win::drives::letter_bit(letter).unwrap_or(0);
        let (off, forced) = (hidden & bit != 0, by_explorer & bit != 0);
        row = row.child(
            h_flex()
                .id(("drive-hide", i))
                .h(px(28.))
                .px_2p5()
                .gap_1p5()
                .items_center()
                .rounded(theme::RADIUS_SM)
                .border_1()
                .border_color(if off { p.accent } else { p.border })
                .bg(p.hover)
                .text_sm()
                .when(off || forced, |d| d.text_color(p.text_secondary))
                .cursor_pointer()
                .hover(|d| d.bg(p.pressed))
                .child(Icon::new(if off || forced { L::EyeOff } else { L::Eye }).size(px(14.)))
                .child(format!("{letter}:"))
                .on_click(move |_, _, cx| settings::update(cx, move |s| set_drive_hidden(s, letter, !off))),
        );
    }
    card(
        p,
        L::HardDrive,
        t!("Gizlenen sürücüler"),
        Some(t!("Gizlediğiniz sürücü kenar çubuğunda, Ana Sayfa'da ve adres çubuğunun sürücü listesinde görünmez; adresini yazarak yine açabilirsiniz. Explorer'ın gizlediği sürücüler burada da gizlidir.")),
        row.into_any_element(),
    )
}

/// The cloud and WSL places hidden from the sidebar one by one (its menu: "Hide this place"): a click shows one again.
fn hidden_places_card(p: &Palette, s: &Settings) -> AnyElement {
    let mut row = h_flex().flex_wrap().gap_2().items_center().justify_end();
    for (i, path) in s.hidden_places.iter().enumerate() {
        let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.clone());
        let key = path.clone();
        row = row.child(
            h_flex()
                .id(("place-hide", i))
                .h(px(28.))
                .px_2p5()
                .gap_1p5()
                .items_center()
                .rounded(theme::RADIUS_SM)
                .border_1()
                .border_color(p.accent)
                .bg(p.hover)
                .text_sm()
                .text_color(p.text_secondary)
                .cursor_pointer()
                .hover(|d| d.bg(p.pressed))
                .child(Icon::new(L::EyeOff).size(px(14.)))
                .child(name)
                .on_click(move |_, _, cx| {
                    let key = key.clone();
                    settings::update(cx, move |s| s.hidden_places.retain(|h| *h != key))
                }),
        );
    }
    card(
        p,
        L::Cloud,
        t!("Kenar çubuğunda gizlenen konumlar"),
        Some(t!("Kenar çubuğunda tek tek gizlediğiniz konumlar. Birine tıklayınca yeniden görünür.")),
        row.into_any_element(),
    )
}

/// The colours offered for the accent (Fluent's own set): blue, purple, magenta, red, orange, yellow, green, teal, grey.
pub(crate) const ACCENT_CHOICES: [u32; 9] = [0x0078D4, 0x8764B8, 0xE3008C, 0xE81123, 0xF7630C, 0xFFB900, 0x107C10, 0x00B7C3, 0x69797E];

/// What the accent setting holds after the user wrote a colour of their own: the colour as it is kept, or what to tell them.
pub(crate) fn accent_answer(text: &str) -> Result<String, String> {
    rf_win::accent::parse_hex(text).map(rf_win::accent::to_hex).ok_or_else(|| t!("Rengi #RRGGBB biçiminde yazın, örneğin #F7630C.").to_string())
}

/// The accent colour: Windows' own, one of a few, or any colour written as #RRGGBB.
fn accent_card(p: &Palette, s: &Settings) -> AnyElement {
    let current = rf_win::accent::parse_hex(&s.accent_color);
    let chip = |id: &'static str, label: &'static str, on: bool, p: &Palette| {
        div()
            .id(id)
            .h(px(28.))
            .px_3()
            .flex()
            .items_center()
            .rounded(theme::RADIUS_SM)
            .border_1()
            .border_color(if on { p.accent } else { p.border })
            .bg(p.hover)
            .text_sm()
            .cursor_pointer()
            .hover(|d| d.bg(p.pressed))
            .child(label)
    };
    let mut row = h_flex().flex_wrap().gap_2().items_center().justify_end().child(chip("accent-windows", t!("Windows'un rengi"), current.is_none(), p).on_click(|_, _, cx| settings::update(cx, |s| s.accent_color.clear())));
    // the swatches as one block: on a narrow window they go down a line together, not one by one (Discord, 2026-12-01: "the accent
    // colour row wraps too much")
    let mut swatches = h_flex().flex_shrink_0().gap_2().items_center();
    for (i, c) in ACCENT_CHOICES.into_iter().enumerate() {
        let on = current == Some(c);
        swatches = swatches.child(
            div()
                .id(("accent-choice", i))
                .size(px(24.))
                .rounded_full()
                .bg(gpui_kit::rgb(c))
                .border_2()
                .border_color(if on { p.text } else { gpui_kit::transparent_black() })
                .cursor_pointer()
                .on_click(move |_, _, cx| settings::update(cx, move |s| s.accent_color = rf_win::accent::to_hex(c))),
        );
    }
    row = row.child(swatches);
    let custom = current.is_some_and(|c| !ACCENT_CHOICES.contains(&c));
    let shown = s.accent_color.clone();
    row = row.child(chip("accent-own", t!("Kendi rengim…"), custom, p).on_click(move |_, window, cx| {
        crate::prompt::show(
            t!("Vurgu rengi"),
            Some(t!("Rengi #RRGGBB biçiminde yazın, örneğin #F7630C.").to_string()),
            Some((shown.clone(), "#F7630C".to_string())),
            vec![
                crate::prompt::Button::new(t!("Kaydet"), crate::prompt::Kind::Primary, |text, _, cx| {
                    let color = accent_answer(&text.unwrap_or_default())?;
                    settings::update(cx, move |s| s.accent_color = color);
                    Ok(())
                }),
                crate::prompt::Button::cancel(),
            ],
            window,
            cx,
        );
    }));
    card(
        p,
        L::Palette,
        t!("Vurgu rengi"),
        Some(t!("Düğmelerin, seçimin ve vurguların rengi: Windows'unki, hazır renklerden biri ya da kendi yazdığınız renk.")),
        row.into_any_element(),
    )
}

fn backdrop_card(p: &Palette, s: &Settings) -> AnyElement {
    // On a Windows without materials (before Windows 11 22H2, issue 24) the windows are "Solid" whatever was chosen, and that is the
    // one choice shown: a list of four materials that all look the same would be a lie.
    let choices = if crate::settings::materials_available() {
        vec![
            (BackdropPref::Mica, "Mica".into()),
            (BackdropPref::MicaAlt, "Mica Alt".into()),
            (BackdropPref::Acrylic, t!("Akrilik").into()),
            (BackdropPref::Solid, t!("Düz").into()),
            // a product name: only the "(experimental)" is translated
            (BackdropPref::Glass, "HyperGlass".into()),
        ]
    } else {
        // Windows 10: Acrylic and HyperGlass for the main window only (issue 78); Mica left the window see-through there
        vec![
            (BackdropPref::Solid, t!("Düz").into()),
            (BackdropPref::Acrylic, t!("Akrilik").into()),
            (BackdropPref::Glass, "HyperGlass".into()),
        ]
    };
    let control = dropdown("backdrop", p, s.backdrop_in_use(), choices, |s, v| s.backdrop = v);
    let mut notes: Vec<String> = Vec::new();
    if !crate::settings::materials_available() && s.backdrop_in_use() != BackdropPref::Solid {
        notes.push(t!("Bu Windows sürümünde malzeme yalnızca ana pencereye uygulanır; menüler ve açılır pencereler düz kalır.").to_string());
    }
    if s.backdrop_in_use() == BackdropPref::Glass || crate::glass::forced() {
        notes.push(t!("Pencerenin arkasındaki görüntüyü gerçek cam gibi büker ve buzlar. Ekranı canlı izleyip her değişiklikte yeniden çizdiği için Mica'dan daha fazla ekran kartı ve pil kullanır.").to_string());
        // Only where the windows really are hidden from screenshots: with a capture session (Windows 11 24H2 and the border-free capture
        // permission) they are not, and the line would be untrue. Before the engine has chosen (no window has glass yet) the mode is
        // Off and the line is left out; the page is drawn again once the glass is on the window.
        if rf_win::glass::capture_mode() == rf_win::glass::CaptureMode::Affinity {
            notes.push(t!("Bu Windows sürümünde ya da ekran görüntüsü kenarlığı izni kapalıyken rustyfiles pencereleri ekran görüntülerinde, kayıtlarda ve ekran paylaşımında görünmez.").to_string());
        }
        if let Some(why) = crate::glass::failure() {
            notes.push(t!("Cam başlatılamadı: {reason}. Mica kullanılıyor.").replace("{reason}", &why));
        }
    }
    shell(p)
        // (the line about Mica is left out where Windows has no Mica to choose)
        .child(card_body(
            p,
            L::Layers,
            t!("Arka plan malzemesi").into(),
            crate::settings::materials_available().then(|| t!("Mica masaüstü renginden ton alır; Mica Alt daha renklidir.").into()),
            Some(control),
        ))
        .children(notes.into_iter().map(|n| div().pl(px(56.)).pr_4().pb_3().text_xs().text_color(p.text_secondary).child(n)))
        // with Solid: ClearType text (opaque windows; Mica under it otherwise, so that a switch back is instant)
        .when(s.backdrop_in_use() == BackdropPref::Solid, |d| {
            d.child(sub(
                p,
                t!("ClearType yazı"),
                Some(t!("Pencereler ve düz menüler opak olur, yazılar Windows'un ClearType yumuşatmasıyla çizilir. Yeniden açılan pencerelerde geçerli olur.")),
                sw("solid-cleartype", p, s.solid_cleartype, |s, v| s.solid_cleartype = v),
            ))
        })
        .into_any_element()
}

// ---------------------------------------------------------------- HyperGlass settings

/// The five HyperGlass values, in the order of the card. The number is also the slider's id.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Hg {
    Frost,
    Tint,
    Refraction,
    Saturation,
    Surface,
}

impl Hg {
    const ALL: [Hg; 5] = [Hg::Frost, Hg::Tint, Hg::Refraction, Hg::Saturation, Hg::Surface];

    fn get(self, s: &Settings) -> u8 {
        match self {
            Hg::Frost => s.hg_frost,
            Hg::Tint => s.hg_tint,
            Hg::Refraction => s.hg_refraction,
            Hg::Saturation => s.hg_saturation,
            Hg::Surface => s.hg_surface,
        }
        .min(100)
    }

    fn set(self, s: &mut Settings, v: u8) {
        let v = v.min(100);
        match self {
            Hg::Frost => s.hg_frost = v,
            Hg::Tint => s.hg_tint = v,
            Hg::Refraction => s.hg_refraction = v,
            Hg::Saturation => s.hg_saturation = v,
            Hg::Surface => s.hg_surface = v,
        }
    }

    fn title(self) -> &'static str {
        match self {
            Hg::Frost => t!("Bulanıklık"),
            Hg::Tint => t!("Ton"),
            Hg::Refraction => t!("Kenar kırılması"),
            Hg::Saturation => t!("Renk doygunluğu"),
            Hg::Surface => t!("Yüzey örtüsü"),
        }
    }

    fn desc(self) -> &'static str {
        match self {
            Hg::Frost => t!("Camın arkasındaki görüntünün ne kadar bulanık olacağı. En solda cam berraktır."),
            Hg::Tint => t!("Temanın tonunun görüntünün üstündeki payı. Koyu temada görüntüyü biraz da karartır."),
            Hg::Refraction => t!("Camın kenarlarının arkasındaki görüntüyü ne kadar büktüğü."),
            Hg::Saturation => t!("Camdan görünen renklerin canlılığı."),
            Hg::Surface => t!("Uygulamanın kendi yüzeylerinin camın üstündeki örtüsü. En solda örtü yoktur; yazılar zor okunabilir."),
        }
    }
}

/// Width of a slider's track and the thumb's size, in logical px.
const SLIDER_W: f32 = 220.;
const THUMB: f32 = 18.;

/// The value (0..=100) under the pointer: `left` and `width` are the slider's box, the thumb's centre travels from half a thumb
/// inside the left edge to half a thumb inside the right one. `thumb` is the thumb's width AT REST (the classic round one, or the
/// liquid capsule): a thumb that grows while it is held keeps its centre, so the mapping does not change under the pointer.
#[cfg(test)]
fn slider_value_at(x: f32, left: f32, width: f32, thumb: f32) -> u8 {
    slider_position_at(x, left, width, thumb, 100)
}

/// [`slider_value_at`] for a slider over the positions 0..=`max`.
fn slider_position_at(x: f32, left: f32, width: f32, thumb: f32, max: u8) -> u8 {
    let run = (width - thumb).max(1.0);
    (((x - left - thumb / 2.0) / run).clamp(0.0, 1.0) * f32::from(max)).round() as u8
}

/// The slider being dragged right now (its id), `usize::MAX` for none. Together with `cx.has_active_drag()` it says whether to draw
/// the thumb as the held glass lens: the press state of the element is cleared by GPUI when a drag starts.
static HG_DRAG: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(usize::MAX);

/// The slider the pointer went down on and has not been let go from (its id), `usize::MAX` for none. A mouse-up anywhere else on the page
/// reaches every slider as a mouse-up-out; only the one that was pressed has a gesture to end.
static SLIDER_HELD: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(usize::MAX);

/// What a key does to a slider that has the focus: the new value, or `None` for a key the slider does not take. Arrows move by 1,
/// Shift or Page Up / Down by 10, Home and End jump to the ends.
#[cfg(test)]
fn slider_key(value: u8, key: &str, shift: bool) -> Option<u8> {
    slider_key_in(value, key, shift, 100, 10)
}

/// [`slider_key`] for a slider over the positions 0..=`max` whose big step (Shift, Page Up / Down) is `big`.
fn slider_key_in(value: u8, key: &str, shift: bool, max: u8, big: u8) -> Option<u8> {
    let step = if shift { big } else { 1 };
    let v = value.min(max);
    Some(match key {
        "left" | "down" => v.saturating_sub(step),
        "right" | "up" => v.saturating_add(step).min(max),
        "pagedown" => v.saturating_sub(big),
        "pageup" => v.saturating_add(big).min(max),
        "home" => 0,
        "end" => max,
        _ => return None,
    })
}

/// What a slider drags: which of the five.
#[derive(Clone)]
struct SliderDrag(usize);

struct SliderGhost;
impl Render for SliderGhost {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
    }
}

/// A slider for one HyperGlass value: a thin track filled up to a round thumb. A click puts the thumb there, a drag moves it, the arrow
/// keys move it while it has the focus. Every step is applied and drawn at once and written to the file once the steps settle.
fn slider(which: Hg, p: &Palette, value: u8, focus: FocusHandle, dragging: bool) -> AnyElement {
    let spec = SliderSpec {
        id: which as usize,
        max: 100,
        big: 10,
        get: std::rc::Rc::new(move |cx| which.get(cx.global::<Settings>())),
        apply: std::rc::Rc::new(move |v, cx| {
            if which.get(cx.global::<Settings>()) != v {
                settings::update_live(cx, |s| which.set(s, v));
            }
        }),
        release: None,
    };
    slider_for(spec, p, value, focus, dragging)
}

/// What a slider is bound to: the positions 0..=`max` it offers, how to read the current one and what to do for each step. The
/// HyperGlass sliders are positions 0..=100; the Dock page's size slider (`dock::size_slider`) is positions 0..=15.
#[derive(Clone)]
pub(crate) struct SliderSpec {
    /// Tells the sliders apart (focus, drag, the lens): the HyperGlass ones are 0..=4.
    pub id: usize,
    pub max: u8,
    /// The step of Shift and of Page Up / Down.
    pub big: u8,
    /// The position the setting has now (read at a key press).
    pub get: std::rc::Rc<dyn Fn(&App) -> u8>,
    /// A step of a click, a drag or a key: the new position.
    pub apply: SliderStep,
    /// The pointer was let go: nothing more is coming for now. (Not called for keys: see the key handler.)
    pub release: Option<SliderEnd>,
}

/// What a slider does for a step (the new position) and at the end of a gesture.
pub(crate) type SliderStep = std::rc::Rc<dyn Fn(u8, &mut App)>;
pub(crate) type SliderEnd = std::rc::Rc<dyn Fn(&mut App)>;

/// The slider of a [`SliderSpec`], with its box and thumb as the HyperGlass sliders have them.
pub(crate) fn slider_for(spec: SliderSpec, p: &Palette, value: u8, focus: FocusHandle, dragging: bool) -> AnyElement {
    let id = spec.id;
    let max = spec.max.max(1);
    let value = value.min(max);
    let frac = f32::from(value) / f32::from(max);
    let liquid = p.liquid;
    // the width the pointer mapping leaves the thumb at rest (a thumb that grows while held keeps its centre)
    let thumb_w = if liquid { crate::liquid::SL_REST_W } else { THUMB };
    // (only the liquid thumb needs to know that the pointer is down on the slider; the classic slider stays as it was)
    let group: Option<SharedString> = liquid.then(|| format!("hg-slider-{id}").into());
    let bounds = std::rc::Rc::new(std::cell::Cell::new(Bounds::<Pixels>::default()));
    let (apply_down, apply_drag, apply_key) = (spec.apply.clone(), spec.apply.clone(), spec.apply.clone());
    let (b_down, f_down) = (bounds.clone(), focus.clone());
    let (b_drag, b_probe) = (bounds.clone(), bounds.clone());
    let root = div()
        .id(("hg-slider", id))
        .when_some(group.clone(), |d, g| d.group(g))
        .relative()
        .w(px(SLIDER_W))
        .h(px(24.))
        .flex_shrink_0()
        .cursor_pointer()
        .rounded(px(12.))
        .border_1()
        .border_color(transparent_black())
        .track_focus(&focus)
        .focus(|s| s.border_color(p.accent))
        // (the probe records where the slider is; the mouse events do not carry the element's box)
        .child(canvas(move |b, _, _| b_probe.set(b), |_, _, _, _| {}).absolute().top_0().left_0().size_full());
    let root = if let Some(group) = group {
        // a 4 px track and a capsule thumb that turns into a glass lens while it is held (no clip anywhere: it overhangs the box)
        let (track, lane) = crate::liquid::slider_parts(id, group, p, SLIDER_W - 2.0 * crate::liquid::SL_BORDER, frac, dragging);
        root.child(track).child(lane)
    } else {
        root.child(
            // the track, filled up to the thumb
            div()
                .absolute()
                .left(px(THUMB / 2.0))
                .right(px(THUMB / 2.0))
                .top(px(10.))
                .h(px(4.))
                .rounded_full()
                .bg(p.pressed)
                .child(div().h_full().rounded_full().bg(p.accent).w(relative(frac))),
        )
        .child(
            // The thumb's lane is the slider's inner width less one thumb, and the thumb sits at a share of it. Measured from the
            // box the children are placed in (not from SLIDER_W), so it agrees with the track and with the pointer mapping whatever
            // the border takes: the root's 1 px focus border made a thumb placed by SLIDER_W stick out by 2 px at the far right.
            div().absolute().top(px(3.)).left_0().right(px(THUMB)).h(px(THUMB)).child(
                div()
                    .absolute()
                    .top_0()
                    .left(relative(frac))
                    .size(px(THUMB))
                    .rounded_full()
                    .bg(p.card_bg)
                    .border_1()
                    .border_color(p.border)
                    .child(div().m(px(4.)).size(px(8.)).rounded_full().bg(p.accent)),
            ),
        )
    };
    let root = root
        .on_mouse_down(MouseButton::Left, move |e, window, cx| {
            window.focus(&f_down, cx);
            SLIDER_HELD.store(id, std::sync::atomic::Ordering::Relaxed);
            let b = b_down.get();
            apply_down(slider_position_at(f32::from(e.position.x), f32::from(b.left()), f32::from(b.size.width), thumb_w, max), cx);
            cx.stop_propagation();
        })
        .on_drag(SliderDrag(id), |_, _, _, cx| cx.new(|_| SliderGhost))
        .on_drag_move(move |e: &DragMoveEvent<SliderDrag>, window, cx| {
            if e.drag(cx).0 == id {
                if liquid && HG_DRAG.swap(id, std::sync::atomic::Ordering::Relaxed) != id {
                    // the thumb turns into the held lens at the first step of the drag, even when the value did not change
                    window.refresh();
                }
                // the same box as a click uses (the probe's), so a click and a drag agree on the value under the pointer
                let b = b_drag.get();
                apply_drag(slider_position_at(f32::from(e.event.position.x), f32::from(b.left()), f32::from(b.size.width), thumb_w, max), cx);
            }
        })
        // (captured, so the arrows reach the slider before the file list's own shortcuts do)
        .capture_key_down({
            let get = spec.get.clone();
            let big = spec.big;
            move |ev: &KeyDownEvent, _, cx| {
                let now = get(cx);
                if let Some(v) = slider_key_in(now, ev.keystroke.key.as_str(), ev.keystroke.modifiers.shift, max, big) {
                    apply_key(v, cx);
                    // (no release here: a held key is a run of key presses, and a slider whose end does costly work (the dock's band
                    // and icons) would do it for each one. Whoever listens settles by itself once the steps stop.)
                    cx.stop_propagation();
                }
            }
        });
    let release = spec.release.clone();
    if !liquid && release.is_none() {
        return root.into_any_element();
    }
    // the thumb goes back to rest when the pointer is let go, on the slider or off it; a slider with something to do at the end of a drag
    // does it then
    let (release_in, release_out) = (release.clone(), release);
    root.on_mouse_up(MouseButton::Left, move |_, window, cx| {
        HG_DRAG.store(usize::MAX, std::sync::atomic::Ordering::Relaxed);
        window.refresh();
        if let Some(r) = &release_in
            && SLIDER_HELD.swap(usize::MAX, std::sync::atomic::Ordering::Relaxed) == id
        {
            r(cx);
        }
    })
    .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
        HG_DRAG.store(usize::MAX, std::sync::atomic::Ordering::Relaxed);
        window.refresh();
        if let Some(r) = &release_out
            && SLIDER_HELD.swap(usize::MAX, std::sync::atomic::Ordering::Relaxed) == id
        {
            r(cx);
        }
    })
    .into_any_element()
}

/// Whether the slider `id` is the one being dragged right now (for the lens thumb). A flag left by a drag that ended without its mouse-up
/// is cleared here.
pub(crate) fn slider_dragged(cx: &App, id: usize) -> bool {
    if !cx.has_active_drag() {
        HG_DRAG.store(usize::MAX, std::sync::atomic::Ordering::Relaxed);
        return false;
    }
    HG_DRAG.load(std::sync::atomic::Ordering::Relaxed) == id
}

/// The focus handle of slider `i`, made at the first call.
pub(crate) fn hg_focus(cx: &mut App, i: usize) -> FocusHandle {
    while ui(cx).hg_focus.len() <= i {
        let h = cx.focus_handle();
        ui(cx).hg_focus.push(h);
    }
    ui(cx).hg_focus[i].clone()
}

/// The HyperGlass card: five sliders for the look of the glass, each with its value, and a button back to the shipped look. Shown
/// under the backdrop card while the backdrop is Glass.
fn hyperglass_card(p: &Palette, s: &Settings, cx: &mut App) -> AnyElement {
    let reset = button("hg-reset", p, t!("Varsayılana dön"), |_, cx| settings::update(cx, |s| s.reset_hyperglass()));
    let mut rows: Vec<AnyElement> = Vec::new();
    if !cx.has_active_drag() {
        // No drag is on: whatever slider the flag still names lost its mouse-up (the page went away with the button down), and must not
        // show as held when some other drag starts.
        HG_DRAG.store(usize::MAX, std::sync::atomic::Ordering::Relaxed);
    }
    for which in Hg::ALL {
        let value = which.get(s);
        // dragged right now: the drag is on and it is this slider's (a flag left over from a drag that ended does not count)
        let dragging = cx.has_active_drag() && HG_DRAG.load(std::sync::atomic::Ordering::Relaxed) == which as usize;
        let control = h_flex()
            .gap_3()
            .items_center()
            .child(slider(which, p, value, hg_focus(cx, which as usize), dragging))
            .child(div().w(px(32.)).flex_shrink_0().text_right().text_sm().text_color(p.text_secondary).child(value.to_string()))
            .into_any_element();
        rows.push(sub(p, which.title(), Some(which.desc()), control));
    }
    // not a look but a cost: the glass of a window that is not in front stops following the screen (off by default)
    rows.push(sub(
        p,
        t!("Odakta değilken camı dondur"),
        Some(t!("Öndeki pencere değilse ve imleç üstünde durmuyorsa camın son görüntüsü kalır; arkada ne değişirse değişsin hiçbir şey yakalanmaz ya da çizilmez. Pencere öne gelince cam yeniden akar.")),
        sw("hg-freeze", p, s.hg_freeze_behind, |s, v| s.hg_freeze_behind = v),
    ));
    shell(p)
        .child(card_body(p, L::Sparkles, t!("HyperGlass ayarları").into(), Some(t!("Cam görünümünü ayarlayın. Değişiklikler açık tüm pencerelerde hemen görünür.").into()), Some(reset)))
        .child(div().h(px(1.)).bg(p.divider))
        .child(v_flex().py_1().children(rows))
        .into_any_element()
}

fn appearance(p: &Palette, s: &Settings, cx: &mut App) -> Vec<AnyElement> {
    let mut v: Vec<(AppearanceGroup, AnyElement)> = vec![
        (AppearanceGroup::Theme, card(
            p,
            L::SunMoon,
            t!("Tema"),
            None,
            dropdown(
                "theme",
                p,
                s.theme,
                vec![(ThemePref::System, t!("Sistem ayarını kullan").into()), (ThemePref::Light, crate::i18n::tx("Açık", "Light").into()), (ThemePref::Dark, t!("Koyu").into()), (ThemePref::Black, t!("Siyah (OLED)").into())],
                |s, v| s.theme = v,
            ),
        )),
        (AppearanceGroup::Theme, card(
            p,
            L::Image,
            t!("İkon teması").into(),
            Some(t!("Dosya ve klasör simgeleri. Sistem simgelerini kullanır; Freedesktop paketlerini listeden seçin ya da klasörü açın. Paketin varyasyonları varsa ayrıca seçilebilir.").into()),
            v_flex()
                .gap_2()
                .items_start()
                .child(
                    h_flex()
                        .gap_2()
                        .items_center()
                        .child(icon_pack_dropdown(p))
                        .child(icon_button("icon-theme-folder", p, L::FolderOpen, t!("Gözat"), open_icon_themes_folder)),
                )
                .children(icon_variant_dropdown(p))
                .into_any_element(),
        )),
        (AppearanceGroup::Theme, backdrop_card(p, s)),
        (AppearanceGroup::Theme, card(
            p,
            L::Layers,
            t!("Açılır menü malzemesi"),
            Some(t!("Bağlam menülerinin ve açılır listelerin arka planını belirler. Renkler seçili temayı izler.")),
            dropdown(
                "menu-material",
                p,
                s.menu_material,
                vec![
                    (settings::MenuMaterial::Automatic, t!("Otomatik").into()),
                    (settings::MenuMaterial::Mica, "Mica".into()),
                    (settings::MenuMaterial::MicaAlt, "Mica Alt".into()),
                    (settings::MenuMaterial::Acrylic, t!("Akrilik").into()),
                    (settings::MenuMaterial::Solid, t!("Düz").into()),
                    (settings::MenuMaterial::Glass, "HyperGlass".into()),
                ],
                |s, v| s.menu_material = v,
            ),
        )),
        (AppearanceGroup::Theme, accent_card(p, s)),
        (AppearanceGroup::Tabs, card(
            p,
            L::AppWindow,
            t!("Sekmeler adları kadar geniş"),
            Some(t!("Kapalıyken bütün sekmeler eşit genişlikte. Açıkken her sekme adına göre genişler, en az 72 ve en çok 220 piksel.")),
            sw("tabs-fit", p, s.tabs_fit_names, |s, v| s.tabs_fit_names = v),
        )),
        (AppearanceGroup::Tabs, card(
            p,
            L::FolderOpen,
            t!("Sekmede klasörün yolu"),
            Some(t!("Sekme, klasörün adı yerine tam yolunu küçük yazıyla gösterir; sığmayan kısım sondan kesilir.")),
            sw("tab-path", p, s.tab_shows_path, |s, v| s.tab_shows_path = v),
        )),
        (AppearanceGroup::Toolbar, card(
            p,
            L::Bookmark,
            t!("Yer imleri çubuğu"),
            Some(t!("Adres çubuğunun altında, tarayıcılardaki gibi; tarayıcıların yer imi dosyalarını (HTML) içe ve dışa aktarır")),
            sw("bookmarks-bar", p, s.bookmarks_bar, |s, v| s.bookmarks_bar = v),
        )),
        (AppearanceGroup::Toolbar, card(
            p,
            L::Bookmark,
            t!("Sürüklenen yer imine yer açılsın"),
            Some(t!("Sürüklenen yer imi yeni yerini hemen alır, diğerleri kayar (tarayıcı sekmeleri gibi)")),
            sw("bookmarks-live", p, s.bookmarks_live_drag, |s, v| s.bookmarks_live_drag = v),
        )),
        (AppearanceGroup::Tabs, card(
            p,
            L::SquareTerminal,
            t!("Sekmelerde terminal düğmesi"),
            Some(t!("Her klasör sekmesinde, o klasörde bir terminal açan düğme.")),
            sw("tab-terminal", p, s.tab_terminal_button, |s, v| s.tab_terminal_button = v),
        )),
        (AppearanceGroup::Window, card(
            p,
            L::Activity,
            t!("Animasyonlar"),
            Some(t!("Sekme açılırken ve kapanırken kısa geçişler. Hiçbir işi geciktirmez.")),
            dropdown(
                "animations",
                p,
                s.animations,
                vec![
                    (AnimPref::System, t!("Windows ayarına uy").into()),
                    (AnimPref::On, t!("Açık").into()),
                    (AnimPref::Off, t!("Kapalı").into()),
                ],
                |s, v| s.animations = v,
            ),
        )),
        (AppearanceGroup::Window, card(
            p,
            L::Folder,
            t!("Windows Dosya Gezgini görünümü"),
            None,
            sw("windows-file-explorer-theme", p, s.windows_file_explorer_theme, |s, v| s.windows_file_explorer_theme = v),
        )),
        (AppearanceGroup::Window, card(
            p,
            L::Ruler,
            t!("Dosya Gezgini'nin ölçüleri"),
            Some(t!("Windows Dosya Gezgini görünümünde onun ölçüleri: listede ve kenar çubuğunda 12 piksel Segoe UI (açık temada siyah), Ayrıntılar satırları 28, kenar çubuğu satırları 32 piksel")),
            sw("explorer-metrics", p, s.explorer_metrics, |s, v| s.explorer_metrics = v),
        )),
        (AppearanceGroup::Window, card(
            p,
            L::Menu,
            t!("Kompakt menüler"),
            Some(t!("Windows Dosya Gezgini görünümünde menüler Windows'un kendi menüsü boyutunda olur: daha sık satırlar ve 12 piksel yazı")),
            sw("compact-menus", p, s.compact_menus, |s, v| s.compact_menus = v),
        )),
        (AppearanceGroup::Toolbar, card(
            p,
            L::PanelTop,
            t!("Komut çubuğu yalnızca listenin üstünde"),
            Some(t!("Windows Dosya Gezgini görünümünde komut çubuğu kenar çubuğunun üstüne uzanmaz, bu görünüm kapalıyken olduğu gibi yalnızca listenin üstünde durur")),
            sw("commandbar-over-list", p, s.commandbar_over_list, |s, v| s.commandbar_over_list = v),
        )),
        (AppearanceGroup::Toolbar, card(
            p,
            L::PanelTop,
            t!("Komut çubuğunun yüksekliği"),
            None,
            dropdown(
                "command-bar-height",
                p,
                s.command_bar_height,
                vec![
                    (0u8, t!("Görünümün kendi yüksekliği").to_string()),
                    (48, "48 px".to_string()),
                    (44, "44 px".to_string()),
                    (36, "36 px".to_string()),
                ],
                |s, v| s.command_bar_height = v,
            ),
        )),
        (AppearanceGroup::Window, card(
            p,
            L::Minimize2,
            t!("Kompakt pencere"),
            Some(t!("Sekmeler, adres çubuğu ve komut çubuğu daha ince olur, içerik pencerenin sağına ve altına kadar uzanır. Simgeler ve yazılar aynı boyda kalır.")),
            sw("compact-window", p, s.compact_window, |s, v| s.compact_window = v),
        )),
        (AppearanceGroup::Files, card(
            p,
            L::Rows3,
            t!("Sıkışık öğeler"),
            Some(t!("Explorer'ın sıkışık görünümü gibi: ayrıntılar görünümünde satırlar incelir, ızgarada öğeler birbirine ve adlar simgelerine yaklaşır. Her klasörde geçerlidir.")),
            sw("compact-items", p, s.compact_items, |s, v| s.compact_items = v),
        )),
        (AppearanceGroup::Sidebar, card(
            p,
            L::PanelLeft,
            t!("Kenar çubuğunda yazı boyutu"),
            Some(t!("Yalnızca kenar çubuğundaki yazıların boyutu; pencerenin geri kalanı değişmez")),
            dropdown(
                "sidebar-text-size",
                p,
                u32::from(s.sidebar_text_percent),
                vec![
                    (0, t!("Pencereyle aynı").into()),
                    (87, t!("Çok küçük").into()),
                    (93, t!("Küçük").into()),
                    (100, t!("Normal").into()),
                    (112, t!("Büyük").into()),
                    (125, t!("Çok büyük").into()),
                ],
                |s, v| s.sidebar_text_percent = v as u16,
            ),
        )),
        (AppearanceGroup::Sidebar, card(
            p,
            L::Rows3,
            t!("Sıkışık kenar çubuğu"),
            Some(t!("Kenar çubuğunun satırları incelir, kaydırmadan daha çok yer görünür")),
            sw("sidebar-compact", p, s.sidebar_compact, |s, v| s.sidebar_compact = v),
        )),
        (AppearanceGroup::Sidebar, card(
            p,
            L::PanelLeft,
            t!("Kenar çubuğu simge şeridi"),
            Some(t!("Açıkken kenar çubuğu dar bir simge şeridine dönüşür ve üstüne gelince açılır. Kenarını sürükleyerek de değiştirebilirsiniz.")),
            sw("sidebar-rail", p, s.sidebar_rail, |s, v| s.sidebar_rail = v),
        )),
        (AppearanceGroup::Files, card(
            p,
            L::Rows2,
            t!("Dönüşümlü satır renkleri"),
            Some(t!("Ayrıntılar, Liste ve Sütunlar görünümlerinde satırların biri açık biri koyu olur, yan yana satırlar daha kolay ayırt edilir.")),
            sw("alternating-rows", p, s.alternating_rows, |s, v| s.alternating_rows = v),
        )),
        (AppearanceGroup::Files, card(
            p,
            L::LayoutGrid,
            t!("Izgarada ad satırları"),
            Some(t!("Uzun adlar simgenin altında en çok bu kadar satıra yayılır")),
            dropdown("tile-name-lines", p, s.tile_name_lines.clamp(2, 4), vec![(2u8, "2".to_string()), (3, "3".to_string()), (4, "4".to_string())], |s, v| s.tile_name_lines = v),
        )),
        (AppearanceGroup::Files, card(
            p,
            L::Play,
            t!("Videolarda oynat işareti"),
            Some(t!("Izgarada videoların küçük resminin köşesinde, resimlerden ayırt edilsin diye")),
            sw("video-badge", p, s.video_badge, |s, v| s.video_badge = v),
        )),
        (AppearanceGroup::Window, card(
            p,
            L::Image,
            t!("Uygulama simgesi"),
            Some(t!("Başlat menüsündeki, masaüstündeki ve görev çubuğuna sabitlenmiş rustyfiles kısayollarının simgesi. Güncellemelerden sonra da kalır.")),
            h_flex()
                .gap_2()
                .child(button("app-icon-pick", p, t!("Seç…"), |window, cx| crate::app_icon::pick(window, cx)))
                .when(s.app_icon.is_some(), |d| d.child(button("app-icon-default", p, t!("Varsayılan"), |_, cx| crate::app_icon::set(None, cx))))
                .into_any_element(),
        )),
        (AppearanceGroup::Window, card(
            p,
            L::PanelRight,
            t!("Kaydırma çubuğunu göster"),
            Some(t!("Ayrıntılar ve Izgara listelerinin sağında; sürükleyin ya da bir yere tıklayıp oraya atlayın.")),
            sw("scrollbar", p, s.show_scrollbar, |s, v| s.show_scrollbar = v),
        )),
    ];
    if s.show_scrollbar {
        // (right under the scrollbar's own card)
        v.push((AppearanceGroup::Window, card(
            p,
            L::PanelRight,
            t!("Kaydırma çubuğu hep görünsün"),
            Some(t!("Kapalıyken yalnızca kaydırırken görünür (Windows'ta kaydırma çubuklarını her zaman göster açıksa yine hep görünür).")),
            sw("scrollbar-always", p, s.scrollbar_always, |s, v| s.scrollbar_always = v),
        )));
    }
    // HyperGlass look, right under the backdrop card (index 3) while Glass is the material
    if s.backdrop_in_use() == BackdropPref::Glass || crate::glass::forced() {
        v.insert(3, (AppearanceGroup::Theme, hyperglass_card(p, s, cx)));
    }
    // tint swatches
    let tint = s.tint;
    let pp = *p;
    let swatch_now: AnyElement = match tint {
        Some(c) => div().size(px(20.)).rounded(px(4.)).bg(rgb(c)).border_1().border_color(p.border).into_any_element(),
        None => div().text_sm().text_color(p.text_secondary).child(t!("Varsayılan")).into_any_element(),
    };
    v.push((AppearanceGroup::Theme, expander(
        "tint",
        p,
        L::Paintbrush,
        t!("Arka plan rengi"),
        None,
        Some(swatch_now),
        move || {
            let tile = |id: usize, label: String, color: Option<u32>, selected: bool| {
                v_flex()
                    .id(("tint", id))
                    .w(px(96.))
                    .gap_1()
                    .items_center()
                    .p_1()
                    .rounded(theme::RADIUS_SM)
                    .border_1()
                    .border_color(if selected { pp.accent } else { transparent_black() })
                    .hover(|s| s.bg(pp.pressed))
                    .child(
                        div()
                            .w_full()
                            .h(px(44.))
                            .rounded(theme::RADIUS_SM)
                            .border_1()
                            .border_color(pp.border)
                            .when_some(color, |d, c| d.bg(hsla_alpha(c, 0.55)))
                            .when(color.is_none(), |d| d.bg(pp.content_bg)),
                    )
                    .child(div().text_xs().text_color(pp.text_secondary).child(label))
                    .on_click(move |_, _, cx| settings::update(cx, |s| s.tint = color))
            };
            let mut grid = div().px_4().py_3().flex().flex_wrap().gap_2();
            grid = grid.child(tile(0, t!("Varsayılan").to_string(), None, tint.is_none()));
            for (i, (name, c)) in TINTS.iter().enumerate() {
                grid = grid.child(tile(i + 1, crate::i18n::t(name).to_string(), Some(*c), tint == Some(*c)));
            }
            vec![grid.into_any_element()]
        },
        cx,
    )));
    // background image
    let img = s.background_image.clone();
    let opacity = s.background_opacity;
    let pp = *p;
    let img_desc = img.as_ref().map(|i| i.display().to_string());
    v.push((AppearanceGroup::Theme, expander(
        "bgimg",
        p,
        L::Image,
        t!("Arka plan resmi"),
        Some(img_desc.as_deref().unwrap_or(t!("Yok"))),
        Some(button("bg-browse", p, t!("Gözat"), |window, cx| pick_into(window, cx, t!("Arka plan resmi"), PickTarget::BackgroundImage))),
        move || {
            vec![
                sub(
                    &pp,
                    t!("Görünürlük"),
                    None,
                    dropdown(
                        "bg-opacity",
                        &pp,
                        (opacity * 100.).round() as u32,
                        vec![(10, "%10".into()), (20, "%20".into()), (35, "%35".into()), (50, "%50".into())],
                        |s, v| s.background_opacity = v as f32 / 100.,
                    ),
                ),
                sub(&pp, t!("Resmi kaldır"), None, button("bg-clear", &pp, t!("Kaldır"), |_, cx| settings::update(cx, |s| s.background_image = None))),
            ]
        },
        cx,
    )));
    // the theme folder: colours and icons of the user's own (issues 93 and 94)
    let themes = crate::themes::list();
    let cur_theme = s.theme_folder.clone();
    let none = t!("Yok").to_string();
    let shown_theme = if cur_theme.is_empty() { none.clone() } else { cur_theme.clone() };
    v.push((AppearanceGroup::Theme, card(
        p,
        L::Palette,
        t!("Tema klasörü"),
        Some(t!("Ayar klasöründeki themes içinden bir klasör: theme.toml renkleri, icons klasörü simgeleri değiştirir. Biçimi GitHub'da docs/themes.md'de.")),
        select_box("theme-folder", p, shown_theme, move |_| {
            std::iter::once(String::new())
                .chain(themes.iter().cloned())
                .map(|name| {
                    let label = if name.is_empty() { none.clone() } else { name.clone() };
                    Choice::new(label, name == cur_theme, move |_, cx| {
                        let n = name.clone();
                        settings::update(cx, |s| s.theme_folder = n)
                    })
                })
                .collect()
        }),
    )));
    v.push((AppearanceGroup::Theme, link_row(p, "open-themes", L::FolderOpen, t!("Tema klasörlerini aç"), None, |_, _| {
        if let Some(d) = crate::themes::dir() {
            let _ = std::fs::create_dir_all(&d);
            std::thread::spawn(move || {
                let _ = rf_win::shell::open(&d);
            });
        }
    })));
    // font (issue 45: any font installed on this PC, like macOS SettingsAppearance)
    let current_font = s.font.clone().unwrap_or_default();
    let font_label = if current_font.is_empty() { t!("Varsayılan").to_string() } else { current_font.clone() };
    v.push((AppearanceGroup::Text, card(
        p,
        L::Type,
        t!("Yazı tipi"),
        None,
        select_box("font", p, font_label, move |cx| {
            std::iter::once(String::new())
                .chain(font_choices(cx))
                .map(|f| {
                    let label = if f.is_empty() { t!("Varsayılan").to_string() } else { f.clone() };
                    let sel = f == current_font;
                    Choice::new(label, sel, move |_, cx| {
                        let name = if f.is_empty() { None } else { Some(f.clone()) };
                        settings::update(cx, |s| s.font = name)
                    })
                })
                .collect()
        }),
    )));
    // the text size (issue 89): smaller for a low-resolution screen, larger to read more easily
    v.push((AppearanceGroup::Text, card(
        p,
        L::CaseSensitive,
        t!("Yazı boyutu"),
        Some(t!("Dosya yöneticisinin pencerelerindeki yazıların boyutu")),
        dropdown(
            "text-size",
            p,
            u32::from(s.text_percent),
            // (four steps since issue 89: "a font size in between small and normal". What was Small is Extra small, at the same
            // size, so nobody's text changes; the new step is 13 px where Normal is 14.)
            // (a fifth since issue 1105: "an extra-large font size")
            vec![(87, t!("Çok küçük").into()), (93, t!("Küçük").into()), (100, t!("Normal").into()), (112, t!("Büyük").into()), (125, t!("Çok büyük").into())],
            |s, v| s.text_percent = v as u16,
        ),
    )));
    v.push((AppearanceGroup::Window, card(p, L::PanelBottom, t!("Durum çubuğunu göster"), None, sw("statusbar", p, s.show_statusbar, |s, v| s.show_statusbar = v))));
    v.push((AppearanceGroup::Preview, card(p, L::PanelRight, t!("Önizleme paneli"), Some("Alt+P"), sw("preview", p, s.preview_open, |s, v| s.preview_open = v))));
    v.push((AppearanceGroup::Preview, card(
        p,
        L::PanelBottom,
        t!("Önizleme paneli yeri"),
        Some(t!("Sağda: dosya listesinin yanında. Altta: listenin altında, tüm genişlikte; yüksekliği üst kenarından sürükleyerek ayarlanır")),
        dropdown(
            "preview-position",
            p,
            s.preview_position,
            vec![(rf_core::previewpane::PreviewPos::Right, t!("Sağda").into()), (rf_core::previewpane::PreviewPos::Bottom, t!("Altta").into())],
            |s, v| s.preview_position = v,
        ),
    )));
    v.push((AppearanceGroup::Preview, card(
        p,
        L::Info,
        t!("Önizlemede dosya bilgileri"),
        Some(t!("Önizlemenin altında türü, boyutu, tarihleri ve konumu gösterir")),
        sw("preview-details", p, s.preview_details, |s, v| s.preview_details = v),
    )));
    let hidden = s.sidebar_hidden.clone();
    let libs = s.show_libraries;
    let space = s.sidebar_drive_space;
    let (tree_on, tree_follow) = (s.sidebar_tree, s.sidebar_tree_follow);
    let pp = *p;
    v.push((AppearanceGroup::Sidebar, expander(
        "sidebar",
        p,
        L::PanelLeft,
        t!("Kenar çubuğu bölümleri"),
        None,
        None,
        move || {
            let shown = |k: &str| !hidden.iter().any(|h| h == k);
            vec![
                sub(&pp, t!("Sürücüler"), None, switch("sb-drives", &pp, shown("drives"), {
                    let on = shown("drives");
                    move |_, cx| settings::update(cx, |s| show_section(s, "drives", !on))
                })),
                sub(&pp, t!("Sürücülerin doluluğunu sayıyla göster"), Some(t!("Her sürücünün çubuğunun altında kullanılan ve toplam alan")), switch("sb-drive-space", &pp, space, move |_, cx| {
                    settings::update(cx, |s| s.sidebar_drive_space = !space)
                })),
                sub(&pp, t!("Bulut ve Linux"), None, switch("sb-cloud", &pp, shown("cloud"), {
                    let on = shown("cloud");
                    move |_, cx| settings::update(cx, |s| show_section(s, "cloud", !on))
                })),
                sub(&pp, t!("Kütüphaneler"), Some(t!("Sabitlenenlerle aynı klasörleri gösterir")), switch("sb-libs", &pp, libs, move |_, cx| {
                    settings::update(cx, |s| s.show_libraries = !libs)
                })),
                sub(&pp, t!("Ağ"), None, switch("sb-net", &pp, shown("network"), {
                    let on = shown("network");
                    move |_, cx| settings::update(cx, |s| show_section(s, "network", !on))
                })),
                sub(&pp, t!("Etiketler"), None, switch("sb-tags", &pp, shown("tags"), {
                    let on = shown("tags");
                    move |_, cx| settings::update(cx, |s| show_section(s, "tags", !on))
                })),
                // (discussion 720)
                sub(&pp, t!("Geri Dönüşüm Kutusu"), None, switch("sb-recycle-shown", &pp, shown("recycle"), {
                    let on = shown("recycle");
                    move |_, cx| settings::update(cx, |s| show_section(s, "recycle", !on))
                })),
                // the folder tree (crate::sidebar_tree)
                sub(&pp, t!("Klasör ağacı"), Some(t!("Kenar çubuğunun altına, sürücüleri ve kullanıcı klasörünü açılıp kapanan bir ağaç olarak gösteren Klasörler bölümü ekler")), switch("sb-tree", &pp, tree_on, move |_, cx| {
                    settings::update(cx, |s| s.sidebar_tree = !tree_on)
                })),
                sub(&pp, t!("Açık klasörü izle"), Some(t!("Gezindikçe ağaç, açık klasöre giden dalı açar, klasörü seçili gösterir ve görünür yere kaydırır")), switch("sb-tree-follow", &pp, tree_follow, move |_, cx| {
                    settings::update(cx, |s| s.sidebar_tree_follow = !tree_follow)
                })),
            ]
        },
        cx,
    )));
    let (bar_hidden, bar_extra) = (s.toolbar_hidden.clone(), s.toolbar_extra.clone());
    let commands = s.toolbar_commands.clone();
    let explorer = s.windows_file_explorer_theme;
    let bar_order = crate::toolbar_layout::order(&s.toolbar_order, explorer);
    let bar_looks = s.toolbar_look.clone();
    let icon_size = s.toolbar_icon_size;
    let windows_icons = s.toolbar_windows_icons;
    // the switch and the buttons it shows stand together (issue 111)
    v.push((AppearanceGroup::Toolbar, card(p, L::PanelTop, t!("Araç çubuğunu göster"), Some("Ctrl+Shift+B"), sw("toolbar", p, s.show_toolbar, |s, v| s.show_toolbar = v))));
    v.push((AppearanceGroup::Toolbar, expander(
        "toolbar-buttons",
        p,
        L::PanelTop,
        t!("Araç çubuğu düğmeleri"),
        None,
        None,
        move || {
            use crate::toolbar_layout::{Look, SEP};
            // (key, id, label, off unless asked for)
            const BUTTONS: [(&str, &str, &str, bool); 30] = [
                ("new", "tb-new", "Yeni", false),
                ("newfolder", "tb-newfolder", "Yeni klasör", true),
                ("cut", "tb-cut", "Kes", false),
                ("copy", "tb-copy", "Kopyala", false),
                ("paste", "tb-paste", "Yapıştır", false),
                ("rename", "tb-rename", "Yeniden adlandır", false),
                ("share", "tb-share", "Paylaş", false),
                ("delete", "tb-delete", "Sil", false),
                ("props", "tb-props", "Özellikler", false),
                ("edit", "tb-edit", "Metin düzenleyicide düzenle", true),
                ("terminal", "tb-terminal", "Terminalde aç", true),
                ("terminaladmin", "tb-terminaladmin", "Terminalde yönetici olarak aç", true),
                ("hidden", "tb-hidden", "Gizli öğeleri göster/gizle", true),
                ("extensions", "tb-extensions", "Dosya uzantıları", true),
                ("dual", "tb-dual", "Çift panel", true),
                ("shelf", "tb-shelf", "Raf", true),
                ("refresh", "tb-refresh", "Yenile", true),
                ("undo", "tb-undo", "Geri al", true),
                ("redo", "tb-redo", "Yinele", true),
                ("selectall", "tb-selectall", "Tümünü seç", true),
                ("selectnone", "tb-selectnone", "Hiçbirini seçme", true),
                ("invertsel", "tb-invertsel", "Seçimi tersine çevir", true),
                ("compress", "tb-compress", "Sıkıştır", true),
                ("extract", "tb-extract", "Çıkar", true),
                ("more", "tb-more", "Diğer", false),
                ("filter", "tb-filter", "Filtrele", false),
                ("sort", "tb-sort", "Sırala ve gruplandır", false),
                ("view", "tb-view", "Görünüm", false),
                ("preview", "tb-preview", "Önizleme paneli", false),
                ("settings", "tb-settings", "Ayarlar", true),
            ];
            let button_of = |key: &str| BUTTONS.iter().find(|b| b.0 == key).copied();
            let shown_switch = |key: &'static str, id: &'static str, optional: bool| {
                let shown = if optional { bar_extra.iter().any(|k| k == key) } else { !bar_hidden.iter().any(|k| k == key) };
                switch(id, &pp, shown, move |_, cx| {
                    settings::update(cx, |s| {
                        let list = if optional { &mut s.toolbar_extra } else { &mut s.toolbar_hidden };
                        list.retain(|k| k != key);
                        // (the optional ones are listed when on, the others when off)
                        if shown != optional {
                            list.push(key.to_string());
                        }
                    })
                })
            };
            // a button's look: as it was, its picture, its word, or both (issue 374)
            let look_box = |key: &'static str| {
                let now = crate::toolbar_layout::look_of(&bar_looks, key);
                let name = |l: Look| -> &'static str {
                    match l {
                        Look::Auto => t!("Otomatik"),
                        Look::Icon => t!("Simge"),
                        Look::Text => t!("Yazı"),
                        Look::Both => t!("Simge ve yazı"),
                    }
                };
                crate::select_box::select_box_h(format!("tb-look-{key}"), &pp, name(now), 32., move |_| {
                    [Look::Auto, Look::Icon, Look::Text, Look::Both]
                        .into_iter()
                        .map(|l| {
                            Choice::new(name(l), l == now, move |_, cx| {
                                settings::update(cx, |s| s.toolbar_look = crate::toolbar_layout::with_look(&s.toolbar_look, key, l))
                            })
                        })
                        .collect()
                })
            };
            let set_order = move |o: Vec<String>, cx: &mut App| settings::update(cx, move |s| s.toolbar_order = o);
            // up and down for the entry at `i` of the left group (issue 373: "move it to another position")
            let arrows = |i: usize| {
                let (up, down) = (bar_order.clone(), bar_order.clone());
                h_flex()
                    .gap_1()
                    .child(icon_button(("tb-up", i), &pp, L::ChevronUp, t!("Yukarı taşı"), move |_, cx| set_order(crate::toolbar_layout::moved(&up, i, true), cx)))
                    .child(icon_button(("tb-down", i), &pp, L::ChevronDown, t!("Aşağı taşı"), move |_, cx| set_order(crate::toolbar_layout::moved(&down, i, false), cx)))
            };
            let mut rows: Vec<AnyElement> = Vec::new();
            // the pictures' size (issue 248)
            rows.push(sub(
                &pp,
                t!("Simge boyutu"),
                None,
                crate::select_box::select_box_h(
                    "tb-icon-size",
                    &pp,
                    match icon_size {
                        settings::ToolbarIconSize::Small => t!("Küçük"),
                        settings::ToolbarIconSize::Medium => t!("Orta boy"),
                        settings::ToolbarIconSize::Large => t!("Büyük"),
                    },
                    32.,
                    move |_| {
                        [(settings::ToolbarIconSize::Small, t!("Küçük")), (settings::ToolbarIconSize::Medium, t!("Orta boy")), (settings::ToolbarIconSize::Large, t!("Büyük"))]
                            .into_iter()
                            .map(|(v, l)| Choice::new(l, v == icon_size, move |_, cx| settings::update(cx, |s| s.toolbar_icon_size = v)))
                            .collect()
                    },
                ),
            ));
            // Windows' own pictures, as in the Explorer look (issue 382)
            if !explorer {
                rows.push(sub(
                    &pp,
                    t!("Windows simgeleri"),
                    Some(t!("Araç çubuğunda Windows Dosya Gezgini'nin simgeleri")),
                    switch("tb-win-icons", &pp, windows_icons, move |_, cx| settings::update(cx, |s| s.toolbar_windows_icons = !windows_icons)),
                ));
            }
            // the pictures in the accent colour (issue 413)
            let accent_icons = s.toolbar_accent_icons;
            rows.push(sub(
                &pp,
                t!("Simgeler vurgu renginde"),
                Some(t!("Araç çubuğunun simgeleri Windows'un vurgu renginde, Files'taki gibi")),
                switch("tb-accent-icons", &pp, accent_icons, move |_, cx| settings::update(cx, |s| s.toolbar_accent_icons = !accent_icons)),
            ));
            // the left group in its order, lines included
            for (i, name) in bar_order.iter().enumerate() {
                // where the right side begins: what is under it stands at the right of the bar (issue 405)
                if name == crate::toolbar_layout::GAP {
                    rows.push(sub(&pp, t!("Sağ taraf"), Some(t!("Altındaki düğmeler araç çubuğunun sağında durur")), arrows(i).into_any_element()));
                    continue;
                }
                if name == SEP {
                    let o = bar_order.clone();
                    let remove = button(("tb-sep-x", i), &pp, t!("Kaldır"), move |_, cx| set_order(crate::toolbar_layout::without(&o, i), cx));
                    rows.push(sub(&pp, t!("Ayırıcı"), None, h_flex().gap_2().items_center().child(arrows(i)).child(remove).into_any_element()));
                    continue;
                }
                let Some((key, id, label, optional)) = button_of(name) else { continue };
                let controls = h_flex().gap_2().items_center().child(look_box(key)).child(arrows(i)).child(shown_switch(key, id, optional));
                rows.push(sub_icon(&pp, toolbar_icon_of(key), crate::i18n::t(label), None, controls.into_any_element()));
            }
            // the right group: shown or not, the look of Sort and View, and its order (issue 405)
            let right = crate::toolbar_layout::right_order(&s.toolbar_right_order, explorer);
            for (i, key) in right.iter().enumerate() {
                let Some((key, id, label, optional)) = button_of(key) else { continue };
                let (up, down) = (right.clone(), right.clone());
                let set_right = |o: Vec<String>, cx: &mut App| settings::update(cx, move |s| s.toolbar_right_order = o);
                let arrows = h_flex()
                    .gap_1()
                    .child(icon_button(("tb-r-up", i), &pp, L::ChevronUp, t!("Yukarı taşı"), move |_, cx| set_right(crate::toolbar_layout::moved(&up, i, true), cx)))
                    .child(icon_button(("tb-r-down", i), &pp, L::ChevronDown, t!("Aşağı taşı"), move |_, cx| set_right(crate::toolbar_layout::moved(&down, i, false), cx)));
                let controls = h_flex().gap_2().items_center().when(matches!(key, "sort" | "view"), |d| d.child(look_box(key))).child(arrows).child(shown_switch(key, id, optional));
                rows.push(sub_icon(&pp, toolbar_icon_of(key), crate::i18n::t(label), None, controls.into_any_element()));
            }
            // (Settings, when it is not in either group, stands in the address row: its switch is under "Address bar buttons")
            // the More menu's Exit (issue 443)
            let exit_shown = !bar_hidden.iter().any(|k| k == crate::ctx_menu::MORE_EXIT);
            rows.push(sub(
                &pp,
                t!("Diğer menüsünde Çıkış"),
                Some(t!("Diğer'de başka bir şey kalmayınca düğmesi de gizlenir")),
                switch("tb-more-exit", &pp, exit_shown, move |_, cx| {
                    settings::update(cx, |s| {
                        s.toolbar_hidden.retain(|k| k != crate::ctx_menu::MORE_EXIT);
                        if exit_shown {
                            s.toolbar_hidden.push(crate::ctx_menu::MORE_EXIT.to_string());
                        }
                    })
                }),
            ));
            let with_line = bar_order.clone();
            rows.push(sub(
                &pp,
                t!("Ayırıcı"),
                None,
                h_flex()
                    .gap_2()
                    .child(button("tb-add-sep", &pp, t!("Ayırıcı ekle"), move |_, cx| set_order(crate::toolbar_layout::with_line(&with_line), cx)))
                    .child(button("tb-reset-order", &pp, t!("Varsayılan sıra"), |_, cx| settings::update(cx, |s| {
                        s.toolbar_order.clear();
                        s.toolbar_right_order.clear();
                    })))
                    .into_any_element(),
            ));
            rows.extend(commands.into_iter().enumerate().map(|(i, command)| {
                sub(&pp, command.name(), Some(&command.program), crate::quick_commands::controls(i, command.clone(), &pp).into_any_element())
            }));
            let add = crate::i18n::tx("Komut ekle", "Add command");
            rows.push(sub(
                &pp,
                crate::i18n::tx("Özel komutlar", "Custom commands"),
                None,
                button("add-quick-command", &pp, add, |window, cx| crate::quick_commands::edit(None, window, cx)),
            ));
            rows
        },
        cx,
    )));
    // the buttons beside the address bar (issue 438: the Settings button's switch was among the toolbar's, but it stands there)
    let in_toolbar = |key: &str| {
        crate::toolbar_layout::order(&s.toolbar_order, explorer).iter().any(|o| o == key)
            || crate::toolbar_layout::right_order(&s.toolbar_right_order, explorer).iter().any(|r| r == key)
    };
    if !in_toolbar("settings") {
        let settings_shown = s.toolbar_extra.iter().any(|k| k == "settings");
        let pp = p.clone();
        v.push((AppearanceGroup::Toolbar, expander(
            "address-buttons",
            p,
            L::TextCursorInput,
            t!("Adres çubuğu düğmeleri"),
            None,
            None,
            move || {
                vec![sub(
                    &pp,
                    t!("Ayarlar"),
                    Some(t!("Adres çubuğunun sağında, Ayarlar'ı açan düğme")),
                    switch("tb-settings", &pp, settings_shown, move |_, cx| {
                        settings::update(cx, |s| {
                            s.toolbar_extra.retain(|k| k != "settings");
                            if !settings_shown {
                                s.toolbar_extra.push("settings".to_string());
                            }
                        })
                    }),
                )]
            },
            cx,
        )));
    }
    let home_hidden = s.home_hidden.clone();
    let recent_arrivals = s.recent_arrivals;
    let split_drives = s.home_split_drives;
    v.push((AppearanceGroup::Home, expander(
        "home-sections",
        p,
        L::House,
        t!("Ana sayfa bölümleri"),
        None,
        None,
        move || {
            const SECTIONS: [(&str, &str, &str); 6] = [
                ("quick", "hm-quick", "Hızlı Erişim"),
                ("drives", "hm-drives", "Sürücüler"),
                ("devices", "hm-devices", "Cihazlar"),
                ("network", "hm-network", "Ağ konumları"),
                ("tags", "hm-tags", "Etiketler"),
                ("recent", "hm-recent", "Son kullanılanlar"),
            ];
            let mut rows: Vec<AnyElement> = SECTIONS
                .iter()
                .map(|&(key, id, label)| {
                    let on = !home_hidden.iter().any(|h| h == key);
                    sub(&pp, crate::i18n::t(label), None, switch(id, &pp, on, move |_, cx| settings::update(cx, |s| show_home_section(s, key, !on))))
                })
                .collect();
            // (issue 563)
            rows.push(sub(
                &pp,
                t!("Son kullanılanlarda indirilen ve kopyalanan dosyalar"),
                Some(t!("İndirilenler'e yeni gelen ve bu bilgisayara kopyalanan dosyalar, açılmasalar da listede görünür. Kapalıyken yalnızca açtığınız öğeler.")),
                switch("hm-recent-arrivals", &pp, recent_arrivals, move |_, cx| settings::update(cx, |s| s.recent_arrivals = !recent_arrivals)),
            ));
            // the drives in groups, as This PC has them, each group on its own switch
            rows.push(sub(&pp, crate::i18n::t("Sürücüleri gruplara ayır"), Some(crate::i18n::t("Yerel diskler, çıkarılabilir sürücüler (USB, disk) ve ağ sürücüleri ayrı başlıklar altında gösterilir, Bu bilgisayar'daki gibi.")), switch("hm-split-drives", &pp, split_drives, move |_, cx| settings::update(cx, |s| s.home_split_drives = !split_drives))));
            if split_drives {
                for (key, id, label) in [("drives_local", "hm-drives-local", "Yerel diskler"), ("drives_removable", "hm-drives-removable", "Çıkarılabilir sürücüler"), ("drives_network", "hm-drives-network", "Ağ sürücüleri")] {
                    let on = !home_hidden.iter().any(|h| h == key);
                    rows.push(sub(&pp, crate::i18n::t(label), None, switch(id, &pp, on, move |_, cx| settings::update(cx, |s| show_home_section(s, key, !on)))));
                }
            }
            rows
        },
        cx,
    )));
    // under headings, each group's settings in the order they were added above
    let mut out = Vec::with_capacity(v.len() + AppearanceGroup::ALL.len());
    for group in AppearanceGroup::ALL {
        let (mine, rest): (Vec<_>, Vec<_>) = v.into_iter().partition(|(g, _)| *g == group);
        v = rest;
        if !mine.is_empty() {
            out.push(section(p, group.title()));
            out.extend(mine.into_iter().map(|(_, e)| e));
        }
    }
    out
}

/// The headings of the Appearance page, in the page's order.
#[derive(Clone, Copy, PartialEq, Eq)]
enum AppearanceGroup {
    Theme,
    Text,
    Window,
    Tabs,
    Toolbar,
    Sidebar,
    Files,
    Preview,
    Home,
}

impl AppearanceGroup {
    const ALL: [AppearanceGroup; 9] = [Self::Theme, Self::Text, Self::Window, Self::Tabs, Self::Toolbar, Self::Sidebar, Self::Files, Self::Preview, Self::Home];

    fn title(self) -> &'static str {
        match self {
            Self::Theme => t!("Tema"),
            Self::Text => t!("Yazı"),
            Self::Window => t!("Pencere"),
            Self::Tabs => t!("Sekmeler"),
            Self::Toolbar => t!("Araç çubuğu"),
            Self::Sidebar => t!("Kenar çubuğu"),
            Self::Files => t!("Dosya listesi"),
            Self::Preview => t!("Önizleme paneli"),
            Self::Home => t!("Ana sayfa"),
        }
    }
}

fn hsla_alpha(c: u32, a: f32) -> Hsla {
    let mut h: Hsla = rgb(c).into();
    h.a = a;
    h
}

/// Every font installed on the PC (alphabetical, without internal `.` or vertical `@` faces).
fn font_choices(cx: &App) -> Vec<String> {
    sort_font_names(cx.text_system().all_font_names())
}

/// Filters out blank, internal (`.…`), and vertical (`@…`) font faces, then sorts alphabetically without duplicates.
fn sort_font_names(names: Vec<String>) -> Vec<String> {
    let mut out: Vec<String> = names
        .into_iter()
        .filter(|f| {
            let trimmed = f.trim();
            !trimmed.is_empty() && !trimmed.starts_with('.') && !trimmed.starts_with('@')
        })
        .collect();
    out.sort_by(|a, b| a.to_lowercase().cmp(&b.to_lowercase()).then_with(|| a.cmp(b)));
    out.dedup();
    out
}

fn layout(p: &Palette, s: &Settings, cx: &mut App) -> Vec<AnyElement> {
    use rf_core::SortKey;
    let mut v = vec![
        card(
            p,
            L::FolderSync,
            t!("Düzen ve sıralamayı tüm klasörlerde eşitle"),
            Some(t!("Kapalıyken her klasör kendi görünümünü ve sıralamasını hatırlar.")),
            sw("sync-layout", p, s.sync_layout, |s, v| s.sync_layout = v),
        ),
        card(
            p,
            L::MousePointer,
            t!("Ctrl+tekerlek düzeni değiştirsin"),
            Some(t!("Açıkken Ctrl+tekerlek düzenler arasında gezer (Ayrıntılar, Liste, Kartlar, Izgara, Sütunlar), Ctrl+Shift+tekerlek o düzenin boyutunu değiştirir. Kapalıyken Explorer'daki gibi yakınlaştırır.")),
            sw("ctrl-wheel-layouts", p, s.ctrl_wheel_layouts, |s, v| s.ctrl_wheel_layouts = v),
        ),
        card(
            p,
            L::LayoutGrid,
            t!("Varsayılan düzen"),
            Some(t!("Uyarlanabilir: çoğunlukla resim/video olan klasörler ızgarada açılır.")),
            dropdown(
                "view",
                p,
                s.default_view,
                vec![
                    (DefaultView::Details, t!("Ayrıntılar").into()),
                    (DefaultView::Grid, t!("Izgara").into()),
                    (DefaultView::Columns, t!("Sütunlar").into()),
                    (DefaultView::List, t!("Liste").into()),
                    (DefaultView::Cards, t!("Kartlar").into()),
                    (DefaultView::Adaptive, t!("Uyarlanabilir").into()),
                ],
                |s, v| s.default_view = v,
            ),
        ),
        // (Discussion 730: Downloads small in one pane, a new archive opened big in the other)
        card(
            p,
            L::Rows3,
            t!("Varsayılan satır boyutu"),
            Some(t!("Kendi düzeni olmayan klasörler Ayrıntılar ve Liste'de bu boyutta açılır")),
            dropdown("default-row-size", p, s.default_row_size, size_steps(crate::folder_view::ROW_SIZES, 1), |s, v| s.default_row_size = v),
        ),
        card(
            p,
            L::LayoutGrid,
            t!("Varsayılan simge boyutu"),
            Some(t!("Kendi düzeni olmayan klasörler ızgarada bu boyutta açılır")),
            dropdown("default-grid-size", p, s.default_grid_size, size_steps(crate::folder_view::GRID_SIZES.map(|g| g.0), 2), |s, v| s.default_grid_size = v),
        ),
        section(p, t!("Sıralama ve gruplama")),
        card(
            p,
            L::ArrowUpDown,
            t!("Sırala"),
            None,
            dropdown(
                "sort",
                p,
                s.default_sort,
                vec![
                    (SortKey::Name, t!("Ad").into()),
                    (SortKey::Modified, t!("Değiştirme tarihi").into()),
                    (SortKey::Created, t!("Oluşturma tarihi").into()),
                    (SortKey::Type, t!("Tür").into()),
                    (SortKey::Size, t!("Boyut").into()),
                ],
                |s, v| s.default_sort = v,
            ),
        ),
        card(p, L::ArrowDownWideNarrow, t!("Azalan sırada"), None, sw("sort-desc", p, s.default_sort_desc, |s, v| s.default_sort_desc = v)),
        card(p, L::FolderUp, t!("Önce klasörler"), None, sw("dirs-first", p, s.folders_first, |s, v| s.folders_first = v)),
        card(
            p,
            L::ListTree,
            t!("Gruplandır"),
            None,
            dropdown(
                "group",
                p,
                group_ix(&s.default_group),
                vec![
                    (0, t!("Yok").into()),
                    (1, t!("Ad").into()),
                    (2, t!("Tür").into()),
                    (3, t!("Değiştirme tarihi").into()),
                    (4, t!("Boyut").into()),
                    (5, t!("Oluşturma tarihi").into()),
                    (6, t!("Yıl").into()),
                    (7, t!("Ay").into()),
                    (8, t!("Gün").into()),
                    (9, t!("Etiket").into()),
                ],
                |s, v| s.default_group = crate::folder_view::GroupBy::ALL[v.min(9)].1.into(),
            ),
        ),
        section(p, t!("Ayrıntılar görünümü")),
    ];
    let c = s.columns.clone();
    let pp = *p;
    v.push(expander(
        "columns",
        p,
        L::Columns3,
        t!("Sütunlar"),
        Some(t!("Ad sütunu her zaman görünür")),
        None,
        move || {
            type Set = fn(&mut Settings, bool);
            let rows: [(&str, bool, Set); 11] = [
                (t!("Değiştirme tarihi"), c.modified, |s, v| s.columns.modified = v),
                (t!("Oluşturma tarihi"), c.created, |s, v| s.columns.created = v),
                (t!("Tür"), c.kind, |s, v| s.columns.kind = v),
                (t!("Boyut"), c.size, |s, v| s.columns.size = v),
                (t!("Dosya etiketi"), c.tags, |s, v| s.columns.tags = v),
                (t!("Git durumu"), c.git, |s, v| s.columns.git = v),
                (t!("Eşitleme durumu"), c.sync, |s, v| s.columns.sync = v),
                (t!("Son commit mesajı"), c.git_message, |s, v| s.columns.git_message = v),
                (t!("Commit yazarı"), c.git_author, |s, v| s.columns.git_author = v),
                (t!("Commit tarihi"), c.git_date, |s, v| s.columns.git_date = v),
                (t!("Commit hash"), c.git_hash, |s, v| s.columns.git_hash = v),
            ];
            rows.into_iter()
                .enumerate()
                .map(|(i, (label, on, set))| sub(&pp, label, None, switch(("col-sw", i), &pp, on, move |_, cx| settings::update(cx, |s| set(s, !on)))))
                .collect()
        },
        cx,
    ));
    v
}

pub fn group_ix(g: &str) -> usize {
    crate::folder_view::GroupBy::ALL.iter().position(|(_, name)| *name == g).unwrap_or(0)
}

fn files(p: &Palette, s: &Settings, cx: &mut App) -> Vec<AnyElement> {
    let mut v = vec![section(p, t!("Görünüm"))];
    let (h, sys, dot) = (s.show_hidden, s.show_system_files, s.show_dot_files);
    let pp = *p;
    v.push(expander(
        "hidden",
        p,
        L::EyeOff,
        t!("Gizli öğeler"),
        None,
        None,
        move || {
            vec![
                sub(&pp, t!("Gizli öğeleri göster"), Some("Ctrl+H"), switch("h1", &pp, h, move |_, cx| settings::update(cx, |s| s.show_hidden = !h))),
                sub(
                    &pp,
                    t!("Korunan işletim sistemi dosyalarını göster"),
                    Some(t!("desktop.ini, thumbs.db gibi sistem dosyaları")),
                    switch("h2", &pp, sys, move |_, cx| settings::update(cx, |s| s.show_system_files = !sys)),
                ),
                sub(
                    &pp,
                    t!("Nokta ile başlayan dosyaları göster"),
                    Some(t!("Kapalıyken .git, .config gibi öğeler gizli sayılır")),
                    switch("h3", &pp, dot, move |_, cx| settings::update(cx, |s| s.show_dot_files = !dot)),
                ),
            ]
        },
        cx,
    ));
    v.push(card(p, L::FileType, t!("Dosya uzantılarını göster"), None, sw("ext", p, s.show_extensions, |s, v| s.show_extensions = v)));
    v.push(card(p, L::Image, t!("Küçük resimleri göster"), None, sw("thumbs", p, s.show_thumbnails, |s, v| s.show_thumbnails = v)));
    if s.show_thumbnails {
        v.push(card(p, L::List, t!("Liste düzeninde de küçük resim göster"), None, sw("thumbs-list", p, s.list_thumbnails, |s, v| s.list_thumbnails = v)));
    }
    let placeholder_choices = || {
        vec![
            (PlaceholderIconsPref::Off, t!("Kapalı").into()),
            (PlaceholderIconsPref::Folders, t!("Yalnızca klasörler").into()),
            (PlaceholderIconsPref::Files, t!("Yalnızca dosyalar").into()),
            (PlaceholderIconsPref::All, t!("Dosyalar ve klasörler").into()),
        ]
    };
    let preview_placeholder = s.windows_preview_icons;
    v.push(expander(
        "win-icons",
        p,
        L::Image,
        t!("Yüklenirken Windows simgeleri"),
        Some(t!("Bir öğenin kendi resmi gelene kadar ve önizleme bölmesinde, rustyfiles'ın simgeleri yerine Windows'un o türün simgesi gösterilir (klasörün, dosya türünün, kişiselleştirilmiş simgenin)")),
        Some(dropdown("win-icons", p, s.windows_placeholder_icons, placeholder_choices(), |s, v| s.windows_placeholder_icons = v)),
        move || {
            vec![sub(
                &pp,
                t!("Önizleme paneli"),
                Some(t!("Önizleme panelinde küçük resmi olmayan öğeler için Windows simgeleri")),
                dropdown(
                    "win-preview-icons",
                    &pp,
                    preview_placeholder,
                    vec![
                        (None, t!("Yukarıdakiyle aynı").into()),
                        (Some(PlaceholderIconsPref::Off), t!("Kapalı").into()),
                        (Some(PlaceholderIconsPref::Folders), t!("Yalnızca klasörler").into()),
                        (Some(PlaceholderIconsPref::Files), t!("Yalnızca dosyalar").into()),
                        (Some(PlaceholderIconsPref::All), t!("Dosyalar ve klasörler").into()),
                    ],
                    |s, v| s.windows_preview_icons = v,
                ),
            )]
        },
        cx,
    ));
    v.push(card(
        p,
        L::BadgeCheck,
        t!("Diğer programların simge işaretlerini göster"),
        Some(t!("Google Drive, OneDrive, TortoiseGit gibi programların Gezgin'de simgelerin köşesine koyduğu durum işaretleri.")),
        sw("overlays", p, s.show_overlays, |s, v| s.show_overlays = v),
    ));
    v.push(card(p, L::SquareCheck, t!("Seçerken onay kutularını göster"), None, sw("checkboxes", p, s.show_checkboxes, |s, v| s.show_checkboxes = v)));

    v.push(section(p, t!("Davranışlar")));
    v.push(card(
        p,
        L::MousePointerClick,
        t!("Öğeleri tek tıklamayla aç"),
        None,
        dropdown(
            "single-click",
            p,
            s.single_click,
            vec![(ClickPref::Never, t!("Asla").into()), (ClickPref::Folders, t!("Yalnızca klasörler").into()), (ClickPref::Always, t!("Her zaman").into())],
            |s, v| s.single_click = v,
        ),
    ));
    v.push(card(p, L::SquarePlus, t!("Klasörleri yeni sekmede aç"), None, sw("dir-newtab", p, s.open_folders_in_new_tab, |s, v| s.open_folders_in_new_tab = v)));
    v.push(card(
        p,
        L::Trash,
        t!("Silmeden önce onay iste"),
        None,
        dropdown(
            "confirm-del",
            p,
            s.confirm_delete,
            vec![
                (DeletePref::Always, t!("Her zaman").into()),
                (DeletePref::PermanentOnly, t!("Yalnızca kalıcı silmede").into()),
                (DeletePref::Never, t!("Asla").into()),
            ],
            |s, v| s.confirm_delete = v,
        ),
    ));
    v.push(card(
        p,
        L::TrashOff,
        t!("Silinenleri Geri Dönüşüm Kutusu'na taşı"),
        Some(t!("Kapalıyken Delete de kalıcı olarak siler, Shift+Delete gibi")),
        sw("delete-to-bin", p, s.delete_to_bin, |s, v| s.delete_to_bin = v),
    ));
    v.push(card(p, L::TriangleAlert, t!("Uzantı değişince uyar"), None, sw("ext-warn", p, s.warn_extension_change, |s, v| s.warn_extension_change = v)));
    v.push(card(
        p,
        L::Wand,
        t!("Adlardaki geçersiz karakterleri düzelt"),
        Some(t!("Windows'un kabul etmediği karakterler Enter'da düzeltilir: iki nokta \" - \" olur; / \\ | tire, \" tek tırnak olur; * ? < > çıkarılır.")),
        sw("fix-names", p, s.fix_name_characters, |s, v| s.fix_name_characters = v),
    ));
    v.push(card(
        p,
        L::TextCursorInput,
        t!("F2 birden çok öğeyi yerinde yeniden adlandırır"),
        Some(t!("Seçili öğelerin adları birlikte düzenlenir: kutuda yazılan ya da silinen hepsinde olur, sağ tık sıra numarası ve tarih ekler. Kapalıyken toplu yeniden adlandırma penceresi açılır.")),
        sw("multi-rename", p, s.rename_several_in_place, |s, v| s.rename_several_in_place = v),
    ));
    v.push(card(p, L::MousePointer, t!("Üzerine gelince seç"), None, sw("hover-sel", p, s.select_on_hover, |s, v| s.select_on_hover = v)));
    v.push(card(
        p,
        L::Info,
        t!("Üzerine gelince ayrıntıları göster"),
        Some(t!("İşaretçi bir öğenin üzerinde durunca boyutu, tarihleri ve resmin boyutlarını gösteren kutu")),
        sw("hover-details", p, s.item_hover_details, |s, v| s.item_hover_details = v),
    ));
    // what typing in a folder's list does: select (Explorer), filter (issue 106), or the search box (Discord, 2026-11-30)
    let typing = |s: &Settings| if s.type_to_search { 2 } else if s.type_to_filter { 1 } else { 0 };
    let typing_label = |n: u8| match n {
        1 => t!("Bu klasörü süzer"),
        2 => t!("Arama kutusuna yazar"),
        _ => t!("Adı o harflerle başlayan öğeyi seçer"),
    };
    let now = typing(s);
    v.push(card(
        p,
        L::ListFilter,
        t!("Klasörde yazmaya başlamak"),
        Some(t!("Arama kutusunda yazılanlar bu klasörü süzer, Enter alt klasörlerde de arar.")),
        crate::select_box::select_box("type-action", p, typing_label(now), move |cx| {
            let now = typing(cx.global::<Settings>());
            [0u8, 1, 2]
                .into_iter()
                .map(|n| {
                    Choice::new(typing_label(n), n == now, move |_, cx| {
                        settings::update(cx, move |s| {
                            s.type_to_filter = n == 1;
                            s.type_to_search = n == 2;
                        })
                    })
                })
                .collect()
        }),
    ));
    v.push(card(p, L::ArrowUp, t!("Boş alana çift tıklayınca üst klasöre çık"), None, sw("dbl-up", p, s.double_click_up, |s, v| s.double_click_up = v)));
    v.push(card(
        p,
        L::ListChecks,
        t!("Satırın boş yerinden seçim kutusu başlat"),
        Some(t!("Ayrıntılar ve Sütunlar görünümünde. Kapalıyken öğe, satırının neresinden tutulursa tutulsun sürüklenir.")),
        sw("row-box", p, s.row_selection_box, |s, v| s.row_selection_box = v),
    ));
    v.push(card(p, L::FolderUp, t!("Yukarı çıkınca önceki klasörü seç"), None, sw("prev-sel", p, s.select_previous_on_up, |s, v| s.select_previous_on_up = v)));
    v.push(card(
        p,
        L::SquareTerminal,
        t!("Adres çubuğundan komut çalıştır"),
        Some(t!("Adres çubuğuna yazılan metin var olan bir yer değilse program olarak aranır (cmd, powershell, wt…) ve açık klasörde başlatılır; Enter ile onaylanır")),
        sw("addr-cmd", p, s.address_commands, |s, v| s.address_commands = v),
    ));
    v.push(card(
        p,
        L::FolderTree,
        t!("Adres çubuğunda klasörlerin gerçek adları"),
        Some(t!("Yol, Windows'un çevirdiği adlar yerine diskteki adlarla gösterilir (Users, Documents…), programların ve komutların kullandığı gibi")),
        sw("addr-real", p, s.address_real_names, |s, v| s.address_real_names = v),
    ));
    v.push(card(
        p,
        L::FileArchive,
        t!("Arşivleri klasör gibi aç"),
        Some(t!("ZIP, 7z ve tar dosyalarının içine çift tıklayarak girilir; içindeki dosyalar açılınca geçici bir klasöre çıkarılır")),
        sw("browse-arc", p, s.browse_archives, |s, v| s.browse_archives = v),
    ));
    if s.browse_archives {
        use crate::settings::ArchiveOpen as A;
        v.push(card(
            p,
            L::AppWindow,
            t!("Arşivler nerede açılsın"),
            None,
            dropdown("archives-open-in", p, s.archives_open_in, vec![(A::Here, t!("Aynı sekmede").to_string()), (A::NewTab, t!("Yeni sekmede").to_string()), (A::NewWindow, t!("Yeni pencerede").to_string())], |s, v| {
                s.archives_open_in = v
            }),
        ));
    }
    {
        use crate::settings::QuickCompress as Q;
        let mut options = vec![(Q::Menu, t!("Yalnızca menüyü aç").to_string()), (Q::Zip, "ZIP".into()), (Q::SevenZ, "7z".into()), (Q::TarZst, "tar.zst".into()), (Q::TarGz, "tar.gz".into()), (Q::Tar, "tar".into())];
        if crate::archive_view::winrar().is_some() || s.quick_compress == Q::Rar {
            options.push((Q::Rar, "RAR (WinRAR)".into()));
        }
        v.push(card(
            p,
            L::Archive,
            t!("Sıkıştır'a tıklayınca"),
            Some(t!("Sağ tık menüsünde Sıkıştır'a tıklamak seçilenleri bu biçimde hemen sıkıştırır; diğer seçenekler üzerine gelince açılır")),
            dropdown("quick-compress", p, s.quick_compress, options, |s, v| s.quick_compress = v),
        ));
    }
    {
        use crate::settings::PlainDrag as D;
        v.push(card(
            p,
            L::Move,
            t!("Sürükleyip bırakınca"),
            Some(t!("Ctrl'siz ve Shift'siz bir sürükleme ne yapsın. Ctrl her zaman kopyalar, Shift her zaman taşır.")),
            dropdown(
                "plain-drag",
                p,
                s.plain_drag,
                vec![
                    (D::Auto, t!("Windows gibi: aynı sürücüde taşı, başka sürücüye kopyala").to_string()),
                    (D::Move, t!("Her zaman taşı").to_string()),
                    (D::Copy, t!("Her zaman kopyala").to_string()),
                ],
                |s, v| s.plain_drag = v,
            ),
        ));
        use crate::settings::QuickExtract as X;
        let options = vec![
            (X::Menu, t!("Yalnızca menüyü aç").to_string()),
            (X::Named, t!("Klasöre çıkar").to_string()),
            (X::Smart, t!("Akıllı çıkar").to_string()),
            (X::Here, t!("Buraya çıkar").to_string()),
        ];
        v.push(card(
            p,
            L::FolderOutput,
            t!("Çıkar'a tıklayınca"),
            Some(t!("Sağ tık menüsünde Çıkar'a tıklamak arşivi bu şekilde hemen çıkarır; diğer seçenekler üzerine gelince açılır")),
            dropdown("quick-extract", p, s.quick_extract, options, |s, v| s.quick_extract = v),
        ));
    }
    v.push(card(
        p,
        L::FolderOutput,
        t!("Çıkardıktan sonra klasörü aç"),
        Some(t!("Bir arşiv yeni bir klasöre çıkarılınca o klasör yeni sekmede açılır")),
        sw("open-extracted", p, s.open_after_extract, |s, v| s.open_after_extract = v),
    ));
    v.push(card(
        p,
        L::Search,
        t!("Aramada Windows dizinini kullan"),
        Some(t!("Dizinlenmiş klasörlerde dosya içerikleri de aranır ve kind:picture, size:>10MB gibi filtreler çalışır")),
        sw("search-index", p, s.search_index, |s, v| s.search_index = v),
    ));
    v.push(card(
        p,
        L::Zap,
        t!("Hızlı arama dizini"),
        Some(&name_index_status()),
        sw("name-index", p, s.name_index, |s, v| s.name_index = v),
    ));
    if s.name_index {
        v.push(card(
            p,
            L::HardDrive,
            t!("Sabit diskleri de dizinle"),
            Some(t!("Dönen diskler (HDD) varsayılan olarak dizine alınmaz: taranmaları dakikalar sürer ve duyulur. Açılırsa tarama bilgisayar boştayken yapılır.")),
            sw("index-hard-drives", p, s.index_hard_drives, |s, v| s.index_hard_drives = v),
        ));
        v.push(index_drives_card(p, s, cx));
        v.push(index_exclusions(p, s));
    }
    v.push(card(
        p,
        L::HardDrive,
        t!("Boyut biçimi"),
        None,
        dropdown(
            "size-fmt",
            p,
            (s.decimal_sizes, s.binary_prefixes && !s.decimal_sizes),
            vec![
                ((false, false), t!("İkili (1 KB = 1024 bayt)").into()),
                ((false, true), t!("İkili, IEC adlarıyla (1 KiB = 1024 bayt)").into()),
                ((true, false), t!("Ondalık (1 KB = 1000 bayt)").into()),
            ],
            |s, (decimal, iec)| {
                s.decimal_sizes = decimal;
                s.binary_prefixes = iec;
            },
        ),
    ));
    let pp = *p;
    v.push(expander(
        "folder-sizes",
        p,
        L::FolderSearch,
        t!("Klasör boyutlarını hesapla"),
        Some(t!("Boyut sütununda klasörlerin toplam boyutu gösterilir")),
        Some(sw("calc-sizes", p, s.calculate_folder_sizes, |s, v| s.calculate_folder_sizes = v)),
        move || {
            vec![
                h_flex()
                    .mx_4()
                    .my_2()
                    .px_3()
                    .py_2()
                    .gap_2()
                    .items_center()
                    .rounded(theme::RADIUS_SM)
                    .bg(hsla_alpha(0xFCE100, 0.12))
                    .child(Icon::new(L::CircleAlert).size(px(14.)).text_color(rgb(0xFCE100)))
                    // (wrapped: a longer language ran out of the box, issue 283)
                    .child(div().flex_1().min_w_0().whitespace_normal().text_xs().text_color(pp.text).child(t!("Büyük klasörlerde disk ve işlemci yükü artabilir; hesap arka planda yapılır, arayüz donmaz.")))
                    .into_any_element(),
            ]
        },
        cx,
    ));

    v.push(card(
        p,
        L::Network,
        t!("Ağ sürücülerinde de hesapla"),
        Some(t!("Kapalıyken klasör boyutları yalnızca bu bilgisayarın sürücülerinde hesaplanır; ağ paylaşımları yorulmaz")),
        sw("calc-sizes-net", p, s.folder_sizes_on_network, |s, v| s.folder_sizes_on_network = v),
    ));
    v.push(card(
        p,
        L::HardDrive,
        t!("Klasörlerde disk üzerindeki boyutu göster"),
        Some(t!("Boyut sütunu klasörler için dosya boyutlarının toplamı yerine kümelere yuvarlanmış boyutu gösterir; sıralama da buna göre yapılır")),
        sw("folder-on-disk", p, s.folder_size_on_disk, |s, v| s.folder_size_on_disk = v),
    ));
    v.push(card(
        p,
        L::Search,
        t!("Klasör boyutlarını Everything'den al"),
        Some(t!("Everything açıksa ve klasör boyutlarını dizinliyorsa (Seçenekler › Dizinler › Klasör boyutunu dizinle), klasör boyutları diski taramadan onun dizininden gelir. Everything'in bilmediği klasörler yalnızca «Klasör boyutlarını hesapla» açıkken ya da elle istendiğinde ölçülür.")),
        sw("sizes-everything", p, s.folder_sizes_everything, |s, v| s.folder_sizes_everything = v),
    ));

    // Files' folder aliases: "@name" in the address box
    v.push(section(p, t!("Sürücüler")));
    v.push(hidden_drives_card(p, s));
    if !s.hidden_places.is_empty() {
        v.push(hidden_places_card(p, s));
    }
    v.push(section(p, t!("Klasör takma adları")));
    let aliases: Vec<(String, std::path::PathBuf)> = s.folder_aliases.iter().map(|(n, p)| (n.clone(), p.clone())).collect();
    let count = aliases.len();
    v.push(expander(
        "aliases",
        p,
        L::AtSign,
        t!("Takma adlar"),
        Some(t!("Adres çubuğuna @ad yazarak klasöre gidin. Eklemek için bir klasöre Shift basılıyken sağ tıklayıp \"Takma ad ver…\" seçin (ya da Ayarlar › Genel › Sağ tık menüsünde her zaman tüm komutlar).")),
        Some(div().text_sm().text_color(p.text_secondary).child(count.to_string()).into_any_element()),
        move || {
            if aliases.is_empty() {
                return vec![sub(&pp, t!("Henüz takma ad yok"), None, div().into_any_element())];
            }
            aliases
                .into_iter()
                .enumerate()
                .map(|(i, (name, path))| {
                    let key = name.clone();
                    sub(
                        &pp,
                        &format!("@{name}"),
                        Some(&path.to_string_lossy()),
                        button(("alias-rm", i), &pp, t!("Kaldır"), move |_, cx| {
                            let key = key.clone();
                            settings::update(cx, move |s| {
                                s.folder_aliases.remove(&key);
                            });
                        }),
                    )
                })
                .collect()
        },
        cx,
    ));
    v
}

fn actions(p: &Palette, s: &Settings, cx: &mut App) -> Vec<AnyElement> {
    let mut grid = div().px_4().py_3().flex().flex_wrap().gap_x_6().gap_y_0p5();
    let capturing = crate::keymap_editor::capturing(cx);
    let entries = crate::command_palette::shortcut_entries();
    let conflicts = crate::keymap_editor::conflicts(&entries, &|a| crate::keymap_editor::custom_keys(a, cx));
    for (i, (label, keys, action)) in entries.into_iter().enumerate() {
        let custom = crate::keymap_editor::custom_keys(&action, cx);
        // another command has the same keys: both are marked, hovering says which
        let clash = conflicts.get(&action).map(|other| format!("{} {}", t!("Aynı kısayol:"), crate::i18n::t(other)));
        let waiting = capturing.as_deref() == Some(action.as_str());
        let shown: SharedString = if waiting {
            t!("Tuşlara basın…").into()
        } else if let Some(k) = &custom {
            crate::keymap_editor::pretty(k).into()
        } else if keys.is_empty() {
            "—".into()
        } else {
            keys.into()
        };
        let act = action.clone();
        let reset_act = action.clone();
        grid = grid.child(
            h_flex()
                .id(("kb", i))
                .w(px(380.))
                .h(px(32.))
                .px_2()
                .rounded(theme::RADIUS_SM)
                .justify_between()
                .items_center()
                .text_sm()
                .cursor_pointer()
                .hover(|s| s.bg(p.pressed))
                .when(waiting, |d| d.bg(p.selection))
                .on_click(move |_, window, cx| {
                    crate::keymap_editor::start(act.clone(), cx);
                    window.refresh();
                })
                .child(crate::i18n::t(label))
                .child(
                    h_flex()
                        .id(("kb-keys", i))
                        .gap_1()
                        .items_center()
                        .child(
                            div()
                                .px_2()
                                .py_0p5()
                                .rounded(px(4.))
                                .border_1()
                                .border_color(p.border)
                                .text_xs()
                                .text_color(if clash.is_some() && !waiting {
                                    p.danger
                                } else if waiting || custom.is_some() {
                                    p.accent
                                } else {
                                    p.text_secondary
                                })
                                .when(clash.is_some() && !waiting, |d| d.border_color(p.danger))
                                .child(shown),
                        )
                        .when_some(clash.filter(|_| !waiting), |d, tip| {
                            d.tooltip(move |w, cx| gpui_kit::component::tooltip::Tooltip::new(tip.clone()).build(w, cx))
                        })
                        .when(custom.is_some() && !waiting, |d| {
                            d.child(
                                div()
                                    .id(("kb-reset", i))
                                    .px_1()
                                    .rounded(theme::RADIUS_SM)
                                    .text_xs()
                                    .text_color(p.text_secondary)
                                    .hover(|s| s.bg(p.pressed))
                                    .child("↺")
                                    .on_click(move |_, window, cx| {
                                        cx.stop_propagation();
                                        crate::keymap_editor::reset(&reset_act, cx);
                                        window.refresh();
                                    }),
                            )
                        }),
                ),
        );
    }
    vec![
        card(
            p,
            L::Clock,
            t!("Komut paletinde geçmiş klasörleri göster"),
            Some(t!("Yazdıkça daha önce gidilen klasörler komutlarla birlikte listelenir. Ctrl+P her zaman yalnızca geçmiş klasörlerde arar.")),
            sw("palette-folders", p, s.palette_folder_history, |s, v| s.palette_folder_history = v),
        ),
        shell(p)
            .child(card_body(
                p,
                L::Keyboard,
                t!("Klavye kısayolları").into(),
                Some(t!("Değiştirmek için bir komuta tıklayıp yeni tuşlara basın (Esc: vazgeç). ↺ varsayılana döndürür.").into()),
                None,
            ))
            .child(div().h(px(1.)).bg(p.divider))
            .child(grid)
            .into_any_element(),
    ]
}

fn tags(p: &Palette, cx: &mut App) -> Vec<AnyElement> {
    let defs = cx.global::<crate::tags::Tags>().0.defs.clone();
    let mut list = v_flex().py_1();
    for d in defs {
        let (id, name, color) = (d.id, d.name.clone(), d.color);
        let rename_name = name.clone();
        list = list.child(
            h_flex()
                .min_h(px(48.))
                .pl(px(56.))
                .pr_4()
                .gap_3()
                .items_center()
                .child(
                    div()
                        .id(("tag-color", id as usize))
                        .size(px(18.))
                        .rounded_full()
                        .bg(rgb(color))
                        .cursor_pointer()
                        .on_click(move |ev: &ClickEvent, window, cx| {
                            let items = TAG_COLORS
                                .iter()
                                .map(|(n, c)| {
                                    let c = *c;
                                    Item::action(crate::i18n::t(n), MenuIcon::Dot(rgb(c).into()), move |_, cx| crate::tags::update(cx, |t| t.recolor(id, c)))
                                        .checked(c == color)
                                })
                                .collect();
                            fluent_menu::show(Menu { quick: Vec::new(), items }, ev.position(), window, cx);
                        }),
                )
                .child(div().flex_1().text_sm().child(crate::i18n::td(&name)))
                .child(button(("tag-edit", id as usize), p, t!("Yeniden adlandır"), move |window, cx| {
                    // the box starts from the name the list shows: a tag the app came with is kept under its Turkish name and shown
                    // in the interface's language, and the box began with the Turkish one (issue 320)
                    tag_name_dialog(Some((id, crate::i18n::td(&rename_name))), window, cx)
                }))
                .child(button(("tag-del", id as usize), p, t!("Sil"), move |window, cx| {
                    crate::prompt::show(
                        t!("Etiket silinsin mi?"),
                        Some(t!("Etiket tüm öğelerden kaldırılır. Dosyalar silinmez.").to_string()),
                        None,
                        vec![
                            crate::prompt::Button::new(t!("Sil"), crate::prompt::Kind::Danger, move |_, _, cx| {
                                crate::tags::update(cx, |t| t.remove(id));
                                Ok(())
                            }),
                            crate::prompt::Button::cancel(),
                        ],
                        window,
                        cx,
                    )
                })),
        );
    }
    vec![
        shell(p)
            .child(card_body(
                p,
                L::Tag,
                t!("Etiketler").into(),
                Some(t!("Renkli etiketlerle dosyaları klasörlerden bağımsız gruplayın. Renge tıklayarak değiştirin.").into()),
                Some(button("tag-new", p, t!("Yeni etiket"), |window, cx| tag_name_dialog(None, window, cx))),
            ))
            .child(div().h(px(1.)).bg(p.divider))
            .child(list)
            .into_any_element(),
    ]
}

const TAG_COLORS: [(&str, u32); 8] = [
    ("Kırmızı", 0xFF453A),
    ("Turuncu", 0xFF9F0A),
    ("Sarı", 0xFFD60A),
    ("Yeşil", 0x30D158),
    ("Turkuaz", 0x40C8E0),
    ("Mavi", 0x0A84FF),
    ("Mor", 0xBF5AF2),
    ("Gri", 0x8E8E93),
];

fn tag_name_dialog(existing: Option<(u32, String)>, window: &mut Window, cx: &mut App) {
    let title = if existing.is_some() { t!("Etiketi yeniden adlandır") } else { t!("Yeni etiket") };
    let initial = existing.as_ref().map(|e| e.1.clone()).unwrap_or_default();
    crate::prompt::show(
        title,
        None,
        Some((initial, t!("Etiket adı").to_string())),
        vec![
            crate::prompt::Button::new(t!("Kaydet"), crate::prompt::Kind::Primary, move |value, _, cx| {
                let name = value.unwrap_or_default().trim().to_string();
                if name.is_empty() {
                    return Err(t!("Bir ad yazın").to_string());
                }
                match &existing {
                    // (left as it was: the tag keeps the name it has, which every language shows in its own word)
                    Some((_, shown)) if *shown == name => {}
                    Some((id, _)) => crate::tags::update(cx, |t| t.rename(*id, &name)),
                    None => crate::tags::update(cx, |t| {
                        t.add(&name, TAG_COLORS[t.defs.len() % TAG_COLORS.len()].1);
                    }),
                }
                Ok(())
            }),
            crate::prompt::Button::cancel(),
        ],
        window,
        cx,
    );
}

fn dev(p: &Palette, s: &Settings, cx: &mut App) -> Vec<AnyElement> {
    // The editors that are installed (`rf_win::editors`): each is a button that chooses it, and "automatic" is the first of them.
    // The look for them asks the disk and the registry, so it runs on another thread and the page is drawn again when the list
    // is another one; while the page is open it is repeated now and then (an editor installed meanwhile shows up).
    static LOOKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
    let (editors, fresh) = rf_win::editors::peek();
    if !fresh && !LOOKING.swap(true, std::sync::atomic::Ordering::Relaxed) {
        cx.spawn(async move |cx| {
            let changed = cx.background_executor().spawn(async { rf_win::editors::refresh() }).await;
            LOOKING.store(false, std::sync::atomic::Ordering::Relaxed);
            if changed {
                let _ = cx.update(|cx| cx.refresh_windows());
            }
        })
        .detach();
    }
    let ide_label = if s.ide_path.is_empty() {
        match editors.first() {
            Some(editor) => format!("{}: {}", t!("Otomatik"), editor.name),
            None => t!("VS Code (otomatik)").to_string(),
        }
    } else {
        match rf_win::editors::name_of(&editors, std::path::Path::new(&s.ide_path)) {
            // (one of the installed editors: its name says it; its path beside it broke over three lines)
            Some(name) => name.to_string(),
            None => s.ide_path.clone(),
        }
    };
    let choices = editors.iter().enumerate().map(|(i, editor)| {
        let exe = editor.exe.display().to_string();
        button(("ide-editor", i), p, editor.name, move |_, cx| {
            let exe = exe.clone();
            settings::update(cx, move |s| s.ide_path = exe)
        })
    });
    vec![
        card(
            p,
            L::Code,
            t!("Durum çubuğunda \"Düzenleyicide aç\" düğmesi"),
            None,
            dropdown(
                "ide-btn",
                p,
                s.ide_button,
                vec![
                    (IdePref::GitRepos, t!("Git depolarında göster").into()),
                    (IdePref::Always, t!("Her zaman göster").into()),
                    (IdePref::Never, t!("Gösterme").into()),
                ],
                |s, v| s.ide_button = v,
            ),
        ),
        card(
            p,
            L::SquareTerminal,
            t!("Düzenleyici"),
            Some(&ide_label),
            h_flex()
                .gap_2()
                .flex_wrap()
                .justify_end()
                .children(choices)
                .child(button("ide-browse", p, t!("Gözat"), |window, cx| pick_into(window, cx, t!("Düzenleyici seç"), PickTarget::Ide)))
                .child(button("ide-reset", p, t!("Otomatik"), |_, cx| settings::update(cx, |s| s.ide_path.clear())))
                .into_any_element(),
        ),
        terminal_card(p, s),
        text_editor_card(p, s, &editors),
        card(
            p,
            L::GitCompare,
            t!("Git durumunu göster"),
            Some(t!("Depoların içinde dosyaların Git durumu, adın yanındaki işaret ve commit sütunları; kapalıyken liste için Git hiç çalıştırılmaz")),
            sw("git-integration", p, s.git_integration, |s, v| s.git_integration = v),
        ),
        git_card(p, s, cx),
    ]
}

/// The program every Git command runs: `git` from the PATH, or any one through "Browse" (another Git, `wslgit.exe`), with the version
/// it answers with. It is asked on another thread, and again now and then while the page is open, as the editors above are.
fn git_card(p: &Palette, s: &Settings, cx: &mut App) -> AnyElement {
    static LOOKING: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
    fn looking() -> std::sync::MutexGuard<'static, Vec<String>> {
        LOOKING.lock().unwrap_or_else(|e| e.into_inner())
    }
    let (version, fresh) = rf_win::git_program::peek(&s.git_path);
    if !fresh && !looking().contains(&s.git_path) {
        looking().push(s.git_path.clone());
        let program = s.git_path.clone();
        cx.spawn(async move |cx| {
            let asked = program.clone();
            let changed = cx.background_executor().spawn(async move { rf_win::git_program::refresh(&asked) }).await;
            looking().retain(|l| *l != program);
            if changed {
                let _ = cx.update(|cx| cx.refresh_windows());
            }
        })
        .detach();
    }
    let found = match version {
        Some(Some(version)) => format!("Git {version}"),
        Some(None) => t!("Git bulunamadı").to_string(),
        None => t!("Denetleniyor…").to_string(),
    };
    let label = if s.git_path.is_empty() { format!("{}: {found}", t!("Otomatik")) } else { format!("{found} · {}", s.git_path) };
    card(
        p,
        L::GitBranch,
        "Git",
        Some(&label),
        h_flex()
            .gap_2()
            .flex_wrap()
            .justify_end()
            .child(button("git-browse", p, t!("Gözat"), |window, cx| pick_into(window, cx, t!("Git programı seç"), PickTarget::Git)))
            .child(button("git-reset", p, t!("Otomatik"), |_, cx| settings::update(cx, |s| s.git_path.clear())))
            .into_any_element(),
    )
}

/// The text editors a file can be edited in with F4 (or the toolbar's "Edit"): Notepad, the usual ones that are installed, the code
/// editors found for "Open in editor", or any program through "Browse".
fn text_editor_card(p: &Palette, s: &Settings, code_editors: &[rf_win::editors::Editor]) -> AnyElement {
    // (looked for once: a few files in the programs folders)
    static FOUND: std::sync::OnceLock<Vec<(&'static str, String)>> = std::sync::OnceLock::new();
    let found = FOUND.get_or_init(|| {
        let roots: Vec<std::path::PathBuf> = ["ProgramFiles", "ProgramFiles(x86)"].iter().filter_map(std::env::var_os).map(std::path::PathBuf::from).collect();
        let mut out = Vec::new();
        for (name, rel) in [("Notepad++", r"Notepad++\notepad++.exe"), ("Sublime Text", r"Sublime Text\sublime_text.exe"), ("Sublime Text 3", r"Sublime Text 3\sublime_text.exe")] {
            if let Some(exe) = roots.iter().map(|r| r.join(rel)).find(|p| p.is_file()) {
                out.push((name, exe.display().to_string()));
            }
        }
        out
    });
    let mut choices: Vec<(String, String)> = vec![("Notepad".to_string(), "notepad.exe".to_string())];
    choices.extend(found.iter().map(|(n, e)| (n.to_string(), e.clone())));
    choices.extend(code_editors.iter().map(|e| (e.name.to_string(), e.exe.display().to_string())));
    let label = if s.text_editor_path.is_empty() {
        t!("Otomatik: Not Defteri").to_string()
    } else {
        choices.iter().find(|(_, e)| e.eq_ignore_ascii_case(&s.text_editor_path)).map_or_else(|| s.text_editor_path.clone(), |(n, _)| n.clone())
    };
    let buttons = choices.into_iter().enumerate().map(|(i, (name, exe))| {
        button(("text-editor-pick", i), p, name, move |_, cx| {
            let exe = exe.clone();
            settings::update(cx, move |s| s.text_editor_path = exe)
        })
    });
    card(
        p,
        L::FilePen,
        t!("Metin düzenleyici (F4)"),
        Some(&label),
        h_flex()
            .gap_2()
            .flex_wrap()
            .justify_end()
            .children(buttons)
            .child(button("text-editor-browse", p, t!("Gözat"), |window, cx| pick_into(window, cx, t!("Metin düzenleyici seç"), PickTarget::TextEditor)))
            .child(button("text-editor-reset", p, t!("Otomatik"), |_, cx| settings::update(cx, |s| s.text_editor_path.clear())))
            .into_any_element(),
    )
}

/// "Open in Terminal" starts this program (issue 224): the usual ones as buttons, any other one through "Browse".
fn terminal_card(p: &Palette, s: &Settings) -> AnyElement {
    const KNOWN: &[(&str, &str)] = &[("wt.exe", "Windows Terminal"), ("pwsh.exe", "PowerShell 7"), ("powershell.exe", "Windows PowerShell"), ("cmd.exe", "cmd")];
    let label = if s.terminal_path.is_empty() {
        t!("Otomatik: Windows Terminal, yoksa PowerShell").to_string()
    } else {
        KNOWN.iter().find(|(exe, _)| exe.eq_ignore_ascii_case(&s.terminal_path)).map_or_else(|| s.terminal_path.clone(), |(_, name)| name.to_string())
    };
    let choices = KNOWN.iter().enumerate().map(|(i, (exe, name))| {
        let exe = exe.to_string();
        button(("terminal-pick", i), p, *name, move |_, cx| {
            let exe = exe.clone();
            settings::update(cx, move |s| s.terminal_path = exe)
        })
    });
    card(
        p,
        L::SquareTerminal,
        t!("Terminal"),
        Some(&label),
        h_flex()
            .gap_2()
            .flex_wrap()
            .justify_end()
            .children(choices)
            .child(button("terminal-browse", p, t!("Gözat"), |window, cx| pick_into(window, cx, t!("Terminal seç"), PickTarget::Terminal)))
            .child(button("terminal-reset", p, t!("Otomatik"), |_, cx| settings::update(cx, |s| s.terminal_path.clear())))
            .into_any_element(),
    )
}

/// DirectLook ayarı anahtarı (ayrı dosya `directlook.toml`; değişince DirectLook'a haber verilir).
fn lsw(id: &'static str, p: &Palette, on: bool, set: fn(&mut LookSettings, bool)) -> AnyElement {
    switch(id, p, on, move |_, cx| look_update(cx, |s| set(s, !on)))
}

fn look_update(cx: &mut App, f: impl FnOnce(&mut LookSettings)) {
    crate::look::config::update(cx, f);
    crate::look::ipc::send(crate::look::ipc::Msg::Reload, false);
}

fn ldropdown<T: Copy + PartialEq + 'static>(id: &'static str, p: &Palette, current: T, options: Vec<(T, String)>, set: fn(&mut LookSettings, T)) -> AnyElement {
    let label = options.iter().find(|(v, _)| *v == current).map(|(_, l)| l.clone()).unwrap_or_default();
    select_box(id, p, label, move |_| {
        options.iter().map(|(v, l)| {
            let v = *v;
            Choice::new(l.clone(), v == current, move |_, cx| look_update(cx, |s| set(s, v)))
        }).collect()
    })
}

/// DirectLook (Hızlı Bakış, ayrı program) ayarları.
fn look(p: &Palette, s: &Settings, cx: &mut App) -> Vec<AnyElement> {
    use crate::settings::{LookBackdrop, LookImageTheme};
    // DirectLook da yazabilir: sayfa her açılışta dosyadan okunur
    let l = LookSettings::load();
    let enabled = s.directlook_enabled;
    let mut v = vec![card(
        p,
        L::Eye,
        t!("DirectLook'u kullan"),
        Some(t!("Boşluk ile önizleme. Ayrı bir program olarak çalışır: rustyfiles'ı yavaşlatmaz, biri kapanınca öteki etkilenmez.")),
        switch("dl-enabled", p, enabled, move |_, cx| {
            settings::update(cx, |s| s.directlook_enabled = !enabled);
            if enabled {
                crate::look::ipc::send(crate::look::ipc::Msg::Quit, false);
            } else {
                crate::look::ipc::send(crate::look::ipc::Msg::Wake, true);
            }
        }),
    )];
    // QuickLook instead (asked on Discord): shown with DirectLook off too, as that is how it is meant to be used
    let ql = s.space_quicklook;
    v.push(card(
        p,
        L::ScanEye,
        t!("Boşluk QuickLook'u açsın"),
        Some(if crate::quicklook::installed() {
            t!("Dosyalar QuickLook'a gönderilir ve açık önizleme seçimi izler. DirectLook'u yukarıdan kapatabilirsiniz.")
        } else {
            t!("QuickLook kurulu değil: Microsoft Store'dan ya da GitHub'dan (QL-Win/QuickLook) kurulabilir.")
        }),
        switch("space-ql", p, ql, move |_, cx| settings::update(cx, |s| s.space_quicklook = !ql)),
    ));
    if !enabled {
        return v;
    }
    v.push(card(
        p,
        L::Monitor,
        t!("Explorer ve masaüstünde de Boşluk ile önizle"),
        Some(t!("DirectLook arka planda çalışır ve Windows başladığında açılır (bildirim alanında simge); rustyfiles kapalıyken de")),
        switch("look-wide", p, l.look_system_wide, {
            let on = l.look_system_wide;
            move |_, cx| {
                look_update(cx, |s| s.look_system_wide = !on);
                if let Some(exe) = crate::look::ipc::exe() {
                    if let Err(e) = rf_win::dialogs::set_start_with_windows_as("DirectLook", &exe, &["--background"], !on) {
                        log::warn!("DirectLook start with Windows: {e}");
                    }
                }
                crate::look::ipc::send(crate::look::ipc::Msg::Wake, true);
            }
        }),
    ));
    if l.look_system_wide && !l.look_ignore_quicklook && crate::look::system::quicklook_running() {
        v.push(card(
            p,
            L::TriangleAlert,
            t!("QuickLook çalışıyor"),
            Some(t!("İki uygulama aynı tuşu dinlemesin diye sistem geneli kısayol başlatılmadı")),
            button("look-force", p, t!("Yine de aç"), |window, cx| {
                look_update(cx, |s| s.look_ignore_quicklook = true);
                window.refresh();
            }),
        ));
    }
    let _ = cx;
    v.extend([
        section(p, t!("Pencere")),
        card(
            p,
            L::Layers,
            t!("Arka plan"),
            None,
            ldropdown(
                "look-backdrop",
                p,
                l.look_backdrop,
                vec![
                    (LookBackdrop::Mica, "Mica".into()),
                    (LookBackdrop::Acrylic, "Acrylic".into()),
                    (LookBackdrop::Tabbed, t!("Mica (sekmeli)").into()),
                    (LookBackdrop::None, t!("Düz renk").into()),
                ],
                |s, v| s.look_backdrop = v,
            ),
        ),
        card(p, L::PictureInPicture, t!("Her zaman üstte"), None, lsw("look-top", p, l.look_topmost, |s, v| s.look_topmost = v)),
        card(p, L::PanelBottom, t!("Görev çubuğunda göster"), None, lsw("look-taskbar", p, l.look_show_in_taskbar, |s, v| s.look_show_in_taskbar = v)),
        card(
            p,
            L::AppWindow,
            t!("Bildirim alanında DirectLook simgesi"),
            Some(t!("rustyfiles arka planda çalışırken gösterilmez: tek simge rustyfiles'ınkidir")),
            lsw("look-tray", p, l.look_tray_icon, |s, v| s.look_tray_icon = v),
        ),
        card(p, L::MousePointerClick, t!("Açılınca pencereyi odakla"), Some(t!("Kapalıyken klavye Explorer'da kalır: oklarla dosyalar arasında gezinilir")), lsw("look-focus", p, l.look_focus_on_open, |s, v| s.look_focus_on_open = v)),
        card(p, L::CircleX, t!("Başka pencereye geçince kapat"), Some(t!("Sabitlenmiş pencereler açık kalır")), lsw("look-lostfocus", p, l.look_close_on_lost_focus, |s, v| s.look_close_on_lost_focus = v)),
        card(p, L::Zap, t!("Geçiş animasyonu"), None, lsw("look-transition", p, l.look_transition, |s, v| s.look_transition = v)),
        card(p, L::RefreshCw, t!("Yeniden yükle düğmesi"), None, lsw("look-reload", p, l.look_show_reload, |s, v| s.look_show_reload = v)),
        card(p, L::FolderSync, t!("Dosya değişince yeniden yükle"), None, lsw("look-autoreload", p, l.look_auto_reload, |s, v| s.look_auto_reload = v)),
        section(p, t!("İçerik")),
        card(
            p,
            L::Image,
            t!("Resim zemini"),
            None,
            ldropdown(
                "look-imgtheme",
                p,
                l.look_image_theme,
                vec![(LookImageTheme::Dark, t!("Koyu").into()), (LookImageTheme::Light, t!("Açık").into())],
                |s, v| s.look_image_theme = v,
            ),
        ),
        card(p, L::RotateCw, t!("Videoları döngüde oynat"), None, lsw("look-loop", p, l.look_loop, |s, v| s.look_loop = v)),
        card(p, L::List, t!("Metinde satır numaraları"), Some(t!("Önizlemede Alt+L")), lsw("look-lines", p, l.look_text_line_numbers, |s, v| s.look_text_line_numbers = v)),
        card(p, L::TextAlignJustify, t!("Metinde sözcük kaydırma"), Some(t!("Önizlemede Alt+Z")), lsw("look-wrap", p, l.look_text_wrap, |s, v| s.look_text_wrap = v)),
    ]);
    // text font and size
    let font_label = if l.look_text_font.is_empty() { t!("Varsayılan").to_string() } else { l.look_text_font.clone() };
    let cur_font = l.look_text_font.clone();
    v.push(card(
        p,
        L::Type,
        t!("Metin yazı tipi"),
        None,
        select_box("look-font", p, font_label, move |cx| {
            std::iter::once(String::new())
                .chain(font_choices(cx))
                .map(|f| {
                    let label = if f.is_empty() { t!("Varsayılan").to_string() } else { f.clone() };
                    let sel = f == cur_font;
                    Choice::new(label, sel, move |_, cx| {
                        let f = f.clone();
                        look_update(cx, |s| s.look_text_font = f)
                    })
                })
                .collect()
        }),
    ));
    let cur_size = l.look_text_font_size.round() as u32;
    v.push(card(
        p,
        L::ALargeSmall,
        t!("Metin boyutu"),
        None,
        select_box("look-font-size", p, format!("{cur_size} px"), move |_| {
            [11u32, 12, 13, 14, 15, 16, 18, 20, 24]
                .into_iter()
                .map(|n| Choice::new(format!("{n} px"), n == cur_size, move |_, cx| look_update(cx, |s| s.look_text_font_size = n as f32)))
                .collect()
        }),
    ));
    // which file types DirectLook previews
    v.push(card(
        p,
        L::ListFilter,
        t!("Önizlenecek dosyalar"),
        None,
        ldropdown(
            "look-ext-mode",
            p,
            l.look_ext_allow_mode,
            vec![(false, t!("Hepsi, listedekiler hariç").to_string()), (true, t!("Yalnızca listedekiler").to_string())],
            |s, v| s.look_ext_allow_mode = v,
        ),
    ));
    let allow = l.look_ext_allow_mode;
    let list = if allow { l.look_ext_allowlist.clone() } else { l.look_ext_blocklist.clone() };
    let shown = if list.trim().is_empty() { "—".to_string() } else { list.clone() };
    v.push(card(
        p,
        L::CircleSlash,
        if allow { t!("Önizlenecek uzantılar") } else { t!("Önizlenmeyecek uzantılar") },
        Some(&shown),
        button("look-ext-edit", p, t!("Düzenle…"), move |window, cx| {
            let ok = crate::prompt::Button::new(t!("Kaydet"), crate::prompt::Kind::Primary, move |text, _, cx| {
                let text = normalize_exts(&text.unwrap_or_default());
                look_update(cx, |s| if allow { s.look_ext_allowlist = text } else { s.look_ext_blocklist = text });
                Ok(())
            });
            crate::prompt::show(
                if allow { t!("Önizlenecek uzantılar") } else { t!("Önizlenmeyecek uzantılar") },
                Some(t!("Noktalı virgülle ayırın, örneğin: .iso; .insv; .psd").to_string()),
                Some((list.clone(), ".iso; .insv".to_string())),
                vec![ok, crate::prompt::Button::cancel()],
                window,
                cx,
            );
        }),
    ));
    v
}

/// "iso, .PSD ;; insv" → ".iso;.psd;.insv": dots added, lowercase, no duplicates.
fn normalize_exts(text: &str) -> String {
    let mut out: Vec<String> = Vec::new();
    for part in text.split([';', ',', ' ']) {
        let p = part.trim().trim_start_matches('*').to_lowercase();
        if p.is_empty() || p == "." {
            continue;
        }
        let e = if p.starts_with('.') { p } else { format!(".{p}") };
        if !out.contains(&e) {
            out.push(e);
        }
    }
    out.join(";")
}

#[cfg(test)]
mod ext_tests {
    #[test]
    fn extension_lists_are_normalized() {
        assert_eq!(super::normalize_exts("iso, .PSD ;; insv *.Mkv .iso"), ".iso;.psd;.insv;.mkv");
        assert_eq!(super::normalize_exts("  "), "");
    }
}

fn advanced(p: &Palette, s: &Settings, cx: &mut App) -> Vec<AnyElement> {
    let start_on = rf_win::dialogs::starts_with_windows();
    let load = hybrid::load_snapshot();
    let pct = |v: Option<f32>| v.map(crate::i18n::pct).unwrap_or_else(|| "—".into());
    let live = format!(
        "{} {} · {} {} · {} {} · {} {:.1} ms · {} {}",
        t!("Şu an:"),
        hybrid::current_backend_label(),
        t!("GPU yükü"),
        pct(load.gpu_percent),
        t!("CPU yükü"),
        pct(load.cpu_percent),
        t!("son kare"),
        load.last_frame_ms,
        hybrid::switch_count(),
        t!("geçiş")
    );
    let dfm_on = crate::DEFAULT_FM.load(std::sync::atomic::Ordering::Relaxed);
    let dialogs_on = crate::FILE_DIALOGS.load(std::sync::atomic::Ordering::Relaxed);
    // (only looks: the copy is made when the switch is turned on)
    let has_dll = std::env::current_exe().is_ok_and(|e| e.with_file_name(rf_win::dialog_reg::DLL_NAME).exists());
    // while rustyfiles is the default file manager: archives can be given to it too (only the
    // user can pick the default app, in Windows' own page)
    let archives = dfm_on.then(|| {
        card(
            p,
            L::FileArchive,
            t!("Arşivleri rustyfiles ile aç"),
            Some(t!("Zip, 7z, rar, tar için varsayılan uygulama Windows'ta seçilir. Açılan sayfada rustyfiles'ı varsayılan yapın.")),
            button("dfm-arch", p, t!("Varsayılan uygulamalar"), |_, _| {
                let page = format!("ms-settings:defaultapps?registeredAppUser={}", rf_win::default_fm::APP_NAME);
                if let Err(e) = rf_win::shell::open(std::path::Path::new(&page)) {
                    log::warn!("default apps page: {e:#}");
                }
            }),
        )
    });
    let mut out = vec![
        link_row(p, "export", L::Upload, t!("Ayarları dışa aktar"), None, |window, cx| pick_into(window, cx, t!("Ayarları dışa aktar"), PickTarget::Export)),
        link_row(p, "import", L::Download, t!("Ayarları içe aktar"), None, |window, cx| pick_into(window, cx, t!("Ayarları içe aktar"), PickTarget::Import)),
        link_row(p, "edit-file", L::FilePen, t!("Ayar dosyasını düzenle"), Some(t!("settings.toml metin düzenleyicide açılır")), |_, _| {
            if let Some(path) = settings::path() {
                std::thread::spawn(move || {
                    let _ = std::process::Command::new("notepad.exe").arg(path).spawn();
                });
            }
        }),
        card(
            p,
            L::Power,
            t!("Windows başladığında rustyfiles'ı aç"),
            None,
            switch("start-win", p, start_on, move |window, _| {
                if let Ok(exe) = std::env::current_exe() {
                    if let Err(e) = rf_win::dialogs::set_start_with_windows(&exe, !start_on) {
                        log::warn!("start with Windows: {e}");
                    }
                }
                window.refresh();
            }),
        ),
        card(
            p,
            L::PanelBottom,
            t!("Pencere kapatılınca arka planda çalışmaya devam et"),
            Some(t!("Bildirim alanında bir simge kalır; yeni pencere anında açılır")),
            sw("background", p, s.run_in_background, |s, v| s.run_in_background = v),
        ),
        card(
            p,
            L::Bell,
            t!("Uzun işlemler bitince bildirim göster"),
            Some(t!("Kopyalama, taşıma, sıkıştırma 10 saniyeden uzun sürdüyse ve rustyfiles önde değilse")),
            sw("notify-ops", p, s.notify_long_ops, |s, v| s.notify_long_ops = v),
        ),
        card(
            p,
            L::ListChecks,
            t!("Aktarım ilerlemesi"),
            Some(t!("Kopyalama, taşıma ve silme çalışırken ilerlemenin nerede görüneceği. Durum Merkezi düğmesindeki halka her durumda çalışır.")),
            dropdown(
                "transfer-progress",
                p,
                s.transfer_progress,
                vec![
                    (crate::settings::TransferProgress::StatusBar, t!("Durum çubuğu").into()),
                    (crate::settings::TransferProgress::FloatingCard, t!("Yüzen kart").into()),
                    (crate::settings::TransferProgress::StatusCenter, t!("Yalnız Durum Merkezi").into()),
                ],
                |s, v| s.transfer_progress = v,
            ),
        ),
        // discussion 700
        card(
            p,
            L::Eraser,
            t!("Biten işlemleri temizle"),
            Some(t!("Durum Merkezi'ndeki biten işlemler bu kadar süre sonra kendiliğinden kalkar")),
            dropdown(
                "status-clear",
                p,
                s.status_clear_hours,
                vec![(0, t!("Hiçbir zaman").into()), (1, t!("1 saat sonra").into()), (24, t!("1 gün sonra").into()), (168, t!("1 hafta sonra").into())],
                |s, v| s.status_clear_hours = v,
            ),
        ),
        section(p, t!("Performans")),
        card(
            p,
            L::Zap,
            t!("Hızlı dosya işlemleri"),
            Some(t!("Kopyalama, başka sürücüye taşıma ve kalıcı silme kendi paralel motorumuzla. Kapalıyken her şey Windows'un motoruyla yapılır.")),
            sw("fast-ops", p, s.fast_file_ops, |s, v| s.fast_file_ops = v),
        ),
        disk_kinds(p, s, cx),
        card(
            p,
            L::Trash,
            t!("Hızlı Geri Dönüşüm Kutusu"),
            Some(t!("NTFS sürücülerde silinen öğeler Geri Dönüşüm Kutusu'na tek adımda taşınır (20.000 dosya bir saniyeden kısa). Kapalıyken Windows'un motoru kullanılır.")),
            sw("fast-recycle", p, s.fast_recycle, |s, v| s.fast_recycle = v),
        ),
        card(
            p,
            L::SquareTerminal,
            t!("WSL'e kopyalarken indirme işaretini bırakma"),
            Some(t!("Windows, internetten inen bir dosyanın yanına WSL'de ayrı bir \"Zone.Identifier\" dosyası yazar. Açıkken kopyalama onu siler.")),
            sw("wsl-zone", p, s.wsl_drop_zone, |s, v| s.wsl_drop_zone = v),
        ),
        card(
            p,
            L::ShieldCheck,
            t!("Kopyaları doğrula"),
            Some(t!("Kopyalama bitince her dosya kaynağıyla karşılaştırılır. Tam doğrulama kopyayı diskten okur; daha uzun sürer.")),
            dropdown(
                "copy-verify",
                p,
                s.copy_verify,
                vec![
                    (crate::settings::CopyVerify::Off, t!("Kapalı").into()),
                    (crate::settings::CopyVerify::Quick, t!("Hızlı: boyut ve tarih").into()),
                    (crate::settings::CopyVerify::Full, t!("Tam: içerik").into()),
                ],
                |s, v| s.copy_verify = v,
            ),
        ),
        card(
            p,
            L::Gauge,
            t!("Kopyalama hız sınırı"),
            Some(t!("Ağa veya USB belleğe kopyalarken bağlantıyı tıkamamak için.")),
            dropdown(
                "copy-limit",
                p,
                s.copy_speed_limit,
                std::iter::once((0, t!("Sınırsız").to_string())).chain([5u32, 10, 25, 50, 100, 250].into_iter().map(|m| (m, format!("{m} MB/s")))).collect(),
                |s, v| s.copy_speed_limit = v,
            ),
        ),
        card(
            p,
            L::Activity,
            t!("Durum çubuğunda performans bilgisi"),
            Some(t!("Klasörün listelenme süresi ve çizim yöntemi (GPU / CPU)")),
            sw("perf-info", p, s.show_perf_info, |s, v| s.show_perf_info = v),
        ),
        shell(p)
            .child(card_body(
                p,
                L::Activity,
                t!("Çizim yöntemi").into(),
                Some(t!("Otomatik: açılışta ekran kartı denetlenir, sorun yoksa arayüz GPU ile çizilir. GPU doluyken (oyun, render) CPU'ya geçer, boşalınca geri döner. Geçiş fark edilmez.").into()),
                Some(dropdown(
                    "renderer",
                    p,
                    s.renderer,
                    vec![(RendererPref::Auto, t!("Otomatik").into()), (RendererPref::Gpu, "GPU".into()), (RendererPref::Cpu, "CPU".into())],
                    |s, v| s.renderer = v,
                )),
            ))
            .child(div().pl(px(56.)).pr_4().pb_3().text_xs().text_color(p.text_tertiary).child(live))
            .into_any_element(),
        section(p, t!("Deneysel")),
        card(
            p,
            L::AppWindow,
            t!("Varsayılan dosya yöneticisi olarak ayarla"),
            Some(t!("Klasörler ve Win+E rustyfiles ile açılır. Yalnızca bu kullanıcı için; istediğiniz an geri alınır.")),
            switch("dfm", p, dfm_on, move |window, _| {
                let exe = std::env::current_exe().map(|e| e.display().to_string()).unwrap_or_default();
                std::thread::spawn(move || {
                    let classes = rf_win::default_fm::CLASSES;
                    let r = if dfm_on { rf_win::default_fm::disable(classes) } else { rf_win::default_fm::enable(&exe, classes) };
                    if let Err(e) = r {
                        log::warn!("default file manager: {e:#}");
                    }
                    crate::DEFAULT_FM.store(rf_win::default_fm::is_enabled(classes), std::sync::atomic::Ordering::Relaxed);
                });
                window.refresh();
            }),
        ),
        card(
            p,
            L::ExternalLink,
            t!("Başka programların açtığı Explorer pencereleri"),
            Some(t!("Bir program (örneğin bir indirme yöneticisi) Explorer'ı kendisi açarsa pencere kapanır ve aynı yer rustyfiles'ta açılır. rustyfiles çalışırken geçerlidir.")),
            sw("catch-explorer", p, s.catch_explorer_windows, |s, v| s.catch_explorer_windows = v),
        ),
    ];
    // rustyfiles as the Windows shell from the next sign-in (experimental): the per-user Winlogon Shell value names the guard, which
    // gives Explorer back on its own when the shell cannot run (rf_win::shell_switch). Only an installed copy has the guard.
    if let Some(guard) = std::env::current_exe().ok().and_then(|e| rf_win::shell_switch::guard_next_to(&e)) {
        let on = rf_win::shell_switch::is_on(&guard);
        out.push(card(
            p,
            L::Monitor,
            t!("Windows kabuğu olarak rustyfiles (deneysel)"),
            Some(t!("Bir sonraki oturum açışından itibaren Explorer yerine rustyfiles'ın masaüstü, dock'u ve Başlat'ı açılır. Kapatıp oturumu yeniden açınca Explorer geri gelir. Bir sorun olursa ya da oturum açarken Shift basılı tutulursa Explorer kendiliğinden açılır.")),
            switch("shell-switch", p, on, move |window, cx| {
                let guard = guard.clone();
                if on {
                    if let Err(e) = rf_win::shell_switch::set(&guard, false) {
                        log::warn!("shell switch off: {e}");
                    }
                    window.refresh();
                    return;
                }
                // turning it on is asked once more: it changes what Windows starts at the next sign-in
                let rx = crate::prompt::pick_rich(
                    t!("rustyfiles Windows kabuğu olsun mu?"),
                    t!("Bir sonraki oturum açışında Explorer başlamaz; masaüstü, görev çubuğu ve Başlat rustyfiles'tan gelir. Deneysel: bazı Windows parçaları (bildirimler, bazı uygulamaların açılışı) eksik kalabilir. Geri dönmek için bu anahtarı kapatıp oturumu yeniden açın; oturum açarken Shift basılı tutmak da o seferlik Explorer'ı açar.").to_string(),
                    None,
                    vec![(t!("Evet, aç").into(), crate::prompt::Kind::Primary), (t!("İptal").into(), crate::prompt::Kind::Normal)],
                    window,
                    cx,
                );
                cx.spawn(async move |cx| {
                    if rx.await == Ok(0) {
                        if let Err(e) = rf_win::shell_switch::set(&guard, true) {
                            log::warn!("shell switch on: {e}");
                        }
                        cx.update(|cx| cx.refresh_windows());
                    }
                })
                .detach();
            }),
        ));
    }
    // another program is the folder handler for this user (Discord, 2026-11-29: File Pilot's leftover entry, its program gone, made
    // every folder answer "Application not found", and it also wins over the switch above): said, with a way to take its place
    if let Some(other) = rf_win::default_fm::other_folder_handler(rf_win::default_fm::CLASSES) {
        let who = other.program.as_ref().map(|p| p.display().to_string()).unwrap_or_else(|| other.command.clone());
        let mut text = t!("{program} klasörleri açan program olarak kayıtlı: Windows klasörleri onunla açar, rustyfiles'ın varsayılan dosya yöneticisi ayarı geçerli olmaz.").replace("{program}", &who);
        if !other.program_exists {
            text.push(' ');
            text.push_str(t!("Bu program artık bulunamıyor, bu yüzden klasörler açılmıyor olabilir (\"Uygulama bulunamadı\")."));
        }
        let take = button("dfm-take-over", p, t!("Yine de rustyfiles kullansın"), |window, _| {
            let exe = std::env::current_exe().map(|e| e.display().to_string()).unwrap_or_default();
            std::thread::spawn(move || {
                let classes = rf_win::default_fm::CLASSES;
                // (its values are kept and put back when the default file manager is turned off)
                let r = rf_win::default_fm::enable(&exe, classes).and_then(|_| rf_win::default_fm::take_over_folders(&exe, classes));
                if let Err(e) = r {
                    log::warn!("default file manager, taking over: {e:#}");
                }
                crate::DEFAULT_FM.store(rf_win::default_fm::is_enabled(classes), std::sync::atomic::Ordering::Relaxed);
            });
            window.refresh();
        });
        out.push(card(p, L::TriangleAlert, t!("Klasörleri başka bir program açıyor"), Some(&text), take));
    }
    out.extend(archives);
    // other apps' Open / Save / folder dialogs show rustyfiles (needs rustyfiles_dialog.dll)
    out.push(card(
        p,
        L::FolderOpen,
        t!("Aç / Kaydet pencerelerinde rustyfiles"),
        Some(if has_dll {
            t!("Uygulamaların dosya açma, kaydetme ve klasör seçme pencereleri rustyfiles ile açılır. Pencereye kendi seçeneklerini ekleyen uygulamalarda Windows'un penceresi açılır. Açık uygulamalarda, yeniden başlatınca geçerli olur.")
        } else {
            t!("rustyfiles_dialog.dll bulunamadı: rustyfiles'ı kurulum betiğiyle kurun.")
        }),
        switch("dlg", p, dialogs_on, move |window, _| {
            if !has_dll && !dialogs_on {
                return;
            }
            std::thread::spawn(move || {
                let classes = rf_win::dialog_reg::CLASSES;
                let r = if dialogs_on { rf_win::dialog_reg::disable(classes) } else { crate::dialog_registration(crate::DialogReg::Enable).map(|_| ()) };
                if let Err(e) = r {
                    log::warn!("file dialogs: {e:#}");
                }
                crate::FILE_DIALOGS.store(rf_win::dialog_reg::is_enabled(classes), std::sync::atomic::Ordering::Relaxed);
            });
            window.refresh();
        }),
    ));
    out.push(card(
        p,
        L::Sparkles,
        t!("Aç / Kaydet penceresinde de HyperGlass"),
        Some(t!("Kapalıyken pencere mattır: arkasındaki program görünmez, yazılar okunaklı kalır. Açıkken ana pencerenin malzemesi kullanılır.")),
        sw("picker-glass", p, s.picker_see_through, |s, v| s.picker_see_through = v),
    ));
    // (issue 473: a dialog kept its sidebar open only after its edge had been dragged wide, which nobody would guess)
    out.push(card(
        p,
        L::PanelLeft,
        t!("Aç / Kaydet penceresinde kenar çubuğu açık"),
        Some(t!("Kapalıyken kenar çubuğu bir simge şerididir, üstüne gelince açılır. Pencerede kenarını sürükleyerek de değişir.")),
        sw("picker-sidebar", p, !s.picker_sidebar_rail, |s, v| s.picker_sidebar_rail = !v),
    ));
    // the folders some apps' Open / Save windows always start in (set with the pin button of the dialog)
    for (i, (app, dir)) in s.dialog_folders.iter().enumerate() {
        let key = app.clone();
        out.push(card(
            p,
            L::Pin,
            app.trim_end_matches(".exe"),
            Some(&format!("{} {dir}", t!("Aç / Kaydet penceresi hep bu klasörde açılır:"))),
            button(("dlg-folder", i), p, t!("Kaldır"), move |_, cx| {
                let key = key.clone();
                crate::settings::update(cx, move |s| {
                    s.dialog_folders.remove(&key);
                });
            }),
        ));
    }
    // the apps whose Open / Save windows stay Windows' own (added with the dialog's own button, issue 371), in a card of their own
    // that opens: one card per program made the page long (the reporter: "a sub-section ... to keep the menu clean"). A program can
    // be added here too: one whose dialog fails to come up can't be added from the dialog (issue 371: FreeCAD).
    {
        let apps = s.dialog_windows_apps.clone();
        let pp = *p;
        let add = button("dlg-windows-add", p, t!("Program ekle…"), |_, cx| {
            // (on the shell thread, never inside the click: see the index's "Klasör ekle…")
            let (tx, rx) = futures::channel::oneshot::channel::<Option<std::path::PathBuf>>();
            let title = t!("Windows'un Aç / Kaydet penceresini alacak program").to_string();
            let label = t!("Programlar").to_string();
            rf_win::sta::run(move |owner| {
                let _ = tx.send(rf_win::dialogs::pick(owner, &title, rf_win::dialogs::Pick::File { filters: &[(&label, "*.exe")] }));
            });
            cx.spawn(async move |cx| {
                let Ok(Some(exe)) = rx.await else { return };
                let Some(key) = exe.file_name().map(|n| n.to_string_lossy().trim().to_lowercase()).filter(|k| !k.is_empty()) else { return };
                cx.update(|cx| {
                    settings::update(cx, move |s| {
                        if !s.dialog_windows_apps.contains(&key) {
                            s.dialog_windows_apps.push(key);
                            s.dialog_windows_apps.sort();
                        }
                    })
                });
            })
            .detach();
        });
        out.push(expander(
            "dlg-windows-apps",
            p,
            L::AppWindow,
            t!("Windows'un Aç / Kaydet penceresini alan programlar"),
            None,
            Some(add),
            move || {
                apps.iter()
                    .enumerate()
                    .map(|(i, app)| {
                        let key = app.clone();
                        sub(
                            &pp,
                            app.trim_end_matches(".exe"),
                            Some(t!("Bu programda Windows'un Aç / Kaydet penceresi açılır.")),
                            button(("dlg-windows", i), &pp, t!("Kaldır"), move |_, cx| {
                                let key = key.clone();
                                crate::settings::update(cx, move |s| s.dialog_windows_apps.retain(|a| *a != key));
                            }),
                        )
                    })
                    .collect()
            },
            cx,
        ));
    }
    out.extend([
        card(
            p,
            L::FolderTree,
            t!("Düzleştirme seçeneğini göster"),
            Some(t!("Klasördeki tüm alt klasörlerin dosyalarını tek seviyeye taşır. Ctrl+Z ile geri alınır.")),
            sw("flatten", p, s.show_flatten, |s, v| s.show_flatten = v),
        ),
        // issue 690: for the user's own scripts and launchers, read-only, off by default
        card(
            p,
            L::SquareTerminal,
            t!("Betikler açık klasörleri okuyabilsin"),
            Some(t!("\"rustyfiles --state\" açık pencereleri, sekmelerin klasörlerini ve seçimi JSON olarak yazar. Yalnızca bu Windows kullanıcısının programları okuyabilir; hiçbir şey değiştirilemez.")),
            sw("state-api", p, s.state_api, |s, v| s.state_api = v),
        ),
        card(
            p,
            L::ScrollText,
            t!("Günlük dosyası"),
            Some(t!("Uyarılar ve hatalar rustyfiles.log dosyasına yazılır (en çok 1 MB; dolunca eskisi .old olur). Bir sorunu bildirirken eklenebilir.")),
            button("log-open", p, t!("Klasörde göster"), |_, cx| {
                if let Some(path) = crate::logfile::path() {
                    // (after this window's own update: a window cannot be given a tab while it handles the click, and a second
                    // window was made instead: see `workspace::show_in_folder_from`)
                    cx.defer(move |cx| crate::workspace::route_ipc(format!("{}{}", crate::workspace::SELECT_TAB_PREFIX, path.display()), cx));
                }
            }),
        ),
    ]);
    // the thumbnail cache's limit and a clear button (thumb_cache.rs)
    out.push(section(p, t!("Önbellek")));
    out.extend(crate::thumb_cache::cards(p, s, cx));
    out
}

fn open_url(url: &'static str) {
    std::thread::spawn(move || {
        let _ = rf_win::shell::open(std::path::Path::new(url));
    });
}

/// Update status and the button that fits it (Settings → About).
fn update_card(p: &Palette, s: &Settings) -> AnyElement {
    use crate::installer::State;
    let state = crate::installer::state();
    let text = match &state {
        State::NotInstalled => t!("Bu kopya kurulum programıyla kurulmadı: güncellemeleri GitHub'dan indirin.").to_string(),
        State::Idle => t!("Güncellemeler GitHub'dan gelir.").to_string(),
        State::Checking => t!("Denetleniyor…").to_string(),
        State::UpToDate => t!("rustyfiles güncel.").to_string(),
        State::Available(v) => format!("{} {v}", t!("Yeni sürüm var:")),
        // (the percent sign where the language puts it: issue 1114, "%85" in a language that writes "85%")
        State::Downloading(v, pct) => format!("{} {v} · {}", t!("İndiriliyor:"), crate::i18n::pct(*pct as f32)),
        State::Ready(v) => format!("{} {v}. {}", t!("İndirildi:"), t!("Yeniden başlatınca uygulanır.")),
        State::Failed(e) => format!("{} {e}", t!("Denetlenemedi:")),
    };
    let control = match state {
        State::NotInstalled => button("upd-web", p, t!("Sürümler sayfası"), |_, _| open_url(RELEASES_URL)),
        State::Ready(_) => button("upd-restart", p, t!("Yeniden başlat ve güncelle"), |_, _| {
            std::thread::spawn(crate::installer::restart_to_update);
        }),
        // (found while "Download updates automatically" is off: downloaded only when asked). Looking again stays possible: a newer
        // release may have come out since (discussion 675: the card kept offering 1.0.5 while 1.0.6 was out)
        State::Available(_) => h_flex()
            .gap_2()
            .child(button("upd-again", p, t!("Yeniden denetle"), |window, cx| {
                check_updates_now(cx);
                window.refresh();
            }))
            .child(button("upd-download", p, t!("İndir"), |window, cx| {
                download_update_now(cx);
                window.refresh();
            }))
            .into_any_element(),
        State::Checking | State::Downloading(..) => div().into_any_element(),
        _ => button("upd-check", p, t!("Güncellemeleri denetle"), |window, cx| {
            check_updates_now(cx);
            window.refresh();
        }),
    };
    let _ = s;
    let icon = match state {
        State::Available(_) | State::Downloading(..) => L::Download,
        State::Ready(_) => L::CircleCheck,
        _ => L::RefreshCw,
    };
    // behind the row: a light sweeping while checking, a bar filling while downloading, full when done
    let tint = p.accent;
    let layer = match state {
        // The sweep runs at the display's rate: drawn at the slow redraw's pace it stuttered at about 5 frames a second (user,
        // 2026-12-04). It asks for frames only while the card is on screen.
        State::Checking => Some(
            glow(tint, 0.22)
                .w(relative(0.3))
                .with_animation(
                    "upd-sweep",
                    Animation::new(std::time::Duration::from_millis(1200)).repeat().with_easing(ease_in_out),
                    |el, t| el.left(relative(-0.3 + 1.3 * t)),
                )
                .into_any_element(),
        ),
        State::Downloading(_, pct) => Some(
            div()
                .absolute()
                .top_0()
                .bottom_0()
                .left_0()
                .w(relative(pct as f32 / 100.0))
                .overflow_hidden()
                .bg(tint.opacity(0.18))
                .child(
                    // a soft highlight running along the filled part, at the display's rate: it asks for frames only while the card
                    // is on screen (a hidden or closed Settings window draws nothing)
                    glow(tint, 0.2).w(px(120.)).with_animation(
                        "upd-run",
                        Animation::new(std::time::Duration::from_millis(1000)).repeat(),
                        |el, t| el.left(relative(-0.2 + 1.2 * t)),
                    ),
                )
                .into_any_element(),
        ),
        State::Ready(_) => Some(div().absolute().inset_0().bg(tint.opacity(0.14)).into_any_element()),
        _ => None,
    };
    shell(p)
        .relative()
        .overflow_hidden()
        .when(matches!(state, State::Ready(_)), |d| d.border_color(tint.opacity(0.6)))
        .children(layer)
        .child(card_body(p, icon, t!("Güncellemeler").into(), Some(text.into()), Some(control)))
        .into_any_element()
}

/// A soft band of light: transparent at both edges, `alpha` in the middle.
fn glow(c: Hsla, alpha: f32) -> Div {
    let half = |from: f32, to: f32| {
        div().flex_1().h_full().bg(linear_gradient(90., linear_color_stop(c.opacity(from), 0.), linear_color_stop(c.opacity(to), 1.)))
    };
    div().absolute().top_0().bottom_0().flex().child(half(0., alpha)).child(half(alpha, 0.))
}

/// "Check for updates": runs off the UI thread and redraws while it checks, and downloads what it finds only while "Download
/// updates automatically" is on (off: the card offers a Download button, `installer::check`).
pub(crate) fn check_updates_now(cx: &mut App) {
    // (the beta switch as it is now: the check itself runs off this thread)
    crate::installer::set_beta_updates(cx.global::<Settings>().beta_updates);
    let download = cx.global::<Settings>().auto_update;
    cx.spawn(async move |cx| {
        let run = cx.background_executor().spawn(async move { crate::installer::check(download) });
        crate::installer::redraw_while_busy(cx).await;
        run.await;
        cx.update(|cx| cx.refresh_windows());
    })
    .detach();
}

/// The card's Download button: the update the check found is downloaded now, off the UI thread.
fn download_update_now(cx: &mut App) {
    cx.spawn(async move |cx| {
        let run = cx.background_executor().spawn(async { crate::installer::download_available() });
        crate::installer::redraw_while_busy(cx).await;
        run.await;
        cx.update(|cx| cx.refresh_windows());
    })
    .detach();
}

const REPO_URL: &str = "https://github.com/gelenmedya/rustyfiles";
const SITE_URL: &str = "https://rustyfiles.com";
const DISCORD_URL: &str = "https://discord.gg/K2banZ36zJ";
const ISSUES_URL: &str = "https://github.com/gelenmedya/rustyfiles/issues/new";
const RELEASES_URL: &str = "https://github.com/gelenmedya/rustyfiles/releases";

/// The About page's top: the logo beside the name (the brand wordmark, as on rustyfiles.com and the speed test card), drawn once per
/// theme at twice its size so it stays sharp up to 200 % scaling.
fn about_wordmark(p: &Palette) -> AnyElement {
    use std::sync::{Arc, Mutex};
    static DRAWN: Mutex<[Option<Arc<gpui_kit::RenderImage>>; 2]> = Mutex::new([None, None]);
    const HEIGHT: f32 = 44.0;
    let ink = if p.dark { crate::brand::WORDMARK_INK } else { "#1b1a1f" };
    let image = {
        let mut drawn = DRAWN.lock().unwrap_or_else(|e| e.into_inner());
        let slot = &mut drawn[p.dark as usize];
        if slot.is_none() {
            *slot = crate::brand::wordmark_image((HEIGHT * 2.0) as u32, ink);
        }
        slot.clone()
    };
    let Some(image) = image else { return div().into_any_element() };
    div()
        .px_1()
        .pt_2()
        .pb_3()
        .child(gpui_kit::img(image).h(px(HEIGHT)).w(px(HEIGHT * crate::brand::wordmark_aspect())))
        .into_any_element()
}

fn about(p: &Palette, cx: &mut App) -> Vec<AnyElement> {
    let ver = crate::installer::version_full();
    let version = format!("{} {ver}", t!("Sürüm:"));
    let pp = *p;
    let s = cx.global::<Settings>().clone();
    vec![
        about_wordmark(p),
        card(
            p,
            L::FolderOpen,
            "rustyfiles",
            Some(&version),
            button("copy-ver", p, t!("Kopyala"), move |_, cx| cx.write_to_clipboard(ClipboardItem::new_string(format!("rustyfiles {ver}")))),
        ),
        update_card(p, &s),
        card(
            p,
            L::Download,
            t!("Güncellemeleri kendiliğinden indir"),
            Some(t!("Arka planda denetlenir ve indirilir; bir sonraki açılışta uygulanır.")),
            sw("auto-upd", p, s.auto_update, |s, v| s.auto_update = v),
        ),
        card(
            p,
            L::Sparkles,
            t!("Beta sürümlerini de al"),
            Some(if crate::installer::is_beta(env!("CARGO_PKG_VERSION")) && !s.beta_updates {
                t!("Bu kopya bir beta sürümüdür: anahtar kapalıyken de sonraki betaları alır, kararlı sürüm çıkınca ona geçer.")
            } else {
                t!("Yayınlanmadan önce denenen sürümler: yenilikler erken gelir, hatalar da olabilir. Kapalıyken yalnızca kararlı sürümler indirilir.")
            }),
            sw("beta-upd", p, s.beta_updates, |s, v| s.beta_updates = v),
        ),
        section(p, "GitHub"),
        link_row(p, "gh-star", L::Star, t!("GitHub'da yıldız ver"), Some(t!("rustyfiles işinize yarıyorsa başkalarının da bulmasına yardım eder.")), |_, _| open_url(REPO_URL)),
        link_row(p, "coffee", L::Coffee, t!("Geliştiriciye bir kahve ısmarla"), Some(t!("rustyfiles'ı tek başıma geliştiriyorum; her destek, devam etmeme yardım eder.")), |_, _| open_url(crate::installer::DONATE)),
        link_row(p, "gh-issue", L::MessageSquare, t!("Hata bildir ya da öneride bulun"), None, |_, _| open_url(ISSUES_URL)),
        link_row(p, "gh-notes", L::ScrollText, t!("Sürüm notları"), None, |_, _| open_url(RELEASES_URL)),
        section(p, t!("Topluluk")),
        link_row(p, "site", L::Globe, t!("Web sitesi"), Some("rustyfiles.com"), |_, _| open_url(SITE_URL)),
        link_row(p, "discord", L::Users, t!("Discord sunucusu"), Some(t!("Soru sor, fikir paylaş, yeni sürümlerden haberdar ol.")), |_, _| open_url(DISCORD_URL)),
        div()
            .px_1()
            .text_xs()
            .text_color(p.text_secondary)
            .child(t!("Rust + GPUI ile yazılmış, hiç donmayan hafif dosya yöneticisi."))
            .into_any_element(),
        section(p, t!("Yardım ve destek")),
        link_row(p, "open-log", L::FolderOpen, t!("Kayıt ve ayar klasörünü aç"), settings::app_dir().map(|d| d.display().to_string()).as_deref(), |_, _| {
            if let Some(d) = settings::app_dir() {
                std::thread::spawn(move || {
                    rf_win::explorer_catch::quiet_for(std::time::Duration::from_secs(5));
                    let _ = std::process::Command::new("explorer.exe").arg(d).spawn();
                });
            }
        }),
        section(p, t!("Açık kaynak")),
        link_row(
            p,
            "icons8-credit",
            L::Image,
            "Icons8",
            Some("icons8.com"),
            |_, _| open_url("https://icons8.com/icon/Ey9jEx96rxU0/undo"),
        ),
        expander(
            "libs",
            p,
            L::Library,
            t!("Üçüncü taraf kütüphaneler"),
            None,
            None,
            move || {
                [
                    ("GPUI", "Apache-2.0"),
                    ("gpui-kit", "Apache-2.0"),
                    ("Velopack", "MIT"),
                    ("windows-rs", "MIT / Apache-2.0"),
                    ("Lucide icons", "ISC"),
                    ("zip, sevenz-rust2, tar, flate2, zstd", "MIT / Apache-2.0"),
                    ("notify", "CC0 / Artistic-2.0"),
                    ("chrono, serde, toml", "MIT / Apache-2.0"),
                ]
                .iter()
                .map(|(n, l)| sub(&pp, n, Some(l), div().into_any_element()))
                .collect()
            },
            cx,
        ),
    ]
}

/// Shows or hides a section of the Home page (`Settings::home_hidden`).
fn show_home_section(s: &mut Settings, key: &str, show: bool) {
    s.home_hidden.retain(|h| h != key);
    if !show {
        s.home_hidden.push(key.to_string());
    }
}

/// Shows or hides a sidebar section (`Settings::sidebar_hidden`).
fn show_section(s: &mut Settings, key: &str, show: bool) {
    s.sidebar_hidden.retain(|h| h != key);
    if !show {
        s.sidebar_hidden.push(key.to_string());
    }
}

enum PickTarget {
    BackgroundImage,
    Ide,
    Export,
    Import,
    Terminal,
    TextEditor,
    Git,
}

/// Runs a Windows file dialog on the shell thread and applies the result.
fn pick_into(_window: &mut Window, cx: &mut App, title: &str, target: PickTarget) {
    let title = title.to_string();
    let (tx, rx) = futures::channel::oneshot::channel::<Option<std::path::PathBuf>>();
    let images = [(t!("Resimler"), "*.png;*.jpg;*.jpeg;*.webp;*.bmp;*.gif")];
    let exe = [(t!("Programlar"), "*.exe;*.cmd;*.bat")];
    let toml = [(t!("Ayar dosyası"), "*.toml")];
    let (images, exe, toml) = (
        images.map(|(a, b)| (a.to_string(), b.to_string())),
        exe.map(|(a, b)| (a.to_string(), b.to_string())),
        toml.map(|(a, b)| (a.to_string(), b.to_string())),
    );
    let kind = match target {
        PickTarget::BackgroundImage => 0,
        PickTarget::Ide => 1,
        PickTarget::Export => 2,
        PickTarget::Import => 3,
        PickTarget::Terminal => 4,
        PickTarget::TextEditor => 5,
        PickTarget::Git => 6,
    };
    rf_win::sta::run(move |owner| {
        use rf_win::dialogs::{Pick, pick};
        fn f(v: &[(String, String)]) -> Vec<(&str, &str)> {
            v.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect()
        }
        let r = match kind {
            0 => pick(owner, &title, Pick::File { filters: &f(&images) }),
            1 | 4 | 5 | 6 => pick(owner, &title, Pick::File { filters: &f(&exe) }),
            2 => pick(owner, &title, Pick::Save { filters: &f(&toml), default_name: "rustyfiles-ayarlar.toml" }),
            _ => pick(owner, &title, Pick::File { filters: &f(&toml) }),
        };
        let _ = tx.send(r);
    });
    cx.spawn(async move |cx| {
        let Ok(Some(path)) = rx.await else { return };
        let _ = cx.update(|cx| match kind {
            0 => settings::update(cx, |s| s.background_image = Some(path)),
            1 => settings::update(cx, |s| s.ide_path = path.display().to_string()),
            4 => settings::update(cx, |s| s.terminal_path = path.display().to_string()),
            5 => settings::update(cx, |s| s.text_editor_path = path.display().to_string()),
            6 => {
                let program = path.display().to_string();
                rf_win::git_program::forget(&program);
                settings::update(cx, |s| s.git_path = program)
            }
            2 => {
                let s = cx.global::<Settings>().clone();
                // (the Open / Save dialog choice is in the registry, and profile paths name this PC's folders: issue 432)
                let dialogs = rf_win::dialog_reg::is_enabled(rf_win::dialog_reg::CLASSES);
                std::thread::spawn(move || {
                    let table = toml::Table::try_from(&s).unwrap_or_default();
                    if let Ok(text) = crate::settings_transfer::export_text(&table, dialogs, &crate::settings_transfer::profile()) {
                        let _ = std::fs::write(&path, text);
                    }
                });
            }
            _ => {
                let read = std::fs::read_to_string(&path)
                    .ok()
                    .and_then(|t| crate::settings_transfer::import_text(t.trim_start_matches('\u{feff}'), &crate::settings_transfer::profile()).ok());
                if let Some((text, dialogs)) = read {
                    // Programs the file would have rustyfiles start, and the Open / Save dialog registration, are asked about first:
                    // a settings file may come from someone else (a private security report).
                    let classes = rf_win::dialog_reg::CLASSES;
                    let current = toml::Table::try_from(cx.global::<Settings>()).unwrap_or_default();
                    let imported: toml::Table = toml::from_str(&text).unwrap_or_default();
                    let programs = crate::settings_transfer::changed_programs(&imported, &current);
                    let dialogs_on = dialogs == Some(true) && !rf_win::dialog_reg::is_enabled(classes);
                    if programs.is_empty() && !dialogs_on {
                        crate::settings_transfer::apply_import(text, dialogs, true, cx);
                        return;
                    }
                    let Some(window) = cx.active_window() else { return };
                    let mut what: Vec<String> = programs.iter().map(|k| program_key_name(k).to_string()).collect();
                    if dialogs_on {
                        what.push(t!("rustyfiles'ın Aç / Kaydet pencereleri").to_string());
                    }
                    let message = format!("{}\n\n• {}", t!("Bu dosya rustyfiles'ın çalıştıracağı programları da değiştiriyor. Yalnızca dosyaya güveniyorsan al:"), what.join("\n• "));
                    let asked = window.update(cx, |_, window, cx| {
                        crate::prompt::pick_rich(
                            t!("Ayarları içe aktar"),
                            message,
                            None,
                            vec![
                                (t!("Bunları da al").into(), crate::prompt::Kind::Normal),
                                (t!("Benimkiler kalsın").into(), crate::prompt::Kind::Primary),
                                (t!("İptal").into(), crate::prompt::Kind::Normal),
                            ],
                            window,
                            cx,
                        )
                    });
                    if let Ok(rx) = asked {
                        cx.spawn(async move |cx| {
                            let take = match rx.await {
                                Ok(0) => true,
                                Ok(1) => false,
                                _ => return,
                            };
                            cx.update(|cx| crate::settings_transfer::apply_import(text, dialogs, take, cx));
                        })
                        .detach();
                    }
                }
            }
        });
    })
    .detach();
}

/// What the import question calls a key of [`crate::settings_transfer::PROGRAM_KEYS`].
fn program_key_name(key: &str) -> &'static str {
    match key {
        "git_path" => t!("Git programı"),
        "ide_path" => t!("Kod düzenleyici"),
        "terminal_path" => t!("Terminal"),
        "text_editor_path" => t!("Metin düzenleyici"),
        "open_rules" => t!("Dosya türlerinin açıldığı programlar"),
        "toolbar_commands" => t!("Özel komutlar"),
        "app_icon" => t!("Uygulama simgesi"),
        _ => t!("Tema klasörü"),
    }
}

/// The drives to pick from for the drives-to-index card (issue 736), read off the UI thread like
/// the editors are: a network drive whose server is away answers slowly. With them, the letters
/// the automatic set would index with and without hard drives, so the card can draw every drive
/// with its switch already right. Refreshed while the page is open: a drive plugged in
/// meanwhile shows up.
type DrivePick = (Vec<rf_win::drives::Drive>, Vec<String>, Vec<String>, Vec<rf_win::syncroots::SyncRoot>);

fn drive_pick(cx: &mut App) -> DrivePick {
    static PICK: parking_lot::Mutex<Option<(std::time::Instant, DrivePick)>> = parking_lot::Mutex::new(None);
    static LOOKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
    let fresh = PICK.lock().as_ref().is_some_and(|(at, _)| at.elapsed() < std::time::Duration::from_secs(60));
    if !fresh && !LOOKING.swap(true, std::sync::atomic::Ordering::Relaxed) {
        cx.spawn(async move |cx| {
            let pick = cx
                .background_executor()
                .spawn(async {
                    let drives = rf_win::drives::list_drives();
                    let letters = |roots: Vec<std::path::PathBuf>| {
                        roots.iter().filter_map(|r| r.to_string_lossy().chars().next().map(|c| c.to_ascii_uppercase().to_string())).collect::<Vec<_>>()
                    };
                    (drives, letters(rf_win::indexer::local_roots(false)), letters(rf_win::indexer::local_roots(true)), rf_win::syncroots::list())
                })
                .await;
            *PICK.lock() = Some((std::time::Instant::now(), pick));
            LOOKING.store(false, std::sync::atomic::Ordering::Relaxed);
            let _ = cx.update(|cx| cx.refresh_windows());
        })
        .detach();
    }
    PICK.lock().as_ref().map(|(_, d)| d.clone()).unwrap_or_else(|| (Vec::new(), Vec::new(), Vec::new(), Vec::new()))
}

/// The drives of the name index, one switch each (issue 736). Toggling one freezes the automatic
/// set into the list of drives to index, so a drive that appears later is not indexed unasked —
/// and a network drive (SMB share) only ever is when it was picked here.
fn index_drives_card(p: &Palette, s: &Settings, cx: &mut App) -> AnyElement {
    let (drives, auto_soft, auto_hard, clouds) = drive_pick(cx);
    let auto: HashSet<String> = if s.index_hard_drives { auto_hard } else { auto_soft }.into_iter().collect();
    let mut rows = v_flex().py_1();
    for d in drives {
        let letter = d.letter.to_ascii_uppercase().to_string();
        let on = s.index_drives.iter().any(|l| l.eq_ignore_ascii_case(&letter)) || (s.index_drives.is_empty() && auto.contains(&letter));
        let (auto_at_click, letter_at_click) = (auto.iter().cloned().collect::<Vec<String>>(), letter.clone());
        rows = rows.child(
            h_flex()
                .min_h(px(40.))
                .pl(px(56.))
                .pr_4()
                .gap_3()
                .items_center()
                .child(Icon::new(if d.kind == rf_win::drives::DriveKind::Network { L::Network } else { L::HardDrive }).size(px(14.)).text_color(p.text_secondary))
                .child(div().flex_1().min_w_0().text_sm().text_ellipsis().overflow_hidden().whitespace_nowrap().child(d.display_name()))
                .child(switch(
                    ElementId::Name(SharedString::from(format!("idx-drive-{letter}"))),
                    p,
                    on,
                    move |_, cx| {
                        let (auto_at_click, letter) = (auto_at_click.clone(), letter_at_click.clone());
                        settings::update(cx, |s| {
                            let mut list: Vec<String> = if s.index_drives.is_empty() { auto_at_click } else { s.index_drives.clone() };
                            if list.iter().any(|l| l.eq_ignore_ascii_case(&letter)) {
                                list.retain(|l| !l.eq_ignore_ascii_case(&letter));
                            } else {
                                list.push(letter);
                                list.sort_by_key(|l| l.to_ascii_uppercase());
                            }
                            s.index_drives = list;
                        });
                    },
                )),
        );
    }
    // the cloud sync folders (OneDrive, Proton Drive, …): their directories are reparse points
    // the walk now enters, so a folder not picked here is left out of its drive's walk like an
    // excluded folder — the switch holds either way (issue 885)
    if !clouds.is_empty() {
        rows = rows
            .child(div().h(px(1.)).bg(p.divider))
            .child(
                h_flex()
                    .min_h(px(36.))
                    .pl(px(56.))
                    .pr_4()
                    .gap_2()
                    .items_center()
                    .child(Icon::new(L::Cloud).size(px(14.)).text_color(p.text_secondary))
                    .child(
                        v_flex()
                            .child(div().text_sm().child(t!("Bulut klasörleri")))
                            .child(div().text_xs().text_color(p.text_secondary).child(t!("OneDrive ve benzeri bulut klasörleri buradan seçilir: seçilen klasörün kendi dizini tutulur, seçilmeyen disk taranırken atlanır."))),
                    ),
            );
        for r in clouds {
            let path = r.path.to_string_lossy().trim_end_matches('\\').to_string();
            let on = s.index_clouds.iter().any(|c| c.eq_ignore_ascii_case(&path));
            let picked = path.clone();
            rows = rows.child(
                h_flex()
                    .min_h(px(40.))
                    .pl(px(56.))
                    .pr_4()
                    .gap_3()
                    .items_center()
                    .child(Icon::new(L::Cloud).size(px(14.)).text_color(p.text_secondary))
                    .child(div().flex_1().min_w_0().text_sm().text_ellipsis().overflow_hidden().whitespace_nowrap().child(if r.name.is_empty() { path.clone() } else { r.name }))
                    .child(switch(
                        ElementId::Name(SharedString::from(format!("idx-cloud-{path}"))),
                        p,
                        on,
                        move |_, cx| {
                            let picked = picked.clone();
                            settings::update(cx, |s| {
                                if s.index_clouds.iter().any(|c| c.eq_ignore_ascii_case(&picked)) {
                                    s.index_clouds.retain(|c| !c.eq_ignore_ascii_case(&picked));
                                } else {
                                    s.index_clouds.push(picked);
                                }
                            });
                        },
                    )),
            );
        }
    }
    card(
        p,
        L::Network,
        t!("Dizine alınacak sürücüler"),
        Some(t!("Ağ sürücüleri (SMB paylaşımları) buradan seçilirse dizine alınır: değişiklikler izlenir ve dizin arada bir yeniden taranır. Bulut klasörleri (OneDrive ve benzeri) de buradan seçilir. Hiçbir sürücü seçilmemişse yerel diskler otomatik dizine alınır.")),
        rows.into_any_element(),
    )
}

/// "Local drives' file names are kept in an index … · C:\ 2.1 million entries, 84 MB · E:\ indexing…"
fn name_index_status() -> String {
    let mut s = t!("Yerel sürücülerdeki dosya adları bir dizinde tutulur: alt klasörlerde arama milisaniyeler sürer. Dizin arka planda hazırlanır ve güncel tutulur.").to_string();
    let parts: Vec<String> = rf_win::indexer::status()
        .into_iter()
        .map(|(root, state, live, mem)| {
            let r = root.to_string_lossy().trim_end_matches('\\').to_string();
            match state {
                rf_win::indexer::State::Building => format!("{r} {}", t!("hazırlanıyor…")),
                rf_win::indexer::State::Failed => format!("{r} {}", t!("dizinlenemedi")),
                rf_win::indexer::State::Ready => {
                    t!("{root} {n} öğe, {mb} MB").replace("{root}", &r).replace("{n}", &crate::bench_view::count(live as u64)).replace("{mb}", &(mem >> 20).to_string())
                }
            }
        })
        .collect();
    if !parts.is_empty() {
        s.push_str(" · ");
        s.push_str(&parts.join(" · "));
    }
    s
}

/// The folders left out of the search index: the user's (removable) and the built-in ones.
fn index_exclusions(p: &Palette, s: &Settings) -> AnyElement {
    let mut list = v_flex().py_1();
    for (i, dir) in s.index_excluded.iter().enumerate() {
        let d = dir.clone();
        list = list.child(
            h_flex()
                .min_h(px(40.))
                .pl(px(56.))
                .pr_4()
                .gap_3()
                .items_center()
                .child(Icon::new(L::FolderX).size(px(14.)).text_color(p.text_secondary))
                .child(div().flex_1().min_w_0().text_sm().text_ellipsis().overflow_hidden().whitespace_nowrap().child(dir.clone()))
                .child(
                    div()
                        .id(("idx-excl-rm", i))
                        .p_1()
                        .rounded(theme::RADIUS_SM)
                        .hover(|st| st.bg(p.pressed))
                        .child(Icon::new(L::X).size(px(14.)).text_color(p.text_secondary))
                        .on_click(move |_, _, cx| {
                            let d = d.clone();
                            settings::update(cx, |s| s.index_excluded.retain(|e| *e != d));
                        }),
                ),
        );
    }
    let defaults = rf_win::nameindex::default_excluded_names().join(", ");
    shell(p)
        .child(
            h_flex()
                .min_h(px(48.))
                .pl(px(56.))
                .pr_4()
                .py_2()
                .gap_4()
                .items_center()
                .child(
                    v_flex()
                        .flex_1()
                        .min_w_0()
                        .child(div().text_sm().child(t!("Dizine alınmayan klasörler")))
                        .child(div().text_xs().text_color(p.text_secondary).child(format!(
                            "{} {defaults}, Windows. {}",
                            t!("Her zaman:"),
                            t!("Bu klasörlerin içinde arama diskte yapılır. Bir klasörü sağ tıklayıp \"Aramada dizine alma\" ile de ekleyebilirsiniz.")
                        ))),
                )
                .child(button("idx-excl-add", p, t!("Klasör ekle…"), |_, cx| {
                    // The dialog runs on the shell thread, never inside this click: its modal loop pumped the window's messages
                    // while the click still held the app, and the next one crashed it (issue 188: "click the Add Folders... Button
                    // ... crashes the App").
                    let (tx, rx) = futures::channel::oneshot::channel::<Option<std::path::PathBuf>>();
                    let title = t!("Dizine alınmayacak klasör").to_string();
                    rf_win::sta::run(move |owner| {
                        let _ = tx.send(rf_win::dialogs::pick(owner, &title, rf_win::dialogs::Pick::Folder));
                    });
                    cx.spawn(async move |cx| {
                        let Ok(Some(dir)) = rx.await else { return };
                        let d = dir.to_string_lossy().trim_end_matches('\\').to_string();
                        cx.update(|cx| {
                            settings::update(cx, |s| {
                                if !s.index_excluded.iter().any(|e| e.eq_ignore_ascii_case(&d)) {
                                    s.index_excluded.push(d);
                                }
                            });
                        });
                    })
                    .detach();
                })),
        )
        .when(!s.index_excluded.is_empty(), |d| d.child(div().h(px(1.)).bg(p.divider)).child(list))
        .into_any_element()
}

#[cfg(test)]
mod search_tests {
    use super::{COLLECT, COLLECT_AT, Found, PAGES, Page, matching};
    use crate::settings::Settings;
    use crate::theme::Palette;

    #[test]
    fn settings_are_found_by_every_word_of_the_query() {
        let f = |title: &str, desc: Option<&str>, page: Page| Found { title: title.into(), desc: desc.map(str::to_string), page, expander: None };
        let all = vec![
            f("Arşivleri klasör gibi aç", Some("ZIP, 7z ve tar dosyaları"), Page::Files),
            f("Önizleme paneli", None, Page::Layout),
            f("Önizleme paneli", None, Page::Layout),
            f("İlerleme çubuğu", None, Page::Appearance),
        ];
        let titles = |q: &str| matching(all.clone(), q).into_iter().map(|f| f.title).collect::<Vec<_>>();
        assert_eq!(titles("arşiv"), vec!["Arşivleri klasör gibi aç"]);
        // a word of the description; every word must be there
        assert_eq!(titles("zip klasör"), vec!["Arşivleri klasör gibi aç"]);
        assert!(titles("zip panel").is_empty());
        // the same setting drawn twice is one result; the Turkish İ folds
        assert_eq!(titles("ÖNİZLEME"), vec!["Önizleme paneli"]);
        assert_eq!(titles("ilerleme"), vec!["İlerleme çubuğu"]);
        assert!(titles("   ").is_empty());
    }

    #[test]
    fn sidebar_rail_setting_is_searchable_by_rail_and_sidebar() {
        for lang in [crate::i18n::Lang::Tr, crate::i18n::Lang::En] {
            crate::i18n::set(lang);
            let entry = Found {
                title: crate::t!("Kenar çubuğu simge şeridi").into(),
                desc: Some(crate::t!("Açıkken kenar çubuğu dar bir simge şeridine dönüşür ve üstüne gelince açılır. Kenarını sürükleyerek de değiştirebilirsiniz.").into()),
                page: Page::Appearance,
                expander: None,
            };
            for q in ["rail", "sidebar", "icon rail"] {
                assert_eq!(matching(vec![entry.clone()], q).len(), 1, "query {q:?} missed in {lang:?}");
            }
        }
        crate::i18n::set(crate::i18n::Lang::Tr);
    }

    /// Builds the Dock page the way the search does (the builders note their texts) and returns what was noted.
    fn noted_on_the_dock_page(s: &Settings, p: &Palette) -> Vec<Found> {
        COLLECT.with(|c| *c.borrow_mut() = Some(Vec::new()));
        COLLECT_AT.with(|a| a.set((Page::Dock, None)));
        let _ = crate::dock_page::page(p, s, None);
        COLLECT.with(|c| c.borrow_mut().take()).unwrap_or_default()
    }

    #[test]
    fn the_weather_from_position_card_stands_directly_after_the_weather_city_row() {
        crate::dock_page::while_turkish(|| {
            let p = Palette::light();
            let s = Settings { dock_enabled: true, ..Default::default() };
            let titles: Vec<String> = noted_on_the_dock_page(&s, &p).into_iter().map(|f| f.title).collect();
            let city = titles.iter().position(|t| t == "Hava durumu şehri").expect("the city row");
            assert_eq!(titles.get(city + 1).map(String::as_str), Some("Konumumu kullan"), "{titles:?}");
            // and it is in the left island's section, not after the last one: the next row after it is the middle island's first
            assert!(city + 2 < titles.len(), "the page goes on after the card: {titles:?}");
            assert_eq!(titles.iter().filter(|t| *t == "Konumumu kullan").count(), 1);
        });
    }

    #[test]
    fn the_dock_page_follows_the_look_page_and_the_search_finds_every_dock_setting_on_it() {
        crate::dock_page::while_turkish(|| {
            let at = |pg: Page| PAGES.iter().position(|x| x.0 == pg).unwrap();
            assert_eq!(at(Page::Dock), at(Page::Appearance) + 1, "the Dock page comes right after Görünüm");
            for p in [Palette::light(), Palette::dark()] {
                // dock off (the dimmed rows) and on (the live ones): the same texts are noted either way
                for dock_enabled in [false, true] {
                    let s = Settings { dock_enabled, ..Default::default() };
                    let noted = noted_on_the_dock_page(&s, &p);
                    let entries = crate::dock_page::entries();
                    // (the weather-from-position card stands right after the weather city's row, inside the page, and notes its texts too)
                    // (and the card of the right island's own buttons, at the end of the right island's section: one more)
                    // (and the card of what our control centre shows, right under that switch: one more)
                    let extra = crate::dock::weather_card::cards(&p, &s).len() + 2;
                    assert_eq!(noted.len(), entries.len() + extra, "one card per entry, none dropped and none twice");
                    assert_eq!(noted.last().map(|f| f.title.as_str()), Some("Durum simgeleri"), "the buttons' card closes the page");
                    for e in &entries {
                        // searched by its own title, and by a word of its description, it is found and opens the Dock page
                        let hits = matching(noted.clone(), e.title);
                        assert!(hits.iter().any(|f| f.title == e.title && f.page == Page::Dock), "{} is not found by its title", e.field);
                        if let Some(d) = e.desc {
                            let word = d.split_whitespace().find(|w| w.chars().count() > 6).unwrap_or(d);
                            assert!(matching(noted.clone(), word).iter().any(|f| f.title == e.title), "{} is not found by `{word}`", e.field);
                        }
                    }
                    assert!(noted.iter().all(|f| f.page == Page::Dock));
                }
            }
        });
    }
}

#[cfg(test)]
mod desktop_page_tests {
    use super::{COLLECT, COLLECT_AT, Found, PAGES, Page, experimental, matching, page_title};
    use crate::settings::Settings;
    use crate::theme::Palette;

    fn noted_on_the_desktop_page(s: &Settings, p: &Palette) -> Vec<Found> {
        COLLECT.with(|c| *c.borrow_mut() = Some(Vec::new()));
        COLLECT_AT.with(|a| a.set((Page::Desktop, None)));
        let _ = crate::desktop_page::page(p, s);
        COLLECT.with(|c| c.borrow_mut().take()).unwrap_or_default()
    }

    #[test]
    fn the_desktop_page_follows_the_dock_page_and_the_search_finds_every_desktop_setting_on_it() {
        crate::dock_page::while_turkish(|| {
            let at = |pg: Page| PAGES.iter().position(|x| x.0 == pg).unwrap();
            assert_eq!(at(Page::Desktop), at(Page::Dock) + 1, "the Masaüstü page comes right after Dock");
            for p in [Palette::light(), Palette::dark()] {
                for dock_enabled in [false, true] {
                    let s = Settings { dock_enabled, ..Default::default() };
                    let noted = noted_on_the_desktop_page(&s, &p);
                    let entries = crate::desktop_page::entries();
                    assert_eq!(noted.len(), entries.len(), "one card per entry, none dropped and none twice");
                    for e in &entries {
                        let hits = matching(noted.clone(), e.title);
                        assert!(hits.iter().any(|f| f.title == e.title && f.page == Page::Desktop), "{} is not found by its title", e.field);
                    }
                }
            }
        });
    }

    #[test]
    fn the_experimental_pages_are_marked_and_the_mark_is_not_part_of_their_names() {
        crate::dock_page::while_turkish(|| {
            let exp: Vec<Page> = PAGES.iter().map(|x| x.0).filter(|p| experimental(*p)).collect();
            assert_eq!(exp, [Page::Ferry], "exactly these (the Dock and the desktop are no longer experimental)");
            for (page, _, name) in PAGES {
                let title = page_title(page, name);
                if experimental(page) {
                    assert!(title.starts_with(name) && title.ends_with("(deneysel)"), "{title}");
                    assert!(!name.contains("eney"), "the name in the list stays plain so the search and the translation find it: {name}");
                } else {
                    assert_eq!(title, name, "a page that is not experimental is not marked");
                }
            }
            // the mark and the title word have their English pair
            let en: std::collections::HashSet<&str> = crate::i18n_en::EN.iter().map(|(k, _)| *k).collect();
            assert!(en.contains("Deneysel") && en.contains("deneysel"));
            assert!(en.contains("Masaüstü"));
        });
    }

    /// The text of the function that starts with `signature`, from its opening brace to the matching closing one (string literals are
    /// skipped, so a brace inside a text does not count). The page's own braces end it, not a marker comment that may be moved.
    fn fn_body<'a>(src: &'a str, signature: &str) -> &'a str {
        let start = src.find(signature).unwrap_or_else(|| panic!("{signature} is not in the file any more"));
        let open = start + src[start..].find('{').expect("a body");
        let (mut depth, mut in_str, mut esc) = (0usize, false, false);
        for (i, c) in src[open..].char_indices() {
            if in_str {
                match (esc, c) {
                    (true, _) => esc = false,
                    (false, '\\') => esc = true,
                    (false, '"') => in_str = false,
                    _ => {}
                }
                continue;
            }
            match c {
                '"' => in_str = true,
                '{' => depth += 1,
                '}' => {
                    depth -= 1;
                    if depth == 0 {
                        return &src[open..open + i + 1];
                    }
                }
                _ => {}
            }
        }
        panic!("{signature} has no closing brace");
    }

    #[test]
    fn the_body_finder_stops_at_the_functions_own_closing_brace() {
        let src = "fn a() { let s = \"}{\"; if x { y } }
fn b() { z }";
        assert_eq!(fn_body(src, "fn a("), "{ let s = \"}{\"; if x { y } }");
        assert_eq!(fn_body(src, "fn b("), "{ z }");
    }

    #[test]
    fn nothing_of_the_dock_or_the_desktop_is_on_the_developer_or_advanced_page() {
        // the pages' builders live in this file: their source must not read or write a dock_*, shell_* (but shell_submenu) or desktop_* field
        let src = include_str!("settings_view.rs");
        let dev = fn_body(src, "fn dev(p: &Palette");
        let adv = fn_body(src, "fn advanced(p: &Palette");
        // (a finder that found the wrong text would let anything through: both pages are long and are made of rows)
        assert!(dev.len() > 300 && adv.len() > 300, "{} {}", dev.len(), adv.len());
        for (name, body) in [("dev", dev), ("advanced", adv)] {
            for needle in [".dock_", ".shell_desktop", ".shell_win", ".shell_own", ".shell_tray", ".shell_hide", ".desktop_"] {
                assert!(!body.contains(needle), "{name} page still touches {needle}");
            }
        }
    }
}

#[cfg(test)]
mod hyperglass_tests {
    use super::{Hg, SLIDER_W, THUMB, slider_key, slider_value_at};
    use crate::settings::Settings;

    /// The list of pages gives way before the settings do: in a narrow pane it is a strip of icons, and the settings' column is
    /// then wide enough for a setting's words and its widest control side by side or one under the other.
    #[test]
    fn only_a_drives_root_has_a_drive_letter() {
        use std::path::Path;
        assert_eq!(super::drive_letter(Path::new(r"V:\")), Some('V'));
        assert_eq!(super::drive_letter(Path::new("c:")), Some('C'));
        assert_eq!(super::drive_letter(Path::new("D:/")), Some('D'));
        for other in [r"C:\Users", r"\\server\share", "", "C", r"1:\", r"C:\\"] {
            assert_eq!(super::drive_letter(Path::new(other)), None, "{other:?}");
        }
    }

    #[test]
    fn hiding_and_showing_a_drive_keeps_the_letters_once_and_in_order() {
        let mut s = crate::settings::Settings::default();
        super::set_drive_hidden(&mut s, 'v', true);
        super::set_drive_hidden(&mut s, 'D', true);
        super::set_drive_hidden(&mut s, 'V', true);
        assert_eq!(s.hidden_drives, ["D", "V"]);
        super::set_drive_hidden(&mut s, 'd', false);
        assert_eq!(s.hidden_drives, ["V"]);
        super::set_drive_hidden(&mut s, 'Z', false);
        super::set_drive_hidden(&mut s, '1', true);
        assert_eq!(s.hidden_drives, ["V"], "a drive that was not hidden, and what is no drive, change nothing");
        // a list written by hand is cleaned the first time it is changed
        s.hidden_drives = vec!["v:".into(), "x".into(), "V".into(), "?".into()];
        super::set_drive_hidden(&mut s, 'A', true);
        assert_eq!(s.hidden_drives, ["A", "V", "X"]);
    }

    #[test]
    fn a_colour_of_the_users_own_is_kept_as_rrggbb_or_refused_with_words() {
        assert_eq!(super::accent_answer("f7630c"), Ok("#F7630C".to_string()));
        assert_eq!(super::accent_answer(" #abc "), Ok("#AABBCC".to_string()));
        assert!(super::accent_answer("turuncu").is_err());
        assert!(super::accent_answer("").is_err());
        // every colour that is offered is a colour, and none is offered twice
        let unique: std::collections::HashSet<u32> = super::ACCENT_CHOICES.into_iter().collect();
        assert_eq!(unique.len(), super::ACCENT_CHOICES.len());
        assert!(super::ACCENT_CHOICES.iter().all(|c| *c <= 0xFF_FFFF));
    }

    #[test]
    fn a_narrow_pane_gets_the_strip_of_icons_and_a_readable_column() {
        assert!(!super::nav_is_strip(0.0), "a pane that was not measured yet gets the full list");
        assert!(super::nav_is_strip(480.0), "the narrowest window with the app's sidebar open");
        assert!(super::nav_is_strip(super::NAV_STRIP_BELOW - 1.0));
        assert!(!super::nav_is_strip(super::NAV_STRIP_BELOW));
        assert!(!super::nav_is_strip(1200.0));
        // the settings' column with the strip, in the narrowest pane the app's window allows (480): room for a list of the widest
        // kind (320) on a line of its own inside a card's padding, and for the words at their narrowest
        let column = 480.0 - super::NAV_STRIP_W - 48.0;
        assert!(column - 32.0 >= 320.0, "{column}");
        assert!(column - 32.0 >= super::WORDS_MIN + 34.0);
        // and with the full list just above the limit the column is no narrower than that
        assert!(super::NAV_STRIP_BELOW - super::NAV_W - 48.0 >= column - 16.0);
    }

    #[test]
    fn the_thumbs_travel_maps_to_0_through_100() {
        // a slider at x = 100: the thumb's centre runs from 100 + 9 to 100 + 220 - 9 (the classic round thumb), or from + 11 (the liquid one)
        for thumb in [THUMB, crate::liquid::SL_REST_W] {
            let at = |x: f32| slider_value_at(x, 100.0, SLIDER_W, thumb);
            assert_eq!(at(100.0), 0, "left of the track");
            assert_eq!(at(100.0 + thumb / 2.0), 0);
            assert_eq!(at(100.0 + SLIDER_W - thumb / 2.0), 100);
            assert_eq!(at(100.0 + SLIDER_W + 500.0), 100, "far right of the track, as a drag goes on past the end");
            assert_eq!(at(-300.0), 0);
            let mid = at(100.0 + SLIDER_W / 2.0);
            assert_eq!(mid, 50, "the middle of the track is the middle of the range");
            // the thumb drawn for a value is under the pointer that gave it
            for v in [0u8, 1, 37, 52, 99, 100] {
                let centre = 100.0 + f32::from(v) / 100.0 * (SLIDER_W - thumb) + thumb / 2.0;
                assert_eq!(at(centre), v);
            }
        }
        // the liquid thumb's drawn centre (liquid::slider_centre) is the pointer position that gives the value; it grows about its
        // centre while it is held, so the mapping always uses the resting width
        for v in 0..=100u8 {
            let centre = 100.0 + crate::liquid::slider_centre(SLIDER_W, f32::from(v) / 100.0);
            assert_eq!(slider_value_at(centre, 100.0, SLIDER_W, crate::liquid::SL_REST_W), v);
        }
        // a box too small to hold the thumb does not divide by zero
        assert_eq!(slider_value_at(5.0, 0.0, 0.0, THUMB), 0);
    }

    #[test]
    fn keys_move_a_slider_by_one_ten_or_to_an_end() {
        assert_eq!(slider_key(50, "right", false), Some(51));
        assert_eq!(slider_key(50, "up", false), Some(51));
        assert_eq!(slider_key(50, "left", false), Some(49));
        assert_eq!(slider_key(50, "down", false), Some(49));
        assert_eq!(slider_key(50, "right", true), Some(60));
        assert_eq!(slider_key(50, "left", true), Some(40));
        assert_eq!(slider_key(50, "pageup", false), Some(60));
        assert_eq!(slider_key(50, "pagedown", false), Some(40));
        assert_eq!(slider_key(50, "home", false), Some(0));
        assert_eq!(slider_key(50, "end", false), Some(100));
        // at the ends they stay (and are still taken, so the file list does not move)
        assert_eq!(slider_key(0, "left", false), Some(0));
        assert_eq!(slider_key(3, "left", true), Some(0));
        assert_eq!(slider_key(100, "right", false), Some(100));
        assert_eq!(slider_key(95, "pageup", false), Some(100));
        // a value the file had out of range counts as 100
        assert_eq!(slider_key(200, "left", false), Some(99));
        // other keys are not the slider's
        assert_eq!(slider_key(50, "a", false), None);
        assert_eq!(slider_key(50, "enter", false), None);
        assert_eq!(slider_key(50, "tab", false), None);
    }

    #[test]
    fn each_slider_reads_and_writes_its_own_setting() {
        let mut s = Settings::default();
        for (i, which) in Hg::ALL.into_iter().enumerate() {
            which.set(&mut s, 10 + i as u8);
        }
        assert_eq!([s.hg_frost, s.hg_tint, s.hg_refraction, s.hg_saturation, s.hg_surface], [10, 11, 12, 13, 14]);
        for (i, which) in Hg::ALL.into_iter().enumerate() {
            assert_eq!(which.get(&s), 10 + i as u8);
            assert_eq!(which as usize, i, "the slider id is the position on the card");
        }
        // a number out of range is cut on both sides
        Hg::Frost.set(&mut s, 250);
        assert_eq!(s.hg_frost, 100);
        s.hg_tint = 180;
        assert_eq!(Hg::Tint.get(&s), 100);
    }

    #[test]
    fn every_label_and_description_is_there() {
        for which in Hg::ALL {
            assert!(!which.title().is_empty() && !which.desc().is_empty());
        }
    }
}

#[cfg(test)]
mod font_tests {
    use super::sort_font_names;

    #[test]
    fn font_names_are_filtered_deduped_and_alphabetical() {
        let names = vec![
            "Tahoma".into(),
            ".SystemUIFont".into(),
            "@Yu Gothic".into(),
            "   ".into(),
            "".into(),
            "arial".into(),
            "Arial".into(),
            "Arial".into(),
            "BIZ UDGothic".into(),
            "游ゴシック".into(),
            "Consolas".into(),
            " @Vertical".into(),
        ];
        assert_eq!(
            sort_font_names(names),
            vec!["Arial", "arial", "BIZ UDGothic", "Consolas", "Tahoma", "游ゴシック"]
        );
    }
}