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
151 KB
Raw Blame
//! Ajustes do Sistema (src\ajustes\main.cpp): janela, barra lateral, barra de ferramentas, grupos e controles no visual
//! do macOS (Sequoia, Tahoe, Golden Gate) e as Preferências do Sistema do Mac OS X Leopard. As páginas estão em
//! paginas*.rs e o que elas leem e mudam no Windows em sistema.rs.
//! Diferenças do C++: desenha numa HwndRenderTarget (o C++ usa o Direct2D do Finder sobre DirectComposition, com a cena
//! desfocada por baixo da busca e da barra de ferramentas no Tahoe, a sombra própria e o acrílico do DWM atrás da
//! lateral do Sequoia); aqui a lateral e o painel de vidro do Tahoe levam a cor do vidro, chapada, e a barra de cima é
//! opaca. A rolagem anda num temporizador (o C++ espera cada quadro do compositor com o DwmFlush numa thread).
//!   WacOSSettings.exe [--pagina=<id>|ms-settings:...] [--foto <pasta> [--tema=sequoia|tahoe|golden|leopard] [--escuro]]
#![windows_subsystem = "windows"]

mod modelo;
mod paginas;
mod paginas2;
mod paginas3;
mod sistema;

use std::collections::{BTreeMap, HashMap, HashSet};
use std::ffi::c_void;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};
use std::sync::Mutex;

use comum::app2d::{self, d2d, dw};
use comum::campo::TextField;
use comum::ctxmenu::{self, 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::DXGI_FORMAT_B8G8R8A8_UNORM;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::Graphics::Imaging::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::DataExchange::COPYDATASTRUCT;
use comum::windows::Win32::System::LibraryLoader::GetModuleHandleW;
use comum::windows::Win32::System::Registry::*;
use comum::windows::Win32::System::SystemInformation::GetTickCount;
use comum::windows::Win32::UI::Controls::{MARGINS, WM_MOUSELEAVE};
use comum::windows::Win32::UI::HiDpi::*;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

use modelo::*;
use paginas::*;
use paginas3::{open_update_page, sidebar_index_for, sidebar_items, symbol_for};

const SIDE_GAP: f32 = 12.0;
const SEARCH_H: f32 = 28.0;
const ACCOUNT_H: f32 = 50.0;
const PAD: f32 = 20.0;
const GROUP_R: f32 = 8.0;
const GROUP_GAP: f32 = 11.0;
const WM_APP_REBUILD: u32 = WM_APP + 1;
const WM_APP_BITMAP: u32 = WM_APP + 2;
const WM_APP_NA_INTERFACE: u32 = WM_APP + 3;
const T_REFRESH: usize = 1;
const T_ANIM: usize = 2;
/// issue #369: rolagem no ritmo da tela, como no C++ (LigaRelogio). O SetTimer de 15 ms chega a ~64 Hz, fora do
/// compasso da tela (60, 120, 144 Hz), e a rolagem do lado direito dava trancos. Uma thread espera cada quadro do
/// compositor (DwmFlush) e pede um passo; ela para quando a rolagem chega ao destino.
const WM_QUADRO: u32 = WM_APP + 77;
static RELOGIO: AtomicBool = AtomicBool::new(false);
static QUADRO_PENDENTE: AtomicBool = AtomicBool::new(false);
fn liga_relogio(h: HWND) {
    if RELOGIO.swap(true, Ordering::SeqCst) {
        return;
    }
    let hv = h.0 as isize;
    std::thread::spawn(move || {
        let h = HWND(hv as *mut c_void);
        while RELOGIO.load(Ordering::SeqCst) {
            unsafe {
                let _ = DwmFlush();
                if !RELOGIO.load(Ordering::SeqCst) || !IsWindow(h).as_bool() {
                    break;
                }
                if !QUADRO_PENDENTE.swap(true, Ordering::SeqCst) {
                    let _ = PostMessageW(h, WM_QUADRO, WPARAM(0), LPARAM(0));
                }
            }
        }
        RELOGIO.store(false, Ordering::SeqCst);
    });
}
const T_CARET: usize = 3;
const T_FRENTE: usize = 4;
const T_BARRA: usize = 5;
const T_SLIDE: usize = 0x534C;

#[derive(Clone, Copy, PartialEq)]
enum H {
    Light,
    Back,
    Fwd,
    Search,
    Side,
    Account,
    Row,
    Toggle,
    Popup,
    Slider,
    Link,
    Button,
    Custom,
    SheetOk,
    SheetCancel,
    SheetField,
    ShowAll,
}
#[derive(Clone, Copy)]
struct Hit {
    kind: H,
    r: RectF,
    a: i32,
    b: i32,
}
fn hit(kind: H, r: RectF, a: i32, b: i32) -> Hit {
    Hit { kind, r, a, b }
}
#[derive(Clone)]
struct Entry {
    side: i32,
    /// subpáginas abertas a partir da página da barra lateral
    stack: Vec<(String, Builder)>,
}
#[derive(Default)]
struct Sheet {
    open: bool,
    title: String,
    message: String,
    ok_label: String,
    password: bool,
    field: TextField,
    ok: Option<Rc<dyn Fn(String)>>,
}
#[derive(Clone, Copy)]
struct Pal {
    side: Cor,
    content: Cor,
    text: Cor,
    text2: Cor,
    text3: Cor,
    line: Cor,
    group: Cor,
    group_line: Cor,
    control: Cor,
    side_sel: Cor,
    side_sel_text: Cor,
    divider: Cor,
}
struct Fonts {
    body: IDWriteTextFormat,
    side: IDWriteTextFormat,
    small: IDWriteTextFormat,
    bold: IDWriteTextFormat,
    title: IDWriteTextFormat,
    glyph: IDWriteTextFormat,
    glyph_small: IDWriteTextFormat,
    center: IDWriteTextFormat,
    small_center: IDWriteTextFormat,
    small_bold_center: IDWriteTextFormat,
    tile_text: IDWriteTextFormat,
    // Leopard: Lucida Grande no Mac; no Windows a Lucida Sans Unicode
    lf: IDWriteTextFormat,
    lf_r: IDWriteTextFormat,
    lf_b: IDWriteTextFormat,
    lf_s: IDWriteTextFormat,
    lf_sc: IDWriteTextFormat,
    lf_t: IDWriteTextFormat,
}
/// as medidas que mudam com o tema (ApplyWindowTheme)
#[derive(Clone, Copy)]
struct M {
    side_w: f32,
    tool_h: f32,
    side_row: f32,
    row_h: f32,
    search_y: f32,
    account_y: f32,
}
struct App {
    hwnd: HWND,
    rt: Option<ID2D1RenderTarget>,
    hrt: Option<ID2D1HwndRenderTarget>,
    scale: f32,
    dark: bool,
    win_active: bool,
    hover_lights: bool,
    tahoe: bool,
    leo_all: bool,
    m: M,
    f: Fonts,
    hist: Vec<Entry>,
    hist_at: i32,
    page: Page,
    scroll: f32,
    scroll_target: f32,
    content_h: f32,
    side_scroll: f32,
    side_h: f32,
    search: TextField,
    search_focus: bool,
    caret_at: u32,
    sheet: Sheet,
    hits: Vec<Hit>,
    drag: (i32, i32, RectF),
    toggle_anim: HashMap<String, (u32, bool)>,
    side_visible: Vec<usize>,
    barra_ate: u32,
    barra_hover: bool,
    barra_pega: f32,
    tile_bare: bool,
    foto: Option<(f32, f32)>,
    last_anim: u32,
}
static A: Global<Option<App>> = Global::new(None);
fn a() -> &'static mut App {
    A.get().as_mut().unwrap()
}
static HWND_ATOM: AtomicIsize = AtomicIsize::new(0);
static FOTO: AtomicBool = AtomicBool::new(false);
pub fn modo_foto() -> bool {
    FOTO.load(Ordering::Relaxed)
}

// ================= ajustes.txt (%APPDATA%\Shell)
static SETTINGS: Global<BTreeMap<String, String>> = Global::new(BTreeMap::new());
static SETTINGS_PATH: Global<String> = Global::new(String::new());
static SLIDE: Global<(bool, u32, String)> = Global::new((false, 0, String::new())); // arrastando, último envio, chave pendente
fn load_settings() {
    // sem conseguir abrir (arquivo trocado naquele instante), fica o que já estava lido
    if modo_foto() {
        return;
    }
    if let Ok(m) = ajustes::ler(std::path::Path::new(SETTINGS_PATH.get().as_str())) {
        *SETTINGS.get() = m;
    }
}
pub fn setting(k: &str, def: &str) -> String {
    SETTINGS.get().get(k).cloned().unwrap_or_else(|| def.to_string())
}
fn flush_slide() {
    let s = SLIDE.get();
    if !a().hwnd.0.is_null() {
        unsafe {
            let _ = KillTimer(a().hwnd, T_SLIDE);
        }
    }
    if s.2.is_empty() {
        return;
    }
    let k = std::mem::take(&mut s.2);
    let v = setting(&k, "");
    s.1 = 0;
    set_setting(&k, &v);
}
/// grava e avisa o Shell para recarregar. No modo foto, só na memória (a foto nunca muda os ajustes do usuário).
pub fn set_setting(k: &str, v: &str) {
    if modo_foto() {
        SETTINGS.get().insert(k.into(), v.into());
        if k == "tema" || k == "destaque" {
            a().dark = read_dark();
        }
        return;
    }
    let s = SLIDE.get();
    let now = unsafe { GetTickCount() };
    // arrastando um slider: o arquivo e o Shell recebem no máximo a cada 120 ms; o último sempre chega
    if s.0 && now.wrapping_sub(s.1) < 120 {
        SETTINGS.get().insert(k.into(), v.into());
        if !s.2.is_empty() && s.2 != k {
            flush_slide();
        }
        SLIDE.get().2 = k.into();
        unsafe {
            SetTimer(a().hwnd, T_SLIDE, 130, None);
        }
        return;
    }
    s.1 = now;
    if s.2 == k {
        s.2.clear();
        unsafe {
            let _ = KillTimer(a().hwnd, T_SLIDE);
        }
    }
    load_settings(); // o Shell também grava aqui: parte do arquivo atual
    SETTINGS.get().insert(k.into(), v.into());
    let _ = ajustes::gravar(std::path::Path::new(SETTINGS_PATH.get().as_str()), SETTINGS.get()); // atômico
    // avisa o Shell; a mudança vai junto (este app pode estar num contêiner que desvia o %APPDATA%)
    if let Some(sh) = paginas2::shell_msg_window() {
        let kv = wz(&format!("{k}={v}"));
        let cd = COPYDATASTRUCT { dwData: 0x534A5354, cbData: (kv.len() * 2) as u32, lpData: kv.as_ptr() as *mut c_void };
        let mut r = 0usize;
        unsafe {
            if SendMessageTimeoutW(sh, WM_COPYDATA, WPARAM(a().hwnd.0 as usize), LPARAM(&cd as *const _ as isize), SMTO_ABORTIFHUNG, 500, Some(&mut r)).0 == 0 || r == 0 {
                let _ = PostMessageW(sh, reg_msg("ShellAjustesMudaram"), WPARAM(0), LPARAM(0));
            }
        }
    }
    if k == "tema" || k == "destaque" {
        a().dark = read_dark();
    }
}
fn read_dark() -> bool {
    if leo_theme() {
        return false; // Leopard: sempre claro (o 10.5 não tinha modo escuro)
    }
    match setting("tema", "auto").as_str() {
        "claro" => false,
        "escuro" => true,
        _ => {
            if modo_foto() {
                return FOTO_ESCURO.load(Ordering::Relaxed);
            }
            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 u32 as *mut c_void), Some(&mut cb));
            }
            v == 0
        }
    }
}
static FOTO_ESCURO: AtomicBool = AtomicBool::new(false);

// ================= API para as páginas
pub fn tahoe_on() -> bool {
    setting("liquid_glass", "0") == "1"
}
fn leo_theme() -> bool {
    !tahoe_on() && setting("leopard", "0") == "1"
}
fn golden() -> bool {
    a().tahoe && setting("golden_gate", "0") == "1"
}
fn leo() -> bool {
    !a().tahoe && leo_theme()
}
pub fn rebuild() {
    let h = HWND_ATOM.load(Ordering::Relaxed);
    if h != 0 {
        unsafe {
            let _ = PostMessageW(HWND(h as *mut c_void), WM_APP_REBUILD, WPARAM(0), LPARAM(0));
        }
    } else if A.get().is_some() && modo_foto() {
        // a foto refaz a página na hora
    }
}
pub fn redraw() {
    invalidate();
}
pub fn window() -> HWND {
    a().hwnd
}
/// roda f na thread da interface (de uma thread: Setting/SetSetting não são para várias)
pub fn na_interface(f: Box<dyn FnOnce() + Send>) {
    let h = HWND_ATOM.load(Ordering::Relaxed);
    let p = Box::into_raw(Box::new(f));
    unsafe {
        if h == 0 || PostMessageW(HWND(h as *mut c_void), WM_APP_NA_INTERFACE, WPARAM(0), LPARAM(p as isize)).is_err() {
            drop(Box::from_raw(p));
        }
    }
}
pub fn dark() -> bool {
    a().dark
}
pub fn accent() -> Cor {
    const COLS: [(&str, u32); 9] = [("azul", 0x007AFF), ("roxo", 0x953D96), ("rosa", 0xF74F9E), ("vermelho", 0xE0383E), ("laranja", 0xF7821B), ("amarelo", 0xFCB827), ("verde", 0x62BA46), ("grafite", 0x8C8C8C), ("lavanda", 0x98A8D9)];
    let d = setting("destaque", "azul");
    COLS.iter().find(|(n, _)| *n == d).map(|(_, c)| gg_rgb(*c)).unwrap_or(gg_rgb(if a().dark { 0x0A84FF } else { 0x007AFF }))
}
/// ms-settings:..., arquivos, URLs
pub fn open_uri(u: &str) {
    if modo_foto() {
        return;
    }
    if u.starts_with("ms-settings:") {
        unsafe {
            let ok = (|| -> Result<()> {
                let am: IApplicationActivationManager = CoCreateInstance(&ApplicationActivationManager, None, CLSCTX_LOCAL_SERVER)?;
                let uw = wz(u);
                let it: IShellItem = SHCreateItemFromParsingName(pc(&uw), None)?;
                let arr: IShellItemArray = SHCreateShellItemArrayFromShellItem(&it)?;
                let _ = CoAllowSetForegroundWindow(&am, None);
                am.ActivateForProtocol(w!("windows.immersivecontrolpanel_cw5n1h2txyewy!microsoft.windows.immersivecontrolpanel"), &arr)?;
                Ok(())
            })();
            if ok.is_ok() {
                return;
            }
        }
    }
    shell_open(u, None);
}
pub fn push(title: &str, b: Builder) {
    if a().hist_at < 0 {
        return;
    }
    let mut e = a().hist[a().hist_at as usize].clone();
    e.stack.push((title.into(), b.clone()));
    let at = a().hist_at as usize;
    a().hist.truncate(at + 1);
    a().hist.push(e);
    a().hist_at += 1;
    a().page = b();
    a().page.title = title.into();
    a().scroll = 0.0;
    a().scroll_target = 0.0;
    invalidate();
}
pub fn select_side_id(id: &str) {
    let i = sidebar_index_for(id);
    if i >= 0 {
        select_side(i as usize);
    }
}
/// todo texto das páginas passa por aqui: o idioma (Geral > Idioma) se aplica no desenho
pub fn text(c: &Ctx, s: &str, r: RectF, tf: &IDWriteTextFormat, cor: Cor) {
    if s.is_empty() {
        return;
    }
    unsafe {
        c.br.SetColor(&cor);
        c.rt.DrawText(&w(&tr(s)), tf, &r, &c.br, D2D1_DRAW_TEXT_OPTIONS_CLIP | D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT, DWRITE_MEASURING_MODE_NATURAL);
    }
}
pub fn text_width(s: &str, tf: &IDWriteTextFormat) -> f32 {
    unsafe {
        let Ok(l) = dw().CreateTextLayout(&w(&tr(s)), tf, 4000.0, 100.0) else { return 0.0 };
        let mut m = DWRITE_TEXT_METRICS::default();
        let _ = l.GetMetrics(&mut m);
        m.widthIncludingTrailingWhitespace
    }
}
fn text_height(s: &str, tf: &IDWriteTextFormat, width: f32) -> f32 {
    unsafe {
        let Ok(l) = dw().CreateTextLayout(&w(&tr(s)), tf, width.max(10.0), 4000.0) else { return 0.0 };
        let _ = l.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
        let mut m = DWRITE_TEXT_METRICS::default();
        let _ = l.GetMetrics(&mut m);
        m.height
    }
}
pub fn fmt_center() -> IDWriteTextFormat {
    a().f.center.clone()
}
fn brush(c: &Ctx) -> ID2D1Brush {
    c.br.cast().unwrap()
}
fn half_disc(c: &Ctx, r: RectF, ink: Cor) {
    // Aparência: círculo metade preto, metade branco
    let m = pt((r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0);
    let rad = (r.right - r.left) * 0.3;
    unsafe {
        c.br.SetColor(&ink);
        c.rt.DrawEllipse(&ell(m, rad, rad), &c.br, 1.2, None);
        c.rt.PushAxisAlignedClip(&rf(m.x, m.y - rad - 1.0, m.x + rad + 1.0, m.y + rad + 1.0), D2D1_ANTIALIAS_MODE_ALIASED);
        c.rt.FillEllipse(&ell(m, rad, rad), &c.br);
        c.rt.PopAxisAlignedClip();
    }
}
/// o vidro: fio claro e brilho nos cantos (vidro::Borda do C++, a versão clara)
fn glass_rim(c: &Ctx, r: RectF, rad: f32, k: f32) {
    unsafe { comum::vidro::borda(&c.rt, r, rad, 1.0, c.dark, k, true, 1.0, -1.0, -1.0) }
}
/// quadradinho colorido com ícone branco (SF Symbol se houver)
pub fn tile(c: &Ctx, r: RectF, glyph: u16, color: u32, symbol: &str) {
    let w_ = r.right - r.left;
    unsafe {
        // Tahoe: os ícones seguem Aparência > Estilo de ícones e widgets (Escuro, Transparente, Tingido)
        let mut est = if a().tahoe { setting("estilo_icones", "padrao") } else { "padrao".into() };
        if est == "escuro" && setting("estilo_escuro_auto", "0") == "1" && !a().dark {
            est = "padrao".into();
        }
        let glyph_fmt = |w_: f32| if glyph < 0xE000 { &a().f.tile_text } else if w_ > 22.0 { &c.glyph } else { &c.glyph_small };
        if est == "transparente" {
            tile_clear(c, r, glyph, symbol);
            return;
        }
        if est == "escuro" || est == "tingido" {
            let mut ink = col(1.0, 1.0, 1.0, 1.0);
            if est == "escuro" {
                fill_rr(c, r, w_ * 0.24, col(0.17, 0.17, 0.18, 1.0));
                let k = gg_rgb(color);
                ink = col((k.r * 1.15 + 0.08).min(1.0), (k.g * 1.15 + 0.08).min(1.0), (k.b * 1.15 + 0.08).min(1.0), 1.0);
            } else {
                let acc = accent();
                fill_rr(c, r, w_ * 0.24, if est == "tingido" {
                    col(acc.r, acc.g, acc.b, if c.dark { 0.62 } else { 0.72 })
                } else if c.dark {
                    col(1.0, 1.0, 1.0, 0.14)
                } else {
                    col(1.0, 1.0, 1.0, 0.55)
                });
                glass_rim(c, r, w_ * 0.24, 1.0);
                if est == "transparente" && !c.dark {
                    ink = col(0.3, 0.3, 0.33, 1.0);
                }
            }
            let m = w_ * 0.19;
            c.br.SetColor(&ink);
            if !symbol.is_empty() && simbolo::draw(&c.rt, symbol, rf(r.left + m, r.top + m, r.right - m, r.bottom - m), &brush(c)) {
                return;
            }
            if glyph == 1 {
                half_disc(c, r, ink);
                return;
            }
            if glyph != 0 {
                text(c, &g1(glyph), r, glyph_fmt(w_), ink);
            }
            return;
        }
        if a().tahoe && est == "transparente" {
            tile_clear(c, r, glyph, symbol); // Tahoe, estilo transparente: o símbolo na cor do texto, sem o quadradinho
            return;
        }
        // quadradinho com gradiente leve (mais claro em cima), como os ícones do Ajustes do Mac
        let apple_ai = symbol == "apple.intelligence";
        let base = gg_rgb(color);
        let top = col((base.r * 1.08 + 0.05).min(1.0), (base.g * 1.08 + 0.05).min(1.0), (base.b * 1.08 + 0.05).min(1.0), 1.0);
        let lg = if apple_ai {
            // o degradê do Apple Intelligence, na diagonal
            gradient(c, &[(0.0, col(1.0, 0.78, 0.25, 1.0)), (0.3, col(1.0, 0.5, 0.2, 1.0)), (0.55, col(1.0, 0.3, 0.5, 1.0)), (0.78, col(0.7, 0.38, 1.0, 1.0)), (1.0, col(0.22, 0.52, 1.0, 1.0))], pt(r.left, r.top), pt(r.right, r.bottom))
        } else {
            gradient(c, &[(0.0, top), (1.0, base)], pt(0.0, r.top), pt(0.0, r.bottom))
        };
        match lg {
            Some(lg) => c.rt.FillRoundedRectangle(&rr(r, w_ * 0.24, w_ * 0.24), &lg),
            None => fill_rr(c, r, w_ * 0.24, base),
        }
        if !symbol.is_empty() {
            // SF Symbol branco, ~62% do quadradinho
            let m = w_ * 0.19;
            c.br.SetColor(&col(1.0, 1.0, 1.0, 1.0));
            if simbolo::draw(&c.rt, symbol, rf(r.left + m, r.top + m, r.right - m, r.bottom - m), &brush(c)) {
                return;
            }
        }
        if glyph == 1 {
            half_disc(c, r, col(1.0, 1.0, 1.0, 1.0));
            return;
        }
        if glyph != 0 {
            text(c, &g1(glyph), r, glyph_fmt(w_), col(1.0, 1.0, 1.0, 1.0));
        }
    }
}
/// Tahoe, estilo "transparente": na barra lateral só o símbolo; no conteúdo um quadradinho cinza translúcido
fn tile_clear(c: &Ctx, r: RectF, glyph: u16, symbol: &str) {
    let w_ = r.right - r.left;
    unsafe {
        if !a().tile_bare {
            fill_rr(c, r, w_ * 0.24, if c.dark { col(1.0, 1.0, 1.0, 0.1) } else { col(0.0, 0.0, 0.0, 0.06) });
        }
        let ink = if c.dark { col(1.0, 1.0, 1.0, 0.85) } else { col(0.0, 0.0, 0.0, 0.72) };
        let m = w_ * if a().tile_bare { 0.14 } else { 0.19 };
        if !symbol.is_empty() {
            c.br.SetColor(&ink);
            if simbolo::draw(&c.rt, symbol, rf(r.left + m, r.top + m, r.right - m, r.bottom - m), &brush(c)) {
                return;
            }
        }
        if glyph == 1 {
            half_disc(c, r, ink);
            return;
        }
        if glyph != 0 {
            text(c, &g1(glyph), r, if glyph < 0xE000 { &a().f.tile_text } else if w_ > 22.0 { &c.glyph } else { &c.glyph_small }, ink);
        }
    }
}
fn tile_any(c: &Ctx, r: RectF, glyph: u16, color: u32, symbol: &str) {
    tile(c, r, glyph, color, symbol);
}

// ================= imagens (miniaturas de fundo de tela, foto da conta, ícones do Leopard)
struct BmpResult {
    key: String,
    px: Option<(u32, u32, Vec<u8>)>,
}
static BMP_PX: Mutex<Option<HashMap<String, Option<(u32, u32, Vec<u8>)>>>> = Mutex::new(None);
static BMP_PENDING: Mutex<Option<HashSet<String>>> = Mutex::new(None);
static BMP_D2D: Global<Option<HashMap<String, ID2D1Bitmap>>> = Global::new(None);
fn load_pixels(path: &str, max_px: u32) -> Option<(u32, u32, Vec<u8>)> {
    // miniatura: primeiro a do cache do Windows (rápida, sem decodificar a imagem inteira)
    if max_px <= 512 {
        if let Some((w_, h, mut px)) = shell_thumbnail(path, max_px as i32, SIIGBF_RESIZETOFIT | SIIGBF_THUMBNAILONLY) {
            if w_ > 0 && h > 0 {
                if !px.iter().skip(3).step_by(4).any(|&x| x != 0) {
                    px.iter_mut().skip(3).step_by(4).for_each(|x| *x = 255); // foto: sem alfa
                }
                return Some((w_, h, px));
            }
        }
    }
    unsafe {
        let f: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).ok()?;
        let p = wz(path);
        let dec = f.CreateDecoderFromFilename(pc(&p), None, GENERIC_READ, WICDecodeMetadataCacheOnDemand).ok()?;
        let fr = dec.GetFrame(0).ok()?;
        let (mut w0, mut h0) = (0, 0);
        fr.GetSize(&mut w0, &mut h0).ok()?;
        let k = (max_px as f32 / w0.max(h0) as f32).min(1.0);
        let (w1, h1) = (((w0 as f32 * k) as u32).max(1), ((h0 as f32 * k) as u32).max(1));
        let sc = f.CreateBitmapScaler().ok()?;
        sc.Initialize(&fr, w1, h1, WICBitmapInterpolationModeFant).ok()?;
        let cv = f.CreateFormatConverter().ok()?;
        cv.Initialize(&sc, &GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).ok()?;
        let mut px = vec![0u8; (w1 * h1 * 4) as usize];
        cv.CopyPixels(std::ptr::null(), w1 * 4, &mut px).ok()?;
        Some((w1, h1, px))
    }
}
/// miniatura (cache); None se ainda não carregou
pub fn bitmap_from_file(path: &str, max_px: u32) -> Option<ID2D1Bitmap> {
    if path.is_empty() {
        return None;
    }
    let key = format!("{path}|{max_px}");
    if let Some(b) = BMP_D2D.get().get_or_insert_with(HashMap::new).get(&key) {
        return Some(b.clone());
    }
    let px = BMP_PX.lock().unwrap().get_or_insert_with(HashMap::new).get(&key).cloned();
    match px {
        Some(Some((w_, h, px))) => {
            let rt = a().rt.clone()?;
            let b = unsafe { bitmap_bgra(&rt, w_, h, &px) }?;
            BMP_D2D.get().get_or_insert_with(HashMap::new).insert(key, b.clone());
            Some(b)
        }
        Some(None) => None,
        None => {
            if modo_foto() {
                // a foto espera a imagem (sem a thread)
                let r = load_pixels(path, max_px);
                BMP_PX.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, r);
                return bitmap_from_file(path, max_px);
            }
            if !BMP_PENDING.lock().unwrap().get_or_insert_with(HashSet::new).insert(key.clone()) {
                return None;
            }
            let (path, h) = (path.to_string(), HWND_ATOM.load(Ordering::Relaxed));
            std::thread::spawn(move || {
                // no máximo 3 de cada vez: os papéis de parede do Mac têm até 8K
                static SEM: Mutex<i32> = Mutex::new(0);
                loop {
                    let mut n = SEM.lock().unwrap();
                    if *n < 3 {
                        *n += 1;
                        break;
                    }
                    drop(n);
                    std::thread::sleep(std::time::Duration::from_millis(15));
                }
                unsafe {
                    let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
                }
                let res = Box::new(BmpResult { key, px: load_pixels(&path, max_px) });
                *SEM.lock().unwrap() -= 1;
                let raw = Box::into_raw(res);
                unsafe {
                    if PostMessageW(HWND(h as *mut c_void), WM_APP_BITMAP, WPARAM(0), LPARAM(raw as isize)).is_err() {
                        drop(Box::from_raw(raw));
                    }
                }
            });
            None
        }
    }
}
/// menu do Mac embaixo de anchor (DIP); índice ou -1
pub fn menu(anchor: RectF, opts: &[String], cur: i32) -> i32 {
    let items: Vec<Item> = opts.iter().enumerate().map(|(i, o)| Item::new(tr(o), i as i32 + 1).checked(i as i32 == cur)).collect();
    let p = app2d::to_screen(a().hwnd, (anchor.left * a().scale) as i32, (anchor.bottom * a().scale) as i32);
    let id = ctxmenu::show_items(a().hwnd, p, &items);
    invalidate();
    if id > 0 {
        id - 1
    } else {
        -1
    }
}
/// ⌃⌄ (no Tahoe, num círculo cinza), como nos menus das linhas
pub fn popup_badge(c: &Ctx, cx: f32, cy: f32) {
    unsafe {
        if a().tahoe {
            fill_ellipse(c, pt(cx, cy), 10.0, if a().dark { col(1.0, 1.0, 1.0, 0.1) } else { col(0.0, 0.0, 0.0, 0.06) });
        }
    }
    draw_up_down(c, cx, cy, if a().tahoe { c.text } else { c.text2 });
}
/// botão comum (no Tahoe, cápsula cinza)
pub fn button_face(c: &Ctx, b: RectF, label: &str) {
    draw_button(c, b, label, true, false);
}
/// a folha com campo de texto (pedido de senha do Wi-Fi e parecidos), por cima do conteúdo, como no Mac
pub fn ask_text(title: &str, message: &str, ok_label: &str, password: bool, ok: Rc<dyn Fn(String)>, prefill: &str) {
    let s = &mut a().sheet;
    s.open = true;
    s.title = title.into();
    s.message = message.into();
    s.ok_label = ok_label.into();
    s.password = password;
    s.field.set_text(prefill, false);
    if !prefill.is_empty() {
        let n = s.field.text.len() as i32;
        s.field.select(0, n);
    }
    s.ok = Some(ok);
    a().caret_at = unsafe { GetTickCount() };
    if !a().hwnd.0.is_null() {
        unsafe {
            SetTimer(a().hwnd, T_CARET, 530, None);
        }
    }
    invalidate();
}

