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
119 KB
Raw Blame
//! Calculadora (src\calculadora\main.cpp): Básica, Científica e Programador, Converter, RPN e o histórico.
//! Janela própria (sem a barra do Windows), botões da janela desenhados aqui, teclas com o brilho de vidro.
//! Teste: --foto saida.png desenha fora da tela (a janela não aparece); --foto-teclas "12+3×4=" digita antes;
//! --modo basica|cientifica|programador. No modo foto nada é gravado (ajustes nem histórico).
#![windows_subsystem = "windows"]

use std::collections::HashMap;
use std::ffi::c_void;

use comum::app2d::{self, d2d, dw, key_down, post, salvar_png, screen_to_client, to_screen, wheel_delta};
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Globalization::*;
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::LibraryLoader::GetModuleHandleW;
use comum::windows::Win32::System::SystemInformation::GetTickCount;
use comum::windows::Win32::System::Threading::CreateMutexW;
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::WindowsAndMessaging::*;
use comum::*;

const PI: f64 = std::f64::consts::PI;
const E: f64 = std::f64::consts::E;
const TB: f32 = 52.0;
const SBW: f32 = 220.0;
const CONV_H: f32 = 44.0;
const HIST_H: f32 = 54.0;
const ROUND_R: f32 = 18.0;
const WM_NCMOUSELEAVE: u32 = 0x02A2;

#[derive(Clone, Copy, PartialEq)]
enum Mode {
    Basic,
    Sci,
    Prog,
}

// teclas (os mesmos números do C++: 0..15 são dígitos)
const K_DOT: i32 = 16;
const K_ADD: i32 = 17;
const K_SUB: i32 = 18;
const K_MUL: i32 = 19;
const K_DIV: i32 = 20;
const K_EQ: i32 = 21;
const K_AC: i32 = 22;
const K_DEL: i32 = 23;
const K_PCT: i32 = 24;
const K_NEG: i32 = 25;
const K_LP: i32 = 26;
const K_RP: i32 = 27;
const K_MC: i32 = 28;
const K_MP: i32 = 29;
const K_MM: i32 = 30;
const K_MR: i32 = 31;
const K_2ND: i32 = 32;
const K_SQ: i32 = 33;
const K_CUBE: i32 = 34;
const K_POW: i32 = 35;
const K_EXP: i32 = 36;
const K_10X: i32 = 37;
const K_INV: i32 = 38;
const K_SQRT: i32 = 39;
const K_CBRT: i32 = 40;
const K_YROOT: i32 = 41;
const K_LN: i32 = 42;
const K_LOG10: i32 = 43;
const K_FACT: i32 = 44;
const K_SIN: i32 = 45;
const K_COS: i32 = 46;
const K_TAN: i32 = 47;
const K_E: i32 = 48;
const K_EE: i32 = 49;
const K_RAND: i32 = 50;
const K_SINH: i32 = 51;
const K_COSH: i32 = 52;
const K_TANH: i32 = 53;
const K_PI: i32 = 54;
const K_RAD: i32 = 55;
const K_AND: i32 = 56;
const K_OR: i32 = 57;
const K_XOR: i32 = 58;
const K_NOR: i32 = 59;
const K_SHL: i32 = 60;
const K_SHR: i32 = 61;
const K_XSHLY: i32 = 62;
const K_XSHRY: i32 = 63;
const K_ROL: i32 = 64;
const K_ROR: i32 = 65;
const K_2S: i32 = 66;
const K_1S: i32 = 67;
const K_00: i32 = 68;
const K_FF: i32 = 69;
const K_BFLIP: i32 = 70;
const K_WFLIP: i32 = 71;

const S_FN: usize = 0;
const S_NUM: usize = 1;
const S_TOP: usize = 2;
const S_OP: usize = 3;

#[derive(Clone, Copy)]
struct KeyDef {
    id: i32,
    col: i32,
    row: i32,
    style: usize,
}

#[derive(Clone, Copy, PartialEq, Default)]
enum Tg {
    #[default]
    None,
    Light,
    Key,
    SideBtn,
    ModeBtn,
    Hist,
    Conv,
    Bit,
    Base,
}
#[derive(Clone, Copy, PartialEq, Default)]
struct Target {
    kind: Tg,
    idx: i32,
}

#[derive(Clone, Copy, PartialEq, Debug)]
enum TK {
    Num,
    Val,
    Const,
    Op,
    Neg,
    LP,
    RP,
    Func,
    Post,
    Pow,
    YRoot,
    LogY,
}
const TKS: [TK; 12] = [TK::Num, TK::Val, TK::Const, TK::Op, TK::Neg, TK::LP, TK::RP, TK::Func, TK::Post, TK::Pow, TK::YRoot, TK::LogY];

#[derive(Clone, Debug)]
struct Tok {
    k: TK,
    s: String,
    v: f64,
    hidden: bool,
}
fn tk(k: TK, s: &str, v: f64, hidden: bool) -> Tok {
    Tok { k, s: s.into(), v, hidden }
}

struct Unit {
    name: String,
    sym: String,
    f: f64,
}
struct Cat {
    name: String,
    units: Vec<Unit>,
}
fn cats() -> Vec<Cat> {
    let u = |n: &str, s: &str, f: f64| Unit { name: tr(n), sym: s.to_string(), f };
    let ut = |n: &str, s: &str, f: f64| Unit { name: tr(n), sym: tr(s), f };
    let c = |n: &str, units: Vec<Unit>| Cat { name: tr(n), units };
    vec![
        c("Comprimento", vec![u("Metros", "m", 1.0), u("Quilômetros", "km", 1000.0), u("Centímetros", "cm", 0.01), u("Milímetros", "mm", 0.001), u("Milhas", "mi", 1609.344), u("Jardas", "yd", 0.9144), u("Pés", "ft", 0.3048), u("Polegadas", "in", 0.0254), u("Milhas Náuticas", "nmi", 1852.0)]),
        c("Massa", vec![u("Quilogramas", "kg", 1.0), u("Gramas", "g", 0.001), u("Miligramas", "mg", 1e-6), u("Toneladas", "t", 1000.0), u("Libras", "lb", 0.45359237), u("Onças", "oz", 0.028349523125), u("Stones", "st", 6.35029318)]),
        c("Temperatura", vec![u("Celsius", "°C", 0.0), u("Fahrenheit", "°F", 0.0), u("Kelvin", "K", 0.0)]),
        c("Volume", vec![u("Litros", "L", 1.0), u("Mililitros", "mL", 0.001), u("Metros Cúbicos", "m³", 1000.0), u("Galões (EUA)", "gal", 3.785411784), u("Quartos (EUA)", "qt", 0.946352946), ut("Xícaras (EUA)", "xíc.", 0.2365882365), u("Onças Fluidas (EUA)", "fl oz", 0.0295735295625), ut("Colheres de Sopa", "c. sopa", 0.01478676478125)]),
        c("Área", vec![u("Metros Quadrados", "m²", 1.0), u("Quilômetros Quadrados", "km²", 1e6), u("Hectares", "ha", 1e4), u("Acres", "ac", 4046.8564224), u("Pés Quadrados", "ft²", 0.09290304), u("Centímetros Quadrados", "cm²", 1e-4)]),
        c("Velocidade", vec![u("Quilômetros por Hora", "km/h", 1.0 / 3.6), u("Metros por Segundo", "m/s", 1.0), u("Milhas por Hora", "mph", 0.44704), u("Nós", "kn", 1852.0 / 3600.0)]),
        c("Tempo", vec![u("Segundos", "s", 1.0), u("Minutos", "min", 60.0), u("Horas", "h", 3600.0), u("Dias", "d", 86400.0), ut("Semanas", "sem", 604800.0), ut("Anos", "anos", 31557600.0)]),
        c("Dados", vec![u("Bytes", "B", 1.0), u("Bits", "bit", 0.125), u("Kilobytes", "KB", 1e3), u("Megabytes", "MB", 1e6), u("Gigabytes", "GB", 1e9), u("Terabytes", "TB", 1e12), u("Kibibytes", "KiB", 1024.0), u("Mebibytes", "MiB", 1048576.0), u("Gibibytes", "GiB", 1073741824.0)]),
        c("Ângulo", vec![u("Graus", "°", 1.0), u("Radianos", "rad", 180.0 / PI), u("Grados", "grad", 0.9)]),
    ]
}

#[derive(Clone)]
struct HistItem {
    toks: Vec<Tok>,
    val: f64,
}
#[derive(Clone, Default)]
struct Run {
    t: String,
    lvl: i32,
    ghost: bool,
    serif: bool,
}
struct Pal {
    bg: Cor,
    key: [Cor; 4],
    text: Cor,
    op_text: Cor,
    sub: Cor,
    round: Cor,
    icon: Cor,
    sidebar: Cor,
    line: Cor,
    hover: Cor,
    disabled: Cor,
}

struct App {
    hwnd: HWND,
    rt: Option<ID2D1HwndRenderTarget>,
    round: Option<ID2D1StrokeStyle>,
    dark: bool,
    active: bool,
    hover_lights: bool,
    shown: bool,
    user_sizing: bool,
    family: String,
    text_family: String,
    mode: Mode,
    rpn: bool,
    convert: bool,
    sidebar: bool,
    rad: bool,
    second: bool,
    sci_w: f32,
    sci_h: f32,
    dec: char,
    grp: char,
    keys: Vec<KeyDef>,
    rng: u64,
    hover: Target,
    down: Target,
    glow: HashMap<i32, f32>,
    held: HashMap<i32, bool>,
    last_anim: u32,
    hist_scroll: f32,
    toks: Vec<Tok>,
    done: bool,
    done_expr: Vec<Tok>,
    ans: f64,
    rep_op: String,
    rep_val: f64,
    rep_ok: bool,
    mem: f64,
    stack: Vec<f64>,
    entry: String,
    entering: bool,
    p_acc: u64,
    p_entry: u64,
    p_op: i32,
    p_entering: bool,
    p_err: bool,
    base: u32,
    cats: Vec<Cat>,
    conv_cat: usize,
    conv_from: usize,
    conv_to: usize,
    hist: Vec<HistItem>,
    force_theme: String,
    fonts: HashMap<(i32, i32, bool, i32), IDWriteTextFormat>,
    baselines: HashMap<(i32, i32, bool, i32), f32>,
    foto_size: Option<(f32, f32)>,
}
static A: Global<Option<App>> = Global::new(None);
fn a() -> &'static mut App {
    A.get().as_mut().unwrap()
}
fn leo() -> bool {
    semaforo::leopard()
}

// ---------------------------------------------------------------------------
// arquivos
fn read_kv(nome: &str) -> HashMap<String, String> {
    app2d::read_lines(&data_path(nome))
        .into_iter()
        .filter_map(|l| l.split_once('=').map(|(k, v)| (k.to_string(), v.to_string())))
        .collect()
}
fn read_dark() -> bool {
    if !a().force_theme.is_empty() {
        return a().force_theme == "escuro";
    }
    match read_kv("ajustes.txt").get("tema").map(String::as_str) {
        Some("claro") => false,
        Some("escuro") => true,
        _ => {
            // segue o Windows (AppsUseLightTheme), como o app2d
            app2d::dark()
        }
    }
}
fn serialize_toks(t: &[Tok]) -> String {
    let mut o = String::new();
    for k in t {
        let ki = TKS.iter().position(|x| *x == k.k).unwrap_or(0);
        o += &format!("{}\u{1F}{}\u{1F}{:e}\u{1F}{}\u{1E}", ki, if k.hidden { 1 } else { 0 }, k.v, k.s);
    }
    o
}
fn parse_toks(s: &str) -> Vec<Tok> {
    s.split('\u{1E}')
        .filter(|p| !p.is_empty())
        .filter_map(|part| {
            let f: Vec<&str> = part.splitn(4, '\u{1F}').collect();
            if f.len() < 4 {
                return None;
            }
            Some(Tok { k: *TKS.get(f[0].parse::<usize>().ok()?)?, hidden: f[1] == "1", v: f[2].parse().unwrap_or(0.0), s: f[3].to_string() })
        })
        .collect()
}
fn save_history() {
    if app2d::modo_foto() {
        return;
    }
    let linhas: Vec<String> = a().hist.iter().map(|h| format!("{:e}\t{}", h.val, serialize_toks(&h.toks))).collect();
    app2d::write_lines(&data_path("calculadora-historico.txt"), &linhas);
}
fn load_history() {
    for l in app2d::read_lines(&data_path("calculadora-historico.txt")) {
        if let Some((v, t)) = l.split_once('\t') {
            a().hist.push(HistItem { toks: parse_toks(t), val: v.parse().unwrap_or(f64::NAN) });
        }
    }
}

// ---------------------------------------------------------------------------
// números
fn group(d: &str) -> String {
    let n = d.chars().count();
    let mut o = String::new();
    for (i, c) in d.chars().enumerate() {
        o.push(c);
        let left = n - 1 - i;
        if left > 0 && left % 3 == 0 {
            o.push(a().grp);
        }
    }
    o
}
fn format_typed(s: &str) -> String {
    let (sign, body) = match s.strip_prefix('-') {
        Some(b) => ("−", b),
        None => ("", s),
    };
    let (mant, ex) = match body.find('e') {
        Some(e) => (&body[..e], Some(&body[e + 1..])),
        None => (body, None),
    };
    let (ip, fp) = match mant.find('.') {
        Some(d) => (&mant[..d], Some(&mant[d + 1..])),
        None => (mant, None),
    };
    let mut out = format!("{sign}{}", group(if ip.is_empty() { "0" } else { ip }));
    if let Some(fp) = fp {
        out.push(a().dec);
        out += fp;
    }
    if let Some(ex) = ex {
        out.push('e');
        out += &ex.replace('-', "−");
    }
    out
}
fn format_num_g(v: f64, sig: i32, grp: bool) -> String {
    if !v.is_finite() {
        return tr("Erro");
    }
    if v == 0.0 {
        return "0".into();
    }
    let av = v.abs();
    let ex = av.log10().floor() as i32;
    let sign = if v < 0.0 { "−" } else { "" };
    let localize = |s: &str| {
        let (ip, fp) = match s.find('.') {
            Some(d) => (&s[..d], s[d + 1..].trim_end_matches('0')),
            None => (s, ""),
        };
        let mut o = if grp { group(ip) } else { ip.to_string() };
        if !fp.is_empty() {
            o.push(a().dec);
            o += fp;
        }
        o
    };
    if ex < sig && ex >= -8 {
        let dec = (sig - 1 - ex).clamp(0, 17) as usize;
        let s = localize(&format!("{av:.dec$}"));
        if s != "0" {
            return format!("{sign}{s}");
        }
    }
    let p = (sig - 5).max(1) as usize;
    let s = format!("{av:.p$e}");
    let (m, e) = s.split_once('e').unwrap_or((&s, "0"));
    let exp: i32 = e.parse().unwrap_or(0);
    format!("{sign}{}e{}{}", localize(m), if exp < 0 { "−" } else { "" }, exp.abs())
}
fn format_num(v: f64, sig: i32) -> String {
    format_num_g(v, sig, true)
}
fn plain_num(v: f64) -> String {
    format_num_g(v, 15, false).replace('−', "-")
}
fn parse_f(s: &str) -> f64 {
    let s = s.trim_end_matches(['e', '-', '.']);
    s.parse().unwrap_or(0.0)
}

