Skip to content

armgit / WacOS

Public Imported from GitHub
0

A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.

Rust
30.1 KB
Raw Blame
//! indice.cpp: o índice de arquivos próprio do Shell (para o Spotlight): nomes, pastas e datas de tudo na pasta do
//! usuário (sem a AppData) e nos outros discos fixos (sem as pastas do sistema), em memória e salvo em
//! %APPDATA%\Shell\indice.db (mesmo formato do C++: 'INDX' v2, nós de 24 bytes e os nomes em UTF-16). Ao abrir, o
//! arquivo salvo é lido (busca pronta na hora) e uma varredura nova roda em segundo plano (pulada se o Shell só
//! reiniciou: indice.db.vivo); depois o vigia das pastas relê só as que mudaram. A busca é uma passada na memória.
#![allow(dead_code)]

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::io::{Read, Write};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{OnceLock, RwLock};

use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Storage::FileSystem::*;
use comum::windows::Win32::System::IO::{CancelIo, GetOverlappedResult, OVERLAPPED};
use comum::windows::Win32::System::SystemInformation::{GetSystemTimeAsFileTime, GetTickCount, GetTickCount64};
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::UI::Shell::*;
use comum::*;

use crate::{jogo, log};

const ROOT: u32 = u32::MAX;
const LOCAL: u32 = 0x8000_0000;
const MAGIC: u32 = 0x5844_4E49; // 'INDX'
const VERSION: u32 = 2;

#[repr(C)]
#[derive(Clone, Copy, Default)]
struct Node {
    /// índice do pai (ROOT = raiz: o nome é o caminho inteiro)
    parent: u32,
    /// posição em names
    name: u32,
    len: u16,
    dir: u16,
    /// FILETIME
    mtime: u64,
}
#[derive(Default)]
struct Index {
    nodes: Vec<Node>,
    /// todos os nomes, um atrás do outro
    names: Vec<u16>,
}
pub struct Hit {
    pub path: String,
    pub name: String,
    pub dir: bool,
    pub score: i32,
}

static IDX: RwLock<Index> = RwLock::new(Index { nodes: Vec::new(), names: Vec::new() });
static READY: AtomicBool = AtomicBool::new(false);
static DEAD: AtomicU64 = AtomicU64::new(0);
static ULTIMA_COMPLETA: AtomicU64 = AtomicU64::new(0);
static FILE: OnceLock<String> = OnceLock::new();