// ================= Fontes
fn format(family: &str, size: f32, weight: DWRITE_FONT_WEIGHT, al: DWRITE_TEXT_ALIGNMENT, wrap: bool) -> IDWriteTextFormat {
    let f = cjk::format(dw(), family, weight, DWRITE_FONT_STYLE_NORMAL, size, "pt-br").expect("fonte");
    unsafe {
        let _ = f.SetTextAlignment(al);
        let _ = f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
        let _ = f.SetWordWrapping(if wrap { DWRITE_WORD_WRAPPING_WRAP } else { DWRITE_WORD_WRAPPING_NO_WRAP });
        if !wrap {
            if let Ok(e) = dw().CreateEllipsisTrimmingSign(&f) {
                let t = DWRITE_TRIMMING { granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER, delimiter: 0, delimiterCount: 0 };
                let _ = f.SetTrimming(&t, &e);
            }
        }
    }
    f
}
fn pick_family(names: &[&str]) -> String {
    names.iter().find(|n| app2d::has_font(n)).map(|n| n.to_string()).unwrap_or("Segoe UI".into())
}
fn create_formats() -> Fonts {
    // SF Pro só se estiver instalada neste PC (a licença não permite distribuir); senão a Inter
    let ui = pick_family(&["SF Pro Text", "Inter", "Segoe UI Variable Text", "Segoe UI"]);
    let disp = pick_family(&["SF Pro Display", "SF Pro Text", "Inter", "Segoe UI"]);
    let body = if ui == "SF Pro Text" { DWRITE_FONT_WEIGHT_NORMAL } else { DWRITE_FONT_WEIGHT_MEDIUM };
    let icons = pick_family(&["Segoe Fluent Icons", "Segoe MDL2 Assets"]);
    let (l, c) = (DWRITE_TEXT_ALIGNMENT_LEADING, DWRITE_TEXT_ALIGNMENT_CENTER);
    let leo = |size: f32, bold: bool, al: DWRITE_TEXT_ALIGNMENT, wrap: bool| {
        let f = format("Lucida Sans Unicode", size, if bold { DWRITE_FONT_WEIGHT_BOLD } else { DWRITE_FONT_WEIGHT_NORMAL }, al, false);
        if wrap {
            unsafe {
                let _ = f.SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
                let _ = f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
            }
        }
        f
    };
    Fonts {
        body: format(&ui, 13.0, body, l, false),
        side: format(&ui, 13.0, body, l, false),
        small: format(&ui, 11.0, body, l, true),
        bold: format(&ui, 13.0, DWRITE_FONT_WEIGHT_SEMI_BOLD, l, false),
        title: format(&disp, 15.0, DWRITE_FONT_WEIGHT_BOLD, l, false),
        glyph: format(&icons, 14.0, DWRITE_FONT_WEIGHT_NORMAL, c, false),
        glyph_small: format(&icons, 11.5, DWRITE_FONT_WEIGHT_NORMAL, c, false),
        center: format(&ui, 13.0, body, c, false),
        small_center: format(&ui, 11.0, body, c, false),
        small_bold_center: format(&ui, 11.0, DWRITE_FONT_WEIGHT_SEMI_BOLD, c, false),
        tile_text: format(&ui, 13.0, DWRITE_FONT_WEIGHT_BOLD, c, false),
        lf: leo(13.0, false, l, false),
        lf_r: leo(13.0, false, DWRITE_TEXT_ALIGNMENT_TRAILING, false),
        lf_b: leo(12.0, true, l, false),
        lf_s: leo(11.0, false, l, true),
        lf_sc: leo(11.0, false, c, true),
        lf_t: leo(13.0, false, c, false),
    }
}

// ================= Cores
fn colors_base() -> Pal {
    let dark = a().dark;
    let acc = accent();
    let mut sel = if dark { col(acc.r * 0.82, acc.g * 0.82, acc.b * 0.82, 1.0) } else { col(acc.r * 0.9, acc.g * 0.9, acc.b * 0.9, 1.0) };
    if !a().win_active {
        sel = if dark { col(1.0, 1.0, 1.0, 0.12) } else { col(0.0, 0.0, 0.0, 0.09) };
    }
    if dark {
        return Pal { side: col(0.0, 0.0, 0.0, 0.22), content: col(0.122, 0.125, 0.137, 1.0), text: col(1.0, 1.0, 1.0, 0.88), text2: col(1.0, 1.0, 1.0, 0.55), text3: col(1.0, 1.0, 1.0, 0.28), line: col(1.0, 1.0, 1.0, 0.08), group: col(1.0, 1.0, 1.0, 0.035), group_line: col(1.0, 1.0, 1.0, 0.07), control: col(1.0, 1.0, 1.0, 0.16), side_sel: sel, side_sel_text: col(1.0, 1.0, 1.0, 1.0), divider: col(0.0, 0.0, 0.0, 0.55) };
    }
    let act = a().win_active;
    Pal { side: col(0.95, 0.95, 0.95, 0.25), content: col(0.925, 0.925, 0.925, 1.0), text: col(0.0, 0.0, 0.0, 0.85), text2: col(0.0, 0.0, 0.0, 0.5), text3: col(0.0, 0.0, 0.0, 0.25), line: col(0.0, 0.0, 0.0, 0.08), group: col(0.0, 0.0, 0.0, 0.028), group_line: col(0.0, 0.0, 0.0, 0.055), control: col(1.0, 1.0, 1.0, 1.0), side_sel: if act { sel } else { col(0.0, 0.0, 0.0, 0.09) }, side_sel_text: if act { col(1.0, 1.0, 1.0, 1.0) } else { col(0.0, 0.0, 0.0, 0.85) }, divider: col(0.0, 0.0, 0.0, 0.12) }
}
fn colors() -> Pal {
    let mut p = colors_base();
    let dark = a().dark;
    if golden() {
        // medido: claro = barra (236,235,236), conteúdo branco, caixas 247; escuro = conteúdo (29,28,29), caixas (49,48,48),
        // barra lateral (43,41,40); seleção na cor de destaque pura
        p.side = if dark { rgb(43, 41, 40, 1.0) } else { rgb(236, 235, 236, 1.0) };
        p.content = if dark { rgb(29, 28, 29, 1.0) } else { col(1.0, 1.0, 1.0, 1.0) };
        p.group = if dark { col(1.0, 1.0, 1.0, 0.088) } else { col(0.0, 0.0, 0.0, 0.031) };
        p.divider = if dark { col(0.0, 0.0, 0.0, 0.5) } else { col(0.0, 0.0, 0.0, 0.06) };
        if a().win_active {
            p.side_sel = accent();
        }
        return p;
    }
    if a().tahoe {
        p.content = app2d::tinted(p.content); // Tahoe: o fundo da janela leva um pouco da cor do papel de parede
    }
    if !a().tahoe && leo_theme() {
        p.side = leopard::sidebar(a().win_active, dark);
        p.content = rgb(232, 232, 232, 1.0);
        p.group = col(0.0, 0.0, 0.0, 0.04);
        p.group_line = col(0.0, 0.0, 0.0, 0.14);
        p.line = col(0.0, 0.0, 0.0, 0.1);
        p.side_sel_text = col(1.0, 1.0, 1.0, 1.0);
    }
    p
}
/// a cor do acrílico do DWM que o C++ deixa aparecer atrás da lateral (aqui chapada)
fn acrilico() -> Cor {
    if a().dark {
        col(0.17, 0.17, 0.18, 1.0)
    } else {
        col(0.9, 0.9, 0.91, 1.0)
    }
}
fn round_stroke() -> Option<ID2D1StrokeStyle> {
    static R: Global<Option<ID2D1StrokeStyle>> = Global::new(None);
    if R.get().is_none() {
        let sp = D2D1_STROKE_STYLE_PROPERTIES { startCap: D2D1_CAP_STYLE_ROUND, endCap: D2D1_CAP_STYLE_ROUND, dashCap: D2D1_CAP_STYLE_ROUND, lineJoin: D2D1_LINE_JOIN_ROUND, miterLimit: 10.0, ..Default::default() };
        *R.get() = unsafe { d2d().CreateStrokeStyle(&sp, None).ok() };
    }
    R.get().clone()
}
fn line(c: &Ctx, x1: f32, y1: f32, x2: f32, y2: f32, w_: f32) {
    unsafe { c.rt.DrawLine(pt(x1, y1), pt(x2, y2), &c.br, w_, round_stroke().as_ref()) }
}
/// degradê vertical com cantos (rad) — usado pelos controles Aqua
fn leo_fill(c: &Ctx, r: RectF, rad: f32, st: &[(f32, Cor)]) {
    unsafe {
        if let Some(lb) = gradient(c, st, pt(0.0, r.top), pt(0.0, r.bottom)) {
            c.rt.FillRoundedRectangle(&rr(r, rad, rad), &lb);
        }
    }
}
/// gel do Aqua: claro em cima, a quebra do brilho no meio e a luz de baixo (azul) ou o branco perolado (pílula comum)
fn leo_gel(c: &Ctx, r: RectF, rad: f32, blue: bool) {
    if blue {
        leo_fill(c, r, rad, &[(0.0, col(0.66, 0.8, 0.98, 1.0)), (0.5, col(0.38, 0.6, 0.93, 1.0)), (0.5, col(0.24, 0.47, 0.87, 1.0)), (1.0, col(0.58, 0.82, 1.0, 1.0))]);
    } else {
        leo_fill(c, r, rad, &[(0.0, col(1.0, 1.0, 1.0, 1.0)), (0.5, col(0.95, 0.95, 0.95, 1.0)), (0.5, col(0.88, 0.88, 0.88, 1.0)), (1.0, col(0.98, 0.98, 0.98, 1.0))]);
    }
}
fn group_r() -> f32 {
    if a().tahoe {
        11.0
    } else {
        GROUP_R
    }
}
fn panel_r() -> f32 {
    19.0
}
fn panel_rect(h: f32) -> RectF {
    rf(7.0, 7.0, a().m.side_w - 1.0, (h - 7.0).floor())
}
fn client_dip() -> (f32, f32) {
    if let Some(s) = a().foto {
        return s;
    }
    let mut r = RECT::default();
    unsafe {
        let _ = GetClientRect(a().hwnd, &mut r);
    }
    (r.right as f32 / a().scale, r.bottom as f32 / a().scale)
}
fn invalidate() {
    if A.get().is_some() && !a().hwnd.0.is_null() {
        unsafe {
            let _ = InvalidateRect(a().hwnd, None, FALSE);
        }
    }
}
fn inr(r: &RectF, p: Ponto) -> bool {
    p.x >= r.left && p.x < r.right && p.y >= r.top && p.y < r.bottom
}
/// a rolagem desenhada em pixel inteiro da tela (issue #8: o texto tremia em frações de pixel)
fn rolo_px() -> f32 {
    (a().scroll * a().scale).round() / a().scale
}

// ================= Navegação
fn show_page() {
    if a().hist_at < 0 {
        return;
    }
    let items = sidebar_items();
    let e = &mut a().hist[a().hist_at as usize];
    if e.side < 0 || e.side as usize >= items.len() {
        e.side = 0;
    }
    let e = e.clone();
    let (b, t) = match e.stack.last() {
        None => (items[e.side as usize].build.clone(), items[e.side as usize].name.clone()),
        Some((t, b)) => (b.clone(), t.clone()),
    };
    let mut p = b();
    p.title = t;
    a().page = p;
}
fn select_side(i: usize) {
    if i >= sidebar_items().len() {
        return;
    }
    if a().leo_all {
        // Leopard: abriu um painel
        a().leo_all = false;
        a().search.set_text("", false);
        a().search_focus = false;
        invalidate();
    }
    if a().hist_at >= 0 {
        let e = &a().hist[a().hist_at as usize];
        if e.side == i as i32 && e.stack.is_empty() {
            return;
        }
    }
    let at = a().hist_at;
    a().hist.truncate((at + 1) as usize);
    a().hist.push(Entry { side: i as i32, stack: Vec::new() });
    a().hist_at += 1;
    show_page();
    a().scroll = 0.0;
    a().scroll_target = 0.0;
    let id = sidebar_items()[i].id.clone();
    set_setting("ajustes_pagina", &id);
    invalidate();
}
fn go(delta: i32) {
    let to = a().hist_at + delta;
    if to < 0 || to as usize >= a().hist.len() {
        return;
    }
    a().hist_at = to;
    show_page();
    a().scroll = 0.0;
    a().scroll_target = 0.0;
    invalidate();
}
// Issue #292: a busca só olhava o nome do painel e umas palavras-chave; "gênio" não achava a opção do efeito. Agora
// cada painel é montado uma vez (na primeira busca) e entram no texto procurado os títulos dos grupos, os rótulos, as
// descrições e as opções de cada linha, no português do código e na língua do WacOS.
static SIDE_TEXTO: Global<Vec<Option<String>>> = Global::new(Vec::new());
fn texto_do_painel(i: usize) -> String {
    let items = sidebar_items();
    let cache = SIDE_TEXTO.get();
    if cache.len() != items.len() {
        *cache = vec![None; items.len()];
    }
    if let Some(t) = &cache[i] {
        return t.clone();
    }
    let mut t = String::new();
    let mut add = |s: &str| {
        if s.is_empty() {
            return;
        }
        t.push(' ');
        t.push_str(s);
        let tr_ = tr(s);
        if tr_ != s {
            t.push(' ');
            t.push_str(&tr_);
        }
    };
    let pg = (items[i].build)();
    for g in &pg.groups {
        add(&g.title);
        add(&g.subtitle);
        for r in &g.rows {
            add(&r.label);
            add(&r.detail);
            add(&r.button);
            for o in &r.options {
                add(o);
            }
        }
    }
    let t = t.to_lowercase();
    SIDE_TEXTO.get()[i] = Some(t.clone());
    t
}
fn update_side_visible() {
    let q = a().search.string().to_lowercase();
    let n = sidebar_items().len();
    a().side_visible = (0..n)
        .filter(|&i| sidebar_items()[i].id != "conta") // é o cabeçalho da conta, no topo
        .filter(|&i| {
            if q.is_empty() {
                return true;
            }
            let it = &sidebar_items()[i];
            let base = format!("{} {} {}", it.name, tr(&it.name), it.keywords).to_lowercase();
            base.contains(&q) || texto_do_painel(i).contains(&q)
        })
        .collect();
}

