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
106 KB
Raw Blame
//! Monitor de Atividade (src\monitor\main.cpp): processos (NtQuerySystemInformation, todos de uma vez), CPU, memória,
//! energia, disco, rede (IP Helper) e GPU (os contadores PDH do Gerenciador de Tarefas); tabela ordenável com busca,
//! o painel de cada aba com gráfico, as folhas de Encerrar e Informações.
//! Desenha como no C++: Direct2D sobre DirectComposition (comum::tahoe), com o vidro, os cantos de 26 pt e a sombra
//! própria do Tahoe.
//! Teste: --foto saida.png [--aba 0..5] tira a foto depois de duas amostras, sem mostrar a janela.
#![windows_subsystem = "windows"]

use std::collections::{BTreeMap, HashMap};
use std::ffi::c_void;

use comum::app2d::{self, d2d, dw, salvar_png, screen_to_client, wheel_delta};
use comum::pressao::{self, PressaoMemoria};
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::*;
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::NetworkManagement::IpHelper::*;
use comum::windows::Win32::NetworkManagement::Ndis::*;
use comum::windows::Win32::Networking::WinSock::{AF_INET, AF_INET6};
use comum::windows::Win32::Security::*;
use comum::windows::Win32::Storage::FileSystem::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::LibraryLoader::*;
use comum::windows::Win32::System::Performance::*;
use comum::windows::Win32::System::Power::*;
use comum::windows::Win32::System::ProcessStatus::*;
use comum::windows::Win32::System::SystemInformation::*;
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::System::Time::FileTimeToSystemTime;
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::*;

const TOOLBAR_H: f32 = 52.0;
const HEADER_H: f32 = 28.0;
const ROW_H: f32 = 24.0;
const PANEL_H: f32 = 115.0;
const NAME_X: f32 = 51.0;
const ICON_X: f32 = 25.0;
const PILL_TOP: f32 = 7.5;
const PILL_H: f32 = 35.0;
const SEG_X: f32 = 426.0;
const SEG_W: f32 = 76.6;
const SEARCH_W: f32 = 323.0;
const HIST: usize = 90;
const T_SAMPLE: usize = 1;
const T_SEG: usize = 9;
const SAMPLE_MS: u32 = 2000;
const N_TABS: usize = 6;
const T_CPU: usize = 0;
const T_MEM: usize = 1;
const T_ENERGY: usize = 2;
const T_DISK: usize = 3;
const T_NET: usize = 4;

#[derive(Clone, Copy, PartialEq)]
enum K {
    Name,
    Cpu,
    CpuTime,
    Threads,
    Handles,
    Mem,
    Energy,
    Written,
    Read,
    Conn,
    Pid,
    User,
    Ctx,
    Kind,
    Gpu,
    GpuTime,
    Commit,
    GpuMem,
    RdOps,
    WrOps,
    Engine,
    Nap,
}
struct Coluna {
    key: K,
    title: &'static str,
    w: f32,
}
const fn c(key: K, title: &'static str, w: f32) -> Coluna {
    Coluna { key, title, w }
}
const TAB_NAMES: [&str; N_TABS] = ["CPU", "Memória", "Energia", "Disco", "Rede", "GPU"];
static COLS: [&[Coluna]; N_TABS] = [
    &[c(K::Name, "Nome do Processo", 0.0), c(K::Cpu, "% CPU", 80.0), c(K::CpuTime, "Tempo de CPU", 114.0), c(K::Threads, "Threads", 76.0), c(K::Ctx, "Trocas de Contexto", 146.0), c(K::Kind, "Tipo", 70.0), c(K::Gpu, "% GPU", 66.0), c(K::GpuTime, "Tempo de GPU", 114.0), c(K::Pid, "PID", 66.0), c(K::User, "Usuário", 90.0)],
    &[c(K::Name, "Nome do Processo", 0.0), c(K::Mem, "Memória", 100.0), c(K::Commit, "Mem. Comprometida", 162.0), c(K::GpuMem, "Memória da GPU", 142.0), c(K::Threads, "Threads", 77.0), c(K::Handles, "Identificadores", 128.0), c(K::Pid, "PID", 70.0), c(K::User, "Usuário", 110.0)],
    &[c(K::Name, "Nome do Processo", 0.0), c(K::Energy, "Impacto Energético", 158.0), c(K::Cpu, "% CPU", 80.0), c(K::Gpu, "% GPU", 80.0), c(K::Nap, "App Nap", 80.0), c(K::Pid, "PID", 70.0), c(K::User, "Usuário", 110.0)],
    &[c(K::Name, "Nome do Processo", 0.0), c(K::Written, "Bytes Gravados", 132.0), c(K::Read, "Bytes Lidos", 110.0), c(K::WrOps, "Gravações", 100.0), c(K::RdOps, "Leituras", 100.0), c(K::Pid, "PID", 70.0), c(K::User, "Usuário", 110.0)],
    &[c(K::Name, "Nome do Processo", 0.0), c(K::Conn, "Conexões", 95.0), c(K::Written, "Bytes Gravados", 132.0), c(K::Read, "Bytes Lidos", 110.0), c(K::Pid, "PID", 70.0), c(K::User, "Usuário", 110.0)],
    &[c(K::Name, "Nome do Processo", 0.0), c(K::Gpu, "% GPU", 80.0), c(K::GpuTime, "Tempo de GPU", 122.0), c(K::GpuMem, "Memória da GPU", 142.0), c(K::Engine, "Motor", 150.0), c(K::Pid, "PID", 70.0), c(K::User, "Usuário", 110.0)],
];
fn text_col(k: K) -> bool {
    matches!(k, K::Name | K::User | K::Kind | K::Engine)
}

// SYSTEM_PROCESS_INFORMATION completo (o do winternl.h esconde os campos); 0x100 bytes no x64, as threads logo depois
#[repr(C)]
struct Spi {
    next: u32,
    threads: u32,
    ws_private: i64,
    hard_faults: u32,
    threads_hw: u32,
    cycle: u64,
    create: i64,
    user: i64,
    kernel: i64,
    name_len: u16,
    name_max: u16,
    name_buf: *const u16,
    base_prio: i32,
    pid: usize,
    ppid: usize,
    handles: u32,
    session: u32,
    key: usize,
    peak_virtual: usize,
    virtual_: usize,
    page_faults: u32,
    peak_ws: usize,
    ws: usize,
    qppp: usize,
    qpp: usize,
    qpnpp: usize,
    qnpp: usize,
    pagefile: usize,
    peak_pagefile: usize,
    private_pages: usize,
    rd_ops: i64,
    wr_ops: i64,
    other_ops: i64,
    rd_bytes: i64,
    wr_bytes: i64,
    other_bytes: i64,
}
type NtQsi = unsafe extern "system" fn(u32, *mut c_void, u32, *mut u32) -> i32;

#[derive(Default, Clone)]
struct Proc {
    pid: u32,
    ppid: u32,
    create: u64,
    exe: String,
    path: String,
    name: String,
    user: String,
    pack: String,
    cpu: u64,
    cpu_prev: u64,
    cpu_pct: f64,
    energy: f64,
    mem: u64,
    threads: u32,
    handles: u32,
    session: u32,
    conns: u32,
    rd: u64,
    wr: u64,
    rd_prev: u64,
    wr_prev: u64,
    rd_ops: u64,
    wr_ops: u64,
    commit: u64,
    ctx: u64,
    ctx_prev: u64,
    ctx_sec: f64,
    kind: String,
    gpu_pct: f64,
    gpu_time: u64,
    gpu_mem: u64,
    engine: String,
    fresh: bool,
    seen: bool,
    sys: bool,
}

#[derive(Clone, Copy)]
struct Pal {
    bg: Cor,
    bar: Cor,
    text: Cor,
    text2: Cor,
    line: Cor,
    stripe: Cor,
    panel: Cor,
    boxc: Cor,
    accent: Cor,
    seg: Cor,
    seg_sel: Cor,
}
#[derive(PartialEq, Clone, Copy)]
enum Sheet {
    None,
    Quit,
    Info,
}

#[derive(Default)]
struct Coleta {
    procs: HashMap<u32, Proc>,
    buf: Vec<u8>,
    ntqsi: Option<NtQsi>,
    last: u64,
    sys_idle: u64,
    sys_kernel: u64,
    sys_user: u64,
    cpu_sys: f64,
    cpu_user: f64,
    cpu_idle: f64,
    threads_total: u32,
    proc_count: u32,
    ms: MEMORYSTATUSEX,
    pi: PERFORMANCE_INFORMATION,
    app_mem: u64,
    compressed: u64,
    rd_ops: u64,
    wr_ops: u64,
    rd_bytes: u64,
    wr_bytes: u64,
    rd_ops_sec: f64,
    wr_ops_sec: f64,
    rd_bytes_sec: f64,
    wr_bytes_sec: f64,
    net_in: u64,
    net_out: u64,
    pkt_in: u64,
    pkt_out: u64,
    net_in_sec: f64,
    net_out_sec: f64,
    pkt_in_sec: f64,
    pkt_out_sec: f64,
    energy_total: f64,
    first: bool,
    press: PressaoMemoria,
    h_cpu_sys: Vec<f32>,
    h_cpu_user: Vec<f32>,
    h_mem: Vec<f32>,
    h_energy: Vec<f32>,
    h_rd: Vec<f32>,
    h_wr: Vec<f32>,
    h_net_in: Vec<f32>,
    h_net_out: Vec<f32>,
    h_gpu: Vec<f32>,
    samples: i32,
    // GPU
    q: isize,
    c_util: isize,
    c_time: isize,
    c_mem: isize,
    c_adapter: isize,
    gpu_name: String,
    gpu_total_mem: u64,
    gpu_used_mem: u64,
    gpu_total: f64,
    engines: BTreeMap<String, f64>,
    win_dir: String,
    bin_dir: String,
    pack_dir: String,
    me: String,
}

struct App {
    hwnd: HWND,
    co: Coleta,
    rt: Option<ID2D1RenderTarget>,
    hrt: Option<ID2D1HwndRenderTarget>,
    tf: HashMap<&'static str, IDWriteTextFormat>,
    family: String,
    dark: bool,
    tahoe: bool,
    active: bool,
    tab: usize,
    seg_from: f32,
    seg_at: u32,
    sort_col: [usize; N_TABS],
    sort_asc: [bool; N_TABS],
    sel: u32,
    scroll: f32,
    search: String,
    search_focus: bool,
    rows: Vec<u32>,
    icons: HashMap<String, Option<ID2D1Bitmap>>,
    hover_btn: i32,
    hover_lights: bool,
    sheet: Sheet,
    sheet_pid: u32,
    sheet_btns: Vec<(RectF, i32)>,
    sheet_msg: String,
    shown: bool,
    foto: Option<String>,
    foto_size: (f32, f32),
}
static A: Global<Option<App>> = Global::new(None);
fn a() -> &'static mut App {
    A.get().as_mut().unwrap()
}
fn co() -> &'static mut Coleta {
    &mut a().co
}
fn leo() -> bool {
    semaforo::leopard()
}

// ---------------------------------------------------------------------------
// coleta
fn push_h(h: &mut Vec<f32>, v: f32) {
    h.remove(0);
    h.push(v);
}
fn file_description(path: &str) -> String {
    unsafe {
        let p = wz(path);
        let n = GetFileVersionInfoSizeW(pc(&p), None);
        if n == 0 {
            return String::new();
        }
        let mut v = vec![0u8; n as usize];
        if GetFileVersionInfoW(pc(&p), 0, n, v.as_mut_ptr() as *mut c_void).is_err() {
            return String::new();
        }
        let mut lc: *mut c_void = std::ptr::null_mut();
        let mut cb = 0u32;
        if !VerQueryValueW(v.as_ptr() as *const c_void, w!("\\VarFileInfo\\Translation"), &mut lc, &mut cb).as_bool() || cb < 4 {
            return String::new();
        }
        let (lang, cp) = (*(lc as *const u16), *(lc as *const u16).add(1));
        let key = wz(&format!("\\StringFileInfo\\{lang:04x}{cp:04x}\\FileDescription"));
        let mut d: *mut c_void = std::ptr::null_mut();
        let mut dl = 0u32;
        if !VerQueryValueW(v.as_ptr() as *const c_void, pc(&key), &mut d, &mut dl).as_bool() || d.is_null() || dl == 0 {
            return String::new();
        }
        let s = std::slice::from_raw_parts(d as *const u16, dl as usize);
        from_w(s).trim_end().to_string()
    }
}
/// App Nap: o processo está no modo eficiência
fn napped(pid: u32) -> bool {
    unsafe {
        let Ok(h) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid) else { return false };
        let mut s = PROCESS_POWER_THROTTLING_STATE { Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, ..Default::default() };
        let r = GetProcessInformation(h, ProcessPowerThrottling, &mut s as *mut _ as *mut c_void, std::mem::size_of_val(&s) as u32).is_ok() && s.StateMask & PROCESS_POWER_THROTTLING_EXECUTION_SPEED != 0;
        let _ = CloseHandle(h);
        r
    }
}
fn identify(p: &mut Proc) {
    let co = co();
    unsafe {
        if let Ok(h) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, p.pid) {
            let mut buf = [0u16; 520];
            let mut n = buf.len() as u32;
            if QueryFullProcessImageNameW(h, PROCESS_NAME_WIN32, PWSTR(buf.as_mut_ptr()), &mut n).is_ok() {
                p.path = from_w(&buf[..n as usize]);
            }
            let (mut pm, mut nm) = (IMAGE_FILE_MACHINE::default(), IMAGE_FILE_MACHINE::default());
            if IsWow64Process2(h, &mut pm, Some(&mut nm)).is_ok() {
                let m = if pm == IMAGE_FILE_MACHINE_UNKNOWN { nm } else { pm };
                p.kind = tr(match m {
                    IMAGE_FILE_MACHINE_AMD64 => "64 bits",
                    IMAGE_FILE_MACHINE_ARM64 => "ARM64",
                    IMAGE_FILE_MACHINE_I386 => "32 bits",
                    _ => "—",
                })
                .into();
            }
            let mut tok = HANDLE::default();
            if OpenProcessToken(h, TOKEN_QUERY, &mut tok).is_ok() {
                let mut sz = 0u32;
                let _ = GetTokenInformation(tok, TokenUser, None, 0, &mut sz);
                let mut tb = vec![0u8; sz as usize];
                if sz > 0 && GetTokenInformation(tok, TokenUser, Some(tb.as_mut_ptr() as *mut c_void), sz, &mut sz).is_ok() {
                    let tu = &*(tb.as_ptr() as *const TOKEN_USER);
                    let (mut nmb, mut dom) = ([0u16; 128], [0u16; 128]);
                    let (mut nn, mut dn) = (128u32, 128u32);
                    let mut usev = SID_NAME_USE::default();
                    if LookupAccountSidW(PCWSTR::null(), tu.User.Sid, PWSTR(nmb.as_mut_ptr()), &mut nn, PWSTR(dom.as_mut_ptr()), &mut dn, &mut usev).is_ok() {
                        p.user = from_w(&nmb[..nn as usize]);
                    }
                }
                let _ = CloseHandle(tok);
            }
            let _ = CloseHandle(h);
        }
    }
    if p.user.is_empty() {
        p.user = if p.session == 0 { "SYSTEM".into() } else { co.me.clone() };
    }
    if p.kind.is_empty() {
        p.kind = tr("64 bits").into(); // protegidos do sistema: sempre nativos
    }
    // apps (fora da pasta do Windows): nome do app; serviços do sistema: o nome do executável, como no Mac
    let mut base = p.exe.clone();
    if base.to_lowercase().ends_with(".exe") {
        base.truncate(base.len() - 4);
    }
    let lp = p.path.to_lowercase();
    p.sys = p.path.is_empty() || lp.starts_with(&co.win_dir);
    p.name = base;
    if !p.sys {
        let d = file_description(&p.path);
        if !d.is_empty() && d.chars().count() < 60 {
            p.name = d;
        }
    }
    if p.pid == 4 {
        p.name = "System".into();
    }
    // os apps deste projeto aparecem com o nome e o ícone do Mac
    if !p.path.is_empty() && lp.starts_with(&co.bin_dir) {
        let ours = [
            ("wacosfinder.exe", "Finder", "Finder.png"),
            ("wacosshell.exe", "Dock", "Launchpad.png"),
            ("wacossettings.exe", "Ajustes do Sistema", "Settings.png"),
            ("wacosactivitymonitor.exe", "Monitor de Atividade", "Activity Monitor.png"),
            ("wacosterminal.exe", "Terminal", "Terminal.png"),
            ("wacoscalculator.exe", "Calculadora", "Calculator.png"),
            ("wacosnotes.exe", "Notas", "Notes.png"),
            ("wacoswindow32host.exe", "Janelas do Mac (32 bits)", "Mission Control.png"),
        ];
        if let Some(m) = ours.iter().find(|m| m.0.eq_ignore_ascii_case(&p.exe)) {
            p.name = tr(m.1);
            p.pack = format!("{}{}", co.pack_dir, m.2);
        }
    }
    if p.name.is_empty() {
        p.name = format!("{}{})", tr("(pid "), p.pid);
    }
}
fn count_connections() {
    let procs = &mut co().procs;
    for p in procs.values_mut() {
        p.conns = 0;
    }
    unsafe {
        for fam in [AF_INET.0 as u32, AF_INET6.0 as u32] {
            let v6 = fam == AF_INET6.0 as u32;
            for udp in [false, true] {
                let mut sz = 0u32;
                if udp {
                    GetExtendedUdpTable(None, &mut sz, FALSE, fam, UDP_TABLE_OWNER_PID, 0);
                } else {
                    GetExtendedTcpTable(None, &mut sz, FALSE, fam, TCP_TABLE_OWNER_PID_ALL, 0);
                }
                let mut b = vec![0u8; sz as usize + 4096];
                sz = b.len() as u32;
                let r = if udp { GetExtendedUdpTable(Some(b.as_mut_ptr() as *mut c_void), &mut sz, FALSE, fam, UDP_TABLE_OWNER_PID, 0) } else { GetExtendedTcpTable(Some(b.as_mut_ptr() as *mut c_void), &mut sz, FALSE, fam, TCP_TABLE_OWNER_PID_ALL, 0) };
                if r != 0 {
                    continue;
                }
                let n = *(b.as_ptr() as *const u32) as usize;
                // as linhas começam depois do contador (alinhadas a 4); o PID é o último campo de cada uma
                let (tam, off_pid) = match (udp, v6) {
                    (false, false) => (std::mem::size_of::<MIB_TCPROW_OWNER_PID>(), 20),
                    (false, true) => (std::mem::size_of::<MIB_TCP6ROW_OWNER_PID>(), 52),
                    (true, false) => (std::mem::size_of::<MIB_UDPROW_OWNER_PID>(), 8),
                    (true, true) => (std::mem::size_of::<MIB_UDP6ROW_OWNER_PID>(), 24),
                };
                for i in 0..n {
                    let at = 4 + i * tam + off_pid;
                    if at + 4 > b.len() {
                        break;
                    }
                    let pid = u32::from_ne_bytes(b[at..at + 4].try_into().unwrap());
                    if let Some(p) = procs.get_mut(&pid) {
                        p.conns += 1;
                    }
                }
            }
        }
    }
}
fn ft(f: &FILETIME) -> u64 {
    ((f.dwHighDateTime as u64) << 32) | f.dwLowDateTime as u64
}

