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
64.6 KB
Raw Blame
// Porte de src\janelas\controles.cpp: controles do Windows no visual do Mac, dentro das janelas de diálogo que a DLL
// trata (Propriedades do Mouse, Som, a maioria dos diálogos de configuração): fundo e texto do Mac (claro ou escuro,
// como o Windows), fonte SF Pro, botões do Mac (o padrão em azul), caixas de seleção e rádios azuis, abas como o
// controle segmentado sobre uma caixa arredondada, grupos como caixas, menus suspensos como o botão de menu do Mac,
// campos com borda arredondada, listas no tema escuro e controles deslizantes com a bolinha branca.
// Cada controle é subclassificado e desenhado por nós (Direct2D num DC, com antisserrilhado); o comportamento continua
// o do Windows. Desfazer (o Shell sai): tudo volta ao original.
#![allow(clippy::too_many_arguments)]

use std::collections::HashMap;

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::Dxgi::Common::*;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::System::LibraryLoader::GetModuleFileNameW;
use comum::windows::Win32::System::Registry::*;
use comum::windows::Win32::UI::Controls::SetWindowTheme;
use comum::windows::Win32::UI::HiDpi::{AdjustWindowRectExForDpi, GetDpiForWindow};
use comum::windows::Win32::UI::Input::KeyboardAndMouse::{GetFocus, IsWindowEnabled, SetFocus};
use comum::windows::Win32::UI::Shell::{DefSubclassProc, ExtractIconExW, RemoveWindowSubclass, SHDefExtractIconW, SetWindowSubclass};
use crate::GetWindowSubclass; // pelo ordinal (lib.rs)
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::{col, ell, linear, mat, pc, pt, rf, rr, wz, Cor, Global, RectF};

const SUB_ID: usize = 0x4D41434B; // 'MACK'
const PROP_FONT: PCWSTR = w!("MacCtlFonte"); // fonte original do controle (para desfazer)

const T_DIALOG: usize = 1;
const T_BUTTON: usize = 2;
const T_TAB: usize = 3;
const T_COMBO: usize = 4;
const T_EDIT: usize = 5;
const T_LIST: usize = 6;

// estilos e mensagens dos controles comuns (as macros do commctrl.h/windowsx.h)
const BS_TYPEMASK_: u32 = 0xF;
const BS_PUSHBUTTON_: u32 = 0;
const BS_DEFPUSHBUTTON_: u32 = 1;
const BS_CHECKBOX_: u32 = 2;
const BS_AUTOCHECKBOX_: u32 = 3;
const BS_RADIOBUTTON_: u32 = 4;
const BS_3STATE_: u32 = 5;
const BS_AUTO3STATE_: u32 = 6;
const BS_GROUPBOX_: u32 = 7;
const BS_AUTORADIOBUTTON_: u32 = 9;
const BS_ICON_: u32 = 0x40;
const BS_BITMAP_: u32 = 0x80;
const BS_TOP_: u32 = 0x400;
const BS_PUSHLIKE_: u32 = 0x1000;
const BS_MULTILINE_: u32 = 0x2000;
const BST_CHECKED_: usize = 1;
const BST_INDETERMINATE_: usize = 2;
const BST_PUSHED_: usize = 4;
const BM_GETCHECK_: u32 = 0xF0;
const BM_SETCHECK_: u32 = 0xF1;
const BM_GETSTATE_: u32 = 0xF2;
const BM_SETSTATE_: u32 = 0xF3;
const BM_SETSTYLE_: u32 = 0xF4;
const BM_CLICK_: u32 = 0xF5;
const WM_QUERYUISTATE_: u32 = 0x129;
const WM_UPDATEUISTATE_: u32 = 0x128;
const UISF_HIDEFOCUS_: usize = 1;
const TCS_VERTICAL_: u32 = 0x80;
const TCS_BUTTONS_: u32 = 0x100;
const TCS_OWNERDRAWFIXED_: u32 = 0x2000;
const TCM_GETITEMCOUNT: u32 = 0x1304;
const TCM_GETCURSEL: u32 = 0x130B;
const TCM_SETCURSEL: u32 = 0x130C;
const TCM_ADJUSTRECT: u32 = 0x1328;
const TCM_SETCURFOCUS: u32 = 0x1330;
const TCM_GETITEMW: u32 = 0x133C;
const TCIF_TEXT: u32 = 1;
const CBS_DROPDOWNLIST_: u32 = 3;
const CBS_OWNERDRAWFIXED_: u32 = 0x10;
const CBS_OWNERDRAWVARIABLE_: u32 = 0x20;
const CB_GETCURSEL_: u32 = 0x147;
const CB_GETLBTEXT_: u32 = 0x148;
const CB_GETLBTEXTLEN_: u32 = 0x149;
const CB_SELECTSTRING_: u32 = 0x14D;
const CB_SETCURSEL_: u32 = 0x14E;
const LVM_SETBKCOLOR: u32 = 0x1001;
const LVM_GETHEADER: u32 = 0x101F;
const LVM_SETTEXTCOLOR: u32 = 0x1024;
const LVM_SETTEXTBKCOLOR: u32 = 0x1026;
const TVM_SETBKCOLOR: u32 = 0x111D;
const TVM_SETTEXTCOLOR: u32 = 0x111E;
const TBM_GETTHUMBRECT: u32 = 0x419;
const TBS_VERT_: u32 = 2;
const STM_GETICON_: u32 = 0x171;
const NM_CUSTOMDRAW_: u32 = (-12i32) as u32;
const CDDS_PREPAINT: u32 = 1;
const CDDS_ITEMPREPAINT: u32 = 0x10001;
const CDRF_DODEFAULT: isize = 0;
const CDRF_SKIPDEFAULT: isize = 4;
const CDRF_NOTIFYITEMDRAW: isize = 0x20;
const TBCD_THUMB: usize = 2;
const TBCD_CHANNEL: usize = 3;
const CLR_DEFAULT: u32 = 0xFF00_0000;
const WC_TAB: &str = "SysTabControl32";
const WC_COMBO: &str = "ComboBox";
const WC_LISTVIEW: &str = "SysListView32";
const WC_TREEVIEW: &str = "SysTreeView32";
const WC_TRACKBAR: &str = "msctls_trackbar32";
const WC_UPDOWN: &str = "msctls_updown32";

#[repr(C)]
struct Nmhdr {
    from: HWND,
    id: usize,
    code: u32,
}
#[repr(C)]
struct NmCustomDraw {
    hdr: Nmhdr,
    stage: u32,
    hdc: HDC,
    rc: RECT,
    item: usize,
    state: u32,
    lparam: isize,
}
#[repr(C)]
struct TcItem {
    mask: u32,
    state: u32,
    state_mask: u32,
    text: *mut u16,
    cch: i32,
    image: i32,
    lparam: isize,
}

struct Fab {
    d2d: ID2D1Factory,
    dw: Option<IDWriteFactory>,
    face: String, // SF Pro Text se instalada
}
static FAB: Global<Option<Fab>> = Global::new(None);
fn init() -> Option<&'static Fab> {
    let f = FAB.get();
    if f.is_none() {
        unsafe {
            let opts = D2D1_FACTORY_OPTIONS::default();
            let d2d: ID2D1Factory = D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, Some(&opts)).ok()?;
            let dw: Option<IDWriteFactory> = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED).ok();
            let mut face = "Segoe UI".to_string();
            if let Some(dw) = &dw {
                let mut fc: Option<IDWriteFontCollection> = None;
                if dw.GetSystemFontCollection(&mut fc, false).is_ok() {
                    if let Some(fc) = fc {
                        for n in ["SF Pro Text", "Inter"] {
                            let (mut i, mut ok) = (0u32, BOOL(0));
                            let nw = wz(n);
                            if fc.FindFamilyName(pc(&nw), &mut i, &mut ok).is_ok() && ok.as_bool() {
                                face = n.to_string();
                                break;
                            }
                        }
                    }
                }
            }
            *f = Some(Fab { d2d, dw, face });
        }
    }
    f.as_ref()
}

fn dark() -> bool {
    let (mut v, mut cb) = (1u32, 4u32);
    unsafe {
        let _ = RegGetValueW(
            HKEY_CURRENT_USER,
            w!("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"),
            w!("AppsUseLightTheme"),
            RRF_RT_REG_DWORD,
            None,
            Some(&mut v as *mut _ as *mut _),
            Some(&mut cb),
        );
    }
    v == 0
}

// ---- cores do Mac (claro / escuro)
#[derive(Clone, Copy)]
struct Pal {
    bg: u32,
    box_: u32,
    box_border: u32,
    text: u32,
    text2: u32,
    field: u32,
    field_border: u32,
    button: u32,
    #[allow(dead_code)]
    button_top: u32,
    #[allow(dead_code)]
    button_border: u32,
    accent: u32,
    track: u32,
}
const fn rgb(r: u32, g: u32, b: u32) -> u32 {
    r | g << 8 | b << 16
}
fn get_r(c: u32) -> u32 {
    c & 0xFF
}
fn get_g(c: u32) -> u32 {
    (c >> 8) & 0xFF
}
fn get_b(c: u32) -> u32 {
    (c >> 16) & 0xFF
}
fn colors() -> Pal {
    // Leopard: o cinza 232 das janelas do 10.5 (sempre claro: o 10.5 não tinha modo escuro), destaque azul do Aqua
    let v: [u32; 12] = if comum::leopard::on() {
        [
            rgb(232, 232, 232),
            rgb(222, 222, 222),
            rgb(190, 190, 190),
            rgb(0, 0, 0),
            rgb(110, 110, 110),
            rgb(255, 255, 255),
            rgb(150, 150, 150),
            rgb(255, 255, 255),
            rgb(255, 255, 255),
            rgb(140, 140, 140),
            rgb(56, 117, 215),
            rgb(200, 200, 200),
        ]
    } else if dark() {
        [
            rgb(36, 36, 38),
            rgb(48, 48, 50),
            rgb(62, 62, 64),
            rgb(223, 223, 225),
            rgb(150, 150, 155),
            rgb(30, 30, 31),
            rgb(70, 70, 72),
            rgb(88, 88, 90),
            rgb(100, 100, 102),
            rgb(28, 28, 30),
            rgb(10, 132, 255),
            rgb(70, 70, 72),
        ]
    } else {
        [
            rgb(236, 236, 236),
            rgb(226, 226, 226),
            rgb(210, 210, 210),
            rgb(30, 30, 30),
            rgb(120, 120, 124),
            rgb(255, 255, 255),
            rgb(196, 196, 198),
            rgb(255, 255, 255),
            rgb(255, 255, 255),
            rgb(186, 186, 190),
            rgb(0, 122, 255),
            rgb(212, 212, 214),
        ]
    };
    Pal {
        bg: v[0],
        box_: v[1],
        box_border: v[2],
        text: v[3],
        text2: v[4],
        field: v[5],
        field_border: v[6],
        button: v[7],
        button_top: v[8],
        button_border: v[9],
        accent: v[10],
        track: v[11],
    }
}

