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
118 KB
Raw Blame
//! WacOSSetup (src\setup\main.cpp): instalar, atualizar, modificar e desinstalar o WacOS num programa só, no visual
//! do Instalador do macOS. Tudo nativo: arquivos, atalhos (IShellLink), tarefa de login (Agendador por COM), fontes,
//! cursor, Música e QuickTime em "Abrir com", e o registro em Aplicativos instalados (HKCU).
//!   --atualizar, --desinstalar, --foto <pasta> (cada tela num PNG, claro e escuro, sem instalar nada),
//!   --diagnostico <arquivo>, --teste <instalar|atualizar|desinstalar> <arquivo> (como o C++).
//! O logo vem embutido no exe (include_bytes!), como o recurso 2 do C++.
#![windows_subsystem = "windows"]

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

use comum::app2d::{self, d2d, dw};
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct2D::Common::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::Graphics::Imaging::*;
use comum::windows::Win32::Networking::WinHttp::*;
use comum::windows::Win32::Security::Cryptography::*;
use comum::windows::Win32::Storage::FileSystem::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::Diagnostics::ToolHelp::*;
use comum::windows::Win32::System::LibraryLoader::GetModuleHandleW;
use comum::windows::Win32::System::Registry::*;
use comum::windows::Win32::System::TaskScheduler::*;
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::System::WindowsProgramming::GetUserNameW;
use comum::windows::Win32::UI::Controls::{MARGINS, WM_MOUSELEAVE};
use comum::windows::Win32::UI::HiDpi::*;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

static LOGO: &[u8] = include_bytes!("../../../../docs/logo-256.png");

// ============================================================ textos (português ou inglês, pelo idioma do Windows)
static PT: AtomicBool = AtomicBool::new(false);
fn t(pt: &str, en: &str) -> String {
    if PT.load(Ordering::Relaxed) { pt } else { en }.to_string()
}

// ============================================================ caminhos e utilidades
struct Caminhos {
    me: String,
    me_dir: String,
    src: String,
    dest: String,
    log: String,
}
static P: Global<Option<Caminhos>> = Global::new(None);
fn p() -> &'static mut Caminhos {
    P.get().as_mut().unwrap()
}
fn env(n: &str) -> String {
    std::env::var(n).unwrap_or_default()
}
fn exists(p: &str) -> bool {
    std::path::Path::new(p).exists()
}
fn is_dir(p: &str) -> bool {
    std::path::Path::new(p).is_dir()
}
fn parent(p: &str) -> String {
    p.rfind('\\').map(|i| p[..i].to_string()).unwrap_or(p.to_string())
}
fn leaf(p: &str) -> String {
    p.rfind('\\').map(|i| p[i + 1..].to_string()).unwrap_or(p.to_string())
}
fn ext_of(p: &str) -> String {
    let l = leaf(p);
    l.rfind('.').map(|i| l[i..].to_lowercase()).unwrap_or_default()
}
fn mk_dirs(p: &str) {
    let _ = std::fs::create_dir_all(p);
}
fn known(id: &GUID) -> String {
    unsafe {
        match SHGetKnownFolderPath(id, KNOWN_FOLDER_FLAG(0), None) {
            Ok(x) => {
                let s = from_w(x.as_wide());
                CoTaskMemFree(Some(x.0 as *const c_void));
                s
            }
            Err(_) => String::new(),
        }
    }
}
/// UTF-8 (com ou sem BOM) ou UTF-16
fn read_text(path: &str) -> String {
    let Ok(b) = std::fs::read(path) else { return String::new() };
    if b.len() >= 2 && b[0] == 0xFF && b[1] == 0xFE {
        let u: Vec<u16> = b[2..].chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
        return String::from_utf16_lossy(&u);
    }
    let b = if b.starts_with(&[0xEF, 0xBB, 0xBF]) { &b[3..] } else { &b[..] };
    String::from_utf8_lossy(b).to_string()
}
/// UTF-8 com BOM (como o Set-Content -Encoding utf8)
fn write_text(path: &str, text: &str) -> bool {
    let mut v = vec![0xEF, 0xBB, 0xBF];
    v.extend(text.as_bytes());
    std::fs::write(path, v).is_ok()
}
fn lines(t: &str) -> Vec<String> {
    t.lines().map(|l| l.trim_end_matches('\r').to_string()).collect()
}
/// instalacao.log, o mesmo formato do instalar.ps1 (o desinstalar lê)
fn anota(line: &str) {
    use std::io::Write;
    let log = &p().log;
    if log.is_empty() {
        return;
    }
    let nova = !exists(log);
    let Ok(mut f) = std::fs::OpenOptions::new().append(true).create(true).open(log) else { return };
    let st = app2d::local_now();
    let mut s = Vec::new();
    if nova {
        s.extend([0xEF, 0xBB, 0xBF]);
    }
    s.extend(format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02} {line}\r\n", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond).as_bytes());
    let _ = f.write_all(&s);
}
/// bin\versao.txt, linha 1 (build-N)
fn version_of(root: &str) -> String {
    lines(&read_text(&format!("{root}\\bin\\versao.txt"))).first().map(|l| l.trim().to_string()).unwrap_or_default()
}

// ============================================================ processos
fn pids(exe: &str) -> Vec<u32> {
    let mut r = Vec::new();
    unsafe {
        let Ok(s) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) else { return r };
        let mut e = PROCESSENTRY32W { dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32, ..Default::default() };
        let mut ok = Process32FirstW(s, &mut e).is_ok();
        while ok {
            let n = e.szExeFile.iter().position(|&c| c == 0).unwrap_or(260);
            if from_w(&e.szExeFile[..n]).eq_ignore_ascii_case(exe) && (!exe.to_lowercase().starts_with("wacos") || desta_instalacao_pid(e.th32ProcessID)) {
                r.push(e.th32ProcessID);
            }
            ok = Process32NextW(s, &mut e).is_ok();
        }
        let _ = CloseHandle(s);
    }
    r
}
/// o processo é desta edição (a do Rust)? Um WacOS do C++ aberto ao lado nunca é fechado por este instalador
fn desta_instalacao_pid(pid: u32) -> bool {
    use comum::windows::Win32::System::Threading::{QueryFullProcessImageNameW, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION};
    unsafe {
        let Ok(h) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid) else { return false };
        let mut b = [0u16; 1024];
        let mut n = b.len() as u32;
        let ok = QueryFullProcessImageNameW(h, PROCESS_NAME_WIN32, PWSTR(b.as_mut_ptr()), &mut n).is_ok();
        let _ = CloseHandle(h);
        ok && comum::edicao::desta_instalacao(&String::from_utf16_lossy(&b[..n as usize]))
    }
}
fn running(exe: &str) -> bool {
    !pids(exe).is_empty()
}
fn kill(exe: &str) {
    for pid in pids(exe) {
        unsafe {
            if let Ok(h) = OpenProcess(PROCESS_TERMINATE | PROCESS_SYNCHRONIZE, FALSE, pid) {
                let _ = TerminateProcess(h, 1);
                WaitForSingleObject(h, 3000);
                let _ = CloseHandle(h);
            }
        }
    }
}
fn run_wait(exe: &str, args: &str, ms: u32, hide: bool) -> u32 {
    unsafe {
        let mut cmd = wz(&format!("\"{exe}\" {args}"));
        let dir = wz(&parent(exe));
        let mut si = STARTUPINFOW { cb: std::mem::size_of::<STARTUPINFOW>() as u32, ..Default::default() };
        if hide {
            si.dwFlags = STARTF_USESHOWWINDOW;
            si.wShowWindow = SW_HIDE.0 as u16;
        }
        let mut pi = PROCESS_INFORMATION::default();
        if CreateProcessW(None, PWSTR(cmd.as_mut_ptr()), None, None, FALSE, if hide { CREATE_NO_WINDOW } else { PROCESS_CREATION_FLAGS(0) }, None, pc(&dir), &si, &mut pi).is_err() {
            return u32::MAX;
        }
        WaitForSingleObject(pi.hProcess, ms);
        let mut code = 0u32;
        let _ = GetExitCodeProcess(pi.hProcess, &mut code);
        let _ = CloseHandle(pi.hThread);
        let _ = CloseHandle(pi.hProcess);
        code
    }
}
// numa thread: com o antivírus olhando o .exe recém-instalado, o ShellExecute levava segundos (issue #8)
static ABRINDO: AtomicI32 = AtomicI32::new(0);
fn launch(exe: &str, args: &str) {
    ABRINDO.fetch_add(1, Ordering::SeqCst);
    let (exe, args) = (exe.to_string(), args.to_string());
    std::thread::spawn(move || {
        unsafe {
            let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
            let (e, a, d) = (wz(&exe), wz(&args), wz(&parent(&exe)));
            ShellExecuteW(None, w!("open"), pc(&e), if args.is_empty() { PCWSTR::null() } else { pc(&a) }, pc(&d), SW_SHOWNORMAL);
            CoUninitialize();
        }
        ABRINDO.fetch_sub(1, Ordering::SeqCst);
    });
}
/// o exe em uso não pode ser sobrescrito: guarda ao lado como .new e tenta trocar agora mesmo.
/// Se algum processo estiver com o arquivo aberto (o WacOSGancho.dll mora dentro do Explorador e
/// do Chrome, então fechar o Shell não basta), a troca fica marcada para o próximo boot, quando
/// ninguém tem o arquivo aberto. Em paralelo um cmd escondido insiste na troca imediata.
fn agendar_troca(novo: &str, de: &str) {
    let (wn, wd) = (wz(novo), wz(de));
    unsafe {
        if MoveFileExW(pc(&wn), pc(&wd), MOVEFILE_REPLACE_EXISTING).is_ok() {
            return;
        }
        if MoveFileExW(pc(&wn), pc(&wd), MOVEFILE_REPLACE_EXISTING | MOVEFILE_DELAY_UNTIL_REBOOT).is_ok() {
            anota(&format!("adiado para o próximo reinício: {}", leaf(de)));
        }
    }
    let cmd = format!("/c ping -n 2 127.0.0.1 >nul & for /L %i in (1,1,120) do @(move /Y \"{novo}\" \"{de}\" >nul 2>&1 && exit /b 0 || ping -n 2 127.0.0.1 >nul)");
    let (e, a, d) = (wz("cmd.exe"), wz(&cmd), wz(&parent(de)));
    std::thread::spawn(move || {
        unsafe {
            let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
            ShellExecuteW(None, w!("open"), pc(&e), pc(&a), pc(&d), SW_HIDE);
            CoUninitialize();
        }
    });
}
fn wait_gone(exe: &str, ms: u32) -> bool {
    let mut t_ = 0;
    while t_ < ms {
        if !running(exe) {
            return true;
        }
        std::thread::sleep(std::time::Duration::from_millis(250));
        t_ += 250;
    }
    !running(exe)
}
/// o WacOSShell.exe que tem o modo ajudante (--sair, --aplicar-cursor...): os antigos abririam o Shell
fn has_helper(exe: &str) -> bool {
    let Ok(b) = std::fs::read(exe) else { return false };
    // o C++ guarda o texto em UTF-16; o Rust, em UTF-8. Só o UTF-16 fazia o instalador achar que o Shell em Rust não sabe
    // sair: ele não pedia o --sair e falhava com "O WacOS não fechou" ao atualizar uma instalação já em Rust
    let k16: Vec<u8> = "--desfazer-janelas".encode_utf16().flat_map(|u| u.to_le_bytes()).collect();
    let k8 = b"--desfazer-janelas";
    b.windows(k16.len()).any(|w| w == k16.as_slice()) || b.windows(k8.len()).any(|w| w == k8)
}
fn helper() -> String {
    let (dest, src) = (p().dest.clone(), p().src.clone());
    for e in [format!("{dest}\\bin\\WacOSShell.exe"), format!("{src}\\bin\\WacOSShell.exe")] {
        if exists(&e) && has_helper(&e) {
            if !dest.is_empty() && e.starts_with(&dest) {
                // o da instalação pode sair junto com a pasta: usa uma cópia
                let c = format!("{}\\WacOSShell-ajudante.exe", env("TEMP"));
                if std::fs::copy(&e, &c).is_ok() {
                    return c;
                }
            }
            return e;
        }
    }
    String::new()
}

// ============================================================ registro
fn reg_create(root: HKEY, key: &str) -> Option<HKEY> {
    let mut k = HKEY::default();
    let kz = wz(key);
    unsafe { RegCreateKeyExW(root, pc(&kz), 0, None, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, None, &mut k, None).is_ok().then_some(k) }
}
fn name_pc(name: Option<&str>, buf: &mut Vec<u16>) -> PCWSTR {
    match name {
        Some(n) => {
            *buf = wz(n);
            pc(buf)
        }
        None => PCWSTR::null(),
    }
}
fn reg_set_str(root: HKEY, key: &str, name: Option<&str>, v: &str) -> bool {
    let Some(k) = reg_create(root, key) else { return false };
    let mut nb = Vec::new();
    let vz = wz(v);
    let bytes = unsafe { std::slice::from_raw_parts(vz.as_ptr() as *const u8, vz.len() * 2) };
    let r = unsafe { RegSetValueExW(k, name_pc(name, &mut nb), 0, REG_SZ, Some(bytes)).is_ok() };
    unsafe {
        let _ = RegCloseKey(k);
    }
    r
}
fn reg_set_dword(root: HKEY, key: &str, name: &str, v: u32) -> bool {
    let Some(k) = reg_create(root, key) else { return false };
    let mut nb = Vec::new();
    let r = unsafe { RegSetValueExW(k, name_pc(Some(name), &mut nb), 0, REG_DWORD, Some(&v.to_le_bytes())).is_ok() };
    unsafe {
        let _ = RegCloseKey(k);
    }
    r
}
fn reg_set_none(root: HKEY, key: &str, name: &str) {
    if let Some(k) = reg_create(root, key) {
        let mut nb = Vec::new();
        unsafe {
            let _ = RegSetValueExW(k, name_pc(Some(name), &mut nb), 0, REG_NONE, None);
            let _ = RegCloseKey(k);
        }
    }
}
fn reg_get_str(root: HKEY, key: &str, name: Option<&str>) -> String {
    let mut b = [0u16; 1024];
    let mut n = (b.len() * 2) as u32;
    let kz = wz(key);
    let mut nb = Vec::new();
    unsafe {
        if RegGetValueW(root, pc(&kz), name_pc(name, &mut nb), RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | RRF_NOEXPAND, None, Some(b.as_mut_ptr() as *mut c_void), Some(&mut n)).is_err() {
            return String::new();
        }
    }
    let len = b.iter().position(|&c| c == 0).unwrap_or(0);
    from_w(&b[..len])
}
fn reg_del_value(root: HKEY, key: &str, name: &str) {
    let mut k = HKEY::default();
    let kz = wz(key);
    unsafe {
        if RegOpenKeyExW(root, pc(&kz), 0, KEY_SET_VALUE, &mut k).is_ok() {
            let n = wz(name);
            let _ = RegDeleteValueW(k, pc(&n));
            let _ = RegCloseKey(k);
        }
    }
}
fn reg_del_tree(root: HKEY, key: &str) {
    let kz = wz(key);
    unsafe {
        let _ = RegDeleteTreeW(root, pc(&kz));
        let _ = RegDeleteKeyW(root, pc(&kz));
    }
}
/// "HKCU:\Software\X" (como o PowerShell escreve no log) -> HKEY_CURRENT_USER + "Software\X"
fn ps_key(ps: &str) -> Option<(HKEY, String)> {
    let l = ps.to_lowercase();
    if l.starts_with("hkcu:\\") {
        Some((HKEY_CURRENT_USER, ps[6..].to_string()))
    } else if l.starts_with("hklm:\\") {
        Some((HKEY_LOCAL_MACHINE, ps[6..].to_string()))
    } else {
        None
    }
}