// GPU: os mesmos contadores do Gerenciador de Tarefas
fn engine_name(t: &str) -> String {
    let m = [("VideoDecode", "Vídeo (decodificação)"), ("VideoEncode", "Vídeo (codificação)"), ("VideoProcessing", "Processamento de vídeo"), ("Copy", "Cópia"), ("Compute", "Computação"), ("Security", "Segurança")];
    if t == "3D" {
        return t.into();
    }
    m.iter().find(|(p, _)| t.starts_with(p)).map(|(_, n)| tr(n)).unwrap_or_else(|| t.to_string())
}
fn pid_of(inst: &str) -> u32 {
    inst.find("pid_").map(|i| inst[i + 4..].chars().take_while(|c| c.is_ascii_digit()).collect::<String>().parse().unwrap_or(0)).unwrap_or(0)
}
fn engtype_of(inst: &str) -> String {
    inst.find("engtype_").map(|i| inst[i + 8..].to_string()).unwrap_or_default()
}
fn gpu_init() {
    let co = co();
    unsafe {
        let mut q = 0isize;
        if PdhOpenQueryW(PCWSTR::null(), 0, &mut q) != 0 {
            return;
        }
        co.q = q;
        let _ = PdhAddEnglishCounterW(q, w!("\\GPU Engine(*)\\Utilization Percentage"), 0, &mut co.c_util);
        let _ = PdhAddEnglishCounterW(q, w!("\\GPU Engine(*)\\Running Time"), 0, &mut co.c_time);
        let _ = PdhAddEnglishCounterW(q, w!("\\GPU Process Memory(*)\\Dedicated Usage"), 0, &mut co.c_mem);
        let _ = PdhAddEnglishCounterW(q, w!("\\GPU Adapter Memory(*)\\Dedicated Usage"), 0, &mut co.c_adapter);
        if let Ok(f) = CreateDXGIFactory1::<IDXGIFactory1>() {
            let mut i = 0;
            while let Ok(ad) = f.EnumAdapters1(i) {
                if let Ok(d) = ad.GetDesc1() {
                    if d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 && d.DedicatedVideoMemory as u64 > co.gpu_total_mem {
                        co.gpu_total_mem = d.DedicatedVideoMemory as u64;
                        co.gpu_name = from_w(&d.Description);
                    }
                }
                i += 1;
            }
        }
    }
}
/// (nome da instância, valor): formatado (double) ou cru (FirstValue)
fn pdh_array(c: isize, raw: bool) -> Vec<(String, f64, bool)> {
    unsafe {
        let (mut size, mut count) = (0u32, 0u32);
        let fmt = PDH_FMT(PDH_FMT_DOUBLE.0 | 0x8000) /* NOCAP100 */;
        let st = if raw { PdhGetRawCounterArrayW(c, &mut size, &mut count, None) } else { PdhGetFormattedCounterArrayW(c, fmt, &mut size, &mut count, None) };
        if st != PDH_MORE_DATA as u32 || size == 0 {
            return Vec::new();
        }
        let mut b = vec![0u8; size as usize];
        let st = if raw { PdhGetRawCounterArrayW(c, &mut size, &mut count, Some(b.as_mut_ptr() as *mut PDH_RAW_COUNTER_ITEM_W)) } else { PdhGetFormattedCounterArrayW(c, fmt, &mut size, &mut count, Some(b.as_mut_ptr() as *mut PDH_FMT_COUNTERVALUE_ITEM_W)) };
        if st != 0 {
            return Vec::new();
        }
        (0..count as usize)
            .map(|i| {
                if raw {
                    let it = &*(b.as_ptr() as *const PDH_RAW_COUNTER_ITEM_W).add(i);
                    (it.szName.to_string().unwrap_or_default(), it.RawValue.FirstValue as f64, true)
                } else {
                    let it = &*(b.as_ptr() as *const PDH_FMT_COUNTERVALUE_ITEM_W).add(i);
                    let ok = it.FmtValue.CStatus == PDH_CSTATUS_VALID_DATA || it.FmtValue.CStatus == PDH_CSTATUS_NEW_DATA;
                    (it.szName.to_string().unwrap_or_default(), it.FmtValue.Anonymous.doubleValue, ok)
                }
            })
            .collect()
    }
}
fn gpu_sample() {
    let co = co();
    for p in co.procs.values_mut() {
        p.gpu_pct = 0.0;
        p.gpu_time = 0;
        p.gpu_mem = 0;
        p.engine.clear();
    }
    co.engines.clear();
    co.gpu_total = 0.0;
    co.gpu_used_mem = 0;
    if co.q == 0 || unsafe { PdhCollectQueryData(co.q) } != 0 {
        return;
    }
    let mut per: HashMap<u32, BTreeMap<String, f64>> = HashMap::new();
    for (name, v, ok) in pdh_array(co.c_util, false) {
        let eng = engine_name(&engtype_of(&name));
        if !ok || eng.is_empty() {
            continue;
        }
        *per.entry(pid_of(&name)).or_default().entry(eng.clone()).or_default() += v;
        *co.engines.entry(eng).or_default() += v;
    }
    for (pid, engs) in per {
        if let Some(p) = co.procs.get_mut(&pid) {
            for (e, v) in engs {
                if v > p.gpu_pct {
                    p.gpu_pct = v.min(100.0);
                    p.engine = e;
                }
            }
        }
    }
    for v in co.engines.values_mut() {
        *v = v.min(100.0);
        co.gpu_total = co.gpu_total.max(*v);
    }
    for (name, v, _) in pdh_array(co.c_time, true) {
        if let Some(p) = co.procs.get_mut(&pid_of(&name)) {
            p.gpu_time += v as u64;
        }
    }
    for (name, v, _) in pdh_array(co.c_mem, true) {
        if let Some(p) = co.procs.get_mut(&pid_of(&name)) {
            p.gpu_mem += v as u64;
        }
    }
    for (_, v, _) in pdh_array(co.c_adapter, true) {
        co.gpu_used_mem = co.gpu_used_mem.max(v as u64);
    }
}
fn sample() {
    let co = co();
    unsafe {
        let now = ft(&GetSystemTimeAsFileTime());
        let elapsed = if co.last > 0 { (now - co.last) as f64 } else { 0.0 }; // 100 ns
        co.last = now;
        if co.ntqsi.is_none() {
            let nt = GetModuleHandleW(w!("ntdll.dll")).unwrap_or_default();
            co.ntqsi = GetProcAddress(nt, s!("NtQuerySystemInformation")).map(|f| std::mem::transmute::<_, NtQsi>(f));
        }
        let Some(q) = co.ntqsi else { return };
        if co.buf.is_empty() {
            co.buf = vec![0u8; 1 << 20];
        }
        let mut need = 0u32;
        let mut st;
        loop {
            st = q(5, co.buf.as_mut_ptr() as *mut c_void, co.buf.len() as u32, &mut need);
            if st as u32 != 0xC0000004 {
                break;
            }
            let n = (need as usize + 65536).max(co.buf.len() * 2);
            co.buf.resize(n, 0);
        }
        if st < 0 {
            return;
        }
        for p in co.procs.values_mut() {
            p.seen = false;
        }
        co.threads_total = 0;
        co.proc_count = 0;
        co.app_mem = 0;
        co.compressed = 0;
        let (mut rd_ops, mut wr_ops, mut rd_b, mut wr_b) = (0u64, 0u64, 0u64, 0u64);
        let mut at = 0usize;
        loop {
            let s = &*(co.buf.as_ptr().add(at) as *const Spi);
            let pid = s.pid as u32;
            let exe = if s.name_buf.is_null() { String::new() } else { from_w(std::slice::from_raw_parts(s.name_buf, s.name_len as usize / 2)) };
            if pid != 0 {
                if co.procs.get(&pid).map(|p| p.create != s.create as u64).unwrap_or(false) {
                    co.procs.remove(&pid);
                }
                let novo = !co.procs.contains_key(&pid);
                if novo {
                    let mut p = Proc { pid, create: s.create as u64, exe: exe.clone(), session: s.session, ppid: s.ppid as u32, fresh: true, ..Default::default() };
                    identify(&mut p);
                    co.procs.insert(pid, p);
                }
                let p = co.procs.get_mut(&pid).unwrap();
                p.seen = true;
                let cpu = (s.user + s.kernel) as u64;
                p.cpu_prev = if p.fresh { cpu } else { p.cpu };
                p.cpu = cpu;
                p.cpu_pct = if elapsed > 0.0 && !p.fresh { (p.cpu - p.cpu_prev.min(p.cpu)) as f64 / elapsed * 100.0 } else { 0.0 }; // por núcleo, como no Mac
                p.mem = if s.ws_private != 0 { s.ws_private as u64 } else { s.ws as u64 };
                p.threads = s.threads;
                p.handles = s.handles;
                p.rd_prev = if p.fresh { s.rd_bytes as u64 } else { p.rd };
                p.wr_prev = if p.fresh { s.wr_bytes as u64 } else { p.wr };
                p.rd = s.rd_bytes as u64;
                p.wr = s.wr_bytes as u64;
                p.rd_ops = s.rd_ops as u64;
                p.wr_ops = s.wr_ops as u64;
                p.commit = s.private_pages as u64;
                // as threads vêm logo depois (SYSTEM_THREAD_INFORMATION, 80 bytes; trocas de contexto em +64)
                let th = co.buf.as_ptr().add(at + std::mem::size_of::<Spi>());
                let mut cs = 0u64;
                for k in 0..s.threads as usize {
                    cs += *(th.add(k * 80 + 64) as *const u32) as u64;
                }
                p.ctx_prev = if p.ctx > 0 { p.ctx } else { cs };
                p.ctx = cs;
                p.ctx_sec = if elapsed > 0.0 && cs >= p.ctx_prev { (cs - p.ctx_prev) as f64 / (elapsed / 1e7) } else { 0.0 };
                let io = if elapsed > 0.0 { ((p.rd - p.rd_prev.min(p.rd)) + (p.wr - p.wr_prev.min(p.wr))) as f64 / (elapsed / 1e7) / 1e6 } else { 0.0 };
                p.energy = p.cpu_pct + io * 0.5; // impacto aproximado: CPU + um pouco de disco
                p.fresh = false;
                co.threads_total += s.threads;
                co.proc_count += 1;
                if exe == "MemCompression" || exe == "Memory Compression" {
                    co.compressed = s.ws as u64;
                } else {
                    co.app_mem += p.mem;
                }
                rd_ops += s.rd_ops as u64;
                wr_ops += s.wr_ops as u64;
                rd_b += s.rd_bytes as u64;
                wr_b += s.wr_bytes as u64;
            }
            if s.next == 0 {
                break;
            }
            at += s.next as usize;
        }
        co.procs.retain(|_, p| p.seen);
        count_connections();
        gpu_sample();
        let co = self::co();
        // CPU do sistema
        let (mut fi, mut fk, mut fu) = (FILETIME::default(), FILETIME::default(), FILETIME::default());
        if GetSystemTimes(Some(&mut fi), Some(&mut fk), Some(&mut fu)).is_ok() {
            let (i, k, u) = (ft(&fi), ft(&fk), ft(&fu));
            if co.sys_kernel > 0 {
                let (di, dk, du) = ((i - co.sys_idle) as f64, (k - co.sys_kernel) as f64, (u - co.sys_user) as f64);
                let tot = dk + du;
                if tot > 0.0 {
                    co.cpu_idle = di / tot * 100.0;
                    co.cpu_sys = (dk - di) / tot * 100.0;
                    co.cpu_user = du / tot * 100.0;
                }
            }
            (co.sys_idle, co.sys_kernel, co.sys_user) = (i, k, u);
        }
        co.ms.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
        let _ = GlobalMemoryStatusEx(&mut co.ms);
        co.pi.cb = std::mem::size_of::<PERFORMANCE_INFORMATION>() as u32;
        let _ = GetPerformanceInfo(&mut co.pi, co.pi.cb);
        // disco (soma dos processos)
        let secs = elapsed / 1e7;
        let rate = |a: u64, b: u64| if secs > 0.0 && a >= b { (a - b) as f64 / secs } else { 0.0 };
        let first = co.first;
        let prev = |v: u64, old: u64| if first { v } else { old };
        co.rd_ops_sec = rate(rd_ops, prev(rd_ops, co.rd_ops));
        co.wr_ops_sec = rate(wr_ops, prev(wr_ops, co.wr_ops));
        co.rd_bytes_sec = rate(rd_b, prev(rd_b, co.rd_bytes));
        co.wr_bytes_sec = rate(wr_b, prev(wr_b, co.wr_bytes));
        (co.rd_ops, co.wr_ops, co.rd_bytes, co.wr_bytes) = (rd_ops, wr_ops, rd_b, wr_b);
        // rede (placas físicas que estão ligadas)
        let (mut ni, mut no, mut pi_, mut po) = (0u64, 0u64, 0u64, 0u64);
        let mut t: *mut MIB_IF_TABLE2 = std::ptr::null_mut();
        if GetIfTable2(&mut t).is_ok() && !t.is_null() {
            let tb = &*t;
            let rows = std::slice::from_raw_parts(tb.Table.as_ptr(), tb.NumEntries as usize);
            for r in rows {
                let hw = r.InterfaceAndOperStatusFlags._bitfield & 1 != 0;
                if r.Type == IF_TYPE_SOFTWARE_LOOPBACK || r.OperStatus != IfOperStatusUp || !hw {
                    continue;
                }
                ni += r.InOctets;
                no += r.OutOctets;
                pi_ += r.InUcastPkts + r.InNUcastPkts;
                po += r.OutUcastPkts + r.OutNUcastPkts;
            }
            FreeMibTable(t as *const c_void);
        }
        co.net_in_sec = rate(ni, prev(ni, co.net_in));
        co.net_out_sec = rate(no, prev(no, co.net_out));
        co.pkt_in_sec = rate(pi_, prev(pi_, co.pkt_in));
        co.pkt_out_sec = rate(po, prev(po, co.pkt_out));
        (co.net_in, co.net_out, co.pkt_in, co.pkt_out) = (ni, no, pi_, po);
        co.energy_total = co.procs.values().map(|p| p.energy).sum();
        // gráficos
        push_h(&mut co.h_cpu_sys, (co.cpu_sys / 100.0) as f32);
        push_h(&mut co.h_cpu_user, (co.cpu_user / 100.0) as f32);
        co.press = pressao::medir();
        push_h(&mut co.h_mem, co.press.valor);
        push_h(&mut co.h_energy, (co.energy_total / 400.0).min(1.0) as f32);
        let lg = |v: f64, full: f64| ((1.0 + v).log10() / (1.0 + full).log10()).min(1.0) as f32;
        push_h(&mut co.h_rd, lg(co.rd_ops_sec, 5000.0));
        push_h(&mut co.h_wr, lg(co.wr_ops_sec, 5000.0));
        push_h(&mut co.h_net_in, lg(co.pkt_in_sec, 20000.0));
        push_h(&mut co.h_net_out, lg(co.pkt_out_sec, 20000.0));
        push_h(&mut co.h_gpu, (co.gpu_total / 100.0) as f32);
        for p in co.procs.values_mut() {
            p.energy += p.gpu_pct * 0.5; // a GPU também gasta energia
        }
        co.first = false;
        co.samples += 1;
    }
}