fn c(c: u32, a: f32) -> Cor {
    col(get_r(c) as f32 / 255.0, get_g(c) as f32 / 255.0, get_b(c) as f32 / 255.0, a)
}
fn c1(cc: u32) -> Cor {
    c(cc, 1.0)
}

static BRUSHES: Global<Option<HashMap<u32, HBRUSH>>> = Global::new(None);
fn brush(cc: u32) -> HBRUSH {
    *BRUSHES.get().get_or_insert_with(HashMap::new).entry(cc).or_insert_with(|| unsafe { CreateSolidBrush(COLORREF(cc)) })
}

fn class_of(h: HWND) -> String {
    let mut b = [0u16; 64];
    let n = unsafe { GetClassNameW(h, &mut b) } as usize;
    String::from_utf16_lossy(&b[..n])
}
fn wstyle(h: HWND) -> u32 {
    unsafe { GetWindowLongW(h, GWL_STYLE) as u32 }
}
fn ex_style(h: HWND) -> u32 {
    unsafe { GetWindowLongW(h, GWL_EXSTYLE) as u32 }
}
fn scale(h: HWND) -> f32 {
    let d = unsafe { GetDpiForWindow(h) };
    if d != 0 {
        d as f32 / 96.0
    } else {
        1.0
    }
}
fn send(h: HWND, m: u32, w_: usize, l: isize) -> isize {
    unsafe { SendMessageW(h, m, WPARAM(w_), LPARAM(l)).0 }
}
fn win_rect(h: HWND) -> RECT {
    let mut r = RECT::default();
    unsafe {
        let _ = GetWindowRect(h, &mut r);
    }
    r
}
fn client_rect(h: HWND) -> RECT {
    let mut r = RECT::default();
    unsafe {
        let _ = GetClientRect(h, &mut r);
    }
    r
}
/// retângulo da tela nas coordenadas de `to`
fn map_rect(r: RECT, to: HWND) -> RECT {
    let mut p = [POINT { x: r.left, y: r.top }, POINT { x: r.right, y: r.bottom }];
    unsafe {
        MapWindowPoints(None, to, &mut p);
    }
    RECT { left: p[0].x, top: p[0].y, right: p[1].x, bottom: p[1].y }
}
fn child_windows(p: HWND) -> Vec<HWND> {
    let mut v = Vec::new();
    unsafe {
        let mut c = GetWindow(p, GW_CHILD).unwrap_or_default();
        while !c.0.is_null() {
            v.push(c);
            c = GetWindow(c, GW_HWNDNEXT).unwrap_or_default();
        }
    }
    v
}
fn visible(h: HWND) -> bool {
    unsafe { IsWindowVisible(h).as_bool() }
}

/// página de uma folha de propriedades (diálogo filho ao lado de uma barra de abas): fica na cor da caixa
fn is_page(dlg: HWND) -> bool {
    if wstyle(dlg) & WS_CHILD.0 == 0 {
        return false;
    }
    unsafe {
        let Ok(p) = GetParent(dlg) else { return false };
        !p.0.is_null() && FindWindowExW(p, None, w!("SysTabControl32"), None).is_ok()
    }
}
fn mix(a: u32, b: u32, t: f32) -> u32 {
    let m = |x: u32, y: u32| (x as f32 + (y as f32 - x as f32) * t) as u32;
    rgb(m(get_r(a), get_r(b)), m(get_g(a), get_g(b)), m(get_b(a), get_b(b)))
}
fn base_of(dlg: HWND) -> u32 {
    let p = colors();
    if is_page(dlg) {
        p.box_
    } else {
        p.bg
    }
}
fn box_on(base: u32) -> u32 {
    if dark() {
        mix(base, rgb(255, 255, 255), 0.06)
    } else {
        mix(base, rgb(0, 0, 0), 0.045)
    }
}
fn is_group_box(h: HWND) -> bool {
    class_of(h) == "Button" && wstyle(h) & BS_TYPEMASK_ == BS_GROUPBOX_
}
fn parent(h: HWND) -> HWND {
    unsafe { GetParent(h).unwrap_or_default() }
}
/// retângulo da caixa de um grupo (abaixo do título), nas coordenadas do pai
fn group_box_rect(g: HWND) -> RECT {
    let mut r = map_rect(win_rect(g), parent(g));
    r.top += (8.0 * scale(g)) as i32;
    r
}
/// cor embaixo de um controle: a do diálogo ou a de uma caixa de grupo que o contém
fn under_of(ctl: HWND) -> u32 {
    let p = parent(ctl);
    let base = base_of(p);
    if is_group_box(ctl) {
        return base;
    }
    let r = map_rect(win_rect(ctl), p);
    for cc in child_windows(p) {
        if cc == ctl || !visible(cc) || !is_group_box(cc) {
            continue;
        }
        let g = group_box_rect(cc);
        if r.left >= g.left && r.right <= g.right && r.top >= g.top && r.bottom <= g.bottom {
            return box_on(base);
        }
    }
    base
}

// ---- desenho com Direct2D num DC (com cópia na memória: sem piscar)
struct Canvas {
    target: HDC,
    mem: HDC,
    bmp: HBITMAP,
    old: HGDIOBJ,
    rc: RECT,
    rt: Option<ID2D1DCRenderTarget>,
    br: Option<ID2D1SolidColorBrush>,
}
impl Canvas {
    fn new(dc: HDC, r: RECT) -> Canvas {
        unsafe {
            let mem = CreateCompatibleDC(dc);
            let bmp = CreateCompatibleBitmap(dc, (r.right - r.left).max(1), (r.bottom - r.top).max(1));
            let old = SelectObject(mem, bmp);
            let mut cv = Canvas { target: dc, mem, bmp, old, rc: r, rt: None, br: None };
            let props = D2D1_RENDER_TARGET_PROPERTIES {
                r#type: D2D1_RENDER_TARGET_TYPE_DEFAULT,
                pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_IGNORE },
                dpiX: 96.0,
                dpiY: 96.0,
                ..Default::default()
            };
            if let Some(f) = init() {
                if let Ok(rt) = f.d2d.CreateDCRenderTarget(&props) {
                    let b = RECT { left: 0, top: 0, right: r.right - r.left, bottom: r.bottom - r.top };
                    if rt.BindDC(mem, &b).is_ok() {
                        rt.BeginDraw();
                        rt.SetTransform(&mat::trans(-(r.left as f32), -(r.top as f32)));
                        cv.br = rt.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None).ok();
                        if cv.br.is_some() {
                            cv.rt = Some(rt);
                        } else {
                            let _ = rt.EndDraw(None, None);
                        }
                    }
                }
            }
            cv
        }
    }
    fn ok(&self) -> bool {
        self.rt.is_some()
    }
    fn rt(&self) -> &ID2D1DCRenderTarget {
        self.rt.as_ref().unwrap()
    }
    fn br(&self) -> &ID2D1SolidColorBrush {
        self.br.as_ref().unwrap()
    }
    fn set(&self, cc: Cor) {
        unsafe { self.br().SetColor(&cc) }
    }
    fn fill(&self, r: RectF, rad: f32, cc: Cor) {
        self.set(cc);
        unsafe {
            if rad > 0.0 {
                self.rt().FillRoundedRectangle(&rr(r, rad, rad), self.br());
            } else {
                self.rt().FillRectangle(&r, self.br());
            }
        }
    }
    fn stroke(&self, r: RectF, rad: f32, cc: Cor, w_: f32) {
        self.set(cc);
        unsafe { self.rt().DrawRoundedRectangle(&rr(r, rad, rad), self.br(), w_, None) }
    }
    fn line(&self, a: (f32, f32), b: (f32, f32), w_: f32) {
        unsafe { self.rt().DrawLine(pt(a.0, a.1), pt(b.0, b.1), self.br(), w_, None) }
    }
    fn ellipse(&self, x: f32, y: f32, r: f32) {
        unsafe { self.rt().FillEllipse(&ell(pt(x, y), r, r), self.br()) }
    }
    fn text(&self, s: &str, r: RectF, size: f32, cc: Cor, al: DWRITE_TEXT_ALIGNMENT, w_: DWRITE_FONT_WEIGHT, wrap: bool) {
        let Some(f) = init() else { return };
        let Some(dw) = &f.dw else { return };
        if s.is_empty() {
            return;
        }
        let sw: Vec<u16> = s.encode_utf16().collect();
        unsafe {
            let Some(mut tf) = comum::cjk::format(dw, &f.face, w_, DWRITE_FONT_STYLE_NORMAL, size, "pt-br") else { return };
            if !wrap {
                // a SF Pro é mais larga que a fonte do Windows: encolhe até 85% para caber no controle
                if let Ok(lay) = dw.CreateTextLayout(&sw, &tf, 10000.0, 1000.0) {
                    let mut m = DWRITE_TEXT_METRICS::default();
                    let _ = lay.GetMetrics(&mut m);
                    let avail = r.right - r.left;
                    if m.widthIncludingTrailingWhitespace > avail && avail > 0.0 {
                        let k = (avail / m.widthIncludingTrailingWhitespace).max(0.85);
                        let Some(t2) = comum::cjk::format(dw, &f.face, w_, DWRITE_FONT_STYLE_NORMAL, size * k, "pt-br") else { return };
                        tf = t2;
                    }
                }
            }
            let _ = tf.SetTextAlignment(al);
            let _ = tf.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
            let _ = tf.SetWordWrapping(if wrap { DWRITE_WORD_WRAPPING_WRAP } else { DWRITE_WORD_WRAPPING_NO_WRAP });
            let tr = DWRITE_TRIMMING { granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER, delimiter: 0, delimiterCount: 0 };
            let _ = tf.SetTrimming(&tr, None);
            self.set(cc);
            self.rt().DrawText(&sw, &tf, &r, self.br(), D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
        }
    }
}
impl Drop for Canvas {
    fn drop(&mut self) {
        unsafe {
            if let Some(rt) = self.rt.take() {
                let _ = rt.EndDraw(None, None);
            }
            self.br = None;
            let r = self.rc;
            let _ = BitBlt(self.target, r.left, r.top, r.right - r.left, r.bottom - r.top, self.mem, 0, 0, SRCCOPY);
            SelectObject(self.mem, self.old);
            let _ = DeleteObject(self.bmp);
            let _ = DeleteDC(self.mem);
        }
    }
}

