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.

54.2 KB
Raw Blame
//! Settings → Speed test: runs [`crate::bench`] on a background thread and shows the results:
//! a race played back at real speed (like rustyfiles.com), a table with time, CPU and memory per
//! app, our engines against Windows', then a star request and sharing.

use std::collections::HashSet;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

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 parking_lot::Mutex;
use rf_win::bench::{App as BenchApp, AppKind, Machine, OpenResult};

use crate::bench::{OpenTest, Progress, Results};
use crate::settings::{self, Settings};
use crate::t;
use crate::theme::{self, Palette};

const SITE: &str = "https://rustyfiles.com";
const REPO: &str = "https://github.com/gelenmedya/rustyfiles";
/// One dot of the race track stands for this long.
const DOT_MS: f64 = 20.0;

/// What the background run reports.
#[derive(Default)]
struct Shared {
    progress: Option<Progress>,
    done: Option<Result<Results, String>>,
}

struct State {
    detected: Vec<BenchApp>,
    machine: Option<Machine>,
    off: HashSet<AppKind>,
    running: Option<(Arc<Mutex<Shared>>, Arc<AtomicBool>)>,
    progress: Option<Progress>,
    results: Option<Results>,
    error: Option<String>,
    race: OpenTest,
    replay: Instant,
    /// "Copied" feedback on the share buttons.
    note: Option<(String, Instant)>,
}
impl Global for State {}

fn state(cx: &mut App) -> &mut State {
    if !cx.has_global::<State>() {
        let detected = rf_win::bench::detect();
        cx.set_global(State {
            detected,
            machine: None,
            off: HashSet::new(),
            running: None,
            progress: None,
            results: crate::bench::last_results(),
            error: None,
            race: OpenTest::Files100k,
            replay: Instant::now() - Duration::from_secs(600),
            note: None,
        });
        // the machine line reads the registry and asks the disk: not on the UI thread
        cx.spawn(async move |cx| {
            let m = cx.background_spawn(async { rf_win::bench::machine(&crate::bench::bench_dir()) }).await;
            cx.update(|cx| {
                cx.global_mut::<State>().machine = Some(m);
                cx.refresh_windows();
            });
        })
        .detach();
    }
    cx.global_mut::<State>()
}

// ---------------------------------------------------------------- formatting

fn ms(v: f64) -> String {
    if v >= 10_000.0 {
        format!("{:.1} s", v / 1000.0)
    } else if v >= 1000.0 {
        format!("{:.2} s", v / 1000.0)
    } else {
        format!("{v:.0} ms")
    }
}

fn mb(bytes: u64) -> String {
    format!("{} MB", (bytes as f64 / 1_048_576.0).round() as u64)
}

/// 2330750 → "2.330.750" (Turkish) / "2,330,750".
pub(crate) fn count(n: u64) -> String {
    let sep = if crate::i18n::t("1.000 dosya").starts_with("1.000") { '.' } else { ',' };
    let s = n.to_string();
    let mut out = String::new();
    for (i, c) in s.chars().enumerate() {
        if i > 0 && (s.len() - i) % 3 == 0 {
            out.push(sep);
        }
        out.push(c);
    }
    out
}

fn times(slow: f64, fast: f64) -> String {
    let x = slow / fast.max(1.0);
    if x >= 10.0 { format!("{x:.0}×") } else { format!("{x:.1}×") }
}

fn test_label(t: OpenTest) -> &'static str {
    match t {
        OpenTest::Start => t!("Açılış (boş klasör)"),
        OpenTest::Files1k => t!("1.000 dosya"),
        OpenTest::Files10k => t!("10.000 dosya"),
        OpenTest::Files100k => t!("100.000 dosya"),
        OpenTest::Images => t!("2.000 resim"),
    }
}

fn app_label(k: AppKind) -> &'static str {
    match k {
        AppKind::Rustyfiles => "rustyfiles",
        AppKind::Explorer => t!("Dosya Gezgini"),
        AppKind::Files => "Files",
        AppKind::FilePilot => "File Pilot",
        AppKind::Arke => "Arke",
        AppKind::ExplorerPlusPlus => "Explorer++",
        AppKind::DoubleCommander => "Double Commander",
        AppKind::Sigma => "Sigma",
    }
}

fn machine_line(m: &Machine) -> String {
    let mut parts = vec![m.cpu.clone()];
    if m.ram_gb > 0 {
        parts.push(format!("{} GB RAM", m.ram_gb));
    }
    if !m.disk.is_empty() {
        parts.push(m.disk.clone());
    }
    parts.push(m.windows.clone());
    parts.join(" · ")
}

/// rustyfiles' median and the slowest other app's on `test`, for the headline.
fn speedup(r: &Results, test: OpenTest, other: AppKind) -> Option<(f64, f64)> {
    let o = r.open.iter().find(|o| o.test == test)?;
    let ours = o.apps.iter().find(|a| a.app == AppKind::Rustyfiles)?.median()?.settled_ms;
    let theirs = o.apps.iter().find(|a| a.app == other)?.median()?.settled_ms;
    Some((ours, theirs))
}

// ---------------------------------------------------------------- running

fn start(cx: &mut App) {
    let st = state(cx);
    if st.running.is_some() {
        return;
    }
    let mut apps = vec![crate::bench::rustyfiles_app()];
    apps.extend(st.detected.iter().filter(|a| !st.off.contains(&a.kind)).cloned());
    let plan = crate::bench::Plan { apps, open: OpenTest::ALL.to_vec(), copy: true, engines: true };
    let shared = Arc::new(Mutex::new(Shared::default()));
    let cancel = Arc::new(AtomicBool::new(false));
    st.running = Some((shared.clone(), cancel.clone()));
    st.error = None;
    st.progress = None;
    {
        let shared = shared.clone();
        std::thread::Builder::new()
            .name("rf-bench".into())
            .spawn(move || {
                let report = |p: Progress| shared.lock().progress = Some(p);
                let r = crate::bench::run(&plan, &report, &cancel).map_err(|e| format!("{e:#}"));
                shared.lock().done = Some(r);
                // the coffee strip quotes the newest results
                crate::donate::refresh();
            })
            .ok();
    }
    // mirror the thread's progress into the page until it finishes
    cx.spawn(async move |cx| {
        loop {
            cx.background_executor().timer(Duration::from_millis(200)).await;
            let (p, done) = {
                let mut s = shared.lock();
                (s.progress.clone(), s.done.take())
            };
            let finished = cx.update(|cx| {
                let st = cx.global_mut::<State>();
                st.progress = p;
                if let Some(d) = done {
                    st.running = None;
                    match d {
                        Ok(r) => {
                            st.results = Some(r);
                            st.replay = Instant::now();
                        }
                        Err(e) if e == "cancelled" => {}
                        Err(e) => st.error = Some(e),
                    }
                    cx.refresh_windows();
                    return true;
                }
                cx.refresh_windows();
                false
            });
            if finished {
                break;
            }
        }
        replay_frames(cx).await;
    })
    .detach();
}