// ================= Layout do conteúdo
fn row_height(r: &Row, w_: f32) -> f32 {
    if r.kind == Kind::Custom || r.height > 0.0 {
        return r.height;
    }
    let mut h = if r.icon != 0 {
        if golden() {
            49.0
        } else {
            42.0
        }
    } else {
        a().m.row_h
    };
    if r.kind == Kind::Slider && r.has_def {
        h += 14.0; // espaço para a marca "Padrão" embaixo do trilho
    }
    if !r.detail.is_empty() {
        let tw = w_ - 20.0 - if r.icon != 0 { 34.0 } else { 0.0 } - match r.kind {
            Kind::Toggle => 50.0,
            Kind::Button => 120.0,
            _ => 0.0,
        };
        h = h.max(12.0 + 17.0 + text_height(&r.detail, &a().f.small, tw) + 9.0);
    }
    h
}
fn header_height(g: &Group, w_: f32) -> f32 {
    if g.title.is_empty() && g.subtitle.is_empty() {
        return 0.0;
    }
    let mut h = 0.0;
    if !g.title.is_empty() {
        h += 18.0;
    }
    if !g.subtitle.is_empty() {
        h += text_height(&g.subtitle, &a().f.small, w_ - 20.0) + 2.0;
    }
    h + 7.0
}

// ================= Desenho dos controles
fn draw_toggle(c: &Ctx, r: RectF, on: bool, t: f32, enabled: bool) {
    let dark = a().dark;
    unsafe {
        if leo() {
            // Leopard: caixa de seleção Aqua de 14 px (gel azul com o visto ligada; perolada desligada)
            let (x, y) = (r.right - 10.0 - 14.0, (r.top + r.bottom) / 2.0 - 7.0);
            let b = rf(x, y, x + 14.0, y + 14.0);
            fill_rr(c, rf(b.left, b.top + 1.0, b.right, b.bottom + 1.0), 3.0, col(1.0, 1.0, 1.0, 0.6));
            leo_gel(c, b, 3.0, on);
            stroke_rr(c, inflate(b, -0.5), 2.5, if on { col(0.12, 0.27, 0.58, if enabled { 0.9 } else { 0.4 }) } else { col(0.0, 0.0, 0.0, if enabled { 0.42 } else { 0.2 }) }, 1.0);
            if on {
                c.br.SetColor(&col(0.05, 0.08, 0.15, if enabled { 0.95 } else { 0.4 }));
                line(c, x + 3.2, y + 7.2, x + 6.0, y + 10.5, 2.0);
                line(c, x + 6.0, y + 10.5, x + 11.5, y + 2.8, 2.0);
            }
            return;
        }
        if a().tahoe {
            // Tahoe: switch pequeno de 36 × 16, o pino uma pílula branca
            let (tw, th) = (36.0, 16.0);
            let (x, y) = (r.right - 10.0 - tw, (r.top + r.bottom) / 2.0 - th / 2.0);
            let pos = if on { t } else { 1.0 - t };
            let pc_ = pos.clamp(0.0, 1.0);
            let off = if dark { col(1.0, 1.0, 1.0, 0.18) } else { col(0.0, 0.0, 0.0, 0.1) };
            let onc = c.accent;
            let mut cl = col(off.r + (onc.r - off.r) * pc_, off.g + (onc.g - off.g) * pc_, off.b + (onc.b - off.b) * pc_, off.a + (onc.a - off.a) * pc_);
            if !enabled {
                cl.a *= 0.5;
            }
            fill_rr(c, rf(x, y, x + tw, y + th), th / 2.0, cl);
            let kw = 20.0;
            let kx = x + 2.0 + pos * (tw - 4.0 - kw);
            let k = rf(kx, y + 2.0, kx + kw, y + th - 2.0);
            let kr = (th - 4.0) / 2.0;
            fill_rr(c, rf(k.left, k.top + 0.6, k.right, k.bottom + 0.6), kr, col(0.0, 0.0, 0.0, 0.16));
            fill_rr(c, k, kr, col(1.0, 1.0, 1.0, if enabled { 1.0 } else { 0.7 }));
            return;
        }
        // chave "mini" do Ajustes do Sequoia: 26 x 15
        let (x, y) = (r.right - 10.0 - 26.0, (r.top + r.bottom) / 2.0 - 7.5);
        let pos = if on { t } else { 1.0 - t };
        let off = if dark { col(1.0, 1.0, 1.0, 0.16) } else { col(0.0, 0.0, 0.0, 0.09) };
        let onc = c.accent;
        let mut cl = col(off.r + (onc.r - off.r) * pos, off.g + (onc.g - off.g) * pos, off.b + (onc.b - off.b) * pos, off.a + (onc.a - off.a) * pos);
        if !enabled {
            cl.a *= 0.5;
        }
        let track = rf(x, y, x + 26.0, y + 15.0);
        fill_rr(c, track, 7.5, cl);
        if !dark && pos < 0.5 {
            stroke_rr(c, track, 7.5, col(0.0, 0.0, 0.0, 0.06), 0.6);
        }
        let kx = x + 7.5 + pos * 11.0;
        fill_ellipse(c, pt(kx, y + 7.9), 6.8, col(0.0, 0.0, 0.0, 0.18));
        fill_ellipse(c, pt(kx, y + 7.5), 6.5, col(1.0, 1.0, 1.0, if enabled { 1.0 } else { 0.7 }));
    }
}
fn draw_up_down(c: &Ctx, cx: f32, cy: f32, cl: Cor) {
    unsafe { c.br.SetColor(&cl) };
    line(c, cx - 3.0, cy - 1.8, cx, cy - 4.6, 1.25);
    line(c, cx, cy - 4.6, cx + 3.0, cy - 1.8, 1.25);
    line(c, cx - 3.0, cy + 1.8, cx, cy + 4.6, 1.25);
    line(c, cx, cy + 4.6, cx + 3.0, cy + 1.8, 1.25);
}
fn draw_chevron_right(c: &Ctx, cx: f32, cy: f32, cl: Cor) {
    unsafe { c.br.SetColor(&cl) };
    line(c, cx - 2.0, cy - 4.5, cx + 2.5, cy, 1.5);
    line(c, cx + 2.5, cy, cx - 2.0, cy + 4.5, 1.5);
}
fn button_rect(label: &str, right: f32, cy: f32) -> RectF {
    // Tahoe: botão regular de 24 em cápsula (raio = altura / 2)
    let w_ = (text_width(label, &a().f.center) + if a().tahoe { 28.0 } else { 22.0 }).max(60.0);
    let h = if a().tahoe { 12.0 } else { 11.0 };
    rf(right - w_, cy - h, right, cy + h)
}
fn draw_button(c: &Ctx, b: RectF, label: &str, enabled: bool, primary: bool) {
    let dark = a().dark;
    let cf_ = a().f.center.clone();
    unsafe {
        if leo() {
            // Leopard: pílula Aqua perolada (o botão padrão em gel azul), contorno cinza e o relevo branco embaixo
            let rad = (b.bottom - b.top) / 2.0;
            fill_rr(c, rf(b.left, b.top + 1.0, b.right, b.bottom + 1.0), rad, col(1.0, 1.0, 1.0, 0.6));
            leo_gel(c, b, rad, primary);
            stroke_rr(c, inflate(b, -0.5), rad - 0.5, if primary { col(0.12, 0.27, 0.58, 0.9) } else { col(0.0, 0.0, 0.0, 0.4) }, 1.0);
            text(c, label, b, &cf_, col(0.0, 0.0, 0.0, if enabled { 0.9 } else { 0.35 }));
            return;
        }
        if a().tahoe {
            let rad = (b.bottom - b.top) / 2.0;
            if primary {
                // Tahoe: o botão padrão também é cápsula, na cor de destaque
                fill_rr(c, b, rad, c.accent);
                text(c, label, b, &cf_, col(1.0, 1.0, 1.0, if enabled { 1.0 } else { 0.5 }));
            } else {
                // cápsula cinza translúcida, sem sombra nem borda
                fill_rr(c, b, rad, if dark { col(1.0, 1.0, 1.0, 0.12) } else { col(0.0, 0.0, 0.0, 0.07) });
                let mut t = c.text;
                if !enabled {
                    t.a *= 0.45;
                }
                text(c, label, b, &cf_, t);
            }
            return;
        }
        if primary {
            fill_rr(c, b, 5.5, c.accent);
            text(c, label, b, &cf_, col(1.0, 1.0, 1.0, if enabled { 1.0 } else { 0.5 }));
            return;
        }
        if !dark {
            // botão branco com sombra fina embaixo
            fill_rr(c, rf(b.left, b.top + 0.5, b.right, b.bottom + 0.8), 5.5, col(0.0, 0.0, 0.0, 0.1));
            fill_rr(c, b, 5.5, col(1.0, 1.0, 1.0, 1.0));
            stroke_rr(c, b, 5.5, col(0.0, 0.0, 0.0, 0.08), 0.6);
        } else {
            fill_rr(c, b, 5.5, col(1.0, 1.0, 1.0, 0.17));
            c.br.SetColor(&col(1.0, 1.0, 1.0, 0.06));
            c.rt.DrawLine(pt(b.left + 4.0, b.top + 0.5), pt(b.right - 4.0, b.top + 0.5), &c.br, 0.8, None);
        }
        let mut t = c.text;
        if !enabled {
            t.a *= 0.45;
        }
        text(c, label, b, &cf_, t);
    }
}
fn slider_value(r: &Row) -> f32 {
    r.get_f.as_ref().map(|g| ((g() - r.min) / (r.max - r.min).max(0.0001)).clamp(0.0, 1.0)).unwrap_or(0.0)
}
/// trilho do slider (à direita da linha, com espaço para os ícones/rótulos das pontas)
fn slider_track(r: &Row, row: RectF) -> RectF {
    // macOS 27 (Ajustes > Aparência, 2x): trilho de 5,75 de 213 da borda da caixa até 33,5 da outra
    if r.gg {
        return rf(row.left + 213.0, row.top + 15.75 - 2.875, row.right - 33.5, row.top + 15.75 + 2.875);
    }
    let small = a().f.small.clone();
    let gw = |s: &str| if s.is_empty() { 0.0 } else if s.encode_utf16().next().unwrap_or(0) >= 0xE000 { 22.0 } else { text_width(s, &small) + 10.0 };
    let (max_w, min_w) = (gw(&r.max_glyph), gw(&r.min_glyph));
    let right = row.right - 12.0 - max_w;
    let w_ = 240f32.min((row.right - row.left) * 0.5);
    let mut left = right - w_;
    let label_end = row.left + 10.0 + text_width(&r.label, &a().f.body) + 16.0; // o rótulo nunca fica embaixo do slider
    if left - min_w < label_end {
        left = label_end + min_w;
    }
    let cy = if r.has_def { row.top + a().m.row_h / 2.0 } else { (row.top + row.bottom) / 2.0 };
    rf(left, cy - 2.0, right, cy + 2.0)
}
fn slider_default(r: &Row) -> f32 {
    ((r.def - r.min) / (r.max - r.min).max(0.0001)).clamp(0.0, 1.0)
}
fn draw_slider(c: &Ctx, r: &Row, row: RectF, arrastando: bool) {
    let t = slider_track(r, row);
    let v = slider_value(r);
    let dark = a().dark;
    unsafe {
        if leo() {
            // Leopard: trilho fino afundado e o botão redondo de gel perolado do Aqua
            let cy = (t.top + t.bottom) / 2.0;
            let tr_ = rf(t.left, cy - 2.5, t.right, cy + 2.5);
            leo_fill(c, tr_, 2.5, &[(0.0, col(0.55, 0.55, 0.55, 1.0)), (1.0, col(0.8, 0.8, 0.8, 1.0))]);
            stroke_rr(c, tr_, 2.5, col(0.0, 0.0, 0.0, 0.3), 0.8);
            let kx = t.left + v * (t.right - t.left);
            fill_ellipse(c, pt(kx, cy + 1.2), 8.2, col(0.0, 0.0, 0.0, 0.22));
            leo_gel(c, rf(kx - 8.0, cy - 8.0, kx + 8.0, cy + 8.0), 8.0, false);
            c.br.SetColor(&col(0.0, 0.0, 0.0, 0.42));
            c.rt.DrawEllipse(&ell(pt(kx, cy), 7.5, 7.5), &c.br, 1.0, None);
            return;
        }
        if r.gg {
            // macOS 27: trilho arredondado, botão em cápsula branca de 20 × 16 com sombra, os dois pontinhos embaixo das
            // pontas e, nas pontas, os ícones de "transparente" (contorno) e "opaco" (cheio)
            let (cy, rad) = ((t.top + t.bottom) / 2.0, (t.bottom - t.top) / 2.0);
            fill_rr(c, t, rad, if dark { col(1.0, 1.0, 1.0, 0.16) } else { col(0.0, 0.0, 0.0, 0.09) });
            let kx = t.left + 10.0 + v * (t.right - t.left - 20.0);
            fill_rr(c, rf(t.left, t.top, kx, t.bottom), rad, c.accent);
            let dot = if dark { col(1.0, 1.0, 1.0, 0.3) } else { col(0.0, 0.0, 0.0, 0.25) };
            fill_ellipse(c, pt(t.left + 9.5, cy + 8.0), 1.1, dot);
            fill_ellipse(c, pt(t.right - 9.5, cy + 8.0), 1.1, dot);
            // arrastando: o botão cresce (20 × 16 → 25 × 20) e vira uma lente de vidro com o trilho ampliado por dentro
            let kg = if arrastando { 1.25 } else { 1.0 };
            let (kw2, kh2) = (10.0 * kg, 8.0 * kg);
            let kb = rf(kx - kw2, cy - kh2, kx + kw2, cy + kh2);
            for s in (1..=3).rev() {
                let s = s as f32;
                fill_rr(c, rf(kb.left - s * 0.5, kb.top + s * 0.4, kb.right + s * 0.5, kb.bottom + s * 0.8), kh2 + s * 0.5, col(0.0, 0.0, 0.0, (if dark { 0.1 } else { 0.045 }) * if arrastando { 1.6 } else { 1.0 }));
            }
            if !arrastando {
                fill_rr(c, kb, kh2, col(1.0, 1.0, 1.0, 1.0));
            } else if push_round(c, kb, kh2) {
                fill_rr(c, kb, kh2, col(1.0, 1.0, 1.0, if dark { 0.1 } else { 0.28 })); // corpo do vidro, quase transparente
                let mut old = mat::ident();
                c.rt.GetTransform(&mut old);
                c.rt.SetTransform(&mat::mul(&mat::scale(1.18, 1.9, kx, cy), &old)); // refração: o trilho ampliado
                fill_rr(c, t, rad, if dark { col(1.0, 1.0, 1.0, 0.16) } else { col(0.0, 0.0, 0.0, 0.09) });
                fill_rr(c, rf(t.left, t.top, kx, t.bottom), rad, c.accent);
                c.rt.SetTransform(&old);
                glass_rim(c, kb, kh2, 1.2);
                c.rt.PopLayer();
            }
            let box_bg = if dark { col(0.19, 0.19, 0.19, 1.0) } else { col(0.97, 0.97, 0.97, 1.0) };
            let two_boxes = |cx: f32, filled: bool| {
                let back = rf(cx - 7.5, cy - 6.0, cx + 3.0, cy + 2.0);
                let front = rf(cx - 4.5, cy - 3.0, cx + 7.5, cy + 6.0);
                if filled {
                    fill_rr(c, back, 2.5, c.text2);
                    stroke_rr(c, front, 4.0, box_bg, 1.4);
                    fill_rr(c, front, 4.0, c.text2);
                } else {
                    stroke_rr(c, back, 2.5, c.text2, 1.1);
                    fill_rr(c, front, 4.0, box_bg);
                    stroke_rr(c, front, 4.0, c.text2, 1.1);
                }
            };
            two_boxes(row.left + 199.0, false);
            two_boxes(row.right - 20.0, true);
            return;
        }
        let cy = (t.top + t.bottom) / 2.0;
        fill_rr(c, t, 2.0, if dark { col(1.0, 1.0, 1.0, 0.14) } else { col(0.0, 0.0, 0.0, 0.1) });
        let kx = t.left + v * (t.right - t.left);
        fill_rr(c, rf(t.left, t.top, kx, t.bottom), 2.0, c.accent);
        let small = a().f.small.clone();
        if r.has_def {
            // marca do padrão: tracinho embaixo do trilho e "Padrão" centralizado nele, como no Mac
            let dx = (t.left + slider_default(r) * (t.right - t.left)).round() + 0.5;
            c.br.SetColor(&c.text3);
            c.rt.DrawLine(pt(dx, t.bottom + 5.0), pt(dx, t.bottom + 10.0), &c.br, 1.0, None);
            let _ = small.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
            text(c, "Padrão", rf(dx - 40.0, t.bottom + 10.0, dx + 40.0, t.bottom + 24.0), &small, c.text2);
            let _ = small.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
        }
        // botão: círculo branco com sombra, como no Mac
        fill_ellipse(c, pt(kx, cy + 0.6), 9.6, col(0.0, 0.0, 0.0, if dark { 0.45 } else { 0.18 }));
        fill_ellipse(c, pt(kx, cy), 9.0, if dark { col(0.85, 0.85, 0.86, 1.0) } else { col(1.0, 1.0, 1.0, 1.0) });
        let end = |s: &str, left: bool| {
            if s.is_empty() {
                return;
            }
            let glyph = s.encode_utf16().next().unwrap_or(0) >= 0xE000;
            let w_ = if glyph { 22.0 } else { text_width(s, &small) + 10.0 };
            let (top, bottom) = (cy - 19.0, cy + 19.0); // rótulos das pontas na altura do trilho
            let r_ = if left { rf(t.left - w_ - 2.0, top, t.left - 6.0, bottom) } else { rf(t.right + 8.0, top, t.right + w_ + 2.0, bottom) };
            if glyph {
                text(c, s, r_, &c.glyph_small, c.text2);
            } else {
                let _ = small.SetTextAlignment(if left { DWRITE_TEXT_ALIGNMENT_TRAILING } else { DWRITE_TEXT_ALIGNMENT_LEADING });
                text(c, s, r_, &small, c.text2);
                let _ = small.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
            }
        };
        end(&r.min_glyph, true);
        end(&r.max_glyph, false);
    }
}
fn row_key(g: usize, r: usize) -> String {
    format!("{}#{g}#{r}", a().page.title)
}
fn draw_row(c: &Ctx, r: &Row, rr_: RectF, gi: usize, ri: usize) {
    let mut x = rr_.left + 10.0;
    let (mut tx, mut tx2) = (c.text, c.text2);
    if !r.enabled {
        tx.a *= 0.45;
        tx2.a *= 0.45;
    }
    let (gi_, ri_) = (gi as i32, ri as i32);
    if r.kind == Kind::Custom {
        if let Some(d) = &r.draw {
            d(c, rr_);
        }
        a().hits.push(hit(H::Custom, rr_, gi_, ri_));
        return;
    }
    if r.icon != 0 {
        let cy = if r.detail.is_empty() { (rr_.top + rr_.bottom) / 2.0 } else { rr_.top + 21.0 };
        let sym = symbol_for(&r.label);
        if a().tahoe && setting("estilo_icones", "padrao") == "transparente" {
            tile_clear(c, rf(x, cy - 11.0, x + 22.0, cy + 11.0), r.icon, &sym);
        } else {
            tile_any(c, rf(x, cy - 11.0, x + 22.0, cy + 11.0), r.icon, r.icon_color, &sym);
        }
        x += 32.0;
    }
    // área à direita (controle), para o rótulo não passar por cima
    let mut right = rr_.right - 10.0;
    let cy = (rr_.top + rr_.bottom) / 2.0;
    let body = a().f.body.clone();
    let dark = a().dark;
    unsafe {
        match r.kind {
            Kind::Toggle => {
                let on = r.get.as_ref().map(|g| g()).unwrap_or(false);
                let mut t = 1.0;
                let key = row_key(gi, ri);
                if let Some(&(t0, _)) = a().toggle_anim.get(&key) {
                    let ms = GetTickCount().wrapping_sub(t0) as f32;
                    if a().tahoe {
                        // mola medida no switch do macOS 26: resposta 0,44 s, amortecimento 0,74
                        let s = ms / 1000.0;
                        let w0 = 2.0 * std::f32::consts::PI / 0.44;
                        let z: f32 = 0.74;
                        let wd = w0 * (1.0 - z * z).sqrt();
                        t = 1.0 - (-z * w0 * s).exp() * ((wd * s).cos() + z * w0 / wd * (wd * s).sin());
                        if ms >= 450.0 {
                            t = 1.0;
                            a().toggle_anim.remove(&key);
                        }
                    } else {
                        t = (ms / 150.0).min(1.0);
                        t = 1.0 - (1.0 - t) * (1.0 - t);
                        if t >= 1.0 {
                            a().toggle_anim.remove(&key);
                        }
                    }
                }
                draw_toggle(c, rr_, on, t, r.enabled);
                a().hits.push(hit(H::Toggle, rr_, gi_, ri_));
                right -= if a().tahoe { 50.0 } else { 40.0 };
            }
            Kind::Popup => {
                let v = r.value.as_ref().map(|f| f()).unwrap_or_else(|| {
                    let i = r.get_idx.as_ref().map(|g| g()).unwrap_or(-1);
                    if i >= 0 && (i as usize) < r.options.len() {
                        r.options[i as usize].clone()
                    } else {
                        String::new()
                    }
                });
                let v = v.strip_prefix('!').unwrap_or(&v).to_string();
                if r.gg && !leo() {
                    // macOS 27 (Ajustes > Aparência, 2x): botão redondo de 19,5 a 13,5 da borda da caixa, o valor a 13
                    // dele e a bolinha de 16 a 8,5 do texto
                    let sx = rr_.right - 13.5 - 9.75;
                    fill_ellipse(c, pt(sx, cy), 9.75, if dark { col(1.0, 1.0, 1.0, 0.1) } else { col(0.0, 0.0, 0.0, 0.075) });
                    draw_up_down(c, sx, cy, tx);
                    let w_ = text_width(&v, &body);
                    let tx0 = sx - 9.75 - 13.0 - w_;
                    text(c, &v, rf(tx0, rr_.top, sx - 9.75 - 13.0 + 2.0, rr_.bottom), &body, tx);
                    let dx = tx0 - 8.5 - 8.0;
                    if let Some(d) = &r.dot {
                        let cl = d(r.get_idx.as_ref().map(|g| g()).unwrap_or(0));
                        if cl.a < 0.0 {
                            if let Some(lb) = gradient(c, &[(0.0, col(0.62, 0.55, 0.85, 1.0)), (1.0, col(1.0, 0.6, 0.6, 1.0))], pt(dx - 8.0, cy), pt(dx + 8.0, cy)) {
                                c.rt.FillEllipse(&ell(pt(dx, cy), 8.0, 8.0), &lb);
                            }
                        } else {
                            fill_ellipse(c, pt(dx, cy), 8.0, cl);
                        }
                    }
                    a().hits.push(hit(H::Popup, rf(dx - 10.0, rr_.top, rr_.right - 8.0, rr_.bottom), gi_, ri_));
                    right = dx - 16.0;
                } else if leo() {
                    let w_ = text_width(&v, &body).min(260.0);
                    let b = rf(right - w_ - 40.0, cy - 10.0, right + 6.0, cy + 10.0);
                    leo_popup_box(c, b, cy);
                    text(c, &v, rf(b.left + 9.0, b.top, b.right - 23.0, b.bottom), &body, col(0.0, 0.0, 0.0, 0.9));
                    a().hits.push(hit(H::Popup, b, gi_, ri_));
                    right = b.left - 4.0;
                } else {
                    if a().tahoe {
                        // Tahoe: ⌃⌄ num círculo cinza
                        fill_ellipse(c, pt(right - 4.0, cy), 10.0, if dark { col(1.0, 1.0, 1.0, 0.1) } else { col(0.0, 0.0, 0.0, 0.06) });
                        draw_up_down(c, right - 4.0, cy, tx);
                    } else {
                        draw_up_down(c, right - 4.0, cy, tx2);
                    }
                    let w_ = text_width(&v, &body);
                    let _ = body.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_TRAILING);
                    let gap = if a().tahoe { 6.0 } else { 0.0 }; // o círculo é mais largo que as setinhas
                    text(c, &v, rf(right - 16.0 - gap - w_.min(260.0) - 2.0, rr_.top, right - 14.0 - gap, rr_.bottom), &body, tx);
                    let _ = body.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
                    a().hits.push(hit(H::Popup, rf(right - 30.0 - w_, rr_.top, right + 6.0, rr_.bottom), gi_, ri_));
                    right -= 30.0 + w_;
                }
            }
            Kind::Slider => {
                let arr = a().drag.0 == gi_ && a().drag.1 == ri_;
                draw_slider(c, r, rr_, arr);
                let t = slider_track(r, rr_);
                a().hits.push(hit(H::Slider, rf(t.left - 10.0, rr_.top, t.right + 10.0, rr_.bottom), gi_, ri_));
                right = t.left - 30.0;
            }
            Kind::Link => {
                draw_chevron_right(c, right - 3.0, cy, c.text3);
                let v = r.value.as_ref().map(|f| f()).unwrap_or_default();
                if !v.is_empty() {
                    let _ = body.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_TRAILING);
                    text(c, &v, rf(rr_.left + 160.0, rr_.top, right - 16.0, rr_.bottom), &body, tx2);
                    let _ = body.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
                    right -= text_width(&v, &body) + 10.0;
                }
                a().hits.push(hit(H::Link, rr_, gi_, ri_));
                right -= 20.0;
            }
            Kind::Button => {
                let b = button_rect(&r.button, right, cy);
                draw_button(c, b, &r.button, r.enabled, false);
                a().hits.push(hit(H::Button, b, gi_, ri_));
                right = b.left - 10.0;
            }
            Kind::Value => {
                let v = r.value.as_ref().map(|f| f()).unwrap_or_default();
                if !v.is_empty() {
                    let _ = body.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_TRAILING);
                    let w_ = text_width(&v, &body).min((rr_.right - rr_.left) * 0.62);
                    text(c, &v, rf(right - w_ - 1.0, rr_.top, right, rr_.bottom), &body, tx2);
                    let _ = body.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
                    right -= w_ + 12.0;
                }
                if r.click.is_some() {
                    a().hits.push(hit(H::Row, rr_, gi_, ri_));
                }
            }
            Kind::Custom => {}
        }
        if r.detail.is_empty() {
            let bottom = if r.kind == Kind::Slider && r.has_def { rr_.top + a().m.row_h } else { rr_.bottom };
            text(c, &r.label, rf(x, rr_.top, right.max(x + 40.0), bottom), &body, tx);
        } else {
            text(c, &r.label, rf(x, rr_.top + 10.0, right.max(x + 40.0), rr_.top + 28.0), &body, tx);
            let small = a().f.small.clone();
            let h = text_height(&r.detail, &small, right - x);
            let _ = small.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
            text(c, &r.detail, rf(x, rr_.top + 29.0, right, rr_.top + 29.0 + h + 2.0), &small, tx2);
            let _ = small.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
        }
    }
}
/// o pop-up Aqua do Leopard: corpo perolado e a ponta azul com ⌃⌄
fn leo_popup_box(c: &Ctx, b: RectF, cy: f32) {
    unsafe {
        fill_rr(c, rf(b.left, b.top + 1.0, b.right, b.bottom + 1.0), 4.0, col(1.0, 1.0, 1.0, 0.6));
        leo_gel(c, b, 4.0, false);
        let cap = rf(b.right - 19.0, b.top, b.right, b.bottom);
        c.rt.PushAxisAlignedClip(&cap, D2D1_ANTIALIAS_MODE_ALIASED);
        leo_gel(c, b, 4.0, true);
        c.rt.PopAxisAlignedClip();
        stroke_rr(c, inflate(b, -0.5), 3.5, col(0.0, 0.0, 0.0, 0.4), 1.0);
        c.br.SetColor(&col(0.12, 0.27, 0.58, 0.7));
        c.rt.DrawLine(pt(cap.left + 0.5, b.top + 1.0), pt(cap.left + 0.5, b.bottom - 1.0), &c.br, 1.0, None);
        draw_up_down(c, (cap.left + cap.right) / 2.0, cy, col(1.0, 1.0, 1.0, 1.0));
    }
}