// ---------------------------------------------------------------------------
// textos (unidades decimais como no Mac)
/// separadores do idioma do WacOS, pelo Windows (PR #271): "1,234.5" em inglês, chinês, japonês e coreano, "1.234,5"
/// em português, espanhol, alemão, italiano e turco, "1 234,5" em francês, russo e polonês. Antes eram sempre os do
/// português, em qualquer idioma.
fn separador(decimal: bool) -> &'static str {
    use comum::windows::Win32::Globalization::{LOCALE_SDECIMAL, LOCALE_STHOUSAND};
    static SEP: std::sync::OnceLock<(String, String)> = std::sync::OnceLock::new();
    let (dec, mil) = SEP.get_or_init(|| {
        let virgula = comum::idioma::decimal_comma();
        let dec = comum::idioma::locale_info(LOCALE_SDECIMAL);
        let mil = comum::idioma::locale_info(LOCALE_STHOUSAND);
        (
            if dec.is_empty() { (if virgula { "," } else { "." }).to_string() } else { dec },
            if mil.is_empty() { (if virgula { "." } else { "," }).to_string() } else { mil },
        )
    });
    if decimal { dec } else { mil }
}
fn thousands(v: u64) -> String {
    let s = v.to_string();
    let n = s.len();
    let mil = separador(false);
    s.chars().enumerate().fold(String::new(), |mut o, (i, ch)| {
        o.push(ch);
        if (n - 1 - i) % 3 == 0 && i + 1 < n {
            o.push_str(mil);
        }
        o
    })
}
fn comma(s: String) -> String {
    s.replace('.', separador(true))
}
fn bytes(b: f64) -> String {
    comma(if b < 1000.0 {
        cf!(tr("%.0f bytes"), b)
    } else if b < 1e6 {
        format!("{:.0} KB", b / 1e3)
    } else if b < 1e9 {
        format!("{:.1} MB", b / 1e6)
    } else if b < 1e12 {
        format!("{:.2} GB", b / 1e9)
    } else {
        format!("{:.2} TB", b / 1e12)
    })
}
fn pct(v: f64) -> String {
    comma(format!("{v:.1}"))
}
fn cpu_time(t: u64) -> String {
    let cs = t / 100000;
    let s = cs / 100;
    let (h, m, s, cs) = (s / 3600, (s / 60) % 60, s % 60, cs % 100);
    comma(if h > 0 { format!("{h}:{m:02}:{s:02}.{cs:02}") } else { format!("{m}:{s:02}.{cs:02}") }) // os centésimos com o separador do idioma
}

// ---------------------------------------------------------------------------
// janela
fn scale() -> f32 {
    if a().foto.is_some() {
        2.0
    } else {
        unsafe { GetDpiForWindow(a().hwnd) as f32 / 96.0 }
    }
}
fn client() -> (f32, f32) {
    if a().foto.is_some() {
        return a().foto_size;
    }
    let mut r = RECT::default();
    unsafe {
        let _ = GetClientRect(a().hwnd, &mut r);
    }
    let s = scale();
    (r.right as f32 / s, r.bottom as f32 / s)
}
fn read_tahoe() -> bool {
    app2d::read_lines(&data_path("ajustes.txt")).iter().rev().find_map(|l| match l.trim() {
        "liquid_glass=1" => Some(true),
        "liquid_glass=0" => Some(false),
        _ => None,
    }) == Some(true)
}
fn colors() -> Pal {
    let cc = |r, g, b, a| col(r, g, b, a);
    let mut p = if leo() {
        Pal { bg: cc(1.0, 1.0, 1.0, 1.0), bar: cc(0.8, 0.8, 0.8, 1.0), text: cc(0.0, 0.0, 0.0, 0.9), text2: cc(0.0, 0.0, 0.0, 0.55), line: cc(0.0, 0.0, 0.0, 0.15), stripe: rgb(243, 246, 250, 1.0), panel: cc(0.89, 0.89, 0.89, 1.0), boxc: cc(1.0, 1.0, 1.0, 1.0), accent: rgb(56, 117, 215, 1.0), seg: cc(1.0, 1.0, 1.0, 1.0), seg_sel: cc(0.55, 0.55, 0.56, 1.0) }
    } else if a().tahoe {
        if a().dark {
            let b = cc(0.110, 0.110, 0.118, 1.0);
            Pal { bg: b, bar: b, text: cc(1.0, 1.0, 1.0, 0.9), text2: cc(1.0, 1.0, 1.0, 0.5), line: cc(1.0, 1.0, 1.0, 0.1), stripe: cc(1.0, 1.0, 1.0, 0.045), panel: b, boxc: cc(1.0, 1.0, 1.0, 0.035), accent: cc(0.04, 0.42, 0.92, 1.0), seg: cc(0.2, 0.2, 0.21, 1.0), seg_sel: cc(1.0, 1.0, 1.0, 0.14) }
        } else {
            let w_ = cc(1.0, 1.0, 1.0, 1.0);
            Pal { bg: w_, bar: w_, text: cc(0.0, 0.0, 0.0, 0.85), text2: cc(0.0, 0.0, 0.0, 0.5), line: cc(0.0, 0.0, 0.0, 0.08), stripe: cc(0.0, 0.0, 0.0, 0.035), panel: w_, boxc: w_, accent: cc(0.0, 0.39, 0.88, 1.0), seg: w_, seg_sel: cc(0.0, 0.0, 0.0, 0.075) }
        }
    } else if a().dark {
        let b = cc(0.118, 0.118, 0.122, 1.0);
        Pal { bg: b, bar: b, text: cc(1.0, 1.0, 1.0, 0.9), text2: cc(1.0, 1.0, 1.0, 0.5), line: cc(1.0, 1.0, 1.0, 0.12), stripe: cc(1.0, 1.0, 1.0, 0.055), panel: b, boxc: b, accent: cc(0.04, 0.42, 0.92, 1.0), seg: cc(1.0, 1.0, 1.0, 0.055), seg_sel: cc(1.0, 1.0, 1.0, 0.16) }
    } else {
        Pal { bg: cc(1.0, 1.0, 1.0, 1.0), bar: cc(0.969, 0.969, 0.969, 1.0), text: cc(0.0, 0.0, 0.0, 0.85), text2: cc(0.0, 0.0, 0.0, 0.5), line: cc(0.0, 0.0, 0.0, 0.1), stripe: cc(0.957, 0.961, 0.961, 1.0), panel: cc(0.925, 0.925, 0.925, 1.0), boxc: cc(1.0, 1.0, 1.0, 1.0), accent: cc(0.0, 0.39, 0.88, 1.0), seg: cc(1.0, 1.0, 1.0, 1.0), seg_sel: cc(0.86, 0.86, 0.86, 1.0) }
    };
    if a().tahoe && !leo() {
        // o fundo da janela leva 10 % da cor do papel de parede
        p.bg = app2d::tinted(p.bg);
        p.bar = app2d::tinted(p.bar);
        p.panel = app2d::tinted(p.panel);
    }
    p
}
fn mk_fmt(size: f32, wt: DWRITE_FONT_WEIGHT, al: DWRITE_TEXT_ALIGNMENT) -> IDWriteTextFormat {
    let f = cjk::format(dw(), &a().family, wt, DWRITE_FONT_STYLE_NORMAL, size, "pt-br").expect("fonte");
    unsafe {
        let _ = f.SetTextAlignment(al);
        let _ = f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
        let _ = f.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
        if let Ok(e) = dw().CreateEllipsisTrimmingSign(&f) {
            let t = DWRITE_TRIMMING { granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER, delimiter: 0, delimiterCount: 0 };
            let _ = f.SetTrimming(&t, &e);
        }
    }
    f
}
fn tf(k: &str) -> IDWriteTextFormat {
    a().tf[k].clone()
}
fn text(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, s: &str, f: &IDWriteTextFormat, r: RectF, c: Cor) {
    if s.is_empty() {
        return;
    }
    unsafe {
        br.SetColor(&c);
        rt.DrawText(&w(s), f, &r, br, D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
    }
}
fn text_w(f: &IDWriteTextFormat, s: &str) -> f32 {
    unsafe {
        let Ok(l) = dw().CreateTextLayout(&w(s), f, 4000.0, 100.0) else { return 0.0 };
        let mut m = DWRITE_TEXT_METRICS::default();
        let _ = l.GetMetrics(&mut m);
        m.widthIncludingTrailingWhitespace
    }
}
fn inr(r: &RectF, p: Ponto) -> bool {
    p.x >= r.left && p.x < r.right && p.y >= r.top && p.y < r.bottom
}
fn ln(rt: &ID2D1RenderTarget, b: &ID2D1SolidColorBrush, x1: f32, y1: f32, x2: f32, y2: f32, wd: f32) {
    unsafe { rt.DrawLine(pt(x1, y1), pt(x2, y2), b, wd, None) }
}

// ---- ícones dos apps (só fora da pasta do Windows, como no Mac: serviços ficam sem ícone)
fn wic() -> Option<IWICImagingFactory> {
    unsafe { CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).ok() }
}
fn png_bitmap(rt: &ID2D1RenderTarget, file: &str) -> Option<ID2D1Bitmap> {
    if let Some(b) = a().icons.get(file) {
        return b.clone();
    }
    let b = (|| unsafe {
        let wic = wic()?;
        let p = wz(file);
        let dec = wic.CreateDecoderFromFilename(pc(&p), None, GENERIC_READ, WICDecodeMetadataCacheOnDemand).ok()?;
        let fr = dec.GetFrame(0).ok()?;
        let scl = wic.CreateBitmapScaler().ok()?;
        scl.Initialize(&fr, 64, 64, WICBitmapInterpolationModeFant).ok()?;
        let cv = wic.CreateFormatConverter().ok()?;
        cv.Initialize(&scl, &GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).ok()?;
        rt.CreateBitmapFromWicBitmap(&cv, None).ok()
    })();
    a().icons.insert(file.to_string(), b.clone());
    b
}
fn icon_for(rt: &ID2D1RenderTarget, p: &Proc) -> Option<ID2D1Bitmap> {
    if !p.pack.is_empty() {
        if let Some(b) = png_bitmap(rt, &p.pack) {
            return Some(b);
        }
    }
    if p.sys || p.path.is_empty() {
        return None;
    }
    if let Some(b) = a().icons.get(&p.path) {
        return b.clone();
    }
    let big = scale() > 1.25;
    let b = (|| unsafe {
        let mut sfi = SHFILEINFOW::default();
        let pp = wz(&p.path);
        let fl = SHGFI_ICON | if big { SHGFI_LARGEICON } else { SHGFI_SMALLICON };
        if SHGetFileInfoW(pc(&pp), FILE_FLAGS_AND_ATTRIBUTES(0), Some(&mut sfi), std::mem::size_of::<SHFILEINFOW>() as u32, fl) == 0 || sfi.hIcon.is_invalid() {
            return None;
        }
        let r = (|| {
            let wic = wic()?;
            let wb = wic.CreateBitmapFromHICON(sfi.hIcon).ok()?;
            let cv = wic.CreateFormatConverter().ok()?;
            cv.Initialize(&wb, &GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).ok()?;
            rt.CreateBitmapFromWicBitmap(&cv, None).ok()
        })();
        let _ = DestroyIcon(sfi.hIcon);
        r
    })();
    a().icons.insert(p.path.clone(), b.clone());
    b
}

