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.

33.1 KB
Raw Blame
//! Browsing inside archives like folders (Files' "browsable archives"): a path such as
//! `C:\x\photos.zip\2024\summer` lists the archive's `2024/summer` entries. Listings are cached
//! per archive version; opening or copying an item extracts just that item into a new temp
//! folder and uses the real file from there.
//!
//! Every function here touches the disk: call them off the UI thread.

use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use rf_core::{Entry, EntryKind};

use crate::t;

/// Archive types that open like folders (single-stream .gz/.xz/.zst files open normally).
pub fn is_browsable(p: &Path) -> bool {
    let n = lower_name(p);
    ends_with_archive_suffix(&n)
        // first part of a split archive (name.7z.001, name.zip.001…); a bare `name.001` is told by its first bytes (disk access)
        || (n.ends_with(".001") && rf_archive::is_supported(p))
}

const ARCHIVE_SUFFIXES: [&str; 18] =
    [".zip", ".7z", ".tar", ".tar.gz", ".tgz", ".tar.xz", ".txz", ".tar.zst", ".tzst", ".tar.bz2", ".tbz2", ".tbz", ".jar", ".apk", ".nupkg", ".vsix", ".rar", ".iso"];

fn lower_name(p: &Path) -> String {
    p.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default()
}

fn ends_with_archive_suffix(n: &str) -> bool {
    ARCHIVE_SUFFIXES.iter().any(|s| n.ends_with(s))
}

/// [`is_browsable`] from the name alone, for the UI thread: it never opens the file. A bare `name.001` (a split set whose format only
/// the first bytes tell) counts as not browsable here; `name.7z.001` is told by its name.
pub fn is_browsable_by_name(p: &Path) -> bool {
    let n = lower_name(p);
    ends_with_archive_suffix(&n) || n.strip_suffix(".001").is_some_and(ends_with_archive_suffix)
}

/// Whether the name of `p` MAY be that of an archive: [`is_browsable_by_name`] and any `.001`, which only the first bytes can tell.
/// Never opens the file.
pub fn may_be_archive_name(p: &Path) -> bool {
    is_browsable_by_name(p) || lower_name(p).ends_with(".001")
}

/// Whether a change to `name` (a file in the archive's own folder) can have changed the contents of `archive`: the archive file
/// itself, or any volume of a split set (`backup.7z.001`, `backup.7z.002`, …: the first one names the set, the others carry its
/// parts). Pure: the folder view's watcher asks it for every changed name.
pub fn is_change_of(archive: &Path, name: &str) -> bool {
    let a = lower_name(archive);
    let n = name.to_lowercase();
    if n == a {
        return true;
    }
    match a.strip_suffix("001").filter(|p| p.ends_with('.')) {
        Some(prefix) => n.len() == prefix.len() + 3 && n.starts_with(prefix) && n[prefix.len()..].bytes().all(|b| b.is_ascii_digit()),
        None => false,
    }
}

/// WinRAR's Rar.exe (looked up once; RAR creation needs it).
pub fn winrar() -> Option<PathBuf> {
    static EXE: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
    EXE.get_or_init(rf_archive::rar_exe).clone()
}

// ---------- passwords (remembered for this session only, never written to disk) ----------

static PASSWORDS: Mutex<Option<HashMap<PathBuf, String>>> = Mutex::new(None);

pub fn set_password(archive: &Path, pw: Option<String>) {
    {
        let mut g = PASSWORDS.lock().unwrap();
        let m = g.get_or_insert_with(HashMap::new);
        match pw {
            Some(p) => {
                m.insert(archive.to_path_buf(), p);
            }
            None => {
                m.remove(archive);
            }
        }
    }
    // a listing made without the password may be incomplete (7z hides even names)
    if let Some(c) = LISTINGS.lock().unwrap().as_mut() {
        c.remove(archive);
    }
}

pub fn options(archive: &Path) -> rf_archive::Options {
    rf_archive::Options { password: PASSWORDS.lock().unwrap().as_ref().and_then(|m| m.get(archive).cloned()), ..Default::default() }
}

/// Prefix of a listing error that asks for the archive's password.
pub const PASSWORD_MARK: &str = "\u{1}pw:";