// ================= Barra lateral
fn draw_lights(c: &Ctx) {
    let on = semaforo::pick([col(1.0, 0.373, 0.341, 1.0), col(0.996, 0.737, 0.18, 1.0), col(0.157, 0.784, 0.251, 1.0)], semaforo::Kind::Fill);
    let lit = a().win_active || a().hover_lights;
    let dark = a().dark;
    for k in 0..3 {
        let p = pt(23.0 + k as f32 * 23.0, 25.0); // padrão do projeto: 14 pt, 23 entre centros
        unsafe {
            fill_ellipse(c, p, 7.0, if lit {
                on[k]
            } else if dark {
                col(1.0, 1.0, 1.0, 0.18)
            } else {
                col(0.0, 0.0, 0.0, 0.16)
            });
            semaforo::gloss(&c.rt, p, 7.0, &c.br);
            c.br.SetColor(&col(0.0, 0.0, 0.0, 0.14));
            c.rt.DrawEllipse(&ell(p, 6.75, 6.75), &c.br, 0.5, None);
        }
        a().hits.push(hit(H::Light, rf(p.x - 9.0, p.y - 9.0, p.x + 9.0, p.y + 9.0), k as i32, -1));
        if !a().hover_lights {
            continue;
        }
        unsafe { c.br.SetColor(&col(0.0, 0.0, 0.0, 0.55)) };
        let s = 2.6;
        match k {
            0 => {
                line(c, p.x - s, p.y - s, p.x + s, p.y + s, 1.2);
                line(c, p.x - s, p.y + s, p.x + s, p.y - s, 1.2);
            }
            1 => line(c, p.x - 3.2, p.y, p.x + 3.2, p.y, 1.3),
            _ => {
                line(c, p.x - 3.2, p.y, p.x + 3.2, p.y, 1.3);
                line(c, p.x, p.y - 3.2, p.x, p.y + 3.2, 1.3);
            }
        }
    }
}
fn caret_on() -> bool {
    (unsafe { GetTickCount() }.wrapping_sub(a().caret_at) / 530) % 2 == 0
}
fn draw_field(c: &Ctx, field: &mut TextField, tf: &IDWriteTextFormat, r: RectF, ink: Cor, sel: Cor, caret: bool) {
    unsafe {
        let (Ok(tb), Ok(sb)) = (c.rt.CreateSolidColorBrush(&ink, None), c.rt.CreateSolidColorBrush(&sel, None)) else { return };
        let (tb, sb): (ID2D1Brush, ID2D1Brush) = (tb.cast().unwrap(), sb.cast().unwrap());
        field.draw(&c.rt, dw(), tf, r, &tb, &sb, &tb, caret, false);
    }
}
fn draw_search(c: &Ctx, pal: &Pal) {
    let m = a().m;
    let sr = if golden() {
        rf(10.0, m.search_y - 1.0, m.side_w - 10.0, m.search_y + SEARCH_H)
    } else if a().tahoe {
        rf(15.0, m.search_y - 2.0, m.side_w - 9.0, m.search_y + SEARCH_H + 2.0)
    } else {
        rf(10.0, m.search_y, m.side_w - 10.0, m.search_y + SEARCH_H)
    };
    let sr_r = if a().tahoe { (sr.bottom - sr.top) / 2.0 } else { 6.0 }; // Tahoe: busca em cápsula
    let dark = a().dark;
    unsafe {
        if a().tahoe {
            // Tahoe: a busca flutua sobre a lista: cápsula translúcida com sombra fraca e contorno de luz
            for k in (1..=3).rev() {
                let k = k as f32;
                fill_rr(c, rf(sr.left - k * 0.5, sr.top + k * 0.5, sr.right + k * 0.5, sr.bottom + k), sr_r + k * 0.5, col(0.0, 0.0, 0.0, if dark { 0.05 } else { 0.025 }));
            }
            fill_rr(c, sr, sr_r, if dark { col(0.3, 0.3, 0.32, 0.55) } else { col(0.9, 0.9, 0.92, 0.62) });
            stroke_rr(c, inflate(sr, -0.5), sr_r - 0.5, if dark { col(1.0, 1.0, 1.0, 0.12) } else { col(1.0, 1.0, 1.0, 0.75) }, 1.0);
        } else {
            fill_rr(c, sr, sr_r, if dark { col(1.0, 1.0, 1.0, 0.07) } else { col(0.0, 0.0, 0.0, 0.055) });
        }
        if a().search_focus {
            stroke_rr(c, inflate(sr, 1.5), sr_r + 1.5, col(c.accent.r, c.accent.g, c.accent.b, 0.55), 3.0);
        }
        c.br.SetColor(&pal.text2);
        if !simbolo::draw(&c.rt, "magnifyingglass", rf(sr.left + 8.0, sr.top + 8.0, sr.left + 20.0, sr.bottom - 8.0), &brush(c)) {
            text(c, &g1(0xE721), rf(sr.left + 4.0, sr.top, sr.left + 24.0, sr.bottom), &c.glyph_small, pal.text2);
        }
    }
    let tr_ = rf(sr.left + 26.0, sr.top, sr.right - 8.0, sr.bottom);
    if a().search.is_empty() && !a().search_focus {
        text(c, "Buscar", tr_, &a().f.body.clone(), pal.text3);
    } else {
        let caret = a().search_focus && caret_on();
        let mut f = std::mem::take(&mut a().search);
        draw_field(c, &mut f, &a().f.body.clone(), tr_, pal.text, col(c.accent.r, c.accent.g, c.accent.b, 0.35), caret);
        a().search = f;
    }
    a().hits.push(hit(H::Search, sr, -1, -1));
}
fn draw_sidebar(c0: &Ctx, pal: &Pal, hh: f32) {
    let m = a().m;
    let panel = if golden() { rf(0.0, 0.0, m.side_w - 0.5, hh) } else { panel_rect(hh) };
    let tahoe = a().tahoe;
    let dark = a().dark;
    // Tahoe (com a Composição): a lista rola por baixo dos botões da janela e da busca (borda de rolagem desfocada)
    let main_dc = CUR_DC.get().clone();
    let (cw_, _) = client_dip();
    let sdc = match (&main_dc, tahoe) {
        (Some(d), true) => unsafe { comum::tahoe::scene_begin(d, 1, cw_, hh, a().scale * 96.0) },
        _ => None,
    };
    let cs = sdc.as_ref().map(|d| make_ctx(&d.cast().unwrap(), &c0.br, pal));
    let c = cs.as_ref().unwrap_or(c0);
    unsafe {
        c.rt.PushAxisAlignedClip(&rf(0.0, if sdc.is_some() { panel.top } else { m.search_y + SEARCH_H + 6.0 }, m.side_w, hh - if tahoe && !golden() { 9.0 } else { 0.0 }), D2D1_ANTIALIAS_MODE_ALIASED);
    }
    let mut y = m.account_y - a().side_scroll;
    let items = sidebar_items();
    // conta (no topo, como "Iniciar sessão com sua Conta Apple")
    if a().search.is_empty() {
        let inf = sistema::about();
        let ar = rf(10.0, y, m.side_w - 10.0, y + ACCOUNT_H);
        let mc = pt(30.0, y + ACCOUNT_H / 2.0);
        unsafe {
            match account_picture() {
                Some(pic) if push_ellipse(c, mc, 17.0) => {
                    c.rt.DrawBitmap(&pic, Some(&rf(mc.x - 17.0, mc.y - 17.0, mc.x + 17.0, mc.y + 17.0)), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
                    c.rt.PopLayer();
                }
                _ => {
                    fill_ellipse(c, mc, 17.0, if dark { col(0.55, 0.55, 0.58, 1.0) } else { col(0.62, 0.62, 0.65, 1.0) });
                    text(c, &g1(0xE77B), rf(mc.x - 17.0, mc.y - 17.0, mc.x + 17.0, mc.y + 17.0), &c.glyph, col(1.0, 1.0, 1.0, 1.0));
                }
            }
        }
        text(c, &inf.full_name, rf(54.0, y + 8.0, m.side_w - 12.0, y + 26.0), &a().f.bold.clone(), pal.text);
        // issue #193: com "Ocultar menções ao Windows" (ocultar_windows=1), só "Conta"
        text(c, if setting("ocultar_windows", "0") == "1" { "Conta" } else { "Conta do Windows" }, rf(54.0, y + 25.0, m.side_w - 12.0, y + 41.0), &a().f.body.clone(), pal.text2);
        a().hits.push(hit(H::Account, ar, -1, -1));
        y += ACCOUNT_H + 10.0;
    } else {
        y = m.search_y + SEARCH_H + 14.0 - a().side_scroll;
    }
    let cur = if a().hist_at >= 0 { a().hist[a().hist_at as usize].side } else { -1 };
    let mut last_group = -100;
    let side_f = a().f.side.clone();
    let searching = !a().search.is_empty();
    for &i in &a().side_visible.clone() {
        let it = &items[i];
        if !searching && last_group != -100 && it.group != last_group {
            y += SIDE_GAP;
        }
        last_group = it.group;
        let r = if tahoe && !golden() { rf(13.0, y, m.side_w - 8.0, y + m.side_row) } else { rf(10.0, y, m.side_w - 10.0, y + m.side_row) };
        let sel = i as i32 == cur;
        let sel_r = if golden() {
            8.0
        } else if tahoe {
            9.0
        } else {
            6.0
        };
        unsafe {
            if sel && leo() {
                let full = rf(0.0, r.top, m.side_w, r.bottom);
                let act = a().win_active;
                leo_fill(c, full, 0.0, &[(0.0, if act { col(0.43, 0.6, 0.85, 1.0) } else { col(0.68, 0.68, 0.7, 1.0) }), (1.0, if act { col(0.24, 0.44, 0.76, 1.0) } else { col(0.53, 0.53, 0.55, 1.0) })]);
                c.br.SetColor(&if act { col(0.33, 0.52, 0.8, 1.0) } else { col(0.6, 0.6, 0.62, 1.0) });
                c.rt.FillRectangle(&rf(0.0, full.top, m.side_w, full.top + 1.0), &c.br);
            } else if sel {
                fill_rr(c, r, sel_r, pal.side_sel);
            }
        }
        let sym = symbol_for(&it.name);
        a().tile_bare = true;
        // centrado na linha (28 no Sequoia, 32 no Tahoe: o ícone ficava 2 px acima do nome, issue #259)
        let ty = y + (m.side_row - 20.0) / 2.0;
        if tahoe && setting("estilo_icones", "padrao") == "transparente" {
            tile_clear(c, rf(14.0, ty, 34.0, ty + 20.0), it.glyph, &sym);
        } else {
            tile(c, rf(14.0, ty, 34.0, ty + 20.0), it.glyph, it.color, &sym);
        }
        a().tile_bare = false;
        text(c, &it.name, rf(42.0, y, m.side_w - 14.0, y + m.side_row), &side_f, if sel { pal.side_sel_text } else { pal.text });
        a().hits.push(hit(H::Side, r, i as i32, -1));
        y += m.side_row;
    }
    a().side_h = y + a().side_scroll + 12.0 - m.account_y;
    unsafe {
        c.rt.PopAxisAlignedClip();
        if let (Some(_), Some(d)) = (&sdc, &main_dc) {
            comum::tahoe::scene_end(1);
            comum::tahoe::scene_draw(d, 1, panel, m.search_y + SEARCH_H + 12.0 - panel.top, col(0.0, 0.0, 0.0, 0.0));
        }
    }
    draw_lights(c0);
    draw_search(c0, pal);
}

// ================= Folha (sheet)
fn sheet_rect() -> RectF {
    let (sw, _) = client_dip();
    let (w_, h) = (300.0, if a().sheet.message.is_empty() { 150.0 } else { 180.0 });
    let side = a().m.side_w;
    let cx = side + (sw - side) / 2.0;
    rf(cx - w_ / 2.0, a().m.tool_h, cx + w_ / 2.0, a().m.tool_h + h)
}
fn draw_sheet(c: &Ctx, pal: &Pal) {
    let (sw, sh) = client_dip();
    let dark = a().dark;
    unsafe {
        c.br.SetColor(&col(0.0, 0.0, 0.0, 0.18));
        c.rt.FillRectangle(&rf(0.0, 0.0, sw, sh), &c.br);
        let r = sheet_rect();
        for k in (1..=6).rev() {
            let k = k as f32;
            fill_rr(c, rf(r.left - k, r.top - k + 4.0, r.right + k, r.bottom + k + 4.0), 12.0 + k, col(0.0, 0.0, 0.0, 0.035));
        }
        fill_rr(c, r, 12.0, if dark { col(0.17, 0.17, 0.18, 1.0) } else { col(0.96, 0.96, 0.96, 1.0) });
        stroke_rr(c, r, 12.0, pal.group_line, 1.0);
        let mut y = r.top + 18.0;
        text(c, &a().sheet.title.clone(), rf(r.left + 20.0, y, r.right - 20.0, y + 18.0), &a().f.bold.clone(), pal.text);
        y += 22.0;
        if !a().sheet.message.is_empty() {
            let small = a().f.small.clone();
            let _ = small.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
            text(c, &a().sheet.message.clone(), rf(r.left + 20.0, y, r.right - 20.0, y + 30.0), &small, pal.text2);
            let _ = small.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
            y += 30.0;
        }
        let fr = rf(r.left + 20.0, y + 4.0, r.right - 20.0, y + 28.0);
        fill_rr(c, fr, 5.0, if dark { col(1.0, 1.0, 1.0, 0.08) } else { col(1.0, 1.0, 1.0, 1.0) });
        stroke_rr(c, inflate(fr, 1.0), 6.0, col(c.accent.r, c.accent.g, c.accent.b, 0.6), 2.5);
        let mut shown = a().sheet.field.clone();
        if a().sheet.password {
            shown.text = vec!['•' as u16; a().sheet.field.text.len()];
        }
        draw_field(c, &mut shown, &a().f.body.clone(), rf(fr.left + 6.0, fr.top, fr.right - 6.0, fr.bottom), pal.text, col(c.accent.r, c.accent.g, c.accent.b, 0.35), caret_on());
        a().sheet.field.last_rect = shown.last_rect;
        a().sheet.field.last_offset = shown.last_offset;
        a().hits.push(hit(H::SheetField, fr, -1, -1));
        let by = r.bottom - 20.0;
        let ok_l = a().sheet.ok_label.clone();
        let ok = button_rect(&ok_l, r.right - 20.0, by - 11.0);
        let cancel = button_rect("Cancelar", ok.left - 10.0, by - 11.0);
        draw_button(c, cancel, "Cancelar", true, false);
        draw_button(c, ok, &ok_l, true, true);
        a().hits.push(hit(H::SheetCancel, cancel, -1, -1));
        a().hits.push(hit(H::SheetOk, ok, -1, -1));
    }
}

// ================= Mac OS X Leopard: as Preferências do Sistema do 10.5
// Desenho próprio do tema: janela cinza 232 sem barra lateral; barra "unified" de metal com o título em cima e, embaixo,
// ◀ ▶ segmentados, "Mostrar Todos" e a busca em pílula. "Mostrar Todos" é a grade de painéis em faixas por categoria com
// os ícones do 10.5 (icones\leopard\pref <id>.png); cada painel é um formulário com rótulos alinhados à direita.
const LEO_CATS: [(&str, &[&str]); 4] = [
    ("Pessoal", &["aparencia", "fundo", "protetor", "dock", "central", "ilha", "geral", "spotlight"]),
    ("Hardware", &["telas", "som", "energia", "teclado", "mouse", "trackpad", "impressoras", "bluetooth"]),
    ("Internet e Rede", &["rede", "wifi", "contas", "nuvem", "jogos"]),
    ("Sistema", &["usuarios", "privacidade", "senha", "bloqueio", "acessibilidade", "inteligencia", "notificacoes", "foco", "tempo", "experimental"]),
];
fn leo_icon_path(id: &str) -> String {
    let dir = install_dir().join("icones\\leopard");
    let f = dir.join(format!("pref {id}.png"));
    if f.exists() {
        f.to_string_lossy().to_string()
    } else {
        dir.join("pref geral.png").to_string_lossy().to_string()
    }
}
/// texto com relevo branco 1 px abaixo (os textos sobre o metal e o cinza do 10.5)
fn leo_text(c: &Ctx, s: &str, r: RectF, f: &IDWriteTextFormat, cl: Cor, emboss: bool) {
    if emboss {
        text(c, s, rf(r.left, r.top + 1.0, r.right, r.bottom + 1.0), f, col(1.0, 1.0, 1.0, 0.55));
    }
    text(c, s, r, f, cl);
}
/// pílula Aqua (botão comum perolado; padrão/apertado em gel azul)
fn leo_pill(c: &Ctx, b: RectF, label: &str, enabled: bool, blue: bool) {
    let rad = (b.bottom - b.top) / 2.0;
    unsafe {
        fill_rr(c, rf(b.left, b.top + 1.0, b.right, b.bottom + 1.0), rad, col(1.0, 1.0, 1.0, 0.6));
        leo_gel(c, b, rad, blue);
        stroke_rr(c, inflate(b, -0.5), rad - 0.5, if blue { col(0.12, 0.27, 0.58, 0.9) } else { col(0.0, 0.0, 0.0, 0.42) }, 1.0);
        let t = a().f.lf_t.clone();
        let _ = t.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
        text(c, label, b, &t, col(0.0, 0.0, 0.0, if enabled { 0.9 } else { 0.35 }));
    }
}
fn leo_detail_h(r: &Row, w_: f32) -> f32 {
    if r.detail.is_empty() {
        0.0
    } else {
        text_height(&r.detail, &a().f.lf_s, w_) + 6.0
    }
}
fn leo_row_h(r: &Row, col_w: f32) -> f32 {
    if r.kind == Kind::Custom {
        return if r.height > 0.0 { r.height } else { 40.0 };
    }
    let base = if r.kind == Kind::Toggle { 24.0 } else { 30.0 };
    base + leo_detail_h(r, col_w - if r.kind == Kind::Toggle { 20.0 } else { 0.0 })
}
fn leo_row(c: &Ctx, r: &Row, rr_: RectF, x0: f32, col_x: f32, gi: usize, ri: usize) {
    let ink = col(0.0, 0.0, 0.0, if r.enabled { 0.88 } else { 0.35 });
    let gray = col(0.0, 0.0, 0.0, if r.enabled { 0.55 } else { 0.3 });
    let (gi_, ri_) = (gi as i32, ri as i32);
    if r.kind == Kind::Custom {
        if let Some(d) = &r.draw {
            d(c, rr_);
        }
        a().hits.push(hit(H::Custom, rr_, gi_, ri_));
        return;
    }
    let f = &a().f;
    let (lf, lf_r, lf_s, lf_sc, lf_t) = (f.lf.clone(), f.lf_r.clone(), f.lf_s.clone(), f.lf_sc.clone(), f.lf_t.clone());
    let cy = rr_.top + 13.0;
    let right_label = || {
        if !r.label.is_empty() {
            leo_text(c, &format!("{}:", tr(&r.label)), rf(x0, cy - 10.0, col_x - 6.0, cy + 10.0), &lf_r, ink, false);
        }
    };
    let detail = |dx: f32| {
        if !r.detail.is_empty() {
            let h = leo_detail_h(r, rr_.right - dx);
            text(c, &r.detail, rf(dx, rr_.top + 25.0, rr_.right, rr_.top + 25.0 + h), &lf_s, gray);
        }
    };
    unsafe {
        match r.kind {
            Kind::Toggle => {
                let on = r.get.as_ref().map(|g| g()).unwrap_or(false);
                let b = rf(col_x, cy - 7.0, col_x + 14.0, cy + 7.0);
                fill_rr(c, rf(b.left, b.top + 1.0, b.right, b.bottom + 1.0), 3.0, col(1.0, 1.0, 1.0, 0.6));
                leo_gel(c, b, 3.0, on);
                stroke_rr(c, inflate(b, -0.5), 2.5, if on { col(0.12, 0.27, 0.58, if r.enabled { 0.9 } else { 0.4 }) } else { col(0.0, 0.0, 0.0, if r.enabled { 0.45 } else { 0.2 }) }, 1.0);
                if on {
                    c.br.SetColor(&col(0.05, 0.08, 0.15, if r.enabled { 0.95 } else { 0.4 }));
                    line(c, col_x + 3.2, cy + 0.2, col_x + 6.0, cy + 3.5, 2.0);
                    line(c, col_x + 6.0, cy + 3.5, col_x + 11.5, cy - 4.2, 2.0);
                }
                leo_text(c, &tr(&r.label), rf(col_x + 20.0, cy - 10.0, rr_.right, cy + 10.0), &lf, ink, false);
                detail(col_x + 20.0);
                a().hits.push(hit(H::Toggle, rf(col_x - 4.0, rr_.top, rr_.right.min(col_x + 30.0 + text_width(&r.label, &lf)), rr_.top + 26.0), gi_, ri_));
            }
            Kind::Popup => {
                right_label();
                let v = r.value.as_ref().map(|f| f()).unwrap_or_else(|| {
                    let i = r.get_idx.as_ref().map(|g| g()).unwrap_or(-1);
                    if i >= 0 && (i as usize) < r.options.len() {
                        r.options[i as usize].clone()
                    } else {
                        String::new()
                    }
                });
                let v = tr(v.strip_prefix('!').unwrap_or(&v));
                let w_ = (text_width(&v, &lf).min(300.0) + 46.0).max(120.0);
                let b = rf(col_x, cy - 10.0, col_x + w_, cy + 10.0);
                leo_popup_box(c, b, cy);
                text(c, &v, rf(b.left + 9.0, b.top, b.right - 23.0, b.bottom), &lf, ink);
                detail(col_x);
                a().hits.push(hit(H::Popup, b, gi_, ri_));
            }
            Kind::Button => {
                right_label();
                let w_ = (text_width(&r.button, &lf_t) + 30.0).max(80.0);
                let b = rf(col_x, cy - 10.0, col_x + w_, cy + 10.0);
                leo_pill(c, b, &tr(&r.button), r.enabled, false);
                detail(col_x);
                a().hits.push(hit(H::Button, b, gi_, ri_));
            }
            Kind::Link => {
                // abre um painel/folha: botão "Nome…"
                let t = format!("{}…", tr(&r.label));
                let w_ = (text_width(&t, &lf_t) + 30.0).max(80.0);
                let b = rf(col_x, cy - 10.0, col_x + w_, cy + 10.0);
                leo_pill(c, b, &t, r.enabled, false);
                let v = r.value.as_ref().map(|f| f()).unwrap_or_default();
                if !v.is_empty() {
                    text(c, &v, rf(b.right + 10.0, cy - 10.0, rr_.right, cy + 10.0), &lf, gray);
                }
                a().hits.push(hit(H::Link, b, gi_, ri_));
            }
            Kind::Value => {
                right_label();
                let v = r.value.as_ref().map(|f| f()).unwrap_or_default();
                text(c, &v, rf(col_x, cy - 10.0, rr_.right, cy + 10.0), &lf, ink);
                detail(col_x);
                if r.click.is_some() {
                    a().hits.push(hit(H::Row, rr_, gi_, ri_));
                }
            }
            Kind::Slider => {
                right_label();
                let v = slider_value(r);
                let tr_ = rf(col_x + 8.0, cy - 2.5, (rr_.right - 20.0).min(col_x + 268.0), cy + 2.5);
                leo_fill(c, tr_, 2.5, &[(0.0, col(0.55, 0.55, 0.55, 1.0)), (1.0, col(0.82, 0.82, 0.82, 1.0))]);
                stroke_rr(c, tr_, 2.5, col(0.0, 0.0, 0.0, 0.3), 0.8);
                let kx = tr_.left + v * (tr_.right - tr_.left);
                fill_ellipse(c, pt(kx, cy + 1.2), 8.2, col(0.0, 0.0, 0.0, 0.22));
                leo_gel(c, rf(kx - 8.0, cy - 8.0, kx + 8.0, cy + 8.0), 8.0, false);
                c.br.SetColor(&col(0.0, 0.0, 0.0, 0.42));
                c.rt.DrawEllipse(&ell(pt(kx, cy), 7.5, 7.5), &c.br, 1.0, None);
                if r.min_glyph.encode_utf16().next().map(|x| x < 0xE000).unwrap_or(false) {
                    text(c, &r.min_glyph, rf(col_x - 60.0, cy + 6.0, col_x + 60.0, cy + 20.0), &lf_sc, gray);
                }
                detail(col_x);
                a().hits.push(hit(H::Slider, rf(tr_.left - 10.0, cy - 10.0, tr_.right + 10.0, cy + 10.0), gi_, ri_)); // slider_to tira 10 de cada lado
            }
            Kind::Custom => {}
        }
    }
}
fn leo_show_all(c: &Ctx, sw: f32, top: f32) {
    let items = sidebar_items();
    let q = !a().search.is_empty();
    let mut y = top - rolo_px();
    let lf_b = a().f.lf_b.clone();
    let lf_sc = a().f.lf_sc.clone();
    for (band, (name, ids)) in LEO_CATS.iter().filter_map(|(n, ids)| {
        let idx: Vec<usize> = ids.iter().filter_map(|id| {
            let i = sidebar_index_for(id);
            if i < 0 || (q && !a().side_visible.contains(&(i as usize))) {
                None
            } else {
                Some(i as usize)
            }
        }).collect();
        if idx.is_empty() {
            None
        } else {
            Some((*n, idx))
        }
    }).enumerate() {
        const PITCH: f32 = 84.0;
        const ROWH: f32 = 82.0;
        let per_row = (((sw - 24.0) / PITCH) as usize).max(1);
        let rows = ids.len().div_ceil(per_row);
        let h = 24.0 + rows as f32 * ROWH + 6.0;
        unsafe {
            // faixas alternadas (cinza claro / cinza do 10.5) com a linha fina entre elas
            c.br.SetColor(&if band % 2 == 0 { col(0.93, 0.93, 0.93, 1.0) } else { col(0.87, 0.87, 0.87, 1.0) });
            c.rt.FillRectangle(&rf(0.0, y, sw, y + h), &c.br);
            c.br.SetColor(&col(0.0, 0.0, 0.0, 0.12));
            c.rt.FillRectangle(&rf(0.0, y + h - 1.0, sw, y + h), &c.br);
        }
        leo_text(c, &tr(name), rf(12.0, y + 4.0, sw, y + 22.0), &lf_b, col(0.0, 0.0, 0.0, 0.75), true);
        for (k, &i) in ids.iter().enumerate() {
            let x = 14.0 + (k % per_row) as f32 * PITCH;
            let iy = y + 24.0 + (k / per_row) as f32 * ROWH;
            if let Some(b) = bitmap_from_file(&leo_icon_path(&items[i].id), 64) {
                unsafe {
                    c.rt.DrawBitmap(&b, Some(&rf(x + PITCH / 2.0 - 20.0, iy, x + PITCH / 2.0 + 20.0, iy + 40.0)), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
                }
            }
            text(c, &tr(&items[i].name), rf(x + 2.0, iy + 42.0, x + PITCH - 2.0, iy + ROWH), &lf_sc, col(0.0, 0.0, 0.0, 0.85));
            a().hits.push(hit(H::Side, rf(x, iy, x + PITCH, iy + ROWH), i as i32, -1));
        }
        y += h;
    }
    a().content_h = y + rolo_px() - top + 8.0;
}
fn leo_page(c: &Ctx, sw: f32, sh: f32, top: f32) {
    let (x0, x1) = (20.0, sw - 20.0);
    let wd = x1 - x0;
    let col_x = x0 + 170f32.max(wd * 0.38);
    let mut y = top + 18.0 - rolo_px();
    let page = a().page.clone();
    let (lf_b, lf_s) = (a().f.lf_b.clone(), a().f.lf_s.clone());
    for (gi, g) in page.groups.iter().enumerate() {
        if g.rows.is_empty() && g.title.is_empty() {
            continue;
        }
        if gi > 0 {
            // a linha gravada entre os grupos (escura e o fio branco embaixo)
            y += 8.0;
            unsafe {
                c.br.SetColor(&col(0.0, 0.0, 0.0, 0.14));
                c.rt.FillRectangle(&rf(x0, y, x1, y + 1.0), &c.br);
                c.br.SetColor(&col(1.0, 1.0, 1.0, 0.7));
                c.rt.FillRectangle(&rf(x0, y + 1.0, x1, y + 2.0), &c.br);
            }
            y += 12.0;
        }
        if !g.title.is_empty() {
            leo_text(c, &tr(&g.title), rf(x0, y, x1, y + 18.0), &lf_b, col(0.0, 0.0, 0.0, 0.8), true);
            y += 22.0;
        }
        if !g.subtitle.is_empty() {
            let th = text_height(&g.subtitle, &lf_s, wd);
            text(c, &g.subtitle, rf(x0, y, x1, y + th + 2.0), &lf_s, col(0.0, 0.0, 0.0, 0.55));
            y += th + 8.0;
        }
        for (ri, r) in g.rows.iter().enumerate() {
            let rh = leo_row_h(r, x1 - col_x);
            let rr_ = rf(x0, y, x1, y + rh);
            if rr_.bottom > top - 60.0 && rr_.top < sh + 60.0 {
                leo_row(c, r, rr_, x0, col_x, gi, ri);
            }
            y += rh;
        }
    }
    a().content_h = y + rolo_px() - top + 20.0;
}
fn make_ctx(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) -> Ctx {
    let f = &a().f;
    if leo() {
        return Ctx { rt: rt.clone(), br: br.clone(), dark: false, text: col(0.0, 0.0, 0.0, 0.88), text2: col(0.0, 0.0, 0.0, 0.55), text3: col(0.0, 0.0, 0.0, 0.3), accent: accent(), line: col(0.0, 0.0, 0.0, 0.12), group: col(0.0, 0.0, 0.0, 0.04), control: col(1.0, 1.0, 1.0, 1.0), body: f.lf.clone(), note: f.lf_s.clone(), bold: f.lf_b.clone(), title: f.lf_b.clone(), glyph: f.glyph.clone(), glyph_small: f.glyph_small.clone(), center: f.lf_t.clone(), note_center: f.lf_sc.clone(), note_bold_center: f.lf_sc.clone() };
    }
    Ctx { rt: rt.clone(), br: br.clone(), dark: a().dark, text: pal.text, text2: pal.text2, text3: pal.text3, accent: accent(), line: pal.line, group: pal.group, control: pal.control, body: f.body.clone(), note: f.small.clone(), bold: f.bold.clone(), title: f.title.clone(), glyph: f.glyph.clone(), glyph_small: f.glyph_small.clone(), center: f.center.clone(), note_center: f.small_center.clone(), note_bold_center: f.small_bold_center.clone() }
}
fn render_leopard(rt: &ID2D1RenderTarget) {
    let (sw, sh) = client_dip();
    let pal = colors();
    let Ok(br) = (unsafe { rt.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None) }) else { return };
    let c = make_ctx(rt, &br, &pal);
    let tool_h = a().m.tool_h;
    a().hits.clear();
    let all = a().leo_all || !a().search.is_empty();
    unsafe {
        rt.Clear(Some(&rgb(232, 232, 232, 1.0)));
        rt.PushAxisAlignedClip(&rf(0.0, tool_h, sw, sh), D2D1_ANTIALIAS_MODE_ALIASED);
        if all {
            leo_show_all(&c, sw, tool_h);
        } else {
            leo_page(&c, sw, sh, tool_h);
        }
        rt.PopAxisAlignedClip();
        // barra "unified": metal, título, botões da janela e a linha de ferramentas
        leopard::metal(rt, rf(0.0, 0.0, sw, tool_h), a().win_active, false, true, 0.0);
    }
    let lf_t = a().f.lf_t.clone();
    let title = if all { tr("Preferências do Sistema") } else { tr(&a().page.title) };
    leo_text(&c, &title, rf(80.0, 0.0, sw - 80.0, 22.0), &lf_t, col(0.0, 0.0, 0.0, if a().win_active { 0.85 } else { 0.45 }), true);
    let on = semaforo::pick([col(1.0, 0.373, 0.341, 1.0), col(0.996, 0.737, 0.18, 1.0), col(0.157, 0.784, 0.251, 1.0)], semaforo::Kind::Fill);
    for k in 0..3 {
        let p = pt(14.5 + k as f32 * 21.0, 11.0);
        unsafe {
            fill_ellipse(&c, p, 7.0, if a().win_active || a().hover_lights { on[k] } else { col(0.75, 0.75, 0.75, 1.0) });
            semaforo::gloss(rt, p, 7.0, &br);
        }
        a().hits.push(hit(H::Light, rf(p.x - 9.0, p.y - 9.0, p.x + 9.0, p.y + 9.0), k as i32, -1));
        if !a().hover_lights {
            continue;
        }
        unsafe { br.SetColor(&col(0.0, 0.0, 0.0, 0.6)) };
        let s = 2.6;
        match k {
            0 => {
                line(&c, p.x - s, p.y - s, p.x + s, p.y + s, 1.2);
                line(&c, p.x - s, p.y + s, p.x + s, p.y - s, 1.2);
            }
            1 => line(&c, p.x - 3.2, p.y, p.x + 3.2, p.y, 1.3),
            _ => {
                line(&c, p.x - 3.2, p.y, p.x + 3.2, p.y, 1.3);
                line(&c, p.x, p.y - 3.2, p.x, p.y + 3.2, 1.3);
            }
        }
    }
    // ◀ ▶ segmentados (moldura de metal claro)
    let can_back = !all || a().hist_at > 0;
    let can_fwd = a().hist_at + 1 < a().hist.len() as i32;
    let seg = rf(10.0, 30.0, 62.0, 52.0);
    unsafe {
        fill_rr(&c, rf(seg.left, seg.top + 1.0, seg.right, seg.bottom + 1.0), 4.0, col(1.0, 1.0, 1.0, 0.45));
        leo_fill(&c, seg, 4.0, &[(0.0, col(0.99, 0.99, 0.99, 1.0)), (1.0, col(0.84, 0.84, 0.84, 1.0))]);
        stroke_rr(&c, inflate(seg, -0.5), 3.5, col(0.0, 0.0, 0.0, 0.42), 1.0);
        br.SetColor(&col(0.0, 0.0, 0.0, 0.3));
        rt.DrawLine(pt(36.5, seg.top + 1.0), pt(36.5, seg.bottom - 1.0), &br, 1.0, None);
        let tri = |cx: f32, left: bool, on: bool| {
            let Ok(g) = d2d().CreatePathGeometry() else { return };
            if let Ok(sk) = g.Open() {
                let (d, cy) = (if left { -1.0 } else { 1.0 }, 41.0);
                sk.BeginFigure(pt(cx + d * 3.5, cy), D2D1_FIGURE_BEGIN_FILLED);
                sk.AddLine(pt(cx - d * 3.0, cy - 4.5));
                sk.AddLine(pt(cx - d * 3.0, cy + 4.5));
                sk.EndFigure(D2D1_FIGURE_END_CLOSED);
                let _ = sk.Close();
                br.SetColor(&col(0.18, 0.18, 0.19, if on { 0.9 } else { 0.3 }));
                rt.FillGeometry(&g, &br, None);
            }
        };
        tri(23.0, true, can_back);
        tri(49.0, false, can_fwd);
    }
    a().hits.push(hit(H::Back, rf(10.0, 30.0, 36.0, 52.0), -1, -1));
    a().hits.push(hit(H::Fwd, rf(36.0, 30.0, 62.0, 52.0), -1, -1));
    let sa = tr("Mostrar Todos");
    let sb = rf(70.0, 30.0, 70.0 + (text_width(&sa, &lf_t) + 26.0).max(84.0), 52.0);
    leo_pill(&c, sb, &sa, true, false);
    a().hits.push(hit(H::ShowAll, sb, -1, -1));
    // busca: pílula branca afundada com a lupa; com o foco, o anel azul
    let sr = rf(sw - 180.0, 31.0, sw - 12.0, 51.0);
    let sr_r = (sr.bottom - sr.top) / 2.0;
    unsafe {
        if a().search_focus {
            stroke_rr(&c, inflate(sr, 1.5), sr_r + 1.5, col(0.36, 0.6, 0.95, 0.75), 3.0);
        }
        fill_rr(&c, sr, sr_r, col(1.0, 1.0, 1.0, 1.0));
        leo_fill(&c, rf(sr.left + 1.0, sr.top + 1.0, sr.right - 1.0, sr.top + 5.0), 2.0, &[(0.0, col(0.0, 0.0, 0.0, 0.14)), (1.0, col(0.0, 0.0, 0.0, 0.0))]);
        stroke_rr(&c, inflate(sr, -0.5), sr_r - 0.5, col(0.0, 0.0, 0.0, 0.45), 1.0);
        br.SetColor(&col(0.25, 0.25, 0.27, 1.0));
        let my = (sr.top + sr.bottom) / 2.0;
        rt.DrawEllipse(&ell(pt(sr.left + 13.0, my - 1.0), 4.0, 4.0), &br, 1.5, None);
        line(&c, sr.left + 16.0, my + 2.0, sr.left + 19.0, my + 5.0, 1.8);
    }
    let tr_ = rf(sr.left + 24.0, sr.top, sr.right - 8.0, sr.bottom);
    if !a().search.is_empty() || a().search_focus {
        let caret = a().search_focus && caret_on();
        let mut f = std::mem::take(&mut a().search);
        draw_field(&c, &mut f, &a().f.lf.clone(), tr_, col(0.0, 0.0, 0.0, 0.9), col(0.36, 0.6, 0.95, 0.35), caret);
        a().search = f;
    }
    a().hits.push(hit(H::Search, sr, -1, -1));
    if a().sheet.open {
        a().hits.clear();
        draw_sheet(&c, &pal);
    }
}

// ================= Quadro
fn max_scroll() -> f32 {
    (a().content_h - (client_dip().1 - a().m.tool_h)).max(0.0)
}
/// o indicador de rolagem: trilho (top, h) e o pedaço (by, bh), em DIP
fn barra_geo(max_s: f32) -> (f32, f32, f32, f32) {
    let top = a().m.tool_h + 4.0;
    let h = client_dip().1 - 6.0 - top;
    let bh = (h * h / (h + max_s)).max(28.0);
    let by = top + (h - bh) * (a().scroll / max_s).clamp(0.0, 1.0);
    (top, h, by, bh)
}
/// PR #456 (Enesuygurs): a página encolheu (ex.: "Mostrar todas as resoluções" desligado em Telas). O content_h só é
/// medido ao desenhar, e a rolagem ficava além do fim, com o pé da janela vazio até rolar de novo: volta e redesenha
fn prende_rolo() {
    let m = max_scroll();
    if a().scroll <= m + 0.5 && a().scroll_target <= m + 0.5 {
        return;
    }
    a().scroll = a().scroll.min(m);
    a().scroll_target = a().scroll_target.min(m);
    // o content_h é medido no desenho: se ele oscilar entre dois valores, prender e redesenhar a cada quadro piscava a
    // janela (pedido de 02/12, "Ajustes piscando"). Um redesenho de correção a cada 250 ms no máximo
    static ULT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
    let agora = unsafe { GetTickCount() };
    if agora.wrapping_sub(ULT.load(Ordering::Relaxed)) >= 250 {
        ULT.store(agora, Ordering::Relaxed);
        invalidate();
    }
}
fn render(rt: &ID2D1RenderTarget) {
    render_pagina(rt);
    prende_rolo();
}
fn render_pagina(rt: &ID2D1RenderTarget) {
    if leo() {
        render_leopard(rt);
        return;
    }
    let pal = colors();
    let Ok(br) = (unsafe { rt.CreateSolidColorBrush(&pal.text, None) }) else { return };
    let c = make_ctx(rt, &br, &pal);
    a().hits.clear();
    let (sw, sh) = client_dip();
    let m = a().m;
    let (tahoe, dark) = (a().tahoe, a().dark);
    let main_dc = CUR_DC.get().clone();
    unsafe {
        // fundo: barra lateral translúcida (com a Composição, o acrílico do sistema; sem ela, chapado) e conteúdo opaco
        let hw = a().hwnd;
        let win_r = if tahoe && main_dc.is_some() { comum::tahoe::radius(hw, golden()) } else { 0.0 };
        let win_clip = match &main_dc {
            Some(d) => {
                rt.Clear(Some(&col(0.0, 0.0, 0.0, 0.0)));
                tahoe && comum::tahoe::push_window_clip(d, sw, sh, win_r)
            }
            None => false,
        };
        *WIN_CLIP.get() = (win_clip, win_r);
        if golden() {
            comum::tahoe::set_panel(hw, rf(0.0, 0.0, 0.0, 0.0), 0.0);
            // Golden Gate: a barra lateral é uma coluna de cor cheia até a borda (sem o vidro flutuante do Tahoe)
            br.SetColor(&pal.side);
            rt.FillRectangle(&rf(0.0, 0.0, m.side_w, sh), &br);
            br.SetColor(&pal.content);
            rt.FillRectangle(&rf(m.side_w, 0.0, sw, sh), &br);
            br.SetColor(&pal.divider);
            rt.FillRectangle(&rf(m.side_w - 0.5, 0.0, m.side_w, sh), &br);
        } else if tahoe {
            // Tahoe: janela inteira na cor do conteúdo; a barra lateral é um painel de vidro flutuante
            let panel = panel_rect(sh);
            if main_dc.is_some() {
                comum::tahoe::set_panel(hw, panel, panel_r());
                let f = rt.GetFactory().unwrap();
                let hole = comum::squircle::squircle(&f, panel, panel_r()); // canto contínuo
                if let (Ok(all), Some(hole), Ok(rest)) = (f.CreateRectangleGeometry(&rf(0.0, 0.0, sw, sh)), &hole, f.CreatePathGeometry()) {
                    if let Ok(sk) = rest.Open() {
                        if all.CombineWithGeometry(hole, D2D1_COMBINE_MODE_EXCLUDE, None, 0.25, &sk).is_ok() && sk.Close().is_ok() {
                            br.SetColor(&pal.content);
                            rt.FillGeometry(&rest, &br, None);
                        }
                    }
                }
                br.SetColor(&if dark { col(0.0, 0.0, 0.0, 0.1) } else { col(1.0, 1.0, 1.0, 0.18) });
                if let Some(hole) = &hole {
                    rt.FillGeometry(hole, &br, None);
                }
            } else {
                rt.Clear(Some(&pal.content));
                fill_rr(&c, panel, panel_r(), acrilico());
                fill_rr(&c, panel, panel_r(), if dark { col(0.0, 0.0, 0.0, 0.1) } else { col(1.0, 1.0, 1.0, 0.18) });
            }
        } else {
            if main_dc.is_none() {
                br.SetColor(&acrilico());
                rt.FillRectangle(&rf(0.0, 0.0, m.side_w, sh), &br);
            }
            br.SetColor(&pal.side);
            rt.FillRectangle(&rf(0.0, 0.0, m.side_w, sh), &br);
            br.SetColor(&pal.content);
            rt.FillRectangle(&rf(m.side_w, 0.0, sw, sh), &br);
            br.SetColor(&pal.divider);
            rt.FillRectangle(&rf(m.side_w - 0.5, 0.0, m.side_w + 0.5, sh), &br);
        }
        // Leopard (sem Tahoe e com a página moderna): a barra de cima é o metal "unified" do 10.5
        if !tahoe && leo_theme() {
            leopard::metal(rt, rf(0.0, 0.0, sw, m.tool_h), a().win_active, dark, true, 0.0);
        }
        // conteúdo — Golden Gate: caixas a 21 da barra lateral e 20,5 da direita, a primeira a 64,5 do alto
        let x0 = m.side_w + if golden() { 21.0 } else { PAD };
        let x1 = sw - if golden() { 20.5 } else { PAD };
        let wd = x1 - x0;
        // Tahoe (com a Composição): o conteúdo rola por baixo de Voltar/Avançar e do título (borda de rolagem desfocada)
        let cdc = match (&main_dc, tahoe) {
            (Some(d), true) => comum::tahoe::scene_begin(d, 0, sw, sh, a().scale * 96.0),
            _ => None,
        };
        let rt_c: ID2D1RenderTarget = cdc.as_ref().map(|d| d.cast().unwrap()).unwrap_or_else(|| rt.clone());
        let cc = make_ctx(&rt_c, &br, &pal);
        let clip_top = if cdc.is_some() { 0.0 } else { m.tool_h };
        rt_c.PushAxisAlignedClip(&rf(m.side_w + 0.5, clip_top, sw, sh), D2D1_ANTIALIAS_MODE_ALIASED);
        let mut y = (if golden() { 64.5 } else { m.tool_h + 6.0 }) - rolo_px();
        let page = a().page.clone();
        let (bold_f, small_f) = (a().f.bold.clone(), a().f.small.clone());
        for (gi, g) in page.groups.iter().enumerate() {
            if golden() && !g.title.is_empty() && g.subtitle.is_empty() {
                // macOS 27: 57,5 entre as caixas, com o título em negrito centrado a 39,5 da caixa de cima
                if gi > 0 {
                    text(&cc, &g.title, rf(x0 + 10.0, y + 30.5, x1 - 10.0, y + 48.5), &bold_f, pal.text);
                    y += 57.5;
                } else {
                    text(&cc, &g.title, rf(x0 + 10.0, y, x1 - 10.0, y + 18.0), &bold_f, pal.text);
                    y += 25.0;
                }
            } else {
                if gi > 0 {
                    y += if golden() { 10.5 } else { GROUP_GAP };
                }
                let hh = header_height(g, wd);
                if hh > 0.0 {
                    if gi > 0 {
                        y += 10.0;
                    }
                    let mut hy = y;
                    if !g.title.is_empty() {
                        text(&cc, &g.title, rf(x0 + 10.0, hy, x1 - 10.0, hy + 18.0), &bold_f, pal.text);
                        hy += 18.0;
                    }
                    if !g.subtitle.is_empty() {
                        let th = text_height(&g.subtitle, &small_f, wd - 20.0);
                        let _ = small_f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
                        text(&cc, &g.subtitle, rf(x0 + 10.0, hy, x1 - 10.0, hy + th + 2.0), &small_f, pal.text2);
                        let _ = small_f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
                    }
                    y += hh;
                }
            }
            let gh: f32 = g.rows.iter().map(|r| row_height(r, wd)).sum();
            if g.rows.is_empty() {
                continue;
            }
            let bx = rf(x0, y, x1, y + gh);
            if g.boxed && bx.bottom > clip_top - 10.0 && bx.top < sh + 10.0 {
                fill_rr(&cc, bx, group_r(), pal.group);
                if !tahoe {
                    // Tahoe: caixa só pelo tom, sem contorno
                    stroke_rr(&cc, inflate(bx, -0.5), group_r(), pal.group_line, 1.0);
                }
            }
            let mut ry = y;
            for (ri, r) in g.rows.iter().enumerate() {
                let rh = row_height(r, wd);
                let rr_ = rf(x0, ry, x1, ry + rh);
                if rr_.bottom > clip_top - 50.0 && rr_.top < sh + 50.0 {
                    if ri > 0 && g.boxed && !r.no_line {
                        cc.br.SetColor(&pal.line);
                        rt_c.FillRectangle(&rf(x0 + 10.0, ry - 0.5, x1 - 10.0, ry + 0.5), &cc.br);
                    }
                    draw_row(&cc, r, rr_, gi, ri);
                }
                ry += rh;
            }
            y += gh;
        }
        a().content_h = y + rolo_px() + 20.0 - m.tool_h;
        rt_c.PopAxisAlignedClip();
        if let (Some(_), Some(d)) = (&cdc, &main_dc) {
            comum::tahoe::scene_end(0);
            comum::tahoe::scene_draw(d, 0, rf(m.side_w + 0.5, 0.0, sw, sh), m.tool_h + 10.0, col(pal.content.r, pal.content.g, pal.content.b, 0.9));
        } else if !(!tahoe && leo_theme()) {
            // barra de ferramentas: setas e título; linha embaixo quando há rolagem
            br.SetColor(&pal.content);
            rt.FillRectangle(&rf(m.side_w + 0.5, 0.0, sw, m.tool_h), &br);
        }
        if cdc.is_none() && a().scroll > 1.0 {
            br.SetColor(&if dark { col(0.0, 0.0, 0.0, 0.5) } else { col(0.0, 0.0, 0.0, 0.1) });
            rt.FillRectangle(&rf(m.side_w, m.tool_h - 1.0, sw, m.tool_h), &br);
        }
        let can_back = a().hist_at > 0;
        let can_fwd = a().hist_at + 1 < a().hist.len() as i32;
        if tahoe && main_dc.is_some() {
            // Voltar/Avançar numa cápsula de vidro
            comum::tahoe::capsule(rt, &br, rf(m.side_w + 10.0, 8.0, m.side_w + 82.0, 42.0), -1.0, dark, 1.0);
            br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.16) } else { col(0.0, 0.0, 0.0, 0.12) });
            rt.FillRectangle(&rf(m.side_w + 46.0 - 0.5, 17.0, m.side_w + 46.0 + 0.5, 33.0), &br); // divisória entre as setas
        } else if tahoe {
            // Voltar/Avançar numa cápsula de vidro
            let q = rf(m.side_w + 10.0, 8.0, m.side_w + 82.0, 42.0);
            fill_rr(&c, rf(q.left, q.top + 1.0, q.right, q.bottom + 1.5), 17.0, col(0.0, 0.0, 0.0, if dark { 0.22 } else { 0.045 }));
            fill_rr(&c, q, 17.0, if dark { col(1.0, 1.0, 1.0, 0.16) } else { col(0.962, 0.965, 0.972, 0.94) });
            stroke_rr(&c, inflate(q, -0.5), 16.5, if dark { col(1.0, 1.0, 1.0, 0.1) } else { col(0.0, 0.0, 0.0, 0.06) }, 1.0);
            br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.16) } else { col(0.0, 0.0, 0.0, 0.12) });
            rt.FillRectangle(&rf(m.side_w + 46.0 - 0.5, 17.0, m.side_w + 46.0 + 0.5, 33.0), &br); // divisória entre as setas
        }
        let chev = |cx: f32, left: bool, on: bool| {
            br.SetColor(&if on { pal.text2 } else { pal.text3 });
            let d = if left { 1.0 } else { -1.0 };
            line(&c, cx + 2.5 * d, 25.0 - 6.0, cx - 2.5 * d, 25.0, 1.7);
            line(&c, cx - 2.5 * d, 25.0, cx + 2.5 * d, 25.0 + 6.0, 1.7);
        };
        chev(m.side_w + 28.0, true, can_back);
        chev(m.side_w + 64.0, false, can_fwd);
        a().hits.push(hit(H::Back, rf(m.side_w + 14.0, 10.0, m.side_w + 44.0, 40.0), -1, -1));
        a().hits.push(hit(H::Fwd, rf(m.side_w + 50.0, 10.0, m.side_w + 80.0, 40.0), -1, -1));
        if !(golden() && a().page.title == "Geral") {
            // macOS 27: a Geral não tem título na barra (tem o cartão grande)
            text(&c, &a().page.title.clone(), rf(m.side_w + if tahoe { 94.0 } else { 88.0 }, 0.0, sw - 20.0, 50.0), &a().f.title.clone(), pal.text);
        }
        if tahoe && !golden() && main_dc.is_some() {
            comum::tahoe::panel(rt, &br, panel_rect(sh), panel_r(), dark);
        } else if tahoe && !golden() {
            // a borda de luz do painel de vidro (tahoe::Panel)
            stroke_rr(&c, inflate(panel_rect(sh), -0.5), panel_r() - 0.5, if dark { col(1.0, 1.0, 1.0, 0.14) } else { col(1.0, 1.0, 1.0, 0.8) }, 1.0);
            stroke_rr(&c, inflate(panel_rect(sh), 0.5), panel_r() + 0.5, if dark { col(0.0, 0.0, 0.0, 0.35) } else { col(0.0, 0.0, 0.0, 0.08) }, 1.0);
        }
        let max_s = max_scroll();
        if max_s > 0.0 && (GetTickCount() < a().barra_ate || a().barra_hover || a().barra_pega >= 0.0) && !a().sheet.open {
            let (top, h, by, bh) = barra_geo(max_s);
            let largo = a().barra_hover || a().barra_pega >= 0.0;
            if largo {
                // o trilho do Mac ao passar o ponteiro
                fill_rr(&c, rf(sw - 13.0, top, sw - 2.0, top + h), 5.5, if dark { col(1.0, 1.0, 1.0, 0.08) } else { col(0.0, 0.0, 0.0, 0.05) });
            }
            let (bx0, bx1) = (if largo { sw - 11.0 } else { sw - 9.0 }, sw - 4.0);
            fill_rr(&c, rf(bx0, by, bx1, by + bh), (bx1 - bx0) / 2.0, if dark { col(1.0, 1.0, 1.0, if largo { 0.5 } else { 0.38 }) } else { col(0.0, 0.0, 0.0, if largo { 0.45 } else { 0.35 }) });
        }
    }
    draw_sidebar(&c, &pal, sh);
    if a().sheet.open {
        a().hits.clear();
        draw_sheet(&c, &pal);
    }
    let (win_clip, win_r) = *WIN_CLIP.get();
    if win_clip {
        unsafe {
            rt.PopLayer();
            comum::tahoe::window_rim(rt, &br, sw, sh, win_r, dark);
        }
    }
    if !a().toggle_anim.is_empty() && !a().hwnd.0.is_null() {
        unsafe {
            SetTimer(a().hwnd, T_ANIM, 15, None);
        }
    }
}
/// a janela desenhada pela Composição (finder/gfx.cpp), com o vidro, o canto contínuo e as bordas de rolagem do Tahoe
static GFX: Global<Option<comum::tahoe::Gfx>> = Global::new(None);
static SOMBRA: Global<Option<comum::tahoe::Shadow>> = Global::new(None);
/// o contexto da Composição do quadro atual (None: HwndRenderTarget, sem o vidro)
static CUR_DC: Global<Option<ID2D1DeviceContext>> = Global::new(None);
/// recorte da janela aberto no quadro (aberto, raio)
static WIN_CLIP: Global<(bool, f32)> = Global::new((false, 0.0));
fn sombra_update() {
    if let Some(sh) = SOMBRA.get().as_mut() {
        sh.update();
    }
}
fn reduzir() -> bool {
    setting("reduzir_transparencia", "0") == "1"
}
fn paint() {
    unsafe {
        if let Some(g) = GFX.get().as_ref() {
            let Some(dc) = g.begin(GetDpiForWindow(a().hwnd) as f32) else { return };
            let rt: ID2D1RenderTarget = dc.cast().unwrap();
            if a().rt.as_ref() != Some(&rt) {
                a().rt = Some(rt.clone());
            }
            *CUR_DC.get() = if leo() { None } else { Some(dc.clone()) };
            *WIN_CLIP.get() = (false, 0.0);
            render(&rt);
            *CUR_DC.get() = None;
            if g.end().is_err() {
                *BMP_D2D.get() = None;
            }
            return;
        }
        let h = a().hwnd;
        if a().rt.is_none() {
            let mut rc = RECT::default();
            let _ = GetClientRect(h, &mut rc);
            let dpi = GetDpiForWindow(h) as f32;
            let props = D2D1_RENDER_TARGET_PROPERTIES { pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_IGNORE }, dpiX: dpi, dpiY: dpi, ..Default::default() };
            let hp = D2D1_HWND_RENDER_TARGET_PROPERTIES { hwnd: h, pixelSize: D2D_SIZE_U { width: rc.right as u32, height: rc.bottom as u32 }, presentOptions: D2D1_PRESENT_OPTIONS_NONE };
            let Ok(r) = d2d().CreateHwndRenderTarget(&props, &hp) else { return };
            r.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
            a().rt = r.cast().ok();
            a().hrt = Some(r);
            *BMP_D2D.get() = None; // os bitmaps são do alvo antigo
        }
        let Some(rt) = a().rt.clone() else { return };
        rt.BeginDraw();
        render(&rt);
        if let Err(e) = rt.EndDraw(None, None) {
            if e.code() == D2DERR_RECREATE_TARGET {
                a().rt = None;
                a().hrt = None;
            }
        }
    }
}