// ============================================================ atalhos e tarefa agendada
fn shortcut(lnk: &str, target: &str, desc: &str) -> bool {
    unsafe {
        let Ok(sl) = CoCreateInstance::<_, IShellLinkW>(&ShellLink, None, CLSCTX_INPROC_SERVER) else { return false };
        let (tz, dz) = (wz(target), wz(&parent(target)));
        let _ = sl.SetPath(pc(&tz));
        let _ = sl.SetWorkingDirectory(pc(&dz));
        let _ = sl.SetIconLocation(pc(&tz), 0);
        if !desc.is_empty() {
            let d = wz(desc);
            let _ = sl.SetDescription(pc(&d));
        }
        let Ok(pf) = sl.cast::<IPersistFile>() else { return false };
        let l = wz(lnk);
        pf.Save(pc(&l), TRUE).is_ok()
    }
}
fn task_root() -> Option<(ITaskService, ITaskFolder)> {
    unsafe {
        let svc: ITaskService = CoCreateInstance(&TaskScheduler, None, CLSCTX_INPROC_SERVER).ok()?;
        let e = VARIANT::default();
        svc.Connect(&e, &e, &e, &e).ok()?;
        let root = svc.GetFolder(&BSTR::from("\\")).ok()?;
        Some((svc, root))
    }
}
fn task_exists(name: &str) -> bool {
    task_root().map(|(_, r)| unsafe { r.GetTask(&BSTR::from(name)).is_ok() }).unwrap_or(false)
}
fn task_delete(name: &str) {
    if let Some((_, r)) = task_root() {
        unsafe {
            let _ = r.DeleteTask(&BSTR::from(name), 0);
        }
    }
}
/// ao entrar no Windows, só este usuário, sem administrador, sem limite de tempo (como o Register-ScheduledTask do ps1)
fn task_logon(name: &str, exe: &str, desc: &str) -> bool {
    let Some((svc, root)) = task_root() else { return false };
    (|| -> Result<()> {
        unsafe {
            let def = svc.NewTask(0)?;
            let mut ub = [0u16; 256];
            let mut un = 256u32;
            let who = if GetUserNameW(PWSTR(ub.as_mut_ptr()), &mut un).is_ok() { format!("{}\\{}", env("USERDOMAIN"), from_w(&ub[..un.saturating_sub(1) as usize])) } else { String::new() };
            def.RegistrationInfo()?.SetDescription(&BSTR::from(desc))?;
            let pr = def.Principal()?;
            pr.SetLogonType(TASK_LOGON_INTERACTIVE_TOKEN)?;
            pr.SetRunLevel(TASK_RUNLEVEL_LUA)?;
            let st = def.Settings()?;
            st.SetDisallowStartIfOnBatteries(VARIANT_BOOL(0))?;
            st.SetStopIfGoingOnBatteries(VARIANT_BOOL(0))?;
            st.SetExecutionTimeLimit(&BSTR::from("PT0S"))?;
            st.SetMultipleInstances(TASK_INSTANCES_IGNORE_NEW)?;
            st.SetPriority(4)?;
            let tr_ = def.Triggers()?.Create(TASK_TRIGGER_LOGON)?;
            tr_.cast::<ILogonTrigger>()?.SetUserId(&BSTR::from(who.as_str()))?;
            let ea: IExecAction = def.Actions()?.Create(TASK_ACTION_EXEC)?.cast()?;
            ea.SetPath(&BSTR::from(exe))?;
            ea.SetWorkingDirectory(&BSTR::from(parent(exe).as_str()))?;
            let e = VARIANT::default();
            root.RegisterTaskDefinition(&BSTR::from(name), &def, TASK_CREATE_OR_UPDATE.0, &e, &e, TASK_LOGON_INTERACTIVE_TOKEN, &e)?;
            Ok(())
        }
    })()
    .is_ok()
}

// ============================================================ o que dá para instalar
struct AppInfo {
    exe: &'static str,
    name: &'static str,
    on: bool,
}
const OUR_PROCS: [&str; 20] = [
    "WacOSFinder.exe", "WacOSSettings.exe", "WacOSActivityMonitor.exe", "WacOSTerminal.exe", "WacOSCalculator.exe", "WacOSNotes.exe", "WacOSScreenshot.exe", "WacOSWindow32Host.exe", "WacOSPreview.exe", "WacOSReminders.exe", "WacOSCalendar.exe", "WacOSTextEdit.exe", "WacOSClock.exe",
    "WacOSWeather.exe", "WacOSContacts.exe", "WacOSPhotos.exe", "WacOSTimeMachine.exe", "WacOSMusic.exe", "WacOSQuickTime.exe", "WacOSForceQuit.exe",
];
#[derive(Clone, Copy, PartialEq)]
enum Mode {
    Full,
    Apps,
    Bars,
    AppsBars,
}
const MODES: [Mode; 4] = [Mode::Full, Mode::Apps, Mode::Bars, Mode::AppsBars];
const MODE_ID: [&str; 4] = ["completo", "apps", "barras", "apps+barras"];
fn mode_idx(m: Mode) -> usize {
    MODES.iter().position(|x| *x == m).unwrap()
}
struct Choices {
    mode: Mode,
    autostart: bool,
    cursor: bool,
    fonts: bool,
    assoc: bool,
    launch: bool,
    del_settings: bool,
    clean_cache: bool,
}

// ============================================================ estado compartilhado com a thread de trabalho
static STATUS: Mutex<(String, String)> = Mutex::new((String::new(), String::new())); // (status, erro)
static PROGRESS: AtomicU32 = AtomicU32::new(0);
static BUSY: AtomicBool = AtomicBool::new(false);
static WORK_DONE: AtomicBool = AtomicBool::new(false);
static WORK_OK: AtomicBool = AtomicBool::new(false);
static CHECKING: AtomicBool = AtomicBool::new(false);
fn status(s: &str) {
    STATUS.lock().unwrap().0 = s.to_string();
}
fn fail(s: &str) {
    STATUS.lock().unwrap().1 = s.to_string();
}
fn set_prog(v: f32) {
    PROGRESS.store(v.to_bits(), Ordering::Relaxed);
}
fn prog() -> f32 {
    f32::from_bits(PROGRESS.load(Ordering::Relaxed))
}
fn done(ok: bool) {
    WORK_OK.store(ok, Ordering::SeqCst);
    WORK_DONE.store(true, Ordering::SeqCst);
}

// ============================================================ copiar uma pasta (com progresso)
fn list_files(dir: &str, rel: &str, out: &mut Vec<String>) {
    let Ok(rd) = std::fs::read_dir(dir) else { return };
    for e in rd.flatten() {
        let n = e.file_name().to_string_lossy().to_string();
        let r = if rel.is_empty() { n.clone() } else { format!("{rel}\\{n}") };
        if e.file_type().map(|t| t.is_dir()).unwrap_or(false) {
            list_files(&format!("{dir}\\{n}"), &r, out);
        } else if ext_of(&n) != ".log" {
            out.push(r);
        }
    }
}
fn old_dir() -> String {
    let d = format!("{}\\SequoiaBinariosAntigos", env("LOCALAPPDATA"));
    mk_dirs(&d);
    d
}
fn copy_file(from: &str, to: &str) -> bool {
    let (f, t_) = (wz(from), wz(to));
    unsafe { CopyFileW(pc(&f), pc(&t_), FALSE).is_ok() }
}
fn del_file(p_: &str) -> bool {
    let z = wz(p_);
    unsafe { DeleteFileW(pc(&z)).is_ok() }
}
/// o destino já tem exatamente este conteúdo? (arquivo preso por estar aberto não precisa de troca)
fn same_content(a: &str, b: &str) -> bool {
    let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) else { return false };
    if x.len() != y.len() {
        return false;
    }
    match (std::fs::read(a), std::fs::read(b)) {
        (Ok(p), Ok(q)) => p == q,
        _ => false,
    }
}
/// copia; arquivo preso (exe aberto): se o conteúdo já é o mesmo não há o que trocar, senão
/// renomeia o velho para a pasta de antigos e copia de novo
fn copy_one(from: &str, to: &str) -> bool {
    mk_dirs(&parent(to));
    if copy_file(from, to) {
        del_file(&format!("{to}:Zone.Identifier"));
        return true;
    }
    if same_content(from, to) {
        return true;
    }
    let st = app2d::local_now();
    let old = format!("{}\\inst-{:02}{:02}{:02}-{}", old_dir(), st.wHour, st.wMinute, st.wSecond, leaf(to));
    let (a_, b) = (wz(to), wz(&old));
    unsafe {
        if MoveFileExW(pc(&a_), pc(&b), MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED).is_ok() && copy_file(from, to) {
            del_file(&format!("{to}:Zone.Identifier"));
            return true;
        }
    }
    false
}
/// devolve quantos arquivos falharam e quais falharam (origem e destino)
fn copy_trees(trees: &[(String, String)], p0: f32, p1: f32) -> (i32, Vec<(String, String)>) {
    let mut files = Vec::new();
    for (s, d) in trees {
        let mut f = Vec::new();
        list_files(s, "", &mut f);
        files.extend(f.iter().map(|r| (format!("{s}\\{r}"), format!("{d}\\{r}"))));
    }
    let mut fails = 0;
    let mut falhos: Vec<(String, String)> = Vec::new();
    for (i, (a_, b)) in files.iter().enumerate() {
        if !copy_one(a_, b) {
            fails += 1;
            falhos.push((a_.clone(), b.clone()));
        }
        if i % 8 == 0 {
            status(&format!("{}{}", t("Copiando ", "Copying "), leaf(b)));
            set_prog(p0 + (p1 - p0) * (i + 1) as f32 / files.len() as f32);
        }
    }
    set_prog(p1);
    (fails, falhos)
}
fn shell_delete(path: &str) {
    let mut from = w(path);
    from.extend([0, 0]);
    let mut op = SHFILEOPSTRUCTW { wFunc: FO_DELETE, pFrom: PCWSTR(from.as_ptr()), fFlags: FOF_NO_UI.0 as u16, ..Default::default() };
    unsafe {
        let _ = SHFileOperationW(&mut op);
    }
}