// gama de Lanczos (o Rust estável não tem tgamma)
fn gamma(x: f64) -> f64 {
    if x < 0.5 {
        return PI / ((PI * x).sin() * gamma(1.0 - x));
    }
    if x == x.floor() && x <= 171.0 {
        return (1..x as u64).fold(1.0, |p, i| p * i as f64);
    }
    const G: [f64; 9] = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7];
    let x = x - 1.0;
    let mut s = G[0];
    for (i, g) in G.iter().enumerate().skip(1) {
        s += g / (x + i as f64);
    }
    let t = x + 7.5;
    (2.0 * PI).sqrt() * t.powf(x + 0.5) * (-t).exp() * s
}
fn func(f: &str, x: f64) -> f64 {
    let rad = a().rad;
    let to_rad = if rad { 1.0 } else { PI / 180.0 };
    let from_rad = if rad { 1.0 } else { 180.0 / PI };
    let mut r = match f {
        "sin" => (x * to_rad).sin(),
        "cos" => (x * to_rad).cos(),
        "tan" => {
            if !rad && (x.abs() - 90.0) % 180.0 == 0.0 {
                f64::NAN
            } else {
                (x * to_rad).tan()
            }
        }
        "asin" => x.asin() * from_rad,
        "acos" => x.acos() * from_rad,
        "atan" => x.atan() * from_rad,
        "sinh" => x.sinh(),
        "cosh" => x.cosh(),
        "tanh" => x.tanh(),
        "asinh" => x.asinh(),
        "acosh" => x.acosh(),
        "atanh" => x.atanh(),
        "ln" if x > 0.0 => x.ln(),
        "log10" if x > 0.0 => x.log10(),
        "log2" if x > 0.0 => x.log2(),
        "sqrt" if x >= 0.0 => x.sqrt(),
        "cbrt" => x.cbrt(),
        "exp" => x.exp(),
        "exp10" => 10f64.powf(x),
        "exp2" => 2f64.powf(x),
        "!" => {
            if x < 0.0 && x == x.floor() {
                f64::NAN
            } else {
                gamma(x + 1.0)
            }
        }
        "²" => x * x,
        "³" => x * x * x,
        "⁻¹" => 1.0 / x,
        "%" => x / 100.0,
        _ => f64::NAN,
    };
    if r.is_finite() && r.abs() < 1e-15 {
        r = 0.0;
    }
    r
}
fn yroot(x: f64, y: f64) -> f64 {
    if x < 0.0 && y.abs() % 2.0 == 1.0 {
        -(-x).powf(1.0 / y)
    } else {
        x.powf(1.0 / y)
    }
}
fn bin(op: &str, x: f64, y: f64) -> f64 {
    match op {
        "+" => x + y,
        "−" => x - y,
        "×" => x * y,
        "÷" => {
            if y == 0.0 {
                f64::NAN
            } else {
                x / y
            }
        }
        "^" => x.powf(y),
        "√" => yroot(x, y),
        "log" => x.ln() / y.ln(),
        _ => f64::NAN,
    }
}

// avaliação com precedência: + − < × ÷ (e multiplicação implícita) < sinal < potência < pós-fixos
struct Parser<'a> {
    t: &'a [Tok],
    i: usize,
    err: bool,
}
#[derive(Clone, Copy)]
struct V {
    v: f64,
    pct: bool,
}
impl<'a> Parser<'a> {
    fn at(&self, k: TK) -> bool {
        self.i < self.t.len() && self.t[self.i].k == k
    }
    fn at_op(&self, x: &str, y: &str) -> bool {
        self.at(TK::Op) && (self.t[self.i].s == x || self.t[self.i].s == y)
    }
    fn starts_primary(&self) -> bool {
        self.i < self.t.len() && matches!(self.t[self.i].k, TK::Num | TK::Val | TK::Const | TK::LP | TK::Func | TK::Neg)
    }
    fn expr(&mut self) -> V {
        let mut x = self.term();
        while self.at_op("+", "−") {
            let plus = self.t[self.i].s == "+";
            self.i += 1;
            let y = self.term();
            let yv = if y.pct { x.v * y.v } else { y.v };
            x = V { v: if plus { x.v + yv } else { x.v - yv }, pct: false };
        }
        x
    }
    fn term(&mut self) -> V {
        let mut x = self.unary();
        loop {
            if self.at_op("×", "÷") {
                let mul = self.t[self.i].s == "×";
                self.i += 1;
                let y = self.unary();
                x = V { v: if mul { x.v * y.v } else if y.v == 0.0 { f64::NAN } else { x.v / y.v }, pct: false };
            } else if self.starts_primary() {
                let y = self.unary();
                x = V { v: x.v * y.v, pct: false };
            } else {
                break;
            }
        }
        x
    }
    fn unary(&mut self) -> V {
        if self.at(TK::Neg) {
            self.i += 1;
            let x = self.unary();
            return V { v: -x.v, pct: x.pct };
        }
        self.power()
    }
    fn power(&mut self) -> V {
        let mut x = self.postfix();
        if self.at(TK::Pow) || self.at(TK::YRoot) || self.at(TK::LogY) {
            let k = self.t[self.i].k;
            self.i += 1;
            let y = self.unary();
            x = V {
                v: match k {
                    TK::Pow => x.v.powf(y.v),
                    TK::YRoot => yroot(x.v, y.v),
                    _ => x.v.ln() / y.v.ln(),
                },
                pct: false,
            };
        }
        x
    }
    fn postfix(&mut self) -> V {
        let mut x = self.primary();
        while self.at(TK::Post) {
            let s = self.t[self.i].s.clone();
            self.i += 1;
            x.v = func(&s, x.v);
            x.pct = s == "%";
        }
        x
    }
    fn primary(&mut self) -> V {
        if self.i >= self.t.len() {
            self.err = true;
            return V { v: 0.0, pct: false };
        }
        let k = self.t[self.i].clone();
        self.i += 1;
        match k.k {
            TK::Num => V { v: parse_f(&k.s), pct: false },
            TK::Val => V { v: k.v, pct: false },
            TK::Const => V { v: if k.s == "π" { PI } else { E }, pct: false },
            TK::LP => {
                let x = self.expr();
                if self.at(TK::RP) {
                    self.i += 1;
                }
                V { v: x.v, pct: false }
            }
            TK::Func => {
                let x = self.primary();
                V { v: func(&k.s, x.v), pct: false }
            }
            _ => {
                self.err = true;
                V { v: 0.0, pct: false }
            }
        }
    }
}
fn eval(mut t: Vec<Tok>) -> Option<f64> {
    loop {
        let Some(b) = t.last() else { return None };
        if matches!(b.k, TK::Op | TK::Neg | TK::Pow | TK::YRoot | TK::LogY | TK::Func | TK::LP) || (b.k == TK::Num && (b.s == "-" || b.s.is_empty())) {
            t.pop();
            continue;
        }
        break;
    }
    let mut p = Parser { t: &t, i: 0, err: false };
    let v = p.expr();
    while p.i < t.len() && t[p.i].k == TK::RP {
        p.i += 1;
    }
    (!p.err && p.i >= t.len()).then_some(v.v)
}
fn has_operation(t: &[Tok]) -> bool {
    t.len() >= 2 && t.iter().any(|k| !matches!(k.k, TK::Num | TK::Val | TK::Neg))
}
fn current_value() -> f64 {
    let a = a();
    if a.mode == Mode::Prog {
        return (if a.p_entering { a.p_entry } else { a.p_acc }) as i64 as f64;
    }
    if a.rpn {
        return if a.entering { parse_f(&a.entry) } else { a.stack.last().copied().unwrap_or(0.0) };
    }
    if a.done {
        return a.ans;
    }
    if a.toks.is_empty() {
        0.0
    } else {
        eval(a.toks.clone()).unwrap_or(0.0)
    }
}

