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
10.1 KB
Raw Blame
//! "Novo Arquivo" (issue #454): os mesmos tipos do Novo do Windows (texto, Word, Excel, PowerPoint, atalho de pasta
//! compactada...), lidos do registro: cada `HKCR\.<ext>` com uma chave `ShellNew` (nela ou na do ProgID dela).
//! O conteúdo do arquivo novo vem dos valores da ShellNew: `NullFile` (vazio), `Data` (os bytes), `FileName` (um
//! modelo, em %WINDIR%\ShellNew ou com caminho). `Command` (que roda um programa) fica de fora.
use crate::{from_w, pc, wz};
use windows::core::PCWSTR;
use windows::Win32::Foundation::*;
use windows::Win32::System::Registry::*;
use windows::Win32::UI::Shell::*;

#[derive(Clone, Debug)]
pub struct Tipo {
    /// ".txt"
    pub ext: String,
    /// o nome do tipo, no idioma do Windows ("Text Document", "Documento do Microsoft Word")
    pub nome: String,
    conteudo: Conteudo,
}
#[derive(Clone, Debug)]
enum Conteudo {
    Vazio,
    Dados(Vec<u8>),
    Modelo(String),
}

fn abre(raiz: HKEY, sub: &str) -> Option<HKEY> {
    let mut k = HKEY::default();
    unsafe { RegOpenKeyExW(raiz, pc(&wz(sub)), 0, KEY_READ, &mut k).is_ok().then_some(k) }
}
fn fecha(k: HKEY) {
    unsafe {
        let _ = RegCloseKey(k);
    }
}
/// (tipo do valor, bytes) de um valor da chave; None = não existe
fn valor(k: HKEY, nome: &str) -> Option<(u32, Vec<u8>)> {
    let n = wz(nome);
    let mut tipo = REG_VALUE_TYPE(0);
    let mut tam = 0u32;
    unsafe {
        if RegQueryValueExW(k, pc(&n), None, Some(&mut tipo), None, Some(&mut tam)).is_err() {
            return None;
        }
        let mut b = vec![0u8; tam as usize];
        if tam > 0 && RegQueryValueExW(k, pc(&n), None, Some(&mut tipo), Some(b.as_mut_ptr()), Some(&mut tam)).is_err() {
            return None;
        }
        b.truncate(tam as usize);
        Some((tipo.0, b))
    }
}
fn texto(b: &[u8]) -> String {
    let w: Vec<u16> = b.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|&c| c != 0).collect();
    String::from_utf16_lossy(&w)
}
fn padrao(raiz: HKEY, sub: &str) -> String {
    let Some(k) = abre(raiz, sub) else { return String::new() };
    let v = valor(k, "").filter(|(t, _)| *t == REG_SZ.0 || *t == REG_EXPAND_SZ.0).map(|(_, b)| texto(&b)).unwrap_or_default();
    fecha(k);
    v
}
/// a ShellNew da extensão: a da própria `.ext`, a de `.ext\<ProgID>` ou a de `.ext\<ProgID>\ShellNew`
fn shellnew(ext: &str) -> Option<Conteudo> {
    let progid = padrao(HKEY_CLASSES_ROOT, ext);
    let mut caminhos = vec![format!("{ext}\\ShellNew")];
    if !progid.is_empty() {
        caminhos.push(format!("{ext}\\{progid}\\ShellNew"));
    }
    for c in caminhos {
        let Some(k) = abre(HKEY_CLASSES_ROOT, &c) else { continue };
        let r = if valor(k, "Command").is_some() && valor(k, "NullFile").is_none() && valor(k, "Data").is_none() && valor(k, "FileName").is_none() {
            None // roda um programa (Porta-arquivos, contato): fica de fora
        } else if valor(k, "NullFile").is_some() {
            Some(Conteudo::Vazio)
        } else if let Some((t, b)) = valor(k, "Data") {
            Some(Conteudo::Dados(if t == REG_SZ.0 { texto(&b).into_bytes() } else { b }))
        } else if let Some((_, b)) = valor(k, "FileName") {
            Some(Conteudo::Modelo(texto(&b)))
        } else {
            None
        };
        fecha(k);
        if r.is_some() {
            return r;
        }
    }
    None
}
fn nome_do_tipo(ext: &str) -> String {
    let mut fi = SHFILEINFOW::default();
    let n = wz(&format!("x{ext}"));
    unsafe {
        SHGetFileInfoW(pc(&n), windows::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL, Some(&mut fi), std::mem::size_of::<SHFILEINFOW>() as u32, SHGFI_TYPENAME | SHGFI_USEFILEATTRIBUTES);
    }
    let nome = fi.szTypeName; // cópia: em 32 bits a SHFILEINFOW é empacotada (referência ao campo não alinha)
    let t = from_w(&nome);
    if t.is_empty() {
        ext.trim_start_matches('.').to_uppercase()
    } else {
        t
    }
}