// ============================================================ etapas de trabalho
fn close_everything() -> bool {
    let help = helper();
    if running("WacOSShell.exe") {
        status(&t("Fechando o WacOS…", "Quitting WacOS…"));
        if !help.is_empty() {
            run_wait(&help, "--sair", 20000, true);
        }
        if !wait_gone("WacOSShell.exe", 20000) {
            fail(&t("O WacOS não fechou. Feche-o com Ctrl+Alt+Shift+F12 e tente de novo.", "WacOS didn't quit. Quit it with Ctrl+Alt+Shift+F12 and try again."));
            return false;
        }
    }
    if running("WacOSTitleBars.exe") {
        let tb = format!("{}\\bin\\WacOSTitleBars.exe", p().dest);
        if exists(&tb) {
            run_wait(&tb, "--sair", 10000, true);
        }
        if !wait_gone("WacOSTitleBars.exe", 5000) {
            kill("WacOSTitleBars.exe");
        }
    }
    for pr in OUR_PROCS {
        kill(pr);
    }
    if !running("explorer.exe") {
        launch("explorer.exe", "");
    }
    true
}
/// o Shell foi fechado para copiar os arquivos: se a atualização parar no meio, ele volta agora
fn reabrir_shell() {
    let exe = format!("{}\\bin\\WacOSShell.exe", p().dest);
    if exists(&exe) && !running("WacOSShell.exe") {
        launch(&exe, "");
    }
}
fn programs() -> String {
    known(&FOLDERID_Programs)
}
struct Assoc {
    exe_name: &'static str,
    prog: &'static str,
    type_name: &'static str,
    app: &'static str,
    cap_key: &'static str,
    reg_name: &'static str,
    exts: &'static [&'static str],
}
// nomes em inglês (aparecem em Configurações > Aplicativos padrão e no "Abrir com"; issue #2)
const ASSOC: [Assoc; 3] = [
    Assoc { exe_name: "WacOSMusic.exe", prog: comum::edicao::PROG_MUSICA, type_name: "Audio File", app: "Music", cap_key: comum::edicao::CAP_MUSICA, reg_name: comum::edicao::REG_MUSICA, exts: &[".mp3", ".m4a", ".flac", ".wav", ".aac", ".ogg", ".wma", ".aif", ".aiff", ".opus"] },
    // issue #442: a Pré-Visualização também se oferece para imagens (e PDF), como no Mac; o padrão quem escolhe é o usuário
    Assoc { exe_name: "WacOSPreview.exe", prog: comum::edicao::PROG_PREVIEW, type_name: "Image", app: "Preview", cap_key: comum::edicao::CAP_PREVIEW, reg_name: comum::edicao::REG_PREVIEW, exts: &[".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".tif", ".tiff", ".heic", ".ico", ".pdf"] },
    Assoc { exe_name: "WacOSQuickTime.exe", prog: comum::edicao::PROG_QUICKTIME, type_name: "Movie", app: "QuickTime Player", cap_key: comum::edicao::CAP_QUICKTIME, reg_name: comum::edicao::REG_QUICKTIME, exts: &[".mp4", ".mov", ".m4v", ".mkv", ".avi", ".wmv", ".webm", ".mpg", ".mpeg", ".3gp"] },
];
const ANTIGOS_REG: [&str; 2] = ["Música (Sequoia)", "QuickTime Player (Sequoia)"];
/// o mesmo que tools\musica-registrar.ps1 / quicktime-registrar.ps1 (HKCU; o padrão quem escolhe é o usuário)
fn assoc_register(a_: &Assoc) {
    let hk = HKEY_CURRENT_USER;
    let exe = format!("{}\\bin\\{}", p().dest, a_.exe_name);
    let cmd = format!("\"{exe}\" \"%1\"");
    let cls = format!("Software\\Classes\\{}", a_.prog);
    reg_set_str(hk, &cls, None, a_.type_name);
    reg_set_str(hk, &cls, Some("FriendlyTypeName"), a_.type_name);
    reg_set_str(hk, &format!("{cls}\\DefaultIcon"), None, &format!("\"{exe}\",0"));
    reg_set_str(hk, &format!("{cls}\\shell\\open\\command"), None, &cmd);
    let ap = format!("Software\\Classes\\Applications\\{}", a_.exe_name);
    reg_set_str(hk, &ap, Some("FriendlyAppName"), a_.app);
    reg_set_str(hk, &format!("{ap}\\shell\\open\\command"), None, &cmd);
    reg_set_str(hk, a_.cap_key, Some("ApplicationName"), a_.app);
    reg_set_str(hk, a_.cap_key, Some("ApplicationDescription"), &format!("{} (WacOS)", a_.app));
    reg_set_str(hk, a_.cap_key, Some("ApplicationIcon"), &format!("\"{exe}\",0"));
    for e in a_.exts {
        reg_set_none(hk, &format!("Software\\Classes\\{e}\\OpenWithProgids"), a_.prog);
        reg_set_str(hk, &format!("{ap}\\SupportedTypes"), Some(e), "");
        reg_set_str(hk, &format!("{}\\FileAssociations", a_.cap_key), Some(e), a_.prog);
    }
    for antigo in ANTIGOS_REG {
        reg_del_value(hk, "Software\\RegisteredApplications", antigo);
    }
    reg_set_str(hk, "Software\\RegisteredApplications", Some(a_.reg_name), a_.cap_key);
    anota(&format!("{} registrado em Abrir com (HKCU\\Software\\Classes\\{}; o desinstalar remove)", a_.app, a_.prog));
}
fn assoc_undo(a_: &Assoc) {
    let hk = HKEY_CURRENT_USER;
    for e in a_.exts {
        reg_del_value(hk, &format!("Software\\Classes\\{e}\\OpenWithProgids"), a_.prog);
    }
    reg_del_tree(hk, &format!("Software\\Classes\\{}", a_.prog));
    // Applications\<exe> tem o mesmo nome no WacOS do C++: só sai se aponta para esta instalação
    let ap = format!("Software\\Classes\\Applications\\{}", a_.exe_name);
    if reg_get_str(hk, &format!("{ap}\\shell\\open\\command"), None).to_lowercase().contains(&format!("{}\\bin\\", p().dest).to_lowercase()) {
        reg_del_tree(hk, &ap);
    }
    reg_del_value(hk, "Software\\RegisteredApplications", a_.reg_name);
    for antigo in ANTIGOS_REG {
        reg_del_value(hk, "Software\\RegisteredApplications", antigo);
    }
    reg_del_tree(hk, &parent(a_.cap_key));
}
const UNINST_KEY: &str = if comum::edicao::UNICA { "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\WacOS" } else { "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\WacOS-Rust" }; // comum::edicao::CHAVE_DESINSTALAR
fn register_uninstall() {
    let hk = HKEY_CURRENT_USER;
    let dest = p().dest.clone();
    let setup = format!("{dest}\\WacOSSetup.exe");
    reg_set_str(hk, UNINST_KEY, Some("DisplayName"), comum::edicao::NOME);
    reg_set_str(hk, UNINST_KEY, Some("DisplayVersion"), &version_of(&dest));
    reg_set_str(hk, UNINST_KEY, Some("Publisher"), "WacOS");
    reg_set_str(hk, UNINST_KEY, Some("DisplayIcon"), &format!("{setup},0"));
    reg_set_str(hk, UNINST_KEY, Some("InstallLocation"), &dest);
    reg_set_str(hk, UNINST_KEY, Some("URLInfoAbout"), "https://github.com/Eternity070628/WacOS");
    reg_set_str(hk, UNINST_KEY, Some("UninstallString"), &format!("\"{setup}\" --desinstalar"));
    reg_set_str(hk, UNINST_KEY, Some("ModifyPath"), &format!("\"{setup}\""));
    reg_set_dword(hk, UNINST_KEY, "NoRepair", 1);
    let mut f = Vec::new();
    list_files(&dest, "", &mut f);
    let total: u64 = f.iter().filter_map(|r| std::fs::metadata(format!("{dest}\\{r}")).ok()).map(|m| m.len()).sum();
    reg_set_dword(hk, UNINST_KEY, "EstimatedSize", (total / 1024) as u32);
}

/// o mesmo que o instalar.ps1. update = só os arquivos (o resto fica como estava)
fn do_install(update: bool) {
    set_prog(0.02);
    if !close_everything() {
        done(false);
        return;
    }
    let (src, dest) = (p().src.clone(), p().dest.clone());
    mk_dirs(&dest);
    anota(&format!("{}{src} (WacOSSetup)", if update { "atualizando de " } else { "instalando de " }));
    let hk = HKEY_CURRENT_USER;
    // 1. arquivos (quando a fonte não é a própria instalação)
    if !src.eq_ignore_ascii_case(&dest) {
        let mut trees: Vec<(String, String)> = ["bin", "icones", "sons", "tools"].iter().filter(|d| is_dir(&format!("{src}\\{d}"))).map(|d| (format!("{src}\\{d}"), format!("{dest}\\{d}"))).collect();
        if is_dir(&format!("{src}\\cursor-leopard\\Leopard")) {
            trees.push((format!("{src}\\cursor-leopard\\Leopard"), format!("{dest}\\cursor\\Leopard")));
        }
        let (fails, falhos) = copy_trees(&trees, 0.05, 0.7);
        // o próprio instalador vai junto (Aplicativos instalados chama ele para desinstalar).
        // Ele é este processo, que está em execução: a cópia direta falhava sempre e a correção do
        // instalador nunca chegava ao disco (a build-68 continuava instalando com o setup antigo).
        // Vai como .new e um cmd troca quando este processo sair.
        let de_exe = format!("{dest}\\WacOSSetup.exe");
        let se_exe = if exists(&format!("{src}\\WacOSSetup.exe")) { format!("{src}\\WacOSSetup.exe") } else { p().me.clone() };
        if !se_exe.eq_ignore_ascii_case(&de_exe) {
            let novo = format!("{de_exe}.new");
            let _ = del_file(&novo);
            if copy_file(&se_exe, &novo) {
                agendar_troca(&novo, &de_exe);
            }
        }
        for d in ["instalar.cmd", "atualizar.cmd", "desinstalar.cmd", "instalar.ps1", "desinstalar.ps1"] {
            if exists(&format!("{src}\\{d}")) {
                copy_one(&format!("{src}\\{d}"), &format!("{dest}\\tools\\{d}"));
            }
        }
        del_file(&format!("{dest}\\bin\\WacOSWindow32Host.exe"));
        let nomes: Vec<String> = falhos.iter().map(|(_, b)| b.clone()).collect();
        anota(&format!("copiado: bin, icones, sons, tools{}", if fails > 0 { format!(" ({fails} arquivo(s) não copiados: {})", nomes.join(", ")) } else { String::new() }));
        // Um ícone, um som ou uma DLL de gancho ainda carregada noutro processo (antivírus lendo, Explorer com
        // o gancho do WacOS) não pode derrubar a atualização inteira: o Shell já foi fechado e, parando aqui, o
        // usuário ficava sem a atualização E sem o desktop. O que não deu para trocar agora vai para o lado
        // como .new e um cmd escondido troca assim que este processo sair (o mesmo truque do próprio setup).
        let mut pendentes: Vec<String> = Vec::new();
        for (de, para) in &falhos {
            let novo = format!("{para}.new");
            let _ = del_file(&novo);
            if copy_file(de, &novo) {
                agendar_troca(&novo, para);
                pendentes.push(para.clone());
            }
        }
        if !pendentes.is_empty() {
            let lista: Vec<String> = pendentes.iter().map(|p| leaf(p)).collect();
            anota(&format!("adiado: {} (trocado por um cmd escondido quando o instalador sair)", lista.join(", ")));
        }
        // só o próprio Shell, e só se nem a troca adiada deu certo, é motivo para desistir (sem ele não há desktop)
        let shell_solto = nomes.iter().any(|n| leaf(n).eq_ignore_ascii_case("WacOSShell.exe")) && !pendentes.iter().any(|p| leaf(p).eq_ignore_ascii_case("WacOSShell.exe"));
        if shell_solto {
            fail(&format!("{fails}{}", t(" arquivo(s) não puderam ser copiados. Feche os apps do WacOS e tente de novo.", " file(s) could not be copied. Close the WacOS apps and try again.")));
            reabrir_shell();
            done(false);
            return;
        }
    }
    set_prog(0.72);
    // 2. o que instalar (modo.txt; a atualização mantém o que estava)
    let ch = &a().ch;
    if !update {
        let mut tx = format!("{}\r\n", MODE_ID[mode_idx(ch.mode)]);
        if matches!(ch.mode, Mode::Apps | Mode::AppsBars) {
            for ap in a().apps.iter().filter(|x| x.on) {
                tx += &format!("{}\r\n", ap.exe);
            }
        }
        write_text(&format!("{dest}\\modo.txt"), &tx);
        anota(&format!("modo: {}", MODE_ID[mode_idx(ch.mode)]));
    }
    register_uninstall();
    if update {
        // Música/QuickTime já registrados por esta instalação: registra de novo (nomes em inglês desde a issue #2)
        for a_ in &ASSOC {
            if reg_get_str(hk, &format!("Software\\Classes\\{}\\shell\\open\\command", a_.prog), None).to_lowercase().contains(&format!("{dest}\\bin\\").to_lowercase()) {
                assoc_register(a_);
            }
        }
        status(&t("Atualizado.", "Updated."));
        set_prog(1.0);
        // o Shell foi fechado no começo da atualização: sem isto ela terminava com o desktop vazio
        reabrir_shell();
        done(true);
        return;
    }
    let (full, apps, bars) = (ch.mode == Mode::Full, matches!(ch.mode, Mode::Apps | Mode::AppsBars), matches!(ch.mode, Mode::Bars | Mode::AppsBars));
    // 3. fontes SF (só para este usuário)
    if ch.fonts && is_dir(&format!("{src}\\fontes")) {
        status(&t("Instalando as fontes…", "Installing fonts…"));
        let fdir = format!("{}\\Microsoft\\Windows\\Fonts", env("LOCALAPPDATA"));
        mk_dirs(&fdir);
        let mut fs = Vec::new();
        list_files(&format!("{src}\\fontes"), "", &mut fs);
        let mut n = 0;
        let fk = "Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts";
        for r in fs {
            let ext = ext_of(&r);
            if ext != ".otf" && ext != ".ttf" {
                continue;
            }
            let alvo = format!("{fdir}\\{}", leaf(&r));
            if !exists(&alvo) && copy_file(&format!("{src}\\fontes\\{r}"), &alvo) {
                anota(&format!("fonte: {alvo}"));
            }
            let base = leaf(&r);
            let base = &base[..base.rfind('.').unwrap_or(base.len())];
            let nome = format!("{base}{}", if ext == ".otf" { " (OpenType)" } else { " (TrueType)" });
            if reg_get_str(hk, fk, Some(&nome)) != alvo {
                reg_set_str(hk, fk, Some(&nome), &alvo);
                anota(&format!("registro: HKCU:\\{fk} | {nome} = {alvo}"));
            }
            let az = wz(&alvo);
            unsafe {
                AddFontResourceW(pc(&az));
            }
            n += 1;
        }
        if n > 0 {
            unsafe {
                let _ = SendMessageTimeoutW(HWND_BROADCAST, WM_FONTCHANGE, WPARAM(0), LPARAM(0), SMTO_ABORTIFHUNG, 1000, None);
            }
        }
    }
    set_prog(0.8);
    // 4. cursor do Mac (o anterior fica no log e o desinstalar devolve)
    if full && ch.cursor && is_dir(&format!("{src}\\cursor")) {
        let cur_name = std::fs::read_dir(format!("{src}\\cursor")).ok().and_then(|rd| rd.flatten().find(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false) && !e.file_name().to_string_lossy().starts_with('.')).map(|e| e.file_name().to_string_lossy().to_string()));
        if let Some(cur_name) = cur_name {
            status(&t("Aplicando o cursor do Mac…", "Applying the Mac cursor…"));
            let cdir = format!("{dest}\\cursor\\{cur_name}");
            let _ = copy_trees(&[(format!("{src}\\cursor\\{cur_name}"), cdir.clone())], 0.8, 0.84);
            let ck = "Control Panel\\Cursors";
            for l in lines(&read_text(&format!("{src}\\cursor\\cursores.txt"))) {
                let Some((papel, arq)) = l.split_once('=') else { continue };
                let (papel, arq) = (papel.trim(), format!("{cdir}\\{}", arq.trim()));
                if !exists(&arq) {
                    continue;
                }
                anota(&format!("cursor-antes: {papel}={}", reg_get_str(hk, ck, Some(papel))));
                reg_set_str(hk, ck, Some(papel), &arq);
            }
            anota(&format!("cursor-antes: (default)={}", reg_get_str(hk, ck, None)));
            reg_set_str(hk, ck, None, &cur_name);
            reg_set_dword(hk, ck, "Scheme Source", 1);
            anota("registro: HKCU:\\Control Panel\\Cursors (cursor do Mac)");
            unsafe {
                let _ = SystemParametersInfoW(SPI_SETCURSORS, 0, None, SPIF_SENDCHANGE);
            }
        }
    }
    set_prog(0.86);
    status(&t("Criando os atalhos…", "Creating shortcuts…"));
    let progs = programs();
    if full {
        // 5. ajustes de um PC novo: área de trabalho e pastas do Mac
        let cfg = format!("{}\\Shell", env("APPDATA"));
        let aj = format!("{cfg}\\ajustes.txt");
        if !exists(&aj) {
            mk_dirs(&cfg);
            write_text(&aj, "explorer=fundo\r\nfinder_padrao=1\r\n");
            anota(&format!("ajuste: {aj} (padrões: explorer=fundo, finder_padrao=1)"));
        }
        let finder = format!("{dest}\\bin\\WacOSFinder.exe");
        if !read_text(&aj).contains("finder_padrao=0") && exists(&finder) {
            run_wait(&finder, "--quieto --padrao on", 30000, true);
            anota("pastas no Finder: WacOSFinder.exe --padrao on");
        }
        let exe = format!("{dest}\\bin\\WacOSShell.exe");
        if shortcut(&format!("{progs}\\{}.lnk", comum::edicao::NOME), &exe, comum::edicao::NOME) {
            anota(&format!("atalho: {progs}\\{}.lnk", comum::edicao::NOME));
        }
        let _ = std::fs::remove_dir(format!("{progs}\\{}", comum::edicao::NOME));
        if ch.autostart {
            if task_logon(comum::edicao::TAREFA, &exe, &format!("Starts {} at sign-in (WacOSSetup removes it)", comum::edicao::NOME)) {
                anota(&format!("tarefa agendada: {} (ao entrar)", comum::edicao::TAREFA));
            }
        } else {
            task_delete(comum::edicao::TAREFA);
        }
        task_delete(comum::edicao::TAREFA_BARRAS);
    } else {
        // 6. só os apps e/ou as barras: atalhos na pasta "WacOS" do Menu Iniciar, nada do Shell
        let menu = format!("{progs}\\{}", comum::edicao::NOME);
        mk_dirs(&menu);
        if let Ok(rd) = std::fs::read_dir(&menu) {
            for e in rd.flatten().filter(|e| ext_of(&e.file_name().to_string_lossy()) == ".lnk") {
                let _ = std::fs::remove_file(e.path());
            }
        }
        if task_exists(comum::edicao::TAREFA) {
            task_delete(comum::edicao::TAREFA);
            anota("tarefa agendada WacOS removida (modo sem o Shell)");
        }
        del_file(&format!("{progs}\\{}.lnk", comum::edicao::NOME));
        if apps {
            for ap in a().apps.iter().filter(|x| x.on) {
                shortcut(&format!("{menu}\\{}.lnk", ap.name), &format!("{dest}\\bin\\{}.exe", ap.exe), "");
            }
        }
        if bars {
            let tb = format!("{dest}\\bin\\WacOSTitleBars.exe");
            shortcut(&format!("{menu}\\{}.lnk", comum::edicao::TAREFA_BARRAS), &tb, "");
            if ch.autostart {
                if task_logon(comum::edicao::TAREFA_BARRAS, &tb, "Mac title bars on other apps, without the WacOS Shell (WacOSSetup removes it)") {
                    anota("tarefa agendada: WacOS Title Bars (ao entrar)");
                }
            } else {
                task_delete(comum::edicao::TAREFA_BARRAS);
            }
        } else {
            task_delete(comum::edicao::TAREFA_BARRAS);
        }
        anota(&format!("menu iniciar: {menu}"));
    }
    set_prog(0.94);
    // 7. Música e QuickTime em "Abrir com"
    if ch.assoc {
        for a_ in &ASSOC {
            let want = full || (apps && a().apps.iter().any(|x| x.on && format!("{}.exe", x.exe).eq_ignore_ascii_case(a_.exe_name)));
            if want && exists(&format!("{dest}\\bin\\{}", a_.exe_name)) {
                assoc_register(a_);
            }
        }
        unsafe { SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, None, None) };
    }
    register_uninstall();
    anota("instalação concluída (WacOSSetup)");
    status(&t("Pronto.", "Done."));
    set_prog(1.0);
    done(true);
}