// ---- linhas visíveis (busca + ordem)
fn num_key(p: &Proc, k: K) -> f64 {
    match k {
        K::Cpu => p.cpu_pct,
        K::CpuTime => p.cpu as f64,
        K::Threads => p.threads as f64,
        K::Handles => p.handles as f64,
        K::Mem => p.mem as f64,
        K::Energy => p.energy,
        K::Written => p.wr as f64,
        K::Read => p.rd as f64,
        K::Conn => p.conns as f64,
        K::Pid => p.pid as f64,
        K::Nap => napped(p.pid) as i32 as f64,
        K::Ctx => p.ctx_sec,
        K::Gpu => p.gpu_pct,
        K::GpuTime => p.gpu_time as f64,
        K::Commit => p.commit as f64,
        K::GpuMem => p.gpu_mem as f64,
        K::RdOps => p.rd_ops as f64,
        K::WrOps => p.wr_ops as f64,
        _ => 0.0,
    }
}
fn build_rows() {
    let q = a().search.to_lowercase();
    let procs = &co().procs;
    let mut rows: Vec<&Proc> = procs.values().filter(|p| q.is_empty() || p.name.to_lowercase().contains(&q) || p.exe.to_lowercase().contains(&q) || p.pid.to_string().contains(&q)).collect();
    let tab = a().tab;
    let key = COLS[tab][a().sort_col[tab]].key;
    let asc = a().sort_asc[tab];
    rows.sort_by(|x, y| {
        use std::cmp::Ordering::*;
        if text_col(key) {
            let t = |p: &Proc| match key {
                K::Name => p.name.to_lowercase(),
                K::User => p.user.to_lowercase(),
                K::Kind => p.kind.to_lowercase(),
                _ => p.engine.to_lowercase(),
            };
            let o = t(x).cmp(&t(y));
            let o = if asc { o } else { o.reverse() };
            return if o == Equal { x.pid.cmp(&y.pid) } else { o };
        }
        let (a_, b_) = (num_key(x, key), num_key(y, key));
        if a_ != b_ {
            let o = a_.partial_cmp(&b_).unwrap_or(Equal);
            return if asc { o } else { o.reverse() };
        }
        x.name.to_lowercase().cmp(&y.name.to_lowercase())
    });
    a().rows = rows.iter().map(|p| p.pid).collect();
}
fn cell(p: &Proc, k: K) -> String {
    match k {
        K::Name => p.name.clone(),
        K::Cpu => pct(p.cpu_pct),
        K::CpuTime => cpu_time(p.cpu),
        K::Threads => thousands(p.threads as u64),
        K::Handles => thousands(p.handles as u64),
        K::Mem => bytes(p.mem as f64),
        K::Energy => pct(p.energy),
        K::Written => bytes(p.wr as f64),
        K::Read => bytes(p.rd as f64),
        K::Conn => thousands(p.conns as u64),
        K::Pid => p.pid.to_string(),
        K::Nap => tr(if napped(p.pid) { "Sim" } else { "Não" }),
        K::User => p.user.clone(),
        K::Ctx => thousands(p.ctx_sec.round() as u64),
        K::Kind => p.kind.clone(),
        K::Gpu => pct(p.gpu_pct),
        K::GpuTime => cpu_time(p.gpu_time),
        K::Commit => bytes(p.commit as f64),
        K::GpuMem => bytes(p.gpu_mem as f64),
        K::RdOps => thousands(p.rd_ops),
        K::WrOps => thousands(p.wr_ops),
        K::Engine => {
            if p.gpu_pct >= 0.05 {
                p.engine.clone()
            } else {
                String::new()
            }
        }
    }
}
fn selected() -> Option<&'static Proc> {
    co().procs.get(&a().sel)
}

// ---- geometria
fn list_top() -> f32 {
    TOOLBAR_H + HEADER_H
}
fn list_bottom() -> f32 {
    client().1 - PANEL_H
}
fn max_scroll() -> f32 {
    (a().rows.len() as f32 * ROW_H + 8.0 - (list_bottom() - list_top())).max(0.0)
}
fn name_w() -> f32 {
    let others: f32 = COLS[a().tab].iter().map(|c| c.w).sum();
    (client().0 - 26.0 - others).clamp(180.0, 440.0)
}
fn col_spans() -> Vec<(f32, f32)> {
    let mut x = 10.0;
    COLS[a().tab]
        .iter()
        .map(|c| {
            let wd = if c.key == K::Name { name_w() } else { c.w };
            x += wd;
            (x - wd, x)
        })
        .collect()
}
const PILL_A: RectF = RectF { left: 282.0, top: PILL_TOP, right: 350.0, bottom: PILL_TOP + PILL_H };
const PILL_B: RectF = RectF { left: 362.0, top: PILL_TOP, right: 406.0, bottom: PILL_TOP + PILL_H };
fn btn_rect(k: i32) -> RectF {
    if leo() {
        return match k {
            0 => rf(12.0, 26.0, 44.0, 48.0),
            1 => rf(50.0, 26.0, 82.0, 48.0),
            _ => rf(88.0, 26.0, 128.0, 48.0),
        };
    }
    match k {
        0 => rf(PILL_A.left, PILL_A.top, 317.0, PILL_A.bottom),
        1 => rf(317.0, PILL_A.top, PILL_A.right, PILL_A.bottom),
        _ => PILL_B,
    }
}
fn seg_rect(i: usize) -> RectF {
    if leo() {
        let wd = 62.0;
        let x0 = (client().0 / 2.0 - wd * N_TABS as f32 / 2.0).round();
        return rf(x0 + i as f32 * wd, 27.0, x0 + (i + 1) as f32 * wd, 47.0);
    }
    rf(SEG_X + i as f32 * SEG_W, PILL_TOP, SEG_X + (i + 1) as f32 * SEG_W, PILL_TOP + PILL_H)
}
fn search_rect() -> RectF {
    let cw = client().0;
    if leo() {
        return rf(cw - 142.0, 27.0, cw - 12.0, 47.0);
    }
    let r = cw - 8.0;
    rf((SEG_X + SEG_W * N_TABS as f32 + 10.0).max(r - SEARCH_W), PILL_TOP, r, PILL_TOP + PILL_H)
}
fn light_center(k: i32) -> Ponto {
    if leo() {
        pt(14.5 + k as f32 * 21.0, 11.0)
    } else {
        pt(26.0 + k as f32 * 23.0, 25.0)
    }
}
fn seg_pos() -> f32 {
    if a().seg_from < 0.0 {
        return a().tab as f32;
    }
    let s = unsafe { GetTickCount().wrapping_sub(a().seg_at) } as f32 / 1000.0;
    let (w0, z) = (2.0 * std::f32::consts::PI / 0.44, 0.74f32);
    let wd = w0 * (1.0 - z * z).sqrt();
    let e = 1.0 - (-z * w0 * s).exp() * ((wd * s).cos() + z * w0 / wd * (wd * s).sin());
    if s >= 0.6 {
        a().seg_from = -1.0;
        return a().tab as f32;
    }
    a().seg_from + (a().tab as f32 - a().seg_from) * e
}

