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
83.3 KB
Raw Blame
//! apps.cpp: apps do Dock. Os fixos (dock.txt; na primeira vez, os fixados na barra de tarefas do Windows), os abertos
//! (janelas que apareceriam na barra de tarefas) e os recentes. Abrir, ativar, ocultar, encerrar, fixar, abrir ao iniciar.
#![allow(dead_code)]

use std::collections::{BTreeMap, HashMap};
use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Graphics::Imaging::*;
use comum::windows::Win32::Storage::EnhancedStorage::*;
use comum::windows::Win32::UI::Shell::Common::COMDLG_FILTERSPEC;
use std::os::windows::process::CommandExt;
use comum::windows::Win32::Storage::Packaging::Appx::GetApplicationUserModelId;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::SystemInformation::{GetTickCount, GetTickCount64};
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::UI::Shell::PropertiesSystem::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

use crate::progresso;
use crate::genio;
use crate::seletor;
use crate::mesa;
use crate::launchpad;
use crate::{jogos, liquid, log, notificacoes, shell, ui};

#[derive(Clone, Default)]
pub struct AppWin {
    pub hwnd: HWND,
    pub title: String,
    pub minimized: bool,
}
unsafe impl Send for AppWin {}
#[derive(Clone, Default)]
pub struct App {
    /// "aumid:..." ou caminho do .exe em minúsculas
    pub id: String,
    /// .lnk, .exe ou shell:AppsFolder\AUMID
    pub launch: String,
    pub name: String,
    /// .exe de destino em minúsculas (casa janelas sem AUMID com o atalho fixo)
    pub exe: String,
    /// PR #355: o ícone composto que o Chrome fornece para o perfil (cada perfil é um app no Dock)
    pub chrome_icon: String,
    pub pinned: bool,
    /// o Finder (sempre o primeiro)
    pub finder: bool,
    pub recent: bool,
    pub wins: Vec<AppWin>,
    pub iw: u32,
    pub ih: u32,
    /// BGRA pré-multiplicado
    pub icon: Vec<u8>,
    /// ícone do pacote do Mac (já tem a margem: desenha no tamanho cheio)
    pub mac: bool,
    pub launched_at: u32,
    pub aberto_em: u32,
    pub attention_at: u32,
    pub last_active: u32,
}
unsafe impl Send for App {}

