A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
// macjanela.cpp, parte 6: abrir/fechar animados, os ganchos por thread (varredura, WM_SHOWWINDOW, menus nativos), as
// entradas exportadas (GetMsgProc, WacOSPropria, WacOSHostW) e a trava de jogos.
/// abrir/fechar como no Mac (o Shell anima). Só janelas de app comuns: com título, de tamanho de janela, fora da tela
/// cheia; nada enquanto o botão do mouse está apertado (aba do Chrome sendo arrastada vira janela nova)
pub fn open_close_eligible(h: HWND) -> bool {
unsafe {
if GetAncestor(h, GA_ROOT) != h || zoomed(h) || iconic(h) {
return false;
}
let (st, ex) = (get_style(h) as u32, get_ex(h) as u32);
if st & WS_CHILD.0 != 0 || ex & (WS_EX_TOOLWINDOW.0 | WS_EX_NOACTIVATE.0 | WS_EX_TOPMOST.0 | WS_EX_LAYERED.0) != 0 {
return false;
}
if st & WS_CAPTION.0 != WS_CAPTION.0 && GetPropW(h, PROP_LEVE).0.is_null() {
return false;
}
if GetAsyncKeyState(VK_LBUTTON.0 as i32) < 0 || GetAsyncKeyState(VK_RBUTTON.0 as i32) < 0 {
return false;
}
let r = win_rect(h);
if r.right - r.left < 200 || r.bottom - r.top < 120 {
return false;
}
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
if GetMonitorInfoW(MonitorFromWindow(h, MONITOR_DEFAULTTONEAREST), &mut mi).as_bool() {
let m = mi.rcMonitor;
if r.left <= m.left && r.top <= m.top && r.right >= m.right && r.bottom >= m.bottom {
return false;
}
}
let c = class_name(h);
if c == "#32768" || c == "tooltips_class32" {
return false;
}
}
find_window("ShellMensagens").is_some()
}
/// mostra a janela de verdade (fim da animação, ou o Shell não respondeu)
pub fn open_reveal(h: HWND) {
unsafe {
let _ = KillTimer(h, 0x4D52);
let _ = KillTimer(h, 0x4D53);
if RemovePropW(h, w!("MacJanelaAbrindo")).unwrap_or_default().0.is_null() {
return;
}
let off: i32 = 0;
let _ = DwmSetWindowAttribute(h, DWMWA_CLOAK, &off as *const _ as *const _, 4);
// com a nossa barra: ela (escondida junto) aparece, e a sombra e os cantos voltam
if let Some(i) = info_subclass(h) {
if !i.overlay.0.is_null() {
let _ = DwmSetWindowAttribute(i.overlay, DWMWA_CLOAK, &off as *const _ as *const _, 4);
}
place_overlay(i);
update_shadow(i);
}
}
}
unsafe extern "system" fn open_safety(h: HWND, _: u32, _: usize, _: u32) {
// pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
crate::guarda((), || {
open_reveal(h);
})
}
/// o app já pintou: o Shell anima
unsafe extern "system" fn open_ready(h: HWND, _: u32, id: usize, _: u32) {
// pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
crate::guarda((), || {
let _ = KillTimer(h, id);
match find_window("ShellMensagens") {
Some(sh) if PostMessageW(sh, reg_msg("ShellJanelaAbrir"), WPARAM(h.0 as usize), LPARAM(0)).is_ok() => {}
_ => open_reveal(h),
}
})
}
/// a janela (e a sombra/barra/cantos, que esperaram junto) aparece: o app já pintou, ou passou o limite
pub unsafe extern "system" fn uncloak_shown(h: HWND, _: u32, _: usize, _: u32) {
// pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
crate::guarda((), || {
let _ = KillTimer(h, 0x4D50);
let _ = KillTimer(h, 0x4D51);
if RemovePropW(h, w!("MacJanelaPintando")).unwrap_or_default().0.is_null() {
return;
}
if !GetPropW(h, w!("MacJanelaAbrindo")).0.is_null() {
// abrir animado: a barra (escondida também) já se posiciona e o Shell anima as duas
let i = info_subclass(h);
let mut ov = HWND::default();
if let Some(i) = i {
ov = i.overlay;
let on: i32 = 1;
if !ov.0.is_null() {
let _ = DwmSetWindowAttribute(ov, DWMWA_CLOAK, &on as *const _ as *const _, 4);
place_overlay(i);
}
if !i.shadow.wnd.0.is_null() {
let _ = ShowWindow(i.shadow.wnd, SW_HIDE);
}
hide_corners(i);
}
if let Some(sh) = find_window("ShellMensagens") {
if PostMessageW(sh, reg_msg("ShellJanelaAbrir"), WPARAM(h.0 as usize), LPARAM(ov.0 as isize)).is_ok() {
SetTimer(h, 0x4D53, 900, Some(open_safety));
return;
}
}
open_reveal(h);
return;
}
if let Some(i) = info_subclass(h) {
if i.custom && i.filho {
place_overlay(i); // a faixa antes da janela (sem piscar; PR #263)
let _ = DwmFlush();
}
}
let off: i32 = 0;
let _ = DwmSetWindowAttribute(h, DWMWA_CLOAK, &off as *const _ as *const _, 4);
if let Some(i) = info_subclass(h) {
place_overlay(i);
update_shadow(i);
keep_above(i);
}
})
}
// ---- ganchos por thread. A última varredura de cada thread fica no TLS pedido ao Windows (TlsAlloc): numa DLL
// carregada por gancho o TLS implícito não existe nas threads que o programa já tinha (o C++ derrubava o programa).
pub static G_TLS: AtomicU32 = AtomicU32::new(TLS_OUT_OF_INDEXES);
pub static G_TLS_SHOW: AtomicU32 = AtomicU32::new(TLS_OUT_OF_INDEXES);
pub static G_TLS_POS: AtomicU32 = AtomicU32::new(TLS_OUT_OF_INDEXES);
fn tls_get(slot: &AtomicU32) -> isize {
let i = slot.load(Ordering::SeqCst);
if i == TLS_OUT_OF_INDEXES {
return 0;
}
unsafe { TlsGetValue(i) as isize }
}
fn tls_set(slot: &AtomicU32, v: isize) {
let i = slot.load(Ordering::SeqCst);
if i != TLS_OUT_OF_INDEXES {
unsafe {
let _ = TlsSetValue(i, Some(v as *const _));
}
}
}
fn host_de_menus() -> bool {
unsafe { FindWindowExW(HWND_MESSAGE, None, w!("ShellMenusHost"), None).is_ok() }
}
/// aviso do Windows dentro do programa (WinEvent "no contexto"): menu nativo (#32768) sendo mostrado com o Shell
/// trocando os menus pelo do Mac sai da tela antes de ser desenhado; o lugar fica guardado (ShellMenuX/Y)
// ---- Esta cópia ficou velha (porte do 23fcb08 do C++): o Shell foi aberto com outra versão da DLL, escreveu o caminho
// dela no mapa (Local\WacOSGanchoMapa1) e a carregadora já passa as mensagens para a nova. As cópias antigas ficam
// presas no app (PIN, ver DllMain) e os ganchos que ELAS puseram na thread (show_proc, menu_show_event) e o vigia das
// travadas seguiam rodando: só o owner_proc os tirava, então nos apps de barra própria nada tirava. Com 10 versões
// acumuladas, cada janela que se escondia esperava até 10 x 150 ms pelo Shell e o app travava (27/11/2026).
// Sem o mapa (Shell fechado) ou sem caminho nele: não é velha (o jeito de antes).
pub static MEU_CAMINHO: std::sync::OnceLock<String> = std::sync::OnceLock::new();
static MAPA_VISTA: AtomicUsize = AtomicUsize::new(0);
static GEN_VISTO: AtomicI32 = AtomicI32::new(i32::MIN);
static VELHA: AtomicBool = AtomicBool::new(false);
pub fn velha() -> bool {
if G_PROPRIO.load(Ordering::Relaxed) {
return false;
}
let Some(eu) = MEU_CAMINHO.get().filter(|s| !s.is_empty()) else { return false };
unsafe {
let mut v = MAPA_VISTA.load(Ordering::Acquire);
if v == 0 {
let Ok(h) = OpenFileMappingW(FILE_MAP_READ.0, false, w!("Local\\WacOSGanchoMapa1")) else { return false };
let vista = MapViewOfFile(h, FILE_MAP_READ, 0, 0, std::mem::size_of::<GanchoMapa>());
let _ = CloseHandle(h); // a vista mantém o mapa vivo
if vista.Value.is_null() {
return false;
}
if (*(vista.Value as *const GanchoMapa)).tamanho as usize != std::mem::size_of::<GanchoMapa>() {
let _ = UnmapViewOfFile(vista);
return false;
}
match MAPA_VISTA.compare_exchange(0, vista.Value as usize, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => v = vista.Value as usize,
Err(outra) => {
let _ = UnmapViewOfFile(vista);
v = outra;
}
}
}
let mp = v as *const GanchoMapa;
let gen = std::ptr::read_volatile(std::ptr::addr_of!((*mp).gen));
if gen != GEN_VISTO.load(Ordering::Relaxed) {
#[cfg(target_pointer_width = "64")]
let caminho = std::ptr::read_volatile(std::ptr::addr_of!((*mp).real64));
#[cfg(target_pointer_width = "32")]
let caminho = std::ptr::read_volatile(std::ptr::addr_of!((*mp).real32));
let n = caminho.iter().position(|&c| c == 0).unwrap_or(caminho.len());
let p = String::from_utf16_lossy(&caminho[..n]);
VELHA.store(!p.is_empty() && !p.eq_ignore_ascii_case(eu), Ordering::Relaxed);
GEN_VISTO.store(gen, Ordering::Relaxed);
}
}
VELHA.load(Ordering::Relaxed)
}
unsafe extern "system" fn menu_show_event(_: HWINEVENTHOOK, _: u32, h: HWND, obj: i32, child: i32, _: u32, _: u32) {
// pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
crate::guarda((), || {
if velha() {
stop_show_hook(); // a versão nova põe os dela nesta thread
return;
}
if obj != OBJID_WINDOW.0 || child != CHILDID_SELF as i32 || h.0.is_null() {
return;
}
if class_name(h) != "#32768" || !GetPropW(h, w!("ShellMenuLivre")).0.is_null() || !host_de_menus() {
return;
}
let r = win_rect(h);
if r.left <= -30000 {
return;
}
// +40000: 0 não vale como propriedade
let _ = SetPropW(h, w!("ShellMenuX"), HANDLE((r.left + 40000) as isize as *mut _));
let _ = SetPropW(h, w!("ShellMenuY"), HANDLE((r.top + 40000) as isize as *mut _));
let _ = SetWindowPos(h, None, -32000, -32000, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
})
}
fn cloaked(h: HWND) -> bool {
let mut c = 0i32;
unsafe { DwmGetWindowAttribute(h, DWMWA_CLOAKED, &mut c as *mut _ as *mut _, 4).is_ok() && c != 0 }
}
fn abre_escondida(h: HWND) {
unsafe {
let on: i32 = 1;
if DwmSetWindowAttribute(h, DWMWA_CLOAK, &on as *const _ as *const _, 4).is_ok() {
let _ = SetPropW(h, w!("MacJanelaAbrindo"), HANDLE(1 as *mut _));
SetTimer(h, 0x4D52, 45, Some(open_ready)); // ~3 quadros para o app pintar
SetTimer(h, 0x4D53, 900, Some(open_safety)); // o Shell não respondeu: aparece assim mesmo
}
}
}
/// segundo gancho, posto pela própria DLL só nesta thread (sem módulo): pega a janela nova no WM_SHOWWINDOW, antes de
/// ela aparecer, então já abre com a barra do Mac na cor certa
unsafe extern "system" fn show_proc(code: i32, w_: WPARAM, l: LPARAM) -> LRESULT {
// pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
crate::guarda(LRESULT(0), || {
if code >= 0 && velha() {
stop_show_hook(); // cópia velha: sai da thread
return CallNextHookEx(None, code, w_, l);
}
if code >= 0 && l.0 != 0 {
let m = &*(l.0 as *const CWPRETSTRUCT);
let h = m.hwnd;
// menu nativo (#32768) nascendo com o Shell trocando os menus: já nasce invisível (alfa 0)
if m.message == WM_CREATE && class_name(h) == "#32768" && host_de_menus() {
comum::util::set_wlp(h, GWL_EXSTYLE, comum::util::get_wlp(h, GWL_EXSTYLE) | WS_EX_LAYERED.0 as isize);
let _ = SetLayeredWindowAttributes(h, COLORREF(0), 0, LWA_ALPHA);
}
let wp = if m.message == WM_WINDOWPOSCHANGING && m.lParam.0 != 0 { Some(&*(m.lParam.0 as *const WINDOWPOS)) } else { None };
// vai sumir (fechar/esconder, não minimizar): o Shell tira a foto agora, com ela ainda na tela, e anima
if let Some(wp) = wp {
if wp.flags.0 & SWP_HIDEWINDOW.0 != 0 && visible(h) && GetPropW(h, w!("MacJanelaAbrindo")).0.is_null() && open_close_eligible(h) && !cloaked(h) {
let mut bar = 0isize; // com a nossa barra: o Shell desenha a barra na foto (cor e tipo dela)
if let Some(i) = info_subclass(h) {
let cap = if i.cap == CLR_INVALID {
if i.dark {
rgb(0x2D, 0x2D, 0x2F)
} else {
rgb(0xE9, 0xE9, 0xEA)
}
} else {
i.cap
};
let fl: isize = if i.custom {
0
} else if i.tool {
3
} else {
1
};
bar = 0x1000000 | (fl << 25) | (cap & 0xFFFFFF) as isize;
}
if let Some(sh) = find_window("ShellMensagens") {
let mut ok = 0usize;
let _ = SendMessageTimeoutW(sh, reg_msg("ShellJanelaFechar"), WPARAM(h.0 as usize), LPARAM(bar), SMTO_ABORTIFHUNG, 150, Some(&mut ok));
}
}
// aparecendo por SetWindowPos(SWP_SHOWWINDOW) (não manda WM_SHOWWINDOW): também abre animado
if wp.flags.0 & SWP_SHOWWINDOW.0 != 0 && !visible(h) && GetPropW(h, PROP).0.is_null() && GetPropW(h, w!("MacJanelaAbrindo")).0.is_null() && open_close_eligible(h) {
abre_escondida(h);
}
}
if m.message == WM_SHOWWINDOW && m.wParam.0 != 0 {
let md = mode(h, true);
if md != 0 {
attach(h, md);
}
// janela comum aparecendo: escondida (cloak) até o app pintar; o Shell anima e manda mostrar
if GetPropW(h, PROP).0.is_null() && GetPropW(h, w!("MacJanelaAbrindo")).0.is_null() && open_close_eligible(h) {
abre_escondida(h);
}
// janela com a nossa barra aparecendo: fica escondida uns quadros até o app pintar (aparecia em branco antes)
if !GetPropW(h, PROP).0.is_null() && !zoomed(h) {
let on: i32 = 1;
let _ = DwmSetWindowAttribute(h, DWMWA_CLOAK, &on as *const _ as *const _, 4);
let _ = SetPropW(h, w!("MacJanelaPintando"), HANDLE(1 as *mut _));
if open_close_eligible(h) {
let _ = SetPropW(h, w!("MacJanelaAbrindo"), HANDLE(1 as *mut _)); // depois de pintar: abrir animado
}
if let Some(i) = info_subclass(h) {
// a sombra e a barra esperam junto
for x in [i.overlay, i.minis, i.shadow.wnd] {
if !x.0.is_null() {
let _ = ShowWindow(x, SW_HIDE);
}
}
hide_corners(i);
}
SetTimer(h, 0x4D51, 80, Some(uncloak_shown)); // limite; o normal é logo depois da primeira pintura
}
}
// controle criado depois (página nova de uma folha de propriedades): entra no visual do Mac também
if m.message == WM_CREATE && get_style(h) as u32 & WS_CHILD.0 != 0 {
let root = GetAncestor(h, GA_ROOT);
if !root.0.is_null() && !GetPropW(root, w!("MacCtl")).0.is_null() {
controles::child(h); // diálogo já no visual do Mac
}
}
}
CallNextHookEx(None, code, w_, l)
})
}
pub fn stop_show_hook() {
unsafe {
let hk = tls_get(&G_TLS_SHOW);
if hk != 0 {
let _ = UnhookWindowsHookEx(HHOOK(hk as *mut _)); // volta com a próxima varredura (Shell aberto de novo)
tls_set(&G_TLS_SHOW, 0);
}
let hp = tls_get(&G_TLS_POS);
if hp != 0 {
let _ = UnhookWinEvent(HWINEVENTHOOK(hp as *mut _));
tls_set(&G_TLS_POS, 0);
}
}
}
fn registra_msgs() {
for (slot, nome) in [(&G_MSG_UNDO, "MacJanelaDesfazer"), (&G_MSG_ZOOM, "MacJanelaAmpliar"), (&G_MSG_TILE, "MacJanelaEncaixar")] {
if slot.load(Ordering::SeqCst) == 0 {
slot.store(reg_msg(nome), Ordering::SeqCst);
}
}
}
static MSG_ABRIU: AtomicU32 = AtomicU32::new(0);
/// o gancho por thread instalado pelo Shell (pela carregadora): a cada mensagem (no máximo a cada 400 ms) procura
/// janelas novas desta thread e as transforma
#[no_mangle]
pub unsafe extern "system" fn GetMsgProc(code: i32, w_: WPARAM, l: LPARAM) -> LRESULT {
// pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
crate::guarda(LRESULT(0), || {
if code >= 0 && w_.0 == PM_REMOVE.0 as usize && l.0 != 0 {
// o Shell terminou a animação de abrir: a janela de verdade aparece
let opened = reg_static("MacJanelaAbriu", &MSG_ABRIU);
let msg = &*(l.0 as *const MSG);
if msg.message == opened && opened != 0 && !msg.hwnd.0.is_null() {
open_reveal(msg.hwnd);
}
}
if code >= 0 && G_TLS.load(Ordering::SeqCst) != TLS_OUT_OF_INDEXES && !G_FORA.load(Ordering::SeqCst) {
let now = (tick() | 1) as isize; // nunca 0 (0 = ainda não varreu)
let last = tls_get(&G_TLS);
if last == 0 || (now as u32).wrapping_sub(last as u32) > 400 {
tls_set(&G_TLS, now);
registra_msgs();
let _ = EnumThreadWindows(GetCurrentThreadId(), Some(enum_proc), LPARAM(0));
if G_TLS_SHOW.load(Ordering::SeqCst) != TLS_OUT_OF_INDEXES && tls_get(&G_TLS_SHOW) == 0 {
if let Ok(hk) = SetWindowsHookExW(WH_CALLWNDPROCRET, Some(show_proc), None, GetCurrentThreadId()) {
tls_set(&G_TLS_SHOW, hk.0 as isize);
}
}
if G_TLS_POS.load(Ordering::SeqCst) != TLS_OUT_OF_INDEXES && tls_get(&G_TLS_POS) == 0 {
let hk = SetWinEventHook(EVENT_OBJECT_SHOW, EVENT_OBJECT_SHOW, g_mod(), Some(menu_show_event), GetCurrentProcessId(), GetCurrentThreadId(), WINEVENT_INCONTEXT);
tls_set(&G_TLS_POS, hk.0 as isize);
}
}
}
CallNextHookEx(None, code, w_, l)
})
}
/// os apps do WacOS que não desenham os próprios botões carregam esta DLL eles mesmos e chamam esta entrada na thread
/// da interface, antes de criar a janela: o mesmo gancho do Shell, posto pelo próprio app só na thread dele
#[no_mangle]
pub unsafe extern "system" fn WacOSPropria() -> BOOL {
// pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
crate::guarda(FALSE, || {
if G_PROPRIO.swap(true, Ordering::SeqCst) {
return TRUE;
}
registra_msgs();
let tid = GetCurrentThreadId();
let hk = SetWindowsHookExW(WH_GETMESSAGE, Some(GetMsgProc), None, tid);
// o gancho do WM_SHOWWINDOW já agora: a janela principal nasce com a barra do Mac
if G_TLS_SHOW.load(Ordering::SeqCst) != TLS_OUT_OF_INDEXES && tls_get(&G_TLS_SHOW) == 0 {
if let Ok(s) = SetWindowsHookExW(WH_CALLWNDPROCRET, Some(show_proc), None, tid) {
tls_set(&G_TLS_SHOW, s.0 as isize);
}
}
hk.is_ok().into()
})
}
// ---- programas de 32 bits: o Shell abre o rundll32.exe de 32 bits do Windows com esta DLL, entrada WacOSHost: ela fica
// lá esperando os pedidos do Shell ("ponha a barra de título do Mac na thread X") e sai quando o Shell manda. O gancho
// vai pela carregadora fixa de 32 bits (caminho no mapa do Shell); sem ela, esta própria DLL.
#[repr(C)]
struct GanchoMapa {
tamanho: u32,
gen: i32,
real64: [u16; 520],
real32: [u16; 520],
gancho32: [u16; 520],
}
struct Host {
m: HMODULE,
proc_: isize,
hooks: HashMap<u32, (isize, u64)>,
}
static HOST: Global<Option<Host>> = Global::new(None);
const HOST_HOOK: u32 = WM_APP + 1;
const HOST_QUIT: u32 = WM_APP + 2;
fn host_gancho() {
let st = HOST.get().get_or_insert_with(|| Host { m: HMODULE::default(), proc_: 0, hooks: HashMap::new() });
if st.proc_ != 0 {
return;
}
unsafe {
if let Ok(h) = OpenFileMappingW(FILE_MAP_READ.0, false, w!("Local\\WacOSGanchoMapa1")) {
let v = MapViewOfFile(h, FILE_MAP_READ, 0, 0, std::mem::size_of::<GanchoMapa>());
if !v.Value.is_null() {
let mp = &*(v.Value as *const GanchoMapa);
if mp.tamanho as usize == std::mem::size_of::<GanchoMapa>() && mp.gancho32[0] != 0 {
if let Ok(d) = LoadLibraryW(PCWSTR(mp.gancho32.as_ptr())) {
if let Some(p) = GetProcAddress(d, s!("GetMsgProc")) {
st.m = d;
st.proc_ = p as isize;
}
}
}
let _ = UnmapViewOfFile(v);
}
let _ = CloseHandle(h);
}
if st.proc_ == 0 {
st.m = HMODULE(g_mod().0);
st.proc_ = GetMsgProc as *const () as usize as isize;
}
}
}
/// quando a thread nasceu (0 se já não existe): o Windows reaproveita os números de thread
fn thread_born(tid: u32) -> u64 {
unsafe {
let Ok(th) = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, false, tid) else { return 0 };
let (mut c, mut e, mut k, mut u) = (FILETIME::default(), FILETIME::default(), FILETIME::default(), FILETIME::default());
let r = if GetThreadTimes(th, &mut c, &mut e, &mut k, &mut u).is_ok() { (c.dwHighDateTime as u64) << 32 | c.dwLowDateTime as u64 } else { 0 };
let _ = CloseHandle(th);
r
}
}
unsafe extern "system" fn host_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
// pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
crate::guarda(LRESULT(0), || {
if m == HOST_HOOK {
let tid = w_.0 as u32;
let born = thread_born(tid);
host_gancho();
let st = HOST.get().as_mut().unwrap();
// número de uma thread que já morreu, agora de outra (outro programa): o gancho antigo sumiu com ela
if let Some(&(hk, b)) = st.hooks.get(&tid) {
if b != born {
let _ = UnhookWindowsHookEx(HHOOK(hk as *mut _));
st.hooks.remove(&tid);
}
}
// devolve 0 (gancho posto ou já havia) ou o erro do Windows (tabela de DLLs de gancho cheia: erro 126)
let mut err = 0isize;
if !st.hooks.contains_key(&tid) {
let proc_: HOOKPROC = std::mem::transmute(st.proc_);
match SetWindowsHookExW(WH_GETMESSAGE, proc_, st.m, tid) {
Ok(hk) => {
st.hooks.insert(tid, (hk.0 as isize, born));
}
Err(_) => {
let e = GetLastError().0;
err = if e != 0 { e as isize } else { ERROR_GEN_FAILURE.0 as isize };
}
}
}
if l.0 != 0 && err == 0 {
let _ = PostMessageW(HWND(l.0 as *mut _), WM_NULL, WPARAM(0), LPARAM(0)); // a thread processa uma mensagem e a DLL entra
}
return LRESULT(err);
}
if m == HOST_QUIT {
let _ = DestroyWindow(h);
return LRESULT(0);
}
if m == WM_DESTROY {
if let Some(st) = HOST.get().as_mut() {
for (_, (hk, _)) in st.hooks.drain() {
let _ = UnhookWindowsHookEx(HHOOK(hk as *mut _));
}
}
PostQuitMessage(0);
return LRESULT(0);
}
DefWindowProcW(h, m, w_, l)
})
}
#[no_mangle]
pub unsafe extern "system" fn WacOSHostW(_: HWND, _: HINSTANCE, _: PWSTR, _: i32) {
// pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
crate::guarda((), || {
if FindWindowExW(HWND_MESSAGE, None, w!("MacJanela32Host"), None).is_ok() {
return; // já tem um
}
RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(host_proc), hInstance: g_mod(), lpszClassName: w!("MacJanela32Host"), ..Default::default() });
if CreateWindowExW(WINDOW_EX_STYLE(0), w!("MacJanela32Host"), w!(""), WINDOW_STYLE(0), 0, 0, 0, 0, HWND_MESSAGE, None, g_mod(), None).is_err() {
return;
}
let mut m = MSG::default();
while GetMessageW(&mut m, None, 0, 0).0 > 0 {
DispatchMessageW(&m);
}
})
}
/// segunda trava (a primeira é o Shell): carregada dentro de um jogo, launcher ou programa com anti-cheat, recusa
/// carregar (DllMain devolve FALSE). Pelo caminho do .exe, pelos arquivos ao lado dele e pelos módulos já carregados.
fn dentro_de_jogo() -> bool {
let mut p = [0u16; 260];
let n = unsafe { GetModuleFileNameW(None, &mut p) } as usize;
let caminho = String::from_utf16_lossy(&p[..n]);
let c = caminho.to_lowercase();
// os apps do próprio WacOS e o hospedeiro de 32 bits (rundll32) sempre podem
if c.contains("wacos") || c.contains("\\rundll32.exe") {
return false;
}
if jogos::programa_de_jogo(&caminho) {
return true;
}
let tem = |m: &str| unsafe { GetModuleHandleW(pc(&wz(m))) }.is_ok();
// OBS Studio: o overlay da Steam e o XInput do navegador embutido não fazem dele um jogo; só o anti-cheat conta
if jogos::programa_nao_jogo(&caminho) {
return ["BEClient_x64.dll", "BEClient.dll", "EasyAntiCheat_EOS.dll", "EasyAntiCheat_x64.dll", "EasyAntiCheat.dll"].iter().any(|m| tem(m));
}
[
"GameOverlayRenderer64.dll",
"GameOverlayRenderer.dll",
"UnityPlayer.dll",
"GameAssembly.dll",
"steam_api64.dll",
"steam_api.dll",
"EOSSDK-Win64-Shipping.dll",
"EOSSDK-Win32-Shipping.dll",
"BEClient_x64.dll",
"BEClient.dll",
"EasyAntiCheat_EOS.dll",
"EasyAntiCheat_x64.dll",
"EasyAntiCheat.dll",
"xinput1_3.dll",
"galaxy64.dll",
"discord_game_sdk.dll",
]
.iter()
.any(|m| tem(m))
}
#[no_mangle]
pub unsafe extern "system" fn DllMain(h: HINSTANCE, reason: u32, _: *mut core::ffi::c_void) -> BOOL {
// pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
crate::guarda(TRUE, || {
if reason == 1 {
// DLL_PROCESS_ATTACH
if dentro_de_jogo() {
return FALSE;
}
G_MOD.store(h.0 as isize, Ordering::SeqCst);
// o arquivo desta cópia (bin\obj\mj\WacOSWindow-<data>.dll): velha() compara com o do mapa
let mut buf = [0u16; 520];
let n = GetModuleFileNameW(HMODULE(h.0), &mut buf) as usize;
if n > 0 && n < buf.len() {
let _ = MEU_CAMINHO.set(String::from_utf16_lossy(&buf[..n]));
}
G_TLS.store(TlsAlloc(), Ordering::SeqCst);
G_TLS_SHOW.store(TlsAlloc(), Ordering::SeqCst);
G_TLS_POS.store(TlsAlloc(), Ordering::SeqCst);
let _ = DisableThreadLibraryCalls(HMODULE(h.0));
// fica carregada até o programa fechar: se o Shell cair e o gancho sumir, as janelas que usam o nosso código não
// podem perder a DLL (o programa travaria)
let mut pin = HMODULE::default();
let _ = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, PCWSTR(DllMain as *const () as *const u16), &mut pin);
}
TRUE
})
}