/// `Some(true)` = a password was given but is wrong, `Some(false)` = one is needed.
pub fn password_problem(e: &anyhow::Error) -> Option<bool> {
    e.chain().find_map(|c| c.downcast_ref::<rf_archive::PasswordError>()).map(|p| matches!(p, rf_archive::PasswordError::Wrong))
}

/// Before browsing a protected archive: `Some(false)` = a password is needed, `Some(true)` =
/// the remembered one is wrong (and is forgotten), `None` = go ahead. Disk access.
pub fn password_gate(archive: &Path) -> Option<bool> {
    if !rf_archive::needs_password(archive).unwrap_or(false) {
        return None;
    }
    let opts = options(archive);
    if opts.password.is_none() {
        return Some(false);
    }
    match rf_archive::check_password(archive, &opts) {
        Err(e) if password_problem(&e).is_some() => {
            set_password(archive, None);
            Some(true)
        }
        _ => None,
    }
}

/// Needs a password that we don't have yet? (cheap probe; disk access)
pub fn needs_password_now(archive: &Path) -> bool {
    options(archive).password.is_none() && rf_archive::needs_password(archive).unwrap_or(false)
}

/// An operation of ours is rewriting `archive` right now (how many: a paste and a delete of one archive can run at once). A change
/// notice in the middle of one says nothing about what the archive will hold — the file can even be unreadable while it is written —
/// so the folder view's watcher waits for the end of it: [`finish_write`] reads the panes again itself.
static WRITING: Mutex<Option<HashMap<PathBuf, usize>>> = Mutex::new(None);

fn writing(archive: &Path, on: bool) {
    let mut g = WRITING.lock().unwrap();
    let m = g.get_or_insert_with(HashMap::new);
    if on {
        *m.entry(archive.to_path_buf()).or_insert(0) += 1;
    } else if let Some(n) = m.get_mut(archive) {
        *n -= 1;
        if *n == 0 {
            m.remove(archive);
        }
    }
}

/// Whether one of our operations is writing `archive` (the folder view's watcher asks before it reads a change notice as a change).
pub fn is_writing(archive: &Path) -> bool {
    WRITING.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(archive))
}

/// The end of an operation that rewrote `archive`, on the UI thread and however it ended (a cancelled rewrite has changed some of
/// it): the caches are forgotten and every pane showing the archive or a folder in it is read again. No change notice can be waited
/// for there — the panes' path is the archive file's — and the archive's date may not even move.
fn finish_write(archive: &Path, cx: &mut gpui_kit::App) {
    writing(archive, false);
    forget(archive);
    crate::workspace::reread_archive(archive, cx);
}

/// Paste / drop into an archive's folder view: adds `sources` under `inner`.
pub fn add_into(cx: &mut gpui_kit::App, archive: PathBuf, inner: PathBuf, sources: Vec<PathBuf>) {
    let title = format!("{} {} → {}", t!("Arşive ekleniyor:"), crate::i18n::items(sources.len()), rf_core::history::display_name(&archive));
    let inner_dir = inner.to_string_lossy().replace('\\', "/").trim_matches('/').to_string();
    let (started, done) = (archive.clone(), archive);
    crate::status_center::start_with(
        cx,
        title,
        move |t| {
            writing(&started, true);
            let cancel = t.cancel.clone();
            let opts = options(&started);
            let mut prog = crate::status_center::archive_progress_pub(&t);
            match rf_archive::add(&started, &sources, &inner_dir, &opts, &mut prog, &|| cancel.load(std::sync::atomic::Ordering::Relaxed)) {
                Ok(_) => Ok(true),
                Err(e) if e.downcast_ref::<rf_archive::Cancelled>().is_some() => Ok(false),
                Err(e) => Err(e),
            }
        },
        Some(Box::new(move |_, cx| finish_write(&done, cx))),
    );
}

/// F2 inside an archive: renames the entry (a folder renames everything below it).
pub fn rename_inside(cx: &mut gpui_kit::App, archive: PathBuf, inner: String, new_name: String) {
    let title = format!("{} {} → {new_name}", t!("Arşivde yeniden adlandırılıyor:"), inner.rsplit('/').next().unwrap_or_default());
    let (started, done) = (archive.clone(), archive);
    crate::status_center::start_with(
        cx,
        title,
        move |t| {
            writing(&started, true);
            let cancel = t.cancel.clone();
            let opts = options(&started);
            let mut prog = crate::status_center::archive_progress_pub(&t);
            match rf_archive::rename(&started, &inner, &new_name, &opts, &mut prog, &|| cancel.load(std::sync::atomic::Ordering::Relaxed)) {
                Ok(_) => Ok(true),
                Err(e) if e.downcast_ref::<rf_archive::Cancelled>().is_some() => Ok(false),
                Err(e) => Err(e),
            }
        },
        Some(Box::new(move |_, cx| finish_write(&done, cx))),
    );
}