/// o mesmo que o desinstalar.ps1
fn do_uninstall() {
    set_prog(0.03);
    let help = helper();
    if !close_everything() {
        done(false);
        return;
    }
    let dest = p().dest.clone();
    let hk = HKEY_CURRENT_USER;
    set_prog(0.15);
    if !help.is_empty() {
        status(&t("Devolvendo as janelas ao visual do Windows…", "Restoring the Windows look of open windows…"));
        run_wait(&help, "--desfazer-janelas", 30000, true);
    }
    // barra do Windows nos outros monitores
    let aj = format!("{}\\Shell\\ajustes.txt", env("APPDATA"));
    {
        let mut keep = String::new();
        let mut changed = false;
        for l in lines(&read_text(&aj)) {
            if let Some(v) = l.strip_prefix("barra_windows_monitores_antes=") {
                let adv = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";
                let v = v.trim();
                if v == "x" {
                    reg_del_value(hk, adv, "MMTaskbarEnabled");
                } else {
                    reg_set_dword(hk, adv, "MMTaskbarEnabled", v.parse().unwrap_or(0));
                }
                changed = true;
                continue;
            }
            keep += &format!("{l}\r\n");
        }
        if changed {
            write_text(&aj, &keep);
        }
    }
    set_prog(0.25);
    status(&t("Removendo o início automático e os atalhos…", "Removing autostart and shortcuts…"));
    // só as tarefas desta edição (as do C++, "WacOS" e "WacOS Title Bars", ficam)
    for tk in [comum::edicao::TAREFA, comum::edicao::TAREFA_BARRAS] {
        task_delete(tk);
    }
    // "Abrir no lugar da área de trabalho do Windows" (issue #39): o shell do Windows volta a ser o Explorador
    {
        let wl = "Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon";
        let sh = reg_get_str(hk, wl, Some("Shell")).to_lowercase();
        // só se o shell do Windows é o desta instalação (o do C++ fica como está)
        if sh.contains(&format!("{}\\bin\\wacosshell.exe", dest.to_lowercase())) {
            let antes = lines(&read_text(&aj)).iter().find_map(|l| l.strip_prefix("winlogon_shell_antes=").map(|v| v.trim().to_string())).unwrap_or_default();
            if !antes.is_empty() {
                reg_set_str(hk, wl, Some("Shell"), &antes);
                anota(&format!("shell do Windows de volta ao anterior: {antes}"));
            } else {
                reg_del_value(hk, wl, "Shell");
                anota("shell do Windows de volta ao Explorador (HKCU Winlogon Shell apagado)");
            }
        }
    }
    let finder = format!("{dest}\\bin\\WacOSFinder.exe");
    if exists(&finder) {
        run_wait(&finder, "--quieto --padrao off", 30000, true);
    }
    let progs = programs();
    del_file(&format!("{progs}\\{}.lnk", comum::edicao::NOME));
    shell_delete(&format!("{progs}\\{}", comum::edicao::NOME));
    // janela de Abrir/Salvar do Mac (só a desta instalação)
    for raiz in ["Software\\Classes\\CLSID\\", "Software\\Classes\\WOW6432Node\\CLSID\\"] {
        for clsid in ["{DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7}", "{C0B4E2F3-BA21-4773-8DBA-335EC946EB8B}"] {
            let k = format!("{raiz}{clsid}");
            if reg_get_str(hk, &format!("{k}\\InprocServer32"), None).to_lowercase().starts_with(&format!("{dest}\\").to_lowercase()) {
                reg_del_tree(hk, &k);
            }
        }
    }
    set_prog(0.4);
    // ícones do sistema (raro): o script de desfazer, numa janela visível
    let docs = format!("{dest}\\docs");
    let backups = || ["backup-icones-sistema.json", "backup-desktopini", "backup-icones-maquina.json"].iter().any(|b| exists(&format!("{docs}\\{b}")));
    if backups() {
        let ps1 = format!("{dest}\\tools\\icones-sistema.ps1");
        if exists(&ps1) {
            status(&t("Devolvendo os ícones do Windows…", "Restoring the Windows icons…"));
            let ps = format!("{}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", env("WINDIR"));
            run_wait(&ps, &format!("-NoProfile -File \"{ps1}\" -Desfazer"), 300000, false);
        }
        if backups() {
            fail(&t("Parte dos ícones do Windows não voltou. A pasta da instalação fica (os backups estão nela); tente desinstalar de novo.", "Some Windows icons were not restored. The install folder stays (the backups are in it); try uninstalling again."));
            done(false);
            return;
        }
    }
    set_prog(0.5);
    status(&t("Devolvendo o cursor e as fontes…", "Restoring the cursor and fonts…"));
    let ck = "Control Panel\\Cursors";
    let mut cur_changed = false;
    let cur_antes = format!("{}\\Shell\\cursor-antes.txt", env("APPDATA"));
    let nome_ou_padrao = |n: &str| if n == "(default)" { None } else { Some(n.to_string()) };
    if exists(&cur_antes) && reg_get_str(hk, ck, Some("Arrow")).to_lowercase().starts_with(&format!("{dest}\\cursor\\Leopard\\").to_lowercase()) {
        for l in lines(&read_text(&cur_antes)) {
            if let Some((n, v)) = l.split_once('=') {
                reg_set_str(hk, ck, nome_ou_padrao(n).as_deref(), v);
            }
        }
        del_file(&cur_antes);
        cur_changed = true;
    }
    let log = lines(&read_text(&p().log));
    for l in &log {
        if let Some(i) = l.find("cursor-antes: ") {
            if let Some((n, v)) = l[i + 14..].split_once('=') {
                reg_set_str(hk, ck, nome_ou_padrao(n).as_deref(), v);
                cur_changed = true;
            }
        }
    }
    if cur_changed {
        unsafe {
            let _ = SystemParametersInfoW(SPI_SETCURSORS, 0, None, SPIF_SENDCHANGE);
        }
    }
    for l in &log {
        if let Some(i) = l.find("registro: ") {
            let r = &l[i + 10..];
            if let (Some(bar), Some(eq)) = (r.find(" | "), r.find(" = ")) {
                if eq > bar {
                    if let Some((root, sub)) = ps_key(&r[..bar]) {
                        reg_del_value(root, &sub, &r[bar + 3..eq]);
                    }
                }
            }
        } else if let Some(i) = l.find("fonte: ") {
            let path = &l[i + 7..];
            let z = wz(path);
            unsafe {
                let _ = RemoveFontResourceW(pc(&z));
            }
            del_file(path);
        }
    }
    // Software\ShellProprio e o remetente das atualizações são do WacOS do C++: a edição em Rust não apaga
    for a_ in &ASSOC {
        assoc_undo(a_);
    }
    unsafe { SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, None, None) };
    reg_del_tree(hk, UNINST_KEY);
    set_prog(0.7);
    status(&t("Apagando os arquivos…", "Deleting files…"));
    {
        // arquivo por arquivo: os presos vão para uma pasta no TEMP e saem ao reiniciar o PC
        let mut fs = Vec::new();
        list_files(&dest, "", &mut fs);
        for sub in ["", "bin\\"] {
            if let Ok(rd) = std::fs::read_dir(format!("{dest}\\{sub}")) {
                fs.extend(rd.flatten().map(|e| e.file_name().to_string_lossy().to_string()).filter(|n| ext_of(n) == ".log").map(|n| format!("{sub}{n}")));
            }
        }
        let restos = format!("{}\\WacOS-restos", env("TEMP"));
        for r in fs {
            let pth = format!("{dest}\\{r}");
            let z = wz(&pth);
            unsafe {
                let _ = SetFileAttributesW(pc(&z), FILE_ATTRIBUTE_NORMAL);
            }
            if del_file(&pth) || !exists(&pth) {
                continue;
            }
            mk_dirs(&restos);
            let alvo = format!("{restos}\\{}-{}", unsafe { comum::windows::Win32::System::SystemInformation::GetTickCount64() }, leaf(&pth));
            let az = wz(&alvo);
            unsafe {
                if MoveFileExW(pc(&z), pc(&az), MOVEFILE_REPLACE_EXISTING).is_ok() {
                    let _ = MoveFileExW(pc(&az), PCWSTR::null(), MOVEFILE_DELAY_UNTIL_REBOOT);
                } else {
                    let _ = MoveFileExW(pc(&z), PCWSTR::null(), MOVEFILE_DELAY_UNTIL_REBOOT);
                }
            }
        }
        shell_delete(&dest); // as pastas (vazias agora) e o que sobrou
    }
    // os ajustes (%APPDATA%\Shell) são os mesmos do WacOS do C++: com ele instalado, ficam
    let cpp = format!("{}\\Programs\\WacOS\\bin\\WacOSShell.exe", env("LOCALAPPDATA"));
    if a().ch.del_settings && exists(&cpp) {
        anota("ajustes mantidos: o WacOS do C++ também usa %APPDATA%\\Shell");
    }
    if a().ch.del_settings && !exists(&cpp) {
        // só os ajustes e os caches: as notas, os lembretes, os eventos, os contatos e os alarmes ficam
        let ficam = ["notas", "lembretes.txt", "calendario.txt", "contatos.txt", "relogio.txt", "fotos-favoritos.txt", "assinatura.txt", "feriados.txt"];
        let cfg = format!("{}\\Shell", env("APPDATA"));
        if cfg.len() > 6 {
            if let Ok(rd) = std::fs::read_dir(&cfg) {
                for e in rd.flatten() {
                    let n = e.file_name().to_string_lossy().to_string();
                    if !ficam.iter().any(|k| k.eq_ignore_ascii_case(&n)) {
                        shell_delete(&format!("{cfg}\\{n}"));
                    }
                }
            }
            let _ = std::fs::remove_dir(&cfg); // vazia (nenhum documento): a pasta sai também
        }
    }
    set_prog(0.85);
    if a().ch.clean_cache {
        status(&t("Limpando o cache de ícones…", "Clearing the icon cache…"));
        kill("explorer.exe");
        std::thread::sleep(std::time::Duration::from_millis(800));
        let la = env("LOCALAPPDATA");
        let exp = format!("{la}\\Microsoft\\Windows\\Explorer");
        del_file(&format!("{la}\\IconCache.db"));
        if let Ok(rd) = std::fs::read_dir(&exp) {
            for e in rd.flatten() {
                let n = e.file_name().to_string_lossy().to_lowercase();
                if (n.starts_with("iconcache_") || n.starts_with("thumbcache_")) && n.ends_with(".db") {
                    let _ = std::fs::remove_file(e.path());
                }
            }
        }
        launch("explorer.exe", "");
        launch(&format!("{}\\System32\\ie4uinit.exe", env("WINDIR")), "-show");
        for k in [comum::edicao::CHAVE_SOFTWARE.to_string(), format!("Software\\Classes\\{}", comum::edicao::PROG_MUSICA), format!("Software\\Classes\\{}", comum::edicao::PROG_QUICKTIME), format!("Software\\Classes\\{}", comum::edicao::PROG_PREVIEW)] {
            reg_del_tree(hk, &k);
        }
    }
    if !running("explorer.exe") {
        launch("explorer.exe", "");
    }
    if !help.is_empty() && help.starts_with(&env("TEMP")) {
        let z = wz(&help);
        unsafe {
            let _ = MoveFileExW(pc(&z), PCWSTR::null(), MOVEFILE_DELAY_UNTIL_REBOOT);
        }
    }
    status(&if exists(&dest) { t("Alguns arquivos estavam em uso e saem depois de reiniciar o PC.", "Some files were in use and go away after a restart.") } else { t("O WacOS foi removido.", "WacOS was removed.") });
    if exists(&dest) {
        let z = wz(&dest);
        unsafe {
            let _ = MoveFileExW(pc(&z), PCWSTR::null(), MOVEFILE_DELAY_UNTIL_REBOOT);
        }
    }
    set_prog(1.0);
    done(true);
}

// ============================================================ GitHub (versão nova)
#[derive(Default, Clone)]
struct Release {
    tag: String,
    date: String,
    url: String,
    sha: String,
    notes: Vec<String>,
    size: u64,
}
static REL: Mutex<Option<(Release, String)>> = Mutex::new(None); // (release, erro)
fn rel() -> (Release, String) {
    REL.lock().unwrap().clone().unwrap_or_default()
}
static HTTP_CODE: AtomicU32 = AtomicU32::new(0);
/// GET por HTTPS; com out_file grava no disco e devolve "ok" só se chegou inteiro
fn http_get(host: &str, path: &str, accept: &str, out_file: Option<&str>, prog_: &dyn Fn(u64, u64)) -> Vec<u8> {
    let mut body = Vec::new();
    HTTP_CODE.store(0, Ordering::SeqCst);
    unsafe {
        let s = WinHttpOpen(w!("WacOS-Setup/1.0"), WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, PCWSTR::null(), PCWSTR::null(), 0);
        if s.is_null() {
            return body;
        }
        let _ = WinHttpSetTimeouts(s, 10000, 10000, 30000, 60000);
        let hz = wz(host);
        let c = WinHttpConnect(s, pc(&hz), INTERNET_DEFAULT_HTTPS_PORT, 0);
        let pz = wz(path);
        let r = if c.is_null() { std::ptr::null_mut() } else { WinHttpOpenRequest(c, w!("GET"), pc(&pz), PCWSTR::null(), PCWSTR::null(), std::ptr::null(), WINHTTP_FLAG_SECURE) };
        let hdr = w(&format!("Accept: {accept}"));
        if !r.is_null() && WinHttpSendRequest(r, Some(&hdr), None, 0, 0, 0).is_ok() && WinHttpReceiveResponse(r, std::ptr::null_mut()).is_ok() {
            let mut code = 0u32;
            let mut sz = 4u32;
            let _ = WinHttpQueryHeaders(r, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, PCWSTR::null(), Some(&mut code as *mut _ as *mut c_void), &mut sz, std::ptr::null_mut());
            HTTP_CODE.store(code, Ordering::SeqCst);
            let mut len = [0u16; 32];
            let mut ln = 64u32;
            let total: u64 = if WinHttpQueryHeaders(r, WINHTTP_QUERY_CONTENT_LENGTH, PCWSTR::null(), Some(len.as_mut_ptr() as *mut c_void), &mut ln, std::ptr::null_mut()).is_ok() {
                from_w(&len[..(ln / 2) as usize]).trim().parse().unwrap_or(0)
            } else {
                0
            };
            if code == 200 {
                use std::io::Write;
                let mut f = match out_file {
                    Some(o) => match std::fs::File::create(o) {
                        Ok(f) => Some(f),
                        Err(_) => {
                            let _ = WinHttpCloseHandle(r);
                            let _ = WinHttpCloseHandle(c);
                            let _ = WinHttpCloseHandle(s);
                            return body;
                        }
                    },
                    None => None,
                };
                let mut buf = vec![0u8; 1 << 16];
                let mut got = 0u64;
                let mut escreveu = true;
                loop {
                    let mut n = 0u32;
                    if WinHttpReadData(r, buf.as_mut_ptr() as *mut c_void, buf.len() as u32, &mut n).is_err() || n == 0 {
                        break;
                    }
                    match &mut f {
                        Some(f) => {
                            if f.write_all(&buf[..n as usize]).is_err() {
                                escreveu = false;
                                break;
                            }
                        }
                        None => body.extend_from_slice(&buf[..n as usize]),
                    }
                    got += n as u64;
                    prog_(got, total);
                }
                if let Some(o) = out_file {
                    drop(f);
                    // conexão que caiu no meio: só vale inteiro (o tamanho do Content-Length) e gravado
                    if escreveu && (total == 0 || got == total) {
                        body = b"ok".to_vec();
                    } else {
                        let _ = std::fs::remove_file(o);
                    }
                }
            }
        }
        if !r.is_null() {
            let _ = WinHttpCloseHandle(r);
        }
        if !c.is_null() {
            let _ = WinHttpCloseHandle(c);
        }
        let _ = WinHttpCloseHandle(s);
    }
    body
}
fn json_str(j: &str, key: &str, from: usize) -> Option<(String, usize)> {
    let pk = j[from..].find(&format!("\"{key}\""))? + from;
    let p_ = j[pk..].find(':')? + pk;
    let q = j[p_..].find('"')? + p_;
    let mut out = String::new();
    let b: Vec<char> = j[q + 1..].chars().collect();
    let mut i = 0;
    while i < b.len() && b[i] != '"' {
        if b[i] == '\\' && i + 1 < b.len() {
            i += 1;
            match b[i] {
                'n' => out.push('\n'),
                'r' => out.push('\r'),
                't' => out.push('\t'),
                'u' if i + 4 < b.len() => {
                    let hx: String = b[i + 1..i + 5].iter().collect();
                    if let Some(c) = u32::from_str_radix(&hx, 16).ok().and_then(char::from_u32) {
                        if c != '\u{FEFF}' {
                            out.push(c);
                        }
                    }
                    i += 4;
                }
                c => out.push(c),
            }
        } else {
            out.push(b[i]);
        }
        i += 1;
    }
    Some((out.trim_start_matches('\u{FEFF}').to_string(), q))
}
/// sem a API (limite de 60 por hora por IP): a página pública da release tem o mesmo
fn check_github_pagina() -> Option<Release> {
    let pg = String::from_utf8_lossy(&http_get("github.com", "/Eternity070628/WacOS/releases/latest", "text/html", None, &|_, _| {})).to_string();
    let ea = "/Eternity070628/WacOS/releases/expanded_assets/";
    let i = pg.find(ea)? + ea.len();
    let e = pg[i..].find(['"', '\'', '?', '#'])? + i;
    let tag = pg[i..e].to_string();
    let as_ = String::from_utf8_lossy(&http_get("github.com", &format!("{ea}{tag}"), "text/html", None, &|_, _| {})).to_string();
    let dl = format!("/Eternity070628/WacOS/releases/download/{tag}/");
    let mut from = 0;
    while let Some(q) = as_[from..].find(&dl).map(|x| x + from) {
        let qe = as_[q..].find('"')? + q;
        let href = &as_[q..qe];
        from = q + 1;
        if !href.ends_with(".zip") {
            continue;
        }
        let mut r = Release { tag: tag.clone(), url: format!("https://github.com{href}"), ..Default::default() };
        if let Some(h) = as_[qe..].find("sha256:").map(|x| x + qe) {
            if h + 71 <= as_.len() {
                r.sha = as_[h + 7..h + 71].to_lowercase();
            }
        }
        if !r.sha.chars().all(|c| c.is_ascii_hexdigit()) {
            r.sha.clear();
        }
        return Some(r);
    }
    None
}
fn check_github() {
    if !comum::edicao::ATUALIZA_PELO_GITHUB {
        // edição em Rust: as releases do GitHub são do C++; instala só do pacote local (build-rust.ps1)
        return;
    }
    let j = String::from_utf8_lossy(&http_get("api.github.com", "/repos/Eternity070628/WacOS/releases/latest", "application/vnd.github+json", None, &|_, _| {})).to_string();
    let mut r = Release::default();
    let mut err = String::new();
    if j.is_empty() {
        let api = HTTP_CODE.load(Ordering::SeqCst);
        match check_github_pagina() {
            Some(x) => r = x,
            None => {
                err = if api > 0 { cf!(t("O GitHub recusou a consulta (HTTP %lu). Tente de novo em alguns minutos.", "GitHub refused the request (HTTP %lu). Try again in a few minutes."), api as i32) } else { t("Não deu para falar com o GitHub. Confira a internet e tente de novo.", "Couldn't reach GitHub. Check your connection and try again.") };
            }
        }
        *REL.lock().unwrap() = Some((r, err));
        return;
    }
    r.tag = json_str(&j, "tag_name", 0).map(|x| x.0).unwrap_or_default();
    let d = json_str(&j, "published_at", 0).map(|x| x.0).unwrap_or_default();
    if d.len() >= 10 {
        r.date = format!("{}/{}/{}", &d[8..10], &d[5..7], &d[0..4]);
    }
    for l in lines(&json_str(&j, "body", 0).map(|x| x.0).unwrap_or_default()) {
        let tt = l.trim().trim_start_matches(['-', '*', ' ']).to_string();
        if !tt.is_empty() && r.notes.len() < 8 {
            r.notes.push(tt);
        }
    }
    let mut p_ = j.find("\"assets\"").unwrap_or(j.len());
    while p_ < j.len() {
        let Some((url, at)) = json_str(&j, "browser_download_url", p_) else { break };
        if url.to_lowercase().ends_with(".zip") {
            r.url = url;
            let obj = j[..at].rfind('{').unwrap_or(0);
            if let Some((dg, _)) = json_str(&j, "digest", obj) {
                if let Some(s) = dg.strip_prefix("sha256:") {
                    r.sha = s.to_lowercase();
                }
            }
            if let Some(sp) = j[obj..].find("\"size\"").map(|x| x + obj) {
                let num: String = j[sp + 6..].chars().skip_while(|c| !c.is_ascii_digit()).take_while(|c| c.is_ascii_digit()).collect();
                r.size = num.parse().unwrap_or(0);
            }
            break;
        }
        p_ = at + 1;
    }
    if r.tag.is_empty() || r.url.is_empty() {
        err = t("A versão mais nova no GitHub não tem o pacote .zip.", "The latest release on GitHub has no .zip package.");
    }
    *REL.lock().unwrap() = Some((r, err));
}
fn sha256_file(path: &str) -> String {
    unsafe {
        let mut alg = BCRYPT_ALG_HANDLE::default();
        if BCryptOpenAlgorithmProvider(&mut alg, BCRYPT_SHA256_ALGORITHM, PCWSTR::null(), BCRYPT_OPEN_ALGORITHM_PROVIDER_FLAGS(0)).is_err() {
            return String::new();
        }
        let mut out = String::new();
        let mut h = BCRYPT_HASH_HANDLE::default();
        if BCryptCreateHash(alg, &mut h, None, None, 0).is_ok() {
            if let Ok(mut f) = std::fs::File::open(path) {
                use std::io::Read;
                let mut b = vec![0u8; 1 << 20];
                while let Ok(n) = f.read(&mut b) {
                    if n == 0 {
                        break;
                    }
                    let _ = BCryptHashData(h, &b[..n], 0);
                }
                let mut d = [0u8; 32];
                let _ = BCryptFinishHash(h, &mut d, 0);
                out = d.iter().map(|x| format!("{x:02x}")).collect();
            }
            let _ = BCryptDestroyHash(h);
        }
        let _ = BCryptCloseAlgorithmProvider(alg, 0);
        out
    }
}
fn split_url(u: &str) -> (String, String) {
    let hs = u.find("://").map(|x| x + 3).unwrap_or(0);
    let ps = u[hs..].find('/').map(|x| x + hs).unwrap_or(u.len());
    (u[hs..ps].to_string(), u[ps..].to_string())
}
fn do_update() {
    set_prog(0.01);
    let (r, _) = rel();
    let tmp = format!("{}\\wacos-setup-{}", env("TEMP"), unsafe { comum::windows::Win32::System::SystemInformation::GetTickCount() });
    mk_dirs(&tmp);
    let zip = format!("{tmp}\\WacOS.zip");
    status(&format!("{}{}…", t("Baixando ", "Downloading "), r.tag));
    let (host, path) = split_url(&r.url);
    let ok = http_get(&host, &path, "application/octet-stream", Some(&zip), &|got, total| {
        if total > 0 {
            set_prog(0.02 + 0.5 * got as f32 / total as f32);
        }
        status(&cf!(t("Baixando… %.0f de %.0f MB", "Downloading… %.0f of %.0f MB"), got as f64 / 1048576.0, total as f64 / 1048576.0));
    });
    if ok.is_empty() {
        let code = HTTP_CODE.load(Ordering::SeqCst);
        fail(&if code > 0 && code != 200 { cf!(t("O download falhou (HTTP %lu). Tente de novo.", "The download failed (HTTP %lu). Try again."), code as i32) } else { t("O download falhou (sem conexão com o GitHub). Tente de novo.", "The download failed (couldn't reach GitHub). Try again.") });
        done(false);
        return;
    }
    status(&t("Conferindo o pacote (SHA-256)…", "Checking the package (SHA-256)…"));
    set_prog(0.54);
    if !r.sha.is_empty() && sha256_file(&zip) != r.sha {
        fail(&t("O arquivo baixado não bate com o publicado (SHA-256). Nada foi instalado.", "The download doesn't match the published package (SHA-256). Nothing was installed."));
        done(false);
        return;
    }
    status(&t("Extraindo…", "Extracting…"));
    set_prog(0.57);
    let out = format!("{tmp}\\pacote");
    mk_dirs(&out);
    run_wait(&format!("{}\\System32\\tar.exe", env("WINDIR")), &format!("-xf \"{zip}\" -C \"{out}\""), 600000, true);
    let root = if exists(&format!("{out}\\bin\\WacOSShell.exe")) {
        Some(out.clone())
    } else {
        std::fs::read_dir(&out).ok().and_then(|rd| rd.flatten().map(|e| e.path().to_string_lossy().to_string()).find(|d| exists(&format!("{d}\\bin\\WacOSShell.exe"))))
    };
    let Some(root) = root else {
        fail(&t("O pacote baixado não tem os programas do WacOS.", "The downloaded package has no WacOS programs."));
        done(false);
        return;
    };
    p().src = root;
    do_install(true); // a atualização usa o mesmo caminho da instalação, só com os arquivos
    shell_delete(&tmp);
}