// ---------------------------------------------------------------------------
// texto com sobrescritos e subscritos
fn font(size: f32, wt: DWRITE_FONT_WEIGHT, serif: bool, fam: i32) -> IDWriteTextFormat {
    let key = ((size * 20.0).round() as i32, wt.0, serif, fam);
    if let Some(f) = a().fonts.get(&key) {
        return f.clone();
    }
    let family = if serif {
        "Times New Roman".to_string()
    } else if fam != 0 {
        a().text_family.clone()
    } else {
        a().family.clone()
    };
    let tf = cjk::format(dw(), &family, wt, if serif { DWRITE_FONT_STYLE_ITALIC } else { DWRITE_FONT_STYLE_NORMAL }, size, "pt-br").unwrap();
    unsafe {
        let _ = tf.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
        let _ = tf.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
        let _ = tf.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
        let mut b = size * 0.8;
        if let Ok(l) = dw().CreateTextLayout(&w("0"), &tf, 1000.0, 1000.0) {
            let mut lm = [DWRITE_LINE_METRICS::default()];
            let mut n = 0u32;
            if l.GetLineMetrics(Some(&mut lm), &mut n).is_ok() && n > 0 {
                b = lm[0].baseline;
            }
        }
        a().baselines.insert(key, b);
    }
    a().fonts.insert(key, tf.clone());
    tf
}
fn baseline_of(size: f32, w: DWRITE_FONT_WEIGHT, serif: bool, fam: i32) -> f32 {
    a().baselines.get(&((size * 20.0).round() as i32, w.0, serif, fam)).copied().unwrap_or(size * 0.8)
}
fn tw(tf: &IDWriteTextFormat, s: &str) -> f32 {
    if s.is_empty() {
        return 0.0;
    }
    unsafe {
        let Ok(l) = dw().CreateTextLayout(&w(s), tf, 8000.0, 1000.0) else { return 0.0 };
        let mut m = DWRITE_TEXT_METRICS::default();
        let _ = l.GetMetrics(&mut m);
        m.widthIncludingTrailingWhitespace
    }
}
/// texto com a linha de base em `baseline`
fn text_at(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, s: &str, size: f32, wt: DWRITE_FONT_WEIGHT, serif: bool, fam: i32, x: f32, baseline: f32, c: Cor) {
    if s.is_empty() {
        return;
    }
    let tf = font(size, wt, serif, fam);
    let top = baseline - baseline_of(size, wt, serif, fam);
    unsafe {
        br.SetColor(&c);
        rt.DrawText(&w(s), &tf, &rf(x, top, x + 8000.0, top + size * 2.0), br, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
    }
}
fn run_size(size: f32, lvl: i32) -> f32 {
    if lvl == 0 {
        size
    } else if lvl.abs() == 1 {
        size * 0.62
    } else {
        size * 0.5
    }
}
fn run_dy(size: f32, lvl: i32) -> f32 {
    if lvl > 0 {
        -size * (0.38 + 0.2 * (lvl - 1) as f32)
    } else if lvl < 0 {
        size * 0.17
    } else {
        0.0
    }
}
fn runs_width(rs: &[Run], size: f32, wt: DWRITE_FONT_WEIGHT) -> f32 {
    rs.iter().map(|r| tw(&font(run_size(size, r.lvl), wt, r.serif, 0), &r.t)).sum()
}
#[allow(clippy::too_many_arguments)]
fn draw_runs(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, rs: &[Run], size: f32, wt: DWRITE_FONT_WEIGHT, mut x: f32, baseline: f32, c: Cor, ghost: Cor) {
    for r in rs {
        let s = run_size(size, r.lvl);
        text_at(rt, br, &r.t, s, wt, r.serif, 0, x, baseline + run_dy(size, r.lvl), if r.ghost { ghost } else { c });
        x += tw(&font(s, wt, r.serif, 0), &r.t);
    }
}
#[allow(clippy::too_many_arguments)]
fn fit_runs(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, rs: &[Run], mut size: f32, min_size: f32, wt: DWRITE_FONT_WEIGHT, left: f32, right: f32, baseline: f32, c: Cor, ghost: Cor) {
    let avail = right - left;
    let mut width = runs_width(rs, size, wt);
    if width > avail && width > 0.0 {
        size = min_size.max(size * avail / width);
        width = runs_width(rs, size, wt);
    }
    let x = right - width;
    let clip = x < left;
    unsafe {
        if clip {
            rt.PushAxisAlignedClip(&rf(left, baseline - size * 1.6, right, baseline + size * 0.6), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
        }
        draw_runs(rt, br, rs, size, wt, x, baseline, c, ghost);
        if clip {
            rt.PopAxisAlignedClip();
        }
    }
}
/// rótulo das teclas: ^{sobrescrito}, _{subscrito}, ~{e itálico}
fn markup(m: &str) -> Vec<Run> {
    let c: Vec<char> = m.chars().collect();
    let mut rs = Vec::new();
    let mut cur = String::new();
    let mut i = 0;
    while i < c.len() {
        if matches!(c[i], '^' | '_' | '~') && i + 1 < c.len() && c[i + 1] == '{' {
            let Some(end) = c[i + 2..].iter().position(|&x| x == '}').map(|p| p + i + 2) else { break };
            if !cur.is_empty() {
                rs.push(Run { t: std::mem::take(&mut cur), ..Default::default() });
            }
            let mut r = Run { t: c[i + 2..end].iter().collect(), ..Default::default() };
            match c[i] {
                '^' => r.lvl = 1,
                '_' => r.lvl = -1,
                _ => r.serif = true,
            }
            rs.push(r);
            i = end + 1;
            continue;
        }
        cur.push(c[i]);
        i += 1;
    }
    if !cur.is_empty() {
        rs.push(Run { t: cur, ..Default::default() });
    }
    rs
}
fn operand_end(t: &[Tok], j: usize) -> usize {
    if j >= t.len() {
        return j;
    }
    match t[j].k {
        TK::LP => {
            let mut d = 0;
            for (k, x) in t.iter().enumerate().skip(j) {
                if x.k == TK::LP {
                    d += 1;
                } else if x.k == TK::RP {
                    d -= 1;
                    if d == 0 {
                        return k + 1;
                    }
                }
            }
            t.len()
        }
        TK::Func | TK::Neg => operand_end(t, j + 1),
        _ => j + 1,
    }
}
fn render_seq(t: &[Tok], from: usize, to: usize, lvl: i32, rs: &mut Vec<Run>, open: &mut Vec<i32>) {
    let emit = |rs: &mut Vec<Run>, s: &str, l: i32| {
        if let Some(b) = rs.last_mut() {
            if b.lvl == l && !b.serif && !b.ghost {
                b.t += s;
                return;
            }
        }
        rs.push(Run { t: s.into(), lvl: l, ..Default::default() });
    };
    let mut i = from;
    while i < to {
        let k = &t[i];
        match k.k {
            TK::Num => emit(rs, &format_typed(&k.s), lvl),
            TK::Val => emit(rs, &format_num(k.v, 12), lvl),
            TK::Const => {
                if k.s == "e" {
                    rs.push(Run { t: "e".into(), lvl, serif: true, ..Default::default() });
                } else {
                    emit(rs, &k.s, lvl);
                }
            }
            TK::Op => emit(rs, &k.s, lvl),
            TK::Neg => emit(rs, "−", lvl),
            TK::LP => {
                if !k.hidden {
                    emit(rs, "(", lvl);
                    open.push(lvl);
                } else {
                    open.push(-100);
                }
            }
            TK::RP => {
                open.pop();
                if !k.hidden {
                    emit(rs, ")", lvl);
                }
            }
            TK::Func => {
                let f = k.s.as_str();
                match f {
                    "sqrt" => emit(rs, "√", lvl),
                    "cbrt" => {
                        emit(rs, "³", (lvl + 1).min(2));
                        emit(rs, "√", lvl);
                    }
                    "log10" => {
                        emit(rs, "log", lvl);
                        emit(rs, "10", lvl - 1);
                    }
                    "log2" => {
                        emit(rs, "log", lvl);
                        emit(rs, "2", lvl - 1);
                    }
                    _ if f.len() > 1 && f.starts_with('a') => {
                        emit(rs, &f[1..], lvl);
                        emit(rs, "−1", lvl + 1);
                    }
                    _ => emit(rs, f, lvl),
                }
            }
            TK::Post => match k.s.as_str() {
                "²" => emit(rs, "2", lvl + 1),
                "³" => emit(rs, "3", lvl + 1),
                "⁻¹" => emit(rs, "−1", lvl + 1),
                s => emit(rs, s, lvl),
            },
            TK::Pow => {
                let j = i + 1;
                let mut e = operand_end(t, j).min(to);
                while e < to && t[e].k == TK::Post {
                    e += 1;
                }
                render_seq(t, j, e, (lvl + 1).min(3), rs, open);
                i = e;
                continue;
            }
            TK::YRoot => emit(rs, "ʸ√", lvl),
            TK::LogY => {
                emit(rs, "log", lvl);
                emit(rs, "y", lvl - 1);
            }
        }
        i += 1;
    }
}
fn render_toks(t: &[Tok]) -> Vec<Run> {
    let mut rs = Vec::new();
    let mut open = Vec::new();
    render_seq(t, 0, t.len(), 0, &mut rs, &mut open);
    for &l in open.iter().rev() {
        if l != -100 {
            rs.push(Run { t: ")".into(), lvl: l, ghost: true, ..Default::default() });
        }
    }
    rs
}
fn plain_of(rs: &[Run]) -> String {
    rs.iter().filter(|r| !r.ghost).map(|r| if r.lvl > 0 { format!("^{}", r.t) } else { r.t.clone() }).collect()
}

// ---------------------------------------------------------------------------
// geometria
fn scale() -> f32 {
    if a().foto_size.is_some() {
        return 2.0;
    }
    unsafe { GetDpiForWindow(a().hwnd) as f32 / 96.0 }
}
fn client() -> (f32, f32) {
    if let Some(s) = a().foto_size {
        return s;
    }
    let mut r = RECT::default();
    unsafe {
        let _ = GetClientRect(a().hwnd, &mut r);
    }
    let s = scale();
    (r.right as f32 / s, r.bottom as f32 / s)
}
fn side() -> f32 {
    if a().sidebar {
        SBW
    } else {
        0.0
    }
}
fn conv_on() -> bool {
    a().convert && a().mode != Mode::Prog
}
fn content_size() -> (f32, f32) {
    let conv = if conv_on() { CONV_H } else { 0.0 };
    match a().mode {
        Mode::Basic => (229.0, if leo() { 282.0 } else { 405.0 } + conv),
        Mode::Sci => (a().sci_w, a().sci_h + conv),
        Mode::Prog => (572.0, 442.0),
    }
}
fn keys_top() -> f32 {
    let conv = if conv_on() { CONV_H } else { 0.0 };
    if leo() && a().mode != Mode::Prog {
        return 96.0 + conv;
    }
    (match a().mode {
        Mode::Basic => 132.0,
        Mode::Sci => 113.0,
        Mode::Prog => 206.0,
    }) + conv
}
fn key_rect(k: &KeyDef) -> RectF {
    let (cw, ch) = client();
    let x0 = side();
    let wd = cw - x0;
    let top = keys_top();
    if a().mode == Mode::Basic {
        let d = 47.5;
        let cx = x0 + 34.5 + 53.5 * k.col as f32;
        let cy = top + d / 2.0 + 53.1 * k.row as f32;
        if leo() {
            let cy = top + 13.0 + 34.0 * k.row as f32;
            return rf(cx - d / 2.0 - 2.0, cy - 14.0, cx + d / 2.0 + 2.0, cy + 14.0);
        }
        return rf(cx - d / 2.0, cy - d / 2.0, cx + d / 2.0, cy + d / 2.0);
    }
    let cols = if a().mode == Mode::Sci { 10.0 } else { 8.0 };
    let (mx, gx, gy, bottom) = (13.0, 11.5, 5.0, 10.5);
    let kw = (wd - 2.0 * mx - gx * (cols - 1.0)) / cols;
    let kh = (ch - bottom - top - gy * 4.0) / 5.0;
    let x = x0 + mx + k.col as f32 * (kw + gx);
    let y = top + k.row as f32 * (kh + gy);
    rf(x, y, x + kw, y + kh)
}
fn light_center(k: i32) -> Ponto {
    if leo() {
        pt(14.5 + k as f32 * 21.0, 11.0)
    } else {
        pt(23.0 + k as f32 * 23.0, 25.0)
    }
}
fn side_btn_center() -> Ponto {
    if leo() {
        pt(client().0 - 34.0, 11.0)
    } else {
        pt(side() + if a().mode == Mode::Basic { 123.5 } else { 105.5 }, 26.0)
    }
}
fn mode_btn_center() -> Ponto {
    if leo() {
        pt(client().0 - 13.0, 11.0)
    } else {
        pt(client().0 - 26.5, 26.0)
    }
}
fn hist_rect(i: usize) -> RectF {
    let y = TB + 4.0 + i as f32 * HIST_H - a().hist_scroll;
    rf(8.0, y, SBW - 8.0, y + HIST_H - 4.0)
}
fn in_circle(c: Ponto, r: f32, p: Ponto) -> bool {
    let (dx, dy) = (p.x - c.x, p.y - c.y);
    dx * dx + dy * dy <= r * r
}
fn conv_mid() -> f32 {
    TB + (keys_top() - 4.0 - TB) / 2.0
}
fn conv_unit_rect(which: usize) -> RectF {
    let a = a();
    let u = &a.cats[a.conv_cat].units[if which == 0 { a.conv_from } else { a.conv_to }];
    let wd = tw(&font(14.0, DWRITE_FONT_WEIGHT_MEDIUM, false, 0), &u.sym) + 30.0;
    let right = client().0 - 13.0;
    let cy = if which == 0 { TB + (conv_mid() - TB) / 2.0 + 4.0 } else { conv_mid() + (keys_top() - 4.0 - conv_mid()) / 2.0 + 2.0 };
    rf(right - wd, cy - 12.0, right, cy + 12.0)
}
fn conv_swap_center() -> Ponto {
    pt(side() + 26.0, conv_mid() + 2.0)
}
fn bit_rect(b: i32) -> RectF {
    let (cw, _) = client();
    let (left, right) = (side() + 13.0, cw - 13.0);
    let row = if b >= 32 { 0 } else { 1 };
    let pos = 31 - (b % 32);
    let gw = (right - left) / 8.0;
    let cwid = (gw - 12.0) / 4.0;
    let x = left + (pos / 4) as f32 * gw + (pos % 4) as f32 * cwid;
    let y = 114.0 + row as f32 * 32.0;
    rf(x, y, x + cwid, y + 18.0)
}
fn base_rect(i: i32) -> RectF {
    let x = side() + 13.0 + i as f32 * 40.0;
    rf(x, 180.0, x + 36.0, 200.0)
}

fn build_keys() {
    let a = a();
    a.keys.clear();
    let mode = a.mode;
    let mut add = |id: i32, c: i32, r: i32, s: usize| a.keys.push(KeyDef { id, col: c, row: r, style: s });
    let keypad = |add: &mut dyn FnMut(i32, i32, i32, usize), c0: i32| {
        add(K_DEL, c0, 0, S_TOP);
        add(K_AC, c0 + 1, 0, S_TOP);
        add(K_PCT, c0 + 2, 0, S_TOP);
        add(K_DIV, c0 + 3, 0, S_OP);
        for (r, ds) in [(1, [7, 8, 9]), (2, [4, 5, 6]), (3, [1, 2, 3])] {
            for (i, d) in ds.iter().enumerate() {
                add(*d, c0 + i as i32, r, S_NUM);
            }
        }
        add(K_MUL, c0 + 3, 1, S_OP);
        add(K_SUB, c0 + 3, 2, S_OP);
        add(K_ADD, c0 + 3, 3, S_OP);
        if mode == Mode::Prog {
            add(K_BFLIP, c0, 4, S_NUM);
            add(0, c0 + 1, 4, S_NUM);
            add(K_WFLIP, c0 + 2, 4, S_NUM);
        } else {
            add(K_NEG, c0, 4, S_NUM);
            add(0, c0 + 1, 4, S_NUM);
            add(K_DOT, c0 + 2, 4, S_NUM);
        }
        add(K_EQ, c0 + 3, 4, S_OP);
    };
    match mode {
        Mode::Basic => keypad(&mut add, 0),
        Mode::Sci => {
            let fnk = [
                [K_LP, K_RP, K_MC, K_MP, K_MM, K_MR],
                [K_2ND, K_SQ, K_CUBE, K_POW, K_EXP, K_10X],
                [K_INV, K_SQRT, K_CBRT, K_YROOT, K_LN, K_LOG10],
                [K_FACT, K_SIN, K_COS, K_TAN, K_E, K_EE],
                [K_RAND, K_SINH, K_COSH, K_TANH, K_PI, K_RAD],
            ];
            for (r, row) in fnk.iter().enumerate() {
                for (c, id) in row.iter().enumerate() {
                    add(*id, c as i32, r as i32, S_FN);
                }
            }
            keypad(&mut add, 6);
        }
        Mode::Prog => {
            let fnk = [[K_AND, K_OR, 14, 15], [K_NOR, K_XOR, 12, 13], [K_SHL, K_SHR, 10, 11], [K_XSHLY, K_XSHRY, K_FF, K_00], [K_2S, K_1S, K_ROL, K_ROR]];
            for (r, row) in fnk.iter().enumerate() {
                for (c, id) in row.iter().enumerate() {
                    add(*id, c as i32, r as i32, if c >= 2 && *id <= 15 { S_NUM } else { S_FN });
                }
            }
            keypad(&mut add, 4);
        }
    }
}
fn clear_is_c() -> bool {
    let a = a();
    match a.mode {
        Mode::Prog => a.p_entering && a.p_entry != 0,
        _ if a.rpn => a.entering,
        _ => !a.done && !a.toks.is_empty(),
    }
}
fn key_label(id: i32) -> String {
    if (0..=15).contains(&id) {
        return char::from_digit(id as u32, 16).unwrap().to_ascii_uppercase().to_string();
    }
    let s = a().second;
    let r = match id {
        K_DOT => return a().dec.to_string(),
        K_AC => {
            if clear_is_c() {
                "C"
            } else {
                "AC"
            }
        }
        K_PCT => {
            if a().mode == Mode::Prog {
                "mod"
            } else {
                "%"
            }
        }
        K_NEG => "^{+}⁄_{−}",
        K_EQ => {
            if a().rpn && a().mode != Mode::Prog {
                "enter"
            } else {
                ""
            }
        }
        K_LP => {
            if a().rpn {
                "x⇄y"
            } else {
                "("
            }
        }
        K_RP => {
            if a().rpn {
                "R↓"
            } else {
                ")"
            }
        }
        K_MC => "mc",
        K_MP => "m+",
        K_MM => "m-",
        K_MR => "mr",
        K_2ND => "2^{nd}",
        K_SQ => "x^{2}",
        K_CUBE => "x^{3}",
        K_POW => "x^{y}",
        K_EXP => {
            if s {
                "y^{x}"
            } else {
                "~{e}^{x}"
            }
        }
        K_10X => {
            if s {
                "2^{x}"
            } else {
                "10^{x}"
            }
        }
        K_INV => "^{1}⁄_{x}",
        K_SQRT => "^{2}√x",
        K_CBRT => "^{3}√x",
        K_YROOT => "^{y}√x",
        K_LN => {
            if s {
                "log_{y}"
            } else {
                "ln"
            }
        }
        K_LOG10 => {
            if s {
                "log_{2}"
            } else {
                "log_{10}"
            }
        }
        K_FACT => "x!",
        K_SIN => if s { "sin^{−1}" } else { "sin" },
        K_COS => if s { "cos^{−1}" } else { "cos" },
        K_TAN => if s { "tan^{−1}" } else { "tan" },
        K_SINH => if s { "sinh^{−1}" } else { "sinh" },
        K_COSH => if s { "cosh^{−1}" } else { "cosh" },
        K_TANH => if s { "tanh^{−1}" } else { "tanh" },
        K_E => "~{e}",
        K_EE => "EE",
        K_RAND => "Rand",
        K_PI => "π",
        K_RAD => {
            if a().rad {
                "Deg"
            } else {
                "Rad"
            }
        }
        K_AND => "AND",
        K_OR => "OR",
        K_XOR => "XOR",
        K_NOR => "NOR",
        K_SHL => "<<",
        K_SHR => ">>",
        K_XSHLY => "X<<Y",
        K_XSHRY => "X>>Y",
        K_ROL => "RoL",
        K_ROR => "RoR",
        K_2S => "2's",
        K_1S => "1's",
        K_00 => "00",
        K_FF => "FF",
        K_BFLIP => "flip₈",
        K_WFLIP => "flip₁₆",
        _ => "",
    };
    r.to_string()
}
fn key_enabled(id: i32) -> bool {
    if a().mode != Mode::Prog {
        return true;
    }
    if (0..=15).contains(&id) {
        return (id as u32) < a().base;
    }
    if id == K_FF {
        return a().base == 16;
    }
    true
}

// ---------------------------------------------------------------------------
// ajustes
fn save_settings() {
    if app2d::modo_foto() || a().hwnd.0.is_null() {
        return;
    }
    let mut r = RECT::default();
    unsafe {
        let _ = GetWindowRect(a().hwnd, &mut r);
    }
    let sc = scale();
    let a = a();
    let x = r.left + (side() * sc).round() as i32;
    let modo = match a.mode {
        Mode::Basic => "basica",
        Mode::Sci => "cientifica",
        Mode::Prog => "programador",
    };
    let b = |v: bool| if v { 1 } else { 0 };
    let linhas = vec![
        format!("modo={modo}"),
        format!("x={x}"),
        format!("y={}", r.top),
        format!("larg_cientifica={}", a.sci_w as i32),
        format!("alt_cientifica={}", a.sci_h as i32),
        format!("rpn={}", b(a.rpn)),
        format!("converter={}", b(a.convert)),
        format!("historico={}", b(a.sidebar)),
        format!("radianos={}", b(a.rad)),
        format!("base={}", a.base),
        format!("conv_cat={}", a.conv_cat),
        format!("conv_de={}", a.conv_from),
        format!("conv_para={}", a.conv_to),
    ];
    app2d::write_lines(&data_path("calculadora.txt"), &linhas);
}
fn apply_layout(sidebar_delta: i32) {
    build_keys();
    if a().foto_size.is_some() {
        let cs = content_size();
        a().foto_size = Some((cs.0 + side(), cs.1));
        return;
    }
    let sc = scale();
    let cs = content_size();
    let (w_, h) = (((cs.0 + side()) * sc).round() as i32, (cs.1 * sc).round() as i32);
    unsafe {
        let mut r = RECT::default();
        let _ = GetWindowRect(a().hwnd, &mut r);
        let mut x = r.left - (sidebar_delta as f32 * sc).round() as i32;
        let mut y = r.top;
        let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
        let _ = GetMonitorInfoW(MonitorFromWindow(a().hwnd, MONITOR_DEFAULTTONEAREST), &mut mi);
        if x < mi.rcWork.left {
            x = mi.rcWork.left;
        }
        if x + w_ > mi.rcWork.right {
            x = mi.rcWork.left.max(mi.rcWork.right - w_);
        }
        if y + h > mi.rcWork.bottom {
            y = mi.rcWork.top.max(mi.rcWork.bottom - h);
        }
        let _ = SetWindowPos(a().hwnd, None, x, y, w_, h, SWP_NOZORDER | SWP_NOACTIVATE);
    }
    invalidate();
    save_settings();
}

// ---------------------------------------------------------------------------
// Básica / Científica: a expressão
fn inner_open_in(t: &[Tok]) -> i32 {
    let mut d = 0;
    for i in (0..t.len()).rev() {
        if t[i].k == TK::RP {
            d += 1;
        } else if t[i].k == TK::LP {
            if d == 0 {
                return i as i32;
            }
            d -= 1;
        }
    }
    -1
}
fn ends_operand() -> bool {
    match a().toks.last() {
        None => false,
        Some(b) if b.k == TK::Num => b.s != "-",
        Some(b) => matches!(b.k, TK::Val | TK::Const | TK::RP | TK::Post),
    }
}
fn from_ans() {
    let a = a();
    if !a.done {
        return;
    }
    a.toks.clear();
    if a.ans.is_finite() {
        a.toks.push(tk(TK::Val, "", a.ans, false));
    }
    a.done = false;
}
fn fresh() {
    let a = a();
    if a.done {
        a.toks.clear();
        a.done = false;
    }
}
fn close_hidden() {
    let i = inner_open_in(&a().toks);
    if i >= 0 && a().toks[i as usize].hidden && ends_operand() {
        a().toks.push(tk(TK::RP, ")", 0.0, true));
    }
}
fn operand_start(end: usize) -> usize {
    let t = &a().toks;
    let mut i = end;
    while i > 0 && t[i - 1].k == TK::Post {
        i -= 1;
    }
    if i == 0 {
        return 0;
    }
    i -= 1;
    if t[i].k == TK::RP {
        let mut d = 0;
        loop {
            if t[i].k == TK::RP {
                d += 1;
            } else if t[i].k == TK::LP {
                d -= 1;
                if d == 0 {
                    break;
                }
            }
            if i == 0 {
                break;
            }
            i -= 1;
        }
        if i > 0 && t[i - 1].k == TK::Func {
            i -= 1;
        }
    }
    if i > 0 && matches!(t[i - 1].k, TK::Pow | TK::YRoot | TK::LogY) {
        return operand_start(i - 1);
    }
    i
}
/// envolve o último operando: 30 sin → sin(30), 2 eˣ → e^(2)
fn wrap(mut before: Vec<Tok>, hidden: bool) {
    let s = operand_start(a().toks.len());
    before.push(tk(TK::LP, "(", 0.0, hidden));
    let t = &mut a().toks;
    for (k, x) in before.into_iter().enumerate() {
        t.insert(s + k, x);
    }
    t.push(tk(TK::RP, ")", 0.0, hidden));
}
fn func_name(id: i32) -> &'static str {
    let s = a().second;
    match id {
        K_SIN => if s { "asin" } else { "sin" },
        K_COS => if s { "acos" } else { "cos" },
        K_TAN => if s { "atan" } else { "tan" },
        K_SINH => if s { "asinh" } else { "sinh" },
        K_COSH => if s { "acosh" } else { "cosh" },
        K_TANH => if s { "atanh" } else { "tanh" },
        K_LN => "ln",
        K_LOG10 => if s { "log2" } else { "log10" },
        K_SQRT => "sqrt",
        K_CBRT => "cbrt",
        _ => "",
    }
}
fn add_history(expr: Vec<Tok>, val: f64) {
    a().hist.insert(0, HistItem { toks: expr, val });
    a().hist.truncate(200);
    a().hist_scroll = 0.0;
    save_history();
}
fn std_equals() {
    let a = a();
    if a.done {
        if !a.rep_ok || !a.ans.is_finite() {
            return;
        }
        let e = vec![tk(TK::Val, "", a.ans, false), tk(TK::Op, &a.rep_op, 0.0, false), tk(TK::Val, "", a.rep_val, false)];
        a.ans = bin(&a.rep_op.clone(), a.ans, a.rep_val);
        a.done_expr = e.clone();
        add_history(e, self::a().ans);
        return;
    }
    if a.toks.is_empty() {
        return;
    }
    let v = eval(a.toks.clone());
    a.rep_ok = false;
    let mut d = 0;
    for i in (0..a.toks.len()).rev() {
        match a.toks[i].k {
            TK::RP => d += 1,
            TK::LP => d -= 1,
            TK::Op if d == 0 && i > 0 => {
                if let Some(rv) = eval(a.toks[i + 1..].to_vec()) {
                    a.rep_ok = true;
                    a.rep_op = a.toks[i].s.clone();
                    a.rep_val = rv;
                }
                break;
            }
            _ => {}
        }
    }
    let mut e = a.toks.clone();
    while e.last().map(|b| matches!(b.k, TK::Op | TK::Neg)).unwrap_or(false) {
        e.pop();
    }
    loop {
        let i = inner_open_in(&e);
        if i < 0 {
            break;
        }
        let h = e[i as usize].hidden;
        e.push(tk(TK::RP, ")", 0.0, h));
    }
    a.done_expr = e.clone();
    a.ans = v.unwrap_or(f64::NAN);
    a.done = true;
    a.toks.clear();
    add_history(e, self::a().ans);
}
fn rand01() -> f64 {
    let r = &mut a().rng;
    *r ^= *r << 13;
    *r ^= *r >> 7;
    *r ^= *r << 17;
    (*r >> 11) as f64 / (1u64 << 53) as f64
}
fn std_press(id: i32) {
    if (0..=9).contains(&id) {
        fresh();
        let d = char::from_digit(id as u32, 10).unwrap();
        let t = &mut a().toks;
        if let Some(b) = t.last_mut().filter(|b| b.k == TK::Num) {
            if b.s.chars().filter(|c| c.is_ascii_digit()).count() >= 16 {
                return;
            }
            if b.s == "0" {
                b.s = d.to_string();
            } else if b.s == "-0" {
                b.s = format!("-{d}");
            } else {
                b.s.push(d);
            }
        } else {
            t.push(tk(TK::Num, &d.to_string(), 0.0, false));
        }
        return;
    }
    match id {
        K_DOT => {
            fresh();
            let t = &mut a().toks;
            if let Some(b) = t.last_mut().filter(|b| b.k == TK::Num) {
                if !b.s.contains('.') && !b.s.contains('e') {
                    b.s.push('.');
                }
            } else {
                t.push(tk(TK::Num, "0.", 0.0, false));
            }
        }
        K_EE => {
            if let Some(b) = a().toks.last_mut().filter(|b| b.k == TK::Num && !b.s.contains('e')) {
                b.s.push('e');
            }
        }
        K_ADD | K_SUB | K_MUL | K_DIV => {
            let op = match id {
                K_ADD => "+",
                K_SUB => "−",
                K_MUL => "×",
                _ => "÷",
            };
            from_ans();
            let t = &mut a().toks;
            if t.is_empty() {
                if id == K_SUB {
                    t.push(tk(TK::Neg, "", 0.0, false));
                    return;
                }
                t.push(tk(TK::Num, "0", 0.0, false));
            }
            let b = t.last_mut().unwrap();
            if b.k == TK::Num && b.s.ends_with('e') {
                if id == K_SUB {
                    b.s.push('-');
                }
                return;
            }
            if b.k == TK::Op {
                b.s = op.into();
                return;
            }
            if b.k == TK::Neg {
                if id != K_SUB {
                    t.pop();
                }
                return;
            }
            if matches!(b.k, TK::LP | TK::Pow | TK::YRoot | TK::LogY | TK::Func) {
                if id == K_SUB {
                    t.push(tk(TK::Neg, "", 0.0, false));
                }
                return;
            }
            close_hidden();
            a().toks.push(tk(TK::Op, op, 0.0, false));
        }
        K_EQ => std_equals(),
        K_AC => {
            if clear_is_c() {
                a().toks.clear();
                return;
            }
            let a = a();
            a.toks.clear();
            a.done = false;
            a.ans = 0.0;
            a.done_expr.clear();
            a.rep_ok = false;
        }
        K_DEL => {
            let a = a();
            if a.done {
                if !a.ans.is_finite() {
                    a.done = false;
                    a.toks.clear();
                    return;
                }
                let s = plain_num(a.ans).replace(a.dec, ".");
                if s.contains('e') {
                    return;
                }
                a.toks = vec![tk(TK::Num, &s, 0.0, false)];
                a.done = false;
            }
            let Some(b) = a.toks.last_mut() else { return };
            match b.k {
                TK::Num => {
                    b.s.pop();
                    if b.s.is_empty() || b.s == "-" {
                        a.toks.pop();
                    }
                }
                TK::LP => {
                    let hid = b.hidden;
                    a.toks.pop();
                    if a.toks.last().map(|x| x.k == TK::Func || (hid && x.k == TK::Pow)).unwrap_or(false) {
                        a.toks.pop();
                    }
                }
                _ => {
                    a.toks.pop();
                }
            }
        }
        K_PCT | K_SQ | K_CUBE | K_INV | K_FACT => {
            from_ans();
            if !ends_operand() {
                return;
            }
            let p = match id {
                K_PCT => "%",
                K_SQ => "²",
                K_CUBE => "³",
                K_INV => "⁻¹",
                _ => "!",
            };
            a().toks.push(tk(TK::Post, p, 0.0, false));
        }
        K_NEG => {
            from_ans();
            if a().toks.is_empty() {
                a().toks.push(tk(TK::Neg, "", 0.0, false));
                return;
            }
            let eo = ends_operand();
            let t = &mut a().toks;
            let b = t.last_mut().unwrap();
            if b.k == TK::Num && b.s.contains('e') {
                let e = b.s.find('e').unwrap();
                if b.s[e + 1..].starts_with('-') {
                    b.s.remove(e + 1);
                } else {
                    b.s.insert(e + 1, '-');
                }
                return;
            }
            if !eo {
                if b.k == TK::Neg {
                    t.pop();
                } else {
                    t.push(tk(TK::Neg, "", 0.0, false));
                }
                return;
            }
            if b.k == TK::Val {
                b.v = -b.v;
                return;
            }
            let s = operand_start(t.len());
            let t = &mut a().toks;
            if s > 0 && t[s - 1].k == TK::Neg {
                t.remove(s - 1);
            } else {
                t.insert(s, tk(TK::Neg, "", 0.0, false));
            }
        }
        K_LP => {
            fresh();
            a().toks.push(tk(TK::LP, "(", 0.0, false));
        }
        K_RP => {
            let i = inner_open_in(&a().toks);
            if i < 0 || !ends_operand() {
                return;
            }
            let h = a().toks[i as usize].hidden;
            a().toks.push(tk(TK::RP, ")", 0.0, h));
        }
        K_SIN | K_COS | K_TAN | K_SINH | K_COSH | K_TANH | K_LN | K_LOG10 | K_SQRT | K_CBRT => {
            from_ans();
            if id == K_LN && a().second {
                if ends_operand() {
                    a().toks.push(tk(TK::LogY, "", 0.0, false));
                }
                return;
            }
            let f = tk(TK::Func, func_name(id), 0.0, false);
            if ends_operand() {
                wrap(vec![f], false);
            } else {
                a().toks.push(f);
                a().toks.push(tk(TK::LP, "(", 0.0, false));
            }
        }
        K_POW => {
            from_ans();
            if ends_operand() {
                a().toks.push(tk(TK::Pow, "", 0.0, false));
                a().toks.push(tk(TK::LP, "(", 0.0, true));
            }
        }
        K_YROOT => {
            from_ans();
            if ends_operand() {
                a().toks.push(tk(TK::YRoot, "", 0.0, false));
            }
        }
        K_EXP | K_10X => {
            from_ans();
            if id == K_EXP && a().second {
                if ends_operand() {
                    a().toks.push(tk(TK::Pow, "", 0.0, false));
                    a().toks.push(tk(TK::LP, "(", 0.0, true));
                }
                return;
            }
            let base = if id == K_EXP { tk(TK::Const, "e", 0.0, false) } else { tk(TK::Val, "", if a().second { 2.0 } else { 10.0 }, false) };
            if ends_operand() {
                wrap(vec![base, tk(TK::Pow, "", 0.0, false)], true);
            } else {
                let t = &mut a().toks;
                t.push(base);
                t.push(tk(TK::Pow, "", 0.0, false));
                t.push(tk(TK::LP, "(", 0.0, true));
            }
        }
        K_PI => {
            fresh();
            a().toks.push(tk(TK::Const, "π", 0.0, false));
        }
        K_E => {
            fresh();
            a().toks.push(tk(TK::Const, "e", 0.0, false));
        }
        K_RAND => {
            fresh();
            let r = rand01();
            a().toks.push(tk(TK::Val, "", r, false));
        }
        K_MC => a().mem = 0.0,
        K_MP => a().mem += current_value(),
        K_MM => a().mem -= current_value(),
        K_MR => {
            fresh();
            let m = a().mem;
            a().toks.push(tk(TK::Val, "", m, false));
        }
        _ => {}
    }
}

// ---------------------------------------------------------------------------
// RPN
fn commit() {
    let a = a();
    if !a.entering {
        return;
    }
    a.stack.push(parse_f(&a.entry));
    a.entry.clear();
    a.entering = false;
}
fn rpn_press(id: i32) {
    if (0..=9).contains(&id) || id == K_DOT || id == K_EE {
        let a = a();
        if !a.entering {
            a.entering = true;
            a.entry.clear();
        }
        if id == K_DOT {
            if !a.entry.contains('.') && !a.entry.contains('e') {
                a.entry += if a.entry.is_empty() { "0." } else { "." };
            }
        } else if id == K_EE {
            if !a.entry.is_empty() && !a.entry.contains('e') {
                a.entry.push('e');
            }
        } else if a.entry.len() < 18 {
            if a.entry == "0" {
                a.entry.clear();
            }
            a.entry.push(char::from_digit(id as u32, 10).unwrap());
        }
        return;
    }
    let binf = |op: &str| {
        commit();
        let s = &mut a().stack;
        if s.len() < 2 {
            return;
        }
        let x = s.pop().unwrap();
        let y = s.pop().unwrap();
        s.push(bin(op, y, x));
    };
    let un = |f: &str| {
        commit();
        if let Some(t) = a().stack.last().copied() {
            *a().stack.last_mut().unwrap() = func(f, t);
        }
    };
    let push = |v: f64| {
        commit();
        a().stack.push(v);
    };
    match id {
        K_EQ => {
            if a().entering {
                commit();
            } else if let Some(&t) = a().stack.last() {
                a().stack.push(t);
            }
        }
        K_ADD => binf("+"),
        K_SUB => binf("−"),
        K_MUL => binf("×"),
        K_DIV => binf("÷"),
        K_POW => binf("^"),
        K_YROOT => binf("√"),
        K_SQ => un("²"),
        K_CUBE => un("³"),
        K_INV => un("⁻¹"),
        K_FACT => un("!"),
        K_EXP => {
            if a().second {
                binf("^")
            } else {
                un("exp")
            }
        }
        K_10X => un(if a().second { "exp2" } else { "exp10" }),
        K_LN => {
            if a().second {
                binf("log")
            } else {
                un("ln")
            }
        }
        K_SIN | K_COS | K_TAN | K_SINH | K_COSH | K_TANH | K_LOG10 | K_SQRT | K_CBRT => un(func_name(id)),
        K_PCT => {
            commit();
            let s = &mut a().stack;
            let n = s.len();
            if n >= 2 {
                s[n - 1] = s[n - 2] * s[n - 1] / 100.0;
            } else if n == 1 {
                s[0] /= 100.0;
            }
        }
        K_NEG => {
            let a = a();
            if a.entering {
                let at = a.entry.find('e').map(|e| e + 1).unwrap_or(0);
                if a.entry[at..].starts_with('-') {
                    a.entry.remove(at);
                } else {
                    a.entry.insert(at, '-');
                }
            } else if let Some(t) = a.stack.last_mut() {
                *t = -*t;
            }
        }
        K_DEL => {
            let a = a();
            if a.entering {
                a.entry.pop();
                if a.entry.is_empty() || a.entry == "-" {
                    a.entry.clear();
                    a.entering = false;
                }
            } else {
                a.stack.pop();
            }
        }
        K_AC => {
            let a = a();
            if a.entering {
                a.entry.clear();
                a.entering = false;
            } else {
                a.stack.clear();
            }
        }
        K_LP => {
            commit();
            let s = &mut a().stack;
            let n = s.len();
            if n >= 2 {
                s.swap(n - 1, n - 2);
            }
        }
        K_RP => {
            commit();
            let s = &mut a().stack;
            if s.len() >= 2 {
                let x = s.pop().unwrap();
                s.insert(0, x);
            }
        }
        K_PI => push(PI),
        K_E => push(E),
        K_RAND => push(rand01()),
        K_MC => a().mem = 0.0,
        K_MP => a().mem += current_value(),
        K_MM => a().mem -= current_value(),
        K_MR => push(a().mem),
        _ => {}
    }
}

// ---------------------------------------------------------------------------
// Programador (inteiros de 64 bits)
fn prog_cur() -> u64 {
    if a().p_entering {
        a().p_entry
    } else {
        a().p_acc
    }
}
fn prog_set(v: u64) {
    let a = a();
    if a.p_entering || a.p_op != 0 {
        a.p_entry = v;
        a.p_entering = true;
    } else {
        a.p_acc = v;
    }
}
fn prog_apply(x: u64, op: i32, y: u64) -> u64 {
    match op {
        K_ADD => x.wrapping_add(y),
        K_SUB => x.wrapping_sub(y),
        K_MUL => x.wrapping_mul(y),
        K_DIV | K_PCT => {
            if y == 0 {
                a().p_err = true;
                return 0;
            }
            if op == K_DIV {
                (x as i64).wrapping_div(y as i64) as u64
            } else {
                (x as i64).wrapping_rem(y as i64) as u64
            }
        }
        K_AND => x & y,
        K_OR => x | y,
        K_XOR => x ^ y,
        K_NOR => !(x | y),
        K_XSHLY => x << (y & 63),
        K_XSHRY => x >> (y & 63),
        _ => y,
    }
}
fn prog_fmt(v: u64, base: u32) -> String {
    if base == 10 {
        let s = v as i64;
        let d = if s < 0 { (s as i128).unsigned_abs().to_string() } else { v.to_string() };
        return format!("{}{}", if s < 0 { "−" } else { "" }, group(&d));
    }
    if v == 0 {
        return "0".into();
    }
    let mut o = Vec::new();
    let mut v = v;
    while v > 0 {
        o.push(char::from_digit((v % base as u64) as u32, base).unwrap().to_ascii_uppercase());
        v /= base as u64;
    }
    o.iter().rev().collect()
}
fn prog_op_sym(op: i32) -> &'static str {
    match op {
        K_ADD => "+",
        K_SUB => "−",
        K_MUL => "×",
        K_DIV => "÷",
        K_PCT => "mod",
        K_AND => "AND",
        K_OR => "OR",
        K_XOR => "XOR",
        K_NOR => "NOR",
        K_XSHLY => "<<",
        K_XSHRY => ">>",
        _ => "",
    }
}
fn prog_press(id: i32) {
    if (0..=15).contains(&id) {
        let a = a();
        if id as u32 >= a.base {
            return;
        }
        if !a.p_entering {
            a.p_entry = 0;
            a.p_entering = true;
            a.p_err = false;
        }
        a.p_entry = a.p_entry.wrapping_mul(a.base as u64).wrapping_add(id as u64);
        return;
    }
    match id {
        K_00 => {
            prog_press(0);
            prog_press(0);
        }
        K_FF => {
            if a().base == 16 {
                prog_press(15);
                prog_press(15);
            }
        }
        K_ADD | K_SUB | K_MUL | K_DIV | K_PCT | K_AND | K_OR | K_XOR | K_NOR | K_XSHLY | K_XSHRY => {
            let (op, ent, acc, e) = (a().p_op, a().p_entering, a().p_acc, a().p_entry);
            if op != 0 && ent {
                a().p_acc = prog_apply(acc, op, e);
            } else if op == 0 && ent {
                a().p_acc = e;
            }
            a().p_op = id;
            a().p_entering = false;
        }
        K_EQ => {
            let (op, ent, acc, e) = (a().p_op, a().p_entering, a().p_acc, a().p_entry);
            if op != 0 {
                a().p_acc = prog_apply(acc, op, if ent { e } else { acc });
                a().p_op = 0;
            } else if ent {
                a().p_acc = e;
            }
            a().p_entering = false;
        }
        K_AC => {
            if clear_is_c() {
                a().p_entry = 0;
                return;
            }
            let a = a();
            a.p_acc = 0;
            a.p_entry = 0;
            a.p_op = 0;
            a.p_entering = false;
            a.p_err = false;
        }
        K_DEL => {
            if a().p_entering {
                a().p_entry /= a().base as u64;
            }
        }
        K_SHL => prog_set(prog_cur() << 1),
        K_SHR => prog_set(prog_cur() >> 1),
        K_ROL => prog_set(prog_cur().rotate_left(1)),
        K_ROR => prog_set(prog_cur().rotate_right(1)),
        K_2S => prog_set(prog_cur().wrapping_neg()),
        K_1S => prog_set(!prog_cur()),
        K_BFLIP => prog_set(prog_cur().swap_bytes()),
        K_WFLIP => {
            let v = prog_cur();
            prog_set((v >> 48) | ((v >> 16) & 0xFFFF0000) | ((v << 16) & 0xFFFF00000000) | (v << 48));
        }
        _ => {}
    }
}
fn press(id: i32) {
    if id == K_2ND {
        a().second = !a().second;
        return;
    }
    if id == K_RAD {
        a().rad = !a().rad;
        save_settings();
        return;
    }
    if a().mode == Mode::Prog {
        prog_press(id);
    } else if a().rpn {
        rpn_press(id);
    } else {
        std_press(id);
    }
}