// ================= Interação
fn hit_at(p: Ponto) -> Option<Hit> {
    let m = a().m;
    for h in a().hits.iter().rev() {
        // de cima para baixo (o último desenhado primeiro)
        if matches!(h.kind, H::Row | H::Toggle | H::Popup | H::Slider | H::Link | H::Button | H::Custom) && (p.y < m.tool_h || p.x < m.side_w) {
            continue; // linhas roladas para baixo da barra de ferramentas
        }
        if h.kind == H::Side && !leo() && p.y < m.search_y + SEARCH_H + 6.0 {
            continue;
        }
        if inr(&h.r, p) {
            return Some(*h);
        }
    }
    None
}
fn row_of(h: &Hit) -> Option<Row> {
    a().page.groups.get(h.a as usize)?.rows.get(h.b as usize).cloned()
}
fn slider_to(h: &Hit, x: f32) {
    let Some(r) = row_of(h) else { return };
    let Some(set) = r.set_f.clone() else { return };
    // h.r é a área de toque (trilho ± 10)
    let mut v = ((x - (h.r.left + 10.0)) / ((h.r.right - 10.0) - (h.r.left + 10.0)).max(1.0)).clamp(0.0, 1.0);
    if r.gg {
        // macOS 27: o botão anda de 10 em 10 pt para dentro das pontas
        v = ((x - (h.r.left + 20.0)) / ((h.r.right - 20.0) - (h.r.left + 20.0)).max(1.0)).clamp(0.0, 1.0);
    }
    // ímã no padrão: perto da marca (até 6 pt), o botão gruda nela
    if r.has_def {
        let d = slider_default(&r);
        let w_ = ((h.r.right - 10.0) - (h.r.left + 10.0)).max(1.0);
        if (v - d).abs() * w_ <= 6.0 {
            v = d;
        }
    }
    set(r.min + v * (r.max - r.min));
    invalidate();
}
fn open_popup(h: &Hit) {
    let Some(r) = row_of(h) else { return };
    if !r.enabled || r.options.is_empty() {
        return;
    }
    let cur = r.get_idx.as_ref().map(|g| g()).unwrap_or(-1);
    let items: Vec<Item> = r
        .options
        .iter()
        .enumerate()
        .map(|(i, o)| {
            if o == "-" {
                return Item::sep();
            }
            let (l, dis) = match o.strip_prefix('!') {
                Some(x) => (x, true),
                None => (o.as_str(), false),
            };
            Item::new(tr(l), i as i32 + 1).checked(i as i32 == cur).disabled(dis)
        })
        .collect();
    let p = app2d::to_screen(a().hwnd, (h.r.left * a().scale) as i32, (h.r.bottom * a().scale) as i32);
    let id = ctxmenu::show_items(a().hwnd, p, &items);
    if id > 0 {
        if let Some(s) = &r.set_idx {
            s(id - 1);
            show_page();
        }
    }
    invalidate();
}
fn close_sheet() {
    a().sheet.open = false;
    a().sheet.field.set_text("", false);
    invalidate();
}
fn sheet_ok() {
    let f = a().sheet.ok.clone();
    let t = a().sheet.field.string();
    close_sheet();
    if let Some(f) = f {
        f(t);
    }
}
fn click(p: Ponto) {
    let Some(h) = hit_at(p) else {
        if a().search_focus {
            a().search_focus = false;
            invalidate();
        }
        return;
    };
    if h.kind != H::Search {
        a().search_focus = false;
    }
    if h.kind == H::ShowAll {
        // Leopard: "Mostrar Todos" (a grade de painéis)
        a().leo_all = true;
        a().search.set_text("", false);
        update_side_visible();
        a().scroll = 0.0;
        a().scroll_target = 0.0;
        invalidate();
        return;
    }
    if h.kind == H::Back && leo() && !a().leo_all && a().hist_at <= 0 {
        a().leo_all = true;
        a().scroll = 0.0;
        a().scroll_target = 0.0;
        invalidate();
        return;
    }
    let hw = a().hwnd;
    match h.kind {
        H::Light => unsafe {
            match h.a {
                0 => {
                    let _ = PostMessageW(hw, WM_CLOSE, WPARAM(0), LPARAM(0));
                }
                1 => {
                    let _ = ShowWindow(hw, SW_MINIMIZE);
                }
                _ => ampliacao::alternar(hw),
            }
        },
        H::Back => go(-1),
        H::Fwd => go(1),
        H::Search => {
            a().search_focus = true;
            a().caret_at = unsafe { GetTickCount() };
            let tf = if leo() { a().f.lf.clone() } else { a().f.body.clone() };
            a().search.click(dw(), &tf, p, false);
            unsafe {
                SetTimer(hw, T_CARET, 530, None);
            }
        }
        H::Side => select_side(h.a as usize),
        H::Account => select_side_id("conta"),
        H::Toggle => {
            let Some(r) = row_of(&h) else { return };
            if !r.enabled {
                return;
            }
            let Some(set) = r.set.clone() else { return };
            let nv = !r.get.as_ref().map(|g| g()).unwrap_or(false);
            let key = row_key(h.a as usize, h.b as usize);
            a().toggle_anim.insert(key, (unsafe { GetTickCount() }, nv));
            set(nv);
            show_page();
        }
        H::Popup => open_popup(&h),
        H::Slider => {
            let Some(r) = row_of(&h) else { return };
            if !r.enabled {
                return;
            }
            a().drag = (h.a, h.b, h.r);
            SLIDE.get().0 = true;
            unsafe {
                SetCapture(hw);
            }
            slider_to(&h, p.x);
        }
        H::Link | H::Row | H::Button => {
            if let Some(r) = row_of(&h) {
                if r.enabled {
                    if let Some(f) = r.click.clone() {
                        f();
                    }
                }
            }
        }
        H::Custom => {
            if let Some(r) = row_of(&h) {
                if let Some(f) = r.click_at.clone() {
                    f(p, h.r);
                }
            }
        }
        H::SheetCancel => close_sheet(),
        H::SheetOk => sheet_ok(),
        H::SheetField => {
            let tf = a().f.body.clone();
            a().sheet.field.click(dw(), &tf, p, false);
            a().caret_at = unsafe { GetTickCount() };
        }
        H::ShowAll => {}
    }
    invalidate();
}
fn na_barra(p: Ponto) -> bool {
    !a().sheet.open && max_scroll() > 0.0 && p.x >= client_dip().0 - 14.0 && p.y > a().m.tool_h
}
fn rola_para(y: f32, suave: bool) {
    a().scroll_target = y.clamp(0.0, max_scroll());
    if !suave {
        a().scroll = a().scroll_target;
    }
    unsafe {
        a().barra_ate = GetTickCount() + 900;
        SetTimer(a().hwnd, T_BARRA, 950, None);
        if suave {
            SetTimer(a().hwnd, T_ANIM, 15, None);
            liga_relogio(a().hwnd);
        }
    }
    invalidate();
}
fn side_max_scroll() -> f32 {
    (a().side_h - (client_dip().1 - a().m.account_y)).max(0.0)
}
fn hit_test_nc(h: HWND, l: LPARAM) -> LRESULT {
    let p_ = app2d::screen_to_client(h, l);
    let mut rc = RECT::default();
    unsafe {
        let _ = GetClientRect(h, &mut rc);
        let s = a().scale;
        if !IsZoomed(h).as_bool() {
            let b = (6.0 * s) as i32;
            let (l_, r_, t_, b_) = (p_.x < b, p_.x >= rc.right - b, p_.y < b, p_.y >= rc.bottom - b);
            let ht = match (t_, b_, l_, r_) {
                (true, _, true, _) => HTTOPLEFT,
                (true, _, _, true) => HTTOPRIGHT,
                (_, true, true, _) => HTBOTTOMLEFT,
                (_, true, _, true) => HTBOTTOMRIGHT,
                (_, _, true, _) => HTLEFT,
                (_, _, _, true) => HTRIGHT,
                (true, _, _, _) => HTTOP,
                (_, true, _, _) => HTBOTTOM,
                _ => 0,
            };
            if ht != 0 {
                return LRESULT(ht as isize);
            }
        }
        let d = pt(p_.x as f32 / s, p_.y as f32 / s);
        if a().sheet.open {
            return LRESULT(HTCLIENT as isize);
        }
        let m = a().m;
        if leo() {
            // Leopard: a barra inteira arrasta, menos os botões, a busca e os três botões da janela
            if d.y >= m.tool_h || a().hits.iter().any(|hh| inr(&hh.r, d)) {
                return LRESULT(HTCLIENT as isize);
            }
            return LRESULT(HTCAPTION as isize);
        }
        let lights = d.x >= 10.0 && d.x < 76.0 && d.y < 40.0;
        let arrows = d.x >= m.side_w + 10.0 && d.x < m.side_w + 84.0 && d.y < m.tool_h;
        if !lights && !arrows && d.y < m.tool_h - 4.0 && (d.x >= m.side_w || d.y < m.search_y - 4.0) {
            return LRESULT(HTCAPTION as isize);
        }
    }
    LRESULT(HTCLIENT as isize)
}
fn apply_window_theme() {
    let tahoe = a().tahoe;
    let gg = golden();
    let lo = leo();
    a().m = M {
        side_w: if lo {
            0.0 // Leopard: as Preferências do Sistema não têm barra lateral (Mostrar Todos)
        } else if tahoe {
            if gg {
                231.0
            } else {
                247.0
            }
        } else {
            215.0
        },
        tool_h: if lo { 56.0 } else { 52.0 },
        side_row: if tahoe { 32.0 } else { 28.0 },
        row_h: if tahoe {
            if gg {
                37.5
            } else {
                42.0
            }
        } else {
            38.0
        },
        search_y: if gg { 62.0 } else { 52.0 },
        account_y: if gg { 96.0 } else { 90.0 },
    };
    let h = a().hwnd;
    if h.0.is_null() {
        return;
    }
    unsafe {
        let dm = BOOL::from(a().dark);
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(20), &dm as *const _ as *const c_void, 4);
        let com_gfx = GFX.get().is_some();
        if com_gfx && tahoe {
            // Tahoe: cantos de 26 pt com o vidro da Composição
            comum::tahoe::frame(h, true);
            comum::tahoe::size(h, a().dark, reduzir());
            if let Some(sh) = SOMBRA.get().as_mut() {
                sh.set_radius(comum::tahoe::window_r(gg));
            }
            return;
        }
        if com_gfx {
            comum::tahoe::frame(h, false);
            if let Some(sh) = SOMBRA.get().as_mut() {
                sh.set_radius(0.0);
            }
        }
        let border = if a().dark { app2d::colorref(88, 88, 92) } else { app2d::colorref(196, 196, 200) };
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(34), &border as *const _ as *const c_void, 4);
        // issue #235: sem a cor de destaque do Windows no topo da barra lateral (ver o mesmo trecho no Finder)
        let sem_barra = 0xFFFF_FFFEu32; // DWMWA_COLOR_NONE
        if DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(35), &sem_barra as *const _ as *const c_void, 4).is_err() {
            let lateral = if a().dark { app2d::colorref(0x2D, 0x2D, 0x2F) } else { app2d::colorref(0xE9, 0xE9, 0xEA) };
            let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(35), &lateral as *const _ as *const c_void, 4);
        }
        let corner: u32 = 2; // DWMWCP_ROUND
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const c_void, 4);
        if com_gfx {
            let backdrop = 3i32; // DWMSBT_TRANSIENTWINDOW: acrílico do sistema na barra lateral
            let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(38), &backdrop as *const _ as *const c_void, 4);
        }
    }
}
/// Renomear um app (pedido no Discord, 24/11/2026): o Dock e o Launchpad abrem os Ajustes com
/// --pagina="renomear:<nome atual>|<chave>|<chave>...". O nome novo vai para %APPDATA%\Shell\nomes-apps.txt
fn pedido_renomear(id: &str) -> bool {
    let Some(rest) = id.strip_prefix("renomear:") else { return false };
    let p: Vec<String> = rest.split('|').map(|s| s.to_string()).collect();
    if p.len() < 2 {
        return true;
    }
    let atual = p[0].clone();
    let chaves: Vec<String> = p[1..].to_vec();
    select_side_id("dock");
    ask_text(&format!("{} “{}”", tr("Renomear"), atual), &tr("O nome novo aparece no Dock, no Launchpad e na barra de menus. Deixe vazio para voltar ao nome original."), "Renomear", false, Rc::new(move |novo: String| {
        if modo_foto() {
            return;
        }
        let novo = novo.replace(['\t', '\r', '\n'], " ").trim().to_string();
        let f = data_path("nomes-apps.txt");
        let mut linhas: Vec<String> = app2d::read_lines(&f)
            .into_iter()
            .filter(|s| match s.split_once('\t') {
                Some((k, _)) => !chaves.iter().any(|c| c.eq_ignore_ascii_case(k)),
                None => false,
            })
            .collect();
        if !novo.is_empty() {
            for k in &chaves {
                linhas.push(format!("{k}\t{novo}"));
            }
        }
        app2d::write_lines(&f, &linhas);
        if let Some(sh) = find_window("ShellMensagens") {
            unsafe {
                let _ = PostMessageW(sh, reg_msg("ShellIconeMudou"), WPARAM(0), LPARAM(0)); // o Dock e o Launchpad redesenham já
            }
        }
    }), &atual);
    true
}
fn reload_theme() -> bool {
    let t = tahoe_on();
    if t != a().tahoe {
        a().tahoe = t;
        a().dark = read_dark();
        apply_window_theme();
        return true;
    }
    false
}