// ---- desenho
unsafe fn draw_lights(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush) {
    let fill = semaforo::pick([col(1.0, 0.373, 0.345, 1.0), col(0.996, 0.737, 0.180, 1.0), col(0.157, 0.784, 0.251, 1.0)], semaforo::Kind::Fill);
    let ring = semaforo::pick([col(0.886, 0.275, 0.247, 1.0), col(0.882, 0.631, 0.086, 1.0), col(0.071, 0.675, 0.157, 1.0)], semaforo::Kind::Ring);
    let glyph = semaforo::pick([col(0.302, 0.0, 0.0, 1.0), col(0.6, 0.341, 0.0, 1.0), col(0.0, 0.396, 0.0, 1.0)], semaforo::Kind::Glyph);
    let lit = a().active || a().hover_lights;
    let dark = a().dark;
    for k in 0..3 {
        let c = light_center(k);
        br.SetColor(&if lit {
            fill[k as usize]
        } else if dark {
            col(0.3, 0.3, 0.31, 1.0)
        } else {
            col(0.84, 0.84, 0.84, 1.0)
        });
        rt.FillEllipse(&ell(c, 7.0, 7.0), br);
        semaforo::gloss(rt, c, 7.0, br);
        br.SetColor(&if lit {
            ring[k as usize]
        } else if dark {
            col(0.0, 0.0, 0.0, 0.3)
        } else {
            col(0.73, 0.73, 0.74, 1.0)
        });
        rt.DrawEllipse(&ell(c, 6.75, 6.75), br, 0.5, None);
        if !a().hover_lights {
            continue;
        }
        br.SetColor(&glyph[k as usize]);
        match k {
            0 => {
                ln(rt, br, c.x - 2.5, c.y - 2.5, c.x + 2.5, c.y + 2.5, 1.1);
                ln(rt, br, c.x - 2.5, c.y + 2.5, c.x + 2.5, c.y - 2.5, 1.1);
            }
            1 => ln(rt, br, c.x - 3.3, c.y, c.x + 3.3, c.y, 1.2),
            _ => {
                ln(rt, br, c.x - 3.0, c.y, c.x + 3.0, c.y, 1.2);
                ln(rt, br, c.x, c.y - 3.0, c.x, c.y + 3.0, 1.2);
            }
        }
    }
}
unsafe fn grad(rt: &ID2D1RenderTarget, r: RectF, rad: f32, st: &[(f32, Cor)]) {
    if let Some(lb) = linear(rt, st, pt(0.0, r.top), pt(0.0, r.bottom)) {
        rt.FillRoundedRectangle(&rr(r, rad, rad), &lb);
    }
}
unsafe fn draw_toolbar_leopard(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) {
    let (cw, _) = client();
    leopard::metal(rt, rf(0.0, 0.0, cw, TOOLBAR_H), a().active, false, true, 0.0);
    draw_lights(rt, br);
    let lu = |sz: f32| {
        let f = cjk::format(dw(), "Lucida Sans Unicode", DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, sz, "pt-br").unwrap();
        let _ = f.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
        let _ = f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
        f
    };
    let title = format!("{} ({})", tr("Monitor de Atividade"), tr("Todos os Processos"));
    text(rt, br, &title, &lu(13.0), rf(80.0, 0.0, cw - 80.0, 22.0), col(0.0, 0.0, 0.0, if a().active { 0.85 } else { 0.45 }));
    let bezel = |r: RectF| {
        br.SetColor(&col(1.0, 1.0, 1.0, 0.45));
        rt.FillRoundedRectangle(&rr(rf(r.left, r.top + 1.0, r.right, r.bottom + 1.0), 4.0, 4.0), br);
        grad(rt, r, 4.0, &[(0.0, col(0.99, 0.99, 0.99, 1.0)), (1.0, col(0.84, 0.84, 0.84, 1.0))]);
        br.SetColor(&col(0.0, 0.0, 0.0, 0.42));
        rt.DrawRoundedRectangle(&rr(inflate(r, -0.5), 3.5, 3.5), br, 1.0, None);
    };
    let sel = selected().is_some();
    for k in 0..3 {
        let r = btn_rect(k);
        bezel(r);
        let en = k == 2 || sel;
        br.SetColor(&col(0.1, 0.1, 0.1, if en { 0.85 } else { 0.30 }));
        let (cx, cy) = (if k == 2 { r.left + 15.0 } else { (r.left + r.right) / 2.0 }, (r.top + r.bottom) / 2.0);
        if k < 2 {
            rt.FillEllipse(&ell(pt(cx, cy), 7.0, 7.0), br);
            br.SetColor(&col(0.95, 0.95, 0.95, 1.0));
            if k == 0 {
                ln(rt, br, cx - 3.0, cy - 3.0, cx + 3.0, cy + 3.0, 1.6);
                ln(rt, br, cx - 3.0, cy + 3.0, cx + 3.0, cy - 3.0, 1.6);
            } else {
                rt.FillEllipse(&ell(pt(cx, cy - 3.3), 1.1, 1.1), br);
                ln(rt, br, cx, cy - 0.8, cx, cy + 3.8, 1.7);
            }
        } else {
            for i in 0..8 {
                let an = i as f32 * std::f32::consts::PI / 4.0;
                ln(rt, br, cx + an.cos() * 4.8, cy + an.sin() * 4.8, cx + an.cos() * 7.2, cy + an.sin() * 7.2, 2.2);
            }
            rt.FillEllipse(&ell(pt(cx, cy), 5.0, 5.0), br);
            br.SetColor(&col(0.9, 0.9, 0.9, 1.0));
            rt.FillEllipse(&ell(pt(cx, cy), 1.8, 1.8), br);
            br.SetColor(&col(0.1, 0.1, 0.1, 0.85));
            let ax = r.right - 10.0;
            ln(rt, br, ax - 3.0, cy - 1.5, ax, cy + 1.5, 1.6);
            ln(rt, br, ax, cy + 1.5, ax + 3.0, cy - 1.5, 1.6);
        }
    }
    let all = rf(seg_rect(0).left, seg_rect(0).top, seg_rect(N_TABS - 1).right, seg_rect(0).bottom);
    bezel(all);
    let r = seg_rect(a().tab);
    grad(rt, inflate(r, -0.5), if a().tab == 0 || a().tab == N_TABS - 1 { 3.0 } else { 0.0 }, &[(0.0, col(0.52, 0.52, 0.53, 1.0)), (1.0, col(0.68, 0.68, 0.69, 1.0))]);
    let ts = lu(12.0);
    for i in 0..N_TABS {
        let r = seg_rect(i);
        if i + 1 < N_TABS {
            br.SetColor(&col(0.0, 0.0, 0.0, 0.3));
            ln(rt, br, r.right.floor() + 0.5, r.top + 1.0, r.right.floor() + 0.5, r.bottom - 1.0, 1.0);
        }
        text(rt, br, &tr(TAB_NAMES[i]), &ts, r, if i == a().tab { col(1.0, 1.0, 1.0, 1.0) } else { col(0.0, 0.0, 0.0, 0.88) });
    }
    let sr = search_rect();
    let rad = (sr.bottom - sr.top) / 2.0;
    br.SetColor(&col(1.0, 1.0, 1.0, 1.0));
    rt.FillRoundedRectangle(&rr(sr, rad, rad), br);
    br.SetColor(&col(0.0, 0.0, 0.0, 0.12));
    rt.FillRectangle(&rf(sr.left + rad, sr.top + 1.0, sr.right - rad, sr.top + 3.0), br);
    let foco = a().search_focus;
    br.SetColor(&if foco { col(0.36, 0.6, 0.95, 0.9) } else { col(0.0, 0.0, 0.0, 0.45) });
    rt.DrawRoundedRectangle(&rr(inflate(sr, -0.5), rad - 0.5, rad - 0.5), br, if foco { 2.0 } else { 1.0 }, None);
    br.SetColor(&col(0.0, 0.0, 0.0, 0.6));
    let (mx, my) = (sr.left + 12.0, (sr.top + sr.bottom) / 2.0 - 1.0);
    rt.DrawEllipse(&ell(pt(mx, my), 4.0, 4.0), br, 1.4, None);
    ln(rt, br, mx + 2.8, my + 2.8, mx + 5.5, my + 5.5, 1.6);
    let caret = if foco && GetTickCount() / 530 % 2 == 0 { "|" } else { "" };
    text(rt, br, &format!("{}{caret}", a().search), &tf("13"), rf(sr.left + 24.0, sr.top, sr.right - 10.0, sr.bottom), pal.text);
}
unsafe fn pill(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal, r: RectF) {
    let dark = a().dark;
    let rad = (r.bottom - r.top) / 2.0;
    if a().tahoe {
        for k in (1..=4).rev() {
            br.SetColor(&col(0.0, 0.0, 0.0, if dark { 0.10 } else { 0.035 } / k as f32));
            let g = k as f32 * 1.4;
            rt.FillRoundedRectangle(&rr(rf(r.left - g, r.top - g + 1.5, r.right + g, r.bottom + g + 1.5), rad + g, rad + g), br);
        }
        br.SetColor(&pal.seg);
        rt.FillRoundedRectangle(&rr(r, rad, rad), br);
        br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.08) } else { col(0.0, 0.0, 0.0, 0.06) });
        rt.DrawRoundedRectangle(&rr(inflate(r, -0.5), rad - 0.5, rad - 0.5), br, 1.0, None);
        return;
    }
    br.SetColor(&pal.seg);
    rt.FillRoundedRectangle(&rr(r, PILL_H / 2.0, PILL_H / 2.0), br);
    br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.09) } else { col(0.0, 0.0, 0.0, 0.10) });
    rt.DrawRoundedRectangle(&rr(inflate(r, -0.5), PILL_H / 2.0 - 0.5, PILL_H / 2.0 - 0.5), br, 1.0, None);
}
unsafe fn draw_toolbar(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) {
    if leo() {
        draw_toolbar_leopard(rt, br, pal);
        return;
    }
    let (cw, _) = client();
    let (dark, tahoe) = (a().dark, a().tahoe);
    br.SetColor(&pal.bar);
    rt.FillRectangle(&rf(0.0, 0.0, cw, TOOLBAR_H), br);
    if !dark && !tahoe {
        br.SetColor(&col(0.0, 0.0, 0.0, 0.10));
        ln(rt, br, 0.0, TOOLBAR_H - 0.5, cw, TOOLBAR_H - 0.5, 1.0);
    }
    draw_lights(rt, br);
    text(rt, br, &tr("Monitor de Atividade"), &tf("14b"), rf(108.0, 8.0, PILL_A.left - 6.0, 28.0), pal.text);
    text(rt, br, &tr("Todos os Processos"), &tf("12"), rf(108.0, 26.0, PILL_A.left - 6.0, 42.0), pal.text2);
    pill(rt, br, pal, PILL_A);
    pill(rt, br, pal, PILL_B);
    let sel = selected().is_some();
    let bx = [300.0f32, 334.0, 377.0];
    for k in 0..3 {
        let r = btn_rect(k);
        let en = k == 2 || sel;
        let cx = bx[k as usize];
        if en && a().hover_btn == k {
            br.SetColor(&pal.line);
            let (hw, dx) = if k == 2 { (21.0, 8.0) } else { (15.0, 0.0) };
            rt.FillRoundedRectangle(&rr(rf(cx - hw + dx, r.top + 3.0, cx + hw + dx, r.bottom - 3.0), 14.5, 14.5), br);
        }
        br.SetColor(&match (en, dark) {
            (true, true) => col(1.0, 1.0, 1.0, 0.85),
            (true, false) => col(0.0, 0.0, 0.0, 0.70),
            (false, true) => col(1.0, 1.0, 1.0, 0.32),
            (false, false) => col(0.0, 0.0, 0.0, 0.25),
        });
        let cy = (r.top + r.bottom) / 2.0;
        rt.DrawEllipse(&ell(pt(cx, cy), 8.5, 8.5), br, 1.4, None);
        match k {
            0 => {
                ln(rt, br, cx - 3.2, cy - 3.2, cx + 3.2, cy + 3.2, 1.4);
                ln(rt, br, cx - 3.2, cy + 3.2, cx + 3.2, cy - 3.2, 1.4);
            }
            1 => {
                rt.FillEllipse(&ell(pt(cx, cy - 3.8), 1.15, 1.15), br);
                ln(rt, br, cx, cy - 0.8, cx, cy + 4.2, 1.6);
            }
            _ => {
                for i in -1..=1 {
                    rt.FillEllipse(&ell(pt(cx + i as f32 * 4.2, cy), 1.3, 1.3), br);
                }
                let ax = 394.0;
                ln(rt, br, ax - 3.2, cy - 1.6, ax, cy + 1.6, 1.4);
                ln(rt, br, ax, cy + 1.6, ax + 3.2, cy - 1.6, 1.4);
            }
        }
    }
    // abas: uma pílula larga; a escolhida é uma pílula clara por dentro (no Tahoe, a gota que desliza)
    let all = rf(seg_rect(0).left, seg_rect(0).top, seg_rect(N_TABS - 1).right, seg_rect(0).bottom);
    pill(rt, br, pal, all);
    let inner = (PILL_H - 8.0) / 2.0;
    for i in 0..N_TABS {
        let r = seg_rect(i);
        if i == a().tab && !tahoe {
            br.SetColor(&pal.seg_sel);
            rt.FillRoundedRectangle(&rr(inflate(r, -4.0), inner, inner), br);
        } else if i == 0 && tahoe {
            let pos = seg_pos();
            let wd = r.right - r.left;
            let l = r.left + pos * wd;
            let g = rf(l + 4.0, r.top + 4.0, l + wd - 4.0, r.bottom - 4.0);
            br.SetColor(&pal.seg_sel);
            rt.FillRoundedRectangle(&rr(g, inner, inner), br);
            br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.18) } else { col(1.0, 1.0, 1.0, 0.8) });
            rt.DrawRoundedRectangle(&rr(inflate(g, -0.5), inner - 0.5, inner - 0.5), br, 1.0, None);
            if a().seg_from >= 0.0 && a().foto.is_none() {
                SetTimer(a().hwnd, T_SEG, 8, None);
            }
        } else if !tahoe && i + 1 < N_TABS && i + 1 != a().tab {
            br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.14) } else { col(0.0, 0.0, 0.0, 0.12) });
            ln(rt, br, r.right, r.top + 10.0, r.right, r.bottom - 10.0, 1.0);
        }
        text(rt, br, &tr(TAB_NAMES[i]), &tf("14c"), r, pal.text);
    }
    let sr = search_rect();
    pill(rt, br, pal, sr);
    let foco = a().search_focus;
    if foco {
        let ac = pal.accent;
        if tahoe {
            br.SetColor(&col(ac.r, ac.g, ac.b, 0.75));
            rt.DrawRoundedRectangle(&rr(inflate(sr, 1.5), PILL_H / 2.0 + 1.5, PILL_H / 2.0 + 1.5), br, 3.0, None);
        } else {
            br.SetColor(&col(ac.r, ac.g, ac.b, 0.6));
            rt.DrawRoundedRectangle(&rr(inflate(sr, -1.0), PILL_H / 2.0 - 1.0, PILL_H / 2.0 - 1.0), br, 2.0, None);
        }
    }
    br.SetColor(&pal.text2);
    let (mx, my) = (sr.left + 18.0, (sr.top + sr.bottom) / 2.0 - 1.0);
    rt.DrawEllipse(&ell(pt(mx, my), 5.0, 5.0), br, 1.4, None);
    ln(rt, br, mx + 3.6, my + 3.6, mx + 7.0, my + 7.0, 1.6);
    let vazio = a().search.is_empty();
    let shown = if vazio { tr("Buscar") } else { a().search.clone() };
    let caret = if foco && GetTickCount() / 530 % 2 == 0 { "|" } else { "" };
    text(rt, br, &format!("{shown}{caret}"), &tf("13"), rf(sr.left + 32.0, sr.top, sr.right - 14.0, sr.bottom), if vazio { pal.text2 } else { pal.text });
}
unsafe fn draw_header(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) {
    let (cw, _) = client();
    let dark = a().dark;
    br.SetColor(&pal.bg);
    rt.FillRectangle(&rf(0.0, TOOLBAR_H, cw, TOOLBAR_H + HEADER_H), br);
    let spans = col_spans();
    let tab = a().tab;
    if leo() {
        grad(rt, rf(0.0, TOOLBAR_H, cw, TOOLBAR_H + HEADER_H), 0.0, &[(0.0, col(1.0, 1.0, 1.0, 1.0)), (1.0, col(0.9, 0.9, 0.9, 1.0))]);
        let s = spans[a().sort_col[tab]];
        grad(rt, rf(s.0, TOOLBAR_H, s.1, TOOLBAR_H + HEADER_H), 0.0, &[(0.0, col(0.8, 0.89, 0.99, 1.0)), (0.5, col(0.64, 0.79, 0.97, 1.0)), (1.0, col(0.74, 0.86, 0.99, 1.0))]);
    }
    for (i, c) in COLS[tab].iter().enumerate() {
        let sorted = i == a().sort_col[tab];
        let right = !text_col(c.key);
        let (l, r) = spans[i];
        let mut t = rf(l + if c.key == K::Name { 19.0 } else { 8.0 }, TOOLBAR_H, r - if right { 12.0 } else { 4.0 }, TOOLBAR_H + HEADER_H);
        if sorted && right {
            t.right -= 12.0;
        }
        let titulo = tr(c.title);
        text(rt, br, &titulo, &tf(if right { "headr" } else { "head" }), t, pal.text);
        if sorted {
            br.SetColor(&pal.text2);
            let ax = if right { r - 14.0 } else { (r - 10.0).min(t.left + text_w(&tf("head"), &titulo) + 10.0) };
            let ay = TOOLBAR_H + HEADER_H / 2.0;
            if a().sort_asc[tab] {
                ln(rt, br, ax - 3.5, ay + 1.5, ax, ay - 2.0, 1.2);
                ln(rt, br, ax, ay - 2.0, ax + 3.5, ay + 1.5, 1.2);
            } else {
                ln(rt, br, ax - 3.5, ay - 1.5, ax, ay + 2.0, 1.2);
                ln(rt, br, ax, ay + 2.0, ax + 3.5, ay - 1.5, 1.2);
            }
        }
        br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.22) } else { col(0.0, 0.0, 0.0, 0.15) });
        ln(rt, br, r + 0.5, TOOLBAR_H + HEADER_H / 2.0 - 7.5, r + 0.5, TOOLBAR_H + HEADER_H / 2.0 + 7.5, 1.0);
    }
    if !a().tahoe {
        br.SetColor(&pal.line);
        ln(rt, br, 0.0, TOOLBAR_H + HEADER_H - 0.5, cw, TOOLBAR_H + HEADER_H - 0.5, 1.0);
    }
}
unsafe fn draw_rows(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) {
    let (cw, _) = client();
    let (top, bottom) = (list_top(), list_bottom());
    rt.PushAxisAlignedClip(&rf(0.0, top, cw, bottom), D2D1_ANTIALIAS_MODE_ALIASED);
    let spans = col_spans();
    let tab = a().tab;
    let (active, dark, tahoe) = (a().active, a().dark, a().tahoe);
    let first = (a().scroll / ROW_H).max(0.0) as usize;
    let rows = a().rows.clone();
    for (i, pid) in rows.iter().enumerate().skip(first) {
        let y = top + 4.0 + i as f32 * ROW_H - a().scroll;
        if y > bottom {
            break;
        }
        let Some(p) = co().procs.get(pid).cloned() else { continue };
        let sel = p.pid == a().sel;
        let sel_c = if active { pal.accent } else if dark { col(1.0, 1.0, 1.0, 0.16) } else { col(0.0, 0.0, 0.0, 0.10) };
        if tahoe {
            let round = rr(rf(10.0, y, cw - 10.0, y + ROW_H), 7.0, 7.0);
            if sel {
                br.SetColor(&sel_c);
                rt.FillRoundedRectangle(&round, br);
            } else if i % 2 == 1 {
                br.SetColor(&pal.stripe);
                rt.FillRoundedRectangle(&round, br);
            }
        } else if sel || i % 2 == 1 {
            br.SetColor(&if sel { sel_c } else { pal.stripe });
            rt.FillRectangle(&rf(0.0, y, cw, y + ROW_H), br);
        }
        let tc = if sel && active { col(1.0, 1.0, 1.0, 1.0) } else { pal.text };
        for (c, cl) in COLS[tab].iter().enumerate() {
            let (l, r) = spans[c];
            let right = !text_col(cl.key);
            if cl.key == K::Name {
                if let Some(ic) = icon_for(rt, &p) {
                    rt.DrawBitmap(&ic, Some(&rf(ICON_X, y + 3.0, ICON_X + 18.0, y + 21.0)), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
                }
                text(rt, br, &p.name, &tf("13"), rf(NAME_X, y, r - 6.0, y + ROW_H), tc);
            } else {
                text(rt, br, &cell(&p, cl.key), &tf(if right { "13r" } else { "13" }), rf(l + 8.0, y, r - if right { 12.0 } else { 4.0 }, y + ROW_H), tc);
            }
        }
    }
    let ms = max_scroll();
    if ms > 0.0 {
        let h = bottom - top;
        let th = (h * h / (h + ms)).max(30.0);
        let ty = top + (h - th) * (a().scroll / ms);
        br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.3) } else { col(0.0, 0.0, 0.0, 0.3) });
        rt.FillRoundedRectangle(&rr(rf(cw - 11.0, ty + 2.0, cw - 4.0, ty + th - 2.0), 3.5, 3.5), br);
    }
    rt.PopAxisAlignedClip();
}
/// gráfico de área; mirror: a segunda série vai para baixo do eixo (disco e rede, como no Mac)
#[allow(clippy::too_many_arguments)]
unsafe fn graph(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, r: RectF, va: &[f32], ca: Cor, vb: Option<&[f32]>, cb: Cor, mirror: bool, stack: bool) {
    rt.PushAxisAlignedClip(&r, D2D1_ANTIALIAS_MODE_ALIASED);
    let (wd, h) = (r.right - r.left, r.bottom - r.top);
    let base = if mirror { r.top + h * 0.62 } else { r.bottom };
    let amp = if mirror { h * 0.55 } else { h };
    let samples = co().samples;
    let path = |v: &[f32], under: Option<&[f32]>, sign: f32, c: Cor| {
        let n = v.len() as i32;
        let have = (samples - 1).clamp(2, n); // o gráfico nasce na direita e anda para a esquerda
        let x = |i: i32| r.left + wd * (i - (n - have)) as f32 / (have - 1) as f32;
        let u = |i: i32| under.map(|u| u[i as usize]).unwrap_or(0.0);
        let y = |i: i32| base - sign * (u(i) + v[i as usize]) * amp;
        let yu = |i: i32| base - sign * u(i) * amp;
        let i0 = n - have;
        let Ok(g) = d2d().CreatePathGeometry() else { return };
        let Ok(sk) = g.Open() else { return };
        sk.BeginFigure(pt(x(i0), yu(i0)), D2D1_FIGURE_BEGIN_FILLED);
        for i in i0..n {
            sk.AddLine(pt(x(i), y(i)));
        }
        for i in (i0..n).rev() {
            sk.AddLine(pt(x(i), yu(i)));
        }
        sk.EndFigure(D2D1_FIGURE_END_CLOSED);
        let _ = sk.Close();
        br.SetColor(&col(c.r, c.g, c.b, 0.35));
        rt.FillGeometry(&g, br, None);
        br.SetColor(&c);
        for i in i0 + 1..n {
            rt.DrawLine(pt(x(i - 1), y(i - 1)), pt(x(i), y(i)), br, 1.2, None);
        }
    };
    match vb {
        Some(b) if stack => {
            path(b, None, 1.0, cb);
            path(va, Some(b), 1.0, ca);
        }
        _ => {
            path(va, None, 1.0, ca);
            if let Some(b) = vb {
                path(b, None, if mirror { -1.0 } else { 1.0 }, cb);
            }
        }
    }
    if mirror {
        br.SetColor(&if a().dark { col(1.0, 1.0, 1.0, 0.25) } else { col(0.0, 0.0, 0.0, 0.25) });
        rt.DrawLine(pt(r.left, base), pt(r.right, base), br, 1.0, None);
    }
    rt.PopAxisAlignedClip();
}
fn stats(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal, r: RectF, rows: &[(String, String, Cor)]) {
    let rh = 20.0;
    let mut y = r.top + 5.0;
    for (k, (l, v, c)) in rows.iter().enumerate() {
        text(rt, br, l, &tf("stat"), rf(r.left + 11.5, y, r.right - 10.0, y + rh), pal.text);
        text(rt, br, v, &tf("statr"), rf(r.left + 11.5, y, r.right - 10.0, y + rh), *c);
        if k + 1 < rows.len() {
            unsafe { br.SetColor(&if a().dark { col(1.0, 1.0, 1.0, 0.22) } else { col(0.0, 0.0, 0.0, 0.14) }) };
            ln(rt, br, r.left + 8.0, y + rh - 0.5, r.right - 8.0, y + rh - 0.5, 1.0);
        }
        y += rh;
    }
}
unsafe fn draw_panel(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) {
    let (cw, ch) = client();
    let (dark, tahoe) = (a().dark, a().tahoe);
    let top = ch - PANEL_H;
    br.SetColor(&pal.panel);
    rt.FillRectangle(&rf(0.0, top, cw, ch), br);
    if !tahoe {
        br.SetColor(&pal.line);
        ln(rt, br, 0.0, top + 0.5, cw, top + 0.5, 1.0);
    }
    let (bw, bh) = (579.0, 90.0);
    let (bx, by) = (((cw - bw) / 2.0).round(), top + 12.5);
    let bxr = rf(bx, by, bx + bw, by + bh);
    let r0 = if tahoe { 10.0 } else { 6.0 };
    br.SetColor(&pal.boxc);
    rt.FillRoundedRectangle(&rr(bxr, r0, r0), br);
    br.SetColor(&match (tahoe, dark) {
        (true, true) => col(1.0, 1.0, 1.0, 0.16),
        (true, false) => col(0.0, 0.0, 0.0, 0.12),
        (false, true) => col(1.0, 1.0, 1.0, 0.30),
        (false, false) => col(0.0, 0.0, 0.0, 0.20),
    });
    rt.DrawRoundedRectangle(&rr(inflate(bxr, -0.5), r0 - 0.5, r0 - 0.5), br, 1.0, None);
    let l_ = rf(bx, by, bx + 197.5, by + bh);
    let m_ = rf(bx + 197.5, by, bx + 381.5, by + bh);
    let r_ = rf(bx + 381.5, by, bx + bw, by + bh);
    br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.3) } else { col(0.0, 0.0, 0.0, 0.2) });
    ln(rt, br, m_.left + 0.5, by, m_.left + 0.5, by + bh, 1.0);
    ln(rt, br, r_.left + 0.5, by, r_.left + 0.5, by + bh, 1.0);
    let blue = if dark { col(0.39, 0.82, 1.0, 1.0) } else { col(0.18, 0.56, 0.93, 1.0) };
    let red = col(1.0, 0.33, 0.30, 1.0);
    let green = col(0.29, 0.78, 0.36, 1.0);
    let title_in = |sec: RectF, t: &str| {
        text(rt, br, &tr(t), &tf("10c"), rf(sec.left, by + 4.0, sec.right, by + 19.0), pal.text2);
        br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.22) } else { col(0.0, 0.0, 0.0, 0.14) });
        ln(rt, br, sec.left + 12.0, by + 22.5, sec.right - 12.0, by + 22.5, 1.0);
    };
    let g = rf(m_.left + 12.0, by + 25.0, m_.right - 4.0, by + bh - 2.0);
    let pc_ = |v: f64| format!("{}%", pct(v));
    let t = pal.text;
    let s = |l: &str, v: String, c: Cor| (tr(l), v, c);
    let co = co();
    match a().tab {
        T_CPU => {
            stats(rt, br, pal, l_, &[s("Sistema:", pc_(co.cpu_sys), red), s("Usuário:", pc_(co.cpu_user), blue), s("Inativo:", pc_(co.cpu_idle), t)]);
            title_in(m_, "CARGA DA CPU");
            graph(rt, br, g, &co.h_cpu_user, blue, Some(&co.h_cpu_sys), red, false, true);
            stats(rt, br, pal, r_, &[s("Threads:", thousands(co.threads_total as u64), t), s("Processos:", thousands(co.proc_count as u64), t)]);
        }
        T_MEM => {
            title_in(l_, "PRESSÃO DE MEMÓRIA");
            let pcor = match co.press.nivel {
                0 => green,
                1 => col(0.98, 0.78, 0.18, 1.0),
                _ => red,
            };
            graph(rt, br, rf(l_.left + 12.0, by + 25.0, l_.right - 4.0, by + bh - 2.0), &co.h_mem, pcor, None, pcor, false, false);
            let page = co.pi.PageSize as f64;
            let used = co.ms.ullTotalPhys - co.ms.ullAvailPhys;
            let swap = (co.pi.CommitTotal as f64 * page - used as f64).max(0.0);
            stats(rt, br, pal, m_, &[s("Memória Física:", bytes(co.ms.ullTotalPhys as f64), t), s("Memória Usada:", bytes(used as f64), t), s("Arquivos em Cache:", bytes(co.pi.SystemCache as f64 * page), t), s("Swap Usado:", bytes(swap), t)]);
            stats(rt, br, pal, r_, &[s("Memória de Apps:", bytes(co.app_mem as f64), t), s("Memória do Kernel:", bytes(co.pi.KernelTotal as f64 * page), t), s("Comprimida:", bytes(co.compressed as f64), t)]);
        }
        T_ENERGY => {
            stats(rt, br, pal, l_, &[s("Impacto Energético:", pct(co.energy_total), t), s("Processos:", thousands(co.proc_count as u64), t)]);
            title_in(m_, "IMPACTO ENERGÉTICO");
            graph(rt, br, g, &co.h_energy, blue, None, blue, false, false);
            let mut ps = SYSTEM_POWER_STATUS::default();
            let _ = GetSystemPowerStatus(&mut ps);
            let charge = if ps.BatteryLifePercent <= 100 && ps.BatteryFlag != 128 { format!("{}%", ps.BatteryLifePercent) } else { tr("Sem bateria") };
            let source = match ps.ACLineStatus {
                1 => tr("Tomada"),
                0 => tr("Bateria"),
                _ => "—".into(),
            };
            let left = if ps.BatteryLifeTime != u32::MAX { format!("{}:{:02}", ps.BatteryLifeTime / 3600, ps.BatteryLifeTime / 60 % 60) } else { "—".into() };
            stats(rt, br, pal, r_, &[s("Carga Restante:", charge, t), s("Alimentação:", source, t), s("Tempo Restante:", left, t)]);
        }
        T_DISK => {
            stats(rt, br, pal, l_, &[s("Leituras:", thousands(co.rd_ops), t), s("Gravações:", thousands(co.wr_ops), t), s("Leituras/s:", thousands(co.rd_ops_sec.round() as u64), blue), s("Gravações/s:", thousands(co.wr_ops_sec.round() as u64), red)]);
            title_in(m_, "IO");
            graph(rt, br, g, &co.h_rd, blue, Some(&co.h_wr), red, true, false);
            stats(rt, br, pal, r_, &[s("Dados lidos:", bytes(co.rd_bytes as f64), t), s("Dados gravados:", bytes(co.wr_bytes as f64), t), s("Dados lidos/s:", bytes(co.rd_bytes_sec), blue), s("Dados gravados/s:", bytes(co.wr_bytes_sec), red)]);
        }
        T_NET => {
            stats(rt, br, pal, l_, &[s("Pacotes recebidos:", thousands(co.pkt_in), t), s("Pacotes enviados:", thousands(co.pkt_out), t), s("Pacotes receb./s:", thousands(co.pkt_in_sec.round() as u64), blue), s("Pacotes env./s:", thousands(co.pkt_out_sec.round() as u64), red)]);
            title_in(m_, "PACOTES");
            graph(rt, br, g, &co.h_net_in, blue, Some(&co.h_net_out), red, true, false);
            stats(rt, br, pal, r_, &[s("Dados recebidos:", bytes(co.net_in as f64), t), s("Dados enviados:", bytes(co.net_out as f64), t), s("Dados receb./s:", bytes(co.net_in_sec), blue), s("Dados env./s:", bytes(co.net_out_sec), red)]);
        }
        _ => {
            let mut name = if co.gpu_name.is_empty() { "—".to_string() } else { co.gpu_name.clone() };
            for p in ["NVIDIA ", "AMD ", "Intel(R) ", "GeForce "] {
                if name.starts_with(p) && name.chars().count() > 22 {
                    name = name[p.len()..].to_string();
                }
            }
            stats(rt, br, pal, l_, &[s("Placa:", name, t), s("Uso:", pc_(co.gpu_total), blue), s("Memória da GPU:", bytes(co.gpu_used_mem as f64), t), s("Total:", bytes(co.gpu_total_mem as f64), t)]);
            title_in(m_, "USO DA GPU");
            graph(rt, br, g, &co.h_gpu, blue, None, blue, false, false);
            let mut eng: Vec<(&String, &f64)> = co.engines.iter().collect();
            eng.sort_by(|x, y| y.1.partial_cmp(x.1).unwrap_or(std::cmp::Ordering::Equal));
            let mut rows: Vec<(String, String, Cor)> = eng.iter().take(4).map(|(e, v)| (format!("{e}:"), pc_(**v), t)).collect();
            if rows.is_empty() {
                rows.push((tr("Motores:"), "—".into(), t));
            }
            stats(rt, br, pal, r_, &rows);
        }
    }
}
// ---- folhas (alerta de encerrar e informações do processo), descendo da barra de cima como no Mac
unsafe fn sheet_button(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal, r: RectF, t: &str, def: bool, id: i32) {
    let dark = a().dark;
    br.SetColor(&if def {
        pal.accent
    } else if dark {
        col(1.0, 1.0, 1.0, 0.2)
    } else {
        col(1.0, 1.0, 1.0, 1.0)
    });
    rt.FillRoundedRectangle(&rr(r, 6.0, 6.0), br);
    if !def && !dark {
        br.SetColor(&col(0.0, 0.0, 0.0, 0.15));
        rt.DrawRoundedRectangle(&rr(inflate(r, -0.5), 5.5, 5.5), br, 1.0, None);
    }
    text(rt, br, &tr(t), &tf("13c"), r, if def { col(1.0, 1.0, 1.0, 1.0) } else { pal.text });
    a().sheet_btns.push((r, id));
}
fn wrap_fmt(size: f32, wt: DWRITE_FONT_WEIGHT, al: DWRITE_TEXT_ALIGNMENT) -> IDWriteTextFormat {
    let f = mk_fmt(size, wt, al);
    unsafe {
        let _ = f.SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
        let _ = f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
    }
    f
}
unsafe fn draw_sheet(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) {
    a().sheet_btns.clear();
    if a().sheet == Sheet::None {
        return;
    }
    let Some(p) = co().procs.get(&a().sheet_pid).cloned() else {
        a().sheet = Sheet::None;
        return;
    };
    let (cw, ch) = client();
    let dark = a().dark;
    br.SetColor(&col(0.0, 0.0, 0.0, if dark { 0.35 } else { 0.18 }));
    rt.FillRectangle(&rf(0.0, TOOLBAR_H, cw, ch), br);
    let quit = a().sheet == Sheet::Quit;
    let (wd, h) = if quit { (440.0, 150.0) } else { (460.0, 330.0) };
    let r = rf((cw - wd) / 2.0, TOOLBAR_H, (cw + wd) / 2.0, TOOLBAR_H + h);
    br.SetColor(&if dark { col(0.17, 0.17, 0.18, 1.0) } else { col(0.96, 0.96, 0.96, 1.0) });
    rt.FillRoundedRectangle(&rr(r, 10.0, 10.0), br);
    br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.16) } else { col(0.0, 0.0, 0.0, 0.16) });
    rt.DrawRoundedRectangle(&rr(inflate(r, -0.5), 9.5, 9.5), br, 1.0, None);
    let wrap = wrap_fmt(11.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING);
    if quit {
        if let Some(ic) = icon_for(rt, &p) {
            rt.DrawBitmap(&ic, Some(&rf(r.left + 20.0, r.top + 20.0, r.left + 68.0, r.top + 68.0)), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
        } else {
            let q = rf(r.left + 24.0, r.top + 24.0, r.left + 64.0, r.top + 64.0);
            br.SetColor(&col(0.98, 0.78, 0.18, 1.0));
            rt.FillRoundedRectangle(&rr(q, 9.0, 9.0), br);
            text(rt, br, "!", &tf("13c"), q, col(1.0, 1.0, 1.0, 1.0));
        }
        let tb = wrap_fmt(13.0, DWRITE_FONT_WEIGHT_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING);
        text(rt, br, &tr("Tem certeza de que deseja encerrar este processo?"), &tb, rf(r.left + 84.0, r.top + 20.0, r.right - 20.0, r.top + 56.0), pal.text);
        let msg = &a().sheet_msg;
        let corpo = if msg.is_empty() { format!("“{}{}{}{}", p.name, tr("” (PID "), p.pid, tr("). Forçar o encerramento fecha o processo na hora, sem salvar nada.")) } else { msg.clone() };
        text(rt, br, &corpo, &wrap, rf(r.left + 84.0, r.top + 58.0, r.right - 20.0, r.top + 100.0), if msg.is_empty() { pal.text2 } else { col(0.92, 0.27, 0.25, 1.0) });
        let by = r.bottom - 40.0;
        sheet_button(rt, br, pal, rf(r.left + 84.0, by, r.left + 236.0, by + 26.0), "Forçar Encerramento", false, 2);
        sheet_button(rt, br, pal, rf(r.right - 196.0, by, r.right - 108.0, by + 26.0), "Cancelar", false, 0);
        sheet_button(rt, br, pal, rf(r.right - 100.0, by, r.right - 20.0, by + 26.0), "Encerrar", true, 1);
    } else {
        if let Some(ic) = icon_for(rt, &p) {
            rt.DrawBitmap(&ic, Some(&rf(r.left + 20.0, r.top + 18.0, r.left + 52.0, r.top + 50.0)), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
        }
        text(rt, br, &format!("{} ({})", p.name, p.pid), &mk_fmt(15.0, DWRITE_FONT_WEIGHT_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING), rf(r.left + 62.0, r.top + 18.0, r.right - 20.0, r.top + 50.0), pal.text);
        let parent = co().procs.get(&p.ppid).map(|x| format!("{} ({})", x.name, p.ppid)).unwrap_or(p.ppid.to_string());
        let cft = FILETIME { dwLowDateTime: p.create as u32, dwHighDateTime: (p.create >> 32) as u32 };
        let mut lft = FILETIME::default();
        let mut st = SYSTEMTIME::default();
        let _ = FileTimeToLocalFileTime(&cft, &mut lft);
        let _ = FileTimeToSystemTime(&lft, &mut st);
        let started = cf!(tr("%02d/%02d/%04d às %02d:%02d:%02d"), st.wDay as i32, st.wMonth as i32, st.wYear as i32, st.wHour as i32, st.wMinute as i32, st.wSecond as i32);
        let rows = [
            ("Processo pai:", parent),
            ("Usuário:", p.user.clone()),
            ("Executável:", p.exe.clone()),
            ("Caminho:", if p.path.is_empty() { "—".into() } else { p.path.clone() }),
            ("% CPU:", pct(p.cpu_pct)),
            ("Tempo de CPU:", cpu_time(p.cpu)),
            ("Memória:", bytes(p.mem as f64)),
            ("Threads:", thousands(p.threads as u64)),
            ("Identificadores:", thousands(p.handles as u64)),
            ("Bytes lidos:", bytes(p.rd as f64)),
            ("Bytes gravados:", bytes(p.wr as f64)),
            ("Iniciado em:", started),
        ];
        let lab = mk_fmt(11.0, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_TRAILING);
        let mut y = r.top + 60.0;
        for (l, v) in rows {
            text(rt, br, &tr(l), &lab, rf(r.left + 10.0, y, r.left + 130.0, y + 17.0), pal.text);
            text(rt, br, &v, &tf("11"), rf(r.left + 138.0, y, r.right - 16.0, y + 17.0), pal.text);
            y += 18.0;
        }
        let by = r.bottom - 40.0;
        sheet_button(rt, br, pal, rf(r.left + 20.0, by, r.left + 170.0, by + 26.0), "Mostrar no Finder", false, 3);
        sheet_button(rt, br, pal, rf(r.right - 196.0, by, r.right - 108.0, by + 26.0), "Encerrar…", false, 4);
        sheet_button(rt, br, pal, rf(r.right - 100.0, by, r.right - 20.0, by + 26.0), "Fechar", true, 0);
    }
}
/// a janela desenhada pela Composição (finder/gfx.cpp), com o canto contínuo e o vidro do Tahoe, e a sombra do Mac
static GFX: Global<Option<comum::tahoe::Gfx>> = Global::new(None);
static SOMBRA: Global<Option<comum::tahoe::Shadow>> = Global::new(None);
fn golden_gate() -> bool {
    comum::ajustes::setting("golden_gate", "0") == "1"
}
fn sombra_update() {
    if a().shown {
        if let Some(sh) = SOMBRA.get().as_mut() {
            sh.update();
        }
    }
}
unsafe fn render_gfx(g: &comum::tahoe::Gfx) {
    let h = a().hwnd;
    let Some(dc) = g.begin(GetDpiForWindow(h) as f32) else { return };
    let rt: ID2D1RenderTarget = dc.cast().unwrap();
    a().rt = Some(rt.clone()); // os bitmaps valem entre quadros (mesmo dispositivo)
    let mut rc = RECT::default();
    let _ = GetClientRect(h, &mut rc);
    let k = GetDpiForWindow(h) as f32 / 96.0;
    let (w_, h_) = (rc.right as f32 / k, rc.bottom as f32 / k);
    rt.Clear(Some(&col(0.0, 0.0, 0.0, 0.0)));
    let win_r = if a().tahoe { comum::tahoe::radius(h, golden_gate()) } else { 0.0 };
    let clip = a().tahoe && comum::tahoe::push_window_clip(&dc, w_, h_, win_r); // fora do canto fica transparente
    render_into(&rt);
    if clip {
        dc.PopLayer();
        if let Ok(br) = rt.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None) {
            comum::tahoe::window_rim(&rt, &br, w_, h_, win_r, a().dark);
        }
    }
    if g.end().is_err() {
        a().icons.clear();
    }
    if !a().shown {
        // aparece só com o primeiro quadro pronto (sem piscar branco); a sombra nasce aqui
        a().shown = true;
        ampliacao::revelar(h);
        let mut sh = comum::tahoe::Shadow::create(h);
        sh.set_active(a().active);
        sh.set_radius(if a().tahoe { comum::tahoe::window_r(golden_gate()) } else { 0.0 });
        sh.update();
        *SOMBRA.get() = Some(sh);
    }
}
unsafe fn render_into(rt: &ID2D1RenderTarget) {
    let pal = colors();
    rt.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
    if GFX.get().is_some() {
        let Ok(b) = rt.CreateSolidColorBrush(&pal.bg, None) else { return };
        let mut rc = RECT::default();
        let _ = GetClientRect(a().hwnd, &mut rc);
        let k = GetDpiForWindow(a().hwnd) as f32 / 96.0;
        rt.FillRectangle(&rf(0.0, 0.0, rc.right as f32 / k, rc.bottom as f32 / k), &b);
    } else {
        rt.Clear(Some(&pal.bg));
    }
    let Ok(br) = rt.CreateSolidColorBrush(&pal.bg, None) else { return };
    a().scroll = a().scroll.clamp(0.0, max_scroll());
    draw_rows(rt, &br, &pal);
    draw_header(rt, &br, &pal);
    draw_panel(rt, &br, &pal);
    draw_toolbar(rt, &br, &pal);
    draw_sheet(rt, &br, &pal);
}
fn render() {
    unsafe {
        if let Some(g) = GFX.get().as_ref() {
            render_gfx(g);
            return;
        }
        let h = a().hwnd;
        if a().rt.is_none() {
            let mut rc = RECT::default();
            let _ = GetClientRect(h, &mut rc);
            let dpi = GetDpiForWindow(h) as f32;
            let props = D2D1_RENDER_TARGET_PROPERTIES { pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_IGNORE }, dpiX: dpi, dpiY: dpi, ..Default::default() };
            let hp = D2D1_HWND_RENDER_TARGET_PROPERTIES { hwnd: h, pixelSize: D2D_SIZE_U { width: rc.right as u32, height: rc.bottom as u32 }, presentOptions: D2D1_PRESENT_OPTIONS_NONE };
            let Ok(r) = d2d().CreateHwndRenderTarget(&props, &hp) else { return };
            a().icons.clear(); // os bitmaps são do alvo antigo
            a().rt = r.cast().ok();
            a().hrt = Some(r);
        }
        let Some(rt) = a().rt.clone() else { return };
        rt.BeginDraw();
        render_into(&rt);
        if let Err(e) = rt.EndDraw(None, None) {
            if e.code() == D2DERR_RECREATE_TARGET {
                a().rt = None;
                a().hrt = None;
            }
        }
        if !a().shown {
            a().shown = true;
            ampliacao::revelar(h); // aparece só com o primeiro quadro pronto (sem piscar branco)
        }
    }
}
fn invalidate() {
    unsafe {
        let _ = InvalidateRect(a().hwnd, None, FALSE);
    }
}
fn set_tab(i: usize) {
    if i == a().tab {
        return;
    }
    a().seg_from = if a().tahoe { seg_pos() } else { -1.0 };
    a().seg_at = unsafe { GetTickCount() };
    a().tab = i;
    build_rows();
    a().scroll = 0.0;
    if a().tahoe {
        unsafe {
            SetTimer(a().hwnd, T_SEG, 8, None);
        }
    }
    invalidate();
}
fn apply_theme() {
    unsafe {
        let h = a().hwnd;
        let dm = BOOL::from(a().dark);
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(20), &dm as *const _ as *const c_void, 4);
        if GFX.get().is_some() {
            if a().tahoe {
                // Tahoe: cantos de 26 pt com o vidro da Composição, como o Ajustes
                comum::tahoe::frame(h, true);
                comum::tahoe::size(h, a().dark, comum::ajustes::setting("reduzir_transparencia", "0") == "1");
                if let Some(sh) = SOMBRA.get().as_mut() {
                    sh.set_radius(comum::tahoe::window_r(golden_gate()));
                }
                return;
            }
            comum::tahoe::frame(h, false);
            if let Some(sh) = SOMBRA.get().as_mut() {
                sh.set_radius(0.0);
            }
        }
        let border = if a().dark { app2d::colorref(88, 88, 92) } else { app2d::colorref(196, 196, 200) };
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(34), &border as *const _ as *const c_void, 4);
        let corner = 2i32; // arredondado (o C++ faz o canto de 26 pt do Tahoe com a Composição)
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const c_void, 4);
    }
}