fn rfr(r: RECT) -> RectF {
    rf(r.left as f32, r.top as f32, r.right as f32, r.bottom as f32)
}
/// largura de um texto (DirectWrite); `trailing`: com os espaços do fim
fn text_width(s: &str, size: f32, weight: DWRITE_FONT_WEIGHT, trailing: bool) -> Option<f32> {
    let f = init()?;
    let dw = f.dw.as_ref()?;
    if s.is_empty() {
        return Some(0.0);
    }
    let sw: Vec<u16> = s.encode_utf16().collect();
    unsafe {
        let tf = comum::cjk::format(dw, &f.face, weight, DWRITE_FONT_STYLE_NORMAL, size, "pt-br")?;
        let lay = dw.CreateTextLayout(&sw, &tf, 4000.0, 400.0).ok()?;
        let mut m = DWRITE_TEXT_METRICS::default();
        lay.GetMetrics(&mut m).ok()?;
        Some(if trailing { m.widthIncludingTrailingWhitespace } else { m.width })
    }
}
fn text_height(s: &str, size: f32, weight: DWRITE_FONT_WEIGHT, width: f32) -> f32 {
    let Some(f) = init() else { return 0.0 };
    let Some(dw) = &f.dw else { return 0.0 };
    if s.is_empty() {
        return 0.0;
    }
    let sw: Vec<u16> = s.encode_utf16().collect();
    unsafe {
        let Some(tf) = comum::cjk::format(dw, &f.face, weight, DWRITE_FONT_STYLE_NORMAL, size, "pt-br") else { return 0.0 };
        let _ = tf.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
        let Ok(lay) = dw.CreateTextLayout(&sw, &tf, width, 4000.0) else { return 0.0 };
        let mut m = DWRITE_TEXT_METRICS::default();
        let _ = lay.GetMetrics(&mut m);
        m.height
    }
}

fn window_text(h: HWND) -> String {
    unsafe {
        let n = GetWindowTextLengthW(h);
        if n <= 0 {
            return String::new();
        }
        let mut b = vec![0u16; n as usize + 1];
        let k = GetWindowTextW(h, &mut b) as usize;
        String::from_utf16_lossy(&b[..k])
    }
}
/// sem o "&" dos atalhos
fn clean_text(h: HWND) -> String {
    let s: Vec<char> = window_text(h).chars().collect();
    let mut o = String::new();
    let mut i = 0;
    while i < s.len() {
        if s[i] == '&' {
            if i + 1 < s.len() && s[i + 1] == '&' {
                o.push('&');
                i += 1;
            }
            i += 1;
            continue;
        }
        o.push(s[i]);
        i += 1;
    }
    o
}
fn get_font(h: HWND) -> HFONT {
    HFONT(send(h, WM_GETFONT, 0, 0) as *mut _)
}
fn logfont(f: HFONT) -> Option<LOGFONTW> {
    let mut lf = LOGFONTW::default();
    let n = unsafe { GetObjectW(HGDIOBJ(f.0), std::mem::size_of::<LOGFONTW>() as i32, Some(&mut lf as *mut _ as *mut _)) };
    (n != 0).then_some(lf)
}
/// tamanho do texto do controle (px)
fn font_px(h: HWND) -> f32 {
    let f = get_font(h);
    if !f.0.is_null() {
        if let Some(lf) = logfont(f) {
            if lf.lfHeight != 0 {
                return lf.lfHeight.abs() as f32 * if lf.lfHeight < 0 { 1.0 } else { 0.8 };
            }
        }
    }
    12.0 * scale(h)
}

// ---- fonte: SF Pro do mesmo tamanho (a disposição do diálogo continua a mesma)
// Chave: a fonte pedida (tamanho, peso, estilo, conjunto de caracteres), não o handle dela. Pelo handle, cada diálogo
// novo criava mais uma fonte nossa que nunca era solta; e um handle reaproveitado com outro tamanho devolvia a antiga.
static FONTS: Global<Option<HashMap<String, HFONT>>> = Global::new(None);
fn mac_font(f: HFONT) -> HFONT {
    if f.0.is_null() {
        return f;
    }
    let Some(mut lf) = logfont(f) else { return f };
    let Some(fab) = init() else { return f };
    let nome = String::from_utf16_lossy(&lf.lfFaceName[..lf.lfFaceName.iter().position(|&x| x == 0).unwrap_or(32)]);
    if nome.eq_ignore_ascii_case(&fab.face) {
        return f;
    }
    let key = format!(
        "{}|{}|{}|{}|{}|{}|{}|{}",
        lf.lfHeight, lf.lfWidth, lf.lfWeight, lf.lfItalic, lf.lfUnderline, lf.lfStrikeOut, lf.lfCharSet.0, lf.lfEscapement
    );
    let m = FONTS.get().get_or_insert_with(HashMap::new);
    if let Some(x) = m.get(&key) {
        return *x;
    }
    lf.lfFaceName = [0; 32];
    for (i, ch) in fab.face.encode_utf16().take(31).enumerate() {
        lf.lfFaceName[i] = ch;
    }
    lf.lfQuality = CLEARTYPE_QUALITY;
    let n = unsafe { CreateFontIndirectW(&lf) };
    if n.0.is_null() {
        return f; // sem guardar: a fonte do app pode ser apagada por ele depois
    }
    m.insert(key, n);
    n
}

fn check_path(cv: &Canvas, pts: [(f32, f32); 3], w_: f32) {
    let Some(f) = init() else { return };
    unsafe {
        let Ok(g) = f.d2d.CreatePathGeometry() else { return };
        let Ok(k) = g.Open() else { return };
        k.BeginFigure(pt(pts[0].0, pts[0].1), D2D1_FIGURE_BEGIN_HOLLOW);
        k.AddLine(pt(pts[1].0, pts[1].1));
        k.AddLine(pt(pts[2].0, pts[2].1));
        k.EndFigure(D2D1_FIGURE_END_OPEN);
        let _ = k.Close();
        let sp = D2D1_STROKE_STYLE_PROPERTIES {
            startCap: D2D1_CAP_STYLE_ROUND,
            endCap: D2D1_CAP_STYLE_ROUND,
            dashCap: D2D1_CAP_STYLE_ROUND,
            lineJoin: D2D1_LINE_JOIN_ROUND,
            miterLimit: 10.0,
            dashStyle: D2D1_DASH_STYLE_SOLID,
            dashOffset: 0.0,
        };
        let ss = f.d2d.CreateStrokeStyle(&sp, None).ok();
        cv.rt().DrawGeometry(&g, cv.br(), w_, ss.as_ref());
    }
}

