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
22.0 KB
Raw Blame
//! main.cpp (namespace shell): ajustes (lidos de várias threads; gravados no disco numa thread, atômico), o shell.log
//! (também numa thread: o disco ocupado não segura a interface), abrir programas sem travar (ShellExecute numa thread),
//! rodar na thread da interface, e utilidades usadas por todas as peças.
//!
//! Modo foto: os ajustes ficam só na memória (nada é gravado) e o log não vai para o disco.
#![allow(dead_code)]

use std::collections::BTreeMap;
use std::ffi::c_void;
use std::io::Write;
use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};
use std::sync::{Condvar, Mutex, OnceLock, RwLock};

use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Globalization::*;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Media::Audio::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::SystemInformation::*;
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::Storage::EnhancedStorage::PKEY_Link_TargetParsingPath;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

/// o Shell no modo nativo (dentro do explorer.exe): não portado (sempre false)
pub const NATIVO: bool = false;
static INST: AtomicIsize = AtomicIsize::new(0);
static DIR: OnceLock<String> = OnceLock::new();
static FOTO: AtomicBool = AtomicBool::new(false);
pub fn inst() -> HINSTANCE {
    HINSTANCE(INST.load(Ordering::Relaxed) as *mut c_void)
}
pub fn set_inst(h: HINSTANCE) {
    INST.store(h.0 as isize, Ordering::Relaxed);
}
/// pasta do WacOSShell.exe
pub fn dir() -> String {
    // no teste (target
elease) os outros apps e os ícones não estão ao lado: usa o bin da instalação do WacOS
    DIR.get_or_init(|| {
        let d = exe_dir();
        let bin = install_dir().join("bin");
        if !d.join(nomes::EXE_FINDER).exists() && bin.join(nomes::EXE_FINDER).exists() { bin } else { d }.to_string_lossy().into_owned()
    })
    .clone()
}
pub fn set_foto() {
    FOTO.store(true, Ordering::Relaxed);
}
pub fn foto() -> bool {
    FOTO.load(Ordering::Relaxed)
}
// ---------------------------------------------------------------------------
// log: numa thread própria (gravando direto, a thread da interface ficava presa no WriteFile com o disco lento)
struct Log {
    fila: Mutex<String>,
    cv: Condvar,
    arq: Mutex<Option<std::fs::File>>,
}
static LOG: OnceLock<Log> = OnceLock::new();
/// o shell.log está aberto: log_linha olha só isto. Antes ele travava o `arq`, que a thread do log segura durante o
/// WriteFile + flush; com o disco lento (memória paginando) cada log! na thread da interface esperava o disco e a
/// interface parou 4,2 s num clique do seletor (27/11/2026). O `arq` agora só é usado pela thread do log.
static LOG_ABERTO: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
fn log_() -> &'static Log {
    LOG.get_or_init(|| Log { fila: Mutex::new(String::new()), cv: Condvar::new(), arq: Mutex::new(None) })
}
/// abre o shell.log (o da sessão anterior vira shell-anterior.log)
pub fn log_abrir(caminho: &str) {
    let anterior = caminho.replace("shell.log", "shell-anterior.log");
    let _ = std::fs::rename(caminho, anterior);
    if let Ok(mut f) = std::fs::File::create(caminho) {
        let _ = f.write_all(&[0xEF, 0xBB, 0xBF]);
        *log_().arq.lock().unwrap() = Some(f);
        LOG_ABERTO.store(true, std::sync::atomic::Ordering::Release);
    }
    std::thread::spawn(|| loop {
        {
            let l = log_();
            let mut g = l.fila.lock().unwrap();
            while g.is_empty() {
                g = l.cv.wait(g).unwrap();
            }
        }
        log_grava();
    });
}
fn log_grava() {
    let s = std::mem::take(&mut *log_().fila.lock().unwrap());
    if s.is_empty() {
        return;
    }
    if let Some(f) = log_().arq.lock().unwrap().as_mut() {
        let _ = f.write_all(s.as_bytes());
        let _ = f.flush();
    }
}
pub fn log_linha(linha: &str) {
    let l = log_();
    if !LOG_ABERTO.load(std::sync::atomic::Ordering::Acquire) {
        if foto() {
            eprintln!("{linha}");
        }
        return;
    }
    let st = unsafe { GetLocalTime() };
    let mut g = l.fila.lock().unwrap();
    if g.len() < 4 * 1024 * 1024 {
        g.push_str(&format!("{:02}:{:02}:{:02} {linha}\n", st.wHour, st.wMinute, st.wSecond)); // disco parado de vez: não cresce sem fim
    }
    drop(g);
    l.cv.notify_one();
}
/// fim do Shell: o que faltou vai junto (log e ajustes.txt)
pub fn log_descarrega() {
    espera_ajustes();
    log_grava();
}
#[macro_export]
macro_rules! log {
    ($($t:tt)*) => { $crate::shell::log_linha(&format!($($t)*)) };
}
// ---------------------------------------------------------------------------
// ajustes: lidos de várias threads (vidro, índice, ilha, widgets...) enquanto a interface relê o arquivo
static SETTINGS: RwLock<BTreeMap<String, String>> = RwLock::new(BTreeMap::new());
struct Grav {
    mapa: Option<BTreeMap<String, String>>,
    ocupado: bool,
}
static GRAV: Mutex<Grav> = Mutex::new(Grav { mapa: None, ocupado: false });
static GRAV_CV: Condvar = Condvar::new();
pub fn setting(key: &str, def: &str) -> String {
    SETTINGS.read().unwrap().get(key).cloned().unwrap_or_else(|| def.to_string())
}
fn settings_path() -> std::path::PathBuf {
    data_path("ajustes.txt")
}
/// espera a gravação na fila (até 3 s)
pub fn espera_ajustes() {
    let g = GRAV.lock().unwrap();
    let _ = GRAV_CV.wait_timeout_while(g, std::time::Duration::from_secs(3), |g| g.mapa.is_some() || g.ocupado);
}
/// o valor vale na hora; o arquivo segue logo depois, numa thread (várias mudanças seguidas viram uma gravação só)
pub fn set_setting(key: &str, value: &str) {
    SETTINGS.write().unwrap().insert(key.to_string(), value.to_string());
    if foto() {
        return; // a foto nunca grava o ajustes.txt da pessoa
    }
    // só as chaves mudadas aqui (issue #258): a gravação relê o arquivo e aplica as mudanças por cima. Gravar o mapa
    // inteiro da memória apagava as linhas postas no arquivo depois de o Shell ler (à mão, por outro app ou por uma
    // versão mais nova) e as que só a outra edição conhece
    GRAV.lock().unwrap().mapa.get_or_insert_with(BTreeMap::new).insert(key.to_string(), value.to_string());
    static UMA_VEZ: std::sync::Once = std::sync::Once::new();
    UMA_VEZ.call_once(|| {
        std::thread::spawn(|| loop {
            let m = {
                let mut g = GRAV.lock().unwrap();
                while g.mapa.is_none() {
                    g = GRAV_CV.wait(g).unwrap();
                }
                g.ocupado = true;
                g.mapa.take().unwrap()
            };
            let mut tudo = ajustes::ler(&settings_path()).unwrap_or_else(|_| SETTINGS.read().unwrap().clone());
            tudo.extend(m);
            let _ = ajustes::gravar(&settings_path(), &tudo); // atômico (.tmp + troca)
            GRAV.lock().unwrap().ocupado = false;
            GRAV_CV.notify_all();
        });
    });
    GRAV_CV.notify_all();
}
/// relê o ajustes.txt do zero (uma linha tirada do arquivo volta ao padrão)
pub fn load_settings() {
    espera_ajustes();
    let Ok(novo) = ajustes::ler(&settings_path()) else { return };
    *SETTINGS.write().unwrap() = novo;
    crate::backdrop::reload();
    crate::anim::REDUCE_MOTION.store(setting("reduzir_movimento", "0") == "1", Ordering::Relaxed);
}
/// modo foto: os ajustes da pessoa lidos uma vez, com trocas só na memória
pub fn settings_foto(trocas: &[(&str, &str)]) {
    let mut m = ajustes::ler(&settings_path()).unwrap_or_default();
    for (k, v) in trocas {
        m.insert(k.to_string(), v.to_string());
    }
    *SETTINGS.write().unwrap() = m;
    crate::backdrop::reload();
}
// ---------------------------------------------------------------------------
/// Modo "Só Dock e barra de menus" (modo=dock): lido na partida do Shell
pub fn so_dock() -> bool {
    static V: OnceLock<bool> = OnceLock::new();
    *V.get_or_init(|| setting("modo", "completo") == "dock")
}
/// WINEVENT_SKIPOWNPROCESS fora do modo nativo
pub fn sem_proprio() -> u32 {
    if NATIVO {
        0
    } else {
        WINEVENT_SKIPOWNPROCESS
    }
}
/// a thread atual segura um gancho global de mouse/teclado: prioridade alta e fora do EcoQoS
pub fn thread_de_gancho() {
    unsafe {
        let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
        let s = THREAD_POWER_THROTTLING_STATE { Version: THREAD_POWER_THROTTLING_CURRENT_VERSION, ControlMask: THREAD_POWER_THROTTLING_EXECUTION_SPEED, StateMask: 0 };
        let _ = SetThreadInformation(GetCurrentThread(), ThreadPowerThrottling, &s as *const _ as *const c_void, std::mem::size_of::<THREAD_POWER_THROTTLING_STATE>() as u32);
    }
}
/// janela do próprio Shell (fora do modo nativo: qualquer janela deste processo)
pub fn nossa(h: HWND) -> bool {
    let mut pid = 0;
    unsafe { GetWindowThreadProcessId(h, Some(&mut pid)) };
    pid == unsafe { GetCurrentProcessId() }
}
/// tira a janela de minimizada (numa de administrador o ShowWindow de fora é recusado; o WM_SYSCOMMAND passa)
pub fn restaurar(h: HWND) {
    unsafe {
        let _ = ShowWindow(h, SW_RESTORE);
        if IsIconic(h).as_bool() {
            let _ = PostMessageW(h, WM_SYSCOMMAND, WPARAM(SC_RESTORE as usize), LPARAM(0));
        }
    }
}
/// marca das teclas que nós mesmos injetamos
pub const KEY_MARK: usize = 0x5348_4C4C;
/// pedido de 02/12/2026 (2º Win abrindo o Iniciar): com o Spotlight/Launchpad em foco, o Windows entrega a tecla à janela
/// deles e o gancho do teclado não a vê. A janela trata: uma tecla muda (0xE8) enquanto o Win está apertado faz o Windows
/// ver "Win + outra tecla" e não abrir o Iniciar ao soltar. Devolve true para o Win (e o F13 da tecla trocada)
/// quando a janela do painel fechou pelo Win: o gancho, se também viu a tecla, não abre o painel de novo
pub static FECHADO_PELO_WIN: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
pub fn win_no_painel(vk: u16) -> bool {
    let f13 = vk == 0x7C && setting("tecla_win_f13", "0") == "1";
    if vk != 0x5B && vk != 0x5C && !f13 {
        return false;
    }
    FECHADO_PELO_WIN.store(unsafe { comum::windows::Win32::System::SystemInformation::GetTickCount() }, std::sync::atomic::Ordering::Relaxed);
    if !f13 {
        unsafe {
            keybd_event(0xE8, 0, KEYBD_EVENT_FLAGS(0), KEY_MARK);
            keybd_event(0xE8, 0, KEYEVENTF_KEYUP, KEY_MARK);
        }
    }
    true
}
/// libera o SetForegroundWindow: Alt apertado e solto com uma tecla sem função (vkE8) no meio (sem ligar o menu do app)
pub fn libera_frente() {
    if foto() {
        return;
    }
    unsafe {
        keybd_event(VK_MENU.0 as u8, 0, KEYBD_EVENT_FLAGS(0), KEY_MARK);
        keybd_event(0xE8, 0, KEYBD_EVENT_FLAGS(0), KEY_MARK);
        keybd_event(0xE8, 0, KEYEVENTF_KEYUP, KEY_MARK);
        keybd_event(VK_MENU.0 as u8, 0, KEYEVENTF_KEYUP, KEY_MARK);
    }
}
/// traz h para a frente; o truque do Alt só se o Windows recusar. Issue #250: as teclas falsas chegavam ao app que
/// acabava de ganhar o foco (o Noctty escrevia um "@" a cada vez que voltava pelo Dock)
pub fn traz_pra_frente(h: HWND) {
    unsafe {
        if SetForegroundWindow(h).as_bool() && GetForegroundWindow() == h {
            return;
        }
    }
    libera_frente();
}
/// janelas "sempre por cima" de outros programas acima das nossas (issue #33): pegas antes de subir as nossas
pub fn alheias_no_topo() -> Vec<HWND> {
    let mut v = Vec::new();
    unsafe {
        let eu = GetCurrentProcessId();
        let mut w = GetTopWindow(None).unwrap_or_default();
        while !w.0.is_null() && v.len() < 32 {
            if GetWindowLongW(w, GWL_EXSTYLE) as u32 & WS_EX_TOPMOST.0 == 0 {
                break; // acabou a faixa das "sempre por cima"
            }
            let next = GetWindow(w, GW_HWNDNEXT).unwrap_or_default();
            if IsWindowVisible(w).as_bool() {
                let mut pid = 0;
                GetWindowThreadProcessId(w, Some(&mut pid));
                if pid == eu {
                    break; // daqui para baixo já estavam abaixo das nossas
                }
                let mut cloak = 0u32;
                let _ = DwmGetWindowAttribute(w, DWMWA_CLOAKED, &mut cloak as *mut _ as *mut c_void, 4);
                let cls = class_name(w);
                let mut r = RECT::default();
                if cloak == 0 && !["tooltips_class32", "#32768", "Shell_TrayWnd", "Shell_SecondaryTrayWnd"].contains(&cls.as_str()) && GetWindowRect(w, &mut r).is_ok() && r.right - r.left >= 2 && r.bottom - r.top >= 2 {
                    v.push(w);
                }
            }
            w = next;
        }
    }
    v
}
/// devolve as alheias por cima, na mesma ordem
pub fn devolve_alheias(v: &[HWND]) {
    unsafe {
        for w in v.iter().rev() {
            if IsWindow(*w).as_bool() && IsWindowVisible(*w).as_bool() {
                let _ = SetWindowPos(*w, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_ASYNCWINDOWPOS);
            }
        }
    }
}
pub fn class_name(h: HWND) -> String {
    let mut c = [0u16; 80];
    let n = unsafe { GetClassNameW(h, &mut c) };
    String::from_utf16_lossy(&c[..n.max(0) as usize])
}
pub fn window_text(h: HWND) -> String {
    let mut c = [0u16; 260];
    let n = unsafe { GetWindowTextW(h, &mut c) };
    String::from_utf16_lossy(&c[..n.max(0) as usize])
}
// ---------------------------------------------------------------------------
/// relogio_formato: auto (o do Windows), 24 ou 12 (issue #43)
pub fn hora12() -> bool {
    match setting("relogio_formato", "auto").as_str() {
        "12" => true,
        "24" => false,
        _ => {
            static C: Global<(u64, bool)> = Global::new((0, false));
            let c = C.get();
            let agora = unsafe { GetTickCount64() };
            if c.0 == 0 || agora - c.0 > 60000 {
                let mut b = [0u16; 80];
                unsafe { GetLocaleInfoEx(PCWSTR::null(), LOCALE_STIMEFORMAT, Some(&mut b)) };
                *c = (agora, from_w(&b).contains('h'));
            }
            c.1
        }
    }
}
/// "14:05" ou "2:05 PM"; segundos: com os segundos; ampm: false tira o AM/PM
pub fn hora(st: &SYSTEMTIME, segundos: bool, ampm: bool) -> String {
    if !hora12() {
        return if segundos { format!("{:02}:{:02}:{:02}", st.wHour, st.wMinute, st.wSecond) } else { format!("{:02}:{:02}", st.wHour, st.wMinute) };
    }
    let h = match st.wHour % 12 {
        0 => 12,
        x => x,
    };
    let mut suf = [0u16; 16];
    let n = unsafe { GetLocaleInfoEx(PCWSTR::null(), if st.wHour < 12 { LOCALE_S1159 } else { LOCALE_S2359 }, Some(&mut suf)) };
    let sufixo = if n > 1 { from_w(&suf) } else if st.wHour < 12 { "AM".into() } else { "PM".into() };
    let mut r = if segundos { format!("{h}:{:02}:{:02}", st.wMinute, st.wSecond) } else { format!("{h}:{:02}", st.wMinute) };
    if ampm {
        r += &format!(" {sufixo}");
    }
    r
}
/// a pasta do programa por trás de um item da pasta Aplicativos, de um atalho ou de um .exe (issue #38: DELTARUNE)
pub fn pasta_do_app(alvo: &str) -> String {
    let pasta_do_exe = |p: &str| -> String {
        let mut p = p.to_string();
        if p.len() > 1 && p.starts_with('"') {
            p = p[1..].split('"').next().unwrap_or("").to_string();
        }
        if p.len() < 5 || !p.to_lowercase().ends_with(".exe") || !p.contains(":\\") {
            return String::new();
        }
        p.rfind('\\').map(|b| p[..b].to_string()).unwrap_or_default()
    };
    let d = pasta_do_exe(alvo);
    if !d.is_empty() {
        return d;
    }
    unsafe {
        let wa = wz(alvo);
        if let Ok(it) = SHCreateItemFromParsingName::<_, _, IShellItem2>(pc(&wa), None) {
            if let Ok(t) = it.GetString(&PKEY_Link_TargetParsingPath) {
                let r = pasta_do_exe(&from_w(t.as_wide()));
                CoTaskMemFree(Some(t.0 as *const c_void));
                return r;
            }
        }
    }
    String::new()
}
/// ShellExecute numa thread (com o disco ocupado ele segurou a interface 3,2 s; issue #32)
pub fn abrir(verb: Option<&str>, file: &str, args: &str, dir: &str, show: SHOW_WINDOW_CMD) {
    if foto() || file.is_empty() {
        return;
    }
    unsafe {
        let _ = AllowSetForegroundWindow(ASFW_ANY);
    }
    let mut d = dir.to_string();
    if d.is_empty() && file.to_lowercase().ends_with(".exe") {
        d = pasta_do_app(file); // a pasta do programa (issue #38)
    }
    let (v, f, a) = (verb.map(|s| s.to_string()), file.to_string(), args.to_string());
    std::thread::spawn(move || unsafe {
        let ci = CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
        let (vw, fw, aw, dw) = (wz(v.as_deref().unwrap_or("")), wz(&f), wz(&a), wz(&d));
        let mut se = SHELLEXECUTEINFOW {
            cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
            fMask: SEE_MASK_NOASYNC,
            lpVerb: if v.is_some() { pc(&vw) } else { PCWSTR::null() },
            lpFile: pc(&fw),
            lpParameters: if a.is_empty() { PCWSTR::null() } else { pc(&aw) },
            lpDirectory: if d.is_empty() { PCWSTR::null() } else { pc(&dw) },
            nShow: show.0,
            ..Default::default()
        };
        if ShellExecuteExW(&mut se).is_err() {
            crate::log!("abrir: não abriu {f} ({})", GetLastError().0);
        }
        if ci.is_ok() {
            CoUninitialize();
        }
    });
}
pub fn abrir_simples(file: &str, args: &str) {
    abrir(Some("open"), file, args, "", SW_SHOWNORMAL);
}
fn exe_nosso(nome: &str) -> String {
    format!("{}\\{nome}", dir())
}
/// alvo é a Calculadora do Windows: abre a nossa; sem ela, segue a do Windows (false)
pub fn open_calculator(target: &str) -> bool {
    let t = target.to_lowercase();
    let calc = t.contains("microsoft.windowscalculator") || t == "calc.exe" || t == "calc" || t.ends_with("\\calc.exe") || t.ends_with("calculatorapp.exe") || t.ends_with("\\calculadora.exe") || t.ends_with("\\wacoscalculator.exe");
    if !calc {
        return false;
    }
    let exe = exe_nosso(nomes::EXE_CALCULATOR);
    if !std::path::Path::new(&exe).exists() {
        return false;
    }
    abrir_simples(&exe, "");
    true
}
/// Monitor de Atividade; sem ele, o Gerenciador de Tarefas
pub fn open_monitor() {
    let mut exe = exe_nosso(nomes::EXE_MONITOR);
    if !std::path::Path::new(&exe).exists() {
        exe = "taskmgr.exe".into();
    }
    abrir_simples(&exe, "");
}
/// Forçar Encerrar Aplicativos; sem ele, o Monitor de Atividade
pub fn open_force_quit(memory: bool) {
    let exe = exe_nosso(nomes::EXE_FORCEQUIT);
    if !std::path::Path::new(&exe).exists() {
        open_monitor();
        return;
    }
    unsafe {
        let _ = AllowSetForegroundWindow(ASFW_ANY);
    }
    abrir_simples(&exe, if memory { "--memoria" } else { "" });
}
/// issue #100 (pastas "Downloads" foram parar na Lixeira): pasta que o Shell nunca manda para a Lixeira: raiz de disco,
/// a pasta do usuário e as pastas especiais (Mesa, Documentos, Downloads, Imagens, Músicas, Vídeos, OneDrive, Público...)
pub fn pasta_protegida(path0: &str) -> bool {
    let p = path0.trim_end_matches(['\\', '/']);
    if p.chars().count() <= 3 {
        return true; // "C:\", "C:" ou vazio
    }
    let ids = [
        FOLDERID_Profile,
        FOLDERID_Desktop,
        FOLDERID_Documents,
        FOLDERID_Downloads,
        FOLDERID_Pictures,
        FOLDERID_Music,
        FOLDERID_Videos,
        FOLDERID_SkyDrive,
        FOLDERID_Public,
        FOLDERID_PublicDesktop,
        FOLDERID_PublicDocuments,
        FOLDERID_PublicDownloads,
        FOLDERID_RoamingAppData,
        FOLDERID_LocalAppData,
        FOLDERID_Windows,
        FOLDERID_ProgramFiles,
        FOLDERID_ProgramFilesX86,
        FOLDERID_UserProfiles,
    ];
    let pl = p.to_lowercase();
    ids.iter().any(|id| {
        let k = crate::menubar::known_folder(id);
        !k.is_empty() && k.to_lowercase() == pl
    })
}
/// toca sons\mac\<name>.wav, sem esperar
pub fn sound(name: &str) {
    if foto() {
        return;
    }
    let p = install_dir().join("sons").join("mac").join(format!("{name}.wav"));
    let pw = wz(&p.to_string_lossy());
    unsafe {
        let _ = PlaySoundW(pc(&pw), None, SND_FILENAME | SND_ASYNC | SND_NODEFAULT);
    }
}
/// abre o Ajustes do Sistema na página
pub fn open_settings(page: &str) {
    let args = if page.is_empty() {
        String::new()
    } else if page.starts_with("ms-settings:") {
        page.to_string()
    } else {
        format!("--pagina={page}")
    };
    abrir_simples(&exe_nosso(nomes::EXE_SETTINGS), &args);
}
/// abre o Finder com estes argumentos
pub fn abrir_finder(args: &str) {
    abrir_simples(&exe_nosso(nomes::EXE_FINDER), args);
}
// ---------------------------------------------------------------------------
// rodar na thread da interface (pela janela de mensagens): o resultado de um trabalho feito numa thread
pub const WM_NA_INTERFACE: u32 = WM_APP + 60;
static MSG_WND: AtomicIsize = AtomicIsize::new(0);
pub fn set_msg_wnd(h: HWND) {
    MSG_WND.store(h.0 as isize, Ordering::Relaxed);
}
pub fn msg_wnd() -> HWND {
    HWND(MSG_WND.load(Ordering::Relaxed) as *mut c_void)
}
pub type Tarefa = Box<dyn FnOnce() + Send>;
pub fn na_interface(f: Tarefa) {
    let h = msg_wnd();
    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));
        }
    }
}
/// a mensagem WM_NA_INTERFACE chegou: roda
pub fn roda_na_interface(l: LPARAM) {
    if l.0 != 0 {
        let f = unsafe { Box::from_raw(l.0 as *mut Tarefa) };
        f();
    }
}