// ---------------------------------------------------------------------------
// cores
fn mix(x: Cor, y: Cor, t: f32) -> Cor {
    col(x.r + (y.r - x.r) * t, x.g + (y.g - x.g) * t, x.b + (y.b - x.b) * t, x.a + (y.a - x.a) * t)
}
fn colors() -> Pal {
    let c = |r, g, b| rgb(r, g, b, 1.0);
    if leo() {
        let w = c(250, 250, 250);
        return Pal { bg: c(196, 196, 196), key: [w, w, w, w], text: c(0, 0, 0), op_text: c(0, 0, 0), sub: rgb(0, 0, 0, 0.55), round: c(240, 240, 240), icon: c(40, 40, 40), sidebar: c(214, 221, 229), line: rgb(0, 0, 0, 0.15), hover: rgb(0, 0, 0, 0.06), disabled: rgb(0, 0, 0, 0.30) };
    }
    if a().dark {
        return Pal {
            bg: c(36, 41, 45),
            key: [c(48, 52, 55), c(70, 74, 76), c(113, 117, 119), c(255, 139, 0)],
            text: c(236, 237, 237),
            op_text: c(255, 255, 255),
            sub: rgb(255, 255, 255, 0.52),
            round: c(25, 29, 32),
            icon: c(233, 234, 234),
            sidebar: c(29, 33, 36),
            line: rgb(255, 255, 255, 0.09),
            hover: rgb(255, 255, 255, 0.07),
            disabled: rgb(255, 255, 255, 0.28),
        };
    }
    Pal {
        bg: c(232, 233, 235),
        key: [c(246, 246, 247), c(255, 255, 255), c(206, 208, 211), c(255, 139, 0)],
        text: c(29, 29, 31),
        op_text: c(255, 255, 255),
        sub: rgb(0, 0, 0, 0.45),
        round: c(250, 250, 251),
        icon: c(60, 60, 64),
        sidebar: c(222, 223, 226),
        line: rgb(0, 0, 0, 0.09),
        hover: rgb(0, 0, 0, 0.05),
        disabled: rgb(0, 0, 0, 0.25),
    }
}