// ---- botões
fn paint_button(h: HWND, dc: HDC) {
    let rc = client_rect(h);
    let st = wstyle(h);
    let typ = st & BS_TYPEMASK_;
    let state = send(h, BM_GETSTATE_, 0, 0) as usize;
    let enabled = unsafe { IsWindowEnabled(h).as_bool() };
    let pressed = state & BST_PUSHED_ != 0;
    let focused = unsafe { GetFocus() } == h;
    let hide_focus = send(h, WM_QUERYUISTATE_, 0, 0) as usize & UISF_HIDEFOCUS_ != 0;
    let p = colors();
    let (s, fs) = (scale(h), font_px(h));
    let under = under_of(h);
    let dk = dark();
    let cv = Canvas::new(dc, rc);
    if !cv.ok() {
        return;
    }
    cv.fill(rfr(rc), 0.0, c1(under));
    let a = if enabled { 1.0 } else { 0.4 };
    let text = clean_text(h);
    let multi = st & BS_MULTILINE_ != 0;
    let check = matches!(typ, BS_CHECKBOX_ | BS_AUTOCHECKBOX_ | BS_3STATE_ | BS_AUTO3STATE_);
    let radio = matches!(typ, BS_RADIOBUTTON_ | BS_AUTORADIOBUTTON_);
    let (l, t, r_, b_) = (rc.left as f32, rc.top as f32, rc.right as f32, rc.bottom as f32);
    if (check || radio) && st & BS_PUSHLIKE_ == 0 {
        let checked = send(h, BM_GETCHECK_, 0, 0) as usize;
        let b = (14.0 * s).round();
        let mut cy = (t + b_) / 2.0;
        if st & BS_TOP_ != 0 {
            cy = t + fs * 0.75;
        }
        let bx = rf(l + 1.0 * s, cy - b / 2.0, l + 1.0 * s + b, cy + b / 2.0);
        let rad = if radio { b / 2.0 } else { 3.5 * s };
        if checked != 0 {
            cv.fill(bx, rad, c(p.accent, a));
            cv.set(col(1.0, 1.0, 1.0, a));
            if radio {
                cv.ellipse((bx.left + bx.right) / 2.0, cy, b * 0.2);
            } else if checked == BST_INDETERMINATE_ {
                cv.line((bx.left + b * 0.28, cy), (bx.right - b * 0.28, cy), 1.8 * s);
            } else {
                // ✓
                check_path(&cv, [(bx.left + b * 0.24, cy + b * 0.02), (bx.left + b * 0.43, cy + b * 0.22), (bx.left + b * 0.77, cy - b * 0.24)], 1.9 * s);
            }
        } else {
            cv.fill(bx, rad, if dk { col(1.0, 1.0, 1.0, 0.12 * a) } else { c(rgb(255, 255, 255), a) });
            cv.stroke(
                rf(bx.left + 0.5, bx.top + 0.5, bx.right - 0.5, bx.bottom - 0.5),
                rad,
                if dk { col(1.0, 1.0, 1.0, 0.18 * a) } else { col(0.0, 0.0, 0.0, 0.28 * a) },
                1.0,
            );
        }
        if focused && !hide_focus {
            cv.stroke(rf(bx.left - 1.5 * s, bx.top - 1.5 * s, bx.right + 1.5 * s, bx.bottom + 1.5 * s), rad + 1.5 * s, c(p.accent, 0.5), 2.5 * s);
        }
        cv.text(&text, rf(bx.right + 6.0 * s, t, r_, b_), fs, c(p.text, a), DWRITE_TEXT_ALIGNMENT_LEADING, DWRITE_FONT_WEIGHT_NORMAL, multi);
        return;
    }
    // botão de apertar (e caixas "como botão")
    let def = typ == BS_DEFPUSHBUTTON_;
    let on = st & BS_PUSHLIKE_ != 0 && send(h, BM_GETCHECK_, 0, 0) as usize == BST_CHECKED_;
    if comum::leopard::on() {
        // Leopard: pílula Aqua de 21 (perolada; o padrão e o apertado em gel azul), texto preto
        let hh = ((b_ - t) - 3.0 * s).min(21.0 * s);
        let yc = (t + b_) / 2.0;
        let r = rf(l + 2.0 * s, yc - hh / 2.0, r_ - 2.0 * s, yc + hh / 2.0);
        let rd = hh / 2.0;
        let blue = def || on || pressed;
        cv.fill(rf(r.left, r.top + 1.0 * s, r.right, r.bottom + 1.0 * s), rd, col(1.0, 1.0, 1.0, 0.6 * a));
        let stops = if blue {
            [(0.0, col(0.66, 0.80, 0.98, a)), (0.5, col(0.38, 0.60, 0.93, a)), (0.5, col(0.24, 0.47, 0.87, a)), (1.0, col(0.58, 0.82, 1.0, a))]
        } else {
            [(0.0, col(1.0, 1.0, 1.0, a)), (0.5, col(0.95, 0.95, 0.95, a)), (0.5, col(0.88, 0.88, 0.88, a)), (1.0, col(0.98, 0.98, 0.98, a))]
        };
        unsafe {
            if let Some(lb) = linear(cv.rt(), &stops, pt(0.0, r.top), pt(0.0, r.bottom)) {
                cv.rt().FillRoundedRectangle(&rr(r, rd, rd), &lb);
            }
        }
        cv.stroke(
            rf(r.left + 0.5, r.top + 0.5, r.right - 0.5, r.bottom - 0.5),
            rd - 0.5,
            if blue { col(0.12, 0.27, 0.58, 0.9 * a) } else { col(0.0, 0.0, 0.0, 0.42 * a) },
            1.0,
        );
        if focused && !hide_focus && !def {
            cv.stroke(rf(r.left - 1.5 * s, r.top - 1.5 * s, r.right + 1.5 * s, r.bottom + 1.5 * s), rd + 1.5 * s, col(0.36, 0.60, 0.95, 0.75), 3.0 * s);
        }
        cv.text(&text, rf(r.left + 8.0 * s, r.top, r.right - 8.0 * s, r.bottom), fs, col(0.0, 0.0, 0.0, 0.9 * a), DWRITE_TEXT_ALIGNMENT_CENTER, DWRITE_FONT_WEIGHT_NORMAL, multi);
        return;
    }
    let hgt = ((b_ - t) - 2.0 * s).min(22.0 * s + fs * 0.3);
    let cy = (t + b_) / 2.0;
    let r = rf(l + 2.0 * s, cy - hgt / 2.0, r_ - 2.0 * s, cy + hgt / 2.0);
    let rad = 5.5 * s;
    if !dk {
        // sombra fina embaixo, como no Mac claro
        cv.fill(rf(r.left, r.top + 0.5 * s, r.right, r.bottom + 0.8 * s), rad, col(0.0, 0.0, 0.0, 0.10 * a));
    }
    let mut fill = if def || on { c(p.accent, a) } else { c(p.button, a) };
    if pressed {
        fill = if def || on {
            c(mix(p.accent, 0, 0.18), a)
        } else if dk {
            c(mix(p.button, rgb(255, 255, 255), 0.15), a)
        } else {
            c(mix(p.button, 0, 0.10), a)
        };
    }
    cv.fill(r, rad, fill);
    if !def && !on {
        if dk {
            // brilho de 1 px em cima
            cv.set(col(1.0, 1.0, 1.0, 0.10 * a));
            cv.line((r.left + rad, r.top + 0.5), (r.right - rad, r.top + 0.5), 1.0);
        } else {
            cv.stroke(rf(r.left + 0.5, r.top + 0.5, r.right - 0.5, r.bottom - 0.5), rad, col(0.0, 0.0, 0.0, 0.16 * a), 1.0);
        }
    }
    if focused && !hide_focus && !def {
        cv.stroke(rf(r.left - 1.0, r.top - 1.0, r.right + 1.0, r.bottom + 1.0), rad + 1.0, c(p.accent, 0.55), 2.5 * s);
    }
    let tc = if def || on { col(1.0, 1.0, 1.0, a) } else { c(p.text, a) };
    cv.text(&text, rf(r.left + 6.0 * s, r.top, r.right - 6.0 * s, r.bottom), fs, tc, DWRITE_TEXT_ALIGNMENT_CENTER, DWRITE_FONT_WEIGHT_NORMAL, multi);
}

fn our_button(h: HWND) -> bool {
    let st = wstyle(h);
    if st & (BS_BITMAP_ | BS_ICON_) != 0 {
        return false; // botões com imagem: o desenho é do app
    }
    matches!(
        st & BS_TYPEMASK_,
        BS_PUSHBUTTON_ | BS_DEFPUSHBUTTON_ | BS_CHECKBOX_ | BS_AUTOCHECKBOX_ | BS_3STATE_ | BS_AUTO3STATE_ | BS_RADIOBUTTON_ | BS_AUTORADIOBUTTON_ | BS_GROUPBOX_
    )
}

// ---- abas: o controle segmentado do Mac, centrado, sobre a caixa das páginas
static SEGMENTS: Global<Option<HashMap<isize, Vec<RECT>>>> = Global::new(None);
fn segments() -> &'static mut HashMap<isize, Vec<RECT>> {
    SEGMENTS.get().get_or_insert_with(HashMap::new)
}

fn paint_tab(h: HWND, dc: HDC) {
    let rc = client_rect(h);
    let p = colors();
    let (s, fs) = (scale(h), font_px(h));
    let base = base_of(parent(h));
    let dk = dark();
    let cv = Canvas::new(dc, rc);
    if !cv.ok() {
        return;
    }
    cv.fill(rfr(rc), 0.0, c1(base));
    let n = send(h, TCM_GETITEMCOUNT, 0, 0).max(0) as usize;
    let cur = send(h, TCM_GETCURSEL, 0, 0);
    let mut names = Vec::with_capacity(n);
    let mut widths = Vec::with_capacity(n);
    let mut total = 0.0f32;
    for i in 0..n {
        let mut b = [0u16; 128];
        let mut it = TcItem { mask: TCIF_TEXT, state: 0, state_mask: 0, text: b.as_mut_ptr(), cch: 127, image: 0, lparam: 0 };
        send(h, TCM_GETITEMW, i, &mut it as *mut _ as isize);
        let k = b.iter().position(|&x| x == 0).unwrap_or(127);
        let t: String = String::from_utf16_lossy(&b[..k]).chars().filter(|&ch| ch != '&').collect();
        // largura aproximada pelo DirectWrite
        let w_ = text_width(&t, fs, DWRITE_FONT_WEIGHT_NORMAL, true).unwrap_or(40.0 * s);
        names.push(t);
        widths.push(w_ + 24.0 * s);
        total += w_ + 24.0 * s;
    }
    let mut disp = rc;
    send(h, TCM_ADJUSTRECT, 0, &mut disp as *mut _ as isize);
    let seg_h = (22.0 * s).round();
    let seg_top = (2.0 * s).max((disp.top as f32 - seg_h) / 2.0 - 2.0 * s);
    let max_w = (rc.right - rc.left) as f32 - 16.0 * s;
    if total > max_w {
        let k = max_w / total;
        for w_ in widths.iter_mut() {
            *w_ *= k;
        }
        total = max_w;
    }
    let x0 = (rc.left + rc.right) as f32 / 2.0 - total / 2.0;
    // caixa das páginas: começa no meio do controle segmentado
    let bx = rf(rc.left as f32 + 0.5, seg_top + seg_h / 2.0, rc.right as f32 - 0.5, rc.bottom as f32 - 0.5);
    cv.fill(bx, 8.0 * s, c1(p.box_));
    cv.stroke(bx, 8.0 * s, c1(p.box_border), 1.0);
    // trilho e segmentos
    let track = rf(x0, seg_top, x0 + total, seg_top + seg_h);
    cv.fill(track, 6.0 * s, if dk { c1(rgb(62, 62, 64)) } else { c1(rgb(222, 222, 224)) });
    let seg = segments().entry(h.0 as isize).or_default();
    seg.clear();
    let mut x = x0;
    for i in 0..n {
        let r = rf(x, seg_top, x + widths[i], seg_top + seg_h);
        seg.push(RECT { left: r.left as i32, top: r.top as i32, right: r.right as i32, bottom: r.bottom as i32 });
        if i as isize == cur {
            let k = rf(r.left + 2.0 * s, r.top + 2.0 * s, r.right - 2.0 * s, r.bottom - 2.0 * s);
            if !dk {
                cv.fill(rf(k.left, k.top + 0.5 * s, k.right, k.bottom + 0.8 * s), 4.5 * s, col(0.0, 0.0, 0.0, 0.12));
            }
            cv.fill(k, 4.5 * s, if dk { c1(rgb(104, 104, 106)) } else { c1(rgb(255, 255, 255)) });
        } else if i > 0 && i as isize - 1 != cur {
            // divisória entre dois não escolhidos
            cv.set(if dk { col(1.0, 1.0, 1.0, 0.14) } else { col(0.0, 0.0, 0.0, 0.14) });
            cv.line((r.left, r.top + 5.0 * s), (r.left, r.bottom - 5.0 * s), 1.0);
        }
        cv.text(
            &names[i],
            r,
            fs,
            c1(p.text),
            DWRITE_TEXT_ALIGNMENT_CENTER,
            if i as isize == cur { DWRITE_FONT_WEIGHT_MEDIUM } else { DWRITE_FONT_WEIGHT_NORMAL },
            false,
        );
        x += widths[i];
    }
}

