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.5 KB
Raw Blame
//! Os comandos do menu "moderno" do Windows 11 (issue #559): apps empacotados (MSIX e pacotes esparsos, como o
//! Malwarebytes, o Terminal, o Bloco de Notas, editores) registram o menu de contexto como IExplorerCommand no
//! AppxManifest (desktop4:FileExplorerContextMenus), e não no IContextMenu clássico que o menu próprio lê. Aqui:
//! o índice (tipo de item → CLSID) lido dos manifestos dos pacotes do usuário uma vez por processo, e os comandos
//! que valem para a seleção (GetState não escondido), com título, prontos para Invoke.

use windows::core::*;
use windows::Win32::Foundation::*;
use windows::Win32::System::Com::*;
use windows::Win32::System::Registry::*;
use windows::Win32::System::SystemInformation::GetTickCount;
use windows::Win32::UI::Shell::*;

use crate::*;

/// um registro do manifesto: tipo ("*", ".md", "directory", "directory\background", "drive") → CLSID
struct Reg {
    tipo: String,
    clsid: GUID,
}
/// um comando pronto para o menu
pub struct Comando {
    pub titulo: String,
    pub cmd: IExplorerCommand,
    pub desativado: bool,
}
/// a seleção em que os comandos agem (tem de viver até o Invoke)
pub struct Modernos {
    pub itens: IShellItemArray,
    pub comandos: Vec<Comando>,
}