// ---------------------------------------------------------------------------
// desenho
fn ln(rt: &ID2D1RenderTarget, b: &ID2D1SolidColorBrush, x1: f32, y1: f32, x2: f32, y2: f32, wd: f32) {
    unsafe { rt.DrawLine(pt(x1, y1), pt(x2, y2), b, wd, a().round.as_ref()) }
}
unsafe fn draw_lights(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush) {
    let fill_c = semaforo::pick([col(1.0, 0.373, 0.345, 1.0), col(0.996, 0.737, 0.180, 1.0), col(0.157, 0.784, 0.251, 1.0)], semaforo::Kind::Fill);
    let ring_c = semaforo::pick([col(0.886, 0.275, 0.247, 1.0), col(0.882, 0.631, 0.086, 1.0), col(0.071, 0.675, 0.157, 1.0)], semaforo::Kind::Ring);
    let glyph_c = semaforo::pick([col(0.302, 0.0, 0.0, 1.0), col(0.6, 0.341, 0.0, 1.0), col(0.0, 0.396, 0.0, 1.0)], semaforo::Kind::Glyph);
    let lit = a().active || a().hover_lights;
    let off = if a().dark { rgb(71, 76, 80, 1.0) } else { rgb(208, 208, 210, 1.0) };
    let off_ring = if a().dark { col(0.0, 0.0, 0.0, 0.3) } else { rgb(186, 186, 189, 1.0) };
    for k in 0..3 {
        let c = light_center(k);
        let en = k < 2;
        br.SetColor(&if lit && en { fill_c[k as usize] } else { off });
        rt.FillEllipse(&ell(c, 7.0, 7.0), br);
        semaforo::gloss(rt, c, 7.0, br);
        br.SetColor(&if lit && en { ring_c[k as usize] } else { off_ring });
        rt.DrawEllipse(&ell(c, 6.75, 6.75), br, 0.5, None);
        if !a().hover_lights || !en {
            continue;
        }
        br.SetColor(&glyph_c[k as usize]);
        if k == 0 {
            ln(rt, br, c.x - 2.5, c.y - 2.5, c.x + 2.5, c.y + 2.5, 1.1);
            ln(rt, br, c.x - 2.5, c.y + 2.5, c.x + 2.5, c.y - 2.5, 1.1);
        } else {
            ln(rt, br, c.x - 3.3, c.y, c.x + 3.3, c.y, 1.2);
        }
    }
}
/// brilho de vidro na borda: claro no meio da diagonal de cima-direita a baixo-esquerda
unsafe fn glass_rim(rt: &ID2D1RenderTarget, r: RectF, rad: f32, kind: i32) {
    let dark = a().dark;
    let c = if kind == 2 { rgb(255, 214, 10, 1.0) } else { rgb(255, 255, 255, 1.0) };
    let peak = if kind == 2 {
        0.85
    } else if dark {
        if kind == 1 {
            0.42
        } else if kind == 3 {
            0.2
        } else {
            0.3
        }
    } else {
        0.9
    };
    let lo = if kind == 2 {
        0.05
    } else if dark {
        0.0
    } else {
        0.2
    };
    let al = |x: f32| col(c.r, c.g, c.b, x);
    let (cx, cy, hw, hh) = ((r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0, (r.right - r.left) / 2.0, (r.bottom - r.top) / 2.0);
    let stops = [(0.0, al(lo)), (0.25, al(peak * 0.55)), (0.5, al(peak)), (0.75, al(peak * 0.55)), (1.0, al(lo))];
    if let Some(gb) = linear(rt, &stops, pt(cx + hw, cy - hh), pt(cx - hw, cy + hh)) {
        let wd = 1.3;
        rt.DrawRoundedRectangle(&rr(rf(r.left + wd / 2.0, r.top + wd / 2.0, r.right - wd / 2.0, r.bottom - wd / 2.0), rad - wd / 2.0, rad - wd / 2.0), &gb, wd, None);
    }
    if !dark && kind != 2 {
        if let Some(b) = brush(rt, rgb(0, 0, 0, 0.07)) {
            rt.DrawRoundedRectangle(&rr(rf(r.left - 0.25, r.top - 0.25, r.right + 0.25, r.bottom + 0.25), rad + 0.25, rad + 0.25), &b, 0.6, None);
        }
    }
}
unsafe fn draw_round_buttons(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) {
    let dark = a().dark;
    let toward = if dark { rgb(255, 255, 255, 1.0) } else { rgb(0, 0, 0, 1.0) };
    let hov_c = mix(pal.round, toward, if dark { 0.1 } else { 0.06 });
    for which in 0..2 {
        let c = if which == 0 { side_btn_center() } else { mode_btn_center() };
        let hov = a().hover.kind == if which == 0 { Tg::SideBtn } else { Tg::ModeBtn };
        let on = which == 0 && a().sidebar;
        let mut old = mat::ident();
        rt.GetTransform(&mut old);
        if leo() {
            rt.SetTransform(&mat::mul(&mat::scale(0.5, 0.5, c.x, c.y), &old));
        }
        br.SetColor(&if hov || on { hov_c } else { pal.round });
        rt.FillEllipse(&ell(c, ROUND_R, ROUND_R), br);
        glass_rim(rt, rf(c.x - ROUND_R, c.y - ROUND_R, c.x + ROUND_R, c.y + ROUND_R), ROUND_R, 3);
        br.SetColor(&pal.icon);
        if which == 0 {
            rt.DrawRoundedRectangle(&rr(rf(c.x - 9.5, c.y - 7.2, c.x + 9.5, c.y + 7.2), 3.0, 3.0), br, 1.4, None);
            ln(rt, br, c.x - 3.2, c.y - 7.2, c.x - 3.2, c.y + 7.2, 1.4);
            for i in 0..3 {
                let y = c.y - 3.6 + i as f32 * 2.6;
                ln(rt, br, c.x - 7.4, y, c.x - 5.4, y, 1.1);
            }
        } else {
            rt.FillRoundedRectangle(&rr(rf(c.x - 5.8, c.y - 8.2, c.x + 5.8, c.y + 8.2), 2.2, 2.2), br);
            br.SetColor(&if hov { hov_c } else { pal.round });
            rt.FillRectangle(&rf(c.x - 3.9, c.y - 6.3, c.x + 3.9, c.y - 3.3), br);
            for yy in 0..4 {
                for xx in 0..3 {
                    let (x, y) = (c.x - 3.9 + xx as f32 * 2.9, c.y - 1.6 + yy as f32 * 2.5);
                    rt.FillRectangle(&rf(x, y, x + 1.9, y + 1.6), br);
                }
            }
        }
        rt.SetTransform(&old);
    }
}
unsafe fn draw_glyph(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, id: i32, r: RectF) {
    let (cx, cy, h) = ((r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0, r.bottom - r.top);
    let basic = a().mode == Mode::Basic;
    let s = (h * 0.36).min(18.0);
    let wd = if basic { 1.6 } else { 1.4 };
    match id {
        K_ADD => {
            ln(rt, br, cx - s / 2.0, cy, cx + s / 2.0, cy, wd);
            ln(rt, br, cx, cy - s / 2.0, cx, cy + s / 2.0, wd);
        }
        K_SUB => ln(rt, br, cx - s / 2.0, cy, cx + s / 2.0, cy, wd),
        K_MUL => {
            let d = s * 0.36;
            ln(rt, br, cx - d, cy - d, cx + d, cy + d, wd);
            ln(rt, br, cx - d, cy + d, cx + d, cy - d, wd);
        }
        K_DIV => {
            ln(rt, br, cx - s / 2.0, cy, cx + s / 2.0, cy, wd);
            rt.FillEllipse(&ell(pt(cx, cy - s * 0.32), wd, wd), br);
            rt.FillEllipse(&ell(pt(cx, cy + s * 0.32), wd, wd), br);
        }
        K_EQ => {
            ln(rt, br, cx - s / 2.0, cy - s * 0.19, cx + s / 2.0, cy - s * 0.19, wd);
            ln(rt, br, cx - s / 2.0, cy + s * 0.19, cx + s / 2.0, cy + s * 0.19, wd);
        }
        K_DEL => {
            let gw = if basic { 22.0 } else { 19.0 };
            let gh = gw * 0.72;
            let (l, t, rr_, b) = (cx - gw / 2.0, cy - gh / 2.0, cx + gw / 2.0, cy + gh / 2.0);
            let tip = l + gh * 0.5;
            if let Ok(g) = d2d().CreatePathGeometry() {
                if let Ok(sk) = g.Open() {
                    let rad = 2.5;
                    let arc = |p: Ponto| D2D1_ARC_SEGMENT { point: p, size: D2D_SIZE_F { width: rad, height: rad }, rotationAngle: 0.0, sweepDirection: D2D1_SWEEP_DIRECTION_CLOCKWISE, arcSize: D2D1_ARC_SIZE_SMALL };
                    sk.BeginFigure(pt(l, cy), D2D1_FIGURE_BEGIN_HOLLOW);
                    sk.AddLine(pt(tip, t));
                    sk.AddLine(pt(rr_ - rad, t));
                    sk.AddArc(&arc(pt(rr_, t + rad)));
                    sk.AddLine(pt(rr_, b - rad));
                    sk.AddArc(&arc(pt(rr_ - rad, b)));
                    sk.AddLine(pt(tip, b));
                    sk.EndFigure(D2D1_FIGURE_END_CLOSED);
                    let _ = sk.Close();
                    rt.DrawGeometry(&g, br, 1.6, a().round.as_ref());
                }
            }
            let (xc, d) = ((tip + rr_) / 2.0 + 1.0, gh * 0.2);
            ln(rt, br, xc - d, cy - d, xc + d, cy + d, 1.6);
            ln(rt, br, xc - d, cy + d, xc + d, cy - d, 1.6);
        }
        _ => {}
    }
}
unsafe fn draw_keys(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) {
    let dark = a().dark;
    for (i, k) in a().keys.clone().iter().enumerate() {
        let mut r = key_rect(k);
        let rad = (r.right - r.left).min(r.bottom - r.top) / 2.0;
        let mut style = k.style;
        if k.id == K_2ND && a().second {
            style = S_TOP;
        }
        if a().mode == Mode::Prog && k.id == K_EQ {
            style = S_OP;
        }
        let mut c = pal.key[style];
        let en = key_enabled(k.id);
        let glow = a().glow.get(&k.id).copied().unwrap_or(0.0);
        let hov = a().hover.kind == Tg::Key && a().hover.idx == i as i32 && en;
        let toward = if dark || style == S_OP { rgb(255, 255, 255, 1.0) } else { rgb(0, 0, 0, 1.0) };
        if hov {
            c = mix(c, toward, if style == S_OP { 0.1 } else if dark { 0.07 } else { 0.04 });
        }
        if glow > 0.0 {
            c = mix(c, toward, glow * if style == S_OP { 0.4 } else if dark { 0.32 } else { 0.14 });
        }
        if leo() {
            let cy0 = (r.top + r.bottom) / 2.0;
            let hh = (r.bottom - r.top - 4.0).min(if k.id == K_EQ && r.bottom - r.top > 60.0 { 999.0 } else { 26.0 });
            let q = rf(r.left + 2.0, cy0 - hh / 2.0, r.right - 2.0, cy0 + hh / 2.0);
            let blue = glow > 0.3;
            let g = |x: (i32, i32, i32), y: (i32, i32, i32)| if blue { rgb(x.0, x.1, x.2, 1.0) } else { rgb(y.0, y.1, y.2, 1.0) };
            let stops = [(0.0, g((170, 205, 250), (255, 255, 255))), (0.5, g((100, 155, 235), (242, 242, 242))), (0.5, g((60, 120, 222), (226, 226, 226))), (1.0, g((150, 205, 255), (248, 248, 248)))];
            br.SetColor(&rgb(255, 255, 255, 0.5));
            rt.FillRoundedRectangle(&rr(rf(q.left, q.top + 1.0, q.right, q.bottom + 1.0), 5.0, 5.0), br);
            if let Some(lb) = linear(rt, &stops, pt(0.0, q.top), pt(0.0, q.bottom)) {
                rt.FillRoundedRectangle(&rr(q, 5.0, 5.0), &lb);
            }
            br.SetColor(&if hov { rgb(0, 0, 0, 0.55) } else { rgb(0, 0, 0, 0.38) });
            rt.DrawRoundedRectangle(&rr(rf(q.left + 0.5, q.top + 0.5, q.right - 0.5, q.bottom - 0.5), 4.5, 4.5), br, 1.0, None);
            r = q;
        } else {
            br.SetColor(&c);
            rt.FillRoundedRectangle(&rr(r, rad, rad), br);
            glass_rim(rt, r, rad, if style == S_OP { 2 } else if style == S_TOP { 1 } else { 0 });
        }
        let tc = if !en {
            pal.disabled
        } else if style == S_OP {
            pal.op_text
        } else {
            pal.text
        };
        br.SetColor(&tc);
        let lab = key_label(k.id);
        if [K_ADD, K_SUB, K_MUL, K_DIV, K_DEL].contains(&k.id) || (k.id == K_EQ && lab.is_empty()) {
            draw_glyph(rt, br, k.id, r);
            continue;
        }
        let rs = markup(&lab);
        let digit = (0..=15).contains(&k.id) || k.id == K_DOT;
        let mut size: f32 = match a().mode {
            Mode::Basic => {
                if digit {
                    23.0
                } else {
                    20.0
                }
            }
            Mode::Sci => {
                if digit {
                    19.0
                } else if lab.chars().count() > 4 && !lab.contains('{') {
                    15.0
                } else {
                    16.5
                }
            }
            Mode::Prog => {
                if digit {
                    19.0
                } else if lab.chars().count() > 3 {
                    14.0
                } else {
                    16.0
                }
            }
        };
        if k.id == K_NEG {
            size = if a().mode == Mode::Basic { 22.0 } else { 19.0 };
        }
        if k.id == K_PCT && a().mode == Mode::Basic {
            size = 24.0;
        }
        if leo() {
            size = size.min(14.0);
        }
        size = size.min((r.bottom - r.top) * 0.5);
        let n = DWRITE_FONT_WEIGHT_NORMAL;
        let mut wd = runs_width(&rs, size, n);
        let max_w = (r.right - r.left) - 8.0;
        if wd > max_w {
            size *= max_w / wd;
            wd = runs_width(&rs, size, n);
        }
        let cy = (r.top + r.bottom) / 2.0;
        let lower = rs.iter().filter(|x| x.lvl == 0).all(|x| x.t.chars().all(|ch| "mcrnsx+−eaowvu".contains(ch)));
        let base = if lower { cy + size * 0.53 / 2.0 } else { cy + size * 0.705 / 2.0 };
        draw_runs(rt, br, &rs, size, n, (r.left + r.right) / 2.0 - wd / 2.0, base, tc, tc);
    }
}
fn display_right() -> f32 {
    client().0 - 13.0
}
unsafe fn draw_std_display(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) {
    let (left, right) = (side() + 14.0, display_right());
    let basic = a().mode == Mode::Basic;
    let (mut grey_size, mut big_size, mut grey_base, mut big_base) = if basic { (21.0, 32.0, 80.0, 118.0) } else { (17.0, 27.0, 68.0, 101.0) };
    if leo() {
        (grey_size, big_size, grey_base, big_base) = (13.0, 22.0, 50.0, 78.0);
    }
    let num = |v: f64| vec![Run { t: format_num(v, if basic { 10 } else { 15 }), ..Default::default() }];
    let a = a();
    let mut grey: Vec<Run> = Vec::new();
    let big = if a.rpn {
        let need = if a.entering { 1 } else { 2 };
        if a.stack.len() >= need {
            grey = num(a.stack[a.stack.len() - need]);
        }
        if a.entering {
            vec![Run { t: format_typed(&a.entry), ..Default::default() }]
        } else {
            num(a.stack.last().copied().unwrap_or(0.0))
        }
    } else if a.done {
        grey = render_toks(&a.done_expr);
        num(a.ans)
    } else if a.toks.is_empty() {
        num(0.0)
    } else {
        if has_operation(&a.toks) {
            if let Some(v) = eval(a.toks.clone()) {
                grey = num(v);
            }
        }
        render_toks(&a.toks)
    };
    let n = DWRITE_FONT_WEIGHT_NORMAL;
    if !grey.is_empty() {
        fit_runs(rt, br, &grey, grey_size, grey_size * 0.6, n, left, right, grey_base, pal.sub, pal.sub);
    }
    let rad = a.rad && !basic;
    fit_runs(rt, br, &big, big_size, big_size * 0.5, n, left + if rad { 34.0 } else { 0.0 }, right, big_base, pal.text, pal.sub);
    if rad {
        text_at(rt, br, "Rad", 13.0, n, false, 0, left, big_base, pal.sub);
    }
}
fn convert_value(v: f64) -> f64 {
    let a = a();
    if a.conv_cat == 2 {
        let k = match a.conv_from {
            0 => v + 273.15,
            1 => (v - 32.0) * 5.0 / 9.0 + 273.15,
            _ => v,
        };
        return match a.conv_to {
            0 => k - 273.15,
            1 => (k - 273.15) * 9.0 / 5.0 + 32.0,
            _ => k,
        };
    }
    let c = &a.cats[a.conv_cat];
    v * c.units[a.conv_from].f / c.units[a.conv_to].f
}
unsafe fn draw_convert(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) {
    let dark = a().dark;
    let toward = if dark { rgb(255, 255, 255, 1.0) } else { rgb(0, 0, 0, 1.0) };
    let (left, mid) = (side() + 48.0, conv_mid());
    for which in 0..2 {
        let ur = conv_unit_rect(which);
        let hov = a().hover.kind == Tg::Conv && a().hover.idx == which as i32;
        br.SetColor(&if hov { mix(pal.key[0], toward, 0.08) } else { pal.key[0] });
        rt.FillRoundedRectangle(&rr(ur, 12.0, 12.0), br);
        let sym = {
            let a = a();
            a.cats[a.conv_cat].units[if which == 0 { a.conv_from } else { a.conv_to }].sym.clone()
        };
        let cy = (ur.top + ur.bottom) / 2.0;
        text_at(rt, br, &sym, 14.0, DWRITE_FONT_WEIGHT_MEDIUM, false, 0, ur.left + 10.0, cy + 5.0, pal.text);
        br.SetColor(&pal.sub);
        ln(rt, br, ur.right - 15.0, cy - 1.5, ur.right - 12.0, cy + 1.5, 1.3);
        ln(rt, br, ur.right - 12.0, cy + 1.5, ur.right - 9.0, cy - 1.5, 1.3);
        let rs = if which == 0 {
            let a = a();
            if !a.rpn && !a.done && !a.toks.is_empty() {
                render_toks(&a.toks)
            } else {
                vec![Run { t: if a.rpn && a.entering { format_typed(&a.entry) } else { format_num(current_value(), 10) }, ..Default::default() }]
            }
        } else {
            vec![Run { t: format_num(convert_value(current_value()), 10), ..Default::default() }]
        };
        fit_runs(rt, br, &rs, 30.0, 14.0, DWRITE_FONT_WEIGHT_NORMAL, left, ur.left - 10.0, cy + 10.0, pal.text, pal.sub);
    }
    br.SetColor(&pal.line);
    rt.DrawLine(pt(side() + 48.0, mid + 2.0), pt(display_right(), mid + 2.0), br, 1.0, None);
    let sc = conv_swap_center();
    let hov = a().hover.kind == Tg::Conv && a().hover.idx == 2;
    br.SetColor(&if hov { mix(pal.key[0], toward, 0.08) } else { pal.key[0] });
    rt.FillEllipse(&ell(sc, 14.0, 14.0), br);
    br.SetColor(&pal.text);
    for (x1, y1, x2, y2) in [(-3.5, -6.0, -3.5, 6.0), (-6.5, -3.0, -3.5, -6.0), (-0.5, -3.0, -3.5, -6.0), (3.5, -6.0, 3.5, 6.0), (0.5, 3.0, 3.5, 6.0), (6.5, 3.0, 3.5, 6.0)] {
        ln(rt, br, sc.x + x1, sc.y + y1, sc.x + x2, sc.y + y2, 1.4);
    }
    let nome = a().cats[a().conv_cat].name.clone();
    text_at(rt, br, &nome, 11.0, DWRITE_FONT_WEIGHT_MEDIUM, false, 1, side() + 14.0, TB + 6.0, pal.sub);
}
unsafe fn draw_prog_display(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) {
    let (left, right) = (side() + 14.0, display_right());
    let n = DWRITE_FONT_WEIGHT_NORMAL;
    let base = a().base;
    if a().p_op != 0 {
        let g = vec![Run { t: format!("{} {}", prog_fmt(a().p_acc, base), prog_op_sym(a().p_op)), ..Default::default() }];
        fit_runs(rt, br, &g, 17.0, 11.0, n, left + 120.0, right, 66.0, pal.sub, pal.sub);
    }
    let b = vec![Run { t: if a().p_err { tr("Erro") } else { prog_fmt(prog_cur(), base) }, ..Default::default() }];
    fit_runs(rt, br, &b, 32.0, 14.0, n, left + 120.0, right, 104.0, pal.text, pal.sub);
    let v = prog_cur();
    text_at(rt, br, &format!("HEX  {}", prog_fmt(v, 16)), 11.0, n, false, 1, left, 70.0, pal.sub);
    text_at(rt, br, &format!("DEC  {}", prog_fmt(v, 10)), 11.0, n, false, 1, left, 86.0, pal.sub);
    text_at(rt, br, &format!("OCT  {}", prog_fmt(v, 8)), 11.0, n, false, 1, left, 102.0, pal.sub);
    let bf = font(13.0, DWRITE_FONT_WEIGHT_MEDIUM, false, 0);
    let lf = font(9.5, n, false, 1);
    for bit in (0..64).rev() {
        let r = bit_rect(bit);
        let on = (v >> bit) & 1 == 1;
        if a().hover.kind == Tg::Bit && a().hover.idx == bit {
            br.SetColor(&pal.hover);
            rt.FillRoundedRectangle(&rr(r, 3.0, 3.0), br);
        }
        let t = if on { "1" } else { "0" };
        let wd = tw(&bf, t);
        text_at(rt, br, t, 13.0, DWRITE_FONT_WEIGHT_MEDIUM, false, 0, (r.left + r.right) / 2.0 - wd / 2.0, r.top + 13.5, if on { pal.text } else { pal.sub });
        if bit % 16 == 15 || bit % 32 == 0 {
            let nn = bit.to_string();
            let nw = tw(&lf, &nn);
            let x = if bit % 32 == 0 { r.right - nw } else { r.left };
            text_at(rt, br, &nn, 9.5, n, false, 1, x, r.bottom + 9.0, pal.sub);
        }
    }
    let dark = a().dark;
    let toward = if dark { rgb(255, 255, 255, 1.0) } else { rgb(0, 0, 0, 1.0) };
    for (i, b) in [8u32, 10, 16].iter().enumerate() {
        let r = base_rect(i as i32);
        let sel = base == *b;
        let hov = a().hover.kind == Tg::Base && a().hover.idx == i as i32;
        br.SetColor(&if sel {
            pal.key[2]
        } else if hov {
            mix(pal.key[0], toward, 0.08)
        } else {
            pal.key[0]
        });
        rt.FillRoundedRectangle(&rr(r, 10.0, 10.0), br);
        let t = b.to_string();
        let tf = font(12.5, DWRITE_FONT_WEIGHT_MEDIUM, false, 0);
        text_at(rt, br, &t, 12.5, DWRITE_FONT_WEIGHT_MEDIUM, false, 0, (r.left + r.right) / 2.0 - tw(&tf, &t) / 2.0, (r.top + r.bottom) / 2.0 + 4.5, pal.text);
    }
}
unsafe fn draw_sidebar(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, pal: &Pal) {
    if !a().sidebar {
        return;
    }
    let (_, ch) = client();
    br.SetColor(&pal.sidebar);
    rt.FillRectangle(&rf(0.0, 0.0, SBW, ch), br);
    br.SetColor(&pal.line);
    rt.DrawLine(pt(SBW - 0.5, 0.0), pt(SBW - 0.5, ch), br, 1.0, None);
    rt.PushAxisAlignedClip(&rf(0.0, TB, SBW, ch), D2D1_ANTIALIAS_MODE_ALIASED);
    let n = DWRITE_FONT_WEIGHT_NORMAL;
    if a().hist.is_empty() {
        let t = tr("Sem Histórico");
        let tf = font(13.0, n, false, 1);
        text_at(rt, br, &t, 13.0, n, false, 1, SBW / 2.0 - tw(&tf, &t) / 2.0, ch / 2.0, pal.sub);
    }
    for (i, h) in a().hist.clone().iter().enumerate() {
        let r = hist_rect(i);
        if r.bottom < TB || r.top > ch {
            continue;
        }
        if a().hover.kind == Tg::Hist && a().hover.idx == i as i32 {
            br.SetColor(&pal.hover);
            rt.FillRoundedRectangle(&rr(r, 8.0, 8.0), br);
        }
        fit_runs(rt, br, &render_toks(&h.toks), 13.0, 9.0, n, r.left + 10.0, r.right - 10.0, r.top + 19.0, pal.sub, pal.sub);
        let v = vec![Run { t: format_num(h.val, 12), ..Default::default() }];
        fit_runs(rt, br, &v, 19.0, 11.0, DWRITE_FONT_WEIGHT_MEDIUM, r.left + 10.0, r.right - 10.0, r.top + 42.0, pal.text, pal.sub);
    }
    rt.PopAxisAlignedClip();
}
/// o quadro inteiro, em qualquer alvo (a janela ou o bitmap do --foto)
unsafe fn render_into(rt: &ID2D1RenderTarget) {
    let pal = colors();
    rt.Clear(Some(&pal.bg));
    let Ok(br) = rt.CreateSolidColorBrush(&pal.text, None) else { return };
    let (cw, ch) = client();
    if leo() {
        if let Some(lb) = linear(rt, &[(0.0, rgb(214, 214, 214, 1.0)), (1.0, rgb(170, 170, 170, 1.0))], pt(0.0, 0.0), pt(0.0, ch)) {
            rt.FillRectangle(&rf(0.0, 0.0, cw, ch), &lb);
        }
        leopard::metal(rt, rf(0.0, 0.0, cw, 22.0), a().active, false, true, 0.0);
        let tt = cjk::format(dw(), "Lucida Sans Unicode", DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, 13.0, "pt-br").unwrap();
        let _ = tt.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
        let _ = tt.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
        br.SetColor(&rgb(0, 0, 0, if a().active { 0.85 } else { 0.45 }));
        rt.DrawText(&w(&tr("Calculadora")), &tt, &rf(80.0, 0.0, cw - 80.0, 22.0), &br, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
        if a().mode != Mode::Prog {
            let lcd = rf(side() + 10.0, 30.0, cw - 10.0, keys_top() - 10.0);
            if let Some(lb) = linear(rt, &[(0.0, rgb(226, 234, 190, 1.0)), (1.0, rgb(240, 245, 205, 1.0))], pt(0.0, lcd.top), pt(0.0, lcd.bottom)) {
                rt.FillRoundedRectangle(&rr(lcd, 4.0, 4.0), &lb);
            }
            br.SetColor(&rgb(0, 0, 0, 0.45));
            rt.DrawRoundedRectangle(&rr(rf(lcd.left + 0.5, lcd.top + 0.5, lcd.right - 0.5, lcd.bottom - 0.5), 3.5, 3.5), &br, 1.0, None);
            br.SetColor(&rgb(0, 0, 0, 0.12));
            rt.FillRectangle(&rf(lcd.left + 1.0, lcd.top + 1.0, lcd.right - 1.0, lcd.top + 3.0), &br);
        }
    }
    draw_sidebar(rt, &br, &pal);
    if a().mode == Mode::Prog {
        draw_prog_display(rt, &br, &pal);
    } else if conv_on() {
        draw_convert(rt, &br, &pal);
    } else {
        draw_std_display(rt, &br, &pal);
    }
    draw_keys(rt, &br, &pal);
    draw_round_buttons(rt, &br, &pal);
    draw_lights(rt, &br);
}
fn render() {
    unsafe {
        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 = Some(r);
        }
        let r = a().rt.clone().unwrap();
        r.BeginDraw();
        render_into(&r.cast().unwrap());
        if let Err(e) = r.EndDraw(None, None) {
            if e.code() == D2DERR_RECREATE_TARGET {
                a().rt = None;
            }
        }
        if !a().shown {
            a().shown = true;
            ampliacao::revelar(h);
        }
    }
}
fn invalidate() {
    unsafe {
        let _ = InvalidateRect(a().hwnd, None, FALSE);
    }
}

// ---------------------------------------------------------------------------
// interação
fn hit_target(p: Ponto) -> Target {
    for k in 0..3 {
        if in_circle(light_center(k), 8.0, p) {
            return Target { kind: Tg::Light, idx: k };
        }
    }
    let rr_ = if leo() { ROUND_R / 2.0 } else { ROUND_R };
    if in_circle(side_btn_center(), rr_, p) {
        return Target { kind: Tg::SideBtn, idx: 0 };
    }
    if in_circle(mode_btn_center(), rr_, p) {
        return Target { kind: Tg::ModeBtn, idx: 0 };
    }
    if a().sidebar && p.x < SBW && p.y >= TB {
        for i in 0..a().hist.len() {
            if in_rect(&hist_rect(i), p.x, p.y) {
                return Target { kind: Tg::Hist, idx: i as i32 };
            }
        }
    }
    for (i, k) in a().keys.iter().enumerate() {
        if in_rect(&key_rect(k), p.x, p.y) {
            return Target { kind: Tg::Key, idx: i as i32 };
        }
    }
    if conv_on() {
        for w_ in 0..2 {
            if in_rect(&conv_unit_rect(w_), p.x, p.y) {
                return Target { kind: Tg::Conv, idx: w_ as i32 };
            }
        }
        if in_circle(conv_swap_center(), 14.0, p) {
            return Target { kind: Tg::Conv, idx: 2 };
        }
    }
    if a().mode == Mode::Prog {
        for b in 0..64 {
            if in_rect(&bit_rect(b), p.x, p.y) {
                return Target { kind: Tg::Bit, idx: b };
            }
        }
        for i in 0..3 {
            if in_rect(&base_rect(i), p.x, p.y) {
                return Target { kind: Tg::Base, idx: i };
            }
        }
    }
    Target::default()
}
fn flash(id: i32) {
    a().glow.insert(id, 1.0);
    a().held.insert(id, false);
    a().last_anim = unsafe { GetTickCount() };
    unsafe {
        SetTimer(a().hwnd, 1, 16, None);
    }
}
fn press_key(id: i32) {
    press(id);
    invalidate();
}
fn copy_text() -> String {
    if a().mode == Mode::Prog {
        return prog_fmt(prog_cur(), a().base).replace(a().grp, "").replace('−', "-");
    }
    let v = current_value();
    if v.is_finite() {
        plain_num(v)
    } else {
        String::new()
    }
}
fn char_key(c: char) -> i32 {
    let sci = a().mode == Mode::Sci;
    let s = |k: i32| if sci { k } else { -1 };
    if a().mode == Mode::Prog {
        if let Some(d) = c.to_digit(16) {
            return d as i32;
        }
        return match c {
            '+' => K_ADD,
            '-' => K_SUB,
            '*' => K_MUL,
            '/' => K_DIV,
            '%' => K_PCT,
            '&' => K_AND,
            '|' => K_OR,
            '^' => K_XOR,
            '~' => K_1S,
            '<' => K_SHL,
            '>' => K_SHR,
            '=' | '\r' => K_EQ,
            _ => -1,
        };
    }
    if let Some(d) = c.to_digit(10) {
        return d as i32;
    }
    if c == a().dec || c == '.' || c == ',' {
        return K_DOT;
    }
    match c {
        '+' => K_ADD,
        '-' | '−' => K_SUB,
        '*' | 'x' | 'X' | '×' => K_MUL,
        '/' | '÷' => K_DIV,
        '%' => K_PCT,
        '=' | '\r' => K_EQ,
        'c' | 'C' => K_AC,
        '(' => s(K_LP),
        ')' => s(K_RP),
        '^' => s(K_POW),
        '!' => s(K_FACT),
        'π' | 'p' => s(K_PI),
        'e' => s(K_E),
        'E' => s(K_EE),
        _ => -1,
    }
}
fn paste_text(t: &str) {
    let ch: Vec<char> = t.chars().take(200).collect();
    for i in 0..ch.len() {
        let c = ch[i];
        if c == a().grp && a().grp != a().dec && a().mode != Mode::Prog {
            continue;
        }
        if (c == 'e' || c == 'E') && a().mode != Mode::Prog && i > 0 && ch[i - 1].is_ascii_digit() {
            press(K_EE);
            continue;
        }
        let k = char_key(c);
        if k >= 0 && k != K_EQ && k != K_AC {
            press(k);
        }
    }
    invalidate();
}
fn set_mode(m: Mode) {
    if m == a().mode {
        return;
    }
    if m == Mode::Prog {
        let v = current_value();
        let a = a();
        a.p_acc = if v.is_finite() { v.clamp(-9.2e18, 9.2e18).round() as i64 as u64 } else { 0 };
        a.p_entry = 0;
        a.p_op = 0;
        a.p_entering = false;
        a.p_err = false;
    } else if a().mode == Mode::Prog {
        let v = prog_cur() as i64 as f64;
        let a = a();
        a.toks.clear();
        a.done_expr.clear();
        a.done = true;
        a.ans = v;
        a.stack.clear();
        a.entering = false;
        if a.rpn {
            a.stack.push(v);
        }
    }
    a().mode = m;
    a().second = false;
    apply_layout(0);
}
fn screen_pt(x: f32, y: f32) -> POINT {
    let sc = scale();
    to_screen(a().hwnd, (x * sc).round() as i32, (y * sc).round() as i32)
}
fn mode_menu() {
    use ctxmenu::Item;
    let c = mode_btn_center();
    let p = screen_pt(c.x + ROUND_R - 196.0, c.y + ROUND_R + 6.0);
    let m = a().mode;
    let prog = m == Mode::Prog;
    let id = ctxmenu::show_items(
        a().hwnd,
        p,
        &[
            Item::new(tr("Básica"), 1).checked(m == Mode::Basic).shortcut("Ctrl+1"),
            Item::new(tr("Científica"), 2).checked(m == Mode::Sci).shortcut("Ctrl+2"),
            Item::new(tr("Programador"), 3).checked(prog).shortcut("Ctrl+3"),
            Item::sep(),
            Item::new(tr("Converter"), 4).checked(a().convert && !prog).disabled(prog),
            Item::new(tr("Modo RPN"), 5).checked(a().rpn && !prog).disabled(prog).shortcut("Ctrl+R"),
            Item::sep(),
            Item::new(tr("Notas Matemáticas…"), 6).disabled(true),
        ],
    );
    match id {
        1 => set_mode(Mode::Basic),
        2 => set_mode(Mode::Sci),
        3 => set_mode(Mode::Prog),
        4 => {
            a().convert = !a().convert;
            apply_layout(0);
        }
        5 => {
            let rpn = !a().rpn;
            let v = if rpn { current_value() } else { a().stack.last().copied().unwrap_or(0.0) };
            let a = a();
            a.rpn = rpn;
            if rpn {
                a.stack.clear();
                if v != 0.0 && v.is_finite() {
                    a.stack.push(v);
                }
                a.entering = false;
                a.entry.clear();
            } else {
                a.toks.clear();
                a.done_expr.clear();
                a.done = v != 0.0;
                a.ans = v;
            }
            build_keys();
            save_settings();
        }
        _ => {}
    }
    a().hover = Target::default();
    invalidate();
}
fn unit_menu(which: usize) {
    use ctxmenu::Item;
    let cur = if which == 0 { a().conv_from } else { a().conv_to };
    let items: Vec<Item> = a()
        .cats
        .iter()
        .enumerate()
        .map(|(c, cat)| {
            let sub = cat.units.iter().enumerate().map(|(u, un)| Item::new(format!("{} ({})", un.name, un.sym), 1 + (c * 100 + u) as i32).checked(c == a().conv_cat && u == cur)).collect();
            Item::new(cat.name.clone(), 0).checked(c == a().conv_cat).sub(sub)
        })
        .collect();
    let r = conv_unit_rect(which);
    let id = ctxmenu::show_items(a().hwnd, screen_pt(r.left, r.bottom + 4.0), &items);
    if id <= 0 {
        return;
    }
    let (c, u) = (((id - 1) / 100) as usize, ((id - 1) % 100) as usize);
    let a = a();
    if c != a.conv_cat {
        a.conv_cat = c;
        let other = if u == 0 { 1 } else { 0 };
        if which == 0 {
            a.conv_from = u;
            a.conv_to = other;
        } else {
            a.conv_to = u;
            a.conv_from = other;
        }
    } else if which == 0 {
        a.conv_from = u;
    } else {
        a.conv_to = u;
    }
    save_settings();
}
fn use_history(i: usize) {
    let Some(h) = a().hist.get(i).cloned() else { return };
    let a = a();
    if a.mode == Mode::Prog {
        a.p_entry = if h.val.is_finite() { h.val.round() as i64 as u64 } else { 0 };
        a.p_entering = true;
        return;
    }
    if a.rpn {
        commit();
        self::a().stack.push(h.val);
        return;
    }
    a.done_expr = h.toks;
    a.ans = h.val;
    a.done = true;
    a.toks.clear();
    a.rep_ok = false;
}
fn history_menu(i: i32, scr: POINT) {
    use ctxmenu::Item;
    let none = i < 0;
    let id = ctxmenu::show_items(
        a().hwnd,
        scr,
        &[
            Item::new(tr("Copiar Resultado"), 1).disabled(none),
            Item::new(tr("Copiar Expressão"), 2).disabled(none),
            Item::new(tr("Apagar"), 3).disabled(none),
            Item::sep(),
            Item::new(tr("Limpar Histórico"), 4).disabled(a().hist.is_empty()),
        ],
    );
    let h = a().hwnd;
    match id {
        1 if !none => {
            clipboard_set_text(h, &plain_num(a().hist[i as usize].val));
        }
        2 if !none => {
            clipboard_set_text(h, &plain_of(&render_toks(&a().hist[i as usize].toks)));
        }
        3 if !none => {
            a().hist.remove(i as usize);
            save_history();
        }
        4 => {
            a().hist.clear();
            a().hist_scroll = 0.0;
            save_history();
        }
        _ => {}
    }
    a().hover = Target::default();
    invalidate();
}
fn toggle_sidebar() {
    a().sidebar = !a().sidebar;
    a().hist_scroll = 0.0;
    apply_layout(if a().sidebar { SBW as i32 } else { -(SBW as i32) });
}
fn hit_test_nc(h: HWND, l: LPARAM) -> LRESULT {
    let p = screen_to_client(h, l);
    let mut rc = RECT::default();
    unsafe {
        let _ = GetClientRect(h, &mut rc);
    }
    let sc = scale();
    if a().mode == Mode::Sci {
        let b = (6.0 * sc) 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 pp = pt(p.x as f32 / sc, p.y as f32 / sc);
    if hit_target(pp).kind != Tg::None || (a().sidebar && pp.x < SBW && pp.y >= TB) {
        return LRESULT(HTCLIENT as isize);
    }
    LRESULT(HTCAPTION as isize)
}
fn tick() {
    let now = unsafe { GetTickCount() };
    let dt = now.wrapping_sub(a().last_anim) as f32 / 1000.0;
    a().last_anim = now;
    let held = a().held.clone();
    a().glow.retain(|id, g| {
        if !held.get(id).copied().unwrap_or(false) {
            *g -= dt / 0.25;
        }
        *g > 0.0
    });
    let vivos: Vec<i32> = a().glow.keys().copied().collect();
    a().held.retain(|k, _| vivos.contains(k));
    if a().glow.is_empty() {
        unsafe {
            let _ = KillTimer(a().hwnd, 1);
        }
    }
    invalidate();
}
fn set_dwm_theme(h: HWND) {
    unsafe {
        let dm = BOOL::from(a().dark);
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(20), &dm as *const _ as *const c_void, 4);
        let border = if a().dark { app2d::colorref(70, 74, 78) } else { app2d::colorref(196, 196, 200) };
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(34), &border as *const _ as *const c_void, 4);
    }
}

extern "system" fn wnd_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    unsafe {
        let sc = scale();
        let p_cli = || pt(get_x_lparam(l) as f32 / sc, get_y_lparam(l) as f32 / sc);
        match m {
            WM_NCCALCSIZE if w_.0 != 0 => return LRESULT(0),
            WM_NCHITTEST => return hit_test_nc(h, l),
            WM_GETMINMAXINFO => {
                if a().hwnd.0.is_null() {
                    return DefWindowProcW(h, m, w_, l);
                }
                let mm = &mut *(l.0 as *mut MINMAXINFO);
                let cs = content_size();
                if a().mode == Mode::Sci {
                    mm.ptMinTrackSize = POINT { x: ((480.0 + side()) * sc) as i32, y: ((300.0 + if conv_on() { CONV_H } else { 0.0 }) * sc) as i32 };
                } else {
                    let p = POINT { x: ((cs.0 + side()) * sc).round() as i32, y: (cs.1 * sc).round() as i32 };
                    mm.ptMinTrackSize = p;
                    mm.ptMaxTrackSize = p;
                }
            }
            WM_ENTERSIZEMOVE => a().user_sizing = true,
            WM_EXITSIZEMOVE => {
                a().user_sizing = false;
                save_settings();
            }
            WM_SIZE => {
                if let Some(r) = &a().rt {
                    let _ = r.Resize(&D2D_SIZE_U { width: loword(l.0 as usize), height: hiword(l.0 as usize) });
                }
                if a().user_sizing && a().mode == Mode::Sci {
                    let (cw, ch) = client();
                    a().sci_w = cw - side();
                    a().sci_h = ch - if conv_on() { CONV_H } else { 0.0 };
                }
                invalidate();
            }
            WM_DPICHANGED => {
                let r = &*(l.0 as *const RECT);
                a().rt = None;
                let _ = SetWindowPos(h, None, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOZORDER | SWP_NOACTIVATE);
            }
            WM_ERASEBKGND => return LRESULT(1),
            WM_PAINT => {
                let mut ps = PAINTSTRUCT::default();
                BeginPaint(h, &mut ps);
                render();
                let _ = EndPaint(h, &ps);
            }
            WM_ACTIVATE => {
                a().active = loword(w_.0) != WA_INACTIVE;
                invalidate();
            }
            WM_SETTINGCHANGE => {
                a().dark = read_dark();
                set_dwm_theme(h);
                invalidate();
            }
            WM_TIMER => {
                if w_.0 == 1 {
                    tick();
                } else if w_.0 == 2 && read_dark() != a().dark {
                    SendMessageW(h, WM_SETTINGCHANGE, WPARAM(0), LPARAM(0));
                }
            }
            WM_MOUSEWHEEL => {
                if a().sidebar && (screen_to_client(h, l).x as f32 / sc) < SBW {
                    let mx = (a().hist.len() as f32 * HIST_H + 8.0 - (client().1 - TB)).max(0.0);
                    a().hist_scroll = (a().hist_scroll - wheel_delta(w_) / 120.0 * HIST_H).clamp(0.0, mx);
                    invalidate();
                }
            }
            WM_NCMOUSEMOVE | WM_MOUSEMOVE => {
                let p = if m == WM_NCMOUSEMOVE {
                    let c = screen_to_client(h, l);
                    pt(c.x as f32 / sc, c.y as f32 / sc)
                } else {
                    p_cli()
                };
                let mut t = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: if m == WM_NCMOUSEMOVE { TME_LEAVE | TME_NONCLIENT } else { TME_LEAVE }, hwndTrack: h, dwHoverTime: 0 };
                let _ = TrackMouseEvent(&mut t);
                let tg = hit_target(p);
                let hl = p.x < 82.0 && p.y < TB;
                if tg != a().hover || hl != a().hover_lights {
                    a().hover = tg;
                    a().hover_lights = hl;
                    invalidate();
                }
                if m == WM_NCMOUSEMOVE {
                    return DefWindowProcW(h, m, w_, l);
                }
            }
            WM_NCMOUSELEAVE | WM_MOUSELEAVE => {
                if a().hover.kind != Tg::None || a().hover_lights {
                    a().hover = Target::default();
                    a().hover_lights = false;
                    invalidate();
                }
            }
            WM_LBUTTONDBLCLK | WM_LBUTTONDOWN => {
                let tg = hit_target(p_cli());
                a().down = tg;
                match tg.kind {
                    Tg::Key => {
                        let id = a().keys[tg.idx as usize].id;
                        if !key_enabled(id) {
                            a().down = Target::default();
                            return LRESULT(0);
                        }
                        a().glow.insert(id, 1.0);
                        a().held.insert(id, true);
                        SetCapture(h);
                        invalidate();
                    }
                    Tg::Light => {
                        if tg.idx == 0 {
                            post(h, WM_CLOSE, 0, 0);
                        } else if tg.idx == 1 {
                            let _ = ShowWindow(h, SW_MINIMIZE);
                        }
                    }
                    Tg::SideBtn => toggle_sidebar(),
                    Tg::ModeBtn => mode_menu(),
                    Tg::Hist => {
                        use_history(tg.idx as usize);
                        invalidate();
                    }
                    Tg::Conv => {
                        if tg.idx == 2 {
                            let a = a();
                            std::mem::swap(&mut a.conv_from, &mut a.conv_to);
                            save_settings();
                        } else {
                            unit_menu(tg.idx as usize);
                        }
                        a().hover = Target::default();
                        invalidate();
                    }
                    Tg::Bit => {
                        prog_set(prog_cur() ^ (1u64 << tg.idx));
                        invalidate();
                    }
                    Tg::Base => {
                        a().base = [8, 10, 16][tg.idx as usize];
                        save_settings();
                        invalidate();
                    }
                    Tg::None => {}
                }
            }
            WM_LBUTTONUP => {
                let d = a().down;
                if d.kind == Tg::Key {
                    let _ = ReleaseCapture();
                    let id = a().keys[d.idx as usize].id;
                    a().held.insert(id, false);
                    a().last_anim = GetTickCount();
                    SetTimer(h, 1, 16, None);
                    if hit_target(p_cli()) == d {
                        press_key(id);
                    }
                }
                a().down = Target::default();
            }
            WM_RBUTTONUP => {
                let p = p_cli();
                if a().sidebar && p.x < SBW && p.y >= TB {
                    let tg = hit_target(p);
                    history_menu(if tg.kind == Tg::Hist { tg.idx } else { -1 }, to_screen(h, get_x_lparam(l), get_y_lparam(l)));
                }
            }
            WM_NCRBUTTONUP => {
                use ctxmenu::Item;
                let sp = POINT { x: get_x_lparam(l), y: get_y_lparam(l) };
                let id = ctxmenu::show_items(h, sp, &[Item::new(tr("Copiar"), 1).shortcut("Ctrl+C"), Item::new(tr("Colar"), 2).shortcut("Ctrl+V")]);
                if id == 1 {
                    clipboard_set_text(h, &copy_text());
                } else if id == 2 {
                    if let Some(t) = clipboard_get_text(h) {
                        paste_text(&t);
                    }
                }
            }
            WM_SYSKEYDOWN => return DefWindowProcW(h, m, w_, l),
            WM_KEYDOWN => {
                let k = w_.0 as u16;
                if key_down(VK_CONTROL.0) {
                    match k as u8 {
                        b'C' => {
                            clipboard_set_text(h, &copy_text());
                        }
                        b'V' => {
                            if let Some(t) = clipboard_get_text(h) {
                                paste_text(&t);
                            }
                        }
                        b'1' => set_mode(Mode::Basic),
                        b'2' => set_mode(Mode::Sci),
                        b'3' => set_mode(Mode::Prog),
                        b'R' if a().mode != Mode::Prog => {
                            let a = a();
                            a.rpn = !a.rpn;
                            a.stack.clear();
                            a.entering = false;
                            a.toks.clear();
                            a.done = false;
                            build_keys();
                            save_settings();
                        }
                        b'W' | b'Q' => post(h, WM_CLOSE, 0, 0),
                        b'S' => toggle_sidebar(),
                        _ => {}
                    }
                    invalidate();
                    return LRESULT(0);
                }
                let key = if k == VK_ESCAPE.0 || k == VK_DELETE.0 {
                    K_AC
                } else if k == VK_BACK.0 {
                    K_DEL
                } else if k == VK_RETURN.0 {
                    K_EQ
                } else {
                    -1
                };
                if key >= 0 {
                    flash(key);
                    press_key(key);
                }
            }
            WM_CHAR => {
                if let Some(c) = char::from_u32(w_.0 as u32) {
                    if c as u32 >= 32 && c as u32 != 127 {
                        let k = char_key(c);
                        if k >= 0 && key_enabled(k) {
                            flash(k);
                            press_key(k);
                        }
                    }
                }
            }
            WM_CLOSE => {
                save_settings();
                let _ = DestroyWindow(h);
            }
            WM_DESTROY => PostQuitMessage(0),
            _ => return DefWindowProcW(h, m, w_, l),
        }
        LRESULT(0)
    }
}