fn file() -> &'static str {
    FILE.get().map(|s| s.as_str()).unwrap_or("")
}
fn agora_ft() -> u64 {
    let f = unsafe { GetSystemTimeAsFileTime() };
    ((f.dwHighDateTime as u64) << 32) | f.dwLowDateTime as u64
}
/// tabela caractere → minúscula sem acento (a busca compara por ela, sem guardar uma cópia dos nomes)
fn fold_table() -> &'static [u16] {
    static T: OnceLock<Vec<u16>> = OnceLock::new();
    T.get_or_init(|| {
        let from: Vec<char> = "áàâãäéèêëíìîïóòôõöúùûüçñ".chars().collect();
        let to: Vec<char> = "aaaaaeeeeiiiiooooouuuucn".chars().collect();
        (0..=0xFFFFu32)
            .map(|i| {
                let Some(c) = char::from_u32(i) else { return i as u16 };
                let l = c.to_lowercase().next().unwrap_or(c);
                let l = from.iter().position(|&f| f == l).map(|k| to[k]).unwrap_or(l);
                if (l as u32) <= 0xFFFF {
                    l as u16
                } else {
                    i as u16
                }
            })
            .collect()
    })
}
fn lower(s: &str) -> String {
    s.to_lowercase()
}
fn skip_dir(n: &str, top: bool, profile: bool) -> bool {
    if n.starts_with('.') {
        return true; // .git, .cache, .vscode...
    }
    let eq = |l: &[&str]| l.iter().any(|s| n.eq_ignore_ascii_case(s));
    if eq(&["node_modules", "__pycache__", "$Recycle.Bin", "System Volume Information", "$WinREAgent", "$SysReset", "Config.Msi", "Recovery"]) {
        return true;
    }
    if top && !profile && eq(&["Windows", "Program Files", "Program Files (x86)", "ProgramData", "PerfLogs", "Users", "MSOCache", "Intel", "AMD", "Windows.old", "$WINDOWS.~BT", "$Windows.~WS", "$GetCurrent", "OneDriveTemp", "inetpub", "XboxGames"]) {
        return true;
    }
    top && profile && eq(&["AppData", "MicrosoftEdgeBackups"])
}
fn known(id: &GUID) -> String {
    unsafe {
        match SHGetKnownFolderPath(id, KF_FLAG_DEFAULT, None) {
            Ok(p) => {
                let s = from_w(p.as_wide());
                comum::windows::Win32::System::Com::CoTaskMemFree(Some(p.0 as *const _));
                s
            }
            Err(_) => String::new(),
        }
    }
}
/// raízes: a pasta do usuário e todos os discos fixos; no disco do Windows ficam de fora as pastas do sistema e a Users
fn roots() -> Vec<(String, bool)> {
    let mut r = Vec::new();
    let prof = known(&FOLDERID_Profile);
    if !prof.is_empty() {
        r.push((prof, true));
    }
    let mask = unsafe { GetLogicalDrives() };
    for d in 0..26u32 {
        if mask & (1 << d) == 0 {
            continue;
        }
        let root = format!("{}:\\", (b'A' + d as u8) as char);
        if unsafe { GetDriveTypeW(pc(&wz(&root))) } == 3 {
            // DRIVE_FIXED
            r.push((root[..2].to_string(), false));
        }
    }
    r
}
fn ft(f: &FILETIME) -> u64 {
    ((f.dwHighDateTime as u64) << 32) | f.dwLowDateTime as u64
}
/// filhos de uma pasta, com os filtros da varredura (sem pastas do sistema, junções e as puladas)
fn list(path: &str, top: bool, profile: bool, mut f: impl FnMut(&[u16], bool, u64)) {
    unsafe {
        let mut fd = WIN32_FIND_DATAW::default();
        let Ok(h) = FindFirstFileExW(pc(&wz(&format!("{path}\\*"))), FindExInfoBasic, &mut fd as *mut _ as *mut _, FindExSearchNameMatch, None, FIND_FIRST_EX_LARGE_FETCH) else { return };
        loop {
            let n = fd.cFileName.iter().position(|&c| c == 0).unwrap_or(260);
            let name = &fd.cFileName[..n];
            let dot = name == [b'.' as u16] || name == [b'.' as u16, b'.' as u16];
            let attr = fd.dwFileAttributes;
            let dir = attr & FILE_ATTRIBUTE_DIRECTORY.0 != 0;
            let skip = dot
                || (dir && attr & FILE_ATTRIBUTE_SYSTEM.0 != 0)
                || (dir && attr & FILE_ATTRIBUTE_REPARSE_POINT.0 != 0) // junções (evita voltas)
                || (dir && skip_dir(&String::from_utf16_lossy(name), top, profile));
            if !skip {
                f(name, dir, ft(&fd.ftLastWriteTime));
            }
            if FindNextFileW(h, &mut fd).is_err() {
                break;
            }
        }
        let _ = FindClose(h);
    }
}
fn path_join(p: &str, n: &[u16]) -> String {
    format!("{p}\\{}", String::from_utf16_lossy(n))
}
/// subárvore de `path` no índice `ix`, com os filhos pendurados em `parent_ref`
fn crawl_from(ix: &mut Index, parent_ref: u32, path: &str, top: bool, profile: bool) {
    let mut stack: Vec<(u32, String, bool)> = vec![(parent_ref, path.to_string(), top)];
    while let Some((tid, tpath, ttop)) = stack.pop() {
        list(&tpath, ttop, profile, |n, dir, mt| {
            let id = ix.nodes.len() as u32;
            ix.nodes.push(Node { parent: tid, name: ix.names.len() as u32, len: n.len() as u16, dir: dir as u16, mtime: mt });
            ix.names.extend_from_slice(n);
            if dir {
                stack.push((id | (tid & LOCAL), path_join(&tpath, n), false));
            }
        });
    }
}
fn crawl(ix: &mut Index, root: &str, profile: bool) {
    let root_id = ix.nodes.len() as u32;
    let w_: Vec<u16> = root.encode_utf16().collect();
    ix.nodes.push(Node { parent: ROOT, name: ix.names.len() as u32, len: w_.len() as u16, dir: 1, mtime: 0 });
    ix.names.extend_from_slice(&w_);
    crawl_from(ix, root_id, root, true, profile);
}
fn name_of(ix: &Index, n: &Node) -> String {
    String::from_utf16_lossy(&ix.names[n.name as usize..n.name as usize + n.len as usize])
}
fn path_of(ix: &Index, id: u32) -> String {
    let mut chain = Vec::new();
    let mut i = id;
    while i != ROOT {
        chain.push(i);
        i = ix.nodes[i as usize].parent;
    }
    chain.iter().rev().map(|&k| name_of(ix, &ix.nodes[k as usize])).collect::<Vec<_>>().join("\\")
}
// ---- arquivo salvo: cabeçalho, nós e os nomes
fn save(ix: &Index) {
    if file().is_empty() {
        return;
    }
    let tmp = format!("{}.novo", file());
    let r = (|| -> std::io::Result<()> {
        let mut f = std::io::BufWriter::new(std::fs::File::create(&tmp)?);
        f.write_all(&MAGIC.to_le_bytes())?;
        f.write_all(&VERSION.to_le_bytes())?;
        f.write_all(&(ix.nodes.len() as u64).to_le_bytes())?;
        f.write_all(&(ix.names.len() as u64).to_le_bytes())?;
        let nb = unsafe { std::slice::from_raw_parts(ix.nodes.as_ptr() as *const u8, ix.nodes.len() * std::mem::size_of::<Node>()) };
        f.write_all(nb)?;
        let sb = unsafe { std::slice::from_raw_parts(ix.names.as_ptr() as *const u8, ix.names.len() * 2) };
        f.write_all(sb)?;
        f.flush()
    })();
    if r.is_ok() {
        let _ = std::fs::rename(&tmp, file());
    } else {
        let _ = std::fs::remove_file(&tmp);
    }
}
fn load(ix: &mut Index) -> bool {
    let Ok(mut f) = std::fs::File::open(file()) else { return false };
    let mut h = [0u8; 24];
    if f.read_exact(&mut h).is_err() {
        return false;
    }
    let m = u32::from_le_bytes(h[0..4].try_into().unwrap());
    let v = u32::from_le_bytes(h[4..8].try_into().unwrap());
    let n = u64::from_le_bytes(h[8..16].try_into().unwrap());
    let c = u64::from_le_bytes(h[16..24].try_into().unwrap());
    if m != MAGIC || v != VERSION || n >= 50_000_000 || c >= 2_000_000_000 {
        return false;
    }
    ix.nodes = vec![Node::default(); n as usize];
    ix.names = vec![0u16; c as usize];
    let nb = unsafe { std::slice::from_raw_parts_mut(ix.nodes.as_mut_ptr() as *mut u8, ix.nodes.len() * std::mem::size_of::<Node>()) };
    let sb = unsafe { std::slice::from_raw_parts_mut(ix.names.as_mut_ptr() as *mut u8, ix.names.len() * 2) };
    f.read_exact(nb).is_ok() && f.read_exact(sb).is_ok()
}
fn rebuild() {
    let t0 = unsafe { GetTickCount() };
    let mut ix = Index { nodes: Vec::with_capacity(200_000), names: Vec::new() };
    let mut per_root = String::new();
    for (root, profile) in roots() {
        let before = ix.nodes.len();
        crawl(&mut ix, &root, profile);
        per_root += &format!(" {} {}", if profile { "usuário" } else { &root }, ix.nodes.len() - before);
    }
    let n = ix.nodes.len();
    ix.nodes.shrink_to_fit(); // sem a folga do crescimento
    ix.names.shrink_to_fit();
    save(&ix);
    ULTIMA_COMPLETA.store(agora_ft(), Ordering::Relaxed);
    *IDX.write().unwrap() = ix;
    DEAD.store(0, Ordering::Relaxed);
    READY.store(true, Ordering::Relaxed);
    log!("índice: {n} itens em {} ms ({per_root})", unsafe { GetTickCount() } - t0);
}
// ---- atualização só do que mudou: o aviso diz QUAL pasta mudou; só os filhos dela são relidos e comparados. O que
// sumiu fica apagado (nome vazio: a busca pula); o que é novo entra no fim. A varredura completa só volta para limpar
// (apagados passando de 1/6 do índice), ao ligar/desligar um disco ou se o Windows perder avisos.
fn noise_file(n: &str) -> bool {
    if n.is_empty() || n.starts_with('~') || n.ends_with('~') {
        return true;
    }
    let l = n.to_lowercase();
    [".tmp", ".crdownload", ".part", ".partial", ".download", ".lock", ".swp", ".temp", ".etl"].iter().any(|e| l.len() > e.len() && l.ends_with(e))
}
/// a mudança em `rel` (caminho a partir da raiz) importa para o índice?
fn relevant(rel: &str, profile: bool) -> bool {
    let parts: Vec<&str> = rel.split('\\').collect();
    for (i, comp) in parts.iter().enumerate() {
        let top = i == 0;
        if i + 1 == parts.len() {
            return !noise_file(comp) && !skip_dir(comp, top, profile);
        }
        if comp.is_empty() || skip_dir(comp, top, profile) {
            return false;
        }
    }
    false
}
/// relê os filhos destas pastas e aplica a diferença no índice. false: não deu (refazer tudo)
fn incremental(dirs: &[String]) -> bool {
    let t0 = unsafe { GetTickCount() };
    let rts = roots();
    struct Target {
        id: u32,
        path: String,
        top: bool,
        profile: bool,
    }
    #[derive(Clone, Copy)]
    struct Kid {
        id: u32,
        mtime: u64,
        dir: bool,
    }
    let mut targets: Vec<Target> = Vec::new();
    let mut kids: HashMap<u32, BTreeMap<String, Kid>> = HashMap::new();
    {
        let ix = IDX.read().unwrap();
        let n_ = ix.nodes.len() as u32;
        let mut root_ids: HashMap<String, u32> = HashMap::new();
        for i in 0..n_ {
            let n = &ix.nodes[i as usize];
            if n.parent == ROOT && n.len > 0 {
                root_ids.insert(lower(&name_of(&ix, n)), i);
            }
        }
        for d in dirs {
            let dl = d.to_lowercase();
            let Some((ri, best)) = rts
                .iter()
                .enumerate()
                .filter(|(_, (rp, _))| {
                    let rl = rp.to_lowercase();
                    dl.starts_with(&rl) && (dl.len() == rl.len() || dl.as_bytes()[rl.len()] == b'\\')
                })
                .map(|(i, (rp, _))| (i, rp.len()))
                .max_by_key(|x| x.1)
            else {
                continue;
            };
            let Some(&root_id) = root_ids.get(&lower(&rts[ri].0)) else { return false }; // raiz nova (disco): varredura completa
            let mut cur = root_id;
            let mut cur_path = rts[ri].0.clone();
            if d.len() > best + 1 {
                for comp in d[best + 1..].split('\\') {
                    // desce pelos nomes até onde o índice conhece
                    let cw: Vec<u16> = comp.encode_utf16().collect();
                    let next = ((cur + 1)..n_).find(|&j| {
                        let n = &ix.nodes[j as usize];
                        n.parent == cur && n.dir != 0 && n.len as usize == cw.len() && String::from_utf16_lossy(&ix.names[n.name as usize..n.name as usize + n.len as usize]).eq_ignore_ascii_case(comp)
                    });
                    let Some(next) = next else { break }; // pasta nova: relê a de cima (a nova entra inteira)
                    cur = next;
                    cur_path = format!("{cur_path}\\{comp}");
                }
            }
            if !targets.iter().any(|t| t.id == cur) {
                targets.push(Target { id: cur, path: cur_path, top: ix.nodes[cur as usize].parent == ROOT, profile: rts[ri].1 });
            }
        }
        if targets.is_empty() {
            return true;
        }
        for t in &targets {
            kids.insert(t.id, BTreeMap::new());
        }
        for i in 0..n_ {
            let n = &ix.nodes[i as usize];
            if n.len == 0 || n.parent == ROOT {
                continue;
            }
            if let Some(m) = kids.get_mut(&n.parent) {
                m.insert(lower(&name_of(&ix, n)), Kid { id: i, mtime: n.mtime, dir: n.dir != 0 });
            }
        }
    }
    // sem trava: lê as pastas no disco e monta a diferença
    let mut add = Index::default();
    let mut gone: Vec<u32> = Vec::new();
    let mut touch: Vec<(u32, u64)> = Vec::new();
    for t in &targets {
        let old = kids.get(&t.id).cloned().unwrap_or_default();
        let mut seen = BTreeSet::new();
        list(&t.path, t.top, t.profile, |n, dir, mt| {
            let key = String::from_utf16_lossy(n).to_lowercase();
            seen.insert(key.clone());
            if let Some(k) = old.get(&key) {
                if k.dir == dir {
                    if k.mtime != mt {
                        touch.push((k.id, mt));
                    }
                    return;
                }
                gone.push(k.id); // virou pasta/arquivo
            }
            let id = add.nodes.len() as u32;
            add.nodes.push(Node { parent: t.id, name: add.names.len() as u32, len: n.len() as u16, dir: dir as u16, mtime: mt });
            add.names.extend_from_slice(n);
            if dir {
                crawl_from(&mut add, id | LOCAL, &path_join(&t.path, n), false, t.profile);
            }
        });
        for (k, v) in &old {
            if !seen.contains(k) {
                gone.push(v.id);
            }
        }
    }
    if gone.is_empty() && add.nodes.is_empty() && touch.is_empty() {
        return true;
    }
    let mut ix = IDX.write().unwrap();
    let n_ = ix.nodes.len() as u32;
    let mut dead = 0u64;
    if !gone.is_empty() {
        // apaga a subárvore (o pai sempre vem antes do filho no índice)
        let mut d = vec![false; n_ as usize];
        for &g in &gone {
            if g < n_ {
                d[g as usize] = true;
            }
        }
        for i in 0..n_ as usize {
            let p = ix.nodes[i].parent;
            if !d[i] && p != ROOT && (p as usize) < i && d[p as usize] {
                d[i] = true;
            }
            if d[i] && ix.nodes[i].len > 0 {
                ix.nodes[i].len = 0;
                ix.nodes[i].dir = 0;
                dead += 1;
            }
        }
    }
    for (id, mt) in &touch {
        if *id < n_ {
            ix.nodes[*id as usize].mtime = *mt;
        }
    }
    // cresce só o que entra (com ~1,5% de folga): o push/extend dobrava a capacidade na primeira atualização depois de
    // carregar e os nomes ficavam com 147 MB para 74 usados (medido em 27/11/2026)
    fn crescer<T>(v: &mut Vec<T>, mais: usize) {
        if v.capacity() - v.len() < mais {
            v.reserve_exact(mais + v.len() / 64);
        }
    }
    let (na, nn) = (add.nodes.len(), add.names.len());
    crescer(&mut ix.nodes, na);
    crescer(&mut ix.names, nn);
    let (base, name_base) = (n_, ix.names.len() as u32);
    for mut n in add.nodes.iter().copied() {
        if n.parent != ROOT && n.parent & LOCAL != 0 {
            n.parent = (n.parent & !LOCAL) + base;
        }
        n.name += name_base;
        ix.nodes.push(n);
    }
    ix.names.extend_from_slice(&add.names);
    DEAD.fetch_add(dead, Ordering::Relaxed);
    log!("índice: {} pasta(s) relidas em {} ms (+{}, -{dead})", targets.len(), unsafe { GetTickCount() } - t0, add.nodes.len());
    true
}
// ---- o vigia: as pastas de cima de cada raiz (as que entram no índice)
struct Watch {
    dir: HANDLE,
    ev: HANDLE,
    ov: Box<OVERLAPPED>,
    base: String,
    root: String,
    profile: bool,
    recursive: bool,
    buf: Vec<u8>,
}
fn arm(w_: &mut Watch) -> bool {
    unsafe {
        let _ = ResetEvent(w_.ev);
        *w_.ov = OVERLAPPED { hEvent: w_.ev, ..Default::default() };
        ReadDirectoryChangesW(w_.dir, w_.buf.as_mut_ptr() as *mut _, w_.buf.len() as u32, w_.recursive, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME, None, Some(&mut *w_.ov), None).is_ok()
    }
}
fn make_watches() -> Vec<Watch> {
    let mut ws: Vec<Watch> = Vec::new();
    let add = |ws: &mut Vec<Watch>, path: String, root: &str, profile: bool, rec: bool| {
        if ws.len() >= 64 {
            return; // MAXIMUM_WAIT_OBJECTS
        }
        unsafe {
            let Ok(d) = CreateFileW(pc(&wz(&path)), FILE_LIST_DIRECTORY.0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, None, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, None) else { return };
            let ev = CreateEventW(None, true, false, None).unwrap_or_default();
            let mut w_ = Watch { dir: d, ev, ov: Box::default(), base: path, root: root.to_string(), profile, recursive: rec, buf: vec![0u8; 64 * 1024] };
            if !arm(&mut w_) {
                let _ = CloseHandle(w_.dir);
                let _ = CloseHandle(w_.ev);
                return;
            }
            ws.push(w_);
        }
    };
    for (root, profile) in roots() {
        add(&mut ws, format!("{root}\\"), &root, profile, false); // a própria raiz, sem subpastas
        let Ok(rd) = std::fs::read_dir(format!("{root}\\")) else { continue };
        for e in rd.flatten() {
            let Ok(md) = e.metadata() else { continue };
            use std::os::windows::fs::MetadataExt;
            let a = md.file_attributes();
            if a & FILE_ATTRIBUTE_DIRECTORY.0 == 0 || a & (FILE_ATTRIBUTE_REPARSE_POINT.0 | FILE_ATTRIBUTE_SYSTEM.0) != 0 {
                continue;
            }
            let n = e.file_name().to_string_lossy().to_string();
            if skip_dir(&n, true, profile) {
                continue;
            }
            add(&mut ws, format!("{root}\\{n}"), &root, profile, true);
        }
    }
    ws
}
fn free_watches(ws: &mut Vec<Watch>) {
    for w_ in ws.drain(..) {
        unsafe {
            let _ = CancelIo(w_.dir);
            let _ = CloseHandle(w_.dir);
            let _ = CloseHandle(w_.ev);
        }
    }
}
/// marca de "o Shell estava rodando com o índice em dia" (indice.db.vivo): a última volta do vigia e a última varredura
/// completa (FILETIMEs); sem ela cada reinício varria os ~940 mil itens de todos os discos
fn grava_vivo() {
    let mut b = agora_ft().to_le_bytes().to_vec();
    b.extend_from_slice(&ULTIMA_COMPLETA.load(Ordering::Relaxed).to_le_bytes());
    let _ = std::fs::write(format!("{}.vivo", file()), b);
}
fn le_vivo() -> Option<(u64, u64)> {
    let b = std::fs::read(format!("{}.vivo", file())).ok()?;
    if b.len() < 16 {
        return None;
    }
    Some((u64::from_le_bytes(b[0..8].try_into().ok()?), u64::from_le_bytes(b[8..16].try_into().ok()?)))
}
fn watcher() {
    let mut ws = make_watches();
    let mut drives = unsafe { GetLogicalDrives() };
    let (mut last_change, mut last_build, mut last_save) = (0u32, unsafe { GetTickCount() }, unsafe { GetTickCount() });
    let mut pending: BTreeSet<String> = BTreeSet::new(); // pastas que mudaram (caminho completo)
    let (mut full, mut unsaved) = (false, false);
    let mut vivo_at = 0u32;
    loop {
        let now0 = unsafe { GetTickCount() };
        if vivo_at == 0 || now0.wrapping_sub(vivo_at) > 60000 {
            vivo_at = now0 | 1;
            grava_vivo();
        }
        let evs: Vec<HANDLE> = ws.iter().map(|w_| w_.ev).collect();
        let r = if evs.is_empty() {
            std::thread::sleep(std::time::Duration::from_secs(2));
            WAIT_TIMEOUT.0
        } else {
            unsafe { WaitForMultipleObjects(&evs, false, 2000).0 }
        };
        if (r as usize) < evs.len() {
            let w_ = &mut ws[r as usize];
            let mut got = 0u32;
            if unsafe { GetOverlappedResult(w_.dir, &*w_.ov, &mut got, false) }.is_err() || got == 0 {
                full = true; // estourou: perdeu avisos
            } else {
                let mut off = 0usize;
                loop {
                    let fi = unsafe { &*(w_.buf.as_ptr().add(off) as *const FILE_NOTIFY_INFORMATION) };
                    let nlen = fi.FileNameLength as usize / 2;
                    let rel = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(fi.FileName.as_ptr(), nlen) });
                    let full_path = format!("{}{}{rel}", w_.base, if w_.base.ends_with('\\') { "" } else { "\\" });
                    let from_root = if full_path.len() > w_.root.len() + 1 { full_path[w_.root.len() + 1..].to_string() } else { String::new() };
                    if !from_root.is_empty() && relevant(&from_root, w_.profile) {
                        let mut parent = full_path[..full_path.rfind('\\').unwrap_or(0)].to_string();
                        if parent.len() <= w_.root.len() {
                            parent = w_.root.clone(); // mudou direto na raiz ("C:")
                        }
                        pending.insert(parent);
                        last_change = unsafe { GetTickCount() };
                    }
                    if fi.NextEntryOffset == 0 {
                        break;
                    }
                    off += fi.NextEntryOffset as usize;
                }
            }
            if !arm(w_) {
                full = true;
            }
            continue;
        }
        let (now, d) = unsafe { (GetTickCount(), GetLogicalDrives()) };
        let drives_changed = d != drives;
        let calm = now.wrapping_sub(last_change) > 3000;
        // modo jogo: as pastas ficam anotadas em `pending` e entram quando o jogo fechar
        if jogo::ativo() && !drives_changed {
            continue;
        }
        if drives_changed || (full && calm && now.wrapping_sub(last_build) > 120000) || (!full && !pending.is_empty() && calm) {
            unsafe {
                let _ = SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN); // CPU e disco em prioridade de fundo
            }
            let mut ok = !drives_changed && !full && pending.len() <= 300;
            if ok {
                ok = incremental(&pending.iter().cloned().collect::<Vec<_>>());
                let total = IDX.read().unwrap().nodes.len() as u64;
                if ok && DEAD.load(Ordering::Relaxed) * 6 > total {
                    ok = false; // muito apagado: limpa com a varredura completa
                }
                if ok {
                    unsaved = true;
                }
            }
            if !ok {
                if drives_changed {
                    std::thread::sleep(std::time::Duration::from_secs(3)); // o disco recém-ligado ainda está montando
                }
                rebuild();
                last_build = unsafe { GetTickCount() };
                last_save = last_build;
                unsaved = false;
            }
            unsafe {
                let _ = SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
            }
            pending.clear();
            full = false;
            if drives_changed {
                drives = d;
                free_watches(&mut ws);
                ws = make_watches();
            }
        }
        if unsaved && unsafe { GetTickCount() }.wrapping_sub(last_save) > 10 * 60 * 1000 {
            // o arquivo salvo, no máximo a cada 10 min
            save(&IDX.read().unwrap());
            last_save = unsafe { GetTickCount() };
            unsaved = false;
        }
    }
}
pub fn start() {
    let _ = FILE.set(format!("{}\\Shell\\indice.db", known(&FOLDERID_RoamingAppData)));
    std::thread::spawn(|| {
        unsafe {
            let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
        }
        let mut ix = Index::default();
        let loaded = load(&mut ix);
        if loaded {
            let n = ix.nodes.len();
            *IDX.write().unwrap() = ix;
            READY.store(true, Ordering::Relaxed);
            log!("índice: {n} itens lidos do disco");
            // com o índice salvo a busca já funciona: a varredura nova espera o login assentar
            let t = if unsafe { GetTickCount64() } < 10 * 60 * 1000 { 4 * 60 } else { 30 };
            std::thread::sleep(std::time::Duration::from_secs(t));
        }
        // o Shell só reiniciou (o índice foi gravado há pouco pelo vigia): vai direto para o vigia
        let mut recente = false;
        if loaded {
            let agora = agora_ft();
            let min = 60u64 * 10_000_000;
            if let Some((vivo, completa)) = le_vivo() {
                ULTIMA_COMPLETA.store(completa, Ordering::Relaxed);
                // o vigia estava rodando há menos de 15 min e a última varredura completa tem menos de 24 h
                recente = agora > vivo && agora - vivo < 15 * min && completa != 0 && agora - completa < 24 * 60 * min;
            } else if let Ok(m) = std::fs::metadata(file()) {
                use std::os::windows::fs::MetadataExt;
                let f = m.last_write_time();
                recente = agora > f && agora - f < 15 * min;
            }
        }
        if recente {
            log!("índice: gravado há pouco (o Shell só reiniciou): sem a varredura completa");
        } else {
            while jogo::ativo() {
                std::thread::sleep(std::time::Duration::from_secs(5)); // a varredura da abertura espera o jogo fechar
            }
            unsafe {
                let _ = SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
            }
            rebuild(); // atualiza o que mudou enquanto o Shell estava fechado
            unsafe {
                let _ = SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
            }
        }
        watcher();
    });
}
pub fn ready() -> bool {
    READY.load(Ordering::Relaxed)
}
/// busca pelo nome (`folded`: minúsculas sem acento); nota pelo lugar onde casou, depois os mais recentes
pub fn search(folded: &str, max: usize, cancelled: impl Fn() -> bool, out: &mut Vec<Hit>) {
    if folded.is_empty() || !ready() {
        return;
    }
    let ix = IDX.read().unwrap();
    let q: Vec<u16> = folded.encode_utf16().collect();
    let fold = fold_table();
    let mut cands: Vec<(u32, i32, u64)> = Vec::new();
    for (i, n) in ix.nodes.iter().enumerate() {
        if n.parent == ROOT || (n.len as usize) < q.len() {
            continue;
        }
        if i & 0xFFFF == 0 && cancelled() {
            return;
        }
        let s_ = &ix.names[n.name as usize..n.name as usize + n.len as usize];
        let Some(hit) = s_.windows(q.len()).position(|w_| w_.iter().zip(&q).all(|(a, b)| fold[*a as usize] == *b)) else { continue };
        let score = if hit == 0 {
            if s_.len() == q.len() {
                120
            } else {
                100
            }
        } else if [b' ', b'-', b'_', b'.'].iter().any(|&c| s_[hit - 1] == c as u16) {
            80
        } else {
            50
        };
        cands.push((i as u32, score, n.mtime));
    }
    cands.sort_by(|a, b| b.1.cmp(&a.1).then(b.2.cmp(&a.2)));
    for &(id, score, _) in cands.iter().take(max) {
        let n = &ix.nodes[id as usize];
        out.push(Hit { path: path_of(&ix, id), name: name_of(&ix, n), dir: n.dir != 0, score });
    }
}
pub fn count() -> usize {
    IDX.read().unwrap().nodes.len()
}
/// teste só de leitura (--teste-indice=<termo>): lê o indice.db salvo e busca, sem varrer nem gravar nada
pub fn teste(q: &str) {
    let _ = FILE.set(format!("{}\\Shell\\indice.db", known(&FOLDERID_RoamingAppData)));
    let t0 = unsafe { GetTickCount() };
    let mut ix = Index::default();
    if !load(&mut ix) {
        println!("índice: não deu para ler {}", file());
        return;
    }
    let n = ix.nodes.len();
    *IDX.write().unwrap() = ix;
    READY.store(true, Ordering::Relaxed);
    let t1 = unsafe { GetTickCount() };
    let mut hits = Vec::new();
    let q = q.to_lowercase();
    search(&q, 10, || false, &mut hits);
    println!("índice: {n} itens lidos em {} ms; busca \"{q}\" em {} ms, {} resultados", t1 - t0, unsafe { GetTickCount() } - t1, hits.len());
    for h in hits.iter().take(5) {
        println!("  {} {} ({})", h.score, h.path, if h.dir { "pasta" } else { "arquivo" });
    }
}