thread_local! {
    static CACHE: std::cell::RefCell<std::collections::HashMap<u128, Option<IExplorerCommand>>> = std::cell::RefCell::new(std::collections::HashMap::new());
}
unsafe fn reg_str(k: HKEY, sub: &str, val: &str) -> Option<String> {
    let mut buf = [0u16; 1024];
    let mut cb = (buf.len() * 2) as u32;
    let (s, v) = (wz(sub), wz(val));
    if RegGetValueW(k, pc(&s), pc(&v), RRF_RT_REG_SZ, None, Some(buf.as_mut_ptr() as *mut _), Some(&mut cb)) != ERROR_SUCCESS {
        return None;
    }
    Some(from_w(&buf))
}
/// os valores de um atributo (`nome="..."`) dentro de um trecho de XML
fn atributo(trecho: &str, nome: &str) -> Option<String> {
    let k = trecho.find(&format!("{nome}=\""))? + nome.len() + 2;
    let f = trecho[k..].find('"')?;
    Some(trecho[k..k + f].to_string())
}
/// os registros de FileExplorerContextMenus de um manifesto
fn ler_manifesto(xml: &str, out: &mut Vec<Reg>) {
    // "<x:FileExplorerContextMenus>" ... "</x:FileExplorerContextMenus>": os pedaços ímpares são os conteúdos
    for (k, bloco) in xml.split("FileExplorerContextMenus").enumerate() {
        if k % 2 == 0 {
            continue;
        }
        // cada <x:ItemType Type="..."> com os <x:Verb Id="..." Clsid="..."/>
        for p in bloco.split("ItemType ").skip(1) {
            let Some(tipo) = atributo(p, "Type") else { continue };
            let tipo = tipo.to_lowercase();
            for v in p.split("Verb ").skip(1) {
                if let Some(c) = atributo(v, "Clsid") {
                    // CLSIDFromString (o From<&str> do GUID entra em pânico com texto inválido)
                    let w = wz(&format!("{{{}}}", c.trim_matches(|ch| ch == '{' || ch == '}')));
                    if let Ok(g) = unsafe { CLSIDFromString(pc(&w)) } {
                        out.push(Reg { tipo: tipo.clone(), clsid: g });
                    }
                }
            }
        }
    }
}
/// o índice, lido uma vez por processo (só os manifestos que citam FileExplorerContextMenus)
fn indice() -> &'static Vec<Reg> {
    static I: std::sync::OnceLock<Vec<Reg>> = std::sync::OnceLock::new();
    I.get_or_init(|| unsafe {
        let t0 = GetTickCount();
        let mut out = Vec::new();
        let base = "Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\CurrentVersion\\AppModel\\Repository\\Packages";
        let mut hk = HKEY::default();
        let bw = wz(base);
        if RegOpenKeyExW(HKEY_CURRENT_USER, pc(&bw), 0, KEY_READ, &mut hk) != ERROR_SUCCESS {
            return out;
        }
        let pf = std::env::var("ProgramFiles").unwrap_or("C:\\Program Files".into());
        let mut i = 0u32;
        let mut n_man = 0;
        loop {
            let mut nome = [0u16; 512];
            let mut n = nome.len() as u32;
            if RegEnumKeyExW(hk, i, PWSTR(nome.as_mut_ptr()), &mut n, None, PWSTR::null(), None, None) != ERROR_SUCCESS {
                break;
            }
            i += 1;
            let pacote = String::from_utf16_lossy(&nome[..n as usize]);
            let raiz = reg_str(hk, &pacote, "PackageRootFolder").unwrap_or_default();
            // pacote comum: o manifesto na raiz; pacote esparso (a raiz é a pasta do programa): em WindowsApps
            let mut xml = None;
            for m in [format!("{raiz}\\AppxManifest.xml"), format!("{pf}\\WindowsApps\\{pacote}\\AppxManifest.xml")] {
                if raiz.is_empty() && m.starts_with('\\') {
                    continue;
                }
                if let Ok(b) = std::fs::read(&m) {
                    xml = Some(String::from_utf8_lossy(&b).into_owned());
                    break;
                }
            }
            let Some(xml) = xml else { continue };
            if xml.contains("FileExplorerContextMenus") {
                n_man += 1;
                ler_manifesto(&xml, &mut out);
            }
        }
        let _ = RegCloseKey(hk);
        crate::ctxmenu::log_pub(&format!("menu moderno: {} registros de {n_man} pacotes em {} ms", out.len(), GetTickCount().wrapping_sub(t0)));
        out
    })
}
/// lê o índice antes do primeiro menu (no aquecimento, fora da interface)
pub fn preparar() {
    let _ = indice();
}
/// os tipos que um caminho satisfaz
fn tipos_de(p: &str) -> Vec<String> {
    let path = std::path::Path::new(p);
    if path.is_dir() {
        let mut v = vec!["directory".to_string(), "folder".to_string()];
        if p.len() <= 3 && p.ends_with(":\\") {
            v.push("drive".into());
        }
        return v;
    }
    let mut v = vec!["*".to_string()];
    if let Some(e) = path.extension() {
        v.push(format!(".{}", e.to_string_lossy().to_lowercase()));
    }
    v
}
/// Os comandos modernos que valem para a seleção (`paths` da mesma pasta) ou, vazio, para o fundo de `folder`.
/// `ja_tem`: rótulos já no menu (o mesmo comando registrado nos dois menus aparece uma vez só).
pub fn para(owner: HWND, folder: &str, paths: &[String], ja_tem: &[String]) -> Option<Modernos> {
    let idx = indice();
    if idx.is_empty() {
        return None;
    }
    let t0 = unsafe { GetTickCount() };
    // CLSIDs que valem para todos os itens selecionados
    let mut clsids: Vec<GUID> = Vec::new();
    let conjuntos: Vec<Vec<String>> = if paths.is_empty() { vec![vec!["directory\\background".into()]] } else { paths.iter().map(|p| tipos_de(p)).collect() };
    for r in idx {
        if clsids.contains(&r.clsid) {
            continue;
        }
        let vale = conjuntos.iter().all(|ts| idx.iter().any(|x| x.clsid == r.clsid && ts.contains(&x.tipo)));
        if vale {
            clsids.push(r.clsid);
        }
    }
    if clsids.is_empty() {
        return None;
    }
    let itens: IShellItemArray = unsafe {
        if paths.is_empty() {
            let w = wz(folder);
            let it: IShellItem = SHCreateItemFromParsingName(pc(&w), None).ok()?;
            SHCreateShellItemArrayFromShellItem(&it).ok()?
        } else {
            let d: IDataObject = crate::ctxmenu::get_ui_object(owner, paths).ok()?;
            SHCreateShellItemArrayFromDataObject(&d).ok()?
        }
    };
    let ja: Vec<String> = ja_tem.iter().map(|s| s.to_lowercase()).collect();
    let mut comandos = Vec::new();
    for c in clsids {
        if unsafe { GetTickCount() }.wrapping_sub(t0) > 2500 {
            crate::ctxmenu::log_pub("menu moderno: tempo esgotado, os outros ficam de fora");
            break;
        }
        let t1 = unsafe { GetTickCount() };
        // um objeto por CLSID, guardado na thread (o menu é sempre da thread da janela): abrir o servidor de novo a
        // cada menu custava ~100 ms por app; o que não abre também fica guardado (não tenta de novo)
        let guardado = CACHE.with(|m| m.borrow().get(&c.to_u128()).cloned());
        let cmd = match guardado {
            Some(Some(x)) => x,
            Some(None) => continue,
            None => match unsafe { CoCreateInstance::<_, IExplorerCommand>(&c, None, CLSCTX_LOCAL_SERVER | CLSCTX_INPROC_SERVER) } {
                Ok(x) => {
                    CACHE.with(|m| m.borrow_mut().insert(c.to_u128(), Some(x.clone())));
                    x
                }
                Err(e) => {
                    crate::ctxmenu::log_pub(&format!("menu moderno: {c:?} não abriu (0x{:08X})", e.code().0 as u32));
                    CACHE.with(|m| m.borrow_mut().insert(c.to_u128(), None));
                    continue;
                }
            },
        };
        juntar(&cmd, &itens, &ja, &mut comandos, 0);
        crate::ctxmenu::log_pub(&format!("menu moderno: {c:?} em {} ms", unsafe { GetTickCount() }.wrapping_sub(t1)));
    }
    if comandos.is_empty() {
        return None;
    }
    Some(Modernos { itens, comandos })
}
/// um comando (e, se tiver, os subcomandos, achatados com o título do pai na frente)
fn juntar(cmd: &IExplorerCommand, itens: &IShellItemArray, ja: &[String], out: &mut Vec<Comando>, nivel: i32) {
    unsafe {
        let estado = cmd.GetState(itens, false).unwrap_or(0);
        if estado & ECS_HIDDEN.0 as u32 != 0 {
            return;
        }
        let titulo = match cmd.GetTitle(itens) {
            Ok(p) if !p.is_null() => {
                let s = p.to_string().unwrap_or_default();
                CoTaskMemFree(Some(p.0 as *const _));
                s.replace('&', "")
            }
            _ => String::new(),
        };
        let flags = cmd.GetFlags().unwrap_or(0);
        if flags & ECF_HASSUBCOMMANDS.0 as u32 != 0 && nivel < 2 {
            if let Ok(en) = cmd.EnumSubCommands() {
                let mut subs = Vec::new();
                loop {
                    let mut um = [None];
                    let mut n = 0u32;
                    if en.Next(&mut um, Some(&mut n)).is_err() || n == 0 {
                        break;
                    }
                    if let Some(s) = um[0].take() {
                        juntar(&s, itens, ja, &mut subs, nivel + 1);
                    }
                }
                for mut s in subs {
                    if !titulo.is_empty() {
                        s.titulo = format!("{titulo}: {}", s.titulo);
                    }
                    out.push(s);
                }
            }
            return;
        }
        if titulo.trim().is_empty() || flags & ECF_ISSEPARATOR.0 as u32 != 0 || ja.contains(&titulo.to_lowercase()) {
            return;
        }
        out.push(Comando { titulo, cmd: cmd.clone(), desativado: estado & ECS_DISABLED.0 as u32 != 0 });
    }
}