/// "New folder" inside an archive.
pub fn mkdir_inside(cx: &mut gpui_kit::App, archive: PathBuf, inner_dir: String, name: String) {
    let title = format!("{} {name}", t!("Arşivde klasör oluşturuluyor:"));
    let (started, done) = (archive.clone(), archive);
    crate::status_center::start_with(
        cx,
        title,
        move |t| {
            writing(&started, true);
            let cancel = t.cancel.clone();
            let opts = options(&started);
            let mut prog = crate::status_center::archive_progress_pub(&t);
            match rf_archive::create_dir(&started, &inner_dir, &name, &opts, &mut prog, &|| cancel.load(std::sync::atomic::Ordering::Relaxed)) {
                Ok(_) => Ok(true),
                Err(e) if e.downcast_ref::<rf_archive::Cancelled>().is_some() => Ok(false),
                Err(e) => Err(e),
            }
        },
        Some(Box::new(move |_, cx| finish_write(&done, cx))),
    );
}

/// `name`, `name (2)`, … — the first one not among `taken` (case-insensitive).
pub fn unique_name(base: &str, ext: &str, taken: &[String]) -> String {
    let lower: Vec<String> = taken.iter().map(|t| t.to_lowercase()).collect();
    let mut n = 1;
    loop {
        let cand = if n == 1 { format!("{base}{ext}") } else { format!("{base} ({n}){ext}") };
        if !lower.contains(&cand.to_lowercase()) {
            return cand;
        }
        n += 1;
    }
}

/// Delete inside an archive (selection of an archive's folder view).
pub fn delete_inside(cx: &mut gpui_kit::App, archive: PathBuf, inners: Vec<String>) {
    let title = format!("{} {} ← {}", t!("Arşivden siliniyor:"), crate::i18n::items(inners.len()), rf_core::history::display_name(&archive));
    let (started, done) = (archive.clone(), archive);
    crate::status_center::start_with(
        cx,
        title,
        move |t| {
            writing(&started, true);
            let cancel = t.cancel.clone();
            let opts = options(&started);
            let mut prog = crate::status_center::archive_progress_pub(&t);
            match rf_archive::delete(&started, &inners, &opts, &mut prog, &|| cancel.load(std::sync::atomic::Ordering::Relaxed)) {
                Ok(_) => Ok(true),
                Err(e) if e.downcast_ref::<rf_archive::Cancelled>().is_some() => Ok(false),
                Err(e) => Err(e),
            }
        },
        Some(Box::new(move |_, cx| finish_write(&done, cx))),
    );
}

/// Asks for an archive's password; `then` runs once one was entered.
pub fn ask_password(archive: PathBuf, wrong: bool, window: &mut gpui_kit::Window, cx: &mut gpui_kit::App, then: impl Fn(&mut gpui_kit::App) + 'static) {
    use crate::prompt::{Button, Kind};
    let msg = if wrong { t!("Parola yanlış. Tekrar deneyin.") } else { t!("Bu arşiv parola ile korunuyor.") };
    let name = rf_core::history::display_name(&archive);
    crate::prompt::show_secret(
        format!("{} — {name}", t!("Parola")),
        Some(msg.to_string()),
        t!("Parola").to_string(),
        vec![
            Button::new(t!("Tamam"), Kind::Primary, move |text, _, cx| {
                let pw = text.unwrap_or_default();
                if pw.is_empty() {
                    return Err(t!("Parola boş olamaz").to_string());
                }
                set_password(&archive, Some(pw));
                then(cx);
                Ok(())
            }),
            Button::cancel(),
        ],
        window,
        cx,
    );
}

/// Whether some component of `p` is named like an archive (no disk access, except the first bytes of a `.001` file: use
/// [`is_browsable_path_by_name`] on the UI thread).
pub fn is_browsable_path(p: &Path) -> bool {
    p.ancestors().any(is_browsable)
}