/// Redraws while the race replays.
async fn replay_frames(cx: &mut AsyncApp) {
    loop {
        let more = cx.update(|cx| {
            let st = cx.global::<State>();
            let longest = st.results.as_ref().map_or(0.0, |r| race_longest(r, st.race));
            let going = st.replay.elapsed().as_secs_f64() * 1000.0 < longest + 300.0;
            cx.refresh_windows();
            going
        });
        if !more {
            break;
        }
        cx.background_executor().timer(Duration::from_millis(33)).await;
    }
}

fn race_longest(r: &Results, test: OpenTest) -> f64 {
    r.open
        .iter()
        .find(|o| o.test == test)
        .map_or(0.0, |o| o.apps.iter().filter_map(|a| a.median()).map(|m| m.settled_ms).fold(0.0, f64::max))
}

fn replay(test: OpenTest, cx: &mut App) {
    let st = state(cx);
    st.race = test;
    st.replay = Instant::now();
    cx.spawn(async move |cx| replay_frames(cx).await).detach();
}

// ---------------------------------------------------------------- sharing

/// base64url without padding.
fn b64url(data: &[u8]) -> String {
    const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    for c in data.chunks(3) {
        let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
        for k in 0..c.len() + 1 {
            out.push(A[(n >> (18 - 6 * k) & 63) as usize] as char);
        }
    }
    out
}

fn app_key(k: AppKind) -> &'static str {
    match k {
        AppKind::Rustyfiles => "rf",
        AppKind::Explorer => "ex",
        AppKind::Files => "fi",
        AppKind::FilePilot => "fp",
        AppKind::Arke => "ar",
        AppKind::ExplorerPlusPlus => "xp",
        AppKind::DoubleCommander => "dc",
        AppKind::Sigma => "sg",
    }
}

/// The results as the site reads them (link format v1, agreed with the site): a small JSON,
/// base64url, in the path of rustyfiles.com/r/…. Measurements and the PC model only.
pub(crate) fn share_payload(r: &Results) -> serde_json::Value {
    use serde_json::{Map, Value, json};
    let mut open = Vec::new();
    let mut shared: Vec<&str> = Vec::new();
    for o in &r.open {
        let mut row = Map::new();
        let n = match o.test {
            OpenTest::Start => 0,
            OpenTest::Files1k => 1000,
            OpenTest::Files10k => 10000,
            OpenTest::Files100k => 100000,
            OpenTest::Images => {
                row.insert("img".into(), json!(true));
                2000
            }
        };
        row.insert("n".into(), json!(n));
        for a in &o.apps {
            let m = a.median();
            row.insert(app_key(a.app).into(), m.map_or(Value::Null, |m| json!(m.settled_ms.round() as i64)));
            if m.is_some_and(|m| m.shared) && !shared.contains(&app_key(a.app)) {
                shared.push(app_key(a.app));
            }
        }
        open.push(Value::Object(row));
    }
    let mut out = json!({
        "v": 1,
        "app": r.version,
        "t": r.when / 1000,
        "pc": {"cpu": r.machine.cpu, "ram": r.machine.ram_gb, "disk": r.machine.disk, "os": r.machine.windows, "cores": r.machine.cores},
        "open": open,
        "shared": shared,
    });
    let o = out.as_object_mut().expect("object");
    // CPU and memory from the largest folder that was opened
    let size = |t: OpenTest| match t {
        OpenTest::Files100k => 100000,
        OpenTest::Files10k => 10000,
        OpenTest::Files1k => 1000,
        _ => 0,
    };
    if let Some(l) = r.open.iter().filter(|x| size(x.test) > 0).max_by_key(|x| size(x.test)) {
        let (mut cpu, mut mem) = (Map::new(), Map::new());
        for a in &l.apps {
            let m = a.median();
            cpu.insert(app_key(a.app).into(), m.map_or(Value::Null, |m| json!(m.cpu_ms.round() as i64)));
            mem.insert(app_key(a.app).into(), m.map_or(Value::Null, |m| json!(((if m.private > 0 { m.private } else { m.ram }) as f64 / 1_048_576.0).round() as i64)));
        }
        o.insert("of".into(), json!(size(l.test)));
        o.insert("cpu".into(), Value::Object(cpu));
        o.insert("mem".into(), Value::Object(mem));
    }
    let e = &r.engines;
    let vs = |v: &Option<crate::bench::Versus>| v.as_ref().and_then(|v| Some((v.ours_ms?.round() as i64, v.windows_ms?.round() as i64)));
    // CPU time (ms) and extra memory (MB) of each side, when measured (0.5.1 on)
    let costs = |v: &crate::bench::Versus, m: &mut Map<String, Value>| {
        for (k, x) in [("rfc", v.ours_cpu_ms), ("winc", v.windows_cpu_ms), ("rfm", v.ours_mb), ("winm", v.windows_mb)] {
            if let Some(x) = x {
                m.insert(k.into(), json!(x.round() as i64));
            }
        }
    };
    for (key, v, extra) in [
        ("copy", &e.copy_small, json!({"n": 10000, "mb": 39})),
        ("big", &e.copy_big, json!({"mb": 1024})),
        ("zip", &e.unzip, json!({"n": 10000})),
    ] {
        if let (Some((a, b)), Some(full)) = (vs(v), v.as_ref()) {
            let Value::Object(mut m) = extra else { continue };
            m.insert("rf".into(), json!(a));
            m.insert("win".into(), json!(b));
            costs(full, &mut m);
            o.insert(key.into(), Value::Object(m));
        }
    }
    if let Some(ms) = e.search_ms {
        let mut m = Map::new();
        m.insert("n".into(), json!(e.search_entries));
        m.insert("rf".into(), json!(ms.round() as i64));
        if let Some(c) = e.search_cpu_ms {
            m.insert("c".into(), json!(c.round() as i64));
        }
        if let Some(x) = e.search_mb {
            m.insert("m".into(), json!(x.round() as i64));
        }
        o.insert("search".into(), Value::Object(m));
    }
    out
}

/// rustyfiles.com/r/… for these results.
pub(crate) fn share_link(r: &Results) -> String {
    let json = serde_json::to_vec(&share_payload(r)).unwrap_or_default();
    format!("{SITE}/r/{}", b64url(&json))
}

/// A short link from the site (rustyfiles.com/r/<8 characters>: the result is stored there), or
/// the long one carrying the result itself when the site can't be reached (offline, an error,
/// no answer in 5 s). Blocking: call it off the UI thread. Asked once per result.
pub(crate) fn short_link(r: &Results) -> String {
    static CACHE: std::sync::Mutex<Option<(i64, String)>> = std::sync::Mutex::new(None);
    if let Some((when, url)) = CACHE.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
        if *when == r.when {
            return url.clone();
        }
    }
    let body = serde_json::to_vec(&share_payload(r)).unwrap_or_default();
    let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(std::time::Duration::from_secs(5))).http_status_as_error(false).build().into();
    let prefix = format!("{SITE}/r/");
    let got = agent
        .post(format!("{SITE}/api/r"))
        .header("User-Agent", format!("rustyfiles/{}", crate::installer::version()))
        .content_type("application/json")
        .send(&body[..])
        .ok()
        .filter(|resp| resp.status() == 200)
        .and_then(|mut resp| resp.body_mut().read_to_string().ok())
        .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
        .and_then(|v| v["url"].as_str().map(str::to_string))
        .filter(|url| url.starts_with(&prefix) && url.len() <= prefix.len() + 16);
    match got {
        Some(url) => {
            *CACHE.lock().unwrap_or_else(|e| e.into_inner()) = Some((r.when, url.clone()));
            url
        }
        None => share_link(r),
    }
}