// ---- ações
fn windows_of(pid: u32) -> Vec<HWND> {
    unsafe extern "system" fn cb(h: HWND, l: LPARAM) -> BOOL {
        let v = &mut *(l.0 as *mut (u32, Vec<HWND>));
        let mut p = 0u32;
        GetWindowThreadProcessId(h, Some(&mut p));
        if p == v.0 && IsWindowVisible(h).as_bool() && GetWindow(h, GW_OWNER).map(|o| o.0.is_null()).unwrap_or(true) {
            v.1.push(h);
        }
        TRUE
    }
    let mut v = (pid, Vec::new());
    unsafe {
        let _ = EnumWindows(Some(cb), LPARAM(&mut v as *mut _ as isize));
    }
    v.1
}
/// Encerrar: pede para as janelas fecharem; sem janela, encerra. Forçar: TerminateProcess.
fn quit_process(pid: u32, force: bool) -> bool {
    unsafe {
        if pid == GetCurrentProcessId() {
            let _ = PostMessageW(a().hwnd, WM_CLOSE, WPARAM(0), LPARAM(0));
            return true;
        }
        let ws = windows_of(pid);
        if !force && !ws.is_empty() {
            for h in ws {
                let _ = PostMessageW(h, WM_CLOSE, WPARAM(0), LPARAM(0));
            }
            return true;
        }
        let Ok(h) = OpenProcess(PROCESS_TERMINATE, FALSE, pid) else { return false };
        let ok = TerminateProcess(h, 1).is_ok();
        let _ = CloseHandle(h);
        ok
    }
}
fn show_in_finder(p: &Proc) {
    if p.path.is_empty() {
        return;
    }
    let finder = exe_dir().join("WacOSFinder.exe");
    if finder.exists() {
        shell_open(&finder.to_string_lossy(), Some(&format!("\"{}\"", p.path)));
    } else {
        shell_open("explorer.exe", Some(&format!("/select,\"{}\"", p.path)));
    }
}
fn open_sheet(s: Sheet) {
    let Some(p) = selected() else { return };
    a().sheet = s;
    a().sheet_pid = p.pid;
    a().sheet_msg.clear();
    invalidate();
}
fn sheet_action(id: i32) {
    let p = co().procs.get(&a().sheet_pid).cloned();
    if id == 0 || p.is_none() {
        a().sheet = Sheet::None;
        invalidate();
        return;
    }
    let p = p.unwrap();
    match id {
        1 | 2 => {
            if quit_process(p.pid, id == 2) {
                a().sheet = Sheet::None;
                unsafe {
                    SetTimer(a().hwnd, T_SAMPLE, 400, None); // atualiza logo
                }
            } else {
                a().sheet_msg = tr("Não foi possível encerrar este processo: ele pertence ao sistema ou a outro usuário. Abra o Monitor de Atividade como administrador.");
            }
        }
        3 => {
            show_in_finder(&p);
            a().sheet = Sheet::None;
        }
        4 => {
            a().sheet = Sheet::Quit;
            a().sheet_msg.clear();
        }
        _ => {}
    }
    invalidate();
}
fn action_menu(screen: POINT) {
    use ctxmenu::Item;
    let p = selected().cloned();
    let sem = p.is_none();
    let sem_cam = p.as_ref().map(|p| p.path.is_empty()).unwrap_or(true);
    let id = ctxmenu::show_items(
        a().hwnd,
        screen,
        &[
            Item::new(tr("Encerrar Processo…"), 1).disabled(sem),
            Item::new(tr("Obter Informações"), 2).disabled(sem),
            Item::sep(),
            Item::new(tr("Mostrar no Finder"), 3).disabled(sem_cam),
            Item::new(tr("Copiar Caminho"), 4).disabled(sem_cam),
            Item::new(tr("Copiar PID"), 5).disabled(sem),
        ],
    );
    let Some(p) = p else { return };
    match id {
        1 => open_sheet(Sheet::Quit),
        2 => open_sheet(Sheet::Info),
        3 => show_in_finder(&p),
        4 => {
            clipboard_set_text(a().hwnd, &p.path);
        }
        5 => {
            clipboard_set_text(a().hwnd, &p.pid.to_string());
        }
        _ => {}
    }
}
fn ensure_visible(i: usize) {
    let y = 4.0 + i as f32 * ROW_H;
    let h = list_bottom() - list_top();
    if y < a().scroll {
        a().scroll = y;
    } else if y + ROW_H > a().scroll + h {
        a().scroll = y + ROW_H - h;
    }
}
fn hit_row(p: Ponto) -> Option<usize> {
    if p.y < list_top() || p.y >= list_bottom() {
        return None;
    }
    let i = ((p.y - list_top() - 4.0 + a().scroll) / ROW_H).floor() as i64;
    (i >= 0 && (i as usize) < a().rows.len()).then_some(i as usize)
}
fn hit_test_nc(h: HWND, l: LPARAM) -> LRESULT {
    let p = screen_to_client(h, l);
    let mut rc = RECT::default();
    unsafe {
        let _ = GetClientRect(h, &mut rc);
        let s = scale();
        if !IsZoomed(h).as_bool() {
            let b = (6.0 * s) as i32;
            let (l_, r_, t_, b_) = (p.x < b, p.x >= rc.right - b, p.y < b, p.y >= rc.bottom - b);
            let ht = match (t_, b_, l_, r_) {
                (true, _, true, _) => HTTOPLEFT,
                (true, _, _, true) => HTTOPRIGHT,
                (_, true, true, _) => HTBOTTOMLEFT,
                (_, true, _, true) => HTBOTTOMRIGHT,
                (_, _, true, _) => HTLEFT,
                (_, _, _, true) => HTRIGHT,
                (true, _, _, _) => HTTOP,
                (_, true, _, _) => HTBOTTOM,
                _ => 0,
            };
            if ht != 0 {
                return LRESULT(ht as isize);
            }
        }
        let q = pt(p.x as f32 / s, p.y as f32 / s);
        if q.y < TOOLBAR_H && a().sheet == Sheet::None {
            let segs = if leo() { q.x >= seg_rect(0).left && q.x < seg_rect(N_TABS - 1).right && q.y >= 22.0 } else { q.x >= SEG_X && q.x < SEG_X + N_TABS as f32 * SEG_W };
            let control = (q.x < 82.0 && (!leo() || q.y < 22.0)) || inr(&search_rect(), q) || (0..3).any(|k| inr(&btn_rect(k), q)) || segs;
            if !control {
                return LRESULT(HTCAPTION as isize);
            }
        }
    }
    LRESULT(HTCLIENT as isize)
}

