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
18.1 KB
Raw Blame
//! tray.cpp: bandeja própria. Uma Shell_TrayWnd acima da do Explorador recebe o Shell_NotifyIcon dos apps (WM_COPYDATA)
//! e repassa tudo ao Explorador. O modo nativo (pela MacBarra) não foi portado.
#![allow(dead_code)]

use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, Ordering};

use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Gdi::{DeleteObject, GetDC, GetDIBits, GetObjectW, ReleaseDC, BITMAP, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS};
use comum::windows::Win32::System::DataExchange::COPYDATASTRUCT;
use comum::windows::Win32::System::SystemInformation::GetTickCount;
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

use crate::{log, shell};

#[derive(Clone, Default)]
pub struct TrayIcon {
    pub hwnd: HWND,
    pub uid: u32,
    pub guid: GUID,
    pub callback: u32,
    pub version: u32,
    pub icon: HICON,
    pub tip: String,
    pub hidden: bool,
    /// issue #502: quantas vezes o escondido trocou desde trocas_desde (piscar)
    pub trocas: u8,
    pub trocas_desde: u32,
}
/// ícone todo transparente (o "apagado" de quem pisca o ícone da bandeja)
fn icone_vazio(h: HICON) -> bool {
    unsafe {
        let mut ii = ICONINFO::default();
        if GetIconInfo(h, &mut ii).is_err() {
            return false;
        }
        let mut vazio = false;
        if !ii.hbmColor.0.is_null() {
            let mut bm = BITMAP::default();
            GetObjectW(ii.hbmColor, std::mem::size_of::<BITMAP>() as i32, Some(&mut bm as *mut _ as *mut c_void));
            let (w, hh) = (bm.bmWidth, bm.bmHeight.abs());
            if bm.bmBitsPixel == 32 && w > 0 && hh > 0 && w <= 256 && hh <= 256 {
                let bi = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: w, biHeight: -hh, biPlanes: 1, biBitCount: 32, biCompression: BI_RGB.0, ..Default::default() }, ..Default::default() };
                let mut v = vec![0u8; (w * hh * 4) as usize];
                let dc = GetDC(None);
                let ok = GetDIBits(dc, ii.hbmColor, 0, hh as u32, Some(v.as_mut_ptr() as *mut c_void), &bi as *const _ as *mut _, DIB_RGB_COLORS) > 0;
                ReleaseDC(None, dc);
                vazio = ok && v.chunks_exact(4).all(|p| p[3] == 0 && p[0] == 0 && p[1] == 0 && p[2] == 0);
            }
            let _ = DeleteObject(ii.hbmColor);
        }
        if !ii.hbmMask.0.is_null() {
            let _ = DeleteObject(ii.hbmMask);
        }
        vazio
    }
}

#[repr(C, packed(4))]
#[derive(Clone, Copy)]
struct NotifyIconData32 {
    cb_size: u32,
    hwnd: u32,
    uid: u32,
    flags: u32,
    callback: u32,
    icon: u32,
    tip: [u16; 128],
    state: u32,
    state_mask: u32,
    info: [u16; 256],
    version: u32,
    info_title: [u16; 64],
    info_flags: u32,
    guid: GUID,
    balloon: u32,
}
const OFS_TIP: usize = 24;

