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
22.3 KB
Raw Blame
//! atalhos.cpp: itens do próprio app no menu do Dock (a "lista de atalhos" da barra de tarefas do Windows):
//!  - tarefas do app ("Nova janela", "Nova janela anônima" do Chrome...): ficam em
//!    %APPDATA%\Microsoft\Windows\Recent\CustomDestinations\*.customDestinations-ms; cada item é o CLSID do ShellLink
//!    seguido do atalho gravado. O arquivo é ligado ao app pelo programa que os atalhos abrem; com vários, vale o mais novo.
//!  - recentes do app (IApplicationDocumentLists) pela identidade dele (AUMID, ou a derivada do caminho do .exe); Ableton,
//!    FL Studio e Cubase guardam a lista por conta própria; plano B: os "Itens recentes" do Windows que abrem com o .exe.
//!  - controles de mídia da sessão do app (GSMTC).
//! A leitura vai numa thread com prazo (300 ms; mídia 800 ms): com o disco ocupado o menu abre sem esses itens.
#![allow(dead_code)]

use std::collections::HashMap;
use std::sync::mpsc;
use std::sync::Mutex;
use std::time::Duration;

use comum::windows::core::*;
use comum::windows::Media::Control::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Storage::EnhancedStorage::*;
use comum::windows::Win32::Storage::FileSystem::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::Registry::*;
use comum::windows::Win32::UI::Shell::Common::IObjectArray;
use comum::windows::Win32::UI::Shell::PropertiesSystem::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
use comum::*;

use crate::{log, shell};

#[derive(Clone, Default, Debug)]
pub struct Item {
    pub title: String,
    pub path: String,
    pub args: String,
    pub dir: String,
    pub recent: bool,
}
#[derive(Clone, Default)]
pub struct Media {
    pub has: bool,
    pub playing: bool,
    pub can_next: bool,
    pub can_prev: bool,
    pub title: String,
    pub artist: String,
}
#[derive(Default)]
struct Cached {
    mt: u64,
    items: Vec<Item>,
    exe: String,
}
/// arquivo -> tarefas lidas
static FILES: Mutex<Option<HashMap<String, Cached>>> = Mutex::new(None);
/// uma leitura de disco de cada vez
static UM: Mutex<()> = Mutex::new(());

