A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! search.cpp: a busca. O índice do Spotlight do Shell (%APPDATA%\Shell\indice.db, src\shell\indice.cpp: nomes de tudo
//! na pasta do usuário e nos discos) e a varredura simples pelo nome para o que ele não cobre.
//! O índice do Windows Search (o "Spotlight" do Windows) entra por ADO, como no C++: lá pelo #import do msado15.dll,
//! aqui pela automação (IDispatch) do mesmo ADODB.Connection. Sem o índice (serviço parado), `index` devolve -1 e o
//! "Buscar por" do Leopard (`smart`) usa as datas e as extensões guardadas no índice do Shell.
use std::sync::Mutex;
use comum::ado::{consulta, like_escape};
/// termo para CONTAINS: só letras, números e espaços (o resto quebra a sintaxe)
fn contains_term(q: &str) -> String {
q.chars().filter(|c| c.is_alphanumeric() || *c == ' ').collect::<String>().trim_end().to_string()
}
/// Busca no índice do Windows Search (folder vazio = tudo que está indexado): nome e conteúdo. -1 se não respondeu
pub fn index(q: &str, folder: &str, max: i32, on_path: &mut dyn FnMut(&str) -> bool) -> i32 {
let mut sql = format!("SELECT TOP {max} System.ItemUrl FROM SystemIndex WHERE (System.FileName LIKE '%{}%'", like_escape(q));
let ct = contains_term(q);
if !ct.is_empty() {
sql += &format!(" OR CONTAINS(System.Search.Contents, '\"{ct}*\"')"); // conteúdo, como o Spotlight
}
sql += ")";
if !folder.is_empty() {
let mut f = folder.replace('\\', "/");
if !f.ends_with('/') {
f.push('/');
}
sql += &format!(" AND SCOPE='file:{}'", f.replace('\'', "''"));
}
let mut n = 0;
let mut conta = |p: &str| {
n += 1;
on_path(p)
};
match consulta(&sql, &mut conta) {
Ok(k) => k,
Err(_) if n > 0 => n,
Err(e) => {
if std::env::var("WACOS_DEBUG_BUSCA").is_ok() {
eprintln!("índice: {:08X} {}", e.code().0 as u32, e.message());
}
-1
}
}
}
/// data local (meia-noite de `d` dias atrás) -> texto UTC para o SQL do índice ('AAAA-MM-DD HH:MM:SS')
fn utc_days_ago(d: u64) -> String {
use comum::windows::Win32::Foundation::{FILETIME, SYSTEMTIME};
use comum::windows::Win32::System::Time::*;
unsafe {
let mut st = comum::windows::Win32::System::SystemInformation::GetLocalTime();
st.wHour = 0;
st.wMinute = 0;
st.wSecond = 0;
st.wMilliseconds = 0;
let mut ft = FILETIME::default();
let _ = SystemTimeToFileTime(&st, &mut ft);
let u = ((ft.dwHighDateTime as u64) << 32 | ft.dwLowDateTime as u64) - d * 864_000_000_000;
let ft = FILETIME { dwLowDateTime: u as u32, dwHighDateTime: (u >> 32) as u32 };
let mut lst = SYSTEMTIME::default();
let _ = FileTimeToSystemTime(&ft, &mut lst);
let mut ust = SYSTEMTIME::default();
let _ = TzSpecificLocalTimeToSystemTime(None, &lst, &mut ust);
format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", ust.wYear, ust.wMonth, ust.wDay, ust.wHour, ust.wMinute, ust.wSecond)
}
}
/// "Buscar por" pelo índice do Windows (as mais novas primeiro); -1 se o índice não respondeu
fn smart_index(kind: i32, max: i32, on_path: &mut dyn FnMut(&str) -> bool) -> i32 {
let Ok(prof) = std::env::var("USERPROFILE") else { return -1 };
let mut scope = prof.replace('\\', "/");
if !scope.ends_with('/') {
scope.push('/');
}
let cond = match kind {
0 => format!("System.DateModified >= '{}'", utc_days_ago(0)),
1 => format!("System.DateModified >= '{}' AND System.DateModified < '{}'", utc_days_ago(1), utc_days_ago(0)),
2 => format!("System.DateModified >= '{}'", utc_days_ago(7)),
3 => "System.Kind = 'picture'".into(),
4 => "System.Kind = 'video'".into(),
_ => "System.Kind = 'document'".into(),
};
let sql = format!("SELECT TOP {max} System.ItemUrl FROM SystemIndex WHERE SCOPE='file:{scope}' AND {cond} AND System.ItemType <> 'Directory' AND System.FileAttributes <> 2 ORDER BY System.DateModified DESC");
let mut n = 0;
let mut conta = |p: &str| {
n += 1;
on_path(p)
};
match consulta(&sql, &mut conta) {
Ok(k) => k,
Err(_) if n > 0 => n,
Err(_) => -1,
}
}
/// Varredura pelo nome (subpastas incluídas), para pastas que o índice não cobre.
pub fn walk(q: &str, folder: &str, max: i32, on_path: &mut dyn FnMut(&str) -> bool) -> i32 {
let ql = q.to_lowercase();
let mut n = 0;
let mut stack = vec![folder.to_string()];
while let Some(dir) = stack.pop() {
let Ok(rd) = std::fs::read_dir(&dir) else { continue };
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().to_string();
if name.starts_with('.') {
continue;
}
let Ok(md) = e.metadata() else { continue };
use std::os::windows::fs::MetadataExt;
let at = md.file_attributes();
if at & (0x2 | 0x4) != 0 {
continue; // escondido, sistema
}
let p = e.path().to_string_lossy().to_string();
if name.to_lowercase().contains(&ql) {
n += 1;
if !on_path(&p) || n >= max {
return n;
}
}
if md.is_dir() && at & 0x400 == 0 {
stack.push(p);
}
}
}
n
}
#[repr(C)]
#[derive(Clone, Copy)]
struct Node {
parent: u32,
name: u32,
len: u16,
dir: u16,
mtime: u64,
}
struct Ix {
nodes: Vec<Node>,
names: Vec<u16>,
loaded: std::time::SystemTime,
}
static IX: Mutex<Option<Ix>> = Mutex::new(None);
fn index_file() -> std::path::PathBuf {
std::path::PathBuf::from(std::env::var("APPDATA").unwrap_or_default()).join("Shell\\indice.db")
}
fn load(ix: &mut Option<Ix>) -> bool {
let f = index_file();
let Ok(md) = std::fs::metadata(&f) else { return ix.is_some() };
let mt = md.modified().unwrap_or(std::time::UNIX_EPOCH);
if let Some(i) = ix {
if i.loaded == mt {
return true;
}
}
let Ok(b) = std::fs::read(&f) else { return ix.is_some() };
if b.len() < 24 {
return ix.is_some();
}
let u32_ = |o: usize| u32::from_le_bytes(b[o..o + 4].try_into().unwrap());
let u64_ = |o: usize| u64::from_le_bytes(b[o..o + 8].try_into().unwrap());
let (m, v, n, c) = (u32_(0), u32_(4), u64_(8), u64_(16));
if m != 0x58444E49 || v != 2 || n >= 50_000_000 || c >= 2_000_000_000 {
return ix.is_some();
}
let ns = std::mem::size_of::<Node>();
let need = 24 + n as usize * ns + c as usize * 2;
if b.len() < need {
return ix.is_some();
}
let mut nodes = Vec::with_capacity(n as usize);
for i in 0..n as usize {
let o = 24 + i * ns;
nodes.push(Node { parent: u32_(o), name: u32_(o + 4), len: u16::from_le_bytes([b[o + 8], b[o + 9]]), dir: u16::from_le_bytes([b[o + 10], b[o + 11]]), mtime: u64_(o + 16) });
}
let base = 24 + n as usize * ns;
let names: Vec<u16> = b[base..base + c as usize * 2].chunks_exact(2).map(|x| u16::from_le_bytes([x[0], x[1]])).collect();
*ix = Some(Ix { nodes, names, loaded: mt });
true
}
fn fold(c: u16) -> u16 {
const FROM: &str = "áàâãäéèêëíìîïóòôõöúùûüçñ";
const TO: &str = "aaaaaeeeeiiiiooooouuuucn";
let ch = char::from_u32(c as u32).unwrap_or(' ').to_lowercase().next().unwrap_or(' ');
match FROM.chars().position(|x| x == ch) {
Some(i) => TO.chars().nth(i).unwrap() as u16,
None => {
let mut b = [0u16; 2];
ch.encode_utf16(&mut b);
b[0]
}
}
}
fn path_of(ix: &Ix, id: u32) -> String {
let mut chain = Vec::new();
let mut i = id;
while i != u32::MAX && (i as usize) < ix.nodes.len() {
chain.push(i);
i = ix.nodes[i as usize].parent;
}
let mut p = String::new();
for k in chain.iter().rev() {
if !p.is_empty() {
p.push('\\');
}
let n = ix.nodes[*k as usize];
p += &String::from_utf16_lossy(&ix.names[n.name as usize..n.name as usize + n.len as usize]);
}
p
}
static FOLD: std::sync::OnceLock<Vec<u16>> = std::sync::OnceLock::new();
/// o índice do Spotlight do Shell (nomes de tudo, instantâneo); -1 se não houver índice
pub fn spotlight(q: &str, folder: &str, max: i32, on_path: &mut dyn FnMut(&str) -> bool) -> i32 {
let fq: Vec<u16> = q.trim_end().encode_utf16().map(fold).collect();
if fq.is_empty() {
return -1;
}
let mut g = IX.lock().unwrap();
if !load(&mut g) {
return -1;
}
let ix = g.as_ref().unwrap();
let tab = FOLD.get_or_init(|| (0..65536u32).map(|i| fold(i as u16)).collect());
let mut scope = folder.to_lowercase();
if !scope.is_empty() && !scope.ends_with('\\') {
scope.push('\\');
}
let ql = fq.len();
let mut cands: Vec<(u32, i32, u64)> = Vec::new();
for (i, n) in ix.nodes.iter().enumerate() {
if n.parent == u32::MAX || (n.len as usize) < ql {
continue;
}
let s = &ix.names[n.name as usize..n.name as usize + n.len as usize];
let Some(hit) = s.windows(ql).position(|w| w.iter().zip(&fq).all(|(a, b)| tab[*a as usize] == *b)) else { continue };
let score = if hit == 0 {
if n.len as usize == ql {
120
} else {
100
}
} else if [' ', '-', '_', '.'].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| if a.1 != b.1 { b.1.cmp(&a.1) } else { b.2.cmp(&a.2) });
let mut count = 0;
for c in cands {
let p = path_of(ix, c.0);
if !scope.is_empty() && !p.to_lowercase().starts_with(&scope) {
continue; // busca na pasta: só o que está dentro dela
}
count += 1;
if !on_path(&p) || count >= max {
break;
}
}
count
}
/// "Buscar por" do Finder do Leopard (dentro da pasta do usuário, as mais novas primeiro): 0 Hoje, 1 Ontem,
/// 2 Semana Passada, 3 Todas as Imagens, 4 Todos os Filmes, 5 Todos os Documentos
pub fn smart(kind: i32, max: i32, on_path: &mut dyn FnMut(&str) -> bool) -> i32 {
// primeiro o índice do Windows (como no C++); sem ele, o índice do Shell
let k = smart_index(kind, max, on_path);
if k >= 0 {
return k;
}
let Ok(prof) = std::env::var("USERPROFILE") else { return -1 };
let scope = format!("{}\\", prof.to_lowercase());
let mut g = IX.lock().unwrap();
if !load(&mut g) {
return -1;
}
let ix = g.as_ref().unwrap();
// meia-noite local de hoje em FILETIME
let now = unsafe { comum::windows::Win32::System::SystemInformation::GetSystemTimeAsFileTime() };
let now = (now.dwHighDateTime as u64) << 32 | now.dwLowDateTime as u64;
let day = 864_000_000_000u64;
let off = {
let st = unsafe { comum::windows::Win32::System::SystemInformation::GetLocalTime() };
(st.wHour as u64 * 3600 + st.wMinute as u64 * 60 + st.wSecond as u64) * 10_000_000
};
let today = now - off;
const IMG: [&str; 8] = ["jpg", "jpeg", "png", "gif", "heic", "bmp", "webp", "tiff"];
const VID: [&str; 7] = ["mp4", "mov", "mkv", "avi", "wmv", "webm", "m4v"];
const DOC: [&str; 12] = ["pdf", "doc", "docx", "txt", "rtf", "odt", "xls", "xlsx", "ppt", "pptx", "md", "pages"];
let mut cands: Vec<(u32, u64)> = Vec::new();
for (i, n) in ix.nodes.iter().enumerate() {
if n.dir != 0 || n.parent == u32::MAX {
continue;
}
let ok = match kind {
0 => n.mtime >= today,
1 => n.mtime >= today - day && n.mtime < today,
2 => n.mtime >= today - 7 * day,
_ => {
let s = String::from_utf16_lossy(&ix.names[n.name as usize..n.name as usize + n.len as usize]);
let e = s.rsplit_once('.').map(|x| x.1.to_lowercase()).unwrap_or_default();
match kind {
3 => IMG.contains(&e.as_str()),
4 => VID.contains(&e.as_str()),
_ => DOC.contains(&e.as_str()),
}
}
};
if ok {
cands.push((i as u32, n.mtime));
}
}
cands.sort_by(|a, b| b.1.cmp(&a.1));
let mut count = 0;
for c in cands {
let p = path_of(ix, c.0);
if !p.to_lowercase().starts_with(&scope) {
continue;
}
count += 1;
if !on_path(&p) || count >= max {
break;
}
}
count
}