/// Runs `f` with the results and their link (short when the site gives one), the request made
/// in the background so the window never waits on the network.
fn with_link(cx: &mut App, f: impl FnOnce(&Results, &str, &mut App) + 'static) {
    let Some(r) = state(cx).results.clone() else { return };
    let r2 = r.clone();
    cx.spawn(async move |cx| {
        let link = cx.background_executor().spawn(async move { short_link(&r2) }).await;
        let _ = cx.update(|cx| f(&r, &link, cx));
    })
    .detach();
}

fn summary_text(r: &Results, link: &str) -> String {
    let mut lines = vec![format!("rustyfiles · {}", machine_line(&r.machine))];
    for o in &r.open {
        if !matches!(o.test, OpenTest::Files100k | OpenTest::Start) {
            continue;
        }
        // "*": the app was already running (Files keeps a process in the background), so the
        // time isn't a start from scratch: the card and the table say so, the text must too
        let row: Vec<String> = o
            .apps
            .iter()
            .filter_map(|a| a.median().map(|m| format!("{} {}{}", app_label(a.app), ms(m.settled_ms), if m.shared { "*" } else { "" })))
            .collect();
        if !row.is_empty() {
            lines.push(format!("{}: {}", test_label(o.test), row.join(", ")));
        }
    }
    let any_shared = r.open.iter().filter(|o| matches!(o.test, OpenTest::Files100k | OpenTest::Start)).any(|o| o.apps.iter().any(|a| a.median().is_some_and(|m| m.shared)));
    if let Some(v) = &r.engines.copy_small {
        if let (Some(a), Some(b)) = (v.ours_ms, v.windows_ms) {
            lines.push(format!("{}: rustyfiles {} · Windows {}", t!("10.000 küçük dosya kopyalama"), ms(a), ms(b)));
        }
    }
    if any_shared {
        lines.push(format!("* {}", t!("uygulama zaten çalışıyordu (sıfırdan açılış değil)")));
    }
    lines.push(format!("{} {}", t!("Sonuçlar:"), link));
    lines.push(format!("{} {SITE}", t!("Ücretsiz ve açık kaynak:")));
    lines.join("\n")
}

/// The short line for X / WhatsApp / Reddit titles.
fn headline(r: &Results) -> String {
    match speedup(r, OpenTest::Files100k, AppKind::Explorer) {
        Some((ours, theirs)) => t!("rustyfiles bilgisayarımda 100.000 dosyalık klasörü {ours} sürede açtı, Dosya Gezgini {theirs}.")
            .replace("{ours}", &ms(ours))
            .replace("{theirs}", &ms(theirs)),
        None => t!("rustyfiles: Windows için hızlı, ücretsiz ve açık kaynak dosya yöneticisi.").to_string(),
    }
}

fn enc(s: &str) -> String {
    let mut out = String::new();
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

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

fn esc(s: &str) -> String {
    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}

/// The first line of the card's headline: what was opened.
fn folder_phrase(t: OpenTest) -> &'static str {
    match t {
        OpenTest::Start => t!("Boş bir klasörü"),
        OpenTest::Files1k => t!("1.000 dosyalık bir klasörü"),
        OpenTest::Files10k => t!("10.000 dosyalık bir klasörü"),
        OpenTest::Files100k => t!("100.000 dosyalık bir klasörü"),
        OpenTest::Images => t!("2.000 resimli bir klasörü"),
    }
}

/// `text` as SVG tspans, with the part `{x}` stands for in `accent` (the rest takes the text element's own colour).
fn with_accent(text: &str, x: &str, accent: &str) -> String {
    match text.split_once("{x}") {
        Some((a, b)) => format!("{}<tspan fill=\"{accent}\">{}</tspan>{}", esc(a), esc(x), esc(b)),
        None => esc(text),
    }
}

/// The result card as SVG (1200 × 675, the size social sites show whole), in the look of rustyfiles' posts: the near-black
/// background with its dot grid and ember glow, the wordmark, a headline in Bricolage Grotesque that says in words what was
/// measured, the bars, and the big numbers in Doto, each with what it counts and both times under it.
fn card_svg(r: &Results) -> String {
    const INK: &str = "#f2f0ec";
    const DIM: &str = "#9d9ba2";
    const FAINT: &str = "#6c6a72";
    const EMBER: &str = "#ff6a1a";
    // (quoted: a family name with "96pt" in it is not a CSS identifier, and an unquoted one dropped the whole list)
    const HEAD: &str = "font-family=\"'Bricolage Grotesque 96pt', 'Bricolage Grotesque 96pt SemiBold', 'Segoe UI'\" font-weight=\"600\"";
    const BODY: &str = "font-family=\"'Bricolage Grotesque', 'Segoe UI'\" font-weight=\"400\"";
    const NUM: &str = "font-family=\"'Doto', 'Doto Black', 'Segoe UI'\" font-weight=\"900\"";
    let (w, h, m): (f64, f64, f64) = (1200.0, 675.0, 64.0);
    let test = if r.open.iter().any(|o| o.test == OpenTest::Files100k) { OpenTest::Files100k } else { r.open.iter().map(|o| o.test).find(|t| *t != OpenTest::Start).unwrap_or(OpenTest::Files10k) };
    let row = r.open.iter().find(|o| o.test == test);
    let mut rows: Vec<(AppKind, f64, bool)> = row.map(|o| o.apps.iter().filter_map(|a| a.median().map(|m| (a.app, m.settled_ms, m.shared))).collect()).unwrap_or_default();
    rows.sort_by(|a, b| a.1.total_cmp(&b.1));
    // at most four bars: rustyfiles and File Explorer always, then the fastest of the others (one very slow app would shrink the
    // others to dots)
    let mut keep: Vec<(AppKind, f64, bool)> = rows.iter().filter(|x| matches!(x.0, AppKind::Rustyfiles | AppKind::Explorer)).cloned().collect();
    for x in &rows {
        if keep.len() >= 4 {
            break;
        }
        if !keep.iter().any(|k| k.0 == x.0) {
            keep.push(x.clone());
        }
    }
    keep.sort_by(|a, b| a.1.total_cmp(&b.1));
    let ours = rows.iter().find(|x| x.0 == AppKind::Rustyfiles).map(|x| x.1);
    let explorer = rows.iter().find(|x| x.0 == AppKind::Explorer).map(|x| x.1);

    // the background, the wordmark, who measured it where
    let mut s = format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}">