fn pick_family(nomes: &[&str]) -> String {
    nomes.iter().find(|n| app2d::has_font(n)).map(|n| n.to_string()).unwrap_or_else(|| "Segoe UI".into())
}
fn load_settings() -> (i32, i32) {
    let kv = read_kv("calculadora.txt");
    let get = |k: &str, d: i32| kv.get(k).and_then(|v| v.parse().ok()).unwrap_or(d);
    let a = a();
    a.mode = match kv.get("modo").map(String::as_str) {
        Some("cientifica") => Mode::Sci,
        Some("programador") => Mode::Prog,
        _ => Mode::Basic,
    };
    a.sci_w = get("larg_cientifica", 572).max(480) as f32;
    a.sci_h = get("alt_cientifica", 347).max(300) as f32;
    a.rpn = get("rpn", 0) != 0;
    a.convert = get("converter", 0) != 0;
    a.sidebar = get("historico", 0) != 0;
    a.rad = get("radianos", 0) != 0;
    a.base = match get("base", 10) {
        8 => 8,
        16 => 16,
        _ => 10,
    };
    a.conv_cat = (get("conv_cat", 0).max(0) as usize).min(a.cats.len() - 1);
    let n = a.cats[a.conv_cat].units.len();
    a.conv_from = (get("conv_de", 1).max(0) as usize).min(n - 1);
    a.conv_to = (get("conv_para", 4.min(n as i32 - 1)).max(0) as usize).min(n - 1);
    (get("x", i32::MIN), get("y", i32::MIN))
}

