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
53.0 KB
Raw Blame
//! info.cpp: "Obter Informações" (Ctrl+I), uma janela por item. Cabeçalho com ícone, nome, tamanho e data; campo de
//! etiquetas; seções que abrem e fecham (Geral, Mais Informações, Nome e Extensão, Comentários, Abrir com,
//! Pré-visualização, Compartilhamento e Permissões). O tamanho de uma pasta é calculado numa thread. "Bloqueado" é o
//! atributo somente leitura. Permissões lidas da DACL; o cadeado reabre a janela como administrador (UAC), onde cada
//! privilégio pode ser trocado.
#![allow(dead_code, non_snake_case)]

use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;

use comum::ctxmenu::Item;
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct2D::Common::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Graphics::Dxgi::Common::*;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::Security::Authorization::*;
use comum::windows::Win32::Security::*;
use comum::windows::Win32::Storage::FileSystem::*;
use comum::windows::Win32::System::Diagnostics::Debug::MessageBeep;
use comum::windows::Win32::System::LibraryLoader::GetModuleHandleW;
use comum::windows::Win32::System::SystemServices::ACCESS_ALLOWED_ACE_TYPE;
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::UI::Controls::{MARGINS, WM_MOUSELEAVE};
use comum::windows::Win32::UI::HiDpi::GetDpiForWindow;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

use crate::tags;

const PAD: f32 = 16.0;
const HDR_ROW: f32 = 24.0;
const ROW: f32 = 17.0;
const WM_INFO_CALC: u32 = WM_APP + 1;
fn wid() -> f32 {
    if semaforo::aqua() {
        301.5
    } else {
        265.0
    }
}
fn title_h() -> f32 {
    if semaforo::aqua() {
        31.5
    } else {
        28.0
    }
}
fn label_x() -> f32 {
    if semaforo::aqua() {
        107.0
    } else {
        92.0
    }
}
const S_GENERAL: usize = 0;
const S_MORE: usize = 1;
const S_NAME: usize = 2;
const S_COMMENTS: usize = 3;
const S_OPENWITH: usize = 4;
const S_PREVIEW: usize = 5;
const S_SHARING: usize = 6;
const S_COUNT: usize = 7;
const SEC_NAMES: [&str; S_COUNT] = ["Geral:", "Mais Informações:", "Nome e Extensão:", "Comentários:", "Abrir com:", "Pré-visualização:", "Compartilhamento e Permissões:"];
const P_NONE: i32 = 0;
const P_READ: i32 = 1;
const P_WRITE: i32 = 2;
const P_RW: i32 = 3;
const PRIV_NAMES: [&str; 4] = ["Sem Acesso", "Somente Leitura", "Somente Gravação", "Leitura e Gravação"];

#[derive(Default)]
struct Calc {
    cancel: AtomicBool,
    done: AtomicBool,
    bytes: AtomicU64,
    disk: AtomicU64,
    items: AtomicU64,
}
#[derive(Clone, Default)]
struct Perm {
    sid: Vec<u8>,
    name: String,
    priv_: i32,
    me: bool,
    inherited: bool,
}
#[derive(Default)]
struct Info {
    hwnd: HWND,
    admin: bool,
    unlocked: bool,
    perms: Vec<Perm>,
    perm_hit: Vec<RectF>,
    lock_hit: RectF,
    rt: Option<ID2D1HwndRenderTarget>,
    path: String,
    name: String,
    kind: String,
    where_: String,
    open_with: String,
    created: String,
    modified: String,
    accessed: String,
    header_date: String,
    size_text: String,
    header_size: String,
    dir: bool,
    read_only: bool,
    can_write: bool,
    is_drive: bool,
    tag_mask: u32,
    open: [bool; S_COUNT],
    calc: Option<Arc<Calc>>,
    icon_px: Option<(u32, u32, Vec<u8>)>,
    prev_px: Option<(u32, u32, Vec<u8>)>,
    icon: Option<ID2D1Bitmap>,
    prev: Option<ID2D1Bitmap>,
    sec_hit: [RectF; S_COUNT],
    locked_hit: RectF,
    press_light: i32,
    active: bool,
    hover_lights: bool,
}
static FAMILY: Global<String> = Global::new(String::new());
static DARK: Global<bool> = Global::new(true);
static STANDALONE: Global<bool> = Global::new(false);