/// os tipos do Novo, em ordem de nome (lidos uma vez por processo: varrer o HKCR leva algumas dezenas de ms)
pub fn tipos() -> Vec<Tipo> {
    static T: std::sync::OnceLock<Vec<Tipo>> = std::sync::OnceLock::new();
    T.get_or_init(|| {
        let mut v: Vec<Tipo> = Vec::new();
        let mut i = 0u32;
        loop {
            let mut nome = [0u16; 256];
            let mut n = nome.len() as u32;
            let r = unsafe { RegEnumKeyExW(HKEY_CLASSES_ROOT, i, windows::core::PWSTR(nome.as_mut_ptr()), &mut n, None, windows::core::PWSTR::null(), None, None) };
            if r != ERROR_SUCCESS {
                break;
            }
            i += 1;
            let ext = String::from_utf16_lossy(&nome[..n as usize]);
            if !ext.starts_with('.') || ext.len() < 2 {
                continue;
            }
            // .lnk (atalho, abre um assistente) e .library-ms ficam de fora; a pasta já tem o Nova Pasta
            if [".lnk", ".library-ms", ".contact", ".url"].contains(&ext.to_lowercase().as_str()) {
                continue;
            }
            if let Some(c) = shellnew(&ext) {
                v.push(Tipo { nome: nome_do_tipo(&ext), ext, conteudo: c });
            }
        }
        // o documento de texto sempre (limpezas do Windows tiram a ShellNew do .txt, e o Novo ficava sem ele)
        if !v.iter().any(|t| t.ext.eq_ignore_ascii_case(".txt")) {
            v.push(Tipo { nome: nome_do_tipo(".txt"), ext: ".txt".into(), conteudo: Conteudo::Vazio });
        }
        v.sort_by_key(|t| t.nome.to_lowercase());
        v.dedup_by(|a, b| a.ext.eq_ignore_ascii_case(&b.ext));
        v
    })
    .clone()
}

/// lê a lista numa thread de fundo (ao abrir a mesa ou o Finder), para o primeiro clique direito não esperar o registro
pub fn preparar() {
    std::thread::spawn(|| {
        unsafe {
            let _ = windows::Win32::System::Com::CoInitializeEx(None, windows::Win32::System::Com::COINIT_APARTMENTTHREADED);
        }
        let _ = tipos();
    });
}