/// [`is_browsable_path`] from the names alone: it never opens a file.
pub fn is_browsable_path_by_name(p: &Path) -> bool {
    p.ancestors().any(is_browsable_by_name)
}

/// Splits a path into (archive file, path inside it) when some ancestor is an archive file.
/// A plain folder (or a non-existent path outside any archive) gives `None`.
pub fn split(path: &Path) -> Option<(PathBuf, PathBuf)> {
    // (the disk is asked only when a name in the path looks like an archive: see nav_touch)
    crate::nav_touch::archive_split(&crate::nav_touch::RealDisk, path)
}

/// [`split`] for an item somewhere inside an archive: None for the archive file itself (which
/// splits as its own root, with an empty inner path).
pub fn split_inside(path: &Path) -> Option<(PathBuf, PathBuf)> {
    split(path).filter(|(_, inner)| !inner.as_os_str().is_empty())
}

/// Whether `place` is `archive` itself or a folder inside it, told by the text of the paths (no disk access): the panes showing the
/// archive and its folders are the ones that must be read again when it is rewritten.
pub fn holds(archive: &Path, place: &Path) -> bool {
    let a = rf_core::navtree::norm(archive);
    let p = rf_core::navtree::norm(place);
    p == a || (p.len() > a.len() && p.starts_with(&a) && p.as_bytes()[a.len()] == b'\\')
}

/// For a place inside an archive: the folder whose change notices matter and the archive file itself. A folder inside an archive has
/// no directory handle of its own (its path exists only in the listing), so its own folder watches the archive file instead; a
/// rewrite of that file is what changes what is in it. `None` for a plain folder. Asks the disk: call it off the UI thread.
pub fn watch_plan(path: &Path) -> Option<(PathBuf, PathBuf)> {
    let (archive, _) = split(path)?;
    Some((archive.parent()?.to_path_buf(), archive))
}

type Listing = Arc<Vec<rf_archive::ArchiveEntry>>;

static LISTINGS: Mutex<Option<HashMap<PathBuf, (i64, Listing)>>> = Mutex::new(None);