extern "system" fn wnd_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 sc = scale();
        let pcli = || pt(get_x_lparam(l) as f32 / sc, get_y_lparam(l) as f32 / sc);
        match m {
            WM_NCCALCSIZE if w_.0 != 0 => {
                if IsZoomed(h).as_bool() {
                    let p = &mut *(l.0 as *mut NCCALCSIZE_PARAMS);
                    let dpi = GetDpiForWindow(h);
                    let fx = GetSystemMetricsForDpi(SM_CXFRAME, dpi) + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi);
                    let fy = GetSystemMetricsForDpi(SM_CYFRAME, dpi) + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi);
                    p.rgrc[0].left += fx;
                    p.rgrc[0].right -= fx;
                    p.rgrc[0].top += fy;
                    p.rgrc[0].bottom -= fy;
                }
                return LRESULT(0);
            }
            WM_NCHITTEST => return hit_test_nc(h, l),
            WM_NCLBUTTONDBLCLK if w_.0 == HTCAPTION as usize => ampliacao::alternar(h),
            WM_GETMINMAXINFO => {
                (*(l.0 as *mut MINMAXINFO)).ptMinTrackSize = POINT { x: (1000.0 * sc) as i32, y: (440.0 * sc) as i32 };
            }
            WM_SIZE => {
                if let Some(g) = GFX.get().as_mut() {
                    if w_.0 != SIZE_MINIMIZED as usize {
                        g.resize(loword(l.0 as usize), hiword(l.0 as usize));
                        if a().tahoe {
                            comum::tahoe::size(h, a().dark, comum::ajustes::setting("reduzir_transparencia", "0") == "1");
                        }
                    }
                }
                if let Some(r) = &a().hrt {
                    let _ = r.Resize(&D2D_SIZE_U { width: loword(l.0 as usize), height: hiword(l.0 as usize) });
                }
                invalidate();
            }
            WM_DPICHANGED => {
                let r = &*(l.0 as *const RECT);
                a().rt = None;
                a().hrt = None;
                let _ = SetWindowPos(h, None, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOZORDER | SWP_NOACTIVATE);
            }
            WM_ERASEBKGND => return LRESULT(1),
            WM_PAINT => {
                let mut ps = PAINTSTRUCT::default();
                BeginPaint(h, &mut ps);
                if a().foto.is_none() {
                    render();
                }
                let _ = EndPaint(h, &ps);
            }
            WM_ACTIVATE => {
                a().active = loword(w_.0) != WA_INACTIVE;
                if a().shown {
                    if let Some(sh) = SOMBRA.get().as_mut() {
                        sh.set_active(a().active);
                        sh.update();
                    }
                }
                invalidate();
            }
            WM_WINDOWPOSCHANGED => sombra_update(),
            WM_SETTINGCHANGE => {
                a().tahoe = read_tahoe();
                a().dark = app2d::dark();
                apply_theme();
                invalidate();
            }
            WM_TIMER => match w_.0 {
                T_SAMPLE => {
                    SetTimer(h, T_SAMPLE, SAMPLE_MS, None);
                    sample();
                    build_rows();
                    invalidate();
                }
                2 if a().search_focus => invalidate(),
                T_SEG => {
                    if a().seg_from < 0.0 {
                        let _ = KillTimer(h, T_SEG);
                    }
                    invalidate();
                }
                3 => {
                    let t = read_tahoe();
                    if t != a().tahoe {
                        a().tahoe = t;
                        invalidate();
                    }
                }
                7 => {
                    // --foto: depois de duas amostras
                    let _ = KillTimer(h, 7);
                    sample();
                    build_rows();
                    foto_salvar();
                    let _ = DestroyWindow(h);
                }
                _ => {}
            },
            WM_MOUSEWHEEL => {
                if a().sheet == Sheet::None {
                    a().scroll -= wheel_delta(w_) / 120.0 * ROW_H * 3.0;
                    invalidate();
                }
            }
            WM_MOUSEMOVE => {
                let p = pcli();
                let mut t = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };
                let _ = TrackMouseEvent(&mut t);
                let hb = (0..3).rev().find(|&k| inr(&btn_rect(k), p)).unwrap_or(-1);
                let hl = p.x < 82.0 && p.y < TOOLBAR_H;
                ampliacao::verde(h, hl && (58.0..81.0).contains(&p.x));
                if hb != a().hover_btn || hl != a().hover_lights {
                    a().hover_btn = hb;
                    a().hover_lights = hl;
                    invalidate();
                }
            }
            WM_MOUSELEAVE => {
                ampliacao::verde(h, false);
                if a().hover_btn >= 0 || a().hover_lights {
                    a().hover_btn = -1;
                    a().hover_lights = false;
                    invalidate();
                }
            }
            WM_LBUTTONDBLCLK | WM_LBUTTONDOWN => {
                let p = pcli();
                if a().sheet != Sheet::None {
                    if let Some(id) = a().sheet_btns.iter().find(|(r, _)| inr(r, p)).map(|x| x.1) {
                        sheet_action(id);
                    }
                    return LRESULT(0);
                }
                for k in 0..3 {
                    let c = light_center(k);
                    if (p.x - c.x).abs() <= 8.0 && (p.y - c.y).abs() <= 8.0 {
                        match k {
                            0 => {
                                let _ = PostMessageW(h, WM_CLOSE, WPARAM(0), LPARAM(0));
                            }
                            1 => {
                                let _ = ShowWindow(h, SW_MINIMIZE);
                            }
                            _ => ampliacao::alternar(h),
                        }
                        return LRESULT(0);
                    }
                }
                let was = a().search_focus;
                a().search_focus = inr(&search_rect(), p);
                if a().search_focus != was {
                    if a().search_focus {
                        SetTimer(h, 2, 530, None);
                    } else {
                        let _ = KillTimer(h, 2);
                    }
                    invalidate();
                }
                if a().search_focus {
                    return LRESULT(0);
                }
                if inr(&btn_rect(0), p) {
                    open_sheet(Sheet::Quit);
                    return LRESULT(0);
                }
                if inr(&btn_rect(1), p) {
                    open_sheet(Sheet::Info);
                    return LRESULT(0);
                }
                if inr(&btn_rect(2), p) {
                    let r = btn_rect(2);
                    let sp = app2d::to_screen(h, (r.left * sc) as i32, ((r.bottom + 4.0) * sc) as i32);
                    action_menu(sp);
                    invalidate();
                    return LRESULT(0);
                }
                if let Some(i) = (0..N_TABS).find(|&i| inr(&seg_rect(i), p)) {
                    set_tab(i);
                    return LRESULT(0);
                }
                if p.y >= TOOLBAR_H && p.y < TOOLBAR_H + HEADER_H {
                    // ordenar pela coluna
                    let tab = a().tab;
                    if let Some(i) = col_spans().iter().position(|s| p.x >= s.0 && p.x < s.1) {
                        if a().sort_col[tab] == i {
                            a().sort_asc[tab] = !a().sort_asc[tab];
                        } else {
                            a().sort_col[tab] = i;
                            a().sort_asc[tab] = matches!(COLS[tab][i].key, K::Name | K::User | K::Pid);
                        }
                        build_rows();
                        invalidate();
                    }
                    return LRESULT(0);
                }
                let r = hit_row(p);
                a().sel = r.map(|r| a().rows[r]).unwrap_or(0);
                if m == WM_LBUTTONDBLCLK && r.is_some() {
                    open_sheet(Sheet::Info);
                }
                invalidate();
            }
            WM_RBUTTONUP => {
                if a().sheet == Sheet::None {
                    if let Some(r) = hit_row(pcli()) {
                        a().sel = a().rows[r];
                        invalidate();
                        action_menu(app2d::to_screen(h, get_x_lparam(l), get_y_lparam(l)));
                    }
                }
            }
            WM_KEYDOWN => {
                let k = w_.0 as u16;
                let ctrl = app2d::key_down(VK_CONTROL.0);
                if a().sheet != Sheet::None {
                    if k == VK_ESCAPE.0 {
                        sheet_action(0);
                    } else if k == VK_RETURN.0 {
                        sheet_action(if a().sheet == Sheet::Quit { 1 } else { 0 });
                    }
                    return LRESULT(0);
                }
                if ctrl {
                    match k {
                        0x46 => {
                            a().search_focus = true;
                            SetTimer(h, 2, 530, None);
                            invalidate();
                        }
                        0x57 => {
                            let _ = PostMessageW(h, WM_CLOSE, WPARAM(0), LPARAM(0));
                        }
                        0x49 => open_sheet(Sheet::Info),
                        0x31..=0x36 => set_tab((k - 0x31) as usize),
                        _ => {}
                    }
                    if matches!(k, 0x46 | 0x57 | 0x49 | 0x31..=0x36) {
                        return LRESULT(0);
                    }
                }
                if a().search_focus {
                    if k == VK_ESCAPE.0 {
                        a().search.clear();
                        a().search_focus = false;
                        let _ = KillTimer(h, 2);
                    } else if k == VK_BACK.0 {
                        a().search.pop();
                    }
                    build_rows();
                    invalidate();
                    if k != VK_DOWN.0 && k != VK_UP.0 {
                        return LRESULT(0);
                    }
                }
                if k == VK_DOWN.0 || k == VK_UP.0 {
                    let n = a().rows.len() as i32;
                    let cur = a().rows.iter().position(|&p| p == a().sel).map(|x| x as i32).unwrap_or(-1);
                    let nx = (cur + if k == VK_DOWN.0 { 1 } else { -1 }).clamp(0, n - 1);
                    if nx >= 0 && nx < n {
                        a().sel = a().rows[nx as usize];
                        ensure_visible(nx as usize);
                    }
                    invalidate();
                } else if k == VK_DELETE.0 && selected().is_some() {
                    open_sheet(Sheet::Quit);
                }
            }
            WM_CHAR => {
                if a().search_focus && w_.0 >= 32 && w_.0 != 127 && a().search.chars().count() < 60 {
                    if let Some(c) = char::from_u32(w_.0 as u32) {
                        a().search.push(c);
                        build_rows();
                        a().scroll = 0.0;
                        invalidate();
                    }
                }
            }
            WM_DESTROY => {
                if let Some(sh) = SOMBRA.get().as_mut() {
                    sh.destroy();
                }
                PostQuitMessage(0)
            }
            _ => return DefWindowProcW(h, m, w_, l),
        }
        LRESULT(0)
    }
}