fn fmt(size: f32, w_: DWRITE_FONT_WEIGHT, a: DWRITE_TEXT_ALIGNMENT) -> Option<IDWriteTextFormat> {
    let f = cjk::format(app2d::dw(), &FAMILY.get().clone(), w_, DWRITE_FONT_STYLE_NORMAL, size, "pt-br")?;
    unsafe {
        let _ = f.SetTextAlignment(a);
        let _ = f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
    }
    Some(f)
}
fn trim_ellipsis(f: &IDWriteTextFormat) {
    unsafe {
        let _ = f.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
        let tr_ = DWRITE_TRIMMING { granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER, delimiter: 0, delimiterCount: 0 };
        if let Ok(el) = app2d::dw().CreateEllipsisTrimmingSign(f) {
            let _ = f.SetTrimming(&tr_, &el);
        }
    }
}
// ---- textos
fn thousands(v: u64) -> String {
    let s_ = v.to_string();
    let mut out = String::new();
    for (i, c) in s_.chars().enumerate() {
        if i > 0 && (s_.len() - i) % 3 == 0 {
            out.push('.');
        }
        out.push(c);
    }
    out
}
/// unidades decimais, como no Mac: 999 bytes, 16 KB, 1,2 MB, 12,5 GB
fn human(b: u64) -> String {
    if b < 1000 {
        return format!("{b}{}", tr(if b == 1 { " byte" } else { " bytes" }));
    }
    let u = ["KB", "MB", "GB", "TB"];
    let (mut v, mut k) = (b as f64, -1i32);
    while v >= 1000.0 && k < 3 {
        v /= 1000.0;
        k += 1;
    }
    let t = if k == 0 || v >= 100.0 { format!("{v:.0} {}", u[k as usize]) } else { format!("{v:.1} {}", u[k as usize]) };
    t.replace('.', ",")
}
fn ft_u64(f: &FILETIME) -> u64 {
    (f.dwHighDateTime as u64) << 32 | f.dwLowDateTime as u64
}
fn full_date(ft: &FILETIME) -> String {
    if ft_u64(ft) == 0 {
        return "--".into();
    }
    let st = crate::base::local_st(ft_u64(ft));
    format!("{}{}{:02}:{:02}", idioma::date(&st, idioma::D_LONG), tr(" às "), st.wHour, st.wMinute)
}
/// cabeçalho: "Hoje, 18:20", "Ontem, 09:02" ou a data
fn short_date(ft: &FILETIME) -> String {
    let st = crate::base::local_st(ft_u64(ft));
    let now = app2d::local_now();
    let day = |s_: &SYSTEMTIME| app2d::day_start(app2d::to_min(s_));
    let days = (day(&now) - day(&st)) / 1440;
    let t = format!("{:02}:{:02}", st.wHour, st.wMinute);
    match days {
        0 => format!("{}{t}", tr("Hoje, ")),
        1 => format!("{}{t}", tr("Ontem, ")),
        _ => full_date(ft),
    }
}
fn cluster(path: &str) -> u64 {
    unsafe {
        let pw = wz(path);
        let mut root = [0u16; 260];
        if GetVolumePathNameW(pc(&pw), &mut root).is_err() {
            return 4096;
        }
        let (mut spc, mut bps, mut fc, mut tc) = (0u32, 0u32, 0u32, 0u32);
        if GetDiskFreeSpaceW(PCWSTR(root.as_ptr()), Some(&mut spc), Some(&mut bps), Some(&mut fc), Some(&mut tc)).is_err() {
            return 4096;
        }
        spc as u64 * bps as u64
    }
}
fn on_disk(bytes: u64, cl: u64) -> u64 {
    if cl > 0 {
        bytes.div_ceil(cl) * cl
    } else {
        bytes
    }
}
fn walk(dir: &str, c: &Calc, cl: u64) {
    let Ok(rd) = std::fs::read_dir(dir) else { return };
    for e in rd.flatten() {
        if c.cancel.load(Ordering::Relaxed) {
            break;
        }
        let Ok(md) = e.metadata() else { continue };
        use std::os::windows::fs::MetadataExt;
        c.items.fetch_add(1, Ordering::Relaxed);
        if !md.is_dir() {
            c.bytes.fetch_add(md.len(), Ordering::Relaxed);
            c.disk.fetch_add(on_disk(md.len(), cl), Ordering::Relaxed);
        } else if md.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT.0 == 0 {
            walk(&e.path().to_string_lossy(), c, cl);
        }
    }
}
// ---- permissões (DACL)
unsafe fn sid_name(sid: PSID) -> String {
    let (mut name, mut dom) = ([0u16; 256], [0u16; 256]);
    let (mut nn, mut dn) = (256u32, 256u32);
    let mut use_ = SID_NAME_USE::default();
    if LookupAccountSidW(PCWSTR::null(), sid, PWSTR(name.as_mut_ptr()), &mut nn, PWSTR(dom.as_mut_ptr()), &mut dn, &mut use_).is_ok() {
        let n = from_w(&name);
        return match n.as_str() {
            "Everyone" | "Todos" => "todos".into(),
            "Users" | "Usuários" => "usuários".into(),
            "Administrators" | "Administradores" => "administradores".into(),
            "SYSTEM" | "SISTEMA" => "sistema".into(),
            "Authenticated Users" | "Usuários autenticados" => "usuários autenticados".into(),
            _ => n,
        };
    }
    sid_string(sid).unwrap_or_else(|| tr("(desconhecido)"))
}
unsafe fn sid_string(sid: PSID) -> Option<String> {
    let mut p = PWSTR::null();
    ConvertSidToStringSidW(sid, &mut p).ok()?;
    let r = p.to_string().ok();
    let _ = LocalFree(HLOCAL(p.0 as *mut c_void));
    r
}
unsafe fn current_user_sid() -> Vec<u8> {
    let mut tok = HANDLE::default();
    if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut tok).is_err() {
        return Vec::new();
    }
    let mut n = 0u32;
    let _ = GetTokenInformation(tok, TokenUser, None, 0, &mut n);
    let mut buf = vec![0u8; n as usize];
    let mut out = Vec::new();
    if n > 0 && GetTokenInformation(tok, TokenUser, Some(buf.as_mut_ptr() as *mut c_void), n, &mut n).is_ok() {
        let s_ = (*(buf.as_ptr() as *const TOKEN_USER)).User.Sid;
        out = std::slice::from_raw_parts(s_.0 as *const u8, GetLengthSid(s_) as usize).to_vec();
    }
    let _ = CloseHandle(tok);
    out
}
fn gather_perms(inf: &mut Info) {
    inf.perms.clear();
    unsafe {
        let pw = wz(&inf.path);
        let (mut owner, mut dacl, mut sd) = (PSID::default(), std::ptr::null_mut::<ACL>(), PSECURITY_DESCRIPTOR::default());
        if GetNamedSecurityInfoW(pc(&pw), SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, Some(&mut owner), None, Some(&mut dacl), None, &mut sd).is_err() {
            return;
        }
        let me = current_user_sid();
        let add = |perms: &mut Vec<Perm>, sid: PSID| -> usize {
            if let Some(i) = perms.iter().position(|p| EqualSid(PSID(p.sid.as_ptr() as *mut c_void), sid).is_ok()) {
                return i;
            }
            let v = std::slice::from_raw_parts(sid.0 as *const u8, GetLengthSid(sid) as usize).to_vec();
            let is_me = !me.is_empty() && EqualSid(sid, PSID(me.as_ptr() as *mut c_void)).is_ok();
            perms.push(Perm { sid: v, name: sid_name(sid), priv_: P_NONE, me: is_me, inherited: false });
            perms.len() - 1
        };
        if !owner.0.is_null() {
            add(&mut inf.perms, owner); // o dono primeiro, como no Mac
        }
        if !dacl.is_null() {
            for i in 0..(*dacl).AceCount as u32 {
                let mut h: *mut c_void = std::ptr::null_mut();
                if GetAce(dacl, i, &mut h).is_err() {
                    continue;
                }
                let hdr = &*(h as *const ACE_HEADER);
                if hdr.AceType as u32 != ACCESS_ALLOWED_ACE_TYPE || hdr.AceFlags as u32 & INHERIT_ONLY_ACE.0 != 0 {
                    continue; // só o que vale para o próprio item
                }
                let a = &*(h as *const ACCESS_ALLOWED_ACE);
                let sid = PSID(&a.SidStart as *const u32 as *mut c_void);
                let ss = sid_string(sid).unwrap_or_default();
                if ss.starts_with("S-1-15-") || ss == "S-1-5-18" || ss.starts_with("S-1-5-80-") {
                    continue; // apps, sistema, serviços
                }
                let k = add(&mut inf.perms, sid);
                let m = a.Mask;
                let r = m & (FILE_READ_DATA.0 | GENERIC_READ.0 | GENERIC_ALL.0) != 0;
                let w_ = m & (FILE_WRITE_DATA.0 | GENERIC_WRITE.0 | GENERIC_ALL.0) != 0;
                let pv = if r && w_ {
                    P_RW
                } else if r {
                    P_READ
                } else if w_ {
                    P_WRITE
                } else {
                    P_NONE
                };
                let p = &mut inf.perms[k];
                if pv == P_RW || (pv == P_READ && p.priv_ == P_WRITE) || (pv == P_WRITE && p.priv_ == P_READ) {
                    p.priv_ = P_RW;
                } else if p.priv_ == P_NONE {
                    p.priv_ = pv;
                }
                if hdr.AceFlags as u32 & INHERITED_ACE.0 != 0 {
                    p.inherited = true;
                }
            }
        }
        if !sd.0.is_null() {
            let _ = LocalFree(HLOCAL(sd.0));
        }
    }
    inf.perms.truncate(6);
}
/// troca o privilégio de alguém (precisa de administrador); false se o Windows recusar
fn set_priv(path: &str, dir: bool, sid: &[u8], priv_: i32) -> bool {
    unsafe {
        let pw = wz(path);
        let (mut dacl, mut sd) = (std::ptr::null_mut::<ACL>(), PSECURITY_DESCRIPTOR::default());
        if GetNamedSecurityInfoW(pc(&pw), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, None, None, Some(&mut dacl), None, &mut sd).is_err() {
            return false;
        }
        let perms = match priv_ {
            P_RW => FILE_GENERIC_READ.0 | FILE_GENERIC_WRITE.0 | FILE_GENERIC_EXECUTE.0 | DELETE.0,
            P_READ => FILE_GENERIC_READ.0 | FILE_GENERIC_EXECUTE.0,
            P_WRITE => FILE_GENERIC_WRITE.0,
            _ => 0,
        };
        let ea = EXPLICIT_ACCESS_W {
            grfAccessPermissions: perms,
            grfAccessMode: if priv_ == P_NONE { REVOKE_ACCESS } else { SET_ACCESS },
            grfInheritance: if dir { SUB_CONTAINERS_AND_OBJECTS_INHERIT } else { NO_INHERITANCE },
            Trustee: TRUSTEE_W { TrusteeForm: TRUSTEE_IS_SID, TrusteeType: TRUSTEE_IS_UNKNOWN, ptstrName: PWSTR(sid.as_ptr() as *mut u16), ..Default::default() },
        };
        let mut nd: *mut ACL = std::ptr::null_mut();
        let mut ok = SetEntriesInAclW(Some(&[ea]), Some(dacl), &mut nd).is_ok();
        if ok {
            ok = SetNamedSecurityInfoW(pc(&pw), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, PSID::default(), PSID::default(), Some(nd), None).is_ok();
        }
        if !nd.is_null() {
            let _ = LocalFree(HLOCAL(nd as *mut c_void));
        }
        if !sd.0.is_null() {
            let _ = LocalFree(HLOCAL(sd.0));
        }
        ok
    }
}
// ---- dados do item
fn gather(inf: &mut Info) {
    let p = inf.path.clone();
    inf.is_drive = (2..=3).contains(&p.chars().count()) && p.chars().nth(1) == Some(':');
    let pw = wz(&p);
    unsafe {
        let mut sfi = SHFILEINFOW::default();
        if SHGetFileInfoW(pc(&pw), FILE_FLAGS_AND_ATTRIBUTES(0), Some(&mut sfi), std::mem::size_of::<SHFILEINFOW>() as u32, SHGFI_DISPLAYNAME | SHGFI_TYPENAME) != 0 {
            inf.name = from_w(&sfi.szDisplayName);
            inf.kind = from_w(&sfi.szTypeName);
        }
        if !inf.is_drive {
            inf.name = crate::base::file_name(&p);
        }
        let mut fa = WIN32_FILE_ATTRIBUTE_DATA::default();
        let _ = GetFileAttributesExW(pc(&pw), GetFileExInfoStandard, &mut fa as *mut _ as *mut c_void);
        inf.dir = fa.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY.0 != 0;
        inf.read_only = !inf.dir && fa.dwFileAttributes & FILE_ATTRIBUTE_READONLY.0 != 0;
        if inf.dir && !inf.is_drive {
            inf.kind = tr("Pasta");
        }
        if inf.is_drive {
            inf.kind = tr("Volume");
        }
        inf.where_ = if inf.is_drive { tr("Este Computador") } else { crate::base::parent(&p) };
        inf.created = full_date(&fa.ftCreationTime);
        inf.modified = full_date(&fa.ftLastWriteTime);
        inf.accessed = full_date(&fa.ftLastAccessTime);
        inf.header_date = format!("{}{}", tr("Modificado: "), short_date(&fa.ftLastWriteTime));
        inf.tag_mask = tags::read(&p);
        if inf.is_drive {
            let (mut free, mut total, mut tfree) = (0u64, 0u64, 0u64);
            let _ = GetDiskFreeSpaceExW(pc(&pw), Some(&mut free), Some(&mut total), Some(&mut tfree));
            inf.header_size = human(total);
            inf.size_text = format!("{} ({}{}", human(total), human(tfree), tr(" disponíveis)"));
        } else if inf.dir {
            inf.header_size = "--".into();
            inf.size_text = tr("Calculando…");
        } else {
            let sz = (fa.nFileSizeHigh as u64) << 32 | fa.nFileSizeLow as u64;
            inf.header_size = human(sz);
            inf.size_text = format!("{}{}{}{}", thousands(sz), tr(" bytes ("), human(on_disk(sz, cluster(&p))), tr(" no disco)"));
            let ext = std::path::Path::new(&p).extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
            let mut app = [0u16; 260];
            let mut n = 260u32;
            let ew = wz(&ext);
            inf.open_with = if !ext.is_empty() && AssocQueryStringW(ASSOCF_INIT_IGNOREUNKNOWN, ASSOCSTR_FRIENDLYAPPNAME, pc(&ew), w!("open"), PWSTR(app.as_mut_ptr()), &mut n).is_ok() { from_w(&app) } else { tr("Nenhum aplicativo") };
        }
        // permissões: tenta abrir para escrita sem mexer em nada
        let acc = if inf.dir { FILE_ADD_FILE.0 } else { FILE_WRITE_DATA.0 };
        let hf = CreateFileW(pc(&pw), acc, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, None, OPEN_EXISTING, if inf.dir { FILE_FLAG_BACKUP_SEMANTICS } else { FILE_FLAGS_AND_ATTRIBUTES(0) }, None);
        inf.can_write = hf.is_ok();
        if let Ok(h) = hf {
            let _ = CloseHandle(h);
        }
    }
    gather_perms(inf);
    // ícone e pré-visualização: pasta azul do pacote do Sequoia; arquivo: miniatura do Windows
    let pack = install_dir().join("icones").join("sequoia").join("folder default.png");
    if inf.dir && !inf.is_drive {
        if let Some(px) = crate::desenho::png_pixels(&pack) {
            inf.prev_px = Some(px.clone());
            inf.icon_px = Some(px);
        }
    }
    if inf.icon_px.is_none() {
        inf.icon_px = shell_thumbnail(&p, 64, SIIGBF(0));
        inf.prev_px = shell_thumbnail(&p, 256, SIIGBF(0));
    }
}
// ---- layout e desenho
/// valores longos quebram linha, como no Mac
fn value_h(v: &str) -> f32 {
    let Some(tf) = fmt(11.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING) else { return ROW };
    unsafe {
        let _ = tf.SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
        let vw = w(v);
        if let Ok(lay) = app2d::dw().CreateTextLayout(&vw, &tf, wid() - PAD - label_x(), 400.0) {
            let mut m = DWRITE_TEXT_METRICS::default();
            let _ = lay.GetMetrics(&mut m);
            return ROW.max(m.height + 3.0);
        }
    }
    ROW
}
fn section_body_h(inf: &Info, k: usize) -> f32 {
    match k {
        S_GENERAL => value_h(&inf.kind) + value_h(&inf.size_text) + value_h(&inf.where_) + value_h(&inf.created) + value_h(&inf.modified) + 8.0 + if inf.dir { 0.0 } else { 22.0 } + 6.0,
        S_MORE => value_h(&inf.accessed) + 8.0,
        S_NAME => 26.0 + 22.0 + 6.0,
        S_COMMENTS => 50.0,
        S_OPENWITH => ROW + 8.0,
        S_PREVIEW => 150.0,
        S_SHARING => ROW + 6.0 + 20.0 + inf.perms.len().max(1) as f32 * 19.0 + 8.0 + 24.0 + 6.0,
        _ => 0.0,
    }
}
fn has_section(inf: &Info, k: usize) -> bool {
    k != S_OPENWITH || !inf.dir
}
fn content_height(inf: &Info) -> f32 {
    let mut y = title_h() + 8.0 + 44.0 + 34.0;
    for k in 0..S_COUNT {
        if !has_section(inf, k) {
            continue;
        }
        y += HDR_ROW;
        if inf.open[k] {
            y += section_body_h(inf, k);
        }
    }
    y + 10.0
}
unsafe fn txt(rt: &ID2D1RenderTarget, b: &ID2D1SolidColorBrush, t: &str, tf: &Option<IDWriteTextFormat>, r: RectF, c: Cor) {
    let Some(tf) = tf else { return };
    if t.is_empty() {
        return;
    }
    b.SetColor(&c);
    let tw = w(t);
    rt.DrawText(&tw, tf, &r, b, D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
}
unsafe fn chevron(rt: &ID2D1RenderTarget, b: &ID2D1SolidColorBrush, cx: f32, cy: f32, open: bool) {
    let (a, m, c) = if open { (pt(cx - 3.5, cy - 1.8), pt(cx, cy + 1.8), pt(cx + 3.5, cy - 1.8)) } else { (pt(cx - 1.8, cy - 3.5), pt(cx + 1.8, cy), pt(cx - 1.8, cy + 3.5)) };
    rt.DrawLine(a, m, b, 1.4, None);
    rt.DrawLine(m, c, b, 1.4, None);
}
unsafe fn checkbox(rt: &ID2D1RenderTarget, b: &ID2D1SolidColorBrush, x: f32, cy: f32, on: bool, enabled: bool, dark: bool) {
    let r = rf(x, cy - 7.0, x + 14.0, cy + 7.0);
    if on {
        b.SetColor(&if enabled { col(0.04, 0.47, 1.0, 1.0) } else { col(0.5, 0.5, 0.5, 0.5) });
        rt.FillRoundedRectangle(&rr(r, 3.5, 3.5), b);
        b.SetColor(&col(1.0, 1.0, 1.0, 1.0));
        rt.DrawLine(pt(x + 3.5, cy), pt(x + 6.0, cy + 3.0), b, 1.6, None);
        rt.DrawLine(pt(x + 6.0, cy + 3.0), pt(x + 10.5, cy - 3.5), b, 1.6, None);
    } else {
        b.SetColor(&if dark { col(1.0, 1.0, 1.0, if enabled { 0.12 } else { 0.06 }) } else { col(1.0, 1.0, 1.0, 1.0) });
        rt.FillRoundedRectangle(&rr(r, 3.5, 3.5), b);
        b.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.22) } else { col(0.0, 0.0, 0.0, 0.22) });
        rt.DrawRoundedRectangle(&rr(inflate(r, -0.5), 3.0, 3.0), b, 1.0, None);
    }
}
unsafe fn light_cx(k: i32) -> f32 {
    (if semaforo::aqua() { 15.75 } else { 19.0 }) + k as f32 * 23.0
}
fn light_cy() -> f32 {
    if semaforo::aqua() {
        15.75
    } else {
        14.0
    }
}
unsafe fn to_bitmap(rt: &ID2D1RenderTarget, px: &Option<(u32, u32, Vec<u8>)>) -> Option<ID2D1Bitmap> {
    let (w_, h, v) = px.as_ref()?;
    bitmap_bgra(rt, *w_, *h, v)
}
unsafe fn paint(inf: &mut Info, rt: &ID2D1RenderTarget) {
    inf.perm_hit.clear();
    let z = rf(0.0, 0.0, 0.0, 0.0);
    inf.lock_hit = z;
    inf.locked_hit = z;
    let dark = *DARK.get();
    let ww = wid();
    rt.Clear(Some(&if dark { col(0.157, 0.157, 0.165, 1.0) } else { col(0.925, 0.925, 0.93, 1.0) }));
    let Ok(b) = rt.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None) else { return };
    let text_c = if dark { col(1.0, 1.0, 1.0, 0.88) } else { col(0.0, 0.0, 0.0, 0.85) };
    let text2 = if dark { col(1.0, 1.0, 1.0, 0.55) } else { col(0.0, 0.0, 0.0, 0.50) };
    let line_c = if dark { col(1.0, 1.0, 1.0, 0.10) } else { col(0.0, 0.0, 0.0, 0.10) };
    // bolinhas: fechar e minimizar ativas; ampliar desligada (a janela tem tamanho fixo)
    let fill = semaforo::pick([col(1.0, 0.373, 0.345, 1.0), col(0.996, 0.737, 0.18, 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);
    for k in 0..3 {
        let c = pt(light_cx(k), light_cy());
        let lit = k < 2 && (inf.active || inf.hover_lights);
        b.SetColor(&if lit { fill[k as usize] } else if dark { col(0.30, 0.30, 0.31, 1.0) } else { col(0.84, 0.84, 0.84, 1.0) });
        rt.FillEllipse(&ell(c, 7.0, 7.0), &b);
        semaforo::gloss(rt, c, 7.0, &b);
        b.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), &b, 0.5, None);
        if inf.hover_lights && k < 2 {
            b.SetColor(&if semaforo::grafite() { col(0.20, 0.20, 0.21, 1.0) } else if k == 0 { col(0.302, 0.0, 0.0, 1.0) } else { col(0.6, 0.341, 0.0, 1.0) });
            if k == 0 {
                rt.DrawLine(pt(c.x - 2.5, c.y - 2.5), pt(c.x + 2.5, c.y + 2.5), &b, 1.1, None);
                rt.DrawLine(pt(c.x - 2.5, c.y + 2.5), pt(c.x + 2.5, c.y - 2.5), &b, 1.1, None);
            } else {
                rt.DrawLine(pt(c.x - 3.3, c.y), pt(c.x + 3.3, c.y), &b, 1.2, None);
            }
        }
    }
    {
        // título centrado na janela inteira (as bolinhas ficam fora); nome longo é cortado no meio
        let t_title = fmt(13.0, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING);
        if let Some(f) = &t_title {
            trim_ellipsis(f);
        }
        let nm: Vec<char> = inf.name.chars().collect();
        let pre = tr("Informações de ");
        let mut t = format!("{pre}{}", inf.name);
        let max_w = ww - 80.0 - 10.0 - 2.0;
        let width = |x: &str| t_title.as_ref().map(|f| crate::desenho::text_width(x, f)).unwrap_or(0.0);
        if width(&t) > max_w {
            let mut keep = nm.len();
            while keep > 2 {
                let (head, tail) = ((keep + 1) / 2, keep / 2);
                t = format!("{pre}{}…{}", nm[..head].iter().collect::<String>(), nm[nm.len() - tail..].iter().collect::<String>());
                if width(&t) <= max_w {
                    break;
                }
                keep -= 1;
            }
        }
        let x0 = 80f32.max((ww - width(&t)) / 2.0); // se bater nas bolinhas, desliza para a direita (como no Mac)
        txt(rt, &b, &t, &t_title, rf(x0, 6.0, ww - 8.0, 24.0), if inf.active { text_c } else { text2 });
    }
    // cabeçalho: ícone 32, nome em negrito, tamanho à direita, data embaixo
    let mut y = title_h() + 8.0;
    if inf.icon.is_none() {
        inf.icon = to_bitmap(rt, &inf.icon_px);
    }
    if let Some(ic) = &inf.icon {
        let sz = ic.GetPixelSize();
        let s_ = 32.0;
        let k = (s_ / sz.width as f32).min(s_ / sz.height as f32);
        let (dw, dh) = (sz.width as f32 * k, sz.height as f32 * k);
        rt.DrawBitmap(ic, Some(&rf(PAD + (s_ - dw) / 2.0, y + (s_ - dh) / 2.0, PAD + (s_ + dw) / 2.0, y + (s_ + dh) / 2.0)), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
    }
    let t_name = fmt(13.0, DWRITE_FONT_WEIGHT_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING);
    let t_size_r = fmt(13.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_TRAILING);
    let t_small = fmt(11.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING);
    let t_label = fmt(11.0, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_TRAILING);
    let t_sec = fmt(11.0, DWRITE_FONT_WEIGHT_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING);
    for f in [&t_name, &t_small].into_iter().flatten() {
        trim_ellipsis(f);
    }
    let size_w = 70.0;
    txt(rt, &b, &inf.header_size, &t_size_r, rf(ww - PAD - size_w, y, ww - PAD, y + 18.0), text_c);
    txt(rt, &b, &inf.name, &t_name, rf(PAD + 40.0, y, ww - PAD - size_w - 4.0, y + 18.0), text_c);
    txt(rt, &b, &inf.header_date, &t_small, rf(PAD + 40.0, y + 19.0, ww - PAD, y + 34.0), text2);
    y += 44.0;
    // etiquetas: campo com as bolinhas atuais ou o texto de ajuda
    let tag_field = rf(PAD, y, ww - PAD, y + 22.0);
    b.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.07) } else { col(1.0, 1.0, 1.0, 1.0) });
    rt.FillRoundedRectangle(&rr(tag_field, 5.0, 5.0), &b);
    b.SetColor(&line_c);
    rt.DrawRoundedRectangle(&rr(inflate(tag_field, -0.5), 4.5, 4.5), &b, 1.0, None);
    let mut tx = tag_field.left + 8.0;
    let mut any = false;
    for t in 0..tags::COUNT {
        if inf.tag_mask & (1 << t) == 0 {
            continue;
        }
        any = true;
        b.SetColor(&crate::rgb_u32(tags::color(t)));
        rt.FillEllipse(&ell(pt(tx + 5.0, y + 11.0), 5.0, 5.0), &b);
        let nm = tr(tags::NAMES[t]);
        let lw = t_small.as_ref().map(|f| crate::desenho::text_width(&nm, f)).unwrap_or(30.0);
        txt(rt, &b, &nm, &t_small, rf(tx + 13.0, y + 4.0, tag_field.right - 4.0, y + 20.0), text_c);
        tx += 13.0 + lw + 10.0;
    }
    if !any {
        txt(rt, &b, &tr("Adicionar Etiquetas…"), &t_small, rf(tag_field.left + 8.0, y + 4.0, tag_field.right - 6.0, y + 20.0), text2);
    }
    y += 34.0;
    // seções
    let row = |label: &str, value: &str, yy: f32| -> f32 {
        let vh = value_h(value);
        txt(rt, &b, label, &t_label, rf(PAD, yy, label_x() - 4.0, yy + ROW), text_c);
        let tv = fmt(11.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING);
        if let Some(f) = &tv {
            let _ = f.SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
        }
        txt(rt, &b, value, &tv, rf(label_x(), yy, ww - PAD, yy + vh), text_c);
        vh
    };
    for k in 0..S_COUNT {
        if !has_section(inf, k) {
            inf.sec_hit[k] = z;
            continue;
        }
        b.SetColor(&line_c);
        rt.DrawLine(pt(PAD - 4.0, y + 0.5), pt(ww - PAD + 4.0, y + 0.5), &b, 1.0, None);
        inf.sec_hit[k] = rf(0.0, y, ww, y + HDR_ROW);
        b.SetColor(&text2);
        chevron(rt, &b, PAD + 1.0, y + HDR_ROW / 2.0, inf.open[k]);
        txt(rt, &b, &tr(SEC_NAMES[k]), &t_sec, rf(PAD + 12.0, y + 5.0, ww - PAD, y + HDR_ROW), text_c);
        y += HDR_ROW;
        if !inf.open[k] {
            continue;
        }
        let mut yy = y + 2.0;
        match k {
            S_GENERAL => {
                yy += row(&tr("Tipo:"), &inf.kind, yy);
                yy += row(&tr("Tamanho:"), &inf.size_text, yy);
                yy += row(&tr("Onde:"), &inf.where_, yy);
                yy += row(&tr("Criado:"), &inf.created, yy);
                yy += row(&tr("Modificado:"), &inf.modified, yy) + 6.0;
                if !inf.dir {
                    checkbox(rt, &b, label_x(), yy + 8.0, inf.read_only, true, dark);
                    inf.locked_hit = rf(label_x() - 2.0, yy, label_x() + 90.0, yy + 16.0);
                    txt(rt, &b, &tr("Bloqueado"), &t_small, rf(label_x() + 20.0, yy + 1.0, ww - PAD, yy + 17.0), text_c);
                }
            }
            S_MORE => {
                row(&tr("Última abertura:"), &inf.accessed, yy);
            }
            S_NAME => {
                let f = rf(PAD, yy, ww - PAD, yy + 22.0);
                b.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.07) } else { col(1.0, 1.0, 1.0, 1.0) });
                rt.FillRoundedRectangle(&rr(f, 5.0, 5.0), &b);
                txt(rt, &b, &inf.name, &t_small, rf(f.left + 7.0, yy + 4.0, f.right - 6.0, yy + 20.0), text_c);
                checkbox(rt, &b, PAD, yy + 37.0, false, false, dark);
                txt(rt, &b, &tr("Ocultar extensão"), &t_small, rf(PAD + 20.0, yy + 29.0, ww - PAD, yy + 45.0), text2);
            }
            S_COMMENTS => {
                b.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.07) } else { col(1.0, 1.0, 1.0, 1.0) });
                rt.FillRoundedRectangle(&rr(rf(PAD, yy, ww - PAD, yy + 40.0), 5.0, 5.0), &b);
            }
            S_OPENWITH => {
                row(&tr("Aplicativo:"), &inf.open_with, yy);
            }
            S_PREVIEW => {
                if inf.prev.is_none() {
                    inf.prev = to_bitmap(rt, &inf.prev_px);
                }
                if let Some(pv) = &inf.prev {
                    let sz = pv.GetPixelSize();
                    let bx = 128.0;
                    let k2 = (bx / sz.width as f32).min(bx / sz.height as f32);
                    let (dw, dh, cx, cy) = (sz.width as f32 * k2, sz.height as f32 * k2, ww / 2.0, yy + 70.0);
                    rt.DrawBitmap(pv, Some(&rf(cx - dw / 2.0, cy - dh / 2.0, cx + dw / 2.0, cy + dh / 2.0)), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
                }
            }
            _ => {
                // Compartilhamento e Permissões
                txt(rt, &b, &tr(if inf.can_write { "Você pode ler e gravar" } else { "Você só pode ler" }), &t_small, rf(PAD, yy, ww - PAD, yy + ROW), text_c);
                let ty = yy + ROW + 6.0;
                let bx = rf(PAD, ty, ww - PAD, ty + 20.0 + inf.perms.len().max(1) as f32 * 19.0);
                b.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.05) } else { col(1.0, 1.0, 1.0, 1.0) });
                rt.FillRoundedRectangle(&rr(bx, 4.0, 4.0), &b);
                b.SetColor(&line_c);
                rt.DrawRoundedRectangle(&rr(inflate(bx, -0.5), 3.5, 3.5), &b, 1.0, None);
                let colx = PAD + (ww - 2.0 * PAD) * 0.44; // coluna do privilégio cabe "Leitura e Gravação"
                let th = fmt(11.0, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING);
                txt(rt, &b, &tr("Nome"), &th, rf(PAD + 8.0, ty + 3.0, colx - 4.0, ty + 18.0), text2);
                txt(rt, &b, &tr("Privilégio"), &th, rf(colx + 6.0, ty + 3.0, ww - PAD - 4.0, ty + 18.0), text2);
                b.SetColor(&line_c);
                rt.DrawLine(pt(PAD, ty + 20.5), pt(ww - PAD, ty + 20.5), &b, 1.0, None);
                rt.DrawLine(pt(colx + 0.5, ty + 3.0), pt(colx + 0.5, bx.bottom - 3.0), &b, 1.0, None);
                let editable = inf.admin && inf.unlocked;
                for (kk, pm) in inf.perms.iter().enumerate() {
                    let ry = ty + 21.0 + kk as f32 * 19.0;
                    b.SetColor(&text2); // pessoa (cabeça + ombros)
                    rt.FillEllipse(&ell(pt(PAD + 14.0, ry + 7.0), 2.6, 2.6), &b);
                    rt.FillRoundedRectangle(&rr(rf(PAD + 9.5, ry + 10.5, PAD + 18.5, ry + 15.0), 2.5, 2.5), &b);
                    let nm = format!("{}{}", pm.name, if pm.me { tr(" (Eu)") } else { String::new() });
                    txt(rt, &b, &nm, &t_small, rf(PAD + 24.0, ry + 2.0, colx - 4.0, ry + 18.0), text_c);
                    let pr = rf(colx + 4.0, ry + 1.0, ww - PAD - 3.0, ry + 18.0);
                    inf.perm_hit.push(pr);
                    txt(rt, &b, &tr(PRIV_NAMES[pm.priv_ as usize]), &t_small, rf(pr.left + 4.0, ry + 2.0, pr.right - 12.0, ry + 18.0), if editable { text_c } else { text2 });
                    if editable {
                        b.SetColor(&text2); // setinhas do menu de privilégio
                        let (ax, ay) = (pr.right - 6.0, ry + 9.5);
                        rt.DrawLine(pt(ax - 2.5, ay - 1.0), pt(ax, ay - 3.5), &b, 1.1, None);
                        rt.DrawLine(pt(ax, ay - 3.5), pt(ax + 2.5, ay - 1.0), &b, 1.1, None);
                        rt.DrawLine(pt(ax - 2.5, ay + 1.0), pt(ax, ay + 3.5), &b, 1.1, None);
                        rt.DrawLine(pt(ax, ay + 3.5), pt(ax + 2.5, ay + 1.0), &b, 1.1, None);
                    }
                }
                // cadeado embaixo à direita: fechado = pede a senha; aberto = pode alterar
                let (ly, lx) = (bx.bottom + 8.0, ww - PAD - 14.0);
                inf.lock_hit = rf(lx - 6.0, ly - 2.0, lx + 18.0, ly + 20.0);
                b.SetColor(&text2);
                rt.FillRoundedRectangle(&rr(rf(lx, ly + 7.0, lx + 12.0, ly + 16.0), 1.5, 1.5), &b);
                if let Ok(g) = app2d::d2d().CreatePathGeometry() {
                    if let Ok(sk) = g.Open() {
                        let sx = if editable { lx + 8.0 } else { lx + 2.0 }; // aberto: a alça sobe para a direita
                        sk.BeginFigure(pt(sx + 1.5, if editable { ly + 3.0 } else { ly + 7.0 }), D2D1_FIGURE_BEGIN_HOLLOW);
                        sk.AddLine(pt(sx + 1.5, ly + 3.5));
                        sk.AddArc(&D2D1_ARC_SEGMENT { point: pt(sx + 6.5, ly + 3.5), size: D2D_SIZE_F { width: 2.5, height: 2.5 }, rotationAngle: 0.0, sweepDirection: D2D1_SWEEP_DIRECTION_CLOCKWISE, arcSize: D2D1_ARC_SIZE_SMALL });
                        sk.AddLine(pt(sx + 6.5, ly + 7.0));
                        sk.EndFigure(D2D1_FIGURE_END_OPEN);
                        let _ = sk.Close();
                        rt.DrawGeometry(&g, &b, 1.5, None);
                    }
                }
                let hint = fmt(10.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING);
                if let Some(f) = &hint {
                    let _ = f.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
                }
                txt(rt, &b, &tr(if editable { "Clique no cadeado para impedir alterações." } else { "Clique no cadeado para fazer alterações." }), &hint, rf(PAD, ly + 4.0, lx - 4.0, ly + 19.0), text2);
            }
        }
        y += section_body_h(inf, k);
    }
}
fn scale(h: HWND) -> f32 {
    unsafe { GetDpiForWindow(h) as f32 / 96.0 }
}
fn fit_height(inf: &Info) {
    let sc = scale(inf.hwnd);
    unsafe {
        let mut r = RECT::default();
        let _ = GetWindowRect(inf.hwnd, &mut r);
        let hpx = (content_height(inf) * sc).round() as i32;
        if r.bottom - r.top != hpx {
            let _ = SetWindowPos(inf.hwnd, None, 0, 0, r.right - r.left, hpx, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
        }
    }
}
fn ensure_target(inf: &mut Info) {
    if inf.rt.is_some() {
        return;
    }
    unsafe {
        let mut rc = RECT::default();
        let _ = GetClientRect(inf.hwnd, &mut rc);
        let dpi = GetDpiForWindow(inf.hwnd) as f32;
        let p = 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: inf.hwnd, pixelSize: D2D_SIZE_U { width: rc.right as u32, height: rc.bottom as u32 }, presentOptions: D2D1_PRESENT_OPTIONS_NONE };
        inf.rt = app2d::d2d().CreateHwndRenderTarget(&p, &hp).ok();
        if let Some(rt) = &inf.rt {
            rt.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
        }
    }
}
fn start_calc(inf: &mut Info) {
    if !inf.dir || inf.is_drive {
        return;
    }
    let c = Arc::new(Calc::default());
    inf.calc = Some(c.clone());
    let (p, h) = (inf.path.clone(), inf.hwnd.0 as isize);
    std::thread::spawn(move || {
        let cl = cluster(&p);
        let stop = Arc::new(AtomicBool::new(false));
        let (st2, c2) = (stop.clone(), c.clone());
        // atualizações parciais a cada 300 ms enquanto conta
        let ticker = std::thread::spawn(move || {
            while !st2.load(Ordering::Relaxed) {
                std::thread::sleep(std::time::Duration::from_millis(300));
                if !st2.load(Ordering::Relaxed) && !c2.cancel.load(Ordering::Relaxed) {
                    unsafe {
                        let _ = PostMessageW(HWND(h as *mut c_void), WM_INFO_CALC, WPARAM(0), LPARAM(0));
                    }
                }
            }
        });
        walk(&p, &c, cl);
        stop.store(true, Ordering::Relaxed);
        let _ = ticker.join();
        c.done.store(true, Ordering::Relaxed);
        if !c.cancel.load(Ordering::Relaxed) {
            unsafe {
                let _ = PostMessageW(HWND(h as *mut c_void), WM_INFO_CALC, WPARAM(0), LPARAM(0));
            }
        }
    });
}
fn update_calc_text(inf: &mut Info) {
    let Some(c) = &inf.calc else { return };
    let (b, d, n) = (c.bytes.load(Ordering::Relaxed), c.disk.load(Ordering::Relaxed), c.items.load(Ordering::Relaxed));
    let items = format!("{}{}", thousands(n), tr(if n == 1 { " item" } else { " itens" }));
    if c.done.load(Ordering::Relaxed) {
        inf.size_text = format!("{}{}{}{}{items}", thousands(b), tr(" bytes ("), human(d), tr(" no disco) para "));
        inf.header_size = human(b);
    } else {
        inf.size_text = format!("{}{}, {items}", tr("Calculando… "), human(b));
    }
}
fn hit_light(p: Ponto) -> i32 {
    (0..2).find(|&k| (p.x - unsafe { light_cx(k) }).abs() <= 9.0 && (p.y - light_cy()).abs() <= 9.0).unwrap_or(-1)
}
fn inr(r: &RectF, p: Ponto) -> bool {
    p.x >= r.left && p.x < r.right && p.y >= r.top && p.y < r.bottom
}
unsafe fn info_of(h: HWND) -> Option<&'static mut Info> {
    let p = GetWindowLongPtrW(h, GWLP_USERDATA) as *mut Info;
    p.as_mut()
}
fn dip(h: HWND, l: LPARAM) -> Ponto {
    let sc = scale(h);
    pt(get_x_lparam(l) as f32 / sc, get_y_lparam(l) as f32 / sc)
}
unsafe extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    let inf = info_of(h);
    match m {
        WM_NCCALCSIZE if w_.0 != 0 => return LRESULT(0),
        WM_NCHITTEST => {
            let r = DefWindowProcW(h, m, w_, l);
            let Some(inf) = inf else { return r };
            if r.0 as u32 != HTCLIENT {
                return if r.0 as u32 == HTCAPTION { LRESULT(HTCLIENT as isize) } else { r };
            }
            let p = app2d::screen_to_client(h, l);
            let sc = scale(h);
            let p = pt(p.x as f32 / sc, p.y as f32 / sc);
            if hit_light(p) >= 0 || (p.x < 80.0 && p.y < title_h()) || inf.sec_hit.iter().any(|r| inr(r, p)) || inr(&inf.lock_hit, p) || inr(&inf.locked_hit, p) || inf.perm_hit.iter().any(|r| inr(r, p)) {
                return LRESULT(HTCLIENT as isize);
            }
            return LRESULT(HTCAPTION as isize); // o resto arrasta a janela, como no Mac
        }
        WM_ACTIVATE => {
            if let Some(inf) = inf {
                inf.active = loword(w_.0) != WA_INACTIVE;
                let _ = InvalidateRect(h, None, false);
            }
            return LRESULT(0);
        }
        WM_SIZE => {
            if let Some(rt) = inf.and_then(|i| i.rt.clone()) {
                let _ = rt.Resize(&D2D_SIZE_U { width: loword(l.0 as usize), height: hiword(l.0 as usize) });
            }
            let _ = InvalidateRect(h, None, false);
            return LRESULT(0);
        }
        WM_DPICHANGED => {
            let r = &*(l.0 as *const RECT);
            if let Some(inf) = inf {
                inf.rt = None;
                inf.icon = None;
                inf.prev = None;
                let _ = SetWindowPos(h, None, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOZORDER | SWP_NOACTIVATE);
                fit_height(inf);
            }
            return LRESULT(0);
        }
        WM_PAINT => {
            let mut ps = PAINTSTRUCT::default();
            BeginPaint(h, &mut ps);
            if let Some(inf) = inf {
                ensure_target(inf);
                if let Some(rt) = inf.rt.clone() {
                    rt.BeginDraw();
                    paint(inf, &rt);
                    if rt.EndDraw(None, None).is_err() {
                        inf.rt = None;
                        inf.icon = None;
                        inf.prev = None;
                    }
                }
            }
            let _ = EndPaint(h, &ps);
            return LRESULT(0);
        }
        WM_ERASEBKGND => return LRESULT(1),
        WM_INFO_CALC => {
            if let Some(inf) = inf {
                update_calc_text(inf);
                fit_height(inf);
                let _ = InvalidateRect(h, None, false);
            }
            return LRESULT(0);
        }
        WM_MOUSEMOVE => {
            if let Some(inf) = inf {
                let mut t = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };
                let _ = TrackMouseEvent(&mut t);
                let p = dip(h, l);
                let over = p.x < 80.0 && p.y < title_h();
                if over != inf.hover_lights {
                    inf.hover_lights = over;
                    let _ = InvalidateRect(h, None, false);
                }
            }
            return LRESULT(0);
        }
        WM_MOUSELEAVE => {
            if let Some(inf) = inf {
                if inf.hover_lights {
                    inf.hover_lights = false;
                    let _ = InvalidateRect(h, None, false);
                }
            }
            return LRESULT(0);
        }
        WM_LBUTTONDOWN => {
            let Some(inf) = inf else { return LRESULT(0) };
            let p = dip(h, l);
            inf.press_light = hit_light(p);
            if inf.press_light >= 0 {
                SetCapture(h);
                return LRESULT(0);
            }
            for k in 0..S_COUNT {
                if inr(&inf.sec_hit[k], p) {
                    inf.open[k] = !inf.open[k];
                    fit_height(inf);
                    let _ = InvalidateRect(h, None, false);
                    return LRESULT(0);
                }
            }
            if inr(&inf.lock_hit, p) && inf.open[S_SHARING] && inf.lock_hit.bottom > inf.lock_hit.top && p.y > inf.sec_hit[S_SHARING].top {
                if inf.admin {
                    inf.unlocked = !inf.unlocked;
                    let _ = InvalidateRect(h, None, false);
                    return LRESULT(0);
                }
                // pede a senha de administrador (UAC) e reabre esta janela como administrador, no mesmo lugar
                let exe = std::env::current_exe().map(|p| p.to_string_lossy().to_string()).unwrap_or_default();
                let mut wr = RECT::default();
                let _ = GetWindowRect(h, &mut wr);
                let args = format!("--info-admin \"{}\" {} {}", inf.path, wr.left, wr.top);
                let (ew, aw) = (wz(&exe), wz(&args));
                let mut sei = SHELLEXECUTEINFOW { cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32, fMask: SEE_MASK_NOASYNC, hwnd: h, lpVerb: w!("runas"), lpFile: pc(&ew), lpParameters: pc(&aw), nShow: SW_SHOWNORMAL.0, ..Default::default() };
                if ShellExecuteExW(&mut sei).is_ok() {
                    let _ = DestroyWindow(h); // a de administrador ocupa o lugar desta
                }
                return LRESULT(0);
            }
            if inf.admin && inf.unlocked {
                for k in 0..inf.perm_hit.len().min(inf.perms.len()) {
                    if !inr(&inf.perm_hit[k], p) {
                        continue;
                    }
                    let items: Vec<Item> = (0..4).rev().map(|v| Item::new(tr(PRIV_NAMES[v as usize]), v + 1).checked(inf.perms[k].priv_ == v)).collect();
                    let sc = scale(h);
                    let sp = app2d::to_screen(h, (inf.perm_hit[k].left * sc) as i32, (inf.perm_hit[k].bottom * sc) as i32);
                    let id = ctxmenu::show_items(h, sp, &items);
                    if id > 0 && id - 1 != inf.perms[k].priv_ {
                        if !set_priv(&inf.path, inf.dir, &inf.perms[k].sid.clone(), id - 1) {
                            let _ = MessageBeep(MB_ICONWARNING);
                        }
                        gather_perms(inf);
                        fit_height(inf);
                    }
                    let _ = InvalidateRect(h, None, false);
                    return LRESULT(0);
                }
            }
            if inr(&inf.locked_hit, p) {
                // Bloqueado = somente leitura
                let pw = wz(&inf.path);
                let a = GetFileAttributesW(pc(&pw));
                if a != INVALID_FILE_ATTRIBUTES {
                    let na = if inf.read_only { a & !FILE_ATTRIBUTE_READONLY.0 } else { a | FILE_ATTRIBUTE_READONLY.0 };
                    if SetFileAttributesW(pc(&pw), FILE_FLAGS_AND_ATTRIBUTES(na)).is_ok() {
                        inf.read_only = !inf.read_only;
                    }
                }
                let _ = InvalidateRect(h, None, false);
            }
            return LRESULT(0);
        }
        WM_LBUTTONUP => {
            if let Some(inf) = inf {
                if inf.press_light >= 0 {
                    let _ = ReleaseCapture();
                    let k = hit_light(dip(h, l));
                    let was = inf.press_light;
                    inf.press_light = -1;
                    if k == was && k == 0 {
                        let _ = DestroyWindow(h);
                    } else if k == was && k == 1 {
                        let _ = ShowWindow(h, SW_MINIMIZE);
                    }
                    return LRESULT(0);
                }
            }
        }
        WM_KEYDOWN => {
            if w_.0 == VK_ESCAPE.0 as usize || (w_.0 == 'W' as usize && GetKeyState(VK_CONTROL.0 as i32) < 0) {
                let _ = DestroyWindow(h);
                return LRESULT(0);
            }
        }
        WM_DESTROY => {
            let p = GetWindowLongPtrW(h, GWLP_USERDATA) as *mut Info;
            if !p.is_null() {
                let b = Box::from_raw(p);
                if let Some(c) = &b.calc {
                    c.cancel.store(true, Ordering::Relaxed);
                }
                SetWindowLongPtrW(h, GWLP_USERDATA, 0);
            }
            if *STANDALONE.get() {
                // era a última: fecha o processo de administrador
                let mut other = false;
                let mut w2 = FindWindowExW(None, None, w!("ArquivosInfo"), PCWSTR::null()).unwrap_or_default();
                while !w2.0.is_null() {
                    let mut pid = 0;
                    GetWindowThreadProcessId(w2, Some(&mut pid));
                    if w2 != h && pid == GetCurrentProcessId() {
                        other = true;
                    }
                    w2 = FindWindowExW(None, w2, w!("ArquivosInfo"), PCWSTR::null()).unwrap_or_default();
                }
                if !other {
                    PostQuitMessage(0);
                }
            }
            return LRESULT(0);
        }
        _ => {}
    }
    DefWindowProcW(h, m, w_, l)
}
/// Abre (ou traz para a frente) a janela de informações de `path`, ao lado da janela `anchor`. px = i32::MIN: posição
/// automática.
pub fn show(path: &str, anchor: HWND, family: &str, dark: bool, admin: bool, px: i32, py: i32) {
    static REG: Global<bool> = Global::new(false);
    unsafe {
        let hi: HINSTANCE = GetModuleHandleW(None).unwrap_or_default().into();
        if !*REG.get() {
            let wc = WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hi, lpszClassName: w!("ArquivosInfo"), hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), ..Default::default() };
            RegisterClassW(&wc);
            *REG.get() = true;
        }
        *FAMILY.get() = family.into();
        *DARK.get() = dark;
        // já tem uma janela deste item: traz para a frente
        let mut count = 0;
        let mut w2 = FindWindowExW(None, None, w!("ArquivosInfo"), PCWSTR::null()).unwrap_or_default();
        while !w2.0.is_null() {
            if let Some(o) = info_of(w2) {
                if o.path.eq_ignore_ascii_case(path) {
                    let _ = ShowWindow(w2, SW_RESTORE);
                    let _ = SetForegroundWindow(w2);
                    return;
                }
            }
            count += 1;
            w2 = FindWindowExW(None, w2, w!("ArquivosInfo"), PCWSTR::null()).unwrap_or_default();
        }
        let mut inf = Box::new(Info { path: path.into(), admin, unlocked: admin, can_write: true, active: true, press_light: -1, open: [true, false, false, false, false, true, false], ..Default::default() });
        if admin {
            inf.open[S_SHARING] = true;
            *STANDALONE.get() = true;
        }
        gather(&mut inf);
        // posição: ao lado direito da janela do Finder, em cascata se já houver outras
        let mut nr = RECT { left: 200, top: 200, right: 800, bottom: 600 };
        if !anchor.0.is_null() {
            let _ = GetWindowRect(anchor, &mut nr);
        }
        let sc = if anchor.0.is_null() { 1.0 } else { GetDpiForWindow(anchor) as f32 / 96.0 };
        let wpx = (wid() * sc).round() as i32;
        let hpx = (content_height(&inf) * sc).round() as i32;
        let step = (22.0 * sc) as i32;
        let mut x = nr.right + (12.0 * sc) as i32 + count * step;
        let mut y = nr.top + count * step;
        let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
        let _ = GetMonitorInfoW(MonitorFromRect(&nr, MONITOR_DEFAULTTONEAREST), &mut mi);
        if x + wpx > mi.rcWork.right {
            x = mi.rcWork.left.max(nr.left + (40.0 * sc) as i32 + count * step);
        }
        if y + hpx > mi.rcWork.bottom {
            y = mi.rcWork.top.max(mi.rcWork.bottom - hpx);
        }
        if px != i32::MIN {
            x = px;
            y = py;
        }
        let title = wz(&format!("{}{}", tr("Informações de "), inf.name));
        let Ok(h) = CreateWindowExW(WINDOW_EX_STYLE(0), w!("ArquivosInfo"), pc(&title), WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, x, y, wpx, hpx, None, None, hi, None) else { return };
        inf.hwnd = h;
        let raw = Box::into_raw(inf);
        SetWindowLongPtrW(h, GWLP_USERDATA, raw as isize);
        let dm = BOOL::from(dark);
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(20), &dm as *const _ as *const c_void, 4);
        let corner = 2u32;
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const c_void, 4);
        let border = if 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 mg = MARGINS { cxLeftWidth: 0, cxRightWidth: 0, cyTopHeight: 1, cyBottomHeight: 0 }; // mantém a sombra do sistema
        let _ = DwmExtendFrameIntoClientArea(h, &mg);
        let _ = SetWindowPos(h, None, x, y, wpx, hpx, SWP_FRAMECHANGED | SWP_NOZORDER);
        fit_height(&*raw);
        let _ = ShowWindow(h, SW_SHOWNORMAL);
        let _ = SetForegroundWindow(h);
        start_calc(&mut *raw);
    }
}
/// Para a foto (--foto ... --info=<caminho>): desenha a janela de informações num bitmap, sem abrir janela.
pub fn foto(path: &str, family: &str, dark: bool, out: &str) -> Result<()> {
    *FAMILY.get() = family.into();
    *DARK.get() = dark;
    let mut inf = Info { path: path.into(), can_write: true, active: true, press_light: -1, open: [true, false, false, false, false, true, false], ..Default::default() };
    gather(&mut inf);
    if inf.dir {
        let c = Calc::default();
        walk(path, &c, cluster(path));
        c.done.store(true, Ordering::Relaxed);
        inf.calc = Some(Arc::new(c));
        update_calc_text(&mut inf);
    }
    let (ww, hh) = (wid(), content_height(&inf));
    unsafe {
        let wic: comum::windows::Win32::Graphics::Imaging::IWICImagingFactory = comum::windows::Win32::System::Com::CoCreateInstance(&comum::windows::Win32::Graphics::Imaging::CLSID_WICImagingFactory, None, comum::windows::Win32::System::Com::CLSCTX_INPROC_SERVER)?;
        let bmp = wic.CreateBitmap((ww * 2.0) as u32, (hh * 2.0) as u32, &comum::windows::Win32::Graphics::Imaging::GUID_WICPixelFormat32bppPBGRA, comum::windows::Win32::Graphics::Imaging::WICBitmapCacheOnLoad)?;
        let props = D2D1_RENDER_TARGET_PROPERTIES { r#type: D2D1_RENDER_TARGET_TYPE_SOFTWARE, pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED }, dpiX: 192.0, dpiY: 192.0, ..Default::default() };
        let rt = app2d::d2d().CreateWicBitmapRenderTarget(&bmp, &props)?;
        rt.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
        rt.BeginDraw();
        paint(&mut inf, &rt);
        rt.EndDraw(None, None)?;
        app2d::salvar_png(&bmp, out)
    }
}