// ---- menu suspenso (lista fixa): o botão de menu do Mac, com as setinhas no quadrado azul
fn paint_combo(h: HWND, dc: HDC) {
    let rc = client_rect(h);
    let p = colors();
    let (s, fs) = (scale(h), font_px(h));
    let enabled = unsafe { IsWindowEnabled(h).as_bool() };
    let focused = unsafe { GetFocus() } == h;
    let a = if enabled { 1.0 } else { 0.4 };
    let dk = dark();
    let cv = Canvas::new(dc, rc);
    if !cv.ok() {
        return;
    }
    cv.fill(rfr(rc), 0.0, c1(under_of(h)));
    let hgt = ((rc.bottom - rc.top) as f32 - 2.0 * s).min(22.0 * s + fs * 0.3);
    let cy = (rc.top + rc.bottom) as f32 / 2.0;
    let r = rf(rc.left as f32 + 1.0 * s, cy - hgt / 2.0, rc.right as f32 - 1.0 * s, cy + hgt / 2.0);
    let rad = 5.5 * s;
    if !dk {
        cv.fill(rf(r.left, r.top + 0.5 * s, r.right, r.bottom + 0.8 * s), rad, col(0.0, 0.0, 0.0, 0.10 * a));
    }
    cv.fill(r, rad, c(p.button, a));
    if !dk {
        cv.stroke(rf(r.left + 0.5, r.top + 0.5, r.right - 0.5, r.bottom - 0.5), rad, col(0.0, 0.0, 0.0, 0.16 * a), 1.0);
    }
    if focused {
        cv.stroke(rf(r.left - 1.0, r.top - 1.0, r.right + 1.0, r.bottom + 1.0), rad + 1.0, c(p.accent, 0.55), 2.5 * s);
    }
    // quadrado azul com ⌃⌄
    let q = hgt - 6.0 * s;
    let sq = rf(r.right - 3.0 * s - q, cy - q / 2.0, r.right - 3.0 * s, cy + q / 2.0);
    cv.fill(sq, 4.0 * s, c(p.accent, a));
    cv.set(col(1.0, 1.0, 1.0, a));
    let (mx, w_, gap, hh) = ((sq.left + sq.right) / 2.0, q * 0.2, q * 0.1, q * 0.13);
    cv.line((mx - w_, cy - gap), (mx, cy - gap - hh), 1.4 * s);
    cv.line((mx, cy - gap - hh), (mx + w_, cy - gap), 1.4 * s);
    cv.line((mx - w_, cy + gap), (mx, cy + gap + hh), 1.4 * s);
    cv.line((mx, cy + gap + hh), (mx + w_, cy + gap), 1.4 * s);
    // texto escolhido
    let mut t = String::new();
    let sel = send(h, CB_GETCURSEL_, 0, 0);
    if sel >= 0 {
        let n = send(h, CB_GETLBTEXTLEN_, sel as usize, 0);
        if n > 0 {
            let mut b = vec![0u16; n as usize + 1];
            let k = send(h, CB_GETLBTEXT_, sel as usize, b.as_mut_ptr() as isize);
            if k > 0 {
                t = String::from_utf16_lossy(&b[..k as usize]);
            }
        }
    }
    cv.text(&t, rf(r.left + 9.0 * s, r.top, sq.left - 6.0 * s, r.bottom), fs, c(p.text, a), DWRITE_TEXT_ALIGNMENT_LEADING, DWRITE_FONT_WEIGHT_NORMAL, false);
}

// ---- borda arredondada dos campos e das listas (área de fora do cliente)
fn paint_field_frame(h: HWND) {
    unsafe {
        let dc = GetWindowDC(h);
        if dc.0.is_null() {
            return;
        }
        let wr = win_rect(h);
        let r = RECT { left: 0, top: 0, right: wr.right - wr.left, bottom: wr.bottom - wr.top };
        let mut cpt = POINT::default();
        let _ = ClientToScreen(h, &mut cpt);
        let cr = client_rect(h);
        let (l, t) = (cpt.x - wr.left, cpt.y - wr.top);
        ExcludeClipRect(dc, l, t, l + cr.right, t + cr.bottom);
        let p = colors();
        let s = scale(h);
        let focused = GetFocus() == h && class_of(h) == "Edit";
        {
            let cv = Canvas::new(dc, r);
            if cv.ok() {
                cv.fill(rfr(r), 0.0, c1(under_of(h)));
                let f = rf(0.5, 0.5, r.right as f32 - 0.5, r.bottom as f32 - 0.5);
                cv.fill(f, 4.0 * s, c1(p.field));
                cv.stroke(f, 4.0 * s, if focused { c1(p.accent) } else { c1(p.field_border) }, if focused { 2.0 * s } else { 1.0 });
            }
        }
        ReleaseDC(h, dc);
    }
}

// ---- controle deslizante (custom draw do pai)
fn trackbar_draw(cd: &NmCustomDraw) -> isize {
    if cd.stage == CDDS_PREPAINT {
        return CDRF_NOTIFYITEMDRAW;
    }
    if cd.stage != CDDS_ITEMPREPAINT {
        return CDRF_DODEFAULT;
    }
    let h = cd.hdr.from;
    let p = colors();
    let s = scale(h);
    let vert = wstyle(h) & TBS_VERT_ != 0;
    if cd.item == TBCD_CHANNEL {
        let rc = cd.rc;
        let mut thumb = RECT::default();
        send(h, TBM_GETTHUMBRECT, 0, &mut thumb as *mut _ as isize);
        // o canal vem com a altura do Windows; o do Mac é um trilho fino
        let cv = Canvas::new(cd.hdc, rc);
        if cv.ok() {
            cv.fill(rfr(rc), 0.0, c1(under_of(h)));
            let th = 4.0 * s;
            if !vert {
                let cy = (rc.top + rc.bottom) as f32 / 2.0;
                let t = rf(rc.left as f32, cy - th / 2.0, rc.right as f32, cy + th / 2.0);
                cv.fill(t, th / 2.0, c1(p.track));
                let mid = (thumb.left + thumb.right) as f32 / 2.0;
                cv.fill(rf(t.left, t.top, (t.left + th).max(mid), t.bottom), th / 2.0, c1(p.accent));
            } else {
                let cx = (rc.left + rc.right) as f32 / 2.0;
                cv.fill(rf(cx - th / 2.0, rc.top as f32, cx + th / 2.0, rc.bottom as f32), th / 2.0, c1(p.track));
            }
        }
        return CDRF_SKIPDEFAULT;
    }
    if cd.item == TBCD_THUMB {
        let rc = cd.rc;
        let cv = Canvas::new(cd.hdc, rc);
        if cv.ok() {
            cv.fill(rfr(rc), 0.0, c1(under_of(h)));
            let mut d = ((rc.right - rc.left) as f32).min((rc.bottom - rc.top) as f32) - 2.0 * s;
            let (cx, cy) = ((rc.left + rc.right) as f32 / 2.0, (rc.top + rc.bottom) as f32 / 2.0);
            d = d.min(20.0 * s);
            cv.set(col(0.0, 0.0, 0.0, 0.25));
            cv.ellipse(cx, cy + 0.6 * s, d / 2.0 + 0.5);
            cv.set(col(1.0, 1.0, 1.0, 1.0));
            cv.ellipse(cx, cy, d / 2.0);
        }
        return CDRF_SKIPDEFAULT;
    }
    CDRF_DODEFAULT
}

fn is_ours(h: HWND) -> bool {
    unsafe { GetWindowSubclass(h, Some(ctl_proc), SUB_ID, None).as_bool() }
}