// ============================================================ interface (Direct2D, no visual do Instalador do macOS)
#[derive(Clone, Copy, PartialEq)]
enum Page {
    Intro,
    Home,
    Type,
    Apps,
    Work,
    Done,
    UpdCheck,
    Uninst,
    Error,
}
#[derive(Clone, Copy, PartialEq)]
enum Flow {
    Install,
    Modify,
    Update,
    Uninstall,
}
const B_BACK: i32 = 1;
const B_NEXT: i32 = 2;
const B_CLOSE: i32 = 3;
const B_MIN: i32 = 4;
const B_ALL: i32 = 5;
const B_NONE: i32 = 6;
const B_MODE0: i32 = 100;
const B_HOME0: i32 = 200;
const B_APP0: i32 = 300;
const B_CHK0: i32 = 400;

struct App {
    hwnd: HWND,
    rt: Option<ID2D1RenderTarget>,
    hrt: Option<ID2D1HwndRenderTarget>,
    logo_src: Option<IWICBitmapSource>,
    logo: Option<ID2D1Bitmap>,
    k: f32,
    dark: bool,
    font_ui: String,
    font_title: String,
    page: Page,
    flow: Flow,
    home_sel: i32,
    spin: f32,
    inst_ver: String,
    pkg_ver: String,
    installed: bool,
    from_pkg: bool,
    force_uninstall_only: bool,
    hits: Vec<(RectF, i32)>,
    hover: i32,
    press: i32,
    ch: Choices,
    apps: Vec<AppInfo>,
}
static A: Global<Option<App>> = Global::new(None);
fn a() -> &'static mut App {
    A.get().as_mut().unwrap()
}
const W: f32 = 800.0;
const H: f32 = 560.0;
const TB: f32 = 40.0;
const SIDE: f32 = 230.0;
const BOTTOM: f32 = 64.0;