// Posição e tamanho da janela entre uma abertura e outra (issue #236): %APPDATA%\Shell\ajustes-janela.txt com
// "x y largura altura" em px (o mesmo arquivo do C++). Fora do ajustes.txt de propósito: o Shell relê tudo a cada gravação.
fn janela_arq() -> Option<String> {
    std::env::var("APPDATA").ok().map(|a| format!("{a}\\Shell\\ajustes-janela.txt"))
}
fn guarda_janela(h: HWND) {
    unsafe {
        if h.0.is_null() || IsZoomed(h).as_bool() || IsIconic(h).as_bool() || !IsWindowVisible(h).as_bool() || modo_foto() {
            return;
        }
        let mut r = RECT::default();
        if GetWindowRect(h, &mut r).is_err() {
            return;
        }
        if let Some(f) = janela_arq() {
            let _ = std::fs::write(f, format!("{} {} {} {}\n", r.left, r.top, r.right - r.left, r.bottom - r.top));
        }
    }
}
/// a guardada, se ainda cabe num monitor (o monitor pode ter saído) e não é menor que o mínimo
fn le_janela(sc: f32) -> Option<(i32, i32, i32, i32)> {
    let t = std::fs::read_to_string(janela_arq()?).ok()?;
    let v: Vec<i32> = t.split_whitespace().filter_map(|x| x.parse().ok()).collect();
    if v.len() != 4 || v[2] < (680.0 * sc) as i32 || v[3] < (420.0 * sc) as i32 {
        return None;
    }
    let r = RECT { left: v[0], top: v[1], right: v[0] + v[2], bottom: v[1] + v[3] };
    unsafe {
        let mon = MonitorFromRect(&r, MONITOR_DEFAULTTONULL);
        let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
        if mon.0.is_null() || !GetMonitorInfoW(mon, &mut mi).as_bool() {
            return None;
        }
        let w = mi.rcWork;
        let iw = r.right.min(w.right) - r.left.max(w.left);
        let ih = r.bottom.min(w.bottom) - r.top.max(w.top);
        if iw < 200 || ih < 100 {
            return None; // quase toda fora da tela
        }
        Some((v[0], v[1].max(w.top), v[2].min(w.right - w.left), v[3].min(w.bottom - w.top)))
    }
}