fn mtime_ms(p: &Path) -> i64 {
    std::fs::metadata(p)
        .and_then(|m| m.modified())
        .ok()
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

fn listing(archive: &Path) -> anyhow::Result<Listing> {
    let m = mtime_ms(archive);
    {
        let g = LISTINGS.lock().unwrap();
        if let Some((t, l)) = g.as_ref().and_then(|c| c.get(archive)) {
            if *t == m {
                return Ok(l.clone());
            }
        }
    }
    let l: Listing = Arc::new(rf_archive::list_with(archive, &options(archive))?);
    let mut g = LISTINGS.lock().unwrap();
    let c = g.get_or_insert_with(HashMap::new);
    if c.len() > 32 {
        c.clear();
    }
    c.insert(archive.to_path_buf(), (m, l.clone()));
    Ok(l)
}

/// Drops what is cached for `archive`: its listing, and the copies of its members extracted for DirectLook and the preview pane. A
/// rewrite of the archive must be read again even when its date did not move (a FAT drive keeps dates to two seconds, and a split
/// set's volumes bring their own), and a copy kept by the old date shows the old bytes.
pub fn forget(archive: &Path) {
    if let Some(c) = LISTINGS.lock().unwrap().as_mut() {
        c.remove(archive);
    }
    if let Some(c) = LOOK_COPIES.lock().unwrap().as_mut() {
        c.retain(|(a, _, _), _| a != archive);
    }
}

/// The entries directly inside `inner` (folders implied by deeper paths included).
pub fn list_inside(archive: &Path, inner: &Path) -> anyhow::Result<Vec<Entry>> {
    let l = listing(archive)?;
    let prefix: String = inner.to_string_lossy().replace('\\', "/").trim_matches('/').to_string();
    let mut out: BTreeMap<String, Entry> = BTreeMap::new();
    for e in l.iter() {
        let p = e.path.replace('\\', "/");
        let p = p.trim_matches('/');
        let rest = if prefix.is_empty() {
            p
        } else if let Some(r) = p.strip_prefix(&prefix).and_then(|r| r.strip_prefix('/')) {
            r
        } else {
            continue;
        };
        if rest.is_empty() {
            continue;
        }
        match rest.split_once('/') {
            // a deeper entry: its first component is a folder here
            Some((dir, _)) => {
                out.entry(dir.to_lowercase()).or_insert_with(|| Entry::new(dir, EntryKind::Dir, 0, e.modified_ms, 0, 0x10));
            }
            None => {
                let kind = if e.is_dir { EntryKind::Dir } else { EntryKind::File };
                // read-only; encrypted members carry the Windows "encrypted" bit (a lock in the list)
                let attrs = if e.is_dir { 0x10 } else { 0x01 | if e.encrypted { rf_core::attrs::ENCRYPTED } else { 0 } };
                out.insert(rest.to_lowercase(), Entry::new(rest, kind, e.size, e.modified_ms, 0, attrs));
            }
        }
    }
    Ok(out.into_values().collect())
}

/// Where items opened or copied out of archives are extracted.
pub(crate) fn temp_root() -> PathBuf {
    std::env::temp_dir().join("rustyfiles-arsiv")
}

/// Extracts the given items (paths inside archives) into a new temp folder per archive and
/// returns where each one landed, in order. Only the selected members are decoded; paths that
/// exist on disk pass through unchanged.
pub fn extract_items(paths: &[PathBuf], cancelled: &dyn Fn() -> bool, progress: &mut dyn FnMut(rf_archive::Progress)) -> anyhow::Result<Vec<PathBuf>> {
    extract_items_max(paths, None, cancelled, progress)
}

/// The most a copy made without the user asking for it (the preview pane, DirectLook following the selection) may write: a member
/// whose stream is far bigger than its header says is stopped there (a private security report: such a copy could fill TEMP).
const AUTO_COPY_MAX: u64 = PREVIEW_EXTRACT_RESTED_MAX + (64 << 20);

/// [`extract_items`] with a limit on the bytes written (see `rf_archive::Options::max_bytes`).
pub fn extract_items_max(paths: &[PathBuf], max_bytes: Option<u64>, cancelled: &dyn Fn() -> bool, progress: &mut dyn FnMut(rf_archive::Progress)) -> anyhow::Result<Vec<PathBuf>> {
    let mut out: Vec<PathBuf> = paths.to_vec();
    // archive → (indexes into `paths`, inner paths)
    let mut groups: Vec<(PathBuf, Vec<usize>, Vec<PathBuf>)> = Vec::new();
    for (i, p) in paths.iter().enumerate() {
        if p.exists() {
            continue;
        }
        let Some((a, inner)) = split(p) else { continue };
        match groups.iter_mut().find(|g| g.0 == a) {
            Some(g) => {
                g.1.push(i);
                g.2.push(inner);
            }
            None => groups.push((a, vec![i], vec![inner])),
        }
    }
    static SERIAL: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
    for (archive, idx, inners) in groups {
        let stem = archive.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
        let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0);
        let n = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let dir = temp_root().join(format!("{stem}-{stamp:x}{n}"));
        let mut opts = options(&archive);
        opts.only = inners.iter().map(|p| p.to_string_lossy().replace('\\', "/")).collect();
        opts.max_bytes = max_bytes;
        if let Err(e) = rf_archive::extract_with(&archive, &dir, &opts, progress, cancelled) {
            let _ = std::fs::remove_dir_all(&dir);
            return Err(e);
        }
        for (i, inner) in idx.into_iter().zip(inners) {
            let p = dir.join(&inner);
            if !p.exists() {
                let _ = std::fs::remove_dir_all(&dir);
                anyhow::bail!("{}: {}", t!("Arşivde bulunamadı"), inner.display());
            }
            out[i] = p;
        }
    }
    Ok(out)
}

/// Deletes extraction folders older than two days (an app may still have a newer one open).
pub fn clean_temp() {
    let Ok(rd) = std::fs::read_dir(temp_root()) else { return };
    let old = std::time::Duration::from_secs(2 * 24 * 3600);
    for e in rd.flatten() {
        let Ok(m) = e.metadata() else { continue };
        let age = m.created().or_else(|_| m.modified()).ok().and_then(|t| t.elapsed().ok());
        if m.is_dir() && age.is_some_and(|a| a > old) {
            let _ = std::fs::remove_dir_all(e.path());
        }
    }
}

