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
6.1 KB
Raw Blame
//! src\titulos\main.cpp: WacOSTitleBars.exe, só a barra de título do Mac nas janelas dos outros programas, sem o resto
//! do WacOS (sem barra de menus, Dock, mesa; a barra de tarefas do Windows fica). O trabalho é o mesmo do Shell: o
//! `janelas.rs` do Shell (gancho por thread com a WacOSWindow.dll, os de 32 bits pelo rundll32 do Windows), compilado
//! junto com este arquivo.
//!   WacOSTitleBars.exe          liga (uma instância só; com o Shell aberto não faz nada: ele já põe as barras)
//!   WacOSTitleBars.exe --sair   desliga a que estiver rodando (as janelas voltam ao visual do Windows)
//! O Shell, ao abrir, fecha esta e assume. Exclusões: %APPDATA%\Shell\janelas-excluidas.txt. Ajustes lidos: janelas_mac
//! (0 desliga) e o tema (a DLL lê o ajustes.txt sozinha).
#![windows_subsystem = "windows"]

use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::System::LibraryLoader::GetModuleHandleW;
use comum::windows::Win32::System::Threading::{CreateMutexW, ReleaseMutex};
use comum::windows::Win32::UI::Accessibility::*;
use comum::windows::Win32::UI::HiDpi::{SetProcessDpiAwarenessContext, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2};
use comum::windows::Win32::UI::WindowsAndMessaging::*;

#[macro_export]
macro_rules! log {
    ($($t:tt)*) => { $crate::shell::log_linha(&format!($($t)*)) };
}

#[path = "../../../shell/src/janelas.rs"]
#[allow(unused_imports)]
mod janelas;
#[path = "../../../shell/src/jogos.rs"]
#[allow(dead_code)]
mod jogos;

/// o pedaço do shell.rs que o janelas.rs usa: pasta, ajustes (só leitura), log e a volta para a thread da janela
mod shell {
    use std::io::Write;
    use std::sync::Mutex;

    use comum::windows::Win32::Foundation::*;
    use comum::windows::Win32::UI::WindowsAndMessaging::*;
    use comum::Global;

    pub const WM_NA_INTERFACE: u32 = WM_APP + 60;
    pub static UI: Global<isize> = Global::new(0);
    static LOG: Mutex<Option<std::fs::File>> = Mutex::new(None);

    pub fn dir() -> String {
        comum::exe_dir().to_string_lossy().to_string()
    }
    pub fn abre_log() {
        *LOG.lock().unwrap() = std::fs::File::create(format!("{}\\barras-titulo.log", dir())).ok();
    }
    pub fn log_linha(s: &str) {
        if let Some(f) = LOG.lock().unwrap().as_mut() {
            let t = unsafe { comum::windows::Win32::System::SystemInformation::GetLocalTime() };
            let _ = writeln!(f, "{:02}:{:02}:{:02}.{:03} {s}", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
        }
    }
    /// %APPDATA%\Shell\ajustes.txt (o mesmo do Shell), só leitura
    pub fn setting(key: &str, def: &str) -> String {
        comum::ajustes::setting(key, def)
    }
    /// sem gravar no ajustes.txt (aqui só se lê): o aviso da tabela de ganchos cheia fica só no log
    pub fn set_setting(_key: &str, _value: &str) {}
    pub type Tarefa = Box<dyn FnOnce() + Send>;
    /// como no Shell: o resultado de uma thread volta para a thread das janelas
    pub fn na_interface(f: Tarefa) {
        let h = HWND(*UI.get() as *mut _);
        let p = Box::into_raw(Box::new(f));
        unsafe {
            if h.0.is_null() || PostMessageW(h, WM_NA_INTERFACE, WPARAM(0), LPARAM(p as isize)).is_err() {
                drop(Box::from_raw(p));
            }
        }
    }
}
/// sem a notificação do Shell: só o log
mod atualizacao {
    pub fn avisar(title: &str, body: &str) {
        crate::log!("aviso: {title} — {body}");
    }
}

unsafe extern "system" fn on_foreground(_: HWINEVENTHOOK, _: u32, h: HWND, obj: i32, _: i32, _: u32, _: u32) {
    if obj == OBJID_WINDOW.0 && !h.0.is_null() {
        janelas::foreground(h);
    }
}
unsafe extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    match m {
        shell::WM_NA_INTERFACE => {
            if l.0 != 0 {
                let f = Box::from_raw(l.0 as *mut shell::Tarefa);
                f();
            }
            LRESULT(0)
        }
        WM_CLOSE => {
            let _ = DestroyWindow(h);
            LRESULT(0)
        }
        WM_ENDSESSION if w_.0 != 0 => {
            janelas::stop();
            LRESULT(0)
        }
        WM_DESTROY => {
            PostQuitMessage(0);
            LRESULT(0)
        }
        _ => DefWindowProcW(h, m, w_, l),
    }
}
fn main() {
    unsafe {
        if std::env::args().any(|a| a == "--sair") {
            if let Ok(h) = FindWindowW(w!("WacOSBarrasDeTitulo"), None) {
                let _ = PostMessageW(h, WM_CLOSE, WPARAM(0), LPARAM(0));
            }
            return;
        }
        let one = CreateMutexW(None, true, w!("WacOSBarrasDeTituloUmaInstancia"));
        if GetLastError() == ERROR_ALREADY_EXISTS {
            return;
        }
        if FindWindowW(w!("ShellMensagens"), None).is_ok() {
            return; // o Shell aberto já põe as barras
        }
        let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
        shell::abre_log();
        log!("WacOSTitleBars iniciando (só as barras de título, sem o Shell)");
        let hi: HINSTANCE = GetModuleHandleW(None).map(|m| m.into()).unwrap_or_default();
        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hi, lpszClassName: w!("WacOSBarrasDeTitulo"), ..Default::default() });
        // janela comum escondida (não "message-only"): o Shell e o --sair a acham pelo FindWindow
        let Ok(wnd) = CreateWindowExW(WS_EX_TOOLWINDOW, w!("WacOSBarrasDeTitulo"), w!("WacOS Title Bars"), WS_POPUP, 0, 0, 0, 0, None, None, hi, None) else { return };
        *shell::UI.get() = wnd.0 as isize;
        if shell::setting("janelas_mac", "1") != "1" {
            log!("janelas_mac=0 no ajustes.txt: nada a fazer");
        }
        janelas::start();
        let _ = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, None, Some(on_foreground), 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
        let mut msg = MSG::default();
        while GetMessageW(&mut msg, None, 0, 0).0 > 0 {
            let _ = TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
        janelas::stop(); // as janelas voltam ao visual do Windows
        log!("WacOSTitleBars saiu");
        if let Ok(m) = one {
            let _ = ReleaseMutex(m);
        }
    }
}