fn hx(v: u32, al: f32) -> Cor {
    rgb(((v >> 16) & 255) as i32, ((v >> 8) & 255) as i32, (v & 255) as i32, al)
}
fn c1(v: u32) -> Cor {
    hx(v, 1.0)
}
fn accent() -> Cor {
    c1(0x0A84FF)
}
fn fg() -> Cor {
    if a().dark {
        hx(0xFFFFFF, 0.92)
    } else {
        c1(0x1D1D1F)
    }
}
fn fg2() -> Cor {
    if a().dark {
        hx(0xFFFFFF, 0.55)
    } else {
        c1(0x6E6E73)
    }
}
fn rt() -> ID2D1RenderTarget {
    a().rt.clone().unwrap()
}
fn fmt(size: f32, wt: DWRITE_FONT_WEIGHT, title: bool, al: DWRITE_TEXT_ALIGNMENT) -> Option<IDWriteTextFormat> {
    let fam = if title { a().font_title.clone() } else { a().font_ui.clone() };
    let f = cjk::format(dw(), &fam, wt, DWRITE_FONT_STYLE_NORMAL, size, if PT.load(Ordering::Relaxed) { "pt-BR" } else { "en-US" })?;
    unsafe {
        let _ = f.SetTextAlignment(al);
        let _ = f.SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
    }
    Some(f)
}
const REG: DWRITE_FONT_WEIGHT = DWRITE_FONT_WEIGHT_REGULAR;
const LEAD: DWRITE_TEXT_ALIGNMENT = DWRITE_TEXT_ALIGNMENT_LEADING;
const CENTER: DWRITE_TEXT_ALIGNMENT = DWRITE_TEXT_ALIGNMENT_CENTER;
#[allow(clippy::too_many_arguments)]
fn text(s: &str, r: RectF, size: f32, c: Cor, wt: DWRITE_FONT_WEIGHT, title: bool, al: DWRITE_TEXT_ALIGNMENT, vcenter: bool) {
    let Some(f) = fmt(size, wt, title, al) else { return };
    unsafe {
        if vcenter {
            let _ = f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
        }
        if let Some(b) = brush(&rt(), c) {
            rt().DrawText(&w(s), &f, &r, &b, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
        }
    }
}
fn metrics(s: &str, wd: f32, size: f32, wt: DWRITE_FONT_WEIGHT) -> Option<DWRITE_TEXT_METRICS> {
    let f = fmt(size, wt, false, LEAD)?;
    unsafe {
        let l = dw().CreateTextLayout(&w(s), &f, wd, 10000.0).ok()?;
        let mut m = DWRITE_TEXT_METRICS::default();
        l.GetMetrics(&mut m).ok()?;
        Some(m)
    }
}
fn text_h(s: &str, wd: f32, size: f32) -> f32 {
    metrics(s, wd, size, REG).map(|m| m.height).unwrap_or(size * 1.3)
}
fn text_w(s: &str, size: f32) -> f32 {
    metrics(s, 10000.0, size, REG).map(|m| m.widthIncludingTrailingWhitespace).unwrap_or(s.len() as f32 * size * 0.55)
}
fn fill(r: RectF, rad: f32, c: Cor) {
    unsafe {
        if let Some(b) = brush(&rt(), c) {
            rt().FillRoundedRectangle(&rr(r, rad, rad), &b);
        }
    }
}
fn stroke(r: RectF, rad: f32, c: Cor, wd: f32) {
    unsafe {
        if let Some(b) = brush(&rt(), c) {
            rt().DrawRoundedRectangle(&rr(r, rad, rad), &b, wd, None);
        }
    }
}
fn circle(x: f32, y: f32, r: f32, c: Cor, cheio: bool, wd: f32) {
    unsafe {
        if let Some(b) = brush(&rt(), c) {
            if cheio {
                rt().FillEllipse(&ell(pt(x, y), r, r), &b);
            } else {
                rt().DrawEllipse(&ell(pt(x, y), r, r), &b, wd, None);
            }
        }
    }
}
fn line(x0: f32, y0: f32, x1: f32, y1: f32, c: Cor, wd: f32) {
    unsafe {
        if let Some(b) = brush(&rt(), c) {
            rt().DrawLine(pt(x0, y0), pt(x1, y1), &b, wd, None);
        }
    }
}
fn check(x: f32, y: f32, s: f32, c: Cor, wd: f32) {
    unsafe {
        let Ok(g) = d2d().CreatePathGeometry() else { return };
        let Ok(k) = g.Open() else { return };
        k.BeginFigure(pt(x - s * 0.45, y), D2D1_FIGURE_BEGIN_HOLLOW);
        k.AddLine(pt(x - s * 0.12, y + s * 0.32));
        k.AddLine(pt(x + s * 0.48, y - s * 0.38));
        k.EndFigure(D2D1_FIGURE_END_OPEN);
        let _ = k.Close();
        let sp = D2D1_STROKE_STYLE_PROPERTIES { startCap: D2D1_CAP_STYLE_ROUND, endCap: D2D1_CAP_STYLE_ROUND, dashCap: D2D1_CAP_STYLE_ROUND, lineJoin: D2D1_LINE_JOIN_ROUND, miterLimit: 10.0, ..Default::default() };
        let ss = d2d().CreateStrokeStyle(&sp, None).ok();
        if let Some(b) = brush(&rt(), c) {
            rt().DrawGeometry(&g, &b, wd, ss.as_ref());
        }
    }
}
fn hit(r: RectF, id: i32) {
    a().hits.push((r, id));
}
fn button(r: RectF, s: &str, id: i32, primary: bool, enabled: bool) {
    let (hov, pr) = (a().hover == id && enabled, a().press == id && enabled);
    let dark = a().dark;
    if primary {
        let c = if !enabled {
            hx(0x8E8E93, 0.5)
        } else if pr {
            c1(0x0060DF)
        } else if hov {
            c1(0x2B95FF)
        } else {
            accent()
        };
        fill(r, 6.0, c);
        text(s, r, 13.0, c1(0xFFFFFF), DWRITE_FONT_WEIGHT_MEDIUM, false, CENTER, true);
    } else {
        fill(
            r,
            6.0,
            if dark {
                hx(0xFFFFFF, if pr { 0.22 } else if hov { 0.17 } else { 0.12 })
            } else {
                c1(if pr { 0xD4D4D8 } else if hov { 0xE6E6EA } else { 0xFFFFFF })
            },
        );
        if !dark {
            stroke(r, 6.0, hx(0, 0.12), 0.8);
        }
        text(s, r, 13.0, if enabled { fg() } else { fg2() }, REG, false, CENTER, true);
    }
    if enabled {
        hit(r, id);
    }
}
fn check_box(x: f32, y: f32, s: &str, on: bool, id: i32, wd: f32) {
    let bx = rf(x, y + 1.0, x + 16.0, y + 17.0);
    let dark = a().dark;
    if on {
        fill(bx, 4.0, accent());
        check(x + 8.0, y + 9.0, 10.0, c1(0xFFFFFF), 1.8);
    } else {
        fill(bx, 4.0, if dark { hx(0xFFFFFF, 0.08) } else { c1(0xFFFFFF) });
        stroke(bx, 4.0, if dark { hx(0xFFFFFF, 0.3) } else { hx(0, 0.25) }, 1.0);
    }
    text(s, rf(x + 26.0, y, x + wd, y + 20.0), 13.0, fg(), REG, false, LEAD, true);
    hit(rf(x - 4.0, y - 3.0, x + wd, y + 22.0), id);
}
fn radio_card(r: RectF, title: &str, desc: &str, on: bool, id: i32) {
    let hov = a().hover == id;
    let dark = a().dark;
    fill(
        r,
        10.0,
        if on {
            hx(0x0A84FF, if dark { 0.18 } else { 0.08 })
        } else if dark {
            hx(0xFFFFFF, if hov { 0.08 } else { 0.04 })
        } else {
            c1(if hov { 0xF5F5F7 } else { 0xFFFFFF })
        },
    );
    stroke(r, 10.0, if on { accent() } else if dark { hx(0xFFFFFF, 0.14) } else { hx(0, 0.1) }, if on { 2.0 } else { 1.0 });
    let (cx, cy) = (r.left + 22.0, r.top + 22.0);
    if on {
        circle(cx, cy, 8.0, accent(), true, 1.0);
        circle(cx, cy, 3.2, c1(0xFFFFFF), true, 1.0);
    } else {
        circle(cx, cy, 8.0, if dark { hx(0xFFFFFF, 0.35) } else { hx(0, 0.28) }, false, 1.2);
    }
    text(title, rf(r.left + 40.0, r.top + 11.0, r.right - 12.0, r.top + 32.0), 14.0, fg(), DWRITE_FONT_WEIGHT_SEMI_BOLD, false, LEAD, false);
    text(desc, rf(r.left + 40.0, r.top + 32.0, r.right - 14.0, r.bottom - 6.0), 12.0, fg2(), REG, false, LEAD, false);
    hit(r, id);
}
/// etapas da barra lateral, conforme o caminho
fn steps() -> (Vec<String>, usize) {
    let (page, flow) = (a().page, a().flow);
    match flow {
        Flow::Uninstall => (vec![t("Desinstalar", "Uninstall"), t("Remoção", "Removal"), t("Resumo", "Summary")], if page == Page::Uninst { 0 } else if page == Page::Work { 1 } else { 2 }),
        Flow::Update => (vec![t("Atualização", "Software Update"), t("Instalação", "Installation"), t("Resumo", "Summary")], if page == Page::UpdCheck { 0 } else if page == Page::Work { 1 } else { 2 }),
        _ => {
            let mut s = vec![t("Introdução", "Introduction"), t("Tipo de Instalação", "Installation Type")];
            let apps = matches!(a().ch.mode, Mode::Apps | Mode::AppsBars);
            if apps {
                s.push("Apps".into());
            }
            s.push(t("Instalação", "Installation"));
            s.push(t("Resumo", "Summary"));
            let cur = match page {
                Page::Intro | Page::Home => 0,
                Page::Type => 1,
                Page::Apps => 2,
                Page::Work => {
                    if apps {
                        3
                    } else {
                        2
                    }
                }
                _ => s.len() - 1,
            };
            (s, cur)
        }
    }
}
fn paint_logo(x: f32, y: f32, s: f32) {
    unsafe {
        if a().logo.is_none() {
            if let Some(src) = &a().logo_src {
                a().logo = rt().CreateBitmapFromWicBitmap(src, None).ok();
            }
        }
        if let Some(l) = &a().logo {
            rt().DrawBitmap(l, Some(&rf(x, y, x + s, y + s)), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR, None);
        }
    }
}
fn any_running() -> bool {
    OUR_PROCS.iter().any(|p| running(p)) || running("WacOSShell.exe")
}
fn paint() {
    if a().rt.is_none() {
        return;
    }
    a().hits.clear();
    let dark = a().dark;
    let (page, flow) = (a().page, a().flow);
    let busy = BUSY.load(Ordering::SeqCst);
    let ok = WORK_OK.load(Ordering::SeqCst);
    unsafe {
        rt().BeginDraw();
        let k = a().k;
        rt().SetTransform(&mat::scale(k, k, 0.0, 0.0));
        rt().Clear(Some(&if dark { c1(0x232325) } else { c1(0xECECEE) }));
    }
    // barra de título com os semáforos (fechar e minimizar; o maximizar fica apagado, como no Instalador)
    let over = a().hover == B_CLOSE || a().hover == B_MIN;
    let off = if dark { hx(0xFFFFFF, 0.18) } else { hx(0, 0.14) };
    circle(22.0, TB / 2.0, 6.5, c1(0xFF5F57), true, 1.0);
    hit(rf(14.0, 10.0, 30.0, 30.0), B_CLOSE);
    circle(42.0, TB / 2.0, 6.5, c1(0xFEBC2E), true, 1.0);
    hit(rf(34.0, 10.0, 50.0, 30.0), B_MIN);
    circle(62.0, TB / 2.0, 6.5, off, true, 1.0);
    if over {
        line(19.5, 17.5, 24.5, 22.5, hx(0x4D0000, 0.7), 1.2);
        line(24.5, 17.5, 19.5, 22.5, hx(0x4D0000, 0.7), 1.2);
        line(39.0, 20.0, 45.0, 20.0, hx(0x5A3A00, 0.7), 1.2);
    }
    let title = match flow {
        Flow::Uninstall => t("Desinstalar o WacOS", "Uninstall WacOS"),
        Flow::Update => t("Atualizar o WacOS", "Update WacOS"),
        _ => t("Instalar o WacOS", "Install WacOS"),
    };
    text(&title, rf(0.0, 0.0, W, TB), 13.0, fg(), DWRITE_FONT_WEIGHT_SEMI_BOLD, false, CENTER, true);
    // barra lateral: logo e etapas
    paint_logo(SIDE / 2.0 - 40.0, TB + 22.0, 80.0);
    let (st_, cur) = steps();
    let mut y = TB + 130.0;
    for (i, s) in st_.iter().enumerate() {
        let feito = i < cur || (page == Page::Done && i == cur && ok);
        let agora = i == cur;
        if agora && !feito {
            circle(36.0, y + 10.0, 5.0, accent(), true, 1.0);
        } else if feito {
            circle(36.0, y + 10.0, 5.0, if dark { hx(0xFFFFFF, 0.45) } else { c1(0x8E8E93) }, true, 1.0);
        } else {
            circle(36.0, y + 10.0, 4.5, if dark { hx(0xFFFFFF, 0.3) } else { hx(0, 0.25) }, false, 1.2);
        }
        text(s, rf(52.0, y, SIDE - 8.0, y + 20.0), 13.0, if agora { fg() } else { fg2() }, if agora { DWRITE_FONT_WEIGHT_SEMI_BOLD } else { REG }, false, LEAD, true);
        y += 30.0;
    }
    // painel de conteúdo
    let c = rf(SIDE + 6.0, TB + 8.0, W - 22.0, H - BOTTOM);
    fill(c, 10.0, if dark { c1(0x1C1C1E) } else { c1(0xFFFFFF) });
    stroke(c, 10.0, if dark { hx(0xFFFFFF, 0.08) } else { hx(0, 0.08) }, 1.0);
    let (l, r_) = (c.left + 30.0, c.right - 30.0);
    let mut yy = c.top + 26.0;
    let heading = |s: &str, yy: &mut f32| {
        text(s, rf(l, *yy, r_, *yy + 34.0), 22.0, fg(), DWRITE_FONT_WEIGHT_SEMI_BOLD, true, LEAD, false);
        *yy += 44.0;
    };
    let para = |s: &str, size: f32, col: Cor, yy: &mut f32| {
        let h = text_h(s, r_ - l, size);
        text(s, rf(l, *yy, r_, *yy + h + 4.0), size, col, REG, false, LEAD, false);
        *yy += h + 12.0;
    };
    let mut next_on = true;
    let mut next = t("Continuar", "Continue");
    let back = t("Voltar", "Go Back");
    let mut show_back = true;
    let (relr, relerr) = rel();
    match page {
        Page::Intro => {
            heading(&t("Bem-vindo ao instalador do WacOS", "Welcome to the WacOS Installer"), &mut yy);
            para(&t("O WacOS traz o macOS para o Windows 11: barra de menus, Dock, Finder, Spotlight, Central de Controle e Liquid Glass. Esta é a edição em Rust, instalada à parte da do C++.", "WacOS brings macOS to Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass. This is the Rust edition, installed separately from the C++ one."), 13.5, fg(), &mut yy);
            para(&t("Você vai escolher se instala o WacOS completo, só os apps ou só as barras de título do Mac. Tudo fica só para o seu usuário, sem administrador, e dá para desfazer depois em Aplicativos instalados.", "You'll choose the full WacOS, only the apps, or only the Mac title bars. Everything is installed for your user only, without administrator rights, and can be undone later in Installed apps."), 13.5, fg(), &mut yy);
            if !a().pkg_ver.is_empty() {
                para(&format!("{}{}", t("Versão: ", "Version: "), a().pkg_ver), 12.0, fg2(), &mut yy);
            }
            para(&t("O WacOS é gratuito para uso pessoal e não comercial. O código-fonte está disponível para consulta, mas não é de código aberto. © 2026 Eternity070628. Todos os direitos reservados. Apple, macOS e os nomes e ícones relacionados são da Apple Inc.; este projeto não é afiliado à Apple.", "WacOS is free for personal, non-commercial use. It is source-available, not open source. © 2026 Eternity070628. All rights reserved. Apple, macOS and related names and icons belong to Apple Inc.; this project is not affiliated with Apple."), 11.5, fg2(), &mut yy);
            show_back = false;
        }
        Page::Home => {
            heading(&format!("WacOS {}", a().inst_ver), &mut yy);
            para(&t("O WacOS já está instalado neste PC. O que você quer fazer?", "WacOS is already installed on this PC. What would you like to do?"), 13.5, fg(), &mut yy);
            yy += 4.0;
            let novo = a().from_pkg && a().pkg_ver != a().inst_ver && !a().pkg_ver.is_empty();
            let upd = if novo { format!("{}{}", t("Atualizar para ", "Update to "), a().pkg_ver) } else { t("Procurar atualizações", "Check for updates") };
            let upd_d = if novo { t("Troca os programas por estes, com os seus ajustes e escolhas mantidos.", "Replaces the programs with these ones; your settings and choices stay.") } else { t("Procura a versão mais nova no GitHub e instala, com os seus ajustes mantidos.", "Looks for the latest version on GitHub and installs it; your settings stay.") };
            let hs = a().home_sel;
            radio_card(rf(l, yy, r_, yy + 64.0), &upd, &upd_d, hs == 0, B_HOME0);
            yy += 76.0;
            radio_card(rf(l, yy, r_, yy + 64.0), &t("Mudar o que está instalado", "Change what's installed"), &t("WacOS completo, só os apps ou só as barras de título.", "Full WacOS, only the apps, or only the title bars."), hs == 1, B_HOME0 + 1);
            yy += 76.0;
            radio_card(rf(l, yy, r_, yy + 64.0), &t("Desinstalar o WacOS", "Uninstall WacOS"), &t("Remove tudo e devolve o visual do Windows.", "Removes everything and brings back the Windows look."), hs == 2, B_HOME0 + 2);
            show_back = false;
        }
        Page::Type => {
            heading(&t("Tipo de instalação", "Installation Type"), &mut yy);
            let ms = [
                (t("WacOS completo", "Full WacOS"), t("Barra de menus, Dock, Finder, Spotlight e todos os apps, no lugar da barra de tarefas.", "Menu bar, Dock, Finder, Spotlight and all apps, replacing the taskbar.")),
                (t("Só os apps", "Only the apps"), t("Os apps que você escolher, no Menu Iniciar. A sua barra de tarefas fica como está.", "The apps you pick, in the Start menu. Your taskbar stays as it is.")),
                (t("Só as barras de título do Mac", "Only the Mac title bars"), t("Os botões e a barra do Mac nas janelas dos outros programas.", "The Mac buttons and title bar on other programs' windows.")),
                (t("Apps e barras de título", "Apps and title bars"), t("Os dois juntos, sem trocar a barra de tarefas.", "Both, without replacing the taskbar.")),
            ];
            let cw = (r_ - l - 12.0) / 2.0;
            let mode = a().ch.mode;
            for (i, (tt, dd)) in ms.iter().enumerate() {
                let (x, y2) = (l + (i % 2) as f32 * (cw + 12.0), yy + (i / 2) as f32 * 96.0);
                radio_card(rf(x, y2, x + cw, y2 + 86.0), tt, dd, mode == MODES[i], B_MODE0 + i as i32);
            }
            yy += 202.0;
            let full = mode == Mode::Full;
            let bars = matches!(mode, Mode::Bars | Mode::AppsBars);
            let src = p().src.clone();
            let ch = &a().ch;
            let (au, cu, fo, as_) = (ch.autostart, ch.cursor, ch.fonts, ch.assoc);
            if full || bars {
                check_box(l, yy, &if full { t("Abrir o WacOS ao entrar no Windows", "Open WacOS when you sign in") } else { t("Ligar as barras de título ao entrar no Windows", "Turn on the title bars when you sign in") }, au, B_CHK0, 400.0);
                yy += 28.0;
            }
            if full && is_dir(&format!("{src}\\cursor")) {
                check_box(l, yy, &t("Usar o cursor do Mac", "Use the Mac cursor"), cu, B_CHK0 + 1, 400.0);
                yy += 28.0;
            }
            if is_dir(&format!("{src}\\fontes")) {
                check_box(l, yy, &t("Instalar as fontes SF Pro (o visual fica igual ao do Mac)", "Install the SF Pro fonts (for the exact Mac look)"), fo, B_CHK0 + 2, 400.0);
                yy += 28.0;
            }
            if mode != Mode::Bars {
                check_box(l, yy, &t("Pôr o Música e o QuickTime em \"Abrir com\"", "Add Music and QuickTime to \"Open with\""), as_, B_CHK0 + 3, 400.0);
                yy += 28.0;
            }
            if any_running() {
                para(&t("O WacOS e os apps dele que estiverem abertos vão ser fechados durante a instalação.", "WacOS and its apps will be closed during installation."), 11.5, fg2(), &mut yy);
            }
        }
        Page::Apps => {
            heading(&t("Escolha os apps", "Choose the apps"), &mut yy);
            let cw = (r_ - l) / 2.0;
            let mut n = 0;
            let src = p().src.clone();
            for i in 0..a().apps.len() {
                if !exists(&format!("{src}\\bin\\{}.exe", a().apps[i].exe)) {
                    continue;
                }
                let (x, y2) = (l + (n % 2) as f32 * cw, yy + (n / 2) as f32 * 27.0);
                let (nm, on) = (a().apps[i].name, a().apps[i].on);
                check_box(x, y2, nm, on, B_APP0 + i as i32, cw - 10.0);
                n += 1;
            }
            yy += ((n + 1) / 2) as f32 * 27.0 + 8.0;
            button(rf(l, yy, l + 140.0, yy + 26.0), &t("Marcar todos", "Select All"), B_ALL, false, true);
            button(rf(l + 150.0, yy, l + 290.0, yy + 26.0), &t("Desmarcar todos", "Select None"), B_NONE, false, true);
            next_on = a().apps.iter().any(|x| x.on);
            next = t("Instalar", "Install");
        }
        Page::UpdCheck => {
            heading(&t("Atualização de Software", "Software Update"), &mut yy);
            if CHECKING.load(Ordering::SeqCst) {
                for i in 0..12 {
                    let an = a().spin + i as f32 * std::f32::consts::PI / 6.0;
                    let al = 0.15 + 0.85 * ((11 - i) as f32 / 11.0);
                    let (cx, cy) = ((l + r_) / 2.0, yy + 50.0);
                    line(cx + an.cos() * 9.0, cy + an.sin() * 9.0, cx + an.cos() * 17.0, cy + an.sin() * 17.0, if dark { hx(0xFFFFFF, al) } else { hx(0, al * 0.6) }, 2.6);
                }
                yy += 86.0;
                text(&t("Procurando atualizações…", "Checking for updates…"), rf(l, yy, r_, yy + 20.0), 13.0, fg2(), REG, false, CENTER, false);
                next_on = false;
            } else if !relerr.is_empty() {
                para(&relerr, 13.5, fg(), &mut yy);
                next = t("Tentar de novo", "Try Again");
            } else if relr.tag == a().inst_ver {
                para(&format!("{}{}).", t("O WacOS está atualizado (", "WacOS is up to date ("), a().inst_ver), 13.5, fg(), &mut yy);
                next = t("Fechar", "Close");
            } else {
                let data = if relr.date.is_empty() { String::new() } else { format!(" ({})", relr.date) };
                para(&format!("{}{}{data}", t("Uma versão nova está disponível: ", "A new version is available: "), relr.tag), 14.0, fg(), &mut yy);
                let iv = if a().inst_ver.is_empty() { t("desconhecida", "unknown") } else { a().inst_ver.clone() };
                let mb = if relr.size > 0 { format!(" · {} MB", relr.size / 1048576) } else { String::new() };
                para(&format!("{}{iv}{mb}", t("Instalada: ", "Installed: ")), 12.0, fg2(), &mut yy);
                for n in &relr.notes {
                    let h = text_h(n, r_ - l - 16.0, 12.5);
                    circle(l + 4.0, yy + 9.0, 2.2, fg2(), true, 1.0);
                    text(n, rf(l + 14.0, yy, r_, yy + h + 2.0), 12.5, fg(), REG, false, LEAD, false);
                    yy += h + 6.0;
                    if yy > c.bottom - 30.0 {
                        break;
                    }
                }
                next = t("Atualizar", "Update");
            }
            show_back = a().installed;
        }
        Page::Uninst => {
            heading(&t("Desinstalar o WacOS", "Uninstall WacOS"), &mut yy);
            para(&t("O WacOS vai ser fechado e removido: programas, atalhos, início automático, fontes e cursor que ele colocou. A barra de tarefas e as janelas voltam ao visual do Windows.", "WacOS will be closed and removed: programs, shortcuts, autostart, and the fonts and cursor it installed. The taskbar and windows go back to the Windows look."), 13.5, fg(), &mut yy);
            yy += 4.0;
            let (ds, cc) = (a().ch.del_settings, a().ch.clean_cache);
            check_box(l, yy, &t("Apagar também os meus ajustes do WacOS (notas, lembretes, eventos e contatos ficam)", "Also delete my WacOS settings (notes, reminders, events and contacts are kept)"), ds, B_CHK0 + 4, r_ - l);
            yy += 46.0; // duas linhas
            check_box(l, yy, &t("Limpar o cache de ícones do Windows (a área de trabalho pisca)", "Clear the Windows icon cache (the desktop flickers)"), cc, B_CHK0 + 5, 400.0);
            next = t("Desinstalar", "Uninstall");
            show_back = a().installed && flow == Flow::Uninstall && !a().force_uninstall_only;
        }
        Page::Work => {
            heading(&match flow {
                Flow::Uninstall => t("Desinstalando…", "Uninstalling…"),
                Flow::Update => t("Atualizando…", "Updating…"),
                _ => t("Instalando…", "Installing…"),
            }, &mut yy);
            yy += 40.0;
            fill(rf(l, yy, r_, yy + 8.0), 4.0, if dark { hx(0xFFFFFF, 0.1) } else { hx(0, 0.08) });
            let pg = prog().clamp(0.0, 1.0);
            if pg > 0.0 {
                fill(rf(l, yy, l + (r_ - l) * pg, yy + 8.0), 4.0, accent());
            }
            yy += 20.0;
            let st = STATUS.lock().unwrap().0.clone();
            text(&st, rf(l, yy, r_, yy + 20.0), 12.5, fg2(), REG, false, LEAD, false);
            next_on = false;
            show_back = false;
        }
        Page::Done => {
            let cx = (l + r_) / 2.0;
            yy += 20.0;
            circle(cx, yy + 34.0, 34.0, if ok { c1(0x30D158) } else { c1(0xFF453A) }, true, 1.0);
            if ok {
                check(cx, yy + 34.0, 34.0, c1(0xFFFFFF), 4.5);
            } else {
                line(cx - 10.0, yy + 24.0, cx + 10.0, yy + 44.0, c1(0xFFFFFF), 4.5);
                line(cx + 10.0, yy + 24.0, cx - 10.0, yy + 44.0, c1(0xFFFFFF), 4.5);
            }
            yy += 90.0;
            let h = if !ok {
                t("Não deu certo", "Something went wrong")
            } else {
                match flow {
                    Flow::Uninstall => t("O WacOS foi desinstalado.", "WacOS was uninstalled."),
                    Flow::Update => t("O WacOS foi atualizado.", "WacOS was updated."),
                    _ => t("A instalação foi concluída.", "The installation was completed successfully."),
                }
            };
            text(&h, rf(l, yy, r_, yy + 30.0), 20.0, fg(), DWRITE_FONT_WEIGHT_SEMI_BOLD, true, CENTER, false);
            yy += 40.0;
            let mode = a().ch.mode;
            let sub = {
                let s = STATUS.lock().unwrap();
                if !ok {
                    if s.1.is_empty() {
                        s.0.clone()
                    } else {
                        s.1.clone()
                    }
                } else if flow == Flow::Uninstall {
                    s.0.clone()
                } else if mode == Mode::Full || flow == Flow::Update {
                    t("Para sair do WacOS: Ctrl+Alt+Shift+F12\nEmergência (devolve o Explorador): Ctrl+Alt+Shift+F11", "To quit WacOS: Ctrl+Alt+Shift+F12\nEmergency exit (brings Explorer back): Ctrl+Alt+Shift+F11")
                } else {
                    t("Os apps estão no Menu Iniciar, na pasta WacOS.", "The apps are in the Start menu, in the WacOS folder.")
                }
            };
            let sh = text_h(&sub, r_ - l, 13.0);
            text(&sub, rf(l, yy, r_, yy + sh + 4.0), 13.0, fg2(), REG, false, CENTER, false);
            yy += sh + 16.0;
            if ok && flow != Flow::Uninstall && mode != Mode::Apps {
                // centrada pelo tamanho de verdade (caixa 16 + 10 de vão + o texto)
                let lbl = if mode == Mode::Full { t("Abrir o WacOS agora", "Open WacOS now") } else { t("Ligar as barras de título agora", "Turn on the title bars now") };
                let lw = 26.0 + text_w(&lbl, 13.0);
                let la = a().ch.launch;
                check_box(cx - lw / 2.0, yy, &lbl, la, B_CHK0 + 6, 260.0);
            }
            next = t("Fechar", "Close");
            show_back = false;
        }
        Page::Error => {
            heading(&t("Não dá para instalar daqui", "Can't install from here"), &mut yy);
            let e = STATUS.lock().unwrap().1.clone();
            para(&e, 13.5, fg(), &mut yy);
            next = t("Abrir a página de downloads", "Open the downloads page");
            show_back = false;
        }
    }
    // barra de baixo
    let by = H - BOTTOM + 18.0;
    button(rf(W - 142.0, by, W - 22.0, by + 30.0), &next, B_NEXT, true, next_on && !busy);
    if show_back && !busy {
        button(rf(W - 272.0, by, W - 152.0, by + 30.0), &back, B_BACK, false, true);
    }
    unsafe {
        if let Err(e) = rt().EndDraw(None, None) {
            if e.code() == D2DERR_RECREATE_TARGET {
                a().rt = None;
                a().hrt = None;
                a().logo = None;
            }
        }
    }
}
fn invalidate() {
    unsafe {
        let _ = InvalidateRect(a().hwnd, None, FALSE);
    }
}
fn start_work(f: fn()) {
    BUSY.store(true, Ordering::SeqCst);
    WORK_DONE.store(false, Ordering::SeqCst);
    WORK_OK.store(false, Ordering::SeqCst);
    set_prog(0.0);
    *STATUS.lock().unwrap() = (t("Preparando…", "Preparing…"), String::new());
    a().page = Page::Work;
    std::thread::spawn(move || unsafe {
        let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
        f();
        CoUninitialize();
    });
    unsafe {
        SetTimer(a().hwnd, 1, 50, None);
    }
}
fn start_check() {
    CHECKING.store(true, Ordering::SeqCst);
    a().page = Page::UpdCheck;
    a().flow = Flow::Update;
    std::thread::spawn(|| {
        check_github();
        CHECKING.store(false, Ordering::SeqCst);
    });
    if !a().hwnd.0.is_null() {
        unsafe {
            SetTimer(a().hwnd, 1, 40, None);
        }
    }
}
fn next() {
    let dest = p().dest.clone();
    match a().page {
        Page::Intro => {
            a().flow = Flow::Install;
            a().page = Page::Type;
        }
        Page::Home => match a().home_sel {
            0 => {
                if a().from_pkg && a().pkg_ver != a().inst_ver && !a().pkg_ver.is_empty() {
                    a().flow = Flow::Update;
                    start_work(|| do_install(true));
                } else {
                    start_check();
                }
            }
            1 => {
                a().flow = Flow::Modify;
                a().page = Page::Type;
                let l = lines(&read_text(&format!("{dest}\\modo.txt"))); // o que já estava
                if let Some(m) = l.first().and_then(|m| MODE_ID.iter().position(|x| *x == m.trim())) {
                    a().ch.mode = MODES[m];
                }
                if l.len() > 1 {
                    for ap in a().apps.iter_mut() {
                        ap.on = l[1..].iter().any(|x| x.trim() == ap.exe);
                    }
                }
                a().ch.autostart = task_exists(if a().ch.mode == Mode::Full { comum::edicao::TAREFA } else { comum::edicao::TAREFA_BARRAS });
            }
            _ => {
                a().flow = Flow::Uninstall;
                a().page = Page::Uninst;
            }
        },
        Page::Type => {
            if matches!(a().ch.mode, Mode::Apps | Mode::AppsBars) {
                a().page = Page::Apps;
            } else {
                start_work(|| do_install(false));
            }
        }
        Page::Apps => start_work(|| do_install(false)),
        Page::UpdCheck => {
            let (r, e) = rel();
            if !e.is_empty() {
                start_check();
            } else if r.tag == a().inst_ver {
                unsafe {
                    let _ = PostMessageW(a().hwnd, WM_CLOSE, WPARAM(0), LPARAM(0));
                }
            } else {
                start_work(do_update);
            }
        }
        Page::Uninst => start_work(do_uninstall),
        Page::Done => {
            let (ok, flow, mode) = (WORK_OK.load(Ordering::SeqCst), a().flow, a().ch.mode);
            if ok && flow != Flow::Uninstall && a().ch.launch {
                if mode == Mode::Full || flow == Flow::Update {
                    let modo = lines(&read_text(&format!("{dest}\\modo.txt")));
                    let shell = format!("{dest}\\bin\\WacOSShell.exe");
                    if exists(&shell) && (flow != Flow::Update || modo.first().map(|m| m.trim() == "completo").unwrap_or(true)) {
                        launch(&shell, "");
                    }
                } else if matches!(mode, Mode::Bars | Mode::AppsBars) {
                    launch(&format!("{dest}\\bin\\WacOSTitleBars.exe"), "");
                }
            }
            unsafe {
                let _ = PostMessageW(a().hwnd, WM_CLOSE, WPARAM(0), LPARAM(0));
            }
            return;
        }
        Page::Error => {
            shell_open("https://github.com/Eternity070628/WacOS/releases/latest", None);
            unsafe {
                let _ = PostMessageW(a().hwnd, WM_CLOSE, WPARAM(0), LPARAM(0));
            }
            return;
        }
        Page::Work => {}
    }
    invalidate();
}
fn back() {
    match a().page {
        Page::Type => a().page = if a().installed { Page::Home } else { Page::Intro },
        Page::Apps => a().page = Page::Type,
        Page::UpdCheck | Page::Uninst => {
            if a().installed {
                a().page = Page::Home;
                a().flow = Flow::Install;
            }
        }
        _ => {}
    }
    invalidate();
}
fn click(id: i32) {
    let busy = BUSY.load(Ordering::SeqCst);
    let ch = &mut a().ch;
    match id {
        B_CLOSE => {
            if !busy {
                unsafe {
                    let _ = PostMessageW(a().hwnd, WM_CLOSE, WPARAM(0), LPARAM(0));
                }
            }
            return;
        }
        B_MIN => {
            unsafe {
                let _ = ShowWindow(a().hwnd, SW_MINIMIZE);
            }
            return;
        }
        B_NEXT => return next(),
        B_BACK => return back(),
        B_ALL | B_NONE => {
            for ap in a().apps.iter_mut() {
                ap.on = id == B_ALL;
            }
        }
        _ if (B_MODE0..B_MODE0 + 4).contains(&id) => {
            let antes = ch.mode;
            ch.mode = MODES[(id - B_MODE0) as usize];
            if antes != ch.mode {
                ch.autostart = ch.mode != Mode::Apps;
            }
        }
        _ if (B_HOME0..B_HOME0 + 3).contains(&id) => a().home_sel = id - B_HOME0,
        _ if (B_APP0..B_APP0 + 100).contains(&id) => {
            let ap = &mut a().apps[(id - B_APP0) as usize];
            ap.on = !ap.on;
        }
        B_CHK0 => ch.autostart = !ch.autostart,
        _ if id == B_CHK0 + 1 => ch.cursor = !ch.cursor,
        _ if id == B_CHK0 + 2 => ch.fonts = !ch.fonts,
        _ if id == B_CHK0 + 3 => ch.assoc = !ch.assoc,
        _ if id == B_CHK0 + 4 => ch.del_settings = !ch.del_settings,
        _ if id == B_CHK0 + 5 => ch.clean_cache = !ch.clean_cache,
        _ if id == B_CHK0 + 6 => ch.launch = !ch.launch,
        _ => {}
    }
    invalidate();
}
fn hit_at(x: i32, y: i32) -> i32 {
    let (fx, fy) = (x as f32 / a().k, y as f32 / a().k);
    a().hits.iter().rev().find(|(r, _)| fx >= r.left && fx < r.right && fy >= r.top && fy < r.bottom).map(|x| x.1).unwrap_or(-1)
}
fn make_target() {
    if a().rt.is_some() {
        return;
    }
    unsafe {
        let mut rc = RECT::default();
        let _ = GetClientRect(a().hwnd, &mut rc);
        let props = D2D1_RENDER_TARGET_PROPERTIES { dpiX: 96.0, dpiY: 96.0, ..Default::default() };
        let hp = D2D1_HWND_RENDER_TARGET_PROPERTIES { hwnd: a().hwnd, pixelSize: D2D_SIZE_U { width: rc.right as u32, height: rc.bottom as u32 }, presentOptions: D2D1_PRESENT_OPTIONS_NONE };
        if let Ok(h) = d2d().CreateHwndRenderTarget(&props, &hp) {
            h.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
            a().rt = h.cast().ok();
            a().hrt = Some(h);
        }
    }
}
extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    unsafe {
        if A.get().is_none() || a().hwnd.0.is_null() {
            return DefWindowProcW(h, m, w_, l);
        }
        let busy = BUSY.load(Ordering::SeqCst);
        match m {
            WM_NCCALCSIZE if w_.0 != 0 => return LRESULT(0), // sem a moldura do Windows: a nossa barra de título
            WM_NCHITTEST => {
                let p_ = app2d::screen_to_client(h, l);
                if (p_.y as f32) < TB * a().k && hit_at(p_.x, p_.y) < 0 {
                    return LRESULT(HTCAPTION as isize);
                }
                return LRESULT(HTCLIENT as isize);
            }
            WM_PAINT => {
                let mut ps = PAINTSTRUCT::default();
                BeginPaint(h, &mut ps);
                make_target();
                paint();
                let _ = EndPaint(h, &ps);
            }
            WM_SIZE => {
                if let Some(r) = &a().hrt {
                    let _ = r.Resize(&D2D_SIZE_U { width: loword(l.0 as usize), height: hiword(l.0 as usize) });
                }
            }
            WM_MOUSEMOVE => {
                let mut tm = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };
                let _ = TrackMouseEvent(&mut tm);
                let hv = hit_at(get_x_lparam(l), get_y_lparam(l));
                if hv != a().hover {
                    a().hover = hv;
                    SetCursor(LoadCursorW(None, if hv >= 0 { IDC_HAND } else { IDC_ARROW }).unwrap_or_default());
                    invalidate();
                }
            }
            WM_SETCURSOR if loword(l.0 as usize) == HTCLIENT => {
                SetCursor(LoadCursorW(None, if a().hover >= 0 { IDC_HAND } else { IDC_ARROW }).unwrap_or_default());
                return LRESULT(1);
            }
            WM_MOUSELEAVE => {
                if a().hover >= 0 {
                    a().hover = -1;
                    invalidate();
                }
            }
            WM_LBUTTONDOWN => {
                a().press = hit_at(get_x_lparam(l), get_y_lparam(l));
                SetCapture(h);
                invalidate();
            }
            WM_LBUTTONUP => {
                let id = hit_at(get_x_lparam(l), get_y_lparam(l));
                let _ = ReleaseCapture();
                let pr = std::mem::replace(&mut a().press, -1);
                if id >= 0 && id == pr {
                    click(id);
                }
                invalidate();
            }
            WM_KEYDOWN => {
                if w_.0 as u16 == VK_RETURN.0 && !busy {
                    next();
                } else if w_.0 as u16 == VK_ESCAPE.0 && !busy {
                    let _ = PostMessageW(h, WM_CLOSE, WPARAM(0), LPARAM(0));
                }
            }
            WM_TIMER => {
                a().spin += 0.16;
                if a().page == Page::Work && WORK_DONE.load(Ordering::SeqCst) {
                    BUSY.store(false, Ordering::SeqCst);
                    a().page = Page::Done;
                    let _ = KillTimer(h, 1);
                    a().inst_ver = version_of(&p().dest);
                }
                if a().page == Page::UpdCheck && !CHECKING.load(Ordering::SeqCst) {
                    let _ = KillTimer(h, 1);
                }
                invalidate();
            }
            WM_SETTINGCHANGE => {
                a().dark = app2d::dark();
                let d = BOOL::from(a().dark);
                let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(20), &d as *const _ as *const c_void, 4);
                invalidate();
            }
            WM_DPICHANGED => {
                a().k = hiword(w_.0) as f32 / 96.0;
                let r = &*(l.0 as *const RECT);
                let _ = SetWindowPos(h, None, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOZORDER | SWP_NOACTIVATE);
            }
            WM_CLOSE => {
                if !busy {
                    let _ = DestroyWindow(h);
                }
            }
            WM_DESTROY => PostQuitMessage(0),
            _ => return DefWindowProcW(h, m, w_, l),
        }
        LRESULT(0)
    }
}