fn foto_salvar() {
    let p = a().foto.clone().unwrap();
    let (cw, ch) = a().foto_size;
    let r = (|| -> Result<()> {
        unsafe {
            let wic: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
            let bmp = wic.CreateBitmap((cw * 2.0) as u32, (ch * 2.0) as u32, &GUID_WICPixelFormat32bppPBGRA, WICBitmapCacheOnLoad)?;
            let props = D2D1_RENDER_TARGET_PROPERTIES { pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED }, dpiX: 192.0, dpiY: 192.0, ..Default::default() };
            let rt = d2d().CreateWicBitmapRenderTarget(&bmp, &props)?;
            a().icons.clear();
            rt.BeginDraw();
            render_into(&rt);
            rt.EndDraw(None, None)?;
            salvar_png(&bmp, &p)
        }
    })();
    println!("foto: {p} {r:?} ({} processos)", co().procs.len());
}

fn main() {
    let foto = arg_valor("--foto");
    unsafe {
        if foto.is_none() {
            let _ = CreateMutexW(None, true, w!("MonitorAtividadeUmaJanela"));
            if GetLastError() == ERROR_ALREADY_EXISTS {
                if let Some(wd) = find_window("MonitorAtividadeJanela") {
                    if IsIconic(wd).as_bool() {
                        let _ = ShowWindow(wd, SW_RESTORE);
                    }
                    let _ = SetForegroundWindow(wd);
                }
                return;
            }
        }
    }
    if !app2d::init() {
        std::process::exit(1);
    }
    let family = ["SF Pro Text", "Inter", "Segoe UI Variable Text"].into_iter().find(|f| app2d::has_font(f)).unwrap_or("Segoe UI").to_string();
    let exe = exe_dir();
    let win = std::env::var("WINDIR").unwrap_or("C:\\Windows".into());
    let co = Coleta {
        first: true,
        h_cpu_sys: vec![0.0; HIST],
        h_cpu_user: vec![0.0; HIST],
        h_mem: vec![0.0; HIST],
        h_energy: vec![0.0; HIST],
        h_rd: vec![0.0; HIST],
        h_wr: vec![0.0; HIST],
        h_net_in: vec![0.0; HIST],
        h_net_out: vec![0.0; HIST],
        h_gpu: vec![0.0; HIST],
        win_dir: format!("{}\\", win.to_lowercase()),
        bin_dir: format!("{}\\", exe.to_string_lossy().to_lowercase()),
        pack_dir: format!("{}\\", install_dir().join("icones").join("sequoia").to_string_lossy()),
        me: std::env::var("USERNAME").unwrap_or_default(),
        ..Default::default()
    };
    let tab = arg_valor("--aba").and_then(|v| v.parse::<usize>().ok()).unwrap_or(0).min(N_TABS - 1);
    *A.get() = Some(App {
        hwnd: HWND::default(),
        co,
        rt: None,
        hrt: None,
        tf: HashMap::new(),
        family,
        dark: app2d::dark(),
        tahoe: read_tahoe(),
        active: true,
        tab,
        seg_from: -1.0,
        seg_at: 0,
        sort_col: [1; N_TABS],
        sort_asc: [false; N_TABS],
        sel: 0,
        scroll: 0.0,
        search: String::new(),
        search_focus: false,
        rows: Vec::new(),
        icons: HashMap::new(),
        hover_btn: -1,
        hover_lights: false,
        sheet: Sheet::None,
        sheet_pid: 0,
        sheet_btns: Vec::new(),
        sheet_msg: String::new(),
        shown: false,
        foto: foto.clone(),
        foto_size: (1228.0, 634.0),
    });
    let (n, l, r_, c_) = (DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING, DWRITE_TEXT_ALIGNMENT_TRAILING, DWRITE_TEXT_ALIGNMENT_CENTER);
    let md = DWRITE_FONT_WEIGHT_MEDIUM;
    for (k, f) in [
        ("13", mk_fmt(13.0, n, l)),
        ("13r", mk_fmt(13.0, n, r_)),
        ("13c", mk_fmt(13.0, n, c_)),
        ("11", mk_fmt(11.0, md, l)),
        ("10c", mk_fmt(11.0, DWRITE_FONT_WEIGHT_SEMI_BOLD, c_)),
        ("14b", mk_fmt(13.0, DWRITE_FONT_WEIGHT_BOLD, l)),
        ("12", mk_fmt(12.0, n, l)),
        ("14c", mk_fmt(14.0, n, c_)),
        ("head", mk_fmt(13.0, md, l)),
        ("headr", mk_fmt(13.0, md, r_)),
        ("stat", mk_fmt(13.0, n, l)),
        ("statr", mk_fmt(13.0, n, r_)),
    ] {
        a().tf.insert(k, f);
    }
    unsafe {
        let hi: HINSTANCE = GetModuleHandleW(None).unwrap_or_default().into();
        let wc = WNDCLASSEXW {
            cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
            style: CS_DBLCLKS,
            lpfnWndProc: Some(wnd_proc),
            hInstance: hi,
            hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(),
            lpszClassName: w!("MonitorAtividadeJanela"),
            ..Default::default()
        };
        RegisterClassExW(&wc);
        let mut cur = POINT::default();
        let _ = GetCursorPos(&mut cur);
        let mon = MonitorFromPoint(cur, MONITOR_DEFAULTTONEAREST);
        let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
        let _ = GetMonitorInfoW(mon, &mut mi);
        let (mut dx, mut dy) = (96u32, 96u32);
        let _ = GetDpiForMonitor(mon, MDT_EFFECTIVE_DPI, &mut dx, &mut dy);
        let sc = dx as f32 / 96.0;
        let (ww, hh) = ((1228.0 * sc) as i32, (634.0 * sc) as i32);
        let titulo = wz(&tr_pick("Monitor de Atividade", "Activity Monitor"));
        // fora do modo foto: sem bitmap de redirecionamento, o desenho vai pela Composição (como no C++)
        let ex = if foto.is_none() { WS_EX_NOREDIRECTIONBITMAP } else { WINDOW_EX_STYLE(0) };
        let Ok(h) = CreateWindowExW(ex, w!("MonitorAtividadeJanela"), pc(&titulo), WS_OVERLAPPEDWINDOW, (mi.rcWork.left + mi.rcWork.right - ww) / 2, (mi.rcWork.top + mi.rcWork.bottom - hh) / 2, ww, hh, None, None, hi, None) else {
            std::process::exit(1)
        };
        a().hwnd = h;
        app2d::s().wnd = h;
        if foto.is_none() {
            ampliacao::janela(h);
            let cloak = BOOL(1);
            let _ = DwmSetWindowAttribute(h, DWMWA_CLOAK, &cloak as *const _ as *const c_void, 4);
        }
        if foto.is_none() {
            match comum::tahoe::Gfx::init(h) {
                Some(g) => *GFX.get() = Some(g),
                None => eprintln!("erro: Direct2D sobre a Composição não iniciou"),
            }
        }
        let mg = if GFX.get().is_some() { MARGINS { cxLeftWidth: -1, cxRightWidth: -1, cyTopHeight: -1, cyBottomHeight: -1 } } else { MARGINS { cxLeftWidth: 0, cxRightWidth: 0, cyTopHeight: 1, cyBottomHeight: 0 } };
        let _ = DwmExtendFrameIntoClientArea(h, &mg);
        apply_theme();
        let _ = SetWindowPos(h, None, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
        gpu_init();
        sample();
        std::thread::sleep(std::time::Duration::from_millis(250));
        sample(); // segunda amostra: já com % de CPU
        build_rows();
        if foto.is_some() {
            SetTimer(h, 7, 2000, None);
        } else {
            let _ = ShowWindow(h, SW_SHOWNORMAL);
            SetTimer(h, T_SAMPLE, SAMPLE_MS, None);
            SetTimer(h, 3, 500, None);
        }
        let mut msg = MSG::default();
        while GetMessageW(&mut msg, None, 0, 0).as_bool() {
            let _ = TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
    }
}