// ---- grupos (desenhados no fundo do diálogo, antes dos controles)
fn paint_groups(dlg: HWND, dc: HDC) {
    let p = colors();
    let base = base_of(dlg);
    let dk = dark();
    for cc in child_windows(dlg) {
        if !visible(cc) || !is_group_box(cc) || !is_ours(cc) {
            continue;
        }
        let wr = map_rect(win_rect(cc), dlg);
        let (s, fs) = (scale(cc), font_px(cc));
        let g = group_box_rect(cc);
        let cv = Canvas::new(dc, wr);
        if !cv.ok() {
            continue;
        }
        cv.fill(rfr(wr), 0.0, c1(base));
        let bx = rf(g.left as f32 + 0.5, g.top as f32 + 0.5, g.right as f32 - 0.5, g.bottom as f32 - 0.5);
        cv.fill(bx, 7.0 * s, c1(box_on(base)));
        cv.stroke(bx, 7.0 * s, if dk { col(1.0, 1.0, 1.0, 0.07) } else { col(0.0, 0.0, 0.0, 0.07) }, 1.0);
        // título: em cima da caixa, à esquerda, como os títulos de seção do Mac
        let t = clean_text(cc);
        if !t.is_empty() {
            let tw = text_width(&t, fs * 0.92, DWRITE_FONT_WEIGHT_SEMI_BOLD, false).unwrap_or(0.0);
            let tr = rf(g.left as f32 + 8.0 * s, wr.top as f32, g.left as f32 + 8.0 * s + tw + 10.0 * s, g.top as f32 + fs * 0.75);
            cv.fill(rf(tr.left - 3.0 * s, tr.top, tr.right, g.top as f32 + 1.5 * s), 0.0, c1(base)); // o título "corta" a borda de cima
            cv.text(
                &t,
                rf(tr.left, wr.top as f32, tr.right + 20.0 * s, g.top as f32 + fs * 0.4),
                fs * 0.92,
                c1(p.text2),
                DWRITE_TEXT_ALIGNMENT_LEADING,
                DWRITE_FONT_WEIGHT_SEMI_BOLD,
                false,
            );
        }
    }
}

fn redraw_now(h: HWND, typ: usize) {
    if !visible(h) {
        return;
    }
    unsafe {
        let dc = GetDC(h);
        if dc.0.is_null() {
            return;
        }
        if typ == T_BUTTON {
            if !is_group_box(h) {
                paint_button(h, dc);
            }
        } else if typ == T_TAB {
            paint_tab(h, dc);
        } else if typ == T_COMBO {
            paint_combo(h, dc);
        }
        ReleaseDC(h, dc);
    }
}

fn apply_list_colors(h: HWND, undo: bool) {
    let cls = class_of(h);
    let p = colors();
    let dk = dark() && !undo;
    unsafe {
        let _ = SetWindowTheme(h, if dk { w!("DarkMode_Explorer") } else { PCWSTR::null() }, PCWSTR::null());
        if cls == WC_LISTVIEW {
            let (bk, tx) = if undo { (CLR_DEFAULT, CLR_DEFAULT) } else { (p.field, p.text) };
            send(h, LVM_SETBKCOLOR, 0, bk as isize);
            send(h, LVM_SETTEXTBKCOLOR, 0, bk as isize);
            send(h, LVM_SETTEXTCOLOR, 0, tx as isize);
            let hd = HWND(send(h, LVM_GETHEADER, 0, 0) as *mut _);
            if !hd.0.is_null() {
                let _ = SetWindowTheme(hd, if dk { w!("DarkMode_ItemsView") } else { PCWSTR::null() }, PCWSTR::null());
            }
        } else if cls == WC_TREEVIEW {
            send(h, TVM_SETBKCOLOR, 0, if undo { -1 } else { p.field as isize });
            send(h, TVM_SETTEXTCOLOR, 0, if undo { -1 } else { p.text as isize });
        }
        let _ = InvalidateRect(h, None, true);
    }
}

// ---- caixas de mensagem como o alerta do Mac: sem barra de título, ícone do app grande no meio, título em negrito
// centralizado, texto informativo menor e os botões na largura toda (o principal, azul, à direita; três ou mais, um
// embaixo do outro)
struct Alert {
    title: String,
    info: String,
    app: HICON,
    /// o ícone de aviso/erro do Windows, quando houver
    badge: HICON,
    title_h: f32,
    info_h: f32,
    #[allow(dead_code)]
    before: SIZE, // tamanho do cliente original (para desfazer)
}
static ALERTS: Global<Option<HashMap<isize, Alert>>> = Global::new(None);
fn alerts() -> &'static mut HashMap<isize, Alert> {
    ALERTS.get().get_or_insert_with(HashMap::new)
}
/// Tira o alerta da lista e solta o ícone grande do app (SHDefExtractIcon/ExtractIconEx criam um ícone novo a cada
/// caixa de mensagem; sem o DestroyIcon, cada alerta deixava um objeto USER para trás dentro do programa)
fn erase_alert(h: HWND) -> bool {
    match alerts().remove(&(h.0 as isize)) {
        Some(a) => {
            if !a.app.0.is_null() {
                unsafe {
                    let _ = DestroyIcon(a.app);
                }
            }
            true
        }
        None => false,
    }
}

const AW: f32 = 260.0;
const APAD: f32 = 20.0;
const AICON: f32 = 64.0;
const ABTN: f32 = 28.0;
const AGAP: f32 = 8.0;
// Leopard (alerta do 10.5): 420 de largura, ícone de 64 em (24, 15), o texto a 104 da borda (negrito 13 e 11 embaixo),
// botões em pílula de 21 embaixo à direita, o padrão na ponta direita
const LW: f32 = 420.0;
const LTX: f32 = 104.0;
const LTOP: f32 = 15.0;
const LBTN: f32 = 21.0;

fn dlg_item(dlg: HWND, id: i32) -> Option<HWND> {
    unsafe { GetDlgItem(dlg, id).ok().filter(|h| !h.0.is_null()) }
}
/// caixa de mensagem: diálogo de cima com o texto (id 0xFFFF), ícone (id 20) e só botões de apertar
fn is_message_box(dlg: HWND) -> bool {
    if wstyle(dlg) & WS_CHILD.0 != 0 {
        return false;
    }
    let Some(text) = dlg_item(dlg, 0xFFFF) else { return false };
    if class_of(text) != "Static" {
        return false;
    }
    let mut buttons = 0;
    for cc in child_windows(dlg) {
        let cls = class_of(cc);
        if cls == "Static" {
            continue;
        }
        if cls != "Button" {
            return false;
        }
        let t = wstyle(cc) & BS_TYPEMASK_;
        if t != BS_PUSHBUTTON_ && t != BS_DEFPUSHBUTTON_ {
            return false;
        }
        if visible(cc) {
            buttons += 1;
        }
    }
    (1..=4).contains(&buttons)
}

/// ícone do programa (o .exe deste processo), grande
fn app_icon(px: i32) -> HICON {
    unsafe {
        let mut exe = [0u16; 260];
        let n = GetModuleFileNameW(None, &mut exe) as usize;
        if n >= exe.len() {
            return HICON::default();
        }
        let mut big = HICON::default();
        let _ = SHDefExtractIconW(PCWSTR(exe.as_ptr()), 0, 0, Some(&mut big), None, (px as u32 & 0xFFFF) | (16 << 16));
        if big.0.is_null() {
            ExtractIconExW(PCWSTR(exe.as_ptr()), 0, Some(&mut big), None, 1);
        }
        big
    }
}

fn is_def(b: HWND) -> bool {
    wstyle(b) & BS_TYPEMASK_ == BS_DEFPUSHBUTTON_
}
fn move_win(h: HWND, x: i32, y: i32, w_: i32, hh: i32) {
    unsafe {
        let _ = SetWindowPos(h, None, x, y, w_, hh, SWP_NOZORDER | SWP_NOACTIVATE);
    }
}

fn make_alert(dlg: HWND) {
    let Some(text) = dlg_item(dlg, 0xFFFF) else { return };
    let s = clean_text(text);
    // título e texto informativo: o primeiro parágrafo (ou a primeira frase de um texto longo) é o título
    let mut cut = s.find("\n\n").or_else(|| s.find('\n'));
    if cut.is_none() && s.chars().count() > 90 {
        if let Some(dot) = s.find(['.', '?', '!']) {
            if dot + 1 < s.len() {
                cut = Some(dot + 1);
            }
        }
    }
    let (title, info) = match cut {
        Some(k) => (s[..k].trim().to_string(), s[k..].trim().to_string()),
        None => (s.trim().to_string(), String::new()),
    };
    let s1 = scale(dlg);
    let app = app_icon((AICON * s1) as i32);
    let mut badge = HICON::default();
    unsafe {
        if let Some(ic) = dlg_item(dlg, 20) {
            let hi = HICON(send(ic, STM_GETICON_, 0, 0) as *mut _);
            let warn = LoadIconW(None, IDI_WARNING).unwrap_or_default();
            let err = LoadIconW(None, IDI_ERROR).unwrap_or_default();
            if !hi.0.is_null() && (hi == warn || hi == err) {
                badge = hi;
            }
            let _ = ShowWindow(ic, SW_HIDE);
        }
        let _ = ShowWindow(text, SW_HIDE);
    }
    let leo = comum::leopard::on();
    let inner = if leo { (LW - LTX - 20.0) * s1 } else { (AW - 2.0 * APAD) * s1 };
    let title_h = text_height(&title, 13.0 * s1, DWRITE_FONT_WEIGHT_BOLD, inner);
    let info_h = text_height(&info, 11.0 * s1, DWRITE_FONT_WEIGHT_NORMAL, inner);
    let cr = client_rect(dlg);
    let before = SIZE { cx: cr.right, cy: cr.bottom };
    // botões: o padrão (azul) à direita / em cima
    let mut btns: Vec<HWND> = child_windows(dlg).into_iter().filter(|&cc| class_of(cc) == "Button" && visible(cc)).collect();
    let mut y = APAD * s1 + AICON * s1 + 12.0 * s1 + title_h + if info_h > 0.0 { 6.0 * s1 + info_h } else { 0.0 } + 16.0 * s1;
    let mut ww_ = (AW * s1).round() as i32;
    let pad = (APAD * s1).round() as i32;
    let mut bh = (ABTN * s1).round() as i32;
    let gap = (AGAP * s1).round() as i32;
    if leo {
        // Leopard: botões lado a lado embaixo à direita, o padrão por último (na ponta)
        ww_ = (LW * s1).round() as i32;
        y = (LTOP + AICON).max(LTOP + 2.0 + title_h / s1 + if info_h > 0.0 { 8.0 + info_h / s1 } else { 0.0 }) * s1 + 18.0 * s1;
        let (mut nd, d): (Vec<HWND>, Vec<HWND>) = btns.iter().partition(|&&b| !is_def(b));
        nd.extend(d);
        btns = nd;
        let mut x = ww_ - (20.0 * s1).round() as i32;
        bh = (LBTN * s1).round() as i32;
        for &b in btns.iter().rev() {
            let lab: String = window_text(b).chars().filter(|&ch| ch != '&').collect();
            let bw = ((text_width(&lab, 13.0, DWRITE_FONT_WEIGHT_NORMAL, true).unwrap_or(0.0) + 32.0).max(82.0) * s1).round() as i32;
            move_win(b, x - bw, y as i32, bw, bh + (4.0 * s1).round() as i32);
            x -= bw + (12.0 * s1).round() as i32;
        }
        y += bh as f32 + 4.0 * s1;
    } else if btns.len() <= 2 {
        if btns.len() == 2 && is_def(btns[0]) {
            btns.swap(0, 1);
        }
        let n = btns.len().max(1) as i32;
        let bw = (ww_ - 2 * pad - gap * (n - 1)) / n;
        for (i, &b) in btns.iter().enumerate() {
            move_win(b, pad + i as i32 * (bw + gap), y as i32, bw, bh);
        }
        y += bh as f32;
    } else {
        let (mut d, nd): (Vec<HWND>, Vec<HWND>) = btns.iter().partition(|&&b| is_def(b));
        d.extend(nd);
        for b in d {
            move_win(b, pad, y as i32, ww_ - 2 * pad, bh);
            y += (bh + gap) as f32;
        }
        y -= gap as f32;
    }
    let hh = (y + APAD * s1).round() as i32;
    // janela do tamanho novo, no mesmo centro (a barra de título fica para fora do recorte)
    let wr = win_rect(dlg);
    let mut want = RECT { left: 0, top: 0, right: ww_, bottom: hh };
    unsafe {
        let _ = AdjustWindowRectExForDpi(&mut want, WINDOW_STYLE(wstyle(dlg)), false, WINDOW_EX_STYLE(ex_style(dlg)), GetDpiForWindow(dlg));
    }
    let (w2, h2) = (want.right - want.left, want.bottom - want.top);
    let (cx, cy) = ((wr.left + wr.right) / 2, (wr.top + wr.bottom) / 2);
    erase_alert(dlg); // montado de novo: o ícone anterior sai
    alerts().insert(dlg.0 as isize, Alert { title, info, app, badge, title_h, info_h, before });
    move_win(dlg, cx - w2 / 2, cy - h2 / 2, w2, h2);
}