struct St {
    icons: Vec<TrayIcon>,
    tray: HWND,
    changed: Option<Box<dyn Fn()>>,
    aviso_pendente: bool,
    aviso_desde: u32,
}
static ST: Global<Option<St>> = Global::new(None);
fn s() -> &'static mut St {
    ST.get().get_or_insert_with(|| St { icons: Vec::new(), tray: HWND::default(), changed: None, aviso_pendente: false, aviso_desde: 0 })
}
pub fn icons() -> Vec<TrayIcon> {
    s().icons.clone()
}
/// modo foto: ícones de exemplo (os dados ficam só na memória)
pub fn set_icons(v: Vec<TrayIcon>) {
    s().icons = v;
}
fn explorer_tray() -> HWND {
    unsafe {
        let mut h = HWND::default();
        loop {
            h = FindWindowExW(None, h, w!("Shell_TrayWnd"), PCWSTR::null()).unwrap_or_default();
            if h.0.is_null() {
                return h;
            }
            if h != s().tray {
                return h;
            }
        }
    }
}
fn find(n: &NotifyIconData32) -> Option<usize> {
    let (flags, guid, hwnd, uid) = (n.flags, n.guid, n.hwnd, n.uid);
    // PR #461 (Enesuygurs): com NIF_GUID o Windows identifica o ícone só pelo GUID. Dois ícones de GUIDs diferentes na
    // mesma janela e com o mesmo uid (quase sempre 0) se confundiam e um apagava o outro
    if flags & NIF_GUID.0 != 0 && guid != GUID::zeroed() {
        return s().icons.iter().position(|c| c.guid == guid);
    }
    s().icons.iter().position(|c| c.hwnd.0 as usize == hwnd as usize && c.uid == uid)
}
pub fn is_privacy(t: &TrayIcon) -> bool {
    t.guid.data1 == 0x7820AE82
}
/// pelo texto do ícone (em qualquer idioma do Windows que conhecemos): 1 microfone, 2 câmera
pub fn privacy_bits() -> i32 {
    let mut bits = 0;
    for t in &s().icons {
        if !is_privacy(t) || t.hidden {
            continue;
        }
        let s_ = t.tip.to_lowercase();
        let cam = ["camera", "câmera", "cámara", "caméra", "kamera", "fotocamera", "камер", "カメラ", "카메라", "摄像", "相机", "webcam"].iter().any(|w_| s_.contains(w_));
        let mut mic = ["micro", "mikro", "микрофон", "マイク", "마이크", "麦克风"].iter().any(|w_| s_.contains(w_));
        if !cam && !mic {
            mic = true;
        }
        bits |= mic as i32 | (cam as i32) << 1;
    }
    bits
}
fn apply(c: &mut TrayIcon, n: &NotifyIconData32) {
    let fl = n.flags;
    unsafe {
        if fl & NIF_MESSAGE.0 != 0 {
            c.callback = n.callback;
        }
        if fl & NIF_ICON.0 != 0 {
            // issue #502: o WeChat e o DingTalk "piscam" o ícone com mensagem nova trocando entre o ícone e um vazio
            // (nulo ou todo transparente) a cada meio segundo; na barra do Mac o ícone sumia e voltava e os outros
            // andavam junto. O vazio não substitui o ícone que já está lá (no Mac o ícone fica parado)
            let hi = n.icon;
            let novo = if hi != 0 { CopyIcon(HICON(hi as usize as *mut c_void)).unwrap_or_default() } else { HICON::default() };
            if !c.icon.0.is_null() && (novo.0.is_null() || icone_vazio(novo)) {
                if !novo.0.is_null() {
                    let _ = DestroyIcon(novo);
                }
            } else {
                if !c.icon.0.is_null() {
                    let _ = DestroyIcon(c.icon);
                }
                c.icon = novo;
            }
        }
        if fl & NIF_TIP.0 != 0 {
            let tip = n.tip;
            c.tip = from_w(&tip);
        }
        let (st, sm) = (n.state, n.state_mask);
        if fl & NIF_STATE.0 != 0 && sm & NIS_HIDDEN.0 != 0 {
            let esconde = st & NIS_HIDDEN.0 != 0;
            // o mesmo pisca pelo estado escondido: mostra/esconde 3 vezes em 4 s = piscando, fica à mostra
            if esconde != c.hidden {
                let agora = GetTickCount();
                if agora.wrapping_sub(c.trocas_desde) > 4000 {
                    c.trocas_desde = agora;
                    c.trocas = 0;
                }
                c.trocas = c.trocas.saturating_add(1);
            }
            c.hidden = esconde && !(c.trocas >= 3 && GetTickCount().wrapping_sub(c.trocas_desde) <= 4000);
        }
        if fl & NIF_GUID.0 != 0 {
            c.guid = n.guid;
        }
    }
}
fn on_notify(msg: u32, n: &NotifyIconData32) -> bool {
    let i = find(n);
    let m = NOTIFY_ICON_MESSAGE(msg);
    // PR #461 (Enesuygurs): MODIFY de um ícone que não temos entra como ADD. Antes voltava FALSE, mas a barra do Windows
    // (escondida) conhece o ícone e responde TRUE, então o app nunca mandava o ADD de novo e o ícone não aparecia: os
    // que já estavam na barra do Windows antes do Shell e não respondem ao TaskbarCreated
    let modify_novo = m == NIM_MODIFY && i.is_none() && n.flags & NIF_ICON.0 != 0 && n.icon != 0 && unsafe { IsWindow(HWND(n.hwnd as usize as *mut c_void)).as_bool() };
    match m {
        NIM_ADD | NIM_MODIFY if m == NIM_ADD || modify_novo => {
            if let Some(i) = i {
                // o mesmo GUID de novo (o app reabriu): fica com a janela e o uid novos, senão o clique ia à janela morta
                let c = &mut s().icons[i];
                c.hwnd = HWND(n.hwnd as usize as *mut c_void);
                c.uid = n.uid;
                apply(c, n);
            } else {
                let mut c = TrayIcon { hwnd: HWND(n.hwnd as usize as *mut c_void), uid: n.uid, ..Default::default() };
                apply(&mut c, n);
                log!("bandeja: + {} uid {} guid {:08X} tip \"{}\"{}", shell::class_name(c.hwnd), c.uid, c.guid.data1, c.tip, if modify_novo { " (pelo MODIFY)" } else { "" });
                s().icons.push(c);
            }
        }
        NIM_MODIFY => match i {
            Some(i) => apply(&mut s().icons[i], n),
            None => return false,
        },
        NIM_DELETE => match i {
            Some(i) => {
                let c = s().icons.remove(i);
                if !c.icon.0.is_null() {
                    unsafe {
                        let _ = DestroyIcon(c.icon);
                    }
                }
            }
            None => return false,
        },
        NIM_SETVERSION => match i {
            Some(i) => s().icons[i].version = n.version,
            None => return false,
        },
        NIM_SETFOCUS => {}
        _ => return false,
    }
    if let Some(f) = &s().changed {
        f();
    }
    crate::ilha::privacidade_mudou();
    true
}
/// repassa à barra do Windows (escondida), com limite de tempo: um Explorador travado não segura o Shell
fn forward(m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    let ex = explorer_tray();
    if ex.0.is_null() {
        return LRESULT(0);
    }
    let mut r = 0usize;
    unsafe {
        if SendMessageTimeoutW(ex, m, w_, l, SMTO_ABORTIFHUNG | SMTO_NORMAL, 300, Some(&mut r)).0 != 0 {
            LRESULT(r as isize)
        } else {
            LRESULT(0)
        }
    }
}
/// issue #384: barras de outros programas que reservam uma borda da tela (AppBar: SideDesk). O SHAppBarMessage chega
/// como WM_COPYDATA com dwData 0 (APPBARMSGDATA3264: hWnd em 32 bits no byte 4, uEdge no 12, ABM_* no 40); o
/// Explorador continua tratando, o Shell só anota quem reserva qual borda (principal::work_area_for desconta)
static APPBARS: Global<Vec<(isize, u32)>> = Global::new(Vec::new());
unsafe fn anota_appbar(cd: &COPYDATASTRUCT) {
    if cd.lpData.is_null() || cd.cbData < 44 {
        return;
    }
    let b = cd.lpData as *const u8;
    let hw = HWND(*(b.add(4) as *const u32) as usize as *mut c_void);
    let edge = *(b.add(12) as *const u32);
    let msg = *(b.add(40) as *const u32);
    if !IsWindow(hw).as_bool() || crate::apps::is_shell_window(hw) {
        return;
    }
    let v = APPBARS.get();
    let pos = v.iter().position(|a| a.0 == hw.0 as isize);
    if msg == 1 {
        // ABM_REMOVE
        if let Some(i) = pos {
            v.remove(i);
            log!("appbar: saiu {:?}", hw.0);
        }
    } else if msg == 3 && edge <= 3 {
        // ABM_SETPOS
        match pos {
            Some(i) => v[i].1 = edge,
            None => {
                v.push((hw.0 as isize, edge));
                log!("appbar: {:?} reserva a borda {}", hw.0, edge);
            }
        }
    } else {
        return;
    }
    unsafe extern "system" fn depois(h: HWND, _: u32, id: usize, _: u32) {
        let _ = KillTimer(h, id);
        crate::principal::apply_work_area();
    }
    SetTimer(s().tray, 384, 400, Some(depois)); // depois de o app se pôr no lugar
}
/// as barras que reservam uma borda (hwnd, borda: 0 esquerda, 1 topo, 2 direita, 3 embaixo)
pub fn app_bars() -> Vec<(HWND, u32)> {
    let v = APPBARS.get();
    v.retain(|a| unsafe { IsWindow(HWND(a.0 as *mut c_void)).as_bool() });
    v.iter().map(|a| (HWND(a.0 as *mut c_void), a.1)).collect()
}
unsafe extern "system" fn tray_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    if m == WM_COPYDATA && l.0 != 0 {
        let cd = &*(l.0 as *const COPYDATASTRUCT);
        if cd.dwData == 0 {
            anota_appbar(cd);
        }
        if cd.dwData == 1 && cd.cbData as usize >= 8 + OFS_TIP && !cd.lpData.is_null() {
            let mut n: NotifyIconData32 = std::mem::zeroed();
            let len = std::mem::size_of::<NotifyIconData32>().min(cd.cbData as usize - 8);
            let src = (cd.lpData as *const u8).add(8);
            let msg = *(cd.lpData as *const u32).add(1);
            std::ptr::copy_nonoverlapping(src, &mut n as *mut _ as *mut u8, len);
            let ours = on_notify(msg, &n);
            let theirs = forward(m, w_, l);
            return LRESULT((ours || theirs.0 != 0) as isize);
        }
        return forward(m, w_, l);
    }
    if m == WM_WINDOWPOSCHANGED && (*(l.0 as *const WINDOWPOS)).flags.0 & SWP_SHOWWINDOW.0 != 0 {
        let _ = ShowWindow(h, SW_HIDE);
    }
    // mensagens registradas (>= 0xC000) não são do protocolo da bandeja
    if (WM_USER..0xC000).contains(&m) || m == WM_COMMAND || m == WM_ACTIVATEAPP {
        return forward(m, w_, l);
    }
    DefWindowProcW(h, m, w_, l)
}
/// outra Shell_TrayWnd de um WacOSShell (o antigo, num reinício, ainda fechando)
fn outro_shell_com_bandeja() -> bool {
    unsafe {
        let mut h = HWND::default();
        loop {
            h = FindWindowExW(None, h, w!("Shell_TrayWnd"), PCWSTR::null()).unwrap_or_default();
            if h.0.is_null() {
                return false;
            }
            if h == s().tray {
                continue;
            }
            let mut pid = 0;
            GetWindowThreadProcessId(h, Some(&mut pid));
            if pid == 0 || pid == GetCurrentProcessId() {
                continue;
            }
            if crate::apps::exe_of_pid(pid).to_lowercase().contains("wacosshell") {
                return true;
            }
        }
    }
}
fn avisar_apps() {
    s().aviso_pendente = false;
    unsafe {
        let _ = SendNotifyMessageW(HWND_BROADCAST, RegisterWindowMessageW(w!("TaskbarCreated")), WPARAM(0), LPARAM(0));
    }
}
pub fn start(changed: Box<dyn Fn()>) {
    s().changed = Some(changed);
    unsafe {
        let mut tc = WNDCLASSW { lpfnWndProc: Some(tray_proc), hInstance: shell::inst(), lpszClassName: w!("Shell_TrayWnd"), ..Default::default() };
        RegisterClassW(&tc);
        tc.lpszClassName = w!("TrayNotifyWnd");
        RegisterClassW(&tc);
        let mut tb = RECT { left: 0, top: 0, right: 1, bottom: 1 };
        let ex = explorer_tray();
        if !ex.0.is_null() {
            let _ = GetWindowRect(ex, &mut tb);
        }
        s().tray = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW, w!("Shell_TrayWnd"), w!(""), WS_POPUP, tb.left, tb.top, tb.right - tb.left, tb.bottom - tb.top, None, None, shell::inst(), None).unwrap_or_default();
        let _ = CreateWindowExW(WINDOW_EX_STYLE(0), w!("TrayNotifyWnd"), PCWSTR::null(), WS_CHILD, 0, 0, 1, 1, s().tray, None, shell::inst(), None);
    }
    crate::apps::ours().push(s().tray);
    if outro_shell_com_bandeja() {
        s().aviso_pendente = true;
        s().aviso_desde = unsafe { GetTickCount() };
        log!("bandeja: esperando o Shell antigo fechar para chamar os ícones");
    } else {
        avisar_apps();
    }
    log!("bandeja: Shell_TrayWnd próprio criado");
}
static SEM_AVISO: AtomicBool = AtomicBool::new(false);
/// no reinício o "TaskbarCreated" de saída não vai (o Lively lê cada aviso como "o Explorer caiu")
pub fn sem_aviso_ao_sair() {
    SEM_AVISO.store(true, Ordering::Relaxed);
}
pub fn stop() {
    if s().tray.0.is_null() {
        return;
    }
    unsafe {
        let _ = DestroyWindow(s().tray);
    }
    s().tray = HWND::default();
    if !SEM_AVISO.load(Ordering::Relaxed) {
        avisar_apps();
    }
}
pub fn keepalive() {
    unsafe {
        if s().aviso_pendente && (!outro_shell_com_bandeja() || GetTickCount().wrapping_sub(s().aviso_desde) > 15000) {
            log!("bandeja: Shell antigo fechou, chamando os ícones");
            if !s().tray.0.is_null() {
                let _ = SetWindowPos(s().tray, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
            }
            avisar_apps();
        }
        if !s().tray.0.is_null() && FindWindowW(w!("Shell_TrayWnd"), PCWSTR::null()).unwrap_or_default() != s().tray {
            let _ = SetWindowPos(s().tray, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
        }
        // PR #461 (Enesuygurs): ícones de janelas que morreram sem NIM_DELETE (app fechado à força, ou o DELETE foi à
        // barra do Windows) ficavam na lista como fantasmas até alguém clicar neles. A cada 2 s
        static LIMPEZA: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
        let agora = GetTickCount();
        if !s().tray.0.is_null() && agora.wrapping_sub(LIMPEZA.load(Ordering::Relaxed)) > 2000 {
            LIMPEZA.store(agora, Ordering::Relaxed);
            let antes = s().icons.len();
            s().icons.retain(|c| {
                let viva = IsWindow(c.hwnd).as_bool();
                if !viva && !c.icon.0.is_null() {
                    let _ = DestroyIcon(c.icon);
                }
                viva
            });
            let tirados = antes - s().icons.len();
            if tirados > 0 {
                log!("bandeja: {tirados} ícone(s) de janela fechada removido(s)");
                if let Some(f) = &s().changed {
                    f();
                }
                crate::ilha::privacidade_mudou();
            }
        }
    }
}
fn send_icon(c: &TrayIcon, ev: u32, p: POINT) {
    let (w_, l) = if c.version >= 4 { (WPARAM(((p.x as u16 as u32) | (p.y as u16 as u32) << 16) as usize), makelparam(ev as i32, c.uid as i32)) } else { (WPARAM(c.uid as usize), LPARAM(ev as isize)) };
    unsafe {
        let _ = SendNotifyMessageW(c.hwnd, c.callback, w_, l);
    }
}
pub fn click(i: usize, button: u32, p: POINT) {
    let Some(c) = s().icons.get(i).cloned() else { return };
    unsafe {
        if !IsWindow(c.hwnd).as_bool() {
            s().icons.remove(i);
            if let Some(f) = &s().changed {
                f();
            }
            return;
        }
        let mut pid = 0;
        GetWindowThreadProcessId(c.hwnd, Some(&mut pid));
        let _ = AllowSetForegroundWindow(pid);
    }
    let left = button == WM_LBUTTONUP;
    send_icon(&c, if left { WM_LBUTTONDOWN } else { WM_RBUTTONDOWN }, p);
    send_icon(&c, button, p);
    if c.version >= 3 {
        send_icon(&c, if left { NIN_SELECT } else { WM_CONTEXTMENU }, p);
    }
}