/// Opens items inside archives: extracts just them (Status Center shows progress and errors),
/// then opens each with its default app.
pub fn open_items(cx: &mut gpui_kit::App, paths: Vec<PathBuf>) {
    if paths.is_empty() {
        return;
    }
    let title = format!("{} {}", t!("Arşivden açılıyor:"), names(&paths));
    crate::status_center::start(cx, title, move |t| {
        let cancel = t.cancel.clone();
        let mut prog = crate::status_center::archive_progress_pub(&t);
        let real = match extract_items(&paths, &|| cancel.load(std::sync::atomic::Ordering::Relaxed), &mut prog) {
            Ok(r) => r,
            Err(e) if e.downcast_ref::<rf_archive::Cancelled>().is_some() => return Ok(false),
            Err(e) => return Err(e),
        };
        for p in real {
            rf_win::openrules::open(&p)?;
        }
        Ok(true)
    });
}

/// Ctrl+C on items inside an archive: the clipboard is emptied at once (a quick paste must not
/// paste what was there before), the items are extracted, then the copies go on the clipboard
/// unless something else was copied meanwhile. Cut copies: the archive is left as it is.
pub fn copy_items(cx: &mut gpui_kit::App, paths: Vec<PathBuf>) {
    if paths.is_empty() {
        return;
    }
    let (tx, rx) = std::sync::mpsc::channel();
    rf_win::sta::run(move |owner| {
        if let Err(e) = rf_win::clipboard::clear(owner) {
            log::warn!("clipboard: {e:#}");
        }
        let _ = tx.send(rf_win::clipboard::sequence());
    });
    let title = format!("{} {}", t!("Arşivden kopyalanıyor:"), names(&paths));
    crate::status_center::start(cx, title, move |t| {
        let seq = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap_or(0);
        let cancel = t.cancel.clone();
        let mut prog = crate::status_center::archive_progress_pub(&t);
        let real = match extract_items(&paths, &|| cancel.load(std::sync::atomic::Ordering::Relaxed), &mut prog) {
            Ok(r) => r,
            Err(e) if e.downcast_ref::<rf_archive::Cancelled>().is_some() => return Ok(false),
            Err(e) => return Err(e),
        };
        if rf_win::clipboard::sequence() != seq {
            // the user copied something else in the meantime: keep that
            return Ok(true);
        }
        let (tx, rx) = std::sync::mpsc::channel();
        rf_win::sta::run(move |owner| {
            let _ = tx.send(rf_win::clipboard::set_files(owner, &real, rf_win::fileops::Transfer::Copy));
        });
        rx.recv().map_err(|_| anyhow::anyhow!("pano"))??;
        Ok(true)
    });
}

/// Copies extracted for DirectLook: (archive, mtime, inner) → file. Moving through an archive
/// with the arrow keys must not extract the same member again and again.
static LOOK_COPIES: Mutex<Option<HashMap<(PathBuf, i64, PathBuf), PathBuf>>> = Mutex::new(None);

/// Members bigger than this are not extracted just because the selection passed over them.
const LOOK_FOLLOW_MAX: u64 = 64 << 20;

/// Sends a DirectLook message for `path`. An item inside an archive is extracted first (in the
/// background) and DirectLook gets the real file; `follow` (selection moved) skips big members.
pub fn look_send(path: PathBuf, size: u64, follow: bool) {
    use crate::look::ipc::{Msg, send};
    let msg = move |p: PathBuf| if follow { Msg::Follow(p) } else { Msg::Toggle(p) };
    if path.exists() || split(&path).is_none() {
        send(msg(path), !follow);
        return;
    }
    if follow && size > LOOK_FOLLOW_MAX {
        return;
    }
    std::thread::spawn(move || {
        if let Some(real) = real_copy(&path) {
            send(msg(real), !follow);
        }
    });
}

/// A real file for an item inside an archive: extracted once (blocking), then reused while the
/// archive is unchanged. `None` when it isn't in an archive or can't be extracted.
pub fn real_copy(path: &Path) -> Option<PathBuf> {
    real_copy_with(path, &|| false)
}

/// [`real_copy`] that can be given up part way: `cancelled` is asked while the member is decoded (the partial file is removed).
pub fn real_copy_with(path: &Path, cancelled: &dyn Fn() -> bool) -> Option<PathBuf> {
    let (archive, inner) = split(path)?;
    let key = (archive.clone(), mtime_ms(&archive), inner);
    if let Some(p) = LOOK_COPIES.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()).filter(|p| p.exists()) {
        return Some(p);
    }
    match extract_items_max(&[path.to_path_buf()], Some(AUTO_COPY_MAX), cancelled, &mut |_| {}) {
        Ok(mut v) => {
            let p = v.pop()?;
            let mut g = LOOK_COPIES.lock().unwrap();
            let m = g.get_or_insert_with(HashMap::new);
            if m.len() > 256 {
                m.clear();
            }
            m.insert(key, p.clone());
            Some(p)
        }
        Err(e) if e.downcast_ref::<rf_archive::Cancelled>().is_some() => None,
        Err(e) => {
            log::warn!("archive item {path:?}: {e:#}");
            None
        }
    }
}

