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
9.0 KB
Raw Blame
//! pastas.cpp: pastas no Finder, venham de onde vierem ("Mostrar na pasta" do Chrome, "abrir pasta" de outros apps
//! chamam o Explorador direto). A janela de pasta do Explorador (CabinetWClass) fica invisível ao nascer, a pasta e a
//! seleção são lidas dela (IShellWindows) e ela é trocada pelo Finder no mesmo lugar; pastas que não são de disco
//! (Lixeira, Painel de Controle, .zip, rede) voltam a aparecer no Explorador. Ajuste finder_padrao.

use std::sync::atomic::{AtomicIsize, Ordering};

use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::UI::Accessibility::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

use crate::{log, shell};

static HOOK: AtomicIsize = AtomicIsize::new(0);

fn on() -> bool {
    shell::setting("finder_padrao", "1") == "1"
}
/// pasta, seleção e se é do disco, de uma janela do Explorador (None: não achou a janela)
fn read(h: HWND) -> Option<(String, Vec<String>, bool)> {
    unsafe {
        let sw: IShellWindows = CoCreateInstance(&ShellWindows, None, CLSCTX_ALL).ok()?;
        let n = sw.Count().ok()?;
        for i in 0..n {
            let Ok(d) = sw.Item(&VARIANT::from(i)) else { continue };
            let Ok(wb) = d.cast::<IWebBrowserApp>() else { continue };
            if wb.HWND().ok().map(|x| x.0 as isize) != Some(h.0 as isize) {
                continue;
            }
            let (mut folder, mut sel, mut fs) = (String::new(), Vec::new(), false);
            let r = (|| -> Result<()> {
                let sp: IServiceProvider = wb.cast()?;
                let sb: IShellBrowser = sp.QueryService(&SID_STopLevelBrowser)?;
                let fv: IFolderView = sb.QueryActiveShellView()?.cast()?;
                if let Ok(pf) = fv.GetFolder::<IPersistFolder2>() {
                    if let Ok(pidl) = pf.GetCurFolder() {
                        let mut path = [0u16; 260];
                        fs = SHGetPathFromIDListW(pidl, &mut path).as_bool();
                        folder = from_w(&path);
                        if !fs {
                            // pasta virtual: o nome dela (::{CLSID})
                            if let Ok(pn) = SHGetNameFromIDList(pidl, SIGDN_DESKTOPABSOLUTEPARSING) {
                                folder = from_w(pn.as_wide());
                                CoTaskMemFree(Some(pn.0 as *const _));
                            }
                        }
                        CoTaskMemFree(Some(pidl as *const _));
                    }
                }
                if let Ok(items) = fv.Items::<IShellItemArray>(SVGIO_SELECTION) {
                    for k in 0..items.GetCount()?.min(64) {
                        if let Ok(p) = items.GetItemAt(k).and_then(|it| it.GetDisplayName(SIGDN_FILESYSPATH)) {
                            sel.push(from_w(p.as_wide()));
                            CoTaskMemFree(Some(p.0 as *const _));
                        }
                    }
                }
                Ok(())
            })();
            let _ = r;
            return Some((folder, sel, fs));
        }
        None
    }
}
/// a janela do Explorador fica invisível (transparente e fora da tela) em vez de escondida: escondida, a frente voltava
/// para quem pediu e o Finder abria atrás
fn invisivel(h: HWND, on_: bool) {
    unsafe {
        let ex = GetWindowLongPtrW(h, GWL_EXSTYLE);
        if on_ {
            SetWindowLongPtrW(h, GWL_EXSTYLE, ex | WS_EX_LAYERED.0 as isize);
            let _ = SetLayeredWindowAttributes(h, COLORREF(0), 0, LWA_ALPHA);
            let mut r = RECT::default();
            let _ = GetWindowRect(h, &mut r);
            let _ = SetPropW(h, w!("ShellPastaX"), HANDLE(r.left as isize as *mut _));
            let _ = SetPropW(h, w!("ShellPastaY"), HANDLE(r.top as isize as *mut _));
            let _ = SetWindowPos(h, None, -32000, -32000, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS);
        } else {
            let (x, y) = (GetPropW(h, w!("ShellPastaX")).0 as isize as i32, GetPropW(h, w!("ShellPastaY")).0 as isize as i32);
            if x != 0 || y != 0 {
                let _ = SetWindowPos(h, None, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS);
            }
            let _ = SetLayeredWindowAttributes(h, COLORREF(0), 255, LWA_ALPHA);
            SetWindowLongPtrW(h, GWL_EXSTYLE, ex & !(WS_EX_LAYERED.0 as isize));
        }
    }
}
/// janelas do Finder visíveis agora (para saber quando a nova apareceu)
fn finders() -> Vec<isize> {
    let mut v = Vec::new();
    unsafe {
        let mut o = FindWindowW(w!("ArquivosJanela"), None).unwrap_or_default();
        while !o.0.is_null() {
            if IsWindowVisible(o).as_bool() {
                v.push(o.0 as isize);
            }
            o = FindWindowExW(None, o, w!("ArquivosJanela"), None).unwrap_or_default();
        }
    }
    v
}
fn handle(hv: isize) {
    std::thread::spawn(move || unsafe {
        let h = HWND(hv as *mut _);
        let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
        let (mut folder, mut sel, mut fs, mut found) = (String::new(), Vec::new(), false, false);
        // a pasta e a seleção (do /select) chegam um instante depois da janela aparecer
        for t in 0..30 {
            if !IsWindow(h).as_bool() {
                break;
            }
            if let Some((f, s, x)) = read(h) {
                (folder, sel, fs, found) = (f, s, x, true);
                if !folder.is_empty() && (!sel.is_empty() || t >= 8) {
                    break;
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        let ok = found && fs && std::path::Path::new(&folder).is_dir();
        if !ok {
            // não é pasta de disco: fica com o Explorador
            if IsWindow(h).as_bool() {
                invisivel(h, false);
                let _ = ShowWindowAsync(h, SW_SHOWNORMAL);
            }
            log!("pastas: deixei no Explorador ({})", if folder.is_empty() { "pasta especial" } else { &folder });
            CoUninitialize();
            return;
        }
        let arg = if sel.len() == 1 { sel[0].clone() } else { folder.clone() }; // um item: o Finder abre com ele marcado
        let antes = finders();
        let _ = AllowSetForegroundWindow(ASFW_ANY);
        shell::abrir(Some("open"), &format!("{}\\{}", shell::dir(), nomes::EXE_FINDER), &format!("\"{arg}\""), "", SW_SHOWNORMAL);
        let mut novo = 0isize;
        for _ in 0..60 {
            // até 3 s
            std::thread::sleep(std::time::Duration::from_millis(50));
            if let Some(f) = finders().into_iter().find(|f| !antes.contains(f)) {
                novo = f;
                break;
            }
        }
        // só fecha o Explorador depois que o Finder pegou a frente (ele a pega do Explorador, que a segura)
        let mut t = 0;
        while novo != 0 && t < 30 && GetForegroundWindow().0 as isize != novo {
            std::thread::sleep(std::time::Duration::from_millis(50));
            t += 1;
        }
        if IsWindow(h).as_bool() {
            let _ = ShowWindowAsync(h, SW_HIDE);
            let _ = PostMessageW(h, WM_CLOSE, WPARAM(0), LPARAM(0));
        }
        log!("pastas: Explorador trocado pelo Finder ({arg}); Finder {}, na frente: {}", if novo != 0 { "apareceu" } else { "NÃO apareceu em 3 s" }, shell::class_name(GetForegroundWindow()));
        CoUninitialize();
    });
}
unsafe extern "system" fn on_show(_: HWINEVENTHOOK, ev: u32, h: HWND, obj: i32, child: i32, _: u32, _: u32) {
    if ev == EVENT_OBJECT_DESTROY || obj != OBJID_WINDOW.0 || child != CHILDID_SELF as i32 || h.0.is_null() || !on() {
        return;
    }
    if shell::class_name(h) != "CabinetWClass" || GetAncestor(h, GA_ROOT) != h || !GetPropW(h, w!("ShellPastaVista")).is_invalid() {
        return; // já olhada (ficou no Explorador de propósito)
    }
    if !std::path::Path::new(&format!("{}\\{}", shell::dir(), nomes::EXE_FINDER)).exists() {
        return; // sem o Finder: nada a fazer
    }
    // ao ser criada (antes de aparecer) já fica invisível: sem o quadro do Explorador piscando
    if GetPropW(h, w!("ShellPastaInvisivel")).is_invalid() {
        let _ = SetPropW(h, w!("ShellPastaInvisivel"), HANDLE(1 as *mut _));
        invisivel(h, true);
    }
    if ev != EVENT_OBJECT_SHOW {
        return;
    }
    let _ = SetPropW(h, w!("ShellPastaVista"), HANDLE(1 as *mut _));
    handle(h.0 as isize);
}
pub fn start() {
    if shell::foto() || HOOK.load(Ordering::Relaxed) != 0 {
        return;
    }
    // CREATE (0x8000) até SHOW (0x8002): pega a janela já ao nascer
    let h = unsafe { SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_SHOW, None, Some(on_show), 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS) };
    HOOK.store(h.0 as isize, Ordering::Relaxed);
}
pub fn stop() {
    let h = HOOK.swap(0, Ordering::Relaxed);
    if h != 0 {
        unsafe {
            let _ = UnhookWinEvent(HWINEVENTHOOK(h as *mut _));
        }
    }
}