/// --foto <pasta>: desenha cada tela num PNG (claro e escuro), sem instalar nada; para conferir o visual
fn foto(dir: &str) {
    mk_dirs(dir);
    let Ok(wic) = (unsafe { CoCreateInstance::<_, IWICImagingFactory>(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER) }) else { return };
    a().k = 1.5;
    let (pw, ph) = ((W * 1.5) as u32, (H * 1.5) as u32);
    a().inst_ver = "build-13".into();
    a().pkg_ver = "build-14".into();
    a().installed = true;
    a().from_pkg = true;
    *REL.lock().unwrap() = Some((
        Release { tag: "build-14".into(), date: "20/11/2026".into(), size: 172 << 20, notes: vec!["Dynamic Island shows on the desktop again".into(), "License: source-available, all rights reserved".into(), "Mac OS X Leopard theme, Game Mode, apps and title bars without the shell".into()], ..Default::default() },
        String::new(),
    ));
    let shots = [
        ("1-intro", Page::Intro, Flow::Install, Mode::Full, 0.0, true),
        ("2-home", Page::Home, Flow::Install, Mode::Full, 0.0, true),
        ("3-tipo", Page::Type, Flow::Install, Mode::Full, 0.0, true),
        ("4-tipo-apps", Page::Type, Flow::Install, Mode::AppsBars, 0.0, true),
        ("5-apps", Page::Apps, Flow::Install, Mode::Apps, 0.0, true),
        ("6-instalando", Page::Work, Flow::Install, Mode::Full, 0.62, true),
        ("7-concluido", Page::Done, Flow::Install, Mode::Full, 1.0, true),
        ("8-atualizacao", Page::UpdCheck, Flow::Update, Mode::Full, 0.0, true),
        ("9-desinstalar", Page::Uninst, Flow::Uninstall, Mode::Full, 0.0, true),
        ("10-erro", Page::Done, Flow::Install, Mode::Full, 1.0, false),
    ];
    for dark in [false, true] {
        for (name, page, flow, mode, pr, ok) in shots {
            let app = a();
            (app.dark, app.page, app.flow, app.ch.mode) = (dark, page, flow, mode);
            set_prog(pr);
            WORK_OK.store(ok, Ordering::SeqCst);
            *STATUS.lock().unwrap() = (t("Copiando WacOSFinder.exe", "Copying WacOSFinder.exe"), t("O WacOS não fechou. Feche-o com Ctrl+Alt+Shift+F12 e tente de novo.", "WacOS didn't quit."));
            let r = (|| -> Result<()> {
                unsafe {
                    let bmp = wic.CreateBitmap(pw, ph, &GUID_WICPixelFormat32bppPBGRA, WICBitmapCacheOnLoad)?;
                    let props = D2D1_RENDER_TARGET_PROPERTIES { pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED }, dpiX: 96.0, dpiY: 96.0, ..Default::default() };
                    a().rt = Some(d2d().CreateWicBitmapRenderTarget(&bmp, &props)?);
                    a().logo = None;
                    paint();
                    a().logo = None;
                    a().rt = None;
                    app2d::salvar_png(&bmp, &format!("{dir}\\{name}-{}.png", if dark { "escuro" } else { "claro" }))
                }
            })();
            println!("{name} {}: {r:?}", if dark { "escuro" } else { "claro" });
        }
    }
}
fn load_logo() -> Option<IWICBitmapSource> {
    unsafe {
        let wic: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).ok()?;
        let s = wic.CreateStream().ok()?;
        s.InitializeFromMemory(LOGO).ok()?;
        let d = wic.CreateDecoderFromStream(&s, std::ptr::null(), WICDecodeMetadataCacheOnLoad).ok()?;
        let f = d.GetFrame(0).ok()?;
        let c = wic.CreateFormatConverter().ok()?;
        c.Initialize(&f, &GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).ok()?;
        c.cast().ok()
    }
}
/// o argumento depois de `chave` (entre aspas ou até o fim)
fn arg_after(args: &str, chave: &str) -> Option<String> {
    let i = args.find(chave)? + chave.len();
    let r = args[i..].trim();
    Some(if let Some(s) = r.strip_prefix('"') { s[..s.find('"').unwrap_or(s.len())].to_string() } else { r.to_string() })
}