/// Members up to this size are extracted for the preview pane as the selection moves.
pub const PREVIEW_EXTRACT_MAX: u64 = LOOK_FOLLOW_MAX;

/// Bigger members, up to this size, are extracted for the pane once the selection has rested on them.
pub const PREVIEW_EXTRACT_RESTED_MAX: u64 = 1 << 30;

/// How long the selection must rest on a big member before the pane extracts it.
pub const PREVIEW_REST: std::time::Duration = std::time::Duration::from_millis(600);

/// When the preview pane extracts a member of an archive to show it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PaneCopy {
    /// As soon as it is selected.
    AtOnce,
    /// Once the selection has rested on it for [`PREVIEW_REST`]; given up when the selection moves on.
    Rested,
    /// Only when the user asks for it (Play).
    Asked,
}

/// The rule for a member of `size` bytes.
///
/// WHY (rustyfiles Discord, 2026-11-24: "large image files (>64MB) inside archives" showed in DirectLook and not in the pane): the
/// pane took nothing over 64 MB, so that arrow-keying through an archive did not decode every big member on the way. Resting on
/// one is not passing over it. A very big one is still left alone: its copy would fill the temp folder for a glance.
pub fn pane_copy(size: u64) -> PaneCopy {
    if size <= PREVIEW_EXTRACT_MAX {
        PaneCopy::AtOnce
    } else if size <= PREVIEW_EXTRACT_RESTED_MAX {
        PaneCopy::Rested
    } else {
        PaneCopy::Asked
    }
}

