A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! jogo.cpp: Modo Jogo (como o Game Mode do macOS): um jogo na frente desliga o que mais pesa (vidro real, Raw Input do
//! "sacudir para localizar", gancho global do mouse, Cantos Ativos, os avisos de posição) e põe o Shell em prioridade
//! abaixo do normal e no EcoQoS; tudo volta quando o jogo fecha. Jogo = jogos.txt, motor (classe da janela), pasta de
//! loja ou Direct3D em tela cheia. Também é o dono do gancho único de EVENT_OBJECT_LOCATIONCHANGE: quem pede recebe só
//! os avisos de janela (o cursor e as barras de rolagem ficam de fora), e ele sai no modo jogo.
#![allow(dead_code)]
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Gdi::{GetMonitorInfoW, MonitorFromWindow, MONITORINFO, MONITOR_DEFAULTTONEAREST};
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::UI::Accessibility::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;
use crate::revelar;
use crate::ponteiro;
use crate::{apps, backdrop, cantos, log, menubar, mesa, shell};
/// lido também por outras threads (índice)
static ON: AtomicBool = AtomicBool::new(false);
/// o jogo está na frente (o vidro real só sai enquanto ele estiver, issue #160)
static FRENTE: AtomicBool = AtomicBool::new(false);
type PosFn = unsafe extern "system" fn(HWINEVENTHOOK, u32, HWND, i32, i32, u32, u32);
struct S {
enabled: bool,
pid: u32,
gone: i32,
name: String,
extra: Vec<String>,
ganchos: Vec<(PosFn, u32)>,
posicao: HWINEVENTHOOK,
posicao_flags: u32,
ticks: u32,
}
static SS: Global<Option<S>> = Global::new(None);
fn s() -> &'static mut S {
SS.get().get_or_insert_with(|| S { enabled: true, pid: 0, gone: 0, name: String::new(), extra: Vec::new(), ganchos: Vec::new(), posicao: HWINEVENTHOOK::default(), posicao_flags: 0, ticks: 0 })
}
static AVISOS: AtomicU32 = AtomicU32::new(0);
static DE_JANELA: AtomicU32 = AtomicU32::new(0);
/// motores e bibliotecas de jogos (classe da janela principal)
const CLASSES: &[&str] = &["UnrealWindow", "UnityWndClass", "SDL_app", "GLFW30", "Valve001", "CryENGINE", "RiotWindowClass", "LWJGL", "SFML_Window", "OgreD3D11Wnd", "TankWindowClass"];
/// pastas de jogos das lojas
const PATHS: &[&str] = &["\\steamapps\\common\\", "\\epic games\\", "\\riot games\\", "\\xboxgames\\", "\\ea games\\", "\\electronic arts\\", "\\ubisoft game launcher\\games\\", "\\gog galaxy\\games\\", "\\rockstar games\\", "\\call of duty\\", "\\overwatch\\"];
/// o que fica em tela cheia e não é jogo (vídeo, apresentação, navegador, os launchers: o Riot Client abre no login)
const NOT_GAMES: &[&str] = &[
"chrome.exe", "msedge.exe", "firefox.exe", "opera.exe", "brave.exe", "vivaldi.exe", "vlc.exe", "mpc-hc64.exe", "mpc-be64.exe", "mpv.exe", "potplayermini64.exe", "powerpnt.exe", "obs64.exe", "steam.exe", "steamwebhelper.exe",
"epicgameslauncher.exe", "explorer.exe", "applicationframehost.exe", "riot client.exe", "riotclientux.exe", "riotclientuxrender.exe", "riotclientservices.exe", "eadesktop.exe", "ealauncher.exe", "upc.exe", "ubisoftconnect.exe",
"battle.net.exe", "galaxyclient.exe", "rockstarlauncher.exe", "epicwebhelper.exe", "hoyoplay.exe",
// o Wallpaper Engine fica em steamapps\common, mas é app de papel de parede: com a janela dele na frente o modo jogo
// ligava e o vidro real ficava fosco (PR #262)
"wallpaperui.exe", "wallpaper32.exe", "wallpaper64.exe", "webwallpaper32.exe", "webwallpaper64.exe",
];
fn load_extra() {
let st = s();
st.extra.clear();
let f = menubar::known_folder(&FOLDERID_RoamingAppData) + "\\Shell\\jogos.txt";
let Ok(b) = std::fs::read(f) else { return };
let t = String::from_utf8_lossy(b.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(&b)).into_owned();
st.extra = t.lines().map(|l| l.trim_end().to_lowercase()).filter(|l| !l.is_empty() && !l.starts_with('#')).collect();
}
fn covers_monitor(h: HWND) -> bool {
unsafe {
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
let mut r = RECT::default();
if !GetMonitorInfoW(MonitorFromWindow(h, MONITOR_DEFAULTTONEAREST), &mut mi).as_bool() || GetWindowRect(h, &mut r).is_err() {
return false;
}
let m = mi.rcMonitor;
r.left <= m.left && r.top <= m.top && r.right >= m.right && r.bottom >= m.bottom
}
}
/// a janela da frente é de um jogo? (e por quê, para o log). Só lê o nome do .exe (anti-cheat)
fn is_game(fg: HWND, pid: u32) -> Option<(String, &'static str)> {
if fg.0.is_null() || pid == 0 || pid == unsafe { GetCurrentProcessId() } || apps::is_shell_window(fg) {
return None;
}
let cls = shell::class_name(fg);
if mesa::is_desk_class(&cls) {
return None;
}
let path = apps::exe_of_pid(pid).to_lowercase();
let exe = path.rsplit('\\').next().unwrap_or("").to_string();
if exe.is_empty() || exe.contains("wacos") || NOT_GAMES.contains(&exe.as_str()) {
return None;
}
if s().extra.iter().any(|e| exe == *e || path.contains(e.as_str())) {
return Some((exe, "jogos.txt"));
}
if CLASSES.contains(&cls.as_str()) {
return Some((exe, "motor de jogo"));
}
if PATHS.iter().any(|p| path.contains(p)) {
return Some((exe, "pasta de jogos"));
}
// Direct3D em tela cheia exclusiva (o Windows sabe): jogo
if unsafe { SHQueryUserNotificationState() }.is_ok_and(|q| q == QUNS_RUNNING_D3D_FULL_SCREEN) && covers_monitor(fg) {
return Some((exe, "Direct3D em tela cheia"));
}
None
}
fn has_window(pid: u32) -> bool {
let mut c = (pid, false);
unsafe extern "system" fn cb(h: HWND, l: LPARAM) -> BOOL {
let c = &mut *(l.0 as *mut (u32, bool));
let mut p = 0;
GetWindowThreadProcessId(h, Some(&mut p));
if p == c.0 && IsWindowVisible(h).as_bool() {
c.1 = true;
return FALSE;
}
TRUE
}
unsafe {
let _ = EnumWindows(Some(cb), LPARAM(&mut c as *mut _ as isize));
}
c.1
}
/// o gancho único de posição: joga fora na hora o que não é janela e repassa o resto a cada um que pediu
unsafe extern "system" fn posicao(hk: HWINEVENTHOOK, ev: u32, h: HWND, obj: i32, child: i32, tid: u32, t: u32) {
AVISOS.fetch_add(1, Ordering::Relaxed);
if obj != OBJID_WINDOW.0 || h.0.is_null() {
return; // cursor, cursor de texto, barras de rolagem: ninguém usa
}
DE_JANELA.fetch_add(1, Ordering::Relaxed);
let st = s();
let mut proprio: Option<bool> = None;
let lista = st.ganchos.clone(); // quem é chamado pode soltar o próprio gancho
for (f, flags) in lista {
if flags & WINEVENT_SKIPOWNPROCESS != 0 && st.posicao_flags & WINEVENT_SKIPOWNPROCESS == 0 {
let eu = *proprio.get_or_insert_with(|| {
let mut pid = 0;
GetWindowThreadProcessId(h, Some(&mut pid));
pid == GetCurrentProcessId()
});
if eu {
continue; // este não quer as do Shell
}
}
f(hk, ev, h, obj, child, tid, t);
}
}
fn ganchos(on: bool) {
let st = s();
unsafe {
if !st.posicao.is_invalid() {
let _ = UnhookWinEvent(st.posicao);
st.posicao = HWINEVENTHOOK::default();
}
if !on || st.ganchos.is_empty() || shell::foto() {
return;
}
// todos dispensam as janelas do próprio Shell (o normal): o Windows já filtra
let todos = st.ganchos.iter().all(|g| g.1 & WINEVENT_SKIPOWNPROCESS != 0);
st.posicao_flags = WINEVENT_OUTOFCONTEXT | if todos { WINEVENT_SKIPOWNPROCESS } else { 0 };
st.posicao = SetWinEventHook(EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_LOCATIONCHANGE, None, Some(posicao), 0, 0, st.posicao_flags);
}
}
fn eco(on: bool) {
unsafe {
let _ = SetPriorityClass(GetCurrentProcess(), if on { BELOW_NORMAL_PRIORITY_CLASS } else { ABOVE_NORMAL_PRIORITY_CLASS });
let s_ = PROCESS_POWER_THROTTLING_STATE { Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, ControlMask: PROCESS_POWER_THROTTLING_EXECUTION_SPEED, StateMask: if on { PROCESS_POWER_THROTTLING_EXECUTION_SPEED } else { 0 } };
let _ = SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &s_ as *const _ as *const _, std::mem::size_of::<PROCESS_POWER_THROTTLING_STATE>() as u32);
}
}
fn apply(on: bool) {
let st = s();
ON.store(on, Ordering::Relaxed);
FRENTE.store(on, Ordering::Relaxed);
if on {
log!("modo jogo: ligado ({}, pid {})", st.name, st.pid);
} else {
log!("modo jogo: desligado ({} fechou)", st.name);
}
backdrop::reload(); // vidro real fora (o backdrop confere jogo::ativo)
ponteiro::pausar(on); // sem Raw Input do mouse
revelar::pausar(on); // sem gancho global do mouse
cantos::pausar(on); // sem ler o ponteiro 20x/s
ganchos(!on); // sem os avisos de posição
eco(on);
if !on {
mesa::depois_do_jogo(); // a troca de tela que ficou para depois
}
}
fn check(fg: HWND) {
let st = s();
if !st.enabled {
return;
}
if ativo() {
// issue #160: com o jogo aberto mas outro app (ou a mesa) na frente, o vidro real volta; o vidro comum ficava
// cinza no Dock e nos widgets com a mesa do WacOS no lugar da do Windows
let mut fp = 0u32;
unsafe { GetWindowThreadProcessId(fg, Some(&mut fp)) };
let frente = fp == st.pid;
if frente != FRENTE.load(Ordering::Relaxed) {
FRENTE.store(frente, Ordering::Relaxed);
backdrop::reload();
}
if has_window(st.pid) {
st.gone = 0;
return;
}
st.gone += 1;
if st.gone < 2 {
return; // ~4 s sem janela nenhuma: o jogo fechou
}
apply(false);
st.pid = 0;
st.gone = 0;
return;
}
let mut pid = 0;
unsafe { GetWindowThreadProcessId(fg, Some(&mut pid)) };
let Some((exe, why)) = is_game(fg, pid) else { return };
st.pid = pid;
st.name = exe;
st.gone = 0;
log!("modo jogo: {} detectado ({why})", st.name);
apply(true);
}
unsafe extern "system" fn tick(_: HWND, _: u32, _: usize, _: u32) {
check(GetForegroundWindow());
let st = s();
st.ticks += 1;
let av = AVISOS.load(Ordering::Relaxed);
if st.ticks % 30 == 0 && av != 0 {
// a cada minuto (diagnóstico de CPU): quantos avisos de posição chegaram
log!("posição: {av} avisos em 60 s, {} de janela repassados a {}", DE_JANELA.load(Ordering::Relaxed), st.ganchos.len());
AVISOS.store(0, Ordering::Relaxed);
DE_JANELA.store(0, Ordering::Relaxed);
}
}
pub fn start() {
reload();
if !shell::foto() {
unsafe { SetTimer(None, 0, 2000, Some(tick)) };
}
}
pub fn reload() {
let st = s();
let was = st.enabled;
st.enabled = shell::setting("modo_jogo", "1") != "0";
load_extra();
if was && !st.enabled && ativo() {
apply(false);
st.pid = 0;
}
}
pub fn foreground(h: HWND) {
check(h);
}
/// no lugar de SetWinEventHook(EVENT_OBJECT_LOCATIONCHANGE...): o mesmo gancho, que sai durante o modo jogo
pub fn gancho_posicao(f: PosFn, flags: u32) {
s().ganchos.push((f, flags));
ganchos(!ativo());
}
pub fn soltar_posicao(f: PosFn) {
let st = s();
if let Some(i) = st.ganchos.iter().position(|g| g.0 as usize == f as usize) {
st.ganchos.remove(i);
ganchos(!ativo());
}
}
pub fn ativo() -> bool {
ON.load(Ordering::Relaxed)
}
/// jogo aberto E na frente: só então o vidro real sai (issue #160)
pub fn vidro_pausado() -> bool {
ON.load(Ordering::Relaxed) && FRENTE.load(Ordering::Relaxed)
}
/// a janela da frente agora é do jogo detectado (issue #360: o Alt+Tab vai ao Windows)
pub fn na_frente() -> bool {
if !ON.load(Ordering::Relaxed) {
return false;
}
let mut pid = 0u32;
unsafe { GetWindowThreadProcessId(GetForegroundWindow(), Some(&mut pid)) };
pid != 0 && pid == s().pid
}