<defs>
<pattern id="dots" width="24" height="24" patternUnits="userSpaceOnUse"><circle cx="12" cy="12" r="1" fill="#ffffff" fill-opacity="0.055"/></pattern>
<radialGradient id="glow" cx="0.86" cy="0.02" r="0.62"><stop offset="0" stop-color="{EMBER}" stop-opacity="0.30"/><stop offset="1" stop-color="{EMBER}" stop-opacity="0"/></radialGradient>
<radialGradient id="glow2" cx="0.02" cy="1.0" r="0.45"><stop offset="0" stop-color="#d9480f" stop-opacity="0.13"/><stop offset="1" stop-color="#d9480f" stop-opacity="0"/></radialGradient>
<linearGradient id="hot" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="{EMBER}"/><stop offset="1" stop-color="#ff8a45"/></linearGradient>
</defs>
<rect width="{w}" height="{h}" fill="#050505"/>
<rect width="{w}" height="{h}" fill="url(#dots)"/>
<rect width="{w}" height="{h}" fill="url(#glow)"/>
<rect width="{w}" height="{h}" fill="url(#glow2)"/>
{}
<text x="{}" y="74" {BODY} font-size="21" fill="{DIM}" text-anchor="end">{}</text>
<text x="{}" y="98" {BODY} font-size="15" fill="{FAINT}" text-anchor="end">{}</text>
"##,
        crate::brand::wordmark_nested(m as f32, 46.0, 50.0, INK),
        w - m,
        esc(t!("Bilgisayarımdaki hız testi")),
        w - m,
        esc(&machine_line(&r.machine)),
    );

    // the headline, in words: what was opened, and how it went against File Explorer
    let second = match (ours, explorer) {
        (Some(a), Some(b)) if b > a * 1.05 => with_accent(t!("Dosya Gezgini'nden {x} hızlı açar"), &times(b, a), EMBER),
        (Some(_), Some(_)) => esc(t!("Dosya Gezgini kadar hızlı açar")),
        (Some(a), None) => with_accent(t!("{x} içinde açar"), &ms(a), EMBER),
        _ => String::new(),
    };
    s.push_str(&format!(
        r##"<text x="{m}" y="196" {HEAD} font-size="56" letter-spacing="-1.2" fill="{INK}">{}</text>
<text x="{m}" y="260" {HEAD} font-size="56" letter-spacing="-1.2" fill="{INK}">{second}</text>
"##,
        esc(folder_phrase(test)),
    ));

    // the bars: each app opening that folder, from a cold start
    let longest = keep.iter().map(|x| x.1).fold(1.0, f64::max);
    let (lx, bx, bw) = (m, m + 200.0, w - 2.0 * m - 200.0 - 110.0);
    s.push_str(&format!(
        r##"<text x="{m}" y="316" {BODY} font-size="16" fill="{FAINT}">{}</text>"##,
        esc(&format!("{} · {} · {}", t!("Klasörün açılması, gerçek hızda"), test_label(test), t!("kısa olan daha iyi")))
    ));
    for (i, (app, v, shared)) in keep.iter().enumerate() {
        let y = 334.0 + i as f64 * 30.0;
        let len = (v / longest * bw).max(8.0);
        let mine = *app == AppKind::Rustyfiles;
        s.push_str(&format!(
            r##"<text x="{lx}" y="{}" {} font-size="18" fill="{}">{}</text><rect x="{bx}" y="{}" width="{bw:.0}" height="12" rx="6" fill="#ffffff" fill-opacity="0.04"/><rect x="{bx}" y="{}" width="{len:.0}" height="12" rx="6" fill="{}"/><text x="{}" y="{}" {HEAD} font-size="18" fill="{}" text-anchor="end">{}{}</text>"##,
            y + 15.0,
            if mine { HEAD } else { BODY },
            if mine { INK } else { DIM },
            esc(app_label(*app)),
            y + 4.0,
            y + 4.0,
            if mine { "url(#hot)" } else { "#3a3940" },
            w - m,
            y + 15.0,
            if mine { EMBER } else { DIM },
            esc(&ms(*v)),
            if *shared { " *" } else { "" },
        ));
    }

    // the big numbers, each with what it counts and both times
    struct Cell {
        big: String,
        word: &'static str,
        what: String,
        times: String,
    }
    let mut cells: Vec<Cell> = Vec::new();
    for (v, what) in [(&r.engines.copy_small, t!("10.000 küçük dosya kopyalama")), (&r.engines.unzip, t!("ZIP çıkarma: 10.000 dosya"))] {
        if let Some(v) = v
            && let (Some(a), Some(b)) = (v.ours_ms, v.windows_ms)
        {
            cells.push(Cell { big: times(b, a), word: t!("daha hızlı"), what: what.to_string(), times: format!("rustyfiles {} · Windows {}", ms(a), ms(b)) });
        }
    }
    // the memory with that folder open, when it is less than File Explorer's (Task Manager's figure)
    let memory = |k: AppKind| row.and_then(|o| o.apps.iter().find(|a| a.app == k)).and_then(|a| a.median()).filter(|m| m.private_ws > 0).map(|m| m.private_ws);
    if let (Some(a), Some(b)) = (memory(AppKind::Rustyfiles), memory(AppKind::Explorer))
        && b as f64 > a as f64 * 1.1
    {
        cells.push(Cell {
            big: mb(a),
            word: "",
            what: t!("bellek, klasör açıkken").to_string(),
            times: format!("{} {}", app_label(AppKind::Explorer), mb(b)),
        });
    }
    let cells = &cells[..cells.len().min(3)];
    let (cy, ch) = (500.0, 112.0);
    if !cells.is_empty() {
        let cw = (w - 2.0 * m) / cells.len() as f64;
        s.push_str(&format!(r##"<rect x="{m}" y="{cy}" width="{}" height="{ch}" rx="18" fill="#ffffff" fill-opacity="0.035" stroke="#ffffff" stroke-opacity="0.09"/>"##, w - 2.0 * m));
        for (i, c) in cells.iter().enumerate() {
            let x = m + i as f64 * cw + 28.0;
            if i > 0 {
                s.push_str(&format!(r##"<line x1="{0}" y1="{1}" x2="{0}" y2="{2}" stroke="#ffffff" stroke-opacity="0.09"/>"##, x - 28.0, cy + 16.0, cy + ch - 16.0));
            }
            // the multiplier's "×" in Bricolage: Doto's would be a dot pattern too small to read
            let (num, sign) = match c.big.strip_suffix('×') {
                Some(n) => (n.to_string(), "×"),
                None => (c.big.clone(), ""),
            };
            // the digits in Doto; a decimal point in Bricolage (Doto's is one dot, lost beside the digits)
            let digits = match num.split_once('.') {
                Some((a, b)) => format!("{}</tspan><tspan {HEAD} font-size=\"40\">.</tspan><tspan {NUM} font-size=\"46\">{}", esc(a), esc(b)),
                None => esc(&num),
            };
            s.push_str(&format!(
                r##"<text x="{x}" y="{}" fill="{EMBER}"><tspan {NUM} font-size="46">{}</tspan><tspan {HEAD} font-size="30" dx="3">{sign}</tspan><tspan {BODY} font-size="19" fill="{DIM}" dx="8">{}</tspan></text><text x="{x}" y="{}" {BODY} font-size="17" fill="{INK}">{}</text><text x="{x}" y="{}" {BODY} font-size="14" fill="{FAINT}">{}</text>"##,
                cy + 50.0,
                digits,
                esc(c.word),
                cy + 76.0,
                esc(&c.what),
                cy + 97.0,
                esc(&c.times),
            ));
        }
    }

    // the footer
    let shared_note = if keep.iter().any(|x| x.2) { format!(" · * {}", t!("uygulama zaten çalışıyordu (sıfırdan açılış değil)")) } else { String::new() };
    s.push_str(&format!(
        r##"<text x="{m}" y="{}" {HEAD} font-size="20" fill="{EMBER}">rustyfiles.com</text><text x="{}" y="{}" {BODY} font-size="14" fill="{FAINT}" text-anchor="end">{}{}</text></svg>"##,
        h - 34.0,
        w - m,
        h - 34.0,
        esc(t!("Kendi bildirdiği sonuç · ücretsiz ve açık kaynak · Windows")),
        esc(&shared_note),
    ));
    s
}

fn hwnd(window: &Window) -> Option<isize> {
    use raw_window_handle::{HasWindowHandle, RawWindowHandle};
    match HasWindowHandle::window_handle(window).map(|h| h.as_raw()) {
        Ok(RawWindowHandle::Win32(h)) => Some(h.hwnd.get()),
        _ => None,
    }
}

fn note(msg: &str, cx: &mut App) {
    state(cx).note = Some((msg.to_string(), Instant::now()));
    cx.spawn(async move |cx| {
        cx.background_executor().timer(Duration::from_millis(2600)).await;
        cx.update(|cx| cx.refresh_windows());
    })
    .detach();
}

fn copy_picture(window: &Window, cx: &mut App) {
    let Some(r) = state(cx).results.clone() else { return };
    let owner = hwnd(window);
    let svg = card_svg(&r);
    // drawn off the UI thread: the first drawing also reads the system's fonts, which took long enough to freeze the window
    cx.spawn(async move |cx| {
        let pic = cx.background_executor().spawn(async move { rf_win::bench::render_card(&svg, 1.0, crate::brand::FONTS) }).await;
        let _ = cx.update(|cx| match pic {
            Ok(pic) => {
                // also kept as a file next to the results, for attaching
                let path = crate::bench::bench_dir().join("rustyfiles-speed-test.png");
                let _ = std::fs::write(&path, &pic.png);
                let ok = owner.is_some_and(|h| rf_win::clipboard::set_image(windows::Win32::Foundation::HWND(h as *mut _), pic.width, pic.height, &pic.rgba, &pic.png).is_ok());
                note(if ok { t!("Sonuç kartı panoya kopyalandı") } else { t!("Panoya kopyalanamadı") }, cx);
            }
            Err(e) => {
                log::warn!("bench card: {e:#}");
                note(t!("Kart çizilemedi"), cx);
            }
        });
    })
    .detach();
}

/// Saves the card to Downloads and opens it.
fn save_picture(cx: &mut App) {
    let Some(r) = state(cx).results.clone() else { return };
    let svg = card_svg(&r);
    std::thread::spawn(move || {
        let Ok(pic) = rf_win::bench::render_card(&svg, 1.0, crate::brand::FONTS) else { return };
        let dir = rf_win::known::KnownFolder::Downloads.path().unwrap_or_else(std::env::temp_dir);
        let path = rf_win::fileops::unique_name(&dir, "rustyfiles speed test", ".png");
        if std::fs::write(&path, &pic.png).is_ok() {
            let _ = rf_win::shell::open(&path);
        }
    });
    note(t!("Kart İndirilenler klasörüne kaydedildi"), cx);
}

fn copy_text(window: &Window, cx: &mut App) {
    let _ = window;
    with_link(cx, |r, link, cx| {
        cx.write_to_clipboard(ClipboardItem::new_string(summary_text(r, link)));
        note(t!("Sonuçlar panoya kopyalandı"), cx);
    });
}

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

fn button(id: impl Into<ElementId>, p: &Palette, icon: L, label: impl Into<SharedString>, primary: bool, run: impl Fn(&mut Window, &mut App) + 'static) -> AnyElement {
    h_flex()
        .id(id)
        .h(px(32.))
        .px_3()
        .gap_2()
        .items_center()
        .rounded(theme::RADIUS_SM)
        .text_sm()
        .when(primary, |d| d.bg(p.accent).text_color(p.accent_text).hover(|s| s.opacity(0.9)))
        .when(!primary, |d| d.bg(p.hover).border_1().border_color(p.border).hover(|s| s.bg(p.pressed)))
        .active(|s| s.opacity(0.8))
        .child(Icon::new(icon).size(px(14.)))
        .child(label.into())
        .on_click(move |_, window, cx| run(window, cx))
        .into_any_element()
}

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

pub fn page(p: &Palette, cx: &mut App) -> Vec<AnyElement> {
    let st = state(cx);
    let running = st.running.is_some();
    let mut out = Vec::new();

    // intro: what it does, on which machine, with which apps
    let machine = st.machine.as_ref().map(machine_line).unwrap_or_default();
    let mut chips = h_flex().gap_2().flex_wrap().child(chip(p, "bench-app-rf", "rustyfiles", true, true, |_| {}));
    let installed: Vec<AppKind> = st.detected.iter().map(|a| a.kind).collect();
    for kind in [AppKind::Explorer, AppKind::Files, AppKind::FilePilot, AppKind::Arke, AppKind::ExplorerPlusPlus, AppKind::DoubleCommander, AppKind::Sigma] {
        let here = installed.contains(&kind);
        let on = here && !st.off.contains(&kind);
        let label = if here { app_label(kind).to_string() } else { format!("{} · {}", app_label(kind), t!("kurulu değil")) };
        chips = chips.child(chip(p, ("bench-app", kind as usize), &label, on, !here || running, move |cx| {
            let off = &mut state(cx).off;
            if !off.remove(&kind) {
                off.insert(kind);
            }
        }));
    }
    let action = if running {
        button("bench-stop", p, L::X, t!("Durdur"), false, |_, cx| {
            if let Some((_, c)) = &state(cx).running {
                c.store(true, Ordering::Relaxed);
            }
        })
    } else {
        button("bench-start", p, L::Play, if st.results.is_some() { t!("Yeniden çalıştır") } else { t!("Testi başlat") }, true, |_, cx| start(cx))
    };
    let mut intro = v_flex()
        .p_4()
        .gap_3()
        .child(
            h_flex()
                .gap_3()
                .items_center()
                .child(Icon::new(L::Gauge).size(px(22.)).text_color(p.accent))
                .child(
                    v_flex()
                        .flex_1()
                        .min_w_0()
                        .child(div().font_weight(FontWeight::SEMIBOLD).child(t!("Bu bilgisayarda hız testi")))
                        .child(div().text_xs().text_color(p.text_secondary).child(if machine.is_empty() { t!("Bilgisayar okunuyor…").to_string() } else { machine })),
                )
                .child(action),
        )
        .child(chips)
        .child(div().text_xs().text_color(p.text_secondary).child(t!(
            "Her uygulama aynı klasörleri sırayla açar; süre, işlemci ve bellek ölçülür. Test sırasında diğer uygulamaların pencereleri açılıp kapanır: fareye ve klavyeye dokunmayın. Yaklaşık 5–10 dakika sürer; test dosyaları ilk seferde hazırlanır (~1,3 GB, yerel uygulama verisinde)."
        )));
    if running {
        let (frac, label) = match &st.progress {
            Some(Progress::Step { i, n, label }) => (*i as f32 / (*n).max(1) as f32, format!("{} {i}/{n} · {label}", t!("Adım"))),
            Some(Progress::Preparing(what, f)) => (*f * 0.05, format!("{} {what}", t!("Test dosyaları hazırlanıyor:"))),
            None => (0.0, t!("Başlıyor…").to_string()),
        };
        intro = intro.child(
            v_flex()
                .gap_1p5()
                .child(div().h(px(4.)).w_full().rounded_full().bg(p.divider).child(div().h_full().w(relative(frac.clamp(0.01, 1.0))).rounded_full().bg(p.accent)))
                .child(div().text_xs().text_color(p.text_secondary).child(label)),
        );
    }
    if let Some(e) = &st.error {
        intro = intro.child(div().text_sm().text_color(p.danger).child(format!("{} {e}", t!("Test tamamlanamadı:"))));
    }
    out.push(shell(p).child(intro).into_any_element());

    let Some(r) = st.results.clone() else { return out };
    let race = st.race;
    let elapsed = st.replay.elapsed().as_secs_f64() * 1000.0;
    let note_text = st.note.as_ref().filter(|n| n.1.elapsed() < Duration::from_millis(2500)).map(|n| n.0.clone());
    out.push(race_card(p, &r, race, elapsed));
    out.push(table_card(p, &r));
    if let Some(e) = engines_card(p, &r) {
        out.push(e);
    }
    let star_asked = cx.global::<Settings>().star_asked;
    if !star_asked {
        out.push(star_card(p, &r));
    }
    out.push(share_card(p, note_text));
    out.push(
        h_flex()
            .pt_1()
            .gap_2()
            .text_xs()
            .text_color(p.text_tertiary)
            .child(div().flex_1().min_w_0().child(t!(
                "Ortanca değerler (3 çalıştırma, ısınma turu sayılmaz). Süre: uygulama başlatıldığından pencere içeriği 500 ms boyunca değişmeyene dek. * işaretli değerlerde uygulama zaten çalışıyordu: işlemci pencere açıldıktan sonrasını, bellek tüm süreci gösterir. Bellek, Görev Yöneticisi'nin gösterdiği değerdir."
            )))
            .child(
                div()
                    .id("bench-delete")
                    .cursor_pointer()
                    .text_color(p.accent)
                    .hover(|s| s.underline())
                    .child(t!("Test dosyalarını sil"))
                    .on_click(|_, _, cx| {
                        std::thread::spawn(|| {
                            let _ = crate::bench::delete_test_files();
                        });
                        state(cx).results = None;
                        cx.refresh_windows();
                    }),
            )
            .into_any_element(),
    );
    out
}

fn chip(p: &Palette, id: impl Into<ElementId>, label: &str, on: bool, locked: bool, toggle: impl Fn(&mut App) + 'static) -> AnyElement {
    h_flex()
        .id(id)
        .h(px(28.))
        .px_3()
        .gap_1p5()
        .items_center()
        .rounded_full()
        .border_1()
        .text_sm()
        .when(on, |d| d.bg(p.selection).border_color(p.accent))
        .when(!on, |d| d.border_color(p.border).text_color(p.text_secondary))
        .when(!locked, |d| d.hover(|s| s.bg(p.pressed)).on_click(move |_, _, cx| {
            toggle(cx);
            cx.refresh_windows();
        }))
        .when(on, |d| d.child(Icon::new(L::Check).size(px(12.)).text_color(p.accent)))
        .child(label.to_string())
        .into_any_element()
}

fn race_card(p: &Palette, r: &Results, race: OpenTest, elapsed: f64) -> AnyElement {
    // (they go on to a second line where the page is narrow)
    let mut tabs = h_flex().gap_1().flex_wrap();
    for (i, o) in r.open.iter().enumerate() {
        let t = o.test;
        let on = t == race;
        tabs = tabs.child(
            div()
                .id(("bench-tab", i))
                .px_3()
                .h(px(28.))
                .flex()
                .items_center()
                .rounded(theme::RADIUS_SM)
                .text_sm()
                .when(on, |d| d.bg(p.selection).text_color(p.text))
                .when(!on, |d| d.text_color(p.text_secondary).hover(|s| s.bg(p.pressed)))
                .child(test_label(t))
                .on_click(move |_, _, cx| replay(t, cx)),
        );
    }
    let o = r.open.iter().find(|o| o.test == race);
    let rows: Vec<(AppKind, Option<OpenResult>, Option<String>)> =
        o.map(|o| o.apps.iter().map(|a| (a.app, a.median().cloned(), a.error.clone())).collect()).unwrap_or_default();
    let longest = rows.iter().filter_map(|r| r.1.as_ref().map(|m| m.settled_ms)).fold(1.0, f64::max);
    let best = rows.iter().filter_map(|r| r.1.as_ref().map(|m| m.settled_ms)).fold(f64::MAX, f64::min);
    let mut lanes = v_flex().gap_3();
    for (app, m, err) in rows {
        let (track, value): (AnyElement, String) = match (&m, err) {
            (Some(m), _) => {
                let shown = elapsed.min(m.settled_ms);
                let done = elapsed >= m.settled_ms;
                let total_dots = (longest / DOT_MS).ceil().max(1.0);
                let lit = (shown / DOT_MS).ceil();
                let frac = (lit / total_dots).clamp(0.0, 1.0) as f32;
                let color = if app == AppKind::Rustyfiles { p.accent } else { p.text_secondary };
                (
                    div().h(px(8.)).w_full().rounded_full().bg(p.divider).child(div().h_full().w(relative(frac.max(0.005))).rounded_full().bg(color)).into_any_element(),
                    if done { format!("{}{}", ms(m.settled_ms), if m.shared { " *" } else { "" }) } else { t!("Listeleniyor…").to_string() },
                )
            }
            (None, Some(_)) => (div().text_xs().text_color(p.text_tertiary).child(t!("ölçülemedi")).into_any_element(), "—".into()),
            _ => (div().into_any_element(), "—".into()),
        };
        let winner = m.as_ref().is_some_and(|m| m.settled_ms == best && elapsed >= m.settled_ms);
        lanes = lanes.child(
            h_flex()
                .gap_3()
                .items_center()
                .child(div().w(px(120.)).flex_shrink_0().text_sm().child(app_label(app)))
                .child(div().flex_1().min_w_0().child(track))
                .child(
                    div()
                        .w(px(96.))
                        .flex_shrink_0()
                        .text_sm()
                        .text_right()
                        .font_weight(if winner { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })
                        .text_color(if winner { p.accent } else { p.text })
                        .child(value),
                ),
        );
    }
    shell(p)
        .p_4()
        .gap_4()
        .child(
            h_flex()
                .gap_3()
                .items_center()
                .child(div().flex_1().font_weight(FontWeight::SEMIBOLD).child(t!("Klasörün açılması, gerçek hızda")))
                .child(button("bench-replay", p, L::RotateCcw, t!("Tekrar oynat"), false, move |_, cx| replay(race, cx))),
        )
        .child(tabs)
        .child(lanes)
        .into_any_element()
}

/// The details of each opening, one block per test: a row per app with its time and, beside it, what the machine paid (processor time,
/// memory). Stacked, not a table with a column per app: the settings page is narrow, and four columns of two lines did not fit in it
/// (the Files column was cut off and the cells broke mid-word).
fn table_card(p: &Palette, r: &Results) -> AnyElement {
    let mut list = v_flex();
    for (i, o) in r.open.iter().enumerate() {
        let best = o.apps.iter().filter_map(|a| a.median().map(|m| m.settled_ms)).fold(f64::MAX, f64::min);
        let mut block = v_flex().px_4().py_3().gap_1p5().when(i > 0, |d| d.border_t_1().border_color(p.divider)).child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(test_label(o.test)));
        for a in &o.apps {
            let (time, cost, winner) = match (a.median(), &a.error) {
                (Some(m), _) => {
                    // Task Manager's figure; older results: private bytes, else the working set
                    let mem = if m.private_ws > 0 { mb(m.private_ws) } else if m.private > 0 { mb(m.private) } else { mb(m.ram) };
                    (
                        format!("{}{}{}", ms(m.settled_ms), if m.shared { " *" } else { "" }, if m.timed_out { " ⏱" } else { "" }),
                        format!("{} {} · {} {}", t!("işlemci"), ms(m.cpu_ms), t!("bellek"), mem),
                        m.settled_ms == best,
                    )
                }
                (None, Some(e)) => ("—".to_string(), format!("{} ({})", t!("ölçülemedi"), e.chars().take(60).collect::<String>()), false),
                _ => ("—".to_string(), String::new(), false),
            };
            block = block.child(
                h_flex()
                    .gap_3()
                    .items_center()
                    .child(div().w(px(112.)).flex_shrink_0().text_sm().text_color(p.text_secondary).truncate().child(app_label(a.app)))
                    .child(
                        div()
                            .w(px(84.))
                            .flex_shrink_0()
                            .text_sm()
                            .font_weight(if winner { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })
                            .text_color(if winner { p.accent } else { p.text })
                            .child(time),
                    )
                    .child(div().flex_1().min_w_0().text_xs().text_color(p.text_tertiary).child(cost)),
            );
        }
        list = list.child(block);
    }
    shell(p)
        .child(h_flex().px_4().pt_4().pb_1().child(div().font_weight(FontWeight::SEMIBOLD).child(t!("Ayrıntılar: süre, işlemci ve bellek"))))
        .child(list)
        .into_any_element()
}

fn engines_card(p: &Palette, r: &Results) -> Option<AnyElement> {
    let e = &r.engines;
    let mut rows: Vec<(String, String, String, String)> = Vec::new();
    // "işlemci süresi: rustyfiles 1.20 s · Windows 3.40 s · bellek: +12 MB · +40 MB"
    let cost = |ours: (Option<f64>, Option<f64>), theirs: Option<(Option<f64>, Option<f64>, &str)>| -> String {
        let mb = |m: f64| format!("+{m:.0} MB");
        let mut parts = Vec::new();
        if let Some(c) = ours.0 {
            let mut s = format!("{}: rustyfiles {}", t!("işlemci süresi"), ms(c));
            if let Some((Some(tc), _, name)) = theirs {
                s.push_str(&format!(" · {name} {}", ms(tc)));
            }
            parts.push(s);
        }
        if let Some(m) = ours.1 {
            let mut s = format!("{}: {}", t!("bellek"), mb(m));
            if let Some((_, Some(tm), _)) = theirs {
                s.push_str(&format!(" · {}", mb(tm)));
            }
            parts.push(s);
        }
        parts.join(" · ")
    };
    let mut versus = |label: &str, v: &Option<crate::bench::Versus>, windows_name: &str| {
        let Some(v) = v else { return };
        let usage = cost((v.ours_cpu_ms, v.ours_mb), Some((v.windows_cpu_ms, v.windows_mb, windows_name)));
        let (Some(a), Some(b)) = (v.ours_ms, v.windows_ms) else {
            if let Some(a) = v.ours_ms {
                rows.push((label.to_string(), format!("rustyfiles {}", ms(a)), String::new(), usage));
            }
            return;
        };
        // within 10 %: the disk sets the pace for both
        let verdict = if (a - b).abs() <= a.max(b) * 0.1 {
            t!("aynı hızda").to_string()
        } else if b > a {
            t!("{x} daha hızlı").replace("{x}", &times(b, a))
        } else {
            t!("{x} daha yavaş").replace("{x}", &times(a, b))
        };
        rows.push((label.to_string(), format!("rustyfiles {} · {windows_name} {}", ms(a), ms(b)), verdict, usage));
    };
    versus(t!("Kopyalama: 10.000 küçük dosya"), &e.copy_small, "Windows");
    versus(t!("Kopyalama: 1 GB'lık tek dosya"), &e.copy_big, "Windows");
    versus(t!("ZIP çıkarma: 10.000 dosya"), &e.unzip, "Windows");
    if let Some(s) = e.search_ms {
        let rate = e.search_entries as f64 / (s / 1000.0).max(0.001);
        let usage = cost((e.search_cpu_ms, e.search_mb), None);
        rows.push((t!("Alt klasörlerde arama").to_string(), format!("{} {} · {}", count(e.search_entries), t!("öğe"), ms(s)), t!("saniyede {n} öğe").replace("{n}", &count(rate as u64)), usage));
    }
    if rows.is_empty() {
        return None;
    }
    // each row stacked: the name with the verdict at its right, then the times, then what they cost (a fixed name column squeezed the
    // times into a column a few letters wide on the narrow settings page)
    let mut list = v_flex();
    for (i, (label, detail, verdict, usage)) in rows.into_iter().enumerate() {
        list = list.child(
            v_flex()
                .px_4()
                .py_3()
                .gap_1()
                .when(i > 0, |d| d.border_t_1().border_color(p.divider))
                .child(
                    h_flex()
                        .gap_3()
                        .items_center()
                        .child(div().flex_1().min_w_0().text_sm().font_weight(FontWeight::MEDIUM).child(label))
                        .when(!verdict.is_empty(), |d| d.child(div().flex_shrink_0().text_sm().font_weight(FontWeight::SEMIBOLD).text_color(p.accent).child(verdict))),
                )
                .child(div().text_sm().text_color(p.text_secondary).child(detail))
                // what each side cost the machine, under the times
                .when(!usage.is_empty(), |d| d.child(div().text_xs().text_color(p.text_tertiary).child(usage))),
        );
    }
    Some(
        shell(p)
            .child(h_flex().px_4().pt_4().pb_1().child(div().font_weight(FontWeight::SEMIBOLD).child(t!("rustyfiles motorları ve Windows"))))
            .child(list)
            .into_any_element(),
    )
}

fn star_card(p: &Palette, r: &Results) -> AnyElement {
    let line = match speedup(r, OpenTest::Files100k, AppKind::Explorer) {
        Some((ours, theirs)) if theirs > ours => {
            t!("rustyfiles bu bilgisayarda büyük klasörü Dosya Gezgini'nden {x} hızlı açtı.").replace("{x}", &times(theirs, ours))
        }
        _ => t!("Test bitti.").to_string(),
    };
    shell(p)
        .p_4()
        .gap_3()
        .child(
            h_flex()
                .gap_3()
                .items_center()
                .child(Icon::new(L::Star).size(px(20.)).text_color(p.accent))
                .child(
                    v_flex()
                        .flex_1()
                        .min_w_0()
                        .child(div().font_weight(FontWeight::SEMIBOLD).child(line))
                        .child(div().text_sm().text_color(p.text_secondary).child(t!(
                            "rustyfiles ücretsiz ve tek kişinin emeği. Beğendiysen GitHub'da bir yıldız ver: başkalarının da bulmasına yardım eder."
                        ))),
                ),
        )
        // the buttons under the words (beside them they squeezed the sentence into a narrow column)
        .child(
            h_flex()
                .gap_2()
                .flex_wrap()
                .child(button("bench-star", p, L::Star, t!("Yıldız ver"), true, |_, cx| {
                    open_url(REPO.into());
                    settings::update(cx, |s| s.star_asked = true);
                }))
                .child(button("bench-starred", p, L::Check, t!("Verdim"), false, |_, cx| settings::update(cx, |s| s.star_asked = true))),
        )
        .into_any_element()
}

fn share_card(p: &Palette, note_text: Option<String>) -> AnyElement {
    let social = |id: &'static str, label: &'static str, make: fn(&Results, &str) -> String| {
        button(id, p, L::Send, label, false, move |_, cx| with_link(cx, move |r, link, _| open_url(make(r, link))))
    };
    shell(p)
        .p_4()
        .gap_3()
        .child(
            h_flex()
                .gap_3()
                .items_center()
                .child(Icon::new(L::Share2).size(px(20.)).text_color(p.accent))
                .child(
                    v_flex()
                        .flex_1()
                        .min_w_0()
                        .child(div().font_weight(FontWeight::SEMIBOLD).child(t!("Arkadaşlarına öner")))
                        .child(div().text_sm().text_color(p.text_secondary).child(t!("Sonuç kartını paylaş: bilgisayarının özellikleri ve süreler tek bir görselde."))),
                )
                .children(note_text.map(|n| div().text_sm().text_color(p.accent).child(n))),
        )
        .child(
            h_flex()
                .gap_2()
                .flex_wrap()
                .child(button("bench-copy-card", p, L::Image, t!("Kartı kopyala"), true, |w, cx| copy_picture(w, cx)))
                .child(button("bench-save-card", p, L::Download, t!("Kartı kaydet"), false, |_, cx| save_picture(cx)))
                .child(button("bench-copy-text", p, L::Copy, t!("Metni kopyala"), false, |w, cx| copy_text(w, cx)))
                .child(button("bench-copy-link", p, L::Link, t!("Bağlantıyı kopyala"), false, |_, cx| {
                    with_link(cx, |_, link, cx| {
                        cx.write_to_clipboard(ClipboardItem::new_string(link.to_string()));
                        note(t!("Bağlantı kopyalandı"), cx);
                    })
                }))
                .child(social("bench-x", "X", |r, l| format!("https://twitter.com/intent/tweet?text={}&url={}", enc(&headline(r)), enc(l))))
                .child(social("bench-wa", "WhatsApp", |r, l| format!("https://wa.me/?text={}", enc(&format!("{} {}", headline(r), l)))))
                .child(social("bench-reddit", "Reddit", |r, l| format!("https://www.reddit.com/submit?url={}&title={}", enc(l), enc(&headline(r)))))
                .child(social("bench-li", "LinkedIn", |_, l| format!("https://www.linkedin.com/sharing/share-offsite/?url={}", enc(l)))),
        )
        .into_any_element()
}

#[cfg(test)]
mod tests {
    /// Draws the card from the last results on this machine (when there are any) to %TEMP%.
    #[test]
    fn card_renders() {
        for (name, r) in [("rf-bench-card.png", crate::bench::last_results().filter(|r| !r.open.is_empty())), ("rf-bench-card-sample.png", Some(sample()))] {
            let Some(r) = r else { continue };
            let pic = rf_win::bench::render_card(&super::card_svg(&r), 1.0, crate::brand::FONTS).unwrap();
            assert_eq!((pic.width, pic.height), (1200, 675));
            std::fs::write(std::env::temp_dir().join(name), &pic.png).unwrap();
        }
    }

    /// Results with every part of the card filled (numbers of a real run, rounded).
    fn sample() -> crate::bench::Results {
        use crate::bench::{AppRuns, Engines, OpenResults, OpenTest, Results, Versus};
        use rf_win::bench::{AppKind, Machine, OpenResult};
        let run = |ms: f64, mb: u64| OpenResult { settled_ms: ms, private_ws: mb << 20, ..Default::default() };
        let apps = [(AppKind::Rustyfiles, 211.0, 62), (AppKind::Explorer, 1148.0, 87), (AppKind::DoubleCommander, 1395.0, 140), (AppKind::Arke, 358.0, 64), (AppKind::ExplorerPlusPlus, 14913.0, 226)]
            .into_iter()
            .map(|(app, ms, mb)| AppRuns { app, runs: vec![run(ms, mb)], error: None })
            .collect();
        let v = |ours: f64, windows: f64| Some(Versus { ours_ms: Some(ours), windows_ms: Some(windows), ..Default::default() });
        Results {
            when: 0,
            version: "1.0.7".into(),
            machine: Machine { cpu: "AMD Ryzen 7 9800X3D 8-Core Processor".into(), cores: 16, ram_gb: 32, windows: "Windows 11 Pro (26300)".into(), disk: "SSD".into() },
            open: vec![OpenResults { test: OpenTest::Files100k, apps }],
            engines: Engines { copy_small: v(1779.0, 19379.0), unzip: v(3231.0, 26216.0), ..Default::default() },
        }
    }

    #[test]
    fn base64url_matches_the_standard() {
        // RFC 4648 test vectors, url alphabet, no padding
        for (i, o) in [("", ""), ("f", "Zg"), ("fo", "Zm8"), ("foo", "Zm9v"), ("foob", "Zm9vYg"), ("fooba", "Zm9vYmE"), ("foobar", "Zm9vYmFy")] {
            assert_eq!(super::b64url(i.as_bytes()), o);
        }
        assert_eq!(super::b64url(&[0xfb, 0xff]), "-_8");
    }

    #[test]
    fn payload_follows_the_site_format() {
        let Some(r) = crate::bench::last_results() else { return };
        let v = super::share_payload(&r);
        assert_eq!(v["v"], 1);
        assert!(v["pc"]["cpu"].is_string() && v["open"].is_array());
        let link = super::share_link(&r);
        assert!(link.starts_with("https://rustyfiles.com/r/") && link.len() < 2900, "{link}");
    }

    #[test]
    fn counts_get_separators() {
        let c = super::count(2_330_750);
        assert!(c == "2.330.750" || c == "2,330,750", "{c}");
        assert_eq!(super::count(999), "999");
    }
}