/// "a.txt" or "3 öğe" for a title.
fn names(paths: &[PathBuf]) -> String {
    match paths {
        [one] => one.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
        _ => crate::i18n::items(paths.len()),
    }
}

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

    #[test]
    fn the_pane_extracts_small_members_at_once_big_ones_after_a_rest_and_huge_ones_only_when_asked() {
        assert_eq!(pane_copy(0), PaneCopy::AtOnce);
        assert_eq!(pane_copy(64 << 20), PaneCopy::AtOnce);
        assert_eq!(pane_copy((64 << 20) + 1), PaneCopy::Rested);
        assert_eq!(pane_copy(1 << 30), PaneCopy::Rested);
        assert_eq!(pane_copy((1 << 30) + 1), PaneCopy::Asked);
    }

    /// A pane in the archive or in a folder of it is found again after a rewrite; one on a folder that only begins the same is not.
    #[test]
    fn a_place_in_an_archive_is_told_from_one_that_only_begins_the_same() {
        let zip = Path::new(r"C:\data\paket.zip");
        assert!(holds(zip, zip));
        assert!(holds(zip, Path::new(r"c:\DATA\paket.zip\in\alt")));
        assert!(!holds(zip, Path::new(r"C:\data\paket.zip2")));
        assert!(!holds(zip, Path::new(r"C:\data\paket")));
    }

    /// A change of the archive file, or of any volume of a split set, is a change of its contents; a lookalike name is not.
    #[test]
    fn a_change_of_the_archive_or_any_volume_of_its_split_set_is_told() {
        let zip = Path::new(r"C:\data\p.zip");
        assert!(is_change_of(zip, "P.ZIP"));
        assert!(!is_change_of(zip, "p.zip.part"));
        let set = Path::new(r"C:\data\p.7z.001");
        assert!(is_change_of(set, "p.7z.001"));
        assert!(is_change_of(set, "p.7z.002"));
        assert!(!is_change_of(set, "p.7z.01"));
        assert!(!is_change_of(set, "p.7z.0001"));
        assert!(!is_change_of(set, "p.7z.002.tmp"));
    }

    /// A rewrite that keeps the archive's date (a FAT drive's dates are two seconds coarse) must still be read again: an operation
    /// forgets the cached listing instead of trusting the date.
    #[test]
    fn forgetting_an_archive_drops_the_listing_it_cached() {
        let base = std::env::temp_dir().join(format!("rf-av-forget-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).unwrap();
        let one = base.join("bir.txt");
        std::fs::write(&one, b"1").unwrap();
        let zip = base.join("p.zip");
        rf_archive::compress(&[one], &zip, rf_archive::Format::Zip, 5, &mut |_| {}, &|| false).unwrap();
        let names = |es: Vec<Entry>| es.into_iter().map(|e| e.name.to_string()).collect::<Vec<_>>();
        assert_eq!(names(list_inside(&zip, Path::new("")).unwrap()), ["bir.txt"]);
        let date = std::fs::metadata(&zip).unwrap().modified().unwrap();
        let two = base.join("iki.txt");
        std::fs::write(&two, b"2").unwrap();
        rf_archive::add(&zip, &[two], "", &rf_archive::Options::default(), &mut |_| {}, &|| false).unwrap();
        // back to the date the first listing was kept by
        std::fs::OpenOptions::new().write(true).open(&zip).unwrap().set_times(std::fs::FileTimes::new().set_modified(date)).unwrap();
        assert_eq!(names(list_inside(&zip, Path::new("")).unwrap()), ["bir.txt"], "the date says nothing has changed");
        forget(&zip);
        assert_eq!(names(list_inside(&zip, Path::new("")).unwrap()), ["bir.txt", "iki.txt"]);
        std::fs::remove_dir_all(&base).unwrap();
    }

    /// #11: a .zip file itself is not an item inside an archive (deleting it asked to delete ""
    /// from inside it); its entries are.
    #[test]
    fn an_archive_is_not_inside_itself() {
        let dir = std::env::temp_dir().join(format!("rf-av-inside-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let zip = dir.join("paket.zip");
        // an empty ZIP (its end record): the path rules look at the name and that it is a file
        let mut eocd = b"PK".to_vec();
        eocd.resize(22, 0);
        std::fs::write(&zip, eocd).unwrap();
        assert!(split(&zip).is_some_and(|(_, inner)| inner.as_os_str().is_empty()), "the root still splits");
        assert_eq!(split_inside(&zip), None);
        assert_eq!(split_inside(&zip.join("a.txt")), Some((zip.clone(), PathBuf::from("a.txt"))));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn extracts_just_the_items_asked_for() {
        let base = std::env::temp_dir().join(format!("rf-av-items-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let src = base.join("proje");
        std::fs::create_dir_all(src.join("alt")).unwrap();
        std::fs::write(src.join("a.txt"), b"a").unwrap();
        std::fs::write(src.join("alt").join("b.txt"), b"bbb").unwrap();
        std::fs::write(src.join("buyuk.bin"), vec![7u8; 300_000]).unwrap();
        let zip = base.join("arsiv.zip");
        rf_archive::compress(&[src.clone()], &zip, rf_archive::Format::Zip, 5, &mut |_| {}, &|| false).unwrap();

        let outside = base.join("dis.txt");
        std::fs::write(&outside, b"x").unwrap();
        let asked = vec![zip.join("proje").join("alt").join("b.txt"), outside.clone(), zip.join("proje").join("a.txt")];
        let got = extract_items(&asked, &|| false, &mut |_| {}).unwrap();
        assert_eq!(std::fs::read(&got[0]).unwrap(), b"bbb");
        assert_eq!(got[1], outside); // real files pass through
        assert_eq!(std::fs::read(&got[2]).unwrap(), b"a");
        // one folder for the archive, without the member nobody asked for
        let root = got[0].parent().unwrap().parent().unwrap().parent().unwrap();
        assert_eq!(got[2].parent().unwrap().parent().unwrap(), root);
        assert!(!root.join("proje").join("buyuk.bin").exists());

        // asking again gives a fresh copy (the first may be open in an app)
        let again = extract_items(&asked[..1], &|| false, &mut |_| {}).unwrap();
        assert_ne!(again[0], got[0]);
        assert!(extract_items(&[zip.join("yok.txt")], &|| false, &mut |_| {}).is_err());

        for p in [root.to_path_buf(), again[0].parent().unwrap().parent().unwrap().parent().unwrap().to_path_buf()] {
            let _ = std::fs::remove_dir_all(p);
        }
        let _ = std::fs::remove_dir_all(&base);
    }
}