fn ft(f: &FILETIME) -> u64 {
    ((f.dwHighDateTime as u64) << 32) | f.dwLowDateTime as u64
}
fn buf_str(b: &[u16]) -> String {
    from_w(b)
}
fn read_file(path: &str, max: u64) -> Option<Vec<u8>> {
    let m = std::fs::metadata(path).ok()?;
    if m.len() > max {
        return None;
    }
    std::fs::read(path).ok()
}
fn read_custom(file: &str, c: &mut Cached) {
    c.items.clear();
    c.exe.clear();
    let Some(b) = read_file(file, 4 * 1024 * 1024) else { return };
    // o GUID na memória: Data1..3 little-endian
    let g = ShellLink;
    let mut pat = [0u8; 16];
    pat[0..4].copy_from_slice(&g.data1.to_le_bytes());
    pat[4..6].copy_from_slice(&g.data2.to_le_bytes());
    pat[6..8].copy_from_slice(&g.data3.to_le_bytes());
    pat[8..16].copy_from_slice(&g.data4);
    let mut i = 0;
    while i + 16 < b.len() {
        if b[i..i + 16] != pat {
            i += 1;
            continue;
        }
        unsafe {
            if let Some(st) = SHCreateMemStream(Some(&b[i + 16..])) {
                if let Ok(sl) = CoCreateInstance::<_, IShellLinkW>(&ShellLink, None, CLSCTX_INPROC_SERVER) {
                    if sl.cast::<IPersistStream>().and_then(|ps| ps.Load(&st)).is_ok() {
                        let (mut p, mut a, mut d) = ([0u16; 260], [0u16; 2048], [0u16; 260]);
                        let _ = sl.GetPath(&mut p, std::ptr::null_mut(), SLGP_RAWPATH.0 as u32);
                        let _ = sl.GetArguments(&mut a);
                        let _ = sl.GetWorkingDirectory(&mut d);
                        let mut it = Item { path: buf_str(&p), args: buf_str(&a), dir: buf_str(&d), ..Default::default() };
                        if let Ok(ps) = sl.cast::<IPropertyStore>() {
                            it.title = prop_text(&ps, &PKEY_Title);
                        }
                        // título indireto ("@C:\...\app.dll,-123"): o texto de verdade
                        if it.title.starts_with('@') {
                            let mut out = [0u16; 256];
                            if SHLoadIndirectString(pc(&wz(&it.title)), &mut out, None).is_ok() {
                                it.title = buf_str(&out);
                            }
                        }
                        if !it.title.is_empty() && !it.path.is_empty() {
                            if c.exe.is_empty() {
                                c.exe = it.path.to_lowercase();
                            }
                            c.items.push(it);
                        }
                    }
                }
            }
        }
        i += 16;
    }
}
fn known(id: &GUID) -> String {
    unsafe {
        match SHGetKnownFolderPath(id, KF_FLAG_DEFAULT, None) {
            Ok(p) => {
                let s = from_w(p.as_wide());
                CoTaskMemFree(Some(p.0 as *const _));
                s
            }
            Err(_) => String::new(),
        }
    }
}
fn recent_dir() -> String {
    known(&FOLDERID_Recent)
}
/// a identidade que o Windows dá a um .exe sem AUMID: a pasta conhecida trocada pelo GUID dela
fn implicit_ids(exe: &str) -> Vec<String> {
    let mut ids = Vec::new();
    let le = exe.to_lowercase();
    for kf in [FOLDERID_ProgramFilesX64, FOLDERID_ProgramFilesX86, FOLDERID_System, FOLDERID_Windows, FOLDERID_LocalAppData, FOLDERID_RoamingAppData, FOLDERID_Profile] {
        let base = known(&kf).to_lowercase();
        if !base.is_empty() && le.starts_with(&format!("{base}\\")) {
            ids.push(format!("{{{kf:?}}}{}", &exe[base.len()..]));
        }
    }
    ids.push(exe.to_string());
    ids
}
fn file_name(p: &str) -> &str {
    p.rsplit(['\\', '/']).next().unwrap_or(p)
}
fn exists(p: &str) -> bool {
    std::path::Path::new(p).exists()
}
fn add_recent(out: &mut Vec<Item>, path: &str, max: usize) {
    if out.len() >= max || path.is_empty() || out.iter().any(|o| o.path.eq_ignore_ascii_case(path)) || !exists(path) {
        return;
    }
    let name = file_name(path);
    let title = match name.rfind('.') {
        Some(d) if d > 0 => &name[..d],
        _ => name,
    };
    out.push(Item { path: path.to_string(), title: title.to_string(), recent: true, ..Default::default() });
}
/// o arquivo mais recente que casa com `base` + padrão + `resto`
fn newest(base: &str, pattern: &str, rest: &str) -> String {
    let mut best = (0u64, String::new());
    unsafe {
        let mut fd = WIN32_FIND_DATAW::default();
        let Ok(h) = FindFirstFileW(pc(&wz(&format!("{base}{pattern}"))), &mut fd) else { return String::new() };
        loop {
            let c = format!("{base}{}{rest}", from_w(&fd.cFileName));
            if let Ok(m) = std::fs::metadata(&c) {
                let t = m.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_nanos() as u64).unwrap_or(0);
                if t > best.0 {
                    best = (t, c);
                }
            }
            if FindNextFileW(h, &mut fd).is_err() {
                break;
            }
        }
        let _ = FindClose(h);
    }
    best.1
}
/// Ableton Live: os projetos recentes ficam no Preferences.cfg dele, como caminhos completos em UTF-16 (em posições
/// pares e ímpares do arquivo). Lidos na ordem gravada (o mais recente primeiro), sem repetir e só os que existem.
fn ableton_recent(max: usize) -> Vec<Item> {
    let mut out = Vec::new();
    let base = format!("{}\\Ableton\\", known(&FOLDERID_RoamingAppData));
    let cfg = newest(&base, "Live *", "\\Preferences\\Preferences.cfg"); // a versão usada por último
    let Some(b) = (if cfg.is_empty() { None } else { read_file(&cfg, 8 * 1024 * 1024) }) else { return out };
    // ".als" em UTF-16, em qualquer posição: volta até o começo do caminho (letra + ":/")
    let pat = [b'.', 0, b'a', 0, b'l', 0, b's', 0];
    let mut found: Vec<(usize, String)> = Vec::new();
    let mut i = 8;
    while i + 8 <= b.len() {
        if b[i..i + 8] != pat {
            i += 1;
            continue;
        }
        let (mut st, lim) = (i, i.saturating_sub(1040));
        while st >= 2 && st > lim {
            let c = b[st - 2] as u16 | (b[st - 1] as u16) << 8;
            if c < 0x20 || c == b'"' as u16 || c == b'<' as u16 || c == b'>' as u16 || c == b'|' as u16 {
                break;
            }
            st -= 2;
        }
        let u: Vec<u16> = (st..i + 8).step_by(2).map(|k| b[k] as u16 | (b[k + 1] as u16) << 8).collect();
        let path = String::from_utf16_lossy(&u);
        let colon = path.find(":/").or_else(|| path.find(":\\"));
        if let Some(c) = colon.filter(|&c| c >= 1) {
            let start = path[..c].char_indices().last().map(|x| x.0).unwrap_or(0);
            found.push((st, path[start..].replace('/', "\\")));
        }
        i += 1;
    }
    found.sort_by_key(|f| f.0);
    for (_, path) in found {
        if out.len() >= max {
            break;
        }
        if out.iter().any(|o: &Item| o.path.eq_ignore_ascii_case(&path)) || !exists(&path) {
            continue;
        }
        let name = file_name(&path);
        let title = name.strip_suffix(".als").unwrap_or(name).to_string();
        out.push(Item { path, title, recent: true, ..Default::default() });
    }
    out
}
/// FL Studio: HKCU\Software\Image-Line\FL Studio <versão>\MRU, valores "0", "1"... (o mais recente primeiro)
fn fl_recent(max: usize) -> Vec<Item> {
    let mut out = Vec::new();
    unsafe {
        let mut il = HKEY::default();
        if RegOpenKeyExW(HKEY_CURRENT_USER, w!("Software\\Image-Line"), 0, KEY_READ, &mut il).is_err() {
            return out;
        }
        let mut i = 0;
        while out.len() < max {
            let mut sub = [0u16; 256];
            let mut n = 256u32;
            if RegEnumKeyExW(il, i, PWSTR(sub.as_mut_ptr()), &mut n, None, PWSTR::null(), None, None).is_err() {
                break;
            }
            i += 1;
            let sub = String::from_utf16_lossy(&sub[..n as usize]);
            if !sub.to_lowercase().starts_with("fl studio") {
                continue;
            }
            let mru = wz(&format!("{sub}\\MRU"));
            for k in 0..20 {
                if out.len() >= max {
                    break;
                }
                let mut v = [0u16; 520];
                let mut cb = (v.len() * 2) as u32;
                if RegGetValueW(il, pc(&mru), pc(&wz(&k.to_string())), RRF_RT_REG_SZ, None, Some(v.as_mut_ptr() as *mut _), Some(&mut cb)).is_ok() {
                    add_recent(&mut out, &from_w(&v), max);
                }
            }
        }
        let _ = RegCloseKey(il);
    }
    out
}
/// Cubase: %APPDATA%\Steinberg\Cubase <versão>_64\Defaults.xml, lista "GRecentDocumentPaths" (Name + Path)
fn cubase_recent(max: usize) -> Vec<Item> {
    let mut out = Vec::new();
    let base = format!("{}\\Steinberg\\", known(&FOLDERID_RoamingAppData));
    let xml = newest(&base, "Cubase*", "\\Defaults.xml");
    let Some(b) = (if xml.is_empty() { None } else { read_file(&xml, 16 * 1024 * 1024) }) else { return out };
    let t = String::from_utf8_lossy(&b);
    let Some(at) = t.find("GRecentDocumentPaths") else { return out };
    let value = |from: usize, name: &str| -> Option<(String, usize)> {
        let key = format!("name=\"{name}\" value=\"");
        let k = t[from..].find(&key)? + from + key.len();
        let e = t[k..].find('"')? + k;
        Some((t[k..e].to_string(), e))
    };
    let mut pos = at;
    while out.len() < max {
        let Some((nm, e1)) = value(pos, "Name") else { break };
        if nm.len() < 5 || !nm.to_lowercase().ends_with(".cpr") {
            pos = e1; // outro campo "Name" (o tipo do arquivo)
            continue;
        }
        let Some((dir, e2)) = value(e1, "Path") else { break };
        pos = e2;
        add_recent(&mut out, &format!("{dir}{nm}"), max);
    }
    out
}
/// plano B para qualquer app: os "Itens recentes" do Windows que abrem com este .exe, do mais novo para o mais velho
fn shell_recent(exe: &str, max: usize) -> Vec<Item> {
    let mut out = Vec::new();
    let dir = format!("{}\\", recent_dir());
    let mut lnks: Vec<(u64, String)> = Vec::new();
    unsafe {
        let mut fd = WIN32_FIND_DATAW::default();
        let Ok(h) = FindFirstFileW(pc(&wz(&format!("{dir}*.lnk"))), &mut fd) else { return out };
        loop {
            lnks.push((ft(&fd.ftLastWriteTime), format!("{dir}{}", from_w(&fd.cFileName))));
            if FindNextFileW(h, &mut fd).is_err() {
                break;
            }
        }
        let _ = FindClose(h);
    }
    lnks.sort_by(|a, b| b.0.cmp(&a.0));
    let want = exe.to_lowercase();
    let mut ext_ok: HashMap<String, bool> = HashMap::new();
    for (looked, (_, l)) in lnks.iter().enumerate() {
        if out.len() >= max || looked >= 200 {
            break;
        }
        let mut target = String::new();
        unsafe {
            if let Ok(sl) = CoCreateInstance::<_, IShellLinkW>(&ShellLink, None, CLSCTX_INPROC_SERVER) {
                if sl.cast::<IPersistFile>().and_then(|pf| pf.Load(pc(&wz(l)), STGM_READ)).is_ok() {
                    let mut p = [0u16; 260];
                    let _ = sl.GetPath(&mut p, std::ptr::null_mut(), SLGP_RAWPATH.0 as u32);
                    target = from_w(&p);
                }
            }
        }
        let name = file_name(&target);
        let Some(d) = name.rfind('.') else { continue };
        let e = name[d..].to_lowercase();
        let ok = *ext_ok.entry(e.clone()).or_insert_with(|| unsafe {
            let mut h2 = [0u16; 260];
            let mut n = h2.len() as u32;
            AssocQueryStringW(ASSOCF_NONE, ASSOCSTR_EXECUTABLE, pc(&wz(&e)), PCWSTR::null(), PWSTR(h2.as_mut_ptr()), &mut n).is_ok() && from_w(&h2).to_lowercase() == want
        });
        if ok {
            add_recent(&mut out, &target, max);
        }
    }
    out
}
fn tasks_disco(exe: &str) -> Vec<Item> {
    let mut out = Vec::new();
    if exe.is_empty() {
        return out;
    }
    let want = exe.to_lowercase();
    let dir = format!("{}\\CustomDestinations\\", recent_dir());
    let mut g = FILES.lock().unwrap();
    let files = g.get_or_insert_with(HashMap::new);
    let mut best = 0u64;
    unsafe {
        let mut fd = WIN32_FIND_DATAW::default();
        let Ok(h) = FindFirstFileW(pc(&wz(&format!("{dir}*.customDestinations-ms"))), &mut fd) else { return out };
        loop {
            let file = format!("{dir}{}", from_w(&fd.cFileName));
            let mt = ft(&fd.ftLastWriteTime);
            let c = files.entry(file.clone()).or_default();
            if c.mt != mt {
                c.mt = mt;
                read_custom(&file, c);
            }
            if c.exe == want && !c.items.is_empty() && mt > best {
                best = mt;
                out = c.items.clone();
            }
            if FindNextFileW(h, &mut fd).is_err() {
                break;
            }
        }
        let _ = FindClose(h);
    }
    out
}
fn recent_disco(aumid: &str, exe: &str, max: usize) -> Vec<Item> {
    let file = file_name(exe).to_lowercase();
    // apps que guardam a lista por conta própria (não usam a do Windows)
    let own = if file.starts_with("ableton live") {
        ableton_recent(max)
    } else if file == "fl64.exe" || file == "fl.exe" {
        fl_recent(max)
    } else if file.starts_with("cubase") {
        cubase_recent(max)
    } else {
        Vec::new()
    };
    if !own.is_empty() {
        return own;
    }
    let mut out = Vec::new();
    unsafe {
        let Ok(dl) = CoCreateInstance::<_, IApplicationDocumentLists>(&ApplicationDocumentLists, None, CLSCTX_INPROC_SERVER) else { return out };
        let mut ids = Vec::new();
        if !aumid.is_empty() {
            ids.push(aumid.to_string());
        }
        if !exe.is_empty() {
            ids.extend(implicit_ids(exe));
        }
        for id in &ids {
            if dl.SetAppID(pc(&wz(id))).is_err() {
                continue;
            }
            let Ok(arr) = dl.GetList::<IObjectArray>(ADLT_RECENT, max as u32) else { continue };
            for i in 0..arr.GetCount().unwrap_or(0) {
                if let Ok(si) = arr.GetAt::<IShellItem>(i) {
                    let p = si.GetDisplayName(SIGDN_FILESYSPATH).map(|p| {
                        let s = from_w(p.as_wide());
                        CoTaskMemFree(Some(p.0 as *const _));
                        s
                    });
                    let nm = si.GetDisplayName(SIGDN_NORMALDISPLAY).map(|p| {
                        let s = from_w(p.as_wide());
                        CoTaskMemFree(Some(p.0 as *const _));
                        s
                    });
                    if let (Ok(p), Ok(nm)) = (p, nm) {
                        if !p.is_empty() && !nm.is_empty() {
                            out.push(Item { path: p, title: nm, recent: true, ..Default::default() });
                        }
                    }
                    continue;
                }
                if let Ok(sl) = arr.GetAt::<IShellLinkW>(i) {
                    let mut p = [0u16; 260];
                    let _ = sl.GetPath(&mut p, std::ptr::null_mut(), 0);
                    let path = from_w(&p);
                    if !path.is_empty() {
                        out.push(Item { title: file_name(&path).to_string(), path, recent: true, ..Default::default() });
                    }
                }
            }
            if !out.is_empty() {
                log!("atalhos: {} recentes pela identidade {id}", out.len());
                break;
            }
        }
    }
    if out.is_empty() && !exe.is_empty() {
        out = shell_recent(exe, max); // plano B: os Itens recentes do Windows
    }
    out
}
pub fn aumid_of(h: HWND) -> String {
    if h.0.is_null() {
        return String::new();
    }
    unsafe { SHGetPropertyStoreForWindow::<_, IPropertyStore>(h).map(|ps| prop_text(&ps, &PKEY_AppUserModel_ID)).unwrap_or_default() }
}
/// a sessão de mídia deste app: pela identidade (AUMID) ou pelo nome do .exe dentro da identidade da sessão
fn session_of(exe: &str, aumid: &str) -> Option<GlobalSystemMediaTransportControlsSession> {
    let base = file_name(exe).to_lowercase();
    let base = base.strip_suffix(".exe").unwrap_or(&base).to_string();
    let mgr = GlobalSystemMediaTransportControlsSessionManager::RequestAsync().ok()?.get().ok()?;
    let la = aumid.to_lowercase();
    for s in mgr.GetSessions().ok()? {
        let src = s.SourceAppUserModelId().map(|h| h.to_string().to_lowercase()).unwrap_or_default();
        if (!la.is_empty() && src == la) || (!base.is_empty() && src.contains(&base)) {
            return Some(s);
        }
    }
    None
}
fn media_now(exe: &str, aumid: &str) -> Media {
    let Some(s) = session_of(exe, aumid) else { return Media::default() };
    let mut m = Media { has: true, ..Default::default() };
    if let Ok(info) = s.GetPlaybackInfo() {
        m.playing = info.PlaybackStatus().ok() == Some(GlobalSystemMediaTransportControlsSessionPlaybackStatus::Playing);
        if let Ok(c) = info.Controls() {
            m.can_next = c.IsNextEnabled().unwrap_or(false);
            m.can_prev = c.IsPreviousEnabled().unwrap_or(false);
        }
    }
    if let Ok(p) = s.TryGetMediaPropertiesAsync().and_then(|a| a.get()) {
        m.title = p.Title().map(|h| h.to_string()).unwrap_or_default();
        m.artist = p.Artist().map(|h| h.to_string()).unwrap_or_default();
    }
    m
}
/// o WinRT síncrono não pode na thread da janela (STA): uma thread faz a consulta, com prazo (um app de mídia que não
/// responde congelava o Shell no clique direito do ícone do Dock)
pub fn media_of(exe: &str, aumid: &str) -> Media {
    if exe.is_empty() && aumid.is_empty() {
        return Media::default();
    }
    let (tx, rx) = mpsc::channel();
    let (e, a) = (exe.to_string(), aumid.to_string());
    std::thread::spawn(move || {
        unsafe {
            let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
        }
        let _ = tx.send(media_now(&e, &a));
    });
    match rx.recv_timeout(Duration::from_millis(800)) {
        Ok(m) => m,
        Err(_) => {
            log!("atalhos: controles de mídia não responderam em 800 ms (menu sem eles)");
            Media::default()
        }
    }
}
/// 0 tocar/pausar, 1 próxima, 2 anterior, outro parar; sem app: a sessão atual do Windows (as teclas de mídia)
pub fn media_command(exe: &str, aumid: &str, cmd: i32) {
    let (e, a) = (exe.to_string(), aumid.to_string());
    std::thread::spawn(move || {
        unsafe {
            let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
        }
        let s = if e.is_empty() && a.is_empty() {
            GlobalSystemMediaTransportControlsSessionManager::RequestAsync().and_then(|x| x.get()).and_then(|m| m.GetCurrentSession()).ok()
        } else {
            session_of(&e, &a)
        };
        let Some(s) = s else {
            log!("mídia: nenhuma sessão de mídia para o comando {cmd}");
            return;
        };
        let _ = match cmd {
            0 => s.TryTogglePlayPauseAsync().and_then(|x| x.get()),
            1 => s.TrySkipNextAsync().and_then(|x| x.get()),
            2 => s.TrySkipPreviousAsync().and_then(|x| x.get()),
            _ => s.TryStopAsync().and_then(|x| x.get()),
        };
    });
}
pub fn run(it: &Item) {
    if it.recent {
        shell::abrir(Some("open"), &it.path, "", "", SW_SHOWNORMAL);
        return;
    }
    shell::abrir(Some("open"), &it.path, &it.args, &it.dir, SW_SHOWNORMAL);
    log!("atalhos: \"{}\" ({} {})", it.title, it.path, it.args);
}
/// a leitura vai numa thread, uma de cada vez, e o menu espera até 300 ms; passou disso, abre sem esses itens
fn com_prazo(ler: impl FnOnce() -> Vec<Item> + Send + 'static) -> Vec<Item> {
    let (tx, rx) = mpsc::channel();
    std::thread::spawn(move || {
        let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
        let r = {
            let _l = UM.lock().unwrap();
            ler()
        };
        if hr.is_ok() {
            unsafe { CoUninitialize() };
        }
        let _ = tx.send(r);
    });
    match rx.recv_timeout(Duration::from_millis(300)) {
        Ok(r) => r,
        Err(_) => {
            log!("atalhos: o disco demorou; o menu abre sem os itens do app");
            Vec::new()
        }
    }
}
pub fn tasks(exe: &str) -> Vec<Item> {
    let e = exe.to_string();
    com_prazo(move || tasks_disco(&e))
}
pub fn recent(aumid: &str, exe: &str, max: usize) -> Vec<Item> {
    let (a, e) = (aumid.to_string(), exe.to_string());
    com_prazo(move || recent_disco(&a, &e, max))
}