struct St {
    list: Vec<App>,
    recent: Vec<String>,
    ours: Vec<HWND>,
    finder_exe: String,
    hidden: HashMap<isize, u32>,
    oculta_genio: HWND,
}
static ST: Global<Option<St>> = Global::new(None);
fn s() -> &'static mut St {
    ST.get().get_or_insert_with(|| St { list: Vec::new(), recent: Vec::new(), ours: Vec::new(), finder_exe: String::new(), hidden: HashMap::new(), oculta_genio: HWND::default() })
}
/// ordem do Dock: Finder, fixos, abertos/recentes (só da thread da interface)
pub fn list() -> &'static mut Vec<App> {
    &mut s().list
}
pub fn recent() -> &'static mut Vec<String> {
    &mut s().recent
}
/// nossas janelas (não entram no Dock nem na barra)
pub fn ours() -> &'static mut Vec<HWND> {
    &mut s().ours
}
fn lower(s: &str) -> String {
    s.to_lowercase()
}
fn base_name(p: &str) -> &str {
    p.rsplit(['\\', '/']).next().unwrap_or(p)
}
fn data_dir() -> String {
    let d = crate::menubar::known_folder(&FOLDERID_RoamingAppData) + "\\Shell";
    if !shell::foto() {
        let _ = std::fs::create_dir_all(&d);
    }
    d
}
/// um app nosso aberto antes de uma compilação roda do .exe antigo renomeado: para o Dock é o mesmo app do bin
fn our_canonical(path: &str) -> String {
    let file = base_name(path);
    let low = file.to_lowercase();
    if !low.starts_with("sequoia") || low.len() < 12 {
        return path.into();
    }
    let Some(cut) = low.find(['-', '.']) else { return path.into() };
    if &low[cut..] == ".exe" {
        return path.into();
    }
    let canon = format!("{}\\{}.exe", shell::dir(), &file[..cut]);
    if std::path::Path::new(&canon).exists() {
        canon
    } else {
        path.into()
    }
}
fn exe_of_process(pid: u32) -> String {
    let mut out = String::new();
    unsafe {
        if let Ok(hp) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) {
            let mut buf = [0u16; 520];
            let mut n = buf.len() as u32;
            if QueryFullProcessImageNameW(hp, PROCESS_NAME_WIN32, PWSTR(buf.as_mut_ptr()), &mut n).is_ok() {
                out = String::from_utf16_lossy(&buf[..n as usize]);
            }
            let _ = CloseHandle(hp);
        }
    }
    our_canonical(&out)
}
/// o .exe de um processo (caminho completo)
pub fn exe_of_pid(pid: u32) -> String {
    exe_of_process(pid)
}
/// o que já se perguntou de cada janela (o programa de uma janela não muda; perguntar a cada tique travou a interface)
#[derive(Clone, Default)]
struct DaJanela {
    pid: u32,
    tid: u32,
    desde: u64,
    aumid_em: u64,
    exe: String,
    aumid: String,
    aumid_proc: String,
    tem_aumid_proc: bool,
}
static JAN: Mutex<Option<HashMap<isize, DaJanela>>> = Mutex::new(None);
fn guardado(h: HWND) -> DaJanela {
    let mut pid = 0;
    let tid = unsafe { GetWindowThreadProcessId(h, Some(&mut pid)) };
    let mut g = JAN.lock().unwrap();
    let m = g.get_or_insert_with(HashMap::new);
    if m.len() > 1024 {
        m.retain(|k, _| unsafe { IsWindow(HWND(*k as *mut c_void)).as_bool() });
    }
    let d = m.entry(h.0 as isize).or_default();
    if d.pid != pid || d.tid != tid {
        *d = DaJanela { pid, tid, desde: unsafe { GetTickCount64() }, ..Default::default() };
    }
    d.clone()
}
fn guarda(h: HWND, de: &DaJanela, muda: impl FnOnce(&mut DaJanela)) {
    let mut g = JAN.lock().unwrap();
    if let Some(d) = g.as_mut().and_then(|m| m.get_mut(&(h.0 as isize))) {
        if d.pid == de.pid && d.tid == de.tid {
            muda(d);
        }
    }
}
fn exe_of_window(h: HWND) -> String {
    let d = guardado(h);
    if !d.exe.is_empty() || d.pid == 0 {
        return d.exe;
    }
    let exe = exe_of_process(d.pid);
    if !exe.is_empty() {
        guarda(h, &d, |g| g.exe = exe.clone());
    }
    exe
}
fn aumid_of_window(h: HWND) -> String {
    let d = guardado(h);
    // vale por 3 s: o LibreOffice usa a mesma janela da Central Inicial para o Writer, o Calc ou o Impress e troca
    // o AUMID dela; guardado para sempre, o Impress ficava no ícone do Writer (#421)
    let agora = unsafe { GetTickCount64() };
    if !d.aumid.is_empty() && agora - d.aumid_em < 3000 {
        return d.aumid;
    }
    let mut out = String::new();
    unsafe {
        if let Ok(ps) = SHGetPropertyStoreForWindow::<_, IPropertyStore>(h) {
            out = prop_text(&ps, &PKEY_AppUserModel_ID);
        }
        if !out.is_empty() {
            // o da janela pode chegar ou mudar logo depois de ela abrir: só fica guardado depois de 10 s
            if agora - d.desde > 10000 {
                guarda(h, &d, |g| {
                    g.aumid = out.clone();
                    g.aumid_em = agora;
                });
            }
            return out;
        }
        // app da Loja cuja janela não traz o AUMID (WhatsApp, WinUI/WebView2): o do processo
        if d.tem_aumid_proc {
            return d.aumid_proc;
        }
        if let Ok(hp) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, d.pid) {
            let mut buf = [0u16; 130];
            let mut n = buf.len() as u32;
            if GetApplicationUserModelId(hp, &mut n, PWSTR(buf.as_mut_ptr())) == ERROR_SUCCESS {
                out = from_w(&buf);
            }
            let _ = CloseHandle(hp);
            guarda(h, &d, |g| {
                g.aumid_proc = out.clone();
                g.tem_aumid_proc = true;
            });
        }
    }
    out
}
/// os nossos apps aparecem só com o nome do app (como no Mac), na língua escolhida. Vazio: não é um dos nossos
/// todos os apps do pacote (PR #272: antes só os 7 primeiros, e os outros apareciam na barra de menus com a descrição
/// em inglês do .exe em qualquer idioma)
pub fn our_name(exe: &str) -> String {
    let f = base_name(exe).to_lowercase();
    const NAMES: &[(&str, &str, &str)] = &[
        ("wacosfinder.exe", "Finder", "Finder"),
        ("wacossettings.exe", "Ajustes do Sistema", "System Settings"),
        ("wacosactivitymonitor.exe", "Monitor de Atividade", "Activity Monitor"),
        ("wacosterminal.exe", "Terminal", "Terminal"),
        ("wacoscalculator.exe", "Calculadora", "Calculator"),
        ("wacosnotes.exe", "Notas", "Notes"),
        ("wacosscreenshot.exe", "Captura de Tela", "Screenshot"),
        ("wacospreview.exe", "Pré-Visualização", "Preview"),
        ("wacosreminders.exe", "Lembretes", "Reminders"),
        ("wacoscalendar.exe", "Calendário", "Calendar"),
        ("wacostextedit.exe", "TextEdit", "TextEdit"),
        ("wacosclock.exe", "Relógio", "Clock"),
        ("wacosweather.exe", "Clima", "Weather"),
        ("wacoscontacts.exe", "Contatos", "Contacts"),
        ("wacosphotos.exe", "Fotos", "Photos"),
        ("wacostimemachine.exe", "Time Machine", "Time Machine"),
        ("wacosmusic.exe", "Música", "Music"),
        ("wacosquicktime.exe", "QuickTime Player", "QuickTime Player"),
        ("wacosforcequit.exe", "Forçar Encerrar Aplicativos", "Force Quit Applications"),
    ];
    NAMES.iter().find(|n| n.0 == f).map(|n| tr_pick(n.1, n.2)).unwrap_or_default()
}
/// nomes dos nossos apps no idioma escolhido
pub fn relabel() {
    for a in list().iter_mut() {
        if a.finder {
            continue;
        }
        let o = our_name(if a.exe.is_empty() { &a.launch } else { &a.exe });
        if !o.is_empty() {
            a.name = o;
        }
    }
}
/// nome amigável do programa (descrição do arquivo), ou o nome do .exe
fn exe_name(exe: &str) -> String {
    let o = our_name(exe);
    if !o.is_empty() {
        return o;
    }
    if let Some(d) = version_description(exe) {
        return d;
    }
    let f = base_name(exe);
    if f.len() > 4 {
        f[..f.len() - 4].to_string()
    } else {
        f.to_string()
    }
}
fn version_description(exe: &str) -> Option<String> {
    use comum::windows::Win32::Storage::FileSystem::{GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW};
    unsafe {
        let ew = wz(exe);
        let n = GetFileVersionInfoSizeW(pc(&ew), None);
        if n == 0 {
            return None;
        }
        let mut buf = vec![0u8; n as usize];
        GetFileVersionInfoW(pc(&ew), 0, n, buf.as_mut_ptr() as *mut c_void).ok()?;
        let (mut tr_, mut len) = (std::ptr::null_mut::<c_void>(), 0u32);
        if !VerQueryValueW(buf.as_ptr() as *const c_void, w!("\\VarFileInfo\\Translation"), &mut tr_, &mut len).as_bool() || len < 4 {
            return None;
        }
        let lc = std::slice::from_raw_parts(tr_ as *const u16, 2);
        let key = wz(&format!("\\StringFileInfo\\{:04x}{:04x}\\FileDescription", lc[0], lc[1]));
        let (mut desc, mut dl) = (std::ptr::null_mut::<c_void>(), 0u32);
        if VerQueryValueW(buf.as_ptr() as *const c_void, pc(&key), &mut desc, &mut dl).as_bool() && dl > 1 {
            let s = from_w(std::slice::from_raw_parts(desc as *const u16, dl as usize));
            if !s.is_empty() {
                return Some(s);
            }
        }
        None
    }
}
fn display_name_of(parsing: &str) -> String {
    unsafe {
        let pw = wz(parsing);
        let Ok(si) = SHCreateItemFromParsingName::<_, _, IShellItem>(pc(&pw), None) else { return String::new() };
        match si.GetDisplayName(SIGDN_NORMALDISPLAY) {
            Ok(n) => {
                let r = from_w(n.as_wide());
                CoTaskMemFree(Some(n.0 as *const c_void));
                r
            }
            Err(_) => String::new(),
        }
    }
}
/// destino (.exe) e AUMID de um atalho
/// PR #355: o Chrome da Google (cada perfil vira um app próprio no Dock)
fn chrome_exe(exe: &str) -> bool {
    let e = exe.to_lowercase();
    e.ends_with("\\chrome.exe") && e.contains("\\google\\")
}
fn chrome_browser(id: &str, exe: &str) -> bool {
    chrome_exe(exe) && !id.contains("._crx_") && !id.contains("._app_")
}
/// uma propriedade de texto da janela (AppUserModel)
fn window_property(h: HWND, key: &PROPERTYKEY) -> String {
    unsafe {
        let Ok(ps) = SHGetPropertyStoreForWindow::<_, IPropertyStore>(h) else { return String::new() };
        prop_text(&ps, key)
    }
}
/// o id para o App Exposé: as janelas do Chrome (todos os perfis) juntas
pub fn expose_id(h: HWND) -> String {
    let (id, exe) = (id_of_window(h), lower(&exe_of_window(h)));
    if chrome_browser(&id, &exe) {
        return exe;
    }
    list().iter().find(|a| a.wins.iter().any(|w| w.hwnd == h)).map(|a| a.id.clone()).unwrap_or(id)
}
pub fn expose_id_of(id: &str, exe: &str) -> String {
    if chrome_browser(id, exe) { exe.to_string() } else { id.to_string() }
}
/// o "Google Profile.ico" que o Chrome põe em cada janela de perfil
fn chrome_window_icon(h: HWND) -> String {
    let mut icon = window_property(h, &PKEY_AppUserModel_RelaunchIconResource);
    if icon.is_empty() {
        return String::new();
    }
    if let Some(i) = icon.rfind(',') {
        icon.truncate(i);
    }
    let icon = icon.trim_matches('"').to_string();
    if icon.to_lowercase().ends_with("\\google profile.ico") { icon } else { String::new() }
}
/// issue #368: o ícone do perfil do Chrome ("Google Profile.ico", o do Windows) só vale com dois perfis ou mais no
/// Dock, para dar para diferenciar. Com um só, o Chrome usa o ícone do tema, como os outros apps
fn chrome_perfis() -> usize {
    list().iter().filter(|x| chrome_browser(&x.id, &x.exe)).count()
}
fn chrome_profile_icon(a: &App) -> String {
    if !chrome_browser(&a.id, &a.exe) || chrome_perfis() < 2 {
        return String::new();
    }
    if !a.chrome_icon.is_empty() {
        return a.chrome_icon.clone();
    }
    if a.launch.to_lowercase().ends_with(".lnk") {
        let (_, _, icon) = read_link_icon(&a.launch);
        if icon.to_lowercase().ends_with("\\google profile.ico") {
            return icon;
        }
    }
    String::new()
}
fn read_link_icon(lnk: &str) -> (String, String, String) {
    let (t, a) = read_link(lnk);
    let mut icon = String::new();
    unsafe {
        if let Ok(sl) = CoCreateInstance::<_, IShellLinkW>(&ShellLink, None, CLSCTX_INPROC_SERVER) {
            if let Ok(pf) = sl.cast::<IPersistFile>() {
                let lw = wz(lnk);
                if pf.Load(pc(&lw), STGM_READ).is_ok() {
                    let mut p = [0u16; 260];
                    let mut idx = 0i32;
                    if sl.GetIconLocation(&mut p, &mut idx).is_ok() {
                        icon = from_w(&p);
                    }
                }
            }
        }
    }
    (t, a, icon)
}
fn read_link(lnk: &str) -> (String, String) {
    let (mut target, mut aumid) = (String::new(), String::new());
    unsafe {
        let Ok(sl) = CoCreateInstance::<_, IShellLinkW>(&ShellLink, None, CLSCTX_INPROC_SERVER) else { return (target, aumid) };
        let Ok(pf) = sl.cast::<IPersistFile>() else { return (target, aumid) };
        let lw = wz(lnk);
        if pf.Load(pc(&lw), STGM_READ).is_ok() {
            let mut p = [0u16; 260];
            if sl.GetPath(&mut p, std::ptr::null_mut(), 0).is_ok() {
                target = from_w(&p);
            }
            if let Ok(ps) = sl.cast::<IPropertyStore>() {
                aumid = prop_text(&ps, &PKEY_AppUserModel_ID);
            }
        }
    }
    (target, aumid)
}
pub fn is_shell_window(h: HWND) -> bool {
    s().ours.contains(&h)
}
pub fn id_of_window(h: HWND) -> String {
    let exe = lower(&exe_of_window(h));
    let fe = lower(&s().finder_exe);
    if !fe.is_empty() && exe == fe {
        return fe;
    }
    let cls = shell::class_name(h);
    if (cls == "CabinetWClass" || cls == "ArquivosJanela") && !fe.is_empty() {
        return fe; // janela do Explorador conta como do Finder
    }
    let a = aumid_of_window(h);
    if !a.is_empty() {
        return format!("aumid:{}", lower(&a));
    }
    exe
}
pub fn find_by_id(id: &str) -> Option<&'static mut App> {
    list().iter_mut().find(|a| a.id == id)
}
/// janela com dona que fica sozinha (a dona está escondida): conta como janela do app
pub fn lone_owned(h: HWND) -> bool {
    unsafe {
        let owner = GetWindow(h, GW_OWNER).unwrap_or_default();
        if owner.0.is_null() || !IsWindowVisible(h).as_bool() {
            return false;
        }
        let ex = GetWindowLongPtrW(h, GWL_EXSTYLE) as u32;
        let st = GetWindowLongPtrW(h, GWL_STYLE) as u32;
        if ex & (WS_EX_TOOLWINDOW.0 | WS_EX_NOACTIVATE.0) != 0 || (st & WS_CAPTION.0 != WS_CAPTION.0 && GetPropW(h, w!("MacJanela")).0.is_null()) {
            return false;
        }
        let root = GetAncestor(h, GA_ROOTOWNER);
        if root.0.is_null() || root == h {
            return false;
        }
        let mut o = owner;
        while !o.0.is_null() {
            if IsWindowVisible(o).as_bool() {
                let mut cl = 0u32;
                let _ = DwmGetWindowAttribute(o, DWMWA_CLOAKED, &mut cl as *mut _ as *mut c_void, 4);
                if cl == 0 {
                    let oex = GetWindowLongPtrW(o, GWL_EXSTYLE) as u32;
                    if oex & WS_EX_APPWINDOW.0 != 0 || (oex & (WS_EX_TOOLWINDOW.0 | WS_EX_NOACTIVATE.0) == 0 && GetWindow(o, GW_OWNER).unwrap_or_default().0.is_null() && GetWindowTextLengthW(o) > 0) {
                        return false; // a dona já aparece como app
                    }
                }
            }
            o = GetWindow(o, GW_OWNER).unwrap_or_default();
        }
        true
    }
}
/// janela que o Windows mostraria na barra de tarefas (as regras do Alt+Tab)
fn is_taskbar_window(h: HWND) -> bool {
    unsafe {
        if !IsWindowVisible(h).as_bool() || is_shell_window(h) || shell::nossa(h) {
            return false;
        }
        let ex = GetWindowLongPtrW(h, GWL_EXSTYLE) as u32;
        let owner = GetWindow(h, GW_OWNER).unwrap_or_default();
        let mut lone = false;
        if ex & WS_EX_APPWINDOW.0 != 0 {
        } else if !owner.0.is_null() && lone_owned(h) {
            lone = true;
        } else if !owner.0.is_null() || ex & (WS_EX_TOOLWINDOW.0 | WS_EX_NOACTIVATE.0) != 0 {
            return false;
        }
        let mut cloaked = 0u32;
        let _ = DwmGetWindowAttribute(h, DWMWA_CLOAKED, &mut cloaked as *mut _ as *mut c_void, 4);
        if cloaked != 0 {
            return false;
        }
        let cls = shell::class_name(h);
        if mesa::is_desk_class(&cls) || cls == "Shell_TrayWnd" || cls == "Shell_SecondaryTrayWnd" {
            return false;
        }
        if cls == "OperationStatusWindow" && progresso::owns(h) {
            return false;
        }
        GetWindowTextLengthW(h) > 0 || lone
    }
}
pub fn is_app_window(h: HWND) -> bool {
    is_taskbar_window(h)
}
pub fn of_window(h: HWND) -> Option<&'static mut App> {
    if let Some(i) = list().iter().position(|a| a.wins.iter().any(|w| w.hwnd == h)) {
        return list().get_mut(i);
    }
    let id = id_of_window(h);
    if list().iter().any(|a| a.id == id) {
        return find_by_id(&id);
    }
    let exe = lower(&exe_of_window(h));
    if chrome_exe(&exe) {
        return None; // PR #355: um perfil do Chrome não cai no ícone de outro
    }
    list().iter_mut().find(|a| !a.exe.is_empty() && a.exe == exe)
}
/// grava atômica (.tmp + troca); nunca no modo foto
fn gravar_texto(path: &str, s: &str) {
    if shell::foto() {
        return;
    }
    let tmp = format!("{path}.tmp");
    let mut b = vec![0xEF, 0xBB, 0xBF];
    b.extend_from_slice(s.as_bytes());
    if std::fs::write(&tmp, b).is_ok() {
        let _ = std::fs::rename(&tmp, path);
    }
}
pub fn save() {
    let mut s_ = String::new();
    for a in list().iter().filter(|a| a.pinned && !a.finder) {
        s_ += &format!("{}\t{}\t{}\t{}{}\n", a.id, a.launch, a.name, a.exe, if a.chrome_icon.is_empty() { String::new() } else { format!("\t{}", a.chrome_icon) });
    }
    gravar_texto(&(data_dir() + "\\dock.txt"), &s_);
}
fn ler_texto(path: &str) -> Option<String> {
    let b = std::fs::read(path).ok()?;
    let b = b.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(&b);
    Some(String::from_utf8_lossy(b).into_owned())
}
pub fn load(finder_exe: &str) {
    s().finder_exe = finder_exe.into();
    let l = list();
    l.clear();
    l.push(App { id: lower(finder_exe), exe: lower(finder_exe), launch: finder_exe.into(), name: "Finder".into(), pinned: true, finder: true, ..Default::default() });
    if let Some(t) = ler_texto(&(data_dir() + "\\dock.txt")) {
        for line in t.lines() {
            let p: Vec<&str> = line.trim_end_matches(['\r', '\n']).split('\t').collect();
            if p.len() < 3 || p[0] == "aumid:microsoft.windows.explorer" {
                continue;
            }
            let mut x = App { id: p[0].into(), launch: p[1].into(), name: p[2].into(), exe: p.get(3).copied().unwrap_or("").into(), pinned: true, ..Default::default() };
            if chrome_exe(&x.exe) {
                x.chrome_icon = p.get(4).copied().unwrap_or("").into();
            }
            let o = our_name(if x.exe.is_empty() { &x.launch } else { &x.exe });
            if !o.is_empty() {
                x.name = o;
            }
            l.push(x);
        }
        log!("dock: {} apps fixos", l.len() - 1);
        let mut healed = false;
        for a in l.iter_mut() {
            healed |= heal(a);
        }
        if healed {
            save();
        }
        return;
    }
    // primeira vez: o que está fixado na barra de tarefas do Windows
    let pins = crate::menubar::known_folder(&FOLDERID_RoamingAppData) + "\\Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar";
    if let Ok(rd) = std::fs::read_dir(&pins) {
        for e in rd.flatten() {
            let name = e.file_name().to_string_lossy().into_owned();
            if !name.to_lowercase().ends_with(".lnk") {
                continue;
            }
            let lnk = format!("{pins}\\{name}");
            let (target, aumid) = read_link(&lnk);
            let t = lower(&target);
            if t.ends_with("explorer.exe") || lower(&aumid) == "microsoft.windows.explorer" {
                continue;
            }
            l.push(App { id: if aumid.is_empty() { t.clone() } else { format!("aumid:{}", lower(&aumid)) }, exe: t, launch: lnk, name: name[..name.len() - 4].into(), pinned: true, ..Default::default() });
        }
    }
    log!("dock: importados {} apps fixos da barra de tarefas", l.len() - 1);
    save();
}
/// issue #49: um .exe que é um app só (não navegador Chromium, não app da Loja nem o hospedeiro UWP)
fn exe_de_um_app(exe_lower: &str) -> bool {
    static CACHE: Global<Option<HashMap<String, bool>>> = Global::new(None);
    let c = CACHE.get().get_or_insert_with(HashMap::new);
    if let Some(v) = c.get(exe_lower) {
        return *v;
    }
    let um = !exe_lower.is_empty() && !exe_lower.contains("\\windowsapps\\") && !exe_lower.contains("applicationframehost.exe") && !jogos::programa_chromium(exe_lower);
    c.insert(exe_lower.into(), um);
    um
}
fn assinatura() -> String {
    let mut s_ = String::new();
    for a in list().iter() {
        s_ += &format!("{}|{}{};", a.id, a.wins.len(), if a.recent { "r" } else { "" });
    }
    for a in list().iter() {
        for w_ in &a.wins {
            if w_.minimized {
                s_ += &format!("m{}", w_.hwnd.0 as usize);
            }
        }
    }
    s_
}
/// relê as janelas; true se algo mudou
pub fn refresh() -> bool {
    let mut found: BTreeMap<String, Vec<AppWin>> = BTreeMap::new();
    let mut exe_of: HashMap<String, String> = HashMap::new();
    let mut order: Vec<String> = Vec::new();
    let mut hs: Vec<HWND> = Vec::new();
    unsafe extern "system" fn cb(h: HWND, l: LPARAM) -> BOOL {
        (*(l.0 as *mut Vec<HWND>)).push(h);
        TRUE
    }
    unsafe {
        let _ = EnumWindows(Some(cb), LPARAM(&mut hs as *mut _ as isize));
    }
    for h in hs {
        if !is_taskbar_window(h) {
            continue;
        }
        let mut id = id_of_window(h);
        let exe = lower(&exe_of_window(h));
        let id_fixo = list().iter().any(|a| a.id == id && a.pinned);
        if !id_fixo {
            // PR #355: o Chrome só cai no ícone fixo do próprio .exe com o perfil padrão; os outros perfis ficam à parte
            if let Some(a) = list().iter().find(|a| {
                a.id != id
                    && !a.exe.is_empty()
                    && lower(&a.exe) == exe
                    && if chrome_exe(&exe) { a.pinned && a.id == exe && id == "aumid:chrome" } else { !id.starts_with("aumid:") || !a.id.starts_with("aumid:") || (a.pinned && exe_de_um_app(&exe)) }
            }) {
                id = a.id.clone();
            }
        }
        // app fixo que se atualizou enquanto o Shell rodava: é o mesmo ícone do Dock
        if !id.starts_with("aumid:") && exe.contains(|c: char| c.is_ascii_digit()) {
            let mut salvou = false;
            for a in list().iter_mut() {
                if a.pinned && !a.finder && a.id != id && !a.exe.is_empty() && lower(&a.exe) != exe && ver_key(&a.exe) == ver_key(&exe) && ver_nums(&exe) > ver_nums(&lower(&a.exe)) {
                    log!("dock: {} atualizou: {} -> {}", a.name, a.exe, exe);
                    let id_was_exe = a.id == lower(&a.exe);
                    if lower(&a.launch) == lower(&a.exe) {
                        a.launch = exe_of_window(h);
                    }
                    a.exe = exe.clone();
                    if id_was_exe {
                        a.id = exe.clone();
                    }
                    id = a.id.clone();
                    salvou = true;
                    break;
                }
            }
            if salvou {
                save();
            }
        }
        // o nosso Ajustes do Sistema fica no ícone do Ajustes do Windows fixado; a Calculadora idem
        if exe.ends_with("\\ajustes.exe") {
            if let Some(a) = list().iter().find(|a| a.pinned && lower(&a.launch).contains("immersivecontrolpanel")) {
                id = a.id.clone();
            }
        }
        if exe.ends_with("\\calculadora.exe") {
            if let Some(a) = list().iter().find(|a| a.pinned && lower(&(a.id.clone() + &a.launch)).contains("windowscalculator")) {
                id = a.id.clone();
            }
        }
        if !found.contains_key(&id) {
            order.push(id.clone());
        }
        found.entry(id.clone()).or_default().push(AppWin { hwnd: h, title: shell::window_text(h), minimized: unsafe { IsIconic(h).as_bool() } });
        exe_of.insert(id, exe);
    }
    let before = assinatura();
    let (mut chrome_mudou, mut salvar_perfis) = (false, false);
    // PR #355: o ícone do perfil do Chrome (a janela traz o "Google Profile.ico")
    let chrome_icone = |a: &mut App, chrome_mudou: &mut bool, salvar: &mut bool| {
        if a.wins.is_empty() || !a.chrome_icon.is_empty() || !chrome_browser(&a.id, &a.exe) {
            return;
        }
        let icon = chrome_window_icon(a.wins[0].hwnd);
        if !icon.is_empty() && icon != a.chrome_icon {
            a.chrome_icon = icon;
            a.icon.clear();
            a.mac = false;
            *chrome_mudou = true;
            *salvar |= a.pinned;
        }
    };
    for a in list().iter_mut() {
        // PR #498 (shawn89890916): o app reabriu, ou mostrou a janela principal depois de uma auxiliar: a janela nova
        // pode anunciar outro ícone mesmo com o mesmo id e o mesmo número de janelas: o ícone automático é relido
        if !a.icon.is_empty() && !a.mac {
            if let Some(novas) = found.get(&a.id) {
                if novas.iter().any(|w| !a.wins.iter().any(|v| v.hwnd == w.hwnd)) {
                    a.icon.clear();
                    chrome_mudou = true;
                }
            }
        }
        a.wins = found.get(&a.id).cloned().unwrap_or_default();
        if !a.wins.is_empty() {
            a.launched_at = 0;
            a.recent = false;
        }
        chrome_icone(a, &mut chrome_mudou, &mut salvar_perfis);
    }
    for id in &order {
        if list().iter().any(|a| &a.id == id) {
            continue;
        }
        let mut x = App { id: id.clone(), exe: exe_of.get(id).cloned().unwrap_or_default(), wins: found[id].clone(), ..Default::default() };
        chrome_icone(&mut x, &mut chrome_mudou, &mut salvar_perfis);
        let pacote = id.starts_with("aumid:");
        x.launch = if pacote { format!("shell:AppsFolder\\{}", aumid_of_window(x.wins[0].hwnd)) } else { exe_of_window(x.wins[0].hwnd) };
        let mut arq = our_name(if pacote { &x.exe } else { &x.launch });
        if arq.is_empty() {
            arq = base_name(if pacote { &x.exe } else { &x.launch }).to_string();
            if arq.len() > 4 {
                arq.truncate(arq.len() - 4);
            }
        }
        x.name = arq;
        // o nome bonito (descrição do .exe, nome do pacote) vem de uma thread (issue #32)
        let (id2, launch, exe, provisorio) = (id.clone(), x.launch.clone(), x.exe.clone(), x.name.clone());
        let janela = x.wins[0].hwnd.0 as isize;
        if !shell::foto() {
            std::thread::spawn(move || unsafe {
                let ci = CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
                let mut n = String::new();
                if chrome_browser(&id2, &exe) {
                    // PR #355: o nome do perfil do Chrome ("Pessoa 1 - Chrome")
                    n = window_property(HWND(janela as *mut _), &PKEY_AppUserModel_RelaunchDisplayNameResource);
                    if n.starts_with('@') {
                        let src = wz(&n);
                        let mut out = [0u16; 512];
                        n = if SHLoadIndirectString(pc(&src), &mut out, None).is_ok() { from_w(&out) } else { String::new() };
                    }
                }
                if n.is_empty() {
                    n = if pacote { display_name_of(&launch) } else { exe_name(&launch) };
                }
                if n.is_empty() {
                    n = exe_name(&exe);
                }
                if ci.is_ok() {
                    CoUninitialize();
                }
                if n.is_empty() || n == provisorio {
                    return;
                }
                shell::na_interface(Box::new(move || {
                    if let Some(a) = list().iter_mut().find(|a| a.id == id2 && a.name == provisorio) {
                        a.name = n;
                        if a.pinned {
                            save();
                        }
                        crate::dock::update();
                    }
                }));
            });
        }
        log!("dock: aberto {} ({})", x.name, x.id);
        list().push(x);
        chrome_mudou = true; // PR #498: um id que saiu do Dock ainda pode ter um bitmap em cache
    }
    // sem seção de recentes: o app que não está fixo sai do Dock assim que fecha (só fica enquanto abre)
    recent().clear();
    let now = unsafe { GetTickCount() };
    list().retain(|a| a.pinned || !a.wins.is_empty() || (a.launched_at != 0 && now.wrapping_sub(a.launched_at) <= 20000));
    // ordem: fixos (na ordem do usuário), depois abertos
    let (p, o): (Vec<App>, Vec<App>) = std::mem::take(list()).into_iter().partition(|a| a.pinned);
    *list() = p.into_iter().chain(o).collect();
    // issue #368: entrou ou saiu um perfil do Chrome (um só <-> dois ou mais): os ícones do Chrome trocam de estilo
    static PERFIS_ANTES: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(-1);
    let perfis = chrome_perfis() as i32;
    let antes = PERFIS_ANTES.swap(perfis, Ordering::Relaxed);
    if antes >= 0 && (antes >= 2) != (perfis >= 2) {
        for a in list().iter_mut().filter(|a| chrome_browser(&a.id, &a.exe)) {
            a.icon.clear();
            a.mac = false;
        }
        chrome_mudou = true;
    }
    if salvar_perfis {
        save();
    }
    if chrome_mudou {
        crate::dock::icons_changed();
    }
    chrome_mudou || before != assinatura()
}
fn norm(s: &str) -> String {
    s.chars().filter(|c| c.is_alphanumeric()).flat_map(|c| c.to_lowercase()).collect()
}
// ---- ícone e nome próprios do app (%APPDATA%\Shell\icones-dock e nomes-apps.txt)
fn icon_key(s: &str) -> String {
    let r: String = s.chars().map(|c| if (c as u32) < 32 || "\\/:*?\"<>|".contains(c) { '_' } else { c }).collect();
    r.trim_end_matches([' ', '.']).to_string()
}
pub fn custom_icon_dir() -> String {
    static D: Global<String> = Global::new(String::new());
    let d = D.get();
    if d.is_empty() {
        *d = crate::menubar::known_folder(&FOLDERID_RoamingAppData) + "\\Shell\\icones-dock\\";
    }
    d.clone()
}
fn custom_keys(name: &str, exe: &str) -> Vec<String> {
    let mut k = Vec::new();
    let e = base_name(exe);
    if e.len() > 4 && e.to_lowercase().ends_with(".exe") && !e.contains(':') {
        let e = icon_key(&e[..e.len() - 4]);
        if !e.is_empty() {
            k.push(e);
        }
    }
    let n = icon_key(name);
    if !n.is_empty() && (k.is_empty() || !n.eq_ignore_ascii_case(&k[0])) {
        k.push(n);
    }
    k
}
static NOMES: Mutex<(u64, u64, BTreeMap<String, String>)> = Mutex::new((0, 0, BTreeMap::new()));
fn arquivo_nomes() -> String {
    let d = custom_icon_dir();
    if d.len() < 13 {
        return String::new();
    }
    d[..d.len() - 12].to_string() + "nomes-apps.txt"
}
fn le_nomes() {
    // o disco (data e conteúdo do nomes-apps.txt) sem o lock: nome_visivel é chamado pela thread da interface (Dock,
    // barra de menus) e por threads (Launchpad); com o lock preso durante a leitura, um disco lento parava a interface
    let agora = unsafe { GetTickCount64() };
    {
        let mut g = NOMES.lock().unwrap();
        if g.0 != 0 && agora - g.0 < 1000 {
            return;
        }
        g.0 = agora;
    }
    let f = arquivo_nomes();
    let t = std::fs::metadata(&f).and_then(|m| m.modified()).map(|t| t.duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(1)).unwrap_or(0);
    if t == NOMES.lock().unwrap().1 {
        return;
    }
    let mut m = BTreeMap::new();
    if t != 0 {
        if let Some(txt) = ler_texto(&f) {
            for line in txt.lines() {
                let s_ = line.trim_start_matches('\u{FEFF}');
                if let Some(tab) = s_.find('\t') {
                    if tab > 0 && tab + 1 < s_.len() {
                        m.insert(s_[..tab].to_lowercase(), s_[tab + 1..].to_string());
                    }
                }
            }
        }
    }
    let mut g = NOMES.lock().unwrap();
    g.1 = t;
    g.2 = m;
}
/// nome próprio do app (Dock, Launchpad, barra de menus)
pub fn nome_visivel(name: &str, exe: &str) -> String {
    le_nomes();
    let g = NOMES.lock().unwrap();
    if g.2.is_empty() {
        return name.into();
    }
    for k in custom_keys(name, exe) {
        if let Some(v) = g.2.get(&k.to_lowercase()) {
            return v.clone();
        }
    }
    name.into()
}
pub fn renomear(name: &str, exe: &str) {
    let limpa = |s: String| s.replace(['|', '"'], " ");
    let mut pedido = format!("renomear:{}", limpa(nome_visivel(name, exe)));
    for k in custom_keys(name, exe) {
        pedido += &format!("|{}", limpa(k));
    }
    shell::abrir(Some("open"), &format!("{}\\{}", shell::dir(), nomes::EXE_SETTINGS), &format!("\"--pagina={pedido}\""), "", SW_SHOWNORMAL);
}
pub fn custom_icon(name: &str, exe: &str) -> String {
    let dir = custom_icon_dir();
    if dir.is_empty() {
        return String::new();
    }
    custom_keys(name, exe).into_iter().map(|k| format!("{dir}{k}.png")).find(|f| std::path::Path::new(f).exists()).unwrap_or_default()
}
pub fn has_custom_icon(name: &str, exe: &str) -> bool {
    !custom_icon(name, exe).is_empty()
}
/// PNG (BGRA pré-multiplicado na memória; o arquivo vai com alfa normal)
pub fn save_png(path: &str, w_: u32, h: u32, pbgra: &[u8]) -> bool {
    let mut px = pbgra.to_vec();
    for p in px.chunks_exact_mut(4) {
        let a = p[3] as u32;
        if a > 0 && a < 255 {
            for c in 0..3 {
                p[c] = (p[c] as u32 * 255 / a).min(255) as u8;
            }
        }
    }
    let tmp = format!("{path}.tmp");
    let ok = unsafe {
        (|| -> Result<()> {
            let wic: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
            let st = wic.CreateStream()?;
            let tw = wz(&tmp);
            st.InitializeFromFilename(pc(&tw), GENERIC_WRITE.0)?;
            let enc = wic.CreateEncoder(&GUID_ContainerFormatPng, std::ptr::null())?;
            enc.Initialize(&st, WICBitmapEncoderNoCache)?;
            let mut fr = None;
            enc.CreateNewFrame(&mut fr, std::ptr::null_mut())?;
            let fr = fr.ok_or(Error::from(E_FAIL))?;
            fr.Initialize(None)?;
            fr.SetSize(w_, h)?;
            let mut f = GUID_WICPixelFormat32bppBGRA;
            fr.SetPixelFormat(&mut f)?;
            if f != GUID_WICPixelFormat32bppBGRA {
                return Err(E_FAIL.into());
            }
            fr.WritePixels(h, w_ * 4, &px)?;
            fr.Commit()?;
            enc.Commit()
        })()
        .is_ok()
    };
    let ok = ok && std::fs::rename(&tmp, path).is_ok();
    if !ok {
        let _ = std::fs::remove_file(&tmp);
    }
    ok
}
/// lê a imagem escolhida, deixa quadrada (centrada), no máximo 512 px, e grava nos nomes do app
fn save_custom_icon(name: &str, exe: &str, src: &str) -> bool {
    let ext = src.to_lowercase();
    let icon = [".ico", ".exe", ".dll", ".lnk"].iter().any(|e| ext.ends_with(e));
    let mut img = if icon { ui::shell_image(src, 256, true) } else { ui::load_photo(src, 512) };
    if img.is_none() && !icon {
        img = ui::shell_image(src, 256, true);
    }
    let Some(mut img) = img.filter(|i| i.w > 0 && i.h > 0 && i.px.len() >= (i.w * i.h * 4) as usize) else {
        log!("ícone próprio: não deu para ler {src}");
        return false;
    };
    if icon {
        ui::trim_to_square(&mut img);
    }
    if img.w != img.h {
        let s_ = img.w.max(img.h);
        let mut sq = vec![0u8; (s_ * s_ * 4) as usize];
        let (ox, oy) = ((s_ - img.w) / 2, (s_ - img.h) / 2);
        for y in 0..img.h {
            let d = (((y + oy) * s_ + ox) * 4) as usize;
            let o = (y * img.w * 4) as usize;
            sq[d..d + (img.w * 4) as usize].copy_from_slice(&img.px[o..o + (img.w * 4) as usize]);
        }
        img = ui::Img { w: s_, h: s_, px: sq };
    }
    ui::downscale(&mut img, 512);
    let dir = custom_icon_dir();
    if dir.is_empty() {
        return false;
    }
    let _ = std::fs::create_dir_all(&dir);
    let mut any = false;
    for k in custom_keys(name, exe) {
        any |= save_png(&format!("{dir}{k}.png"), img.w, img.h, &img.px);
    }
    log!("ícone próprio: {name} <- {src} ({}x{}, {})", img.w, img.h, if any { "gravado" } else { "ERRO ao gravar" });
    any
}
pub fn avisar_icone_mudou() {
    unsafe {
        let s_ = FindWindowW(w!("ShellMensagens"), PCWSTR::null()).unwrap_or_default();
        if !s_.0.is_null() {
            let _ = PostMessageW(s_, RegisterWindowMessageW(w!("ShellIconeMudou")), WPARAM(0), LPARAM(0));
        }
    }
}
/// escolhe um arquivo (para quem já está numa thread): o Finder em modo escolher, ou a janela de Abrir do Windows.
/// tipos: "Nome|*.a;*.b||Outro|*.c" (o formato do --tipos do Finder). PR #358: o ícone próprio da barra de menus
pub fn pick_file(name: &str, tipos: &str) -> Option<String> {
    unsafe {
        let finder = format!("{}\\{}", shell::dir(), nomes::EXE_FINDER);
        if std::path::Path::new(&finder).exists() {
            let res = std::env::temp_dir().join(format!("mbi{}.tmp", GetTickCount()));
            let res = res.to_string_lossy().into_owned();
            let start = crate::menubar::known_folder(&FOLDERID_Pictures);
            let q = |s: &str| format!("\"{s}\"");
            let args = format!("{} --escolher abrir --tipos {} --tipo 0 --ok {} --resultado {}", q(&start), q(tipos), q(&tr("Escolher")), q(&res));
            if let Ok(mut ch) = std::process::Command::new(&finder).raw_arg(args).spawn() {
                let _ = AllowSetForegroundWindow(ch.id());
                let code = ch.wait().ok().and_then(|s| s.code()).unwrap_or(1);
                let mut path = String::new();
                if code == 0 {
                    if let Some(t) = ler_texto(&res) {
                        path = t.lines().find(|l| !l.is_empty() && !l.starts_with("tipo=")).unwrap_or("").to_string();
                    }
                }
                let _ = std::fs::remove_file(&res);
                return (!path.is_empty()).then_some(path);
            }
        }
        let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
        let mut out = None;
        if let Ok(dlg) = CoCreateInstance::<_, IFileOpenDialog>(&FileOpenDialog, None, CLSCTX_INPROC_SERVER) {
            let partes: Vec<&str> = tipos.split("||").collect();
            let ws: Vec<(Vec<u16>, Vec<u16>)> = partes.iter().filter_map(|p| p.split_once('|')).map(|(n, sp)| (wz(n), wz(sp))).collect();
            let f: Vec<COMDLG_FILTERSPEC> = ws.iter().map(|(n, sp)| COMDLG_FILTERSPEC { pszName: pc(n), pszSpec: pc(sp) }).collect();
            let _ = dlg.SetFileTypes(&f);
            let t = wz(&tr("Escolha o novo ícone de “%ls”").replace("%ls", name));
            let _ = dlg.SetTitle(pc(&t));
            if let Ok(o) = dlg.GetOptions() {
                let _ = dlg.SetOptions(o | FOS_FORCEFILESYSTEM | FOS_FILEMUSTEXIST);
            }
            if dlg.Show(None).is_ok() {
                if let Ok(it) = dlg.GetResult() {
                    if let Ok(p) = it.GetDisplayName(SIGDN_FILESYSPATH) {
                        out = Some(from_w(p.as_wide()));
                        CoTaskMemFree(Some(p.0 as *const c_void));
                    }
                }
            }
        }
        CoUninitialize();
        out
    }
}
/// Dock/Launchpad > Alterar Ícone…: o Finder em modo escolher (ou a janela de Abrir do Windows), numa thread
pub fn choose_icon(name: &str, exe: &str) {
    if shell::foto() {
        return;
    }
    let (name, exe) = (name.to_string(), exe.to_string());
    std::thread::spawn(move || unsafe {
        let finder = format!("{}\\{}", shell::dir(), nomes::EXE_FINDER);
        if std::path::Path::new(&finder).exists() {
            let res = std::env::temp_dir().join(format!("ico{}.tmp", GetTickCount()));
            let res = res.to_string_lossy().into_owned();
            let start = crate::menubar::known_folder(&FOLDERID_Pictures);
            let q = |s: &str| format!("\"{s}\"");
            let tipos = format!("{}|*.png;*.ico;*.jpg;*.jpeg;*.webp;*.bmp;*.gif;*.tif;*.tiff;*.heic||{}|*.ico;*.exe;*.dll", tr("Imagens"), tr("Ícones e programas"));
            let cmd = format!("{} {} --escolher abrir --tipos {} --tipo 0 --ok {} --resultado {}", q(&finder), q(&start), q(&tipos), q(&tr("Escolher")), q(&res));
            if let Ok(mut ch) = std::process::Command::new(&finder).raw_arg(cmd.splitn(2, ' ').nth(1).unwrap_or("")).spawn() {
                let _ = AllowSetForegroundWindow(ch.id());
                let code = ch.wait().ok().and_then(|s| s.code()).unwrap_or(1);
                let mut path = String::new();
                if code == 0 {
                    if let Some(t) = ler_texto(&res) {
                        path = t.lines().find(|l| !l.is_empty() && !l.starts_with("tipo=")).unwrap_or("").to_string();
                    }
                }
                let _ = std::fs::remove_file(&res);
                log!("ícone próprio: Finder escolher terminou ({code}){}", if path.is_empty() { "" } else { ", arquivo escolhido" });
                if !path.is_empty() && save_custom_icon(&name, &exe, &path) {
                    avisar_icone_mudou();
                }
                return;
            }
            log!("ícone próprio: Finder não abriu; janela do Windows");
        }
        let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
        if let Ok(dlg) = CoCreateInstance::<_, IFileOpenDialog>(&FileOpenDialog, None, CLSCTX_INPROC_SERVER) {
            let (imgs, icos) = (wz(&tr("Imagens")), wz(&tr("Ícones e programas")));
            let f = [COMDLG_FILTERSPEC { pszName: pc(&imgs), pszSpec: w!("*.png;*.ico;*.jpg;*.jpeg;*.webp;*.bmp;*.gif;*.tif;*.tiff;*.heic") }, COMDLG_FILTERSPEC { pszName: pc(&icos), pszSpec: w!("*.ico;*.exe;*.dll") }];
            let _ = dlg.SetFileTypes(&f);
            let t = wz(&tr("Escolha o novo ícone de “%ls”").replace("%ls", &name));
            let _ = dlg.SetTitle(pc(&t));
            if let Ok(o) = dlg.GetOptions() {
                let _ = dlg.SetOptions(o | FOS_FORCEFILESYSTEM | FOS_FILEMUSTEXIST);
            }
            if dlg.Show(None).is_ok() {
                if let Ok(it) = dlg.GetResult() {
                    if let Ok(p) = it.GetDisplayName(SIGDN_FILESYSPATH) {
                        if save_custom_icon(&name, &exe, &from_w(p.as_wide())) {
                            avisar_icone_mudou();
                        }
                        CoTaskMemFree(Some(p.0 as *const c_void));
                    }
                }
            }
        }
        CoUninitialize();
    });
}
pub fn restore_icon(name: &str, exe: &str) {
    let dir = custom_icon_dir();
    if dir.is_empty() || shell::foto() {
        return;
    }
    let n = custom_keys(name, exe).iter().filter(|k| std::fs::remove_file(format!("{dir}{k}.png")).is_ok()).count();
    log!("ícone próprio: {name} volta ao original ({n} arquivo(s))");
    if n > 0 {
        avisar_icone_mudou();
    }
}
/// o ícone mudou: todo mundo relê
pub fn reload_icons() {
    for a in list().iter_mut() {
        a.icon.clear();
        a.iw = 0;
        a.ih = 0;
        a.mac = false;
    }
    crate::dock::icons_changed();
    seletor::icons_changed();
    launchpad::icons_changed();
    crate::spotlight::icons_changed(); // o "Apps" do Tahoe/Golden Gate (#397)
    notificacoes::icons_changed();
}
fn pack_icon_for(a: &App) -> String {
    // ícone escolhido pelo usuário vem antes de tudo
    let own = custom_icon(if a.finder { "Finder" } else { &a.name }, if a.finder { "" } else if a.exe.is_empty() { &a.id } else { &a.exe });
    if !own.is_empty() {
        return own;
    }
    static PACK: Global<(i32, Option<HashMap<String, String>>)> = Global::new((-1, None));
    let (loaded, pack) = PACK.get();
    let pack = pack.get_or_insert_with(HashMap::new);
    let tema = if liquid::leopard() {
        3
    } else if liquid::golden() {
        2
    } else if liquid::on() {
        1
    } else {
        0
    };
    if *loaded != tema {
        *loaded = tema;
        pack.clear();
        let dir = shell::dir();
        let root = dir[..dir.rfind('\\').unwrap_or(dir.len())].to_string() + "\\icones";
        // Leopard: icones\leopard ANTES do extra; Golden Gate usa goldengate antes do Tahoe
        let subs = [if tema == 3 { "\\leopard" } else { "" }, "\\extra", if tema == 2 { "\\goldengate" } else { "" }, if tema == 1 || tema == 2 { "\\tahoe" } else { "" }, "\\sequoia"];
        for sub in subs.iter().filter(|s| !s.is_empty()) {
            let mut d = root.clone() + sub;
            let custom = shell::setting("icones", "");
            if !custom.is_empty() && *sub == "\\sequoia" {
                d = custom;
            }
            let Ok(rd) = std::fs::read_dir(&d) else { continue };
            for e in rd.flatten() {
                let n = e.file_name().to_string_lossy().into_owned();
                if n.to_lowercase().ends_with(".png") {
                    pack.entry(norm(&n[..n.len() - 4])).or_insert(format!("{d}\\{n}")); // o primeiro vence
                }
            }
            // PR #333: no Golden Gate, o app Apple Music do Windows também usa o ícone do Música do macOS
            if *sub == "\\goldengate" {
                let music = format!("{d}\\Music.png");
                if std::path::Path::new(&music).is_file() {
                    pack.entry("applemusic".to_string()).or_insert(music);
                }
            }
        }
    }
    if pack.is_empty() {
        return String::new();
    }
    if a.finder {
        return pack.get("finder").cloned().unwrap_or_default();
    }
    const ALIAS: &[(&str, &str)] = &[
        ("msedge", "edge"), ("code", "vscode"), ("winword", "word"), ("powerpnt", "powerpoint"), ("chrome", "googlechrome"), ("notepad", "textedit"), ("mspaint", "paint"), ("calculatorapp", "calculator"),
        ("calculadora", "calculator"), ("windowsterminal", "terminal"), ("wt", "terminal"), ("taskmgr", "activitymonitor"), ("monitoratividade", "activitymonitor"), ("monitordeatividade", "activitymonitor"),
        ("notas", "notes"), ("sequoiacalculator", "calculator"), ("sequoiaterminal", "terminal"), ("sequoiaactivitymonitor", "activitymonitor"), ("sequoianotes", "notes"), ("sequoiasettings", "settings"),
        ("systemsettings", "settings"), ("ajustes", "settings"), ("ajustesdosistema", "settings"), ("mbam", "malwarebytes"), ("steamwebhelper", "steam"), ("ms-teams", "teams"), ("olk", "outlook"),
        ("sublime_text", "sublimetext"),
        ("quicktime", "quicktimeplayer"),
    ];
    let mut exe_base = base_name(&a.exe).to_string();
    if exe_base.len() > 4 {
        exe_base.truncate(exe_base.len() - 4);
    }
    // issue #84: navegadores feitos sobre o Chromium (Helium, Chromium, Ungoogled...) também se chamam chrome.exe e
    // ganhavam o ícone do Google Chrome. O chrome.exe só vale como Chrome dentro de uma pasta do Google.
    if norm(&exe_base) == "chrome" && !lower(&a.exe).contains("\\google\\") {
        exe_base.clear();
    }
    // PR #277: os nossos apps (WacOS<App>.exe) têm o nome na língua do WacOS ("Danh bạ", "Lembretes"), que não é o nome
    // do arquivo do ícone; sem o "WacOS" o nome do .exe é o nome em inglês (WacOSContacts -> Contacts.png)
    let nossa = norm(&exe_base).strip_prefix("wacos").map(|s| s.to_string()).unwrap_or_default();
    for k in [norm(&a.name), norm(&exe_base), nossa] {
        if k.is_empty() {
            continue;
        }
        if let Some(p) = pack.get(&k) {
            return p.clone();
        }
        if let Some((_, al)) = ALIAS.iter().find(|x| x.0 == k) {
            if let Some(p) = pack.get(*al) {
                return p.clone();
            }
        }
    }
    String::new()
}
/// ícone do pacote do Mac pelo nome (ou pelo .exe)
pub fn pack_icon_by_name(name: &str, exe: &str) -> String {
    pack_icon_for(&App { name: name.into(), exe: exe.into(), ..Default::default() })
}
pub fn ensure_icon(a: &mut App, px: i32) {
    if !a.icon.is_empty() && (a.mac || a.iw.max(a.ih) as i32 >= px) {
        return;
    }
    if chrome_browser(&a.id, &a.exe) && custom_icon(&a.name, &a.exe).is_empty() {
        // PR #355: o ícone do perfil do Chrome (com a foto ou a letra da pessoa)
        let icon = chrome_profile_icon(a);
        if !icon.is_empty() {
            if let Some(mut i) = ui::load_png(&icon).or_else(|| ui::shell_image(&icon, px, false)) {
                ui::trim_to_square(&mut i);
                (a.iw, a.ih, a.icon, a.mac) = (i.w, i.h, i.px, false);
                return;
            }
        }
    }
    let png = pack_icon_for(a);
    if !png.is_empty() {
        if let Some(i) = ui::load_png(&png) {
            (a.iw, a.ih, a.icon, a.mac) = (i.w, i.h, i.px, true);
            return;
        }
    }
    if a.finder {
        return;
    }
    // PR #498 (shawn89890916): alguns apps publicam na janela o recurso exato que representa o grupo na barra de tarefas
    for w in &a.wins {
        let res = window_property(w.hwnd, &PKEY_AppUserModel_RelaunchIconResource);
        if let Some(mut i) = icone_do_recurso(&res, px) {
            ui::trim_to_square(&mut i);
            (a.iw, a.ih, a.icon) = (i.w, i.h, i.px);
            return;
        }
    }
    let img = ui::shell_image(&a.launch, px, true).or_else(|| ui::shell_image(&a.launch, px, false)).or_else(|| if a.exe.is_empty() { None } else { ui::shell_image(&a.exe, px, true) });
    if let Some(mut i) = img {
        ui::trim_to_square(&mut i);
        (a.iw, a.ih, a.icon) = (i.w, i.h, i.px);
    }
}
/// PR #498: "caminho,índice" (RelaunchIconResource) -> pixels BGRA pré-multiplicados. Caminho de rede fica de fora
/// (ler um ícone de um compartilhamento lento travaria o Dock)
fn icone_do_recurso(res: &str, px: i32) -> Option<ui::Img> {
    let res = res.trim();
    if res.is_empty() {
        return None;
    }
    let (caminho, indice) = match res.rsplit_once(',') {
        Some((c, i)) if i.trim().parse::<i32>().is_ok() => (c.trim().trim_matches('"'), i.trim().parse::<i32>().unwrap_or(0)),
        _ => (res.trim_matches('"'), 0),
    };
    unsafe {
        let mut exp = vec![0u16; 1024];
        let n = comum::windows::Win32::System::Environment::ExpandEnvironmentStringsW(pc(&wz(caminho)), Some(&mut exp)) as usize;
        if n == 0 || n > exp.len() {
            return None;
        }
        let p = String::from_utf16_lossy(&exp[..n - 1]);
        let b = p.as_bytes();
        if b.len() < 3 || !b[0].is_ascii_alphabetic() || b[1] != b':' || b[2] != b'\\' {
            return None;
        }
        let raiz = format!("{}:\\", b[0] as char);
        if comum::windows::Win32::Storage::FileSystem::GetDriveTypeW(pc(&wz(&raiz))) == 4 {
            return None; // DRIVE_REMOTE
        }
        let mut ic = HICON::default();
        if SHDefExtractIconW(pc(&wz(&p)), indice, 0, Some(&mut ic), None, (px as u32) & 0xFFFF).is_err() || ic.is_invalid() {
            return None;
        }
        let r = (|| -> Option<ui::Img> {
            let wic: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).ok()?;
            let bmp = wic.CreateBitmapFromHICON(ic).ok()?;
            let cv = wic.CreateFormatConverter().ok()?;
            cv.Initialize(&bmp, &GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).ok()?;
            let (mut w, mut h) = (0u32, 0u32);
            cv.GetSize(&mut w, &mut h).ok()?;
            let mut v = vec![0u8; (w * h * 4) as usize];
            cv.CopyPixels(std::ptr::null(), w * 4, &mut v).ok()?;
            Some(ui::Img { w, h, px: v })
        })();
        let _ = DestroyIcon(ic);
        r
    }
}
// ---- abrir
const NO_OCCLUSION: &str = "--disable-features=CalculateNativeWinOcclusion";
fn is_chromium(exe: &str) -> bool {
    let b = base_name(exe).to_lowercase();
    if ["chrome.exe", "msedge.exe", "brave.exe", "vivaldi.exe", "opera.exe", "arc.exe", "thorium.exe"].contains(&b.as_str()) {
        return true;
    }
    let dir = &exe[..exe.rfind('\\').unwrap_or(0)];
    std::path::Path::new(&format!("{dir}\\chrome_100_percent.pak")).exists() || std::path::Path::new(&format!("{dir}\\resources\\app.asar")).exists()
}
/// "{GUID-de-pasta-conhecida}\resto\app.exe" -> caminho real
fn expand_known_folder(p: &str) -> String {
    if p.len() < 40 || !p.starts_with('{') {
        return p.into();
    }
    let Some(close) = p.find('}') else { return p.into() };
    let gw = wz(&p[..=close]);
    unsafe {
        let Ok(g) = CLSIDFromString(pc(&gw)) else { return p.into() };
        let base = crate::menubar::known_folder(&g);
        if base.is_empty() {
            return p.into();
        }
        base + &p[close + 1..]
    }
}
/// app empacotado ("shell:AppsFolder\<AUMID com !>") pelo ativador do Windows, numa thread
pub fn activate_packaged(target: &str, args: &str) -> bool {
    let Some(id) = target.strip_prefix("shell:AppsFolder\\") else { return false };
    if !id.contains('!') {
        return false;
    }
    let done = Arc::new(AtomicBool::new(false));
    if mesa::standalone() {
        let (id, done) = (id.to_string(), done.clone());
        std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_millis(2500));
            if !done.load(Ordering::Relaxed) && mesa::standalone() {
                shell::na_interface(Box::new(move || mesa::need_explorer(&id)));
            }
        });
    }
    let (id, args) = (id.to_string(), args.to_string());
    std::thread::spawn(move || unsafe {
        let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
        let t0 = GetTickCount();
        let r = CoCreateInstance::<_, IApplicationActivationManager>(&ApplicationActivationManager, None, CLSCTX_LOCAL_SERVER).and_then(|am| {
            let (iw, aw) = (wz(&id), wz(&args));
            am.ActivateApplication(pc(&iw), if args.is_empty() { PCWSTR::null() } else { pc(&aw) }, AO_NONE)
        });
        done.store(true, Ordering::Relaxed);
        match r {
            Ok(pid) => log!("app empacotado aberto em {} ms (pid {pid}): {id}", GetTickCount() - t0),
            Err(e) => log!("app empacotado não abriu pelo ativador (0x{:08X}, {} ms): {id}", e.code().0 as u32, GetTickCount() - t0),
        }
        CoUninitialize();
    });
    true
}
/// apps Chromium/Electron: abre sem a "oclusão" (a miniatura do Mission Control fica viva)
pub fn launch_no_occlusion(target: &str, args: &str, exe_hint: &str) -> bool {
    if shell::setting("chromium_sem_oclusao", "1") != "1" {
        return false;
    }
    let (mut exe, mut cmd_args, mut dir) = (String::new(), String::new(), String::new());
    let mut t = target.to_string();
    let mut hint = exe_hint.to_string();
    if hint.is_empty() {
        if let Some(a) = list().iter().find(|a| a.launch == target && !a.exe.is_empty()) {
            hint = a.exe.clone();
        }
    }
    unsafe {
        if let Some(id) = target.strip_prefix("shell:AppsFolder\\") {
            if id.contains('!') {
                if hint.is_empty() || !is_chromium(&hint) {
                    return false;
                }
                let Ok(am) = CoCreateInstance::<_, IApplicationActivationManager>(&ApplicationActivationManager, None, CLSCTX_LOCAL_SERVER) else { return false };
                let all = wz(&(NO_OCCLUSION.to_string() + if args.is_empty() { "" } else { " " } + args));
                let iw = wz(id);
                let ok = am.ActivateApplication(pc(&iw), pc(&all), AO_NONE).is_ok();
                if ok {
                    log!("abrindo sem oclusão (miniatura viva no Mission Control): {id}");
                }
                return ok;
            }
            t = expand_known_folder(id);
            if !t.contains('\\') {
                let tw = wz(target);
                if let Ok(si) = SHCreateItemFromParsingName::<_, _, IShellItem2>(pc(&tw), None) {
                    if let Ok(p) = si.GetString(&PKEY_Link_TargetParsingPath) {
                        exe = from_w(p.as_wide());
                        CoTaskMemFree(Some(p.0 as *const c_void));
                    }
                    if let Ok(a) = si.GetString(&PKEY_Link_Arguments) {
                        cmd_args = from_w(a.as_wide());
                        CoTaskMemFree(Some(a.0 as *const c_void));
                    }
                }
            }
        }
        let low = t.to_lowercase();
        if low.ends_with(".lnk") {
            if let Ok(sl) = CoCreateInstance::<_, IShellLinkW>(&ShellLink, None, CLSCTX_INPROC_SERVER) {
                let tw = wz(&t);
                if sl.cast::<IPersistFile>().and_then(|pf| pf.Load(pc(&tw), STGM_READ)).is_ok() {
                    let (mut p, mut a, mut w_) = ([0u16; 260], [0u16; 1024], [0u16; 260]);
                    let _ = sl.GetPath(&mut p, std::ptr::null_mut(), 0);
                    let _ = sl.GetArguments(&mut a);
                    let _ = sl.GetWorkingDirectory(&mut w_);
                    exe = from_w(&p);
                    cmd_args = from_w(&a);
                    dir = from_w(&w_);
                }
            }
        } else if low.ends_with(".exe") {
            exe = t.clone();
        } else if exe.is_empty() && !hint.is_empty() {
            exe = hint;
        }
    }
    if exe.is_empty() || !std::path::Path::new(&exe).exists() {
        return false;
    }
    let mut base = base_name(&exe).to_lowercase();
    if base != "update.exe" && !is_chromium(&exe) {
        // lançador do Squirrel (Discord, Slack...): o app de verdade está em app-x.y.z\ ao lado do Update.exe
        let dir2 = exe[..exe.rfind('\\').unwrap_or(0)].to_string();
        let file = base_name(&exe).to_string();
        let electron = std::fs::read_dir(&dir2).map(|rd| rd.flatten().any(|e| e.file_name().to_string_lossy().to_lowercase().starts_with("app-") && is_chromium(&format!("{dir2}\\{}\\{file}", e.file_name().to_string_lossy())))).unwrap_or(false);
        if electron && std::path::Path::new(&format!("{dir2}\\Update.exe")).exists() {
            cmd_args = format!("--processStart {file}");
            exe = format!("{dir2}\\Update.exe");
            base = "update.exe".into();
        }
    }
    let mut all = if base == "update.exe" && cmd_args.contains("--processStart") {
        format!("{cmd_args} --process-start-args \"{NO_OCCLUSION}\"")
    } else {
        if !is_chromium(&exe) {
            return false;
        }
        cmd_args.clone() + if cmd_args.is_empty() { "" } else { " " } + NO_OCCLUSION
    };
    if !args.is_empty() {
        all += &format!(" {args}");
    }
    let (ew, aw, dw_) = (wz(&exe), wz(&all), wz(&dir));
    let r = unsafe { ShellExecuteW(None, w!("open"), pc(&ew), pc(&aw), if dir.is_empty() { PCWSTR::null() } else { pc(&dw_) }, SW_SHOWNORMAL) };
    if r.0 as isize <= 32 {
        return false;
    }
    log!("abrindo sem oclusão (miniatura viva no Mission Control): {exe} {all}");
    true
}
/// app da Loja guardado pelo caminho do .exe dentro de WindowsApps: o AUMID pelo nome da pasta e o AppxManifest
fn packaged_aumid(path: &str) -> String {
    let low = path.to_lowercase();
    let Some(w_) = low.find("\\windowsapps\\") else { return String::new() };
    let f0 = w_ + 13;
    let Some(f1) = path[f0..].find('\\').map(|x| x + f0) else { return String::new() };
    let folder = &path[f0..f1];
    let (Some(u), Some(pubi)) = (folder.find('_'), folder.rfind("__")) else { return String::new() };
    if pubi <= u {
        return String::new();
    }
    let pfn = format!("{}_{}", &folder[..u], &folder[pubi + 2..]);
    let want = base_name(path).to_lowercase();
    let mut app_id = String::new();
    if let Ok(x) = std::fs::read(format!("{}\\AppxManifest.xml", &path[..f1])) {
        if x.len() <= 16 * 1024 * 1024 {
            let x = String::from_utf8_lossy(&x).into_owned();
            let lx = x.to_lowercase();
            let mut at = 0;
            while let Some(p) = lx[at..].find("<application ") {
                let a0 = at + p;
                let end = lx[a0..].find('>').map(|e| a0 + e).unwrap_or(lx.len());
                let tag = &lx[a0..end];
                if let Some(i) = tag.find(" id=\"") {
                    let s0 = a0 + i + 5;
                    let id = &x[s0..s0 + x[s0..].find('"').unwrap_or(0)];
                    if app_id.is_empty() || tag.contains(&want) {
                        app_id = id.into();
                    }
                    if tag.contains(&want) {
                        break;
                    }
                }
                at = a0 + 1;
            }
        }
    }
    if app_id.is_empty() {
        app_id = "App".into();
    }
    format!("{pfn}!{app_id}")
}
/// o nome com a versão trocada por '#': "app-1.0.9268" -> "app-#"
fn ver_key(name: &str) -> String {
    let c: Vec<char> = name.chars().collect();
    let mut r = String::new();
    let mut i = 0;
    while i < c.len() {
        if c[i].is_ascii_digit() {
            let (mut j, mut dot) = (i, false);
            while j < c.len() && (c[j].is_ascii_digit() || (c[j] == '.' && j + 1 < c.len() && c[j + 1].is_ascii_digit())) {
                dot |= c[j] == '.';
                j += 1;
            }
            if dot {
                r.push('#');
            } else {
                r.extend(&c[i..j]);
            }
            i = j;
            continue;
        }
        r.extend(c[i].to_lowercase());
        i += 1;
    }
    r
}
fn ver_nums(name: &str) -> Vec<u32> {
    name.split(|c: char| !c.is_ascii_digit()).filter(|s| !s.is_empty()).map(|s| s.parse::<u32>().unwrap_or(u32::MAX)).collect()
}
fn exists(p: &str) -> bool {
    std::path::Path::new(p).exists()
}
/// o mesmo caminho na versão mais nova instalada
fn newest_version(path: &str) -> String {
    if path.len() < 4 || path.as_bytes()[1] != b':' {
        return path.into();
    }
    let mut parts: Vec<String> = path.split('\\').map(String::from).collect();
    let mut prefix = parts[0].clone();
    for i in 1..parts.len().saturating_sub(1) {
        let comp = parts[i].clone();
        let key = ver_key(&comp);
        if key.contains('#') {
            let rest: String = parts[i + 1..].iter().map(|p| format!("\\{p}")).collect();
            let mut best = comp.clone();
            let mut best_v = if exists(&format!("{prefix}\\{comp}{rest}")) { ver_nums(&comp) } else { Vec::new() };
            if let Ok(rd) = std::fs::read_dir(&prefix) {
                for e in rd.flatten() {
                    if !e.file_type().map(|t| t.is_dir()).unwrap_or(false) {
                        continue;
                    }
                    let n = e.file_name().to_string_lossy().into_owned();
                    if n.starts_with('.') || ver_key(&n) != key {
                        continue;
                    }
                    let v = ver_nums(&n);
                    if v > best_v && exists(&format!("{prefix}\\{n}{rest}")) {
                        best = n;
                        best_v = v;
                    }
                }
            }
            parts[i] = best;
        }
        prefix += &format!("\\{}", parts[i]);
    }
    let r = format!("{prefix}\\{}", parts.last().unwrap());
    if exists(&r) {
        r
    } else {
        path.into()
    }
}
/// os nossos apps fixados apontam para o programa da pasta de onde o Shell roda, com o nome de agora
fn our_app(path: &str) -> String {
    let base = base_name(path).to_lowercase();
    let n = if base.starts_with("sequoia") {
        7
    } else if base.starts_with("wacos") {
        5
    } else {
        0
    };
    if n == 0 || base.len() < 5 || !base.ends_with(".exe") {
        return path.into();
    }
    let mine = format!("{}\\WacOS{}", shell::dir(), &base[n..]);
    if !exists(&mine) || lower(&mine) == lower(path) {
        return path.into();
    }
    mine
}
fn heal(a: &mut App) -> bool {
    if a.finder {
        return false;
    }
    let exe = if a.exe.is_empty() { String::new() } else { our_app(&newest_version(&a.exe)) };
    let launch_is_path = a.launch.len() > 4 && a.launch.as_bytes()[1] == b':' && a.launch.to_lowercase().ends_with(".exe");
    let launch = if launch_is_path { our_app(&newest_version(&a.launch)) } else { a.launch.clone() };
    if lower(&exe) == lower(&a.exe) && launch == a.launch {
        return false;
    }
    log!("dock: {} atualizou: {} -> {}", a.name, if launch_is_path { &a.launch } else { &a.exe }, if launch_is_path { &launch } else { &exe });
    if !a.id.is_empty() && a.id == lower(&a.exe) {
        a.id = lower(&exe);
    }
    a.exe = lower(&exe);
    a.launch = launch;
    true
}
/// abrir mexe com o disco e com o ativador: tudo numa thread com uma cópia do app (issue #32)
// espera_abrir (issues #268 e #254): o app aberto pelo Spotlight/atalho aparecia na frente por um instante e voltava
// para trás (o Windows devolvia a frente ao app de antes quando o Spotlight sumia, ou o app nem ganhava a frente quando
// abria por outro processo). Ao abrir: a primeira janela de app que aparecer nos próximos 8 s fica na frente por 1,5 s.
static ABRINDO: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static ABRIU: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);
static ABRIU_EM: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static ABRINDO_EV: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);
unsafe extern "system" fn vigia_abriu(_: HWND, _: u32, id: usize, _: u32) {
    use comum::windows::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_LBUTTON, VK_RBUTTON};
    let h = HWND(ABRIU.load(Ordering::Relaxed) as *mut c_void);
    let clicou = GetAsyncKeyState(VK_LBUTTON.0 as i32) < 0 || GetAsyncKeyState(VK_RBUTTON.0 as i32) < 0;
    if h.0.is_null() || !IsWindow(h).as_bool() || !IsWindowVisible(h).as_bool() || IsIconic(h).as_bool() || clicou
        || GetTickCount64() - ABRIU_EM.load(Ordering::Relaxed) > 3000
    {
        let _ = KillTimer(None, id);
        ABRIU.store(0, Ordering::Relaxed);
        return;
    }
    let fg = GetForegroundWindow();
    let (mut pa, mut pf) = (0u32, 0u32);
    GetWindowThreadProcessId(h, Some(&mut pa));
    if !fg.0.is_null() {
        GetWindowThreadProcessId(fg, Some(&mut pf));
    }
    if fg == h || pf == pa {
        return; // na frente (ou outra janela dele, como a principal depois da de abertura)
    }
    let mut c = [0u16; 64];
    let n = if fg.0.is_null() { 0 } else { GetClassNameW(fg, &mut c) };
    let cls = String::from_utf16_lossy(&c[..n.max(0) as usize]);
    if !fg.0.is_null() && shell::nossa(fg) && GetAncestor(fg, GA_ROOT) == fg && IsWindowVisible(fg).as_bool() && !cls.starts_with("ShellSpotlight") {
        return; // um painel nosso aberto depois (menu, Launchpad): fica
    }
    log!("apps: o app aberto foi para trás (frente: {cls}); trazendo de volta");
    let _ = KillTimer(None, id);
    ABRIU.store(0, Ordering::Relaxed);
    shell::traz_pra_frente(h);
}
unsafe extern "system" fn abriu_janela(_: comum::windows::Win32::UI::Accessibility::HWINEVENTHOOK, _: u32, h: HWND, obj: i32, _: i32, _: u32, _: u32) {
    let quando = ABRINDO.load(Ordering::Relaxed);
    if obj != OBJID_WINDOW.0 || h.0.is_null() || quando == 0 {
        return;
    }
    if GetTickCount64() - quando > 8000 {
        ABRINDO.store(0, Ordering::Relaxed);
        return;
    }
    if GetAncestor(h, GA_ROOT) != h || shell::nossa(h) || !is_taskbar_window(h) {
        return;
    }
    ABRINDO.store(0, Ordering::Relaxed);
    ABRIU.store(h.0 as isize, Ordering::Relaxed);
    ABRIU_EM.store(GetTickCount64(), Ordering::Relaxed);
    SetTimer(None, 0, 100, Some(vigia_abriu));
}
pub fn espera_abrir() {
    use comum::windows::Win32::UI::Accessibility::SetWinEventHook;
    ABRINDO.store(unsafe { GetTickCount64() }, Ordering::Relaxed);
    if ABRINDO_EV.load(Ordering::Relaxed) == 0 {
        let ev = unsafe { SetWinEventHook(EVENT_OBJECT_SHOW, EVENT_OBJECT_SHOW, None, Some(abriu_janela), 0, 0, WINEVENT_OUTOFCONTEXT | shell::sem_proprio()) };
        ABRINDO_EV.store(ev.0 as isize, Ordering::Relaxed);
    }
}
pub fn launch(a: &mut App, args: &str) {
    if shell::foto() {
        return;
    }
    espera_abrir();
    let now = unsafe { GetTickCount() };
    a.launched_at = now;
    a.aberto_em = now;
    unsafe {
        let _ = AllowSetForegroundWindow(ASFW_ANY);
    }
    let (c, args) = (a.clone(), args.to_string());
    std::thread::spawn(move || unsafe {
        let ci = CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
        launch_now(c, &args);
        if ci.is_ok() {
            CoUninitialize();
        }
    });
}
fn launch_now(mut a: App, args: &str) {
    if a.pinned {
        let id0 = a.id.clone();
        if heal(&mut a) {
            let (id, exe, launch) = (a.id.clone(), a.exe.clone(), a.launch.clone());
            shell::na_interface(Box::new(move || {
                if let Some(x) = list().iter_mut().find(|x| x.id == id0) {
                    x.id = id;
                    x.exe = exe;
                    x.launch = launch;
                    save();
                }
            }));
        }
    }
    if chrome_browser(&a.id, &a.exe) && !a.launch.to_lowercase().ends_with(".lnk") && a.chrome_icon.to_lowercase().ends_with("\\google profile.ico") {
        // PR #355: o perfil certo do Chrome (a pasta do perfil é a do ícone)
        let ci = &a.chrome_icon;
        if let Some(end) = ci.rfind('\\') {
            if let Some(start) = ci[..end].rfind('\\') {
                let (profile, folder) = (&ci[start + 1..end], &ci[..start]);
                if !folder.contains('"') && !profile.contains('"') {
                    let mut flags = format!("--user-data-dir=\"{folder}\" --profile-directory=\"{profile}\"");
                    if !args.is_empty() {
                        flags += " ";
                        flags += args;
                    }
                    if launch_no_occlusion(&a.exe, &flags, &a.exe) || shell_open(&a.exe, Some(&flags)) {
                        log!("dock: abrindo {} (perfil {profile})", a.name);
                        return;
                    }
                }
            }
        }
    }
    for c in [&a.launch, &a.exe] {
        let aumid = packaged_aumid(c);
        if aumid.is_empty() {
            continue;
        }
        let target = format!("shell:AppsFolder\\{aumid}");
        if launch_no_occlusion(&target, args, if a.exe.is_empty() { c } else { &a.exe }) || activate_packaged(&target, args) {
            log!("dock: abrindo {} (pacote {aumid})", a.name);
            return;
        }
    }
    if shell::open_calculator(&format!("{}|{}|{}", a.id, a.launch, a.exe)) {
        return;
    }
    if launch_no_occlusion(&a.launch, args, &a.exe) {
        return;
    }
    let lw = format!("{}|{}", a.launch, a.exe).to_lowercase();
    if lw.contains("immersivecontrolpanel") || lw.contains("systemsettings.exe") {
        shell::open_settings("");
        return;
    }
    if activate_packaged(&a.launch, args) {
        log!("dock: abrindo {}", a.name);
        return;
    }
    let (lw2, aw) = (wz(&a.launch), wz(args));
    unsafe {
        ShellExecuteW(None, w!("open"), pc(&lw2), if args.is_empty() { PCWSTR::null() } else { pc(&aw) }, PCWSTR::null(), SW_SHOWNORMAL);
    }
    log!("dock: abrindo {}", a.name);
}
fn force_foreground(h: HWND) {
    unsafe {
        if SetForegroundWindow(h).as_bool() {
            return;
        }
        shell::libera_frente();
        let _ = SetForegroundWindow(h);
    }
}
/// janela oculta pelo Ocultar (minimizada por baixo, mas não aparece no Dock)
pub fn is_hidden(h: HWND) -> bool {
    let k = h.0 as isize;
    let Some(&t) = s().hidden.get(&k) else { return false };
    unsafe {
        if GetTickCount().wrapping_sub(t) < 1500 {
            return true; // ainda minimizando
        }
        if !IsWindow(h).as_bool() || !IsIconic(h).as_bool() {
            s().hidden.remove(&k);
            return false;
        }
    }
    true
}
/// traz todas as janelas para frente (ou abre)
pub fn activate(a: &mut App) {
    if a.wins.is_empty() {
        launch(a, "");
        return;
    }
    unsafe {
        let back: Vec<HWND> = a.wins.iter().filter(|w_| is_hidden(w_.hwnd)).map(|w_| w_.hwnd).collect();
        if !back.is_empty() {
            for h in back.iter().skip(1).rev() {
                s().hidden.remove(&(h.0 as isize));
                let _ = ShowWindowAsync(*h, SW_SHOWNOACTIVATE);
            }
            s().hidden.remove(&(back[0].0 as isize));
            // a da frente sai do ícone do app pelo gênio, como entrou (issue #29)
            let de = crate::dock::app_icon_target(back[0]);
            if de.right > de.left && genio::restore(back[0], de) {
                log!("dock: {} volta pelo gênio ({} janelas)", a.name, back.len());
                return;
            }
            let _ = ShowWindowAsync(back[0], SW_SHOWNOACTIVATE);
            force_foreground(back[0]);
            log!("dock: {} volta ({} janelas)", a.name, back.len());
            return;
        }
        if !a.wins.iter().any(|w_| !w_.minimized) {
            shell::restaurar(a.wins[0].hwnd);
            force_foreground(a.wins[0].hwnd);
            return;
        }
        for w_ in a.wins.iter().rev().filter(|w_| !w_.minimized) {
            let _ = SetWindowPos(w_.hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS);
        }
        if let Some(w_) = a.wins.iter().find(|w_| !w_.minimized) {
            force_foreground(w_.hwnd);
        }
    }
}
/// a janela da frente que o clique no ícone do Dock está ocultando (vai pelo gênio)
pub fn oculta_com_genio(h: HWND) -> bool {
    !h.0.is_null() && h == s().oculta_genio
}
/// Ocultar do Mac: as janelas somem (sem gênio, sem ir para o Dock); clicar no ícone traz de volta
pub fn hide(a: &mut App) {
    unsafe {
        let now = GetTickCount();
        let mut hs = Vec::new();
        for w_ in &a.wins {
            if !w_.minimized && !IsIconic(w_.hwnd).as_bool() {
                s().hidden.insert(w_.hwnd.0 as isize, now);
                hs.push(w_.hwnd);
            }
        }
        s().oculta_genio = HWND::default();
        let mut z = GetTopWindow(None).unwrap_or_default();
        while !z.0.is_null() && s().oculta_genio.0.is_null() {
            if hs.contains(&z) {
                s().oculta_genio = z;
            }
            z = GetWindow(z, GW_HWNDNEXT).unwrap_or_default();
        }
        for h in &hs {
            let _ = ShowWindowAsync(*h, SW_MINIMIZE);
        }
        // a frente passa para a janela de cima de outro app, como no Mac
        let mut all: Vec<HWND> = Vec::new();
        unsafe extern "system" fn cb(h: HWND, l: LPARAM) -> BOOL {
            (*(l.0 as *mut Vec<HWND>)).push(h);
            TRUE
        }
        let _ = EnumWindows(Some(cb), LPARAM(&mut all as *mut _ as isize));
        if let Some(n) = all.into_iter().find(|h| !hs.contains(h) && !IsIconic(*h).as_bool() && is_taskbar_window(*h)) {
            let _ = SetForegroundWindow(n);
        }
        log!("dock: {} oculto ({} janelas)", a.name, hs.len());
    }
}
/// Encerrar = como o "Finalizar tarefa": mata os processos das janelas do app na hora
pub fn quit(a: &mut App) {
    let mut pids: Vec<u32> = Vec::new();
    unsafe {
        for w_ in &a.wins {
            let mut pid = 0;
            GetWindowThreadProcessId(w_.hwnd, Some(&mut pid));
            let mut exe = base_name(&exe_of_window(w_.hwnd)).to_lowercase();
            if exe.ends_with(".exe") {
                exe.truncate(exe.len() - 4);
            }
            if exe == "applicationframehost" {
                // app da Loja: o processo da janela de dentro, nunca o hospedeiro
                let mut f = (pid, 0u32);
                unsafe extern "system" fn cb(c: HWND, l: LPARAM) -> BOOL {
                    let f = &mut *(l.0 as *mut (u32, u32));
                    let mut p = 0;
                    GetWindowThreadProcessId(c, Some(&mut p));
                    if p != 0 && p != f.0 {
                        f.1 = p;
                        return FALSE;
                    }
                    TRUE
                }
                let _ = EnumChildWindows(w_.hwnd, Some(cb), LPARAM(&mut f as *mut _ as isize));
                pid = f.1;
            }
            if a.finder || pid == 0 || pid == GetCurrentProcessId() || exe == "explorer" || exe == "shell" || exe == "sequoiashell" {
                let _ = PostMessageW(w_.hwnd, WM_CLOSE, WPARAM(0), LPARAM(0));
                continue;
            }
            if !pids.contains(&pid) {
                pids.push(pid);
            }
        }
        for &pid in &pids {
            if let Ok(h) = OpenProcess(PROCESS_TERMINATE, false, pid) {
                let _ = TerminateProcess(h, 1);
                let _ = CloseHandle(h);
            }
        }
    }
    log!("dock: encerrado {} ({} processos)", a.name, pids.len());
}
pub fn set_pinned(id: &str, pin: bool) {
    if let Some(a) = find_by_id(id) {
        a.pinned = pin;
        if !pin && a.wins.is_empty() {
            list().retain(|x| x.id != id);
        }
    }
    let (p, o): (Vec<App>, Vec<App>) = std::mem::take(list()).into_iter().partition(|a| a.pinned);
    *list() = p.into_iter().chain(o).collect();
    save();
}
pub fn is_program_file(path: &str) -> bool {
    let l = path.to_lowercase();
    [".lnk", ".exe", ".url", ".appref-ms"].iter().any(|e| l.len() > e.len() && l.ends_with(e))
}
/// programa ou atalho solto no Dock: fica fixo antes do app de índice `at` (-1 = no fim dos fixos)
pub fn pin_path(path: &str, at: i32) -> bool {
    if !is_program_file(path) {
        return false;
    }
    let low = path.to_lowercase();
    let (lnk, exe) = (low.ends_with(".lnk"), low.ends_with(".exe"));
    let (target, aumid) = if lnk {
        read_link(path)
    } else if exe {
        (path.to_string(), String::new())
    } else {
        (String::new(), String::new())
    };
    let t = lower(&target);
    if lnk && t.is_empty() && aumid.is_empty() {
        return false;
    }
    if lnk && !t.is_empty() && std::path::Path::new(&target).is_dir() {
        return false;
    }
    if t.ends_with("explorer.exe") {
        return false;
    }
    let id = if !aumid.is_empty() {
        format!("aumid:{}", lower(&aumid))
    } else if !t.is_empty() {
        t.clone()
    } else {
        low.clone()
    };
    if let Some(a) = list().iter().find(|a| !a.finder && (a.id == id || (!t.is_empty() && !chrome_exe(&t) && lower(&a.exe) == t))) {
        if !a.pinned {
            let i = a.id.clone();
            set_pinned(&i, true);
        }
        return true;
    }
    let file = base_name(path);
    let name = if exe {
        exe_name(path)
    } else {
        file.rsplit_once('.').map(|x| x.0).unwrap_or(file).to_string()
    };
    let x = App { id, exe: t, launch: path.into(), name, pinned: true, ..Default::default() };
    let pinned_end = list().iter().rposition(|a| a.finder || a.pinned).map(|i| i + 1).unwrap_or(0) as i32;
    let pos = if at < 1 || at > pinned_end { pinned_end } else { at };
    list().insert(pos as usize, x);
    save();
    true
}
/// issue #556: um app do Launchpad (item de shell:AppsFolder) fica fixo no Dock sem precisar abrir. Programa com .exe
/// vai pelo pin_path; app da Loja/AUMID entra pelo id "aumid:" (o mesmo de um atalho com AUMID solto no Dock)
pub fn pin_apps_folder(parsing: &str, name: &str) -> bool {
    if parsing.to_lowercase().ends_with(".exe") && std::path::Path::new(parsing).exists() {
        return pin_path(parsing, -1);
    }
    if parsing.is_empty() {
        return false;
    }
    let id = format!("aumid:{}", lower(parsing));
    if let Some(a) = list().iter().find(|a| !a.finder && a.id == id) {
        if !a.pinned {
            let i = a.id.clone();
            set_pinned(&i, true);
        }
        return true;
    }
    let x = App { id, launch: format!("shell:AppsFolder\\{parsing}"), name: name.to_string(), pinned: true, ..Default::default() };
    let pinned_end = list().iter().rposition(|a| a.finder || a.pinned).map(|i| i + 1).unwrap_or(0);
    list().insert(pinned_end, x);
    save();
    true
}
pub fn forget_recent(id: &str) {
    recent().retain(|r| r != id);
    list().retain(|x| !(x.id == id && !x.pinned && x.wins.is_empty()));
}
pub fn move_app(from: usize, to: usize) {
    let n = list().len();
    if from == to || from == 0 || to == 0 || from >= n || to >= n {
        return; // o Finder não sai do lugar
    }
    let a = list().remove(from);
    list().insert(to, a);
    save();
}
fn startup_link(a: &App) -> String {
    let n: String = a.name.chars().map(|c| if "\\/:*?\"<>|".contains(c) { '_' } else { c }).collect();
    format!("{}\\{n}.lnk", crate::menubar::known_folder(&FOLDERID_Startup))
}
pub fn open_at_login(a: &App) -> bool {
    exists(&startup_link(a))
}
pub fn set_open_at_login(a: &App, on: bool) {
    if shell::foto() {
        return;
    }
    let lnk = startup_link(a);
    if !on {
        let _ = std::fs::remove_file(&lnk);
        return;
    }
    unsafe {
        let lw = wz(&a.launch);
        let mut pidl: *mut comum::windows::Win32::UI::Shell::Common::ITEMIDLIST = std::ptr::null_mut();
        if SHParseDisplayName(pc(&lw), None, &mut pidl, 0, None).is_err() {
            return;
        }
        if let Ok(sl) = CoCreateInstance::<_, IShellLinkW>(&ShellLink, None, CLSCTX_INPROC_SERVER) {
            let _ = sl.SetIDList(pidl);
            if let Ok(pf) = sl.cast::<IPersistFile>() {
                let lk = wz(&lnk);
                let _ = pf.Save(pc(&lk), true);
            }
        }
        CoTaskMemFree(Some(pidl as *const c_void));
    }
}
pub fn show_in_finder(a: &App) {
    let mut target = a.exe.clone();
    if target.is_empty() && a.launch.to_lowercase().ends_with(".lnk") {
        target = read_link(&a.launch).0;
    }
    if target.is_empty() {
        target = a.launch.clone();
    }
    shell::abrir(Some("open"), &s().finder_exe.clone(), &format!("\"{target}\""), "", SW_SHOWNORMAL);
}