/// --foto: o desenho num bitmap do tamanho do conteúdo (a 2x), sem janela
fn foto(caminho: &str) -> Result<()> {
    let cs = content_size();
    a().foto_size = Some((cs.0 + side(), cs.1));
    let (cw, ch) = client();
    unsafe {
        let wic: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
        let bmp = wic.CreateBitmap((cw * 2.0) as u32, (ch * 2.0) as u32, &GUID_WICPixelFormat32bppPBGRA, WICBitmapCacheOnLoad)?;
        let props = D2D1_RENDER_TARGET_PROPERTIES {
            pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED },
            dpiX: 192.0,
            dpiY: 192.0,
            ..Default::default()
        };
        let rt = d2d().CreateWicBitmapRenderTarget(&bmp, &props)?;
        rt.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
        rt.BeginDraw();
        render_into(&rt);
        rt.EndDraw(None, None)?;
        salvar_png(&bmp, caminho)
    }
}

fn main() {
    let foto_p = arg_valor("--foto");
    unsafe {
        if foto_p.is_none() {
            let _ = CreateMutexW(None, true, w!("CalculadoraMacUmaJanela"));
            if GetLastError() == ERROR_ALREADY_EXISTS {
                if let Some(wd) = find_window("CalculadoraJanela") {
                    if IsIconic(wd).as_bool() {
                        let _ = ShowWindow(wd, SW_RESTORE);
                    }
                    let _ = SetForegroundWindow(wd);
                }
                return;
            }
        }
    }
    if !app2d::init() {
        std::process::exit(1);
    }
    let seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u64 | 1;
    *A.get() = Some(App {
        hwnd: HWND::default(),
        rt: None,
        round: None,
        dark: true,
        active: true,
        hover_lights: false,
        shown: false,
        user_sizing: false,
        family: pick_family(&["SF Pro Display", "SF Pro", "Segoe UI Variable Display"]),
        text_family: pick_family(&["SF Pro Text", "SF Pro", "Segoe UI Variable Text"]),
        mode: Mode::Basic,
        rpn: false,
        convert: false,
        sidebar: false,
        rad: false,
        second: false,
        sci_w: 572.0,
        sci_h: 347.0,
        dec: '.',
        grp: ',',
        keys: Vec::new(),
        rng: seed,
        hover: Target::default(),
        down: Target::default(),
        glow: HashMap::new(),
        held: HashMap::new(),
        last_anim: 0,
        hist_scroll: 0.0,
        toks: Vec::new(),
        done: false,
        done_expr: Vec::new(),
        ans: 0.0,
        rep_op: String::new(),
        rep_val: 0.0,
        rep_ok: false,
        mem: 0.0,
        stack: Vec::new(),
        entry: String::new(),
        entering: false,
        p_acc: 0,
        p_entry: 0,
        p_op: 0,
        p_entering: false,
        p_err: false,
        base: 10,
        cats: cats(),
        conv_cat: 0,
        conv_from: 1,
        conv_to: 4,
        hist: Vec::new(),
        force_theme: String::new(),
        fonts: HashMap::new(),
        baselines: HashMap::new(),
        foto_size: None,
    });
    unsafe {
        let sp = D2D1_STROKE_STYLE_PROPERTIES { startCap: D2D1_CAP_STYLE_ROUND, endCap: D2D1_CAP_STYLE_ROUND, dashCap: D2D1_CAP_STYLE_ROUND, lineJoin: D2D1_LINE_JOIN_ROUND, miterLimit: 10.0, dashStyle: D2D1_DASH_STYLE_SOLID, dashOffset: 0.0 };
        a().round = d2d().CreateStrokeStyle(&sp, None).ok();
        let mut b = [0u16; 8];
        if GetLocaleInfoEx(PCWSTR::null(), LOCALE_SDECIMAL, Some(&mut b)) > 1 {
            a().dec = char::from_u32(b[0] as u32).unwrap_or('.');
        }
        if GetLocaleInfoEx(PCWSTR::null(), LOCALE_STHOUSAND, Some(&mut b)) > 1 {
            a().grp = if b[0] == 0xA0 { ' ' } else { char::from_u32(b[0] as u32).unwrap_or(',') };
        }
    }
    if a().grp == a().dec {
        a().grp = if a().dec == ',' { '.' } else { ',' };
    }
    let args: Vec<String> = std::env::args().collect();
    if args.iter().any(|x| x == "--tema=claro") || arg_valor("--tema").as_deref() == Some("claro") {
        a().force_theme = "claro".into();
    }
    if args.iter().any(|x| x == "--tema=escuro") || arg_valor("--tema").as_deref() == Some("escuro") {
        a().force_theme = "escuro".into();
    }
    a().dark = read_dark();
    let (sx, sy) = load_settings();
    load_history();
    if let Some(p) = foto_p {
        // teste: o modo e as teclas pedidos na linha de comando, sem ler nem gravar nada além
        if let Some(m) = arg_valor("--modo") {
            a().mode = match m.as_str() {
                "cientifica" => Mode::Sci,
                "programador" => Mode::Prog,
                _ => Mode::Basic,
            };
        }
        a().sidebar = tem_arg("--historico");
        a().foto_size = Some((1.0, 1.0));
        build_keys();
        if let Some(t) = arg_valor("--foto-teclas") {
            for c in t.chars() {
                let k = char_key(c);
                if k >= 0 {
                    press(k);
                }
            }
        }
        let r = foto(&p);
        println!("foto: {p} {r:?}");
        return;
    }
    unsafe {
        let hi: HINSTANCE = GetModuleHandleW(None).unwrap_or_default().into();
        let wc = WNDCLASSEXW {
            cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
            style: CS_DBLCLKS,
            lpfnWndProc: Some(wnd_proc),
            hInstance: hi,
            hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(),
            lpszClassName: w!("CalculadoraJanela"),
            ..Default::default()
        };
        RegisterClassExW(&wc);
        let mut cur = POINT::default();
        let _ = GetCursorPos(&mut cur);
        let want = POINT { x: sx, y: sy };
        let mut mon = if sx != i32::MIN { MonitorFromPoint(want, MONITOR_DEFAULTTONULL) } else { HMONITOR::default() };
        if mon.0.is_null() {
            mon = MonitorFromPoint(cur, MONITOR_DEFAULTTONEAREST);
        }
        let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
        let _ = GetMonitorInfoW(mon, &mut mi);
        let (mut dx, mut dy) = (96u32, 96u32);
        let _ = GetDpiForMonitor(mon, MDT_EFFECTIVE_DPI, &mut dx, &mut dy);
        let sc = dx as f32 / 96.0;
        let cs = content_size();
        let (ww, hh) = (((cs.0 + side()) * sc).round() as i32, (cs.1 * sc).round() as i32);
        let (x, y) = if sx != i32::MIN && !MonitorFromPoint(want, MONITOR_DEFAULTTONULL).0.is_null() {
            (sx - (side() * sc).round() as i32, sy)
        } else {
            ((mi.rcWork.left + mi.rcWork.right - ww) / 2, (mi.rcWork.top + mi.rcWork.bottom - hh) / 2)
        };
        let titulo = wz(&tr_pick("Calculadora", "Calculator"));
        let Ok(h) = CreateWindowExW(WINDOW_EX_STYLE(0), w!("CalculadoraJanela"), pc(&titulo), WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX, x, y, ww, hh, None, None, hi, None) else {
            std::process::exit(1)
        };
        a().hwnd = h;
        app2d::s().wnd = h;
        ampliacao::janela(h);
        let cloak = BOOL(1);
        let _ = DwmSetWindowAttribute(h, DWMWA_CLOAK, &cloak as *const _ as *const c_void, 4);
        set_dwm_theme(h);
        let corner = 2i32;
        let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const c_void, 4);
        let mg = MARGINS { cxLeftWidth: 0, cxRightWidth: 0, cyTopHeight: 1, cyBottomHeight: 0 };
        let _ = DwmExtendFrameIntoClientArea(h, &mg);
        let _ = SetWindowPos(h, None, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
        build_keys();
        let _ = ShowWindow(h, SW_SHOWNORMAL);
        SetTimer(h, 2, 2000, None);
        let mut msg = MSG::default();
        while GetMessageW(&mut msg, None, 0, 0).as_bool() {
            let _ = TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
    }
}

#[cfg(test)]
mod testes {
    use super::*;
    fn calc(teclas: &str) -> f64 {
        *A.get() = None;
        let _ = std::panic::catch_unwind(|| ());
        // estado mínimo para a lógica (sem janela nem Direct2D)
        main_estado();
        for c in teclas.chars() {
            let k = char_key(c);
            if k >= 0 {
                press(k);
            }
        }
        current_value()
    }
    fn main_estado() {
        *A.get() = Some(App {
            hwnd: HWND::default(),
            rt: None,
            round: None,
            dark: true,
            active: true,
            hover_lights: false,
            shown: false,
            user_sizing: false,
            family: String::new(),
            text_family: String::new(),
            mode: Mode::Sci,
            rpn: false,
            convert: false,
            sidebar: false,
            rad: false,
            second: false,
            sci_w: 572.0,
            sci_h: 347.0,
            dec: '.',
            grp: ',',
            keys: Vec::new(),
            rng: 1,
            hover: Target::default(),
            down: Target::default(),
            glow: HashMap::new(),
            held: HashMap::new(),
            last_anim: 0,
            hist_scroll: 0.0,
            toks: Vec::new(),
            done: false,
            done_expr: Vec::new(),
            ans: 0.0,
            rep_op: String::new(),
            rep_val: 0.0,
            rep_ok: false,
            mem: 0.0,
            stack: Vec::new(),
            entry: String::new(),
            entering: false,
            p_acc: 0,
            p_entry: 0,
            p_op: 0,
            p_entering: false,
            p_err: false,
            base: 10,
            cats: Vec::new(),
            conv_cat: 0,
            conv_from: 0,
            conv_to: 0,
            hist: Vec::new(),
            force_theme: String::new(),
            fonts: HashMap::new(),
            baselines: HashMap::new(),
            foto_size: Some((1.0, 1.0)),
        });
    }
    #[test]
    fn contas() {
        assert_eq!(calc("2+3×4="), 14.0);
        assert_eq!(calc("(2+3)×4="), 20.0);
        assert_eq!(calc("50+10%="), 55.0);
        assert_eq!(calc("2^10="), 1024.0);
        assert_eq!(calc("5!="), 120.0);
        assert!((calc("π") - PI).abs() < 1e-12);
        assert!((gamma(5.5) - 52.34277778455352).abs() < 1e-9);
    }
}