/// cria o arquivo novo em `pasta` ("<nome do tipo>.ext", ou "... 2.ext" se já existir) e devolve o caminho
pub fn criar(pasta: &str, t: &Tipo) -> Result<String, String> {
    let base = t.nome.replace(['\\', '/', ':', '*', '?', '"', '<', '>', '|'], "");
    let pasta = pasta.trim_end_matches('\\');
    let mut caminho = format!("{pasta}\\{base}{}", t.ext);
    let mut k = 2;
    while std::path::Path::new(&caminho).exists() {
        caminho = format!("{pasta}\\{base} {k}{}", t.ext);
        k += 1;
    }
    let r = match &t.conteudo {
        Conteudo::Vazio => std::fs::write(&caminho, []),
        Conteudo::Dados(b) => std::fs::write(&caminho, b),
        Conteudo::Modelo(m) => {
            let mut exp = [0u16; 520];
            let n = unsafe { windows::Win32::System::Environment::ExpandEnvironmentStringsW(pc(&wz(m)), Some(&mut exp)) } as usize;
            let m = if n > 0 && n <= exp.len() { from_w(&exp[..n - 1]) } else { m.clone() };
            let src = if std::path::Path::new(&m).is_absolute() {
                m
            } else {
                // os modelos ficam em %WINDIR%\ShellNew (ou na pasta de modelos do usuário)
                let w = std::env::var("WINDIR").unwrap_or_else(|_| "C:\\Windows".into());
                let a = format!("{w}\\ShellNew\\{m}");
                let tpl = format!("{}\\Microsoft\\Windows\\Templates\\{m}", std::env::var("APPDATA").unwrap_or_default());
                if std::path::Path::new(&a).exists() {
                    a
                } else {
                    tpl
                }
            };
            std::fs::copy(&src, &caminho).map(|_| ()).or_else(|_| std::fs::write(&caminho, []))
        }
    };
    r.map(|_| {
        let w = wz(&caminho);
        unsafe { SHChangeNotify(SHCNE_CREATE, SHCNF_PATHW | SHCNF_FLUSHNOWAIT, Some(PCWSTR(w.as_ptr()).0 as *const _), None) };
        caminho.clone()
    })
    .map_err(|e| format!("{e}"))
}

/// Fixar pastas no Dock (issue #469) de fora do Shell (Finder): entram no fim do %APPDATA%\Shell\dock-pastas.txt (sem
/// repetir) e o Shell é avisado (ShellDockPastas) para reler. Devolve quantas entraram.
pub fn fixar_no_dock(pastas: &[String]) -> usize {
    let dir = format!("{}\\Shell", std::env::var("APPDATA").unwrap_or_default());
    let _ = std::fs::create_dir_all(&dir);
    let arq = format!("{dir}\\dock-pastas.txt");
    let atual = std::fs::read_to_string(&arq).unwrap_or_default();
    let mut linhas: Vec<String> = atual.trim_start_matches('\u{feff}').lines().map(|l| l.to_string()).filter(|l| !l.trim().is_empty()).collect();
    let mut n = 0;
    for p in pastas {
        let p = p.trim_end_matches('\\').to_string();
        let p = if p.len() == 2 && p.ends_with(':') { format!("{p}\\") } else { p };
        if !std::path::Path::new(&p).is_dir() || linhas.iter().any(|l| l.trim().eq_ignore_ascii_case(&p)) {
            continue;
        }
        linhas.push(p);
        n += 1;
    }
    if n > 0 {
        let s: String = linhas.iter().map(|l| format!("{l}\n")).collect();
        let tmp = format!("{arq}.tmp");
        if std::fs::write(&tmp, format!("\u{feff}{s}")).is_ok() && std::fs::rename(&tmp, &arq).is_err() {
            let _ = std::fs::remove_file(&tmp);
        }
        unsafe {
            use windows::Win32::UI::WindowsAndMessaging::*;
            let msg = RegisterWindowMessageW(windows::core::w!("ShellDockPastas"));
            if let Ok(h) = FindWindowW(windows::core::w!("ShellMensagens"), None) {
                let _ = PostMessageW(h, msg, WPARAM(0), LPARAM(0));
            }
        }
    }
    n
}

#[cfg(test)]
mod teste {
    #[test]
    fn lista_e_cria() {
        let t = super::tipos();
        for x in &t {
            println!("{} {}", x.ext, x.nome);
        }
        assert!(t.iter().any(|x| x.ext.eq_ignore_ascii_case(".txt")), "sem .txt no Novo");
        let dir = std::env::temp_dir().join("wacos-novoarq-teste");
        let _ = std::fs::create_dir_all(&dir);
        let txt = t.iter().find(|x| x.ext.eq_ignore_ascii_case(".txt")).unwrap();
        let a = super::criar(&dir.to_string_lossy(), txt).unwrap();
        let b = super::criar(&dir.to_string_lossy(), txt).unwrap();
        println!("{a}\n{b}");
        assert!(std::path::Path::new(&a).exists() && std::path::Path::new(&b).exists() && a != b);
        let _ = std::fs::remove_dir_all(&dir);
    }
}