fn main() {
    if !app2d::init() {
        std::process::exit(1);
    }
    let lang = unsafe { comum::windows::Win32::Globalization::GetUserDefaultUILanguage() };
    PT.store(lang & 0x3FF == 0x16, Ordering::Relaxed); // LANG_PORTUGUESE
    let me = std::env::current_exe().map(|p| p.to_string_lossy().to_string()).unwrap_or_default();
    let dest = comum::edicao::pasta_instalacao();
    *P.get() = Some(Caminhos { me_dir: parent(&me), me: me.clone(), src: String::new(), log: format!("{dest}\\instalacao.log"), dest: dest.clone() });
    let args: String = std::env::args().skip(1).map(|x| if x.contains(' ') { format!("\"{x}\"") } else { x }).collect::<Vec<_>>().join(" ");
    let want_uninst = args.contains("--desinstalar");
    let want_update = args.contains("--atualizar");
    let teste = args.contains("--foto") || args.contains("--diagnostico");
    // desinstalar rodando de dentro da pasta que vai ser apagada: uma cópia no TEMP faz o trabalho
    if want_uninst && me.to_lowercase().starts_with(&format!("{dest}\\").to_lowercase()) {
        let c = format!("{}\\WacOSSetup-desinstalar.exe", env("TEMP"));
        if std::fs::copy(&me, &c).is_ok() {
            shell_open(&c, Some("--desinstalar"));
            return;
        }
    }
    if !teste && me.to_lowercase().starts_with(&env("TEMP").to_lowercase()) {
        let z = wz(&me);
        unsafe {
            let _ = MoveFileExW(pc(&z), PCWSTR::null(), MOVEFILE_DELAY_UNTIL_REBOOT);
        }
    }
    // de onde vêm os programas: o pacote ao lado deste exe, ou a própria instalação
    let me_dir = p().me_dir.clone();
    let from_pkg = exists(&format!("{me_dir}\\bin\\WacOSShell.exe")) && !me_dir.eq_ignore_ascii_case(&dest);
    p().src = if from_pkg { me_dir.clone() } else { dest.clone() };
    let installed = exists(&format!("{dest}\\bin\\WacOSShell.exe")) || exists(&format!("{dest}\\bin\\WacOSFinder.exe"));
    let pick = |n: &str, d: &str| if app2d::has_font(n) { n.to_string() } else { d.to_string() };
    *A.get() = Some(App {
        hwnd: HWND::default(),
        rt: None,
        hrt: None,
        logo_src: load_logo(),
        logo: None,
        k: 1.0,
        dark: app2d::dark(),
        font_ui: pick("SF Pro Text", "Segoe UI Variable Text"),
        font_title: pick("SF Pro Display", "Segoe UI Variable Display"),
        page: Page::Intro,
        flow: Flow::Install,
        home_sel: 0,
        spin: 0.0,
        inst_ver: version_of(&dest),
        pkg_ver: if from_pkg { version_of(&me_dir) } else { String::new() },
        installed,
        from_pkg,
        force_uninstall_only: false,
        hits: Vec::new(),
        hover: -1,
        press: -1,
        ch: Choices { mode: Mode::Full, autostart: true, cursor: true, fonts: true, assoc: false, launch: true, del_settings: false, clean_cache: false },
        apps: [
            ("WacOSFinder", "Finder"),
            ("WacOSSettings", "System Settings"),
            ("WacOSActivityMonitor", "Activity Monitor"),
            ("WacOSTerminal", "Terminal"),
            ("WacOSCalculator", "Calculator"),
            ("WacOSNotes", "Notes"),
            ("WacOSScreenshot", "Screenshot"),
            ("WacOSPreview", "Preview"),
            ("WacOSReminders", "Reminders"),
            ("WacOSCalendar", "Calendar"),
            ("WacOSTextEdit", "TextEdit"),
            ("WacOSClock", "Clock"),
            ("WacOSWeather", "Weather"),
            ("WacOSContacts", "Contacts"),
            ("WacOSPhotos", "Photos"),
            ("WacOSTimeMachine", "Time Machine"),
            ("WacOSMusic", "Music"),
            ("WacOSQuickTime", "QuickTime Player"),
            ("WacOSForceQuit", "Force Quit Applications"),
        ]
        .into_iter()
        .map(|(exe, name)| AppInfo { exe, name, on: true })
        .collect(),
    });
    if want_uninst {
        a().flow = Flow::Uninstall;
        a().page = Page::Uninst;
        a().force_uninstall_only = true;
    } else if want_update {
        start_check();
    } else if installed {
        a().page = Page::Home;
    } else if !from_pkg {
        a().page = Page::Error;
        fail(&t("Esta pasta não tem os programas do WacOS. Baixe o pacote pronto (WacOS-<data>.zip) na página de downloads, extraia e abra o WacOSSetup.exe de dentro dele.", "This folder doesn't have the WacOS programs. Download the ready-made package (WacOS-<date>.zip) from the downloads page, extract it and open WacOSSetup.exe from inside it."));
    }
    // --diagnostico <arquivo>: consulta o GitHub, baixa o pacote, confere o SHA-256 e extrai num temporário, sem instalar
    if let Some(out) = arg_after(&args, "--diagnostico") {
        check_github();
        let (r, e) = rel();
        let mut s = format!("tag={}\r\ndata={}\r\nurl={}\r\nsha={}\r\nmb={}\r\nerro={e}\r\n", r.tag, r.date, r.url, r.sha, r.size >> 20);
        for n in &r.notes {
            s += &format!("nota={n}\r\n");
        }
        if e.is_empty() {
            let tmp = format!("{}\\wacos-diag", env("TEMP"));
            mk_dirs(&tmp);
            let zip = format!("{tmp}\\p.zip");
            let (host, path) = split_url(&r.url);
            let ok = !http_get(&host, &path, "application/octet-stream", Some(&zip), &|_, _| {}).is_empty();
            let sha = if ok { sha256_file(&zip) } else { String::new() };
            s += &format!("baixou={}\r\nsha_confere={}\r\n", ok as i32, (!sha.is_empty() && sha == r.sha) as i32);
            let ec = run_wait(&format!("{}\\System32\\tar.exe", env("WINDIR")), &format!("-xf \"{zip}\" -C \"{tmp}\""), 600000, true);
            s += &format!("tar={ec}\r\nbin_shell={}\r\nversao={}\r\n", exists(&format!("{tmp}\\bin\\WacOSShell.exe")) as i32, version_of(&tmp));
            shell_delete(&tmp);
        }
        write_text(&out, &s);
        return;
    }
    // --teste <instalar|atualizar|desinstalar> <arquivo>: o trabalho sem a janela, com as escolhas tiradas do PC
    if let Some(rest) = arg_after(&args, "--teste") {
        let (acao, out) = rest.split_once(' ').map(|(x, y)| (x.to_string(), y.trim().trim_matches('"').to_string())).unwrap_or((rest.clone(), String::new()));
        let ch = &mut a().ch;
        ch.autostart = task_exists(comum::edicao::TAREFA) || task_exists(comum::edicao::TAREFA_BARRAS) || !installed;
        let mut k = HKEY::default();
        ch.assoc = unsafe { RegOpenKeyExW(HKEY_CURRENT_USER, PCWSTR(wz(&format!("Software\\Classes\\{}", comum::edicao::PROG_MUSICA)).as_ptr()), 0, KEY_READ, &mut k).is_ok() };
        if ch.assoc {
            unsafe {
                let _ = RegCloseKey(k);
            }
        }
        let arrow = reg_get_str(HKEY_CURRENT_USER, "Control Panel\\Cursors", Some("Arrow"));
        ch.cursor = arrow.is_empty() || arrow.to_lowercase().contains("\\windows\\cursors\\");
        if let Some(m) = lines(&read_text(&format!("{dest}\\modo.txt"))).first().and_then(|m| MODE_ID.iter().position(|x| *x == m.trim())) {
            ch.mode = MODES[m];
        }
        let mut r = format!("acao={acao}\r\norigem={}\r\nautostart={}\r\nassoc={}\r\ncursor={}\r\nmodo={}\r\n", p().src, ch.autostart as i32, ch.assoc as i32, ch.cursor as i32, MODE_ID[mode_idx(ch.mode)]);
        let t0 = std::time::Instant::now();
        match acao.as_str() {
            "atualizar" => {
                check_github();
                let (rl, e) = rel();
                r += &format!("tag={}\r\nerro_github={e}\r\n", rl.tag);
                if e.is_empty() {
                    do_update();
                }
            }
            "desinstalar" => do_uninstall(),
            "instalar" => {
                if from_pkg {
                    do_install(false);
                } else {
                    fail("sem pacote ao lado do exe");
                }
            }
            _ => {}
        }
        let (st, er) = STATUS.lock().unwrap().clone();
        r += &format!("ok={}\r\nstatus={st}\r\nerro={er}\r\nsegundos={}\r\n", WORK_OK.load(Ordering::SeqCst) as i32, t0.elapsed().as_secs());
        if !out.is_empty() {
            write_text(&out, &r);
        }
        std::process::exit(if WORK_OK.load(Ordering::SeqCst) { 0 } else { 1 });
    }
    if let Some(d) = arg_after(&args, "--foto") {
        foto(&d);
        return;
    }
    unsafe {
        let hi: HINSTANCE = GetModuleHandleW(None).unwrap_or_default().into();
        let wc = WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hi, lpszClassName: w!("WacOSSetup"), hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), hIcon: LoadIconW(hi, PCWSTR(1 as *const u16)).unwrap_or_default(), ..Default::default() };
        RegisterClassW(&wc);
        let mut c = POINT::default();
        let _ = GetCursorPos(&mut c);
        let mon = MonitorFromPoint(c, MONITOR_DEFAULTTOPRIMARY);
        let (mut dx, mut dy) = (96u32, 96u32);
        let _ = GetDpiForMonitor(mon, MDT_EFFECTIVE_DPI, &mut dx, &mut dy);
        a().k = dx as f32 / 96.0;
        let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
        let _ = GetMonitorInfoW(mon, &mut mi);
        let (ww, wh) = ((W * a().k) as i32, (H * a().k) as i32);
        let titulo = wz(&t("Instalar o WacOS", "Install WacOS"));
        let Ok(h) = CreateWindowExW(WINDOW_EX_STYLE(0), w!("WacOSSetup"), pc(&titulo), WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, (mi.rcWork.left + mi.rcWork.right - ww) / 2, (mi.rcWork.top + mi.rcWork.bottom - wh) / 2, ww, wh, None, None, hi, None) else {
            std::process::exit(1)
        };
        a().hwnd = h;
        app2d::s().wnd = h;
        let mg = MARGINS { cxLeftWidth: 0, cxRightWidth: 0, cyTopHeight: 1, cyBottomHeight: 0 };
        let _ = DwmExtendFrameIntoClientArea(h, &mg);
        let corner = 2u32;
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const c_void, 4);
        let d = BOOL::from(a().dark);
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(20), &d as *const _ as *const c_void, 4);
        let _ = SetWindowPos(h, None, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
        let _ = ShowWindow(h, SW_SHOW);
        if CHECKING.load(Ordering::SeqCst) {
            SetTimer(h, 1, 40, None);
        }
        let mut msg = MSG::default();
        while GetMessageW(&mut msg, None, 0, 0).as_bool() {
            let _ = TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
        // a janela já fechou; o WacOS ainda está sendo aberto (launch)
        for _ in 0..300 {
            if ABRINDO.load(Ordering::SeqCst) <= 0 {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
    }
}