fn paint_alert(dlg: HWND, dc: HDC) {
    let Some(a) = alerts().get(&(dlg.0 as isize)) else { return };
    let rc = client_rect(dlg);
    let p = colors();
    let s = scale(dlg);
    let (pad, ic) = (APAD * s, AICON * s);
    let rw = rc.right as f32;
    unsafe {
        if comum::leopard::on() {
            // Leopard: o ícone à esquerda e o texto ao lado, alinhado à esquerda (alerta do 10.5)
            {
                let cv = Canvas::new(dc, rc);
                if !cv.ok() {
                    return;
                }
                cv.fill(rfr(rc), 0.0, c1(p.bg));
                let mut y = LTOP * s + 2.0 * s;
                cv.text(&a.title, rf(LTX * s, y, rw - 20.0 * s, y + a.title_h), 13.0 * s, c1(p.text), DWRITE_TEXT_ALIGNMENT_LEADING, DWRITE_FONT_WEIGHT_BOLD, true);
                y += a.title_h + 8.0 * s;
                if a.info_h > 0.0 {
                    cv.text(&a.info, rf(LTX * s, y, rw - 20.0 * s, y + a.info_h), 11.0 * s, c1(p.text), DWRITE_TEXT_ALIGNMENT_LEADING, DWRITE_FONT_WEIGHT_NORMAL, true);
                }
            }
            let (n, x, y) = (ic.round() as i32, (24.0 * s).round() as i32, (LTOP * s).round() as i32);
            if !a.app.0.is_null() {
                let _ = DrawIconEx(dc, x, y, a.app, n, n, 0, None, DI_NORMAL);
            }
            if !a.badge.0.is_null() {
                // o aviso no canto do ícone do app, como no 10.5
                let m = n * 45 / 100;
                let _ = DrawIconEx(dc, x + n - m, y + n - m, a.badge, m, m, 0, None, DI_NORMAL);
            }
            return;
        }
        {
            let cv = Canvas::new(dc, rc);
            if !cv.ok() {
                return;
            }
            cv.fill(rfr(rc), 0.0, c1(p.bg));
            let mut y = pad + ic + 12.0 * s;
            cv.text(&a.title, rf(pad, y, rw - pad, y + a.title_h), 13.0 * s, c1(p.text), DWRITE_TEXT_ALIGNMENT_CENTER, DWRITE_FONT_WEIGHT_BOLD, true);
            y += a.title_h + 6.0 * s;
            if a.info_h > 0.0 {
                cv.text(&a.info, rf(pad, y, rw - pad, y + a.info_h), 11.0 * s, c1(p.text), DWRITE_TEXT_ALIGNMENT_CENTER, DWRITE_FONT_WEIGHT_NORMAL, true);
            }
            if !a.badge.0.is_null() {
                // o triângulo amarelo de atenção do Mac (vetor: cantos arredondados, "!" escuro)
                let (cx, t, b, hw, r) = (rw / 2.0, pad + ic * 0.06, pad + ic * 0.90, ic * 0.47, ic * 0.09);
                if let Some(f) = init() {
                    if let Ok(g) = f.d2d.CreatePathGeometry() {
                        if let Ok(k) = g.Open() {
                            k.BeginFigure(pt(cx, t + r), D2D1_FIGURE_BEGIN_FILLED);
                            k.AddLine(pt(cx + hw - r, b - r));
                            k.AddLine(pt(cx - hw + r, b - r));
                            k.EndFigure(D2D1_FIGURE_END_CLOSED);
                            let _ = k.Close();
                            let sp = D2D1_STROKE_STYLE_PROPERTIES {
                                startCap: D2D1_CAP_STYLE_ROUND,
                                endCap: D2D1_CAP_STYLE_ROUND,
                                dashCap: D2D1_CAP_STYLE_ROUND,
                                lineJoin: D2D1_LINE_JOIN_ROUND,
                                miterLimit: 10.0,
                                dashStyle: D2D1_DASH_STYLE_SOLID,
                                dashOffset: 0.0,
                            };
                            let ss = f.d2d.CreateStrokeStyle(&sp, None).ok();
                            let lg = linear(cv.rt(), &[(0.0, col(1.0, 0.86, 0.25, 1.0)), (1.0, col(0.98, 0.70, 0.05, 1.0))], pt(cx, t), pt(cx, b));
                            let fill: ID2D1Brush = match &lg {
                                Some(l) => l.cast().unwrap(),
                                None => {
                                    cv.set(col(1.0, 0.80, 0.10, 1.0));
                                    cv.br().cast().unwrap()
                                }
                            };
                            cv.rt().FillGeometry(&g, &fill, None);
                            cv.rt().DrawGeometry(&g, &fill, r * 2.0, ss.as_ref());
                            // "!"
                            cv.set(col(0.12, 0.12, 0.12, 1.0));
                            let (bw, top, bot) = (ic * 0.075, t + ic * 0.30, t + ic * 0.58);
                            cv.rt().FillRoundedRectangle(&rr(rf(cx - bw / 2.0, top, cx + bw / 2.0, bot), bw / 2.0, bw / 2.0), cv.br());
                            cv.ellipse(cx, bot + ic * 0.11, bw * 0.62);
                        }
                    }
                }
            }
        }
        // ícones (GDI, por cima): aviso/erro grande com o app pequeno no canto, como no Mac; senão o app
        let (x, y, n) = (((rw - ic) / 2.0).round() as i32, pad.round() as i32, ic.round() as i32);
        if !a.badge.0.is_null() {
            // o triângulo já foi desenhado; o app pequeno no canto, como no Mac
            if !a.app.0.is_null() {
                let m = n * 45 / 100;
                let _ = DrawIconEx(dc, x + n - m + n / 8, y + n - m + n / 10, a.app, m, m, 0, None, DI_NORMAL);
            }
        } else if !a.app.0.is_null() {
            let _ = DrawIconEx(dc, x, y, a.app, n, n, 0, None, DI_NORMAL);
        }
    }
}

fn has_alert(h: HWND) -> bool {
    alerts().contains_key(&(h.0 as isize))
}