extern "system" fn wnd_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    unsafe {
        if A.get().is_none() || a().hwnd.0.is_null() {
            return DefWindowProcW(h, m, w_, l);
        }
        let s = a().scale;
        let pcli = || pt(get_x_lparam(l) as f32 / s, get_y_lparam(l) as f32 / s);
        if m == WM_QUADRO {
            QUADRO_PENDENTE.store(false, Ordering::SeqCst);
            if !RELOGIO.load(Ordering::SeqCst) {
                return LRESULT(0);
            }
            wnd_proc(h, WM_TIMER, WPARAM(T_ANIM), LPARAM(0)); // o mesmo passo do temporizador
            if GetUpdateRect(h, None, false).as_bool() {
                paint(); // desenha já, neste quadro
                let _ = ValidateRect(h, None);
            }
            return LRESULT(0);
        }
        match m {
            WM_NCCALCSIZE if w_.0 != 0 => {
                if IsZoomed(h).as_bool() {
                    let p = &mut *(l.0 as *mut NCCALCSIZE_PARAMS);
                    let dpi = GetDpiForWindow(h);
                    let fx = GetSystemMetricsForDpi(SM_CXFRAME, dpi) + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi);
                    let fy = GetSystemMetricsForDpi(SM_CYFRAME, dpi) + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi);
                    p.rgrc[0].left += fx;
                    p.rgrc[0].right -= fx;
                    p.rgrc[0].top += fy;
                    p.rgrc[0].bottom -= fy;
                }
                return LRESULT(0);
            }
            WM_NCHITTEST => return hit_test_nc(h, l),
            WM_NCLBUTTONDBLCLK if w_.0 == HTCAPTION as usize => {
                ampliacao::alternar(h);
                return LRESULT(0);
            }
            WM_GETMINMAXINFO => {
                let mm = &mut *(l.0 as *mut MINMAXINFO);
                mm.ptMinTrackSize = POINT { x: (680.0 * s) as i32, y: (420.0 * s) as i32 };
                return LRESULT(0);
            }
            WM_SIZE => {
                if let Some(g) = GFX.get().as_mut() {
                    if w_.0 != SIZE_MINIMIZED as usize {
                        g.resize(loword(l.0 as usize), hiword(l.0 as usize));
                        if a().tahoe {
                            comum::tahoe::size(h, a().dark, reduzir());
                        }
                    }
                }
                if let Some(r) = &a().hrt {
                    let _ = r.Resize(&D2D_SIZE_U { width: loword(l.0 as usize), height: hiword(l.0 as usize) });
                }
                a().scroll = a().scroll.min(max_scroll());
                a().scroll_target = a().scroll;
                invalidate();
                return LRESULT(0);
            }
            WM_DPICHANGED => {
                a().scale = hiword(w_.0) as f32 / 96.0;
                a().rt = None;
                a().hrt = None;
                let r = &*(l.0 as *const RECT);
                let _ = SetWindowPos(h, None, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOZORDER | SWP_NOACTIVATE);
                return LRESULT(0);
            }
            WM_ACTIVATE => {
                a().win_active = loword(w_.0) != WA_INACTIVE;
                if let Some(sh) = SOMBRA.get().as_mut() {
                    sh.set_active(a().win_active);
                    sh.update();
                }
                invalidate();
            }
            WM_WINDOWPOSCHANGED => sombra_update(),
            WM_SETTINGCHANGE => {
                if l.0 != 0 && from_w(std::slice::from_raw_parts(l.0 as *const u16, 64)).eq_ignore_ascii_case("ImmersiveColorSet") {
                    a().dark = read_dark();
                    apply_window_theme();
                    invalidate();
                }
            }
            WM_PAINT => {
                let mut ps = PAINTSTRUCT::default();
                BeginPaint(h, &mut ps);
                let _ = EndPaint(h, &ps);
                paint();
                return LRESULT(0);
            }
            WM_ERASEBKGND => return LRESULT(1),
            WM_MOUSEMOVE => {
                let p = pcli();
                let lbtn = w_.0 & 1 != 0;
                if a().drag.0 >= 0 && lbtn {
                    let (g_, r_, tr_) = a().drag;
                    slider_to(&hit(H::Slider, tr_, g_, r_), p.x);
                    return LRESULT(0);
                }
                if a().barra_pega >= 0.0 {
                    if !lbtn {
                        a().barra_pega = -1.0;
                        let _ = ReleaseCapture();
                        invalidate();
                        return LRESULT(0);
                    }
                    let max_s = max_scroll();
                    let (top, hh, _, bh) = barra_geo(max_s);
                    if hh > bh {
                        rola_para((p.y - a().barra_pega - top) / (hh - bh) * max_s, false);
                    }
                    return LRESULT(0);
                }
                let nb = na_barra(p);
                if nb != a().barra_hover {
                    a().barra_hover = nb;
                    invalidate();
                }
                let hl = p.x >= 10.0 && p.x < 84.0 && p.y < 40.0;
                ampliacao::verde(h, hl && (58.0..81.0).contains(&p.x));
                if hl != a().hover_lights {
                    a().hover_lights = hl;
                    invalidate();
                }
                let mut t = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };
                let _ = TrackMouseEvent(&mut t);
                let ht = hit_at(p);
                SetCursor(LoadCursorW(None, if ht.map(|x| x.kind == H::Search).unwrap_or(false) { IDC_IBEAM } else { IDC_ARROW }).unwrap_or_default());
                return LRESULT(0);
            }
            WM_MOUSELEAVE => {
                ampliacao::verde(h, false);
                if a().hover_lights || a().barra_hover {
                    a().hover_lights = false;
                    a().barra_hover = false;
                    invalidate();
                }
                return LRESULT(0);
            }
            WM_SETCURSOR if loword(l.0 as usize) == HTCLIENT => return LRESULT(1),
            WM_LBUTTONDOWN => {
                let _ = SetFocus(h);
                let p = pcli();
                if na_barra(p) {
                    let max_s = max_scroll();
                    let (_, _, by, bh) = barra_geo(max_s);
                    if p.y >= by && p.y <= by + bh {
                        a().barra_pega = p.y - by;
                        SetCapture(h);
                        invalidate();
                    } else {
                        let tela = client_dip().1 - a().m.tool_h - 40.0;
                        rola_para(a().scroll_target + if p.y < by { -tela } else { tela }, true); // o trilho: uma tela
                    }
                    return LRESULT(0);
                }
                click(p);
                return LRESULT(0);
            }
            WM_LBUTTONUP => {
                if a().barra_pega >= 0.0 {
                    a().barra_pega = -1.0;
                    let _ = ReleaseCapture();
                    invalidate();
                    return LRESULT(0);
                }
                if a().drag.0 >= 0 {
                    a().drag = (-1, -1, rf(0.0, 0.0, 0.0, 0.0));
                    SLIDE.get().0 = false;
                    flush_slide();
                    let _ = ReleaseCapture();
                    show_page();
                    invalidate();
                }
                return LRESULT(0);
            }
            WM_MOUSEWHEEL => {
                let p_ = app2d::screen_to_client(h, l);
                let d = -app2d::wheel_delta(w_) / 120.0 * 48.0;
                if (p_.x as f32 / s) < a().m.side_w {
                    a().side_scroll = (a().side_scroll + d).clamp(0.0, side_max_scroll());
                } else {
                    a().scroll_target = (a().scroll_target + d).clamp(0.0, max_scroll());
                    a().barra_ate = GetTickCount() + 900;
                    SetTimer(h, T_BARRA, 950, None);
                    SetTimer(h, T_ANIM, 15, None);
                    liga_relogio(h);
                }
                invalidate();
                return LRESULT(0);
            }
            WM_TIMER => {
                match w_.0 {
                    T_SLIDE => flush_slide(),
                    T_BARRA => {
                        let _ = KillTimer(h, T_BARRA);
                        invalidate(); // o indicador de rolagem some
                    }
                    T_FRENTE => {
                        // já à mostra: para a frente de verdade
                        let _ = KillTimer(h, T_FRENTE);
                        if GetForegroundWindow() != h {
                            let _ = SetForegroundWindow(h);
                        }
                        let _ = BringWindowToTop(h);
                    }
                    T_REFRESH => {
                        load_settings();
                        if reload_theme() {
                            invalidate();
                        }
                        if !a().sheet.open && a().drag.0 < 0 && !ctxmenu::is_open() {
                            let d = read_dark();
                            if d != a().dark {
                                a().dark = d;
                                apply_window_theme();
                            }
                            show_page();
                            invalidate();
                        }
                    }
                    T_ANIM => {
                        // passo pelo tempo real
                        // relógio fino (o GetTickCount anda de 15,6 em 15,6 ms: com um passo por quadro a 144 Hz, o
                        // tempo vinha 0 ou 16 e a rolagem andava aos saltos)
                        thread_local!(static ULT: std::cell::Cell<Option<std::time::Instant>> = const { std::cell::Cell::new(None) });
                        let agora = std::time::Instant::now();
                        let dt = ULT.with(|u| u.replace(Some(agora))).map(|t| agora.duration_since(t).as_secs_f64() * 1000.0).unwrap_or(15.0).clamp(1.0, 60.0);
                        let diff = a().scroll_target - a().scroll;
                        if diff.abs() < 0.5 {
                            a().scroll = a().scroll_target;
                        } else {
                            a().scroll += diff * (1.0 - 0.55f64.powf(dt / 15.0)) as f32; // issue #176: 45% do que falta a cada 15 ms (era 30%)
                        }
                        if a().scroll == a().scroll_target {
                            RELOGIO.store(false, Ordering::SeqCst); // chegou: a thread do ritmo para
                        }
                        if a().scroll == a().scroll_target && a().toggle_anim.is_empty() {
                            let _ = KillTimer(h, T_ANIM);
                        }
                        invalidate();
                    }
                    T_CARET => {
                        if !a().search_focus && !a().sheet.open {
                            let _ = KillTimer(h, T_CARET);
                        }
                        invalidate();
                    }
                    _ => {}
                }
                return LRESULT(0);
            }
            WM_KEYDOWN => {
                let k = w_.0 as u16;
                let v = VIRTUAL_KEY(k);
                let (shift, ctrl) = (app2d::key_down(VK_SHIFT.0), app2d::key_down(VK_CONTROL.0));
                if a().sheet.open {
                    if v == VK_ESCAPE {
                        close_sheet();
                    } else if v == VK_RETURN {
                        sheet_ok();
                    } else if a().sheet.field.on_key(k, shift, ctrl) {
                        a().caret_at = GetTickCount();
                        invalidate();
                    }
                    return LRESULT(0);
                }
                if ctrl && k == 0x46 {
                    a().search_focus = true;
                    let n = a().search.text.len() as i32;
                    a().search.select(0, n);
                    SetTimer(h, T_CARET, 530, None);
                    invalidate();
                    return LRESULT(0);
                }
                if ctrl && k == 0x57 {
                    let _ = PostMessageW(h, WM_CLOSE, WPARAM(0), LPARAM(0));
                    return LRESULT(0);
                }
                if ctrl && v == VK_OEM_4 {
                    go(-1);
                    return LRESULT(0);
                }
                if ctrl && v == VK_OEM_6 {
                    go(1);
                    return LRESULT(0);
                }
                if a().search_focus {
                    if v == VK_ESCAPE {
                        a().search.set_text("", false);
                        a().search_focus = false;
                        update_side_visible();
                        invalidate();
                        return LRESULT(0);
                    }
                    if v == VK_RETURN {
                        if let Some(&i) = a().side_visible.first() {
                            select_side(i);
                        }
                        return LRESULT(0);
                    }
                    if a().search.on_key(k, shift, ctrl) {
                        a().caret_at = GetTickCount();
                        update_side_visible();
                        invalidate();
                    }
                    return LRESULT(0);
                }
                if [VK_NEXT, VK_PRIOR, VK_HOME, VK_END, VK_SPACE].contains(&v) {
                    // rola o conteúdo
                    let tela = client_dip().1 - a().m.tool_h - 40.0;
                    let y = if v == VK_HOME {
                        0.0
                    } else if v == VK_END {
                        max_scroll()
                    } else {
                        a().scroll_target + if v == VK_PRIOR || (v == VK_SPACE && shift) { -tela } else { tela }
                    };
                    rola_para(y, true);
                    return LRESULT(0);
                }
                if v == VK_UP || v == VK_DOWN {
                    // anda pela barra lateral
                    let cur = if a().hist_at >= 0 { a().hist[a().hist_at as usize].side } else { -1 };
                    let vis = a().side_visible.clone();
                    let pos = match vis.iter().position(|&x| x as i32 == cur) {
                        None => 0,
                        Some(p) => p as i32 + if v == VK_DOWN { 1 } else { -1 },
                    };
                    if pos >= 0 && (pos as usize) < vis.len() {
                        select_side(vis[pos as usize]);
                    }
                }
                return LRESULT(0);
            }
            WM_CHAR => {
                let ch = w_.0 as u16;
                if ch < 32 {
                    return LRESULT(0);
                }
                if a().sheet.open {
                    a().sheet.field.on_char(ch);
                    a().caret_at = GetTickCount();
                    invalidate();
                    return LRESULT(0);
                }
                if !a().search_focus {
                    // digitar vai para a busca, como no Mac
                    a().search_focus = true;
                    SetTimer(h, T_CARET, 530, None);
                }
                a().search.on_char(ch);
                a().caret_at = GetTickCount();
                update_side_visible();
                invalidate();
                return LRESULT(0);
            }
            WM_COPYDATA => {
                // outra instância pediu uma página
                let cd = &*(l.0 as *const COPYDATASTRUCT);
                if cd.dwData == 0x414A5354 && cd.cbData > 0 {
                    let id = String::from_utf16_lossy(std::slice::from_raw_parts(cd.lpData as *const u16, cd.cbData as usize / 2));
                    let i = sidebar_index_for(&id);
                    if pedido_renomear(&id) {
                    } else if i >= 0 {
                        select_side(i as usize);
                    } else if id == "atualizacao" {
                        select_side_id("geral");
                        open_update_page();
                    }
                }
                if IsIconic(h).as_bool() {
                    let _ = ShowWindow(h, SW_RESTORE);
                }
                let _ = SetForegroundWindow(h); // já aberta: para a frente
                let _ = BringWindowToTop(h);
                return LRESULT(1);
            }
            WM_APP_REBUILD => {
                load_settings();
                reload_theme(); // Tema trocado aqui mesmo
                if a().drag.0 < 0 && !ctxmenu::is_open() {
                    show_page();
                }
                invalidate();
                return LRESULT(0);
            }
            WM_APP_NA_INTERFACE => {
                let f = Box::from_raw(l.0 as *mut Box<dyn FnOnce() + Send>);
                f();
                return LRESULT(0);
            }
            WM_APP_BITMAP => {
                let res = Box::from_raw(l.0 as *mut BmpResult);
                BMP_PENDING.lock().unwrap().get_or_insert_with(HashSet::new).remove(&res.key);
                BMP_PX.lock().unwrap().get_or_insert_with(HashMap::new).insert(res.key.clone(), res.px);
                invalidate();
                return LRESULT(0);
            }
            WM_EXITSIZEMOVE => guarda_janela(h),
            WM_CLOSE => {
                guarda_janela(h);
                let _ = DestroyWindow(h);
                return LRESULT(0);
            }
            WM_DESTROY => {
                if let Some(sh) = SOMBRA.get().as_mut() {
                    sh.destroy();
                }
                PostQuitMessage(0);
                return LRESULT(0);
            }
            _ => {}
        }
        DefWindowProcW(h, m, w_, l)
    }
}