unsafe extern "system" fn ctl_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM, _: usize, refdata: usize) -> LRESULT {
    // pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
    crate::guarda(LRESULT(0), || {
        let typ = refdata;
        match m {
            // o diálogo põe a fonte depois de criar
            WM_SETFONT => return DefSubclassProc(h, m, WPARAM(mac_font(HFONT(w_.0 as *mut _)).0 as usize), l),
            WM_NCDESTROY => {
                let _ = RemoveWindowSubclass(h, Some(ctl_proc), SUB_ID);
                segments().remove(&(h.0 as isize));
                erase_alert(h);
            }
            _ => {}
        }
        if typ == 0 {
            return DefSubclassProc(h, m, w_, l); // texto fixo, controle deslizante...: só a fonte
        }
        if typ == T_DIALOG {
            match m {
                WM_PAINT => {
                    // alerta: a caixa de mensagem pintaria a faixa branca de cima por cima do título
                    if has_alert(h) {
                        let mut ps = PAINTSTRUCT::default();
                        let dc = BeginPaint(h, &mut ps);
                        paint_alert(h, dc);
                        let _ = EndPaint(h, &ps);
                        return LRESULT(0);
                    }
                }
                WM_ERASEBKGND => {
                    let dc = HDC(w_.0 as *mut _);
                    if has_alert(h) {
                        paint_alert(h, dc);
                        return LRESULT(1);
                    }
                    let rc = client_rect(h);
                    FillRect(dc, &rc, brush(base_of(h)));
                    paint_groups(h, dc);
                    return LRESULT(1);
                }
                WM_CTLCOLORDLG => return LRESULT(brush(base_of(h)).0 as isize),
                WM_NCHITTEST => {
                    // alerta: sem barra de título, arrasta pelo fundo
                    let r = DefSubclassProc(h, m, w_, l);
                    return if r.0 == HTCLIENT as isize && has_alert(h) { LRESULT(HTCAPTION as isize) } else { r };
                }
                WM_CTLCOLORSTATIC | WM_CTLCOLORBTN => {
                    let cc = HWND(l.0 as *mut _);
                    let dc = HDC(w_.0 as *mut _);
                    let under = under_of(cc);
                    let p = colors();
                    SetTextColor(dc, COLORREF(if IsWindowEnabled(cc).as_bool() { p.text } else { p.text2 }));
                    SetBkColor(dc, COLORREF(under));
                    if class_of(cc) == "Edit" {
                        // campo só de leitura
                        SetBkColor(dc, COLORREF(p.field));
                        return LRESULT(brush(p.field).0 as isize);
                    }
                    return LRESULT(brush(under).0 as isize);
                }
                WM_CTLCOLOREDIT | WM_CTLCOLORLISTBOX => {
                    let dc = HDC(w_.0 as *mut _);
                    let p = colors();
                    SetTextColor(dc, COLORREF(p.text));
                    SetBkColor(dc, COLORREF(p.field));
                    return LRESULT(brush(p.field).0 as isize);
                }
                WM_NOTIFY => {
                    let nm = &*(l.0 as *const Nmhdr);
                    if nm.code == NM_CUSTOMDRAW_ && class_of(nm.from) == WC_TRACKBAR {
                        let r = trackbar_draw(&*(l.0 as *const NmCustomDraw));
                        comum::util::set_wlp(h, WINDOW_LONG_PTR_INDEX(0), r); // DWLP_MSGRESULT: em diálogos a resposta do WM_NOTIFY vai aqui
                        return LRESULT(r);
                    }
                }
                WM_SETTINGCHANGE | WM_THEMECHANGED => {
                    let _ = RedrawWindow(h, None, None, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN | RDW_FRAME);
                }
                _ => {}
            }
            return DefSubclassProc(h, m, w_, l);
        }
        if typ == T_EDIT || typ == T_LIST {
            if m == WM_NCPAINT {
                let r = DefSubclassProc(h, m, w_, l);
                paint_field_frame(h);
                return r;
            }
            let r = DefSubclassProc(h, m, w_, l);
            if m == WM_SETFOCUS || m == WM_KILLFOCUS || m == WM_ENABLE {
                paint_field_frame(h);
            }
            return r;
        }
        if typ == T_BUTTON && is_group_box(h) {
            // o grupo é desenhado no fundo do diálogo
            if m == WM_PAINT {
                let mut ps = PAINTSTRUCT::default();
                BeginPaint(h, &mut ps);
                let _ = EndPaint(h, &ps);
                return LRESULT(0);
            }
            if m == WM_ERASEBKGND {
                return LRESULT(1);
            }
            if m == WM_SETTEXT {
                let r = DefSubclassProc(h, m, w_, l);
                let _ = InvalidateRect(parent(h), None, true);
                return r;
            }
            return DefSubclassProc(h, m, w_, l);
        }
        if typ == T_TAB && m == WM_LBUTTONDOWN {
            // os segmentos não ficam onde o Windows põe as abas
            let p = POINT { x: comum::get_x_lparam(l), y: comum::get_y_lparam(l) };
            let hit = segments().get(&(h.0 as isize)).and_then(|v| v.iter().position(|r| PtInRect(r, p).as_bool()));
            if let Some(i) = hit {
                let _ = SetFocus(h);
                send(h, TCM_SETCURFOCUS, i, 0);
                redraw_now(h, typ);
            }
            return LRESULT(0);
        }
        if m == WM_PAINT || m == WM_PRINTCLIENT {
            let mut ps = PAINTSTRUCT::default();
            let dc = if m == WM_PAINT { BeginPaint(h, &mut ps) } else { HDC(w_.0 as *mut _) };
            match typ {
                T_BUTTON => paint_button(h, dc),
                T_TAB => paint_tab(h, dc),
                T_COMBO => paint_combo(h, dc),
                _ => {}
            }
            if m == WM_PAINT {
                let _ = EndPaint(h, &ps);
            }
            return LRESULT(0);
        }
        if m == WM_ERASEBKGND {
            return LRESULT(1);
        }
        let r = DefSubclassProc(h, m, w_, l);
        // o Windows desenha alguns estados direto, sem WM_PAINT: por cima vai o nosso desenho de novo
        match m {
            BM_SETSTATE_ | BM_SETCHECK_ | BM_SETSTYLE_ | BM_CLICK_ | WM_SETTEXT | WM_ENABLE | WM_SETFOCUS | WM_KILLFOCUS | WM_LBUTTONDOWN | WM_LBUTTONUP | WM_LBUTTONDBLCLK
            | WM_KEYDOWN | WM_KEYUP | WM_MOUSELEAVE_ | WM_CAPTURECHANGED | WM_UPDATEUISTATE_ | CB_SETCURSEL_ | CB_SELECTSTRING_ | TCM_SETCURSEL | TCM_SETCURFOCUS | WM_TIMER => {
                redraw_now(h, typ)
            }
            _ => {}
        }
        r
    })
}
const WM_MOUSELEAVE_: u32 = 0x02A3;

fn sub(h: HWND, typ: usize) {
    if is_ours(h) {
        return;
    }
    unsafe {
        let f = get_font(h);
        if !f.0.is_null() && GetPropW(h, PROP_FONT).0.is_null() {
            let _ = SetPropW(h, PROP_FONT, HANDLE(f.0));
        }
        let _ = SetWindowSubclass(h, Some(ctl_proc), SUB_ID, typ);
        if !f.0.is_null() {
            send(h, WM_SETFONT, mac_font(f).0 as usize, 0);
        }
        if typ == T_LIST {
            apply_list_colors(h, false);
        }
        if typ == T_EDIT || typ == T_LIST {
            let _ = SetWindowPos(h, None, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
        }
        let _ = InvalidateRect(h, None, true);
    }
}

pub fn is_dialog(h: HWND) -> bool {
    class_of(h) == "#32770"
}
pub fn is_alert(h: HWND) -> bool {
    has_alert(h)
}

pub fn child(h: HWND) {
    if init().is_none() {
        return;
    }
    let cls = class_of(h);
    let (st, ex) = (wstyle(h), ex_style(h));
    if cls == "#32770" {
        sub(h, T_DIALOG);
    } else if cls == "Button" {
        if our_button(h) {
            sub(h, T_BUTTON);
        }
    } else if cls == WC_TAB {
        if st & (TCS_BUTTONS_ | TCS_VERTICAL_ | TCS_OWNERDRAWFIXED_) == 0 {
            sub(h, T_TAB);
        }
    } else if cls == WC_COMBO {
        if st & 3 == CBS_DROPDOWNLIST_ && st & (CBS_OWNERDRAWFIXED_ | CBS_OWNERDRAWVARIABLE_) == 0 {
            sub(h, T_COMBO);
        }
    } else if cls == "Edit" {
        if ex & WS_EX_CLIENTEDGE.0 != 0 || st & WS_BORDER.0 != 0 {
            sub(h, T_EDIT);
        } else {
            sub(h, 0);
        }
    } else if cls == WC_LISTVIEW || cls == WC_TREEVIEW || cls == "ListBox" {
        sub(h, T_LIST);
    } else if cls == "Static" || cls == WC_TRACKBAR || cls == WC_UPDOWN {
        sub(h, 0); // só a fonte (e as cores pelo pai)
    }
}

unsafe extern "system" fn enum_child(cc: HWND, _: LPARAM) -> BOOL {
    // pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
    crate::guarda(FALSE, || {
        child(cc);
        TRUE
    })
}
pub fn style_top(top: HWND) {
    if init().is_none() {
        return;
    }
    unsafe {
        let _ = SetPropW(top, w!("MacCtl"), HANDLE(1 as *mut _)); // controles criados depois também entram (gancho em mj6.rs)
        child(top);
        let _ = EnumChildWindows(top, Some(enum_child), LPARAM(0));
        if is_message_box(top) {
            make_alert(top);
        }
        let _ = RedrawWindow(top, None, None, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN | RDW_FRAME);
    }
}
pub use style_top as style;

fn undo_one(cc: HWND) {
    unsafe {
        let mut refd = 0usize;
        if !GetWindowSubclass(cc, Some(ctl_proc), SUB_ID, Some(&mut refd)).as_bool() {
            return;
        }
        let _ = RemoveWindowSubclass(cc, Some(ctl_proc), SUB_ID);
        if let Ok(f) = RemovePropW(cc, PROP_FONT) {
            if !f.0.is_null() {
                send(cc, WM_SETFONT, f.0 as usize, 0);
            }
        }
        if refd == T_LIST {
            apply_list_colors(cc, true);
        }
        let _ = SetWindowPos(cc, None, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
    }
}
unsafe extern "system" fn enum_undo(cc: HWND, _: LPARAM) -> BOOL {
    // pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
    crate::guarda(FALSE, || {
        undo_one(cc);
        TRUE
    })
}
pub fn unstyle(top: HWND) {
    unsafe {
        let _ = RemovePropW(top, w!("MacCtl"));
        if erase_alert(top) {
            // alerta: os textos do Windows voltam (o tamanho fica)
            if let Some(t) = dlg_item(top, 0xFFFF) {
                let _ = ShowWindow(t, SW_SHOW);
            }
            if let Some(i) = dlg_item(top, 20) {
                let _ = ShowWindow(i, SW_SHOW);
            }
        }
        undo_one(top);
        let _ = EnumChildWindows(top, Some(enum_undo), LPARAM(0));
        let _ = RedrawWindow(top, None, None, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN | RDW_FRAME);
    }
}