/// modo foto: cada página num PNG (2x), sem janela à mostra e sem gravar nada
fn foto(pasta: &str, so: Option<String>) {
    let _ = std::fs::create_dir_all(pasta);
    let (w_, h) = a().foto.unwrap();
    let ids: Vec<(i32, String)> = match &so {
        Some(id) => vec![(sidebar_index_for(id), id.clone())],
        None => sidebar_items().iter().enumerate().map(|(i, it)| (i as i32, it.id.clone())).collect(),
    };
    let wic: IWICImagingFactory = unsafe { CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).unwrap() };
    let shot = |nome: &str| -> Result<()> {
        unsafe {
            let bmp = wic.CreateBitmap((w_ * 2.0) as u32, (h * 2.0) as u32, &GUID_WICPixelFormat32bppPBGRA, 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: ID2D1RenderTarget = d2d().CreateWicBitmapRenderTarget(&bmp, &props)?;
            rt.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
            a().rt = Some(rt.clone());
            *BMP_D2D.get() = None;
            // duas passadas: a primeira mede a página (content_h) e carrega as imagens
            for _ in 0..2 {
                rt.BeginDraw();
                rt.Clear(Some(&col(1.0, 1.0, 1.0, 1.0)));
                render(&rt);
                rt.EndDraw(None, None)?;
            }
            app2d::salvar_png(&bmp, &format!("{pasta}\\{nome}.png"))
        }
    };
    let rolar = std::env::args().any(|x| x == "--rolar");
    for (n, (i, id)) in ids.iter().enumerate() {
        if *i < 0 {
            println!("{id}: página não existe");
            continue;
        }
        a().leo_all = false;
        a().hist = vec![Entry { side: *i, stack: Vec::new() }];
        a().hist_at = 0;
        a().scroll = 0.0;
        a().scroll_target = 0.0;
        show_page();
        let nome = format!("{:02}-{id}", n + 1);
        println!("{nome}: {:?}", shot(&nome));
        if rolar {
            // a página rolada até o fim (o que não coube na primeira foto)
            let ms = max_scroll();
            if ms > 0.0 {
                a().scroll = ms;
                a().scroll_target = ms;
                println!("{nome}-fim: {:?}", shot(&format!("{nome}-fim")));
            }
        }
    }
    if so.is_none() && leo() {
        a().leo_all = true;
        a().scroll = 0.0;
        println!("00-mostrar-todos: {:?}", shot("00-mostrar-todos"));
    }
    // a folha de senha do Wi-Fi e as subpáginas de Geral
    if so.is_none() {
        a().hist = vec![Entry { side: sidebar_index_for("geral"), stack: Vec::new() }];
        a().hist_at = 0;
        a().leo_all = false;
        show_page();
        for (t, f) in [("Sobre", sobre as fn() -> Page), ("Atualização de Software", atualizacao), ("Transparência e Efeitos", paginas2::transparencia_efeitos)] {
            push(t, Rc::new(f));
            println!("sub {t}: {:?}", shot(&format!("sub-{}", t.split(' ').next().unwrap().to_lowercase())));
        }
        ask_text(&format!("{}Casa{}", tr("A rede Wi\u{2011}Fi “"), tr("” requer uma senha.")), "", "Conectar", true, Rc::new(|_| {}), "segredo");
        println!("folha: {:?}", shot("folha-senha"));
        close_sheet();
    }
}

/// issue #508: o Ajustes fechava sem deixar rastro (panic = "abort"): o lugar do pânico vai para bin\ajustes-panico.log
fn instala_panico() {
    std::panic::set_hook(Box::new(|info| {
        use std::io::Write;
        let st = unsafe { comum::windows::Win32::System::SystemInformation::GetLocalTime() };
        let pilha = std::backtrace::Backtrace::force_capture();
        let versao = std::env::current_exe().ok().and_then(|e| std::fs::read_to_string(e.with_file_name("versao.txt")).ok()).unwrap_or_default();
        let base = unsafe { comum::windows::Win32::System::LibraryLoader::GetModuleHandleW(None).map(|m| m.0 as usize).unwrap_or(0) };
        let txt = format!(
            "=== {:04}-{:02}-{:02} {:02}:{:02}:{:02} pânico no Ajustes\n{info}\nversão: {}\nbase do WacOSSettings.exe: {base:#x}\n{pilha}\n\n",
            st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, versao.trim().replace('\n', " / ")
        );
        if let Ok(exe) = std::env::current_exe() {
            let p = exe.with_file_name("ajustes-panico.log");
            if std::fs::metadata(&p).map(|m| m.len() > 1024 * 1024).unwrap_or(false) {
                let _ = std::fs::remove_file(&p);
            }
            if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&p) {
                let _ = f.write_all(txt.as_bytes());
            }
        }
    }));
}
fn main() {
    instala_panico();
    let args: Vec<String> = std::env::args().collect();
    let foto_dir = args.iter().position(|x| x == "--foto").and_then(|i| args.get(i + 1).cloned());
    FOTO.store(foto_dir.is_some(), Ordering::Relaxed);
    let page = args.iter().skip(1).find_map(|a_| a_.strip_prefix("--pagina=").map(|s| s.to_string()).or_else(|| if a_.starts_with("ms-settings:") { Some(a_.clone()) } else { None })).unwrap_or_default();
    unsafe {
        let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
        // uma janela só: se já está aberta, só leva para a página pedida
        if foto_dir.is_none() {
            if let Some(other) = find_window("AjustesJanela") {
                let pw: Vec<u16> = page.encode_utf16().collect();
                let cd = COPYDATASTRUCT { dwData: 0x414A5354, cbData: (pw.len() * 2) as u32, lpData: pw.as_ptr() as *mut c_void };
                let _ = AllowSetForegroundWindow(ASFW_ANY);
                let mut r = 0usize;
                SendMessageTimeoutW(other, WM_COPYDATA, WPARAM(0), LPARAM(&cd as *const _ as isize), SMTO_ABORTIFHUNG, 3000, Some(&mut r));
                return;
            }
        }
    }
    if !app2d::init() {
        std::process::exit(1);
    }
    *SETTINGS_PATH.get() = data_path("ajustes.txt").to_string_lossy().to_string();
    // a foto lê os ajustes de verdade uma vez e depois só mexe na cópia da memória
    if let Ok(m) = ajustes::ler(std::path::Path::new(SETTINGS_PATH.get().as_str())) {
        *SETTINGS.get() = m;
    }
    if foto_dir.is_some() {
        if let Some(t) = args.iter().find_map(|x| x.strip_prefix("--tema=")) {
            let (lg, gg, leo_) = match t {
                "golden" => ("1", "1", "0"),
                "tahoe" => ("1", "0", "0"),
                "leopard" => ("0", "0", "1"),
                _ => ("0", "0", "0"),
            };
            let s = SETTINGS.get();
            s.insert("liquid_glass".into(), lg.into());
            s.insert("golden_gate".into(), gg.into());
            s.insert("leopard".into(), leo_.into());
        }
        let esc = args.iter().any(|x| x == "--escuro");
        FOTO_ESCURO.store(esc, Ordering::Relaxed);
        SETTINGS.get().insert("tema".into(), if esc { "escuro".into() } else { "claro".into() });
    }
    let tahoe = tahoe_on();
    let fonts = create_formats();
    let gg0 = tahoe && setting("golden_gate", "0") == "1";
    let foto_size = if gg0 {
        (740.0, 690.0)
    } else if tahoe {
        (801.0, 625.0)
    } else {
        (715.0, 640.0)
    };
    *A.get() = Some(App {
        hwnd: HWND::default(),
        rt: None,
        hrt: None,
        scale: 1.0,
        dark: false,
        win_active: true,
        hover_lights: false,
        tahoe,
        leo_all: true,
        m: M { side_w: 215.0, tool_h: 52.0, side_row: 28.0, row_h: 38.0, search_y: 52.0, account_y: 90.0 },
        f: fonts,
        hist: Vec::new(),
        hist_at: -1,
        page: Page::default(),
        scroll: 0.0,
        scroll_target: 0.0,
        content_h: 0.0,
        side_scroll: 0.0,
        side_h: 0.0,
        search: TextField::default(),
        search_focus: false,
        caret_at: 0,
        sheet: Sheet::default(),
        hits: Vec::new(),
        drag: (-1, -1, rf(0.0, 0.0, 0.0, 0.0)),
        toggle_anim: HashMap::new(),
        side_visible: Vec::new(),
        barra_ate: 0,
        barra_hover: false,
        barra_pega: -1.0,
        tile_bare: false,
        foto: foto_dir.as_ref().map(|_| foto_size),
        last_anim: 0,
    });
    a().dark = read_dark();
    if let Some(l) = SETTINGS.get().get("idioma").cloned() {
        idioma::set(idioma::from_code(&l));
    }
    apply_window_theme();
    update_side_visible();
    let start = {
        let s = sidebar_index_for(&if page.is_empty() { setting("ajustes_pagina", "geral") } else { page.clone() });
        if s < 0 {
            sidebar_index_for("geral")
        } else {
            s
        }
    };
    a().hist.push(Entry { side: start.max(0), stack: Vec::new() });
    a().hist_at = 0;
    show_page();
    a().leo_all = page.is_empty(); // Leopard: abre no Mostrar Todos, a não ser que tenham pedido um painel
    if let Some(dir) = foto_dir {
        let so = if page.is_empty() { None } else { Some(page.clone()) };
        foto(&dir, so);
        return;
    }
    if page == "atualizacao" {
        open_update_page();
    }
    pedido_renomear(&page);
    unsafe {
        let hi: HINSTANCE = GetModuleHandleW(None).unwrap_or_default().into();
        let wc = WNDCLASSEXW { cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32, lpfnWndProc: Some(wnd_proc), hInstance: hi, hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), hIcon: LoadIconW(hi, PCWSTR(1 as *const u16)).unwrap_or_default(), lpszClassName: w!("AjustesJanela"), ..Default::default() };
        RegisterClassExW(&wc);
        // 715 x 640 pt (Tahoe 801 × 625; macOS 27 740 × 690), centralizada na área de trabalho
        let dpi = GetDpiForSystem() as f32;
        let sc = dpi / 96.0;
        let mut wa = RECT::default();
        let _ = SystemParametersInfoW(SPI_GETWORKAREA, 0, Some(&mut wa as *mut RECT as *mut c_void), SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0));
        let ww = (foto_size.0 * sc) as i32;
        let wh = (foto_size.1.min((wa.bottom - wa.top) as f32 / sc - 60.0) * sc) as i32;
        let wx = wa.left + (wa.right - wa.left - ww) / 2;
        let wy = (wa.top + (wa.bottom - wa.top - wh) / 2 - (20.0 * sc) as i32).max(wa.top);
        // como estava ao fechar (issue #236); a foto sempre no tamanho padrão
        let (wx, wy, ww, wh) = if modo_foto() { None } else { le_janela(sc) }.unwrap_or((wx, wy, ww, wh));
        let titulo = wz(&tr_pick("Ajustes do Sistema", "System Settings"));
        // sem bitmap de redirecionamento: o desenho vai pela Composição (como no C++)
        let Ok(h) = CreateWindowExW(WS_EX_NOREDIRECTIONBITMAP, w!("AjustesJanela"), pc(&titulo), WS_OVERLAPPEDWINDOW, wx, wy, ww, wh, None, None, hi, None) else { std::process::exit(1) };
        match comum::tahoe::Gfx::init(h) {
            Some(g) => *GFX.get() = Some(g),
            None => {
                MessageBoxW(None, &HSTRING::from(tr("Não foi possível iniciar o Direct2D.")), &HSTRING::from(tr("Ajustes do Sistema")), MB_ICONERROR);
                std::process::exit(1);
            }
        }
        *SOMBRA.get() = Some(comum::tahoe::Shadow::create(h));
        a().hwnd = h;
        HWND_ATOM.store(h.0 as isize, Ordering::Relaxed);
        app2d::s().wnd = h;
        ampliacao::janela(h); // abrir e fechar animados (o Shell anima)
        a().scale = GetDpiForWindow(h) as f32 / 96.0;
        let mg = MARGINS { cxLeftWidth: -1, cxRightWidth: -1, cyTopHeight: -1, cyBottomHeight: -1 };
        let _ = DwmExtendFrameIntoClientArea(h, &mg);
        apply_window_theme();
        let _ = SetWindowPos(h, None, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
        let _ = ShowWindow(h, SW_SHOW);
        let _ = SetForegroundWindow(h);
        ampliacao::revelar(h);
        SetTimer(h, T_REFRESH, 2500, None);
        SetTimer(h, T_FRENTE, 350, None);
        let mut msg = MSG::default();
        while GetMessageW(&mut msg, None, 0, 0).as_bool() {
            let _ = TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
    }
}