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
28.0 KB
Raw Blame
//! dashboard.cpp: Dashboard do Mac OS X Leopard (tema Leopard; Win+F12, como o F12 do Mac): a tela escurece e os
//! widgets aparecem por cima de tudo, crescendo um pouco ao entrar. Widgets do 10.5: o Relógio (mostrador branco, aro
//! cromado, ponteiro vermelho dos segundos), o Calendário (a folha do dia com a faixa vermelha e o mês ao lado) e a
//! Calculadora (corpo grafite, visor cinza-esverdeado, teclas que funcionam, também pelo teclado). O "+" no canto abre a
//! barra de widgets para ligar/desligar cada um; os widgets se arrastam e a posição fica guardada (dashboard_pos /
//! dashboard_on). Clicar fora dos widgets, Esc ou Win+F12 fecha.
#![allow(dead_code)]

use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::System::SystemInformation::GetLocalTime;
use comum::windows::Win32::System::Threading::{AttachThreadInput, GetCurrentThreadId};
use comum::windows::Win32::System::Time::{FileTimeToSystemTime, SystemTimeToFileTime};
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

use crate::{anim, apps, shell, ui};

const WM_DB_FRAME: u32 = WM_APP + 181;
const T_CLOCK: usize = 1;
const W_CLOCK: usize = 0;
const W_CAL: usize = 1;
const W_CALC: usize = 2;
const W_COUNT: usize = 3;
const BAR_H: f32 = 132.0;
const KEYS: [&str; 22] = ["mc", "m+", "m-", "mr", "C", "±", "÷", "×", "7", "8", "9", "−", "4", "5", "6", "+", "1", "2", "3", "=", "0", "."];
const PI: f32 = std::f32::consts::PI;

#[derive(Clone, Copy)]
struct Wd {
    w: f32,
    h: f32,
    x: f32,
    y: f32,
    on: bool,
}
struct S {
    wnd: HWND,
    s: ui::GpuSurface,
    open: bool,
    closing: bool,
    bar: bool,
    at: f64,
    w: f32,
    h: f32,
    wd: [Wd; W_COUNT],
    drag: Option<usize>,
    drag_off: Ponto,
    moved: bool,
    press: Option<usize>,
    // calculadora
    acc: f64,
    mem: f64,
    op: char,
    disp: String,
    fresh: bool,
    fonts: Vec<(u32, bool, bool, IDWriteTextFormat)>,
    foto: bool,
}
static SS: Global<Option<S>> = Global::new(None);
fn s() -> &'static mut S {
    SS.get().get_or_insert_with(|| S {
        wnd: HWND::default(),
        s: ui::GpuSurface::default(),
        open: false,
        closing: false,
        bar: false,
        at: 0.0,
        w: 0.0,
        h: 0.0,
        wd: [Wd { w: 160.0, h: 178.0, x: 0.0, y: 0.0, on: true }, Wd { w: 300.0, h: 150.0, x: 0.0, y: 0.0, on: true }, Wd { w: 156.0, h: 226.0, x: 0.0, y: 0.0, on: true }],
        drag: None,
        drag_off: pt(0.0, 0.0),
        moved: false,
        press: None,
        acc: 0.0,
        mem: 0.0,
        op: '\0',
        disp: "0".into(),
        fresh: true,
        fonts: Vec::new(),
        foto: false,
    })
}
fn sc() -> f32 {
    if s().foto {
        ui::foto_scale()
    } else {
        ui::scale(s().wnd)
    }
}
/// fonte Lucida (a do Leopard), guardada por tamanho/peso/alinhamento
fn f(size: f32, bold: bool, center: bool) -> IDWriteTextFormat {
    let st = s();
    let key = (size * 10.0) as u32;
    if let Some(x) = st.fonts.iter().find(|x| x.0 == key && x.1 == bold && x.2 == center) {
        return x.3.clone();
    }
    let tf = ui::format_face("Lucida Sans Unicode", size, if bold { DWRITE_FONT_WEIGHT_BOLD } else { DWRITE_FONT_WEIGHT_NORMAL });
    unsafe {
        let _ = tf.SetTextAlignment(if center { DWRITE_TEXT_ALIGNMENT_CENTER } else { DWRITE_TEXT_ALIGNMENT_TRAILING });
        let _ = tf.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
        let _ = tf.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
    }
    st.fonts.push((key, bold, center, tf.clone()));
    tf
}
unsafe fn txt(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, t: &str, tf: &IDWriteTextFormat, r: RectF, c: Cor) {
    br.SetColor(&c);
    dc.DrawText(&w(t), tf, &r, br, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
}
unsafe fn grad(dc: &ID2D1DeviceContext, r: RectF, rad: f32, stops: &[(f32, Cor)], ellipse: bool) {
    let Some(lb) = linear(&dc.cast().unwrap(), stops, pt(0.0, r.top), pt(0.0, r.bottom)) else { return };
    if ellipse {
        dc.FillEllipse(&ell(pt((r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0), (r.right - r.left) / 2.0, (r.bottom - r.top) / 2.0), &lb);
    } else {
        dc.FillRoundedRectangle(&rr(r, rad, rad), &lb);
    }
}
/// sombra macia feita de camadas
unsafe fn shadow(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, r: RectF, rad: f32, ellipse: bool) {
    for i in (1..=4).rev() {
        let i = i as f32;
        br.SetColor(&col(0.0, 0.0, 0.0, 0.07));
        let q = rf(r.left - i, r.top - i + 4.0, r.right + i, r.bottom + i + 5.0);
        if ellipse {
            dc.FillEllipse(&ell(pt((q.left + q.right) / 2.0, (q.top + q.bottom) / 2.0), (q.right - q.left) / 2.0, (q.bottom - q.top) / 2.0), br);
        } else {
            dc.FillRoundedRectangle(&rr(q, rad + i, rad + i), br);
        }
    }
}
fn c1(v: f32) -> Cor {
    col(v, v, v, 1.0)
}
unsafe fn paint_clock(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, r: RectF) {
    let rad = (r.right - r.left) / 2.0 - 8.0;
    let c = pt((r.left + r.right) / 2.0, r.top + 8.0 + rad);
    let o = rf(c.x - rad, c.y - rad, c.x + rad, c.y + rad);
    shadow(dc, br, o, rad, true);
    grad(dc, o, 0.0, &[(0.0, col(0.98, 0.98, 0.99, 1.0)), (0.5, col(0.58, 0.59, 0.62, 1.0)), (1.0, col(0.93, 0.93, 0.95, 1.0))], true);
    let r2 = rad * 0.87;
    grad(dc, rf(c.x - r2, c.y - r2, c.x + r2, c.y + r2), 0.0, &[(0.0, col(0.84, 0.84, 0.86, 1.0)), (1.0, c1(1.0))], true);
    let num = f(15.0, true, true);
    for i in 1..=12 {
        let a = i as f32 * PI / 6.0;
        let (x, y) = (c.x + a.sin() * r2 * 0.76, c.y - a.cos() * r2 * 0.76);
        txt(dc, br, &i.to_string(), &num, rf(x - 14.0, y - 10.0, x + 14.0, y + 10.0), c1(0.08));
    }
    let t = GetLocalTime();
    let mn = t.wMinute as f32 + t.wSecond as f32 / 60.0;
    let hr = (t.wHour % 12) as f32 + mn / 60.0;
    let hand = |ang: f32, len: f32, wd: f32, cl: Cor, tail: f32| {
        br.SetColor(&cl);
        let d = pt(ang.sin(), -ang.cos());
        dc.DrawLine(pt(c.x - d.x * tail, c.y - d.y * tail), pt(c.x + d.x * len, c.y + d.y * len), br, wd, None);
    };
    hand(hr * PI / 6.0, r2 * 0.50, 4.0, c1(0.08), r2 * 0.08);
    hand(mn * PI / 30.0, r2 * 0.74, 3.0, c1(0.08), r2 * 0.08);
    hand(t.wSecond as f32 * PI / 30.0, r2 * 0.80, 1.3, col(0.85, 0.10, 0.08, 1.0), r2 * 0.18);
    br.SetColor(&col(0.85, 0.10, 0.08, 1.0));
    dc.FillEllipse(&ell(c, 3.0, 3.0), br);
    // o brilho de vidro em cima do mostrador
    br.SetColor(&col(1.0, 1.0, 1.0, 0.25));
    dc.FillEllipse(&ell(pt(c.x, c.y - r2 * 0.45), r2 * 0.70, r2 * 0.42), br);
    txt(dc, br, &tr("Hora Local"), &f(12.0, true, true), rf(r.left - 20.0, r.bottom - 16.0, r.right + 20.0, r.bottom + 2.0), col(1.0, 1.0, 1.0, 0.95));
}
const DIAS: [&str; 7] = ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"];
const MESES: [&str; 12] = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
unsafe fn paint_cal(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, r: RectF) {
    shadow(dc, br, r, 12.0, false);
    grad(dc, r, 12.0, &[(0.0, col(0.30, 0.30, 0.32, 1.0)), (1.0, col(0.12, 0.12, 0.13, 1.0))], false);
    br.SetColor(&col(1.0, 1.0, 1.0, 0.25));
    dc.DrawRoundedRectangle(&rr(rf(r.left + 0.5, r.top + 0.5, r.right - 0.5, r.bottom - 0.5), 11.5, 11.5), br, 1.0, None);
    let t = GetLocalTime();
    // a folha do dia (como o ícone do iCal)
    let pg = rf(r.left + 10.0, r.top + 10.0, r.left + 120.0, r.bottom - 10.0);
    grad(dc, pg, 6.0, &[(0.0, c1(1.0)), (1.0, col(0.88, 0.88, 0.89, 1.0))], false);
    let band = rf(pg.left, pg.top, pg.right, pg.top + 30.0);
    grad(dc, band, 6.0, &[(0.0, col(0.93, 0.36, 0.33, 1.0)), (1.0, col(0.72, 0.07, 0.07, 1.0))], false);
    br.SetColor(&col(0.72, 0.07, 0.07, 1.0));
    dc.FillRectangle(&rf(band.left, band.bottom - 6.0, band.right, band.bottom), br);
    let fs = f(10.0, false, true);
    txt(dc, br, &tr(DIAS[t.wDayOfWeek as usize % 7]), &f(13.0, true, true), band, c1(1.0));
    txt(dc, br, &t.wDay.to_string(), &f(64.0, true, true), rf(pg.left, band.bottom, pg.right, pg.bottom), c1(0.1));
    // o mês
    let (gx, gw) = (pg.right + 10.0, r.right - 10.0 - (pg.right + 10.0));
    txt(dc, br, &format!("{} {}", tr(MESES[(t.wMonth as usize).clamp(1, 12) - 1]), t.wYear), &f(12.0, true, true), rf(gx, r.top + 8.0, gx + gw, r.top + 24.0), col(1.0, 1.0, 1.0, 0.95));
    let ini = ["D", "S", "T", "Q", "Q", "S", "S"];
    let cw = gw / 7.0;
    for (i, l) in ini.iter().enumerate() {
        txt(dc, br, l, &fs, rf(gx + i as f32 * cw, r.top + 26.0, gx + (i + 1) as f32 * cw, r.top + 38.0), col(1.0, 1.0, 1.0, 0.55));
    }
    let mut f1 = t;
    f1.wDay = 1;
    let mut ft = FILETIME::default();
    let _ = SystemTimeToFileTime(&f1, &mut ft);
    let _ = FileTimeToSystemTime(&ft, &mut f1);
    let first = f1.wDayOfWeek as usize;
    let dm = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    let y = t.wYear as i32;
    let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
    let days = dm[(t.wMonth as usize).clamp(1, 12) - 1] + if t.wMonth == 2 && leap { 1 } else { 0 };
    let rh = (r.bottom - 8.0 - (r.top + 40.0)) / 6.0;
    for d in 1..=days {
        let idx = first + d - 1;
        let (cl, row) = ((idx % 7) as f32, (idx / 7) as f32);
        let cr = rf(gx + cl * cw, r.top + 40.0 + row * rh, gx + (cl + 1.0) * cw, r.top + 40.0 + (row + 1.0) * rh);
        if d == t.wDay as usize {
            grad(dc, rf(cr.left + 1.0, cr.top, cr.right - 1.0, cr.bottom), 3.0, &[(0.0, col(0.95, 0.45, 0.40, 1.0)), (1.0, col(0.75, 0.10, 0.10, 1.0))], false);
        }
        txt(dc, br, &d.to_string(), &fs, cr, col(1.0, 1.0, 1.0, if d == t.wDay as usize { 1.0 } else { 0.85 }));
    }
}
fn key_rect(r: RectF, i: usize) -> RectF {
    let (x0, y0) = (r.left + 12.0, r.top + 70.0);
    let (kh, g) = (20.0, 5.0);
    let kw = (r.right - r.left - 24.0 - 3.0 * 5.0) / 4.0;
    if i < 20 {
        let (cl, row) = ((i % 4) as f32, (i / 4) as f32);
        let mut k = rf(x0 + cl * (kw + g), y0 + row * (kh + g), x0 + cl * (kw + g) + kw, y0 + row * (kh + g) + kh);
        if i == 19 {
            k.bottom += kh + g; // "=" alto
        }
        return k;
    }
    let y = y0 + 5.0 * (kh + g);
    if i == 20 {
        return rf(x0, y, x0 + 2.0 * kw + g, y + kh); // "0" largo
    }
    rf(x0 + 2.0 * (kw + g), y, x0 + 2.0 * (kw + g) + kw, y + kh)
}
unsafe fn paint_calc(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, r: RectF) {
    let st = s();
    shadow(dc, br, r, 16.0, false);
    grad(dc, r, 16.0, &[(0.0, col(0.40, 0.40, 0.42, 1.0)), (0.5, col(0.22, 0.22, 0.23, 1.0)), (1.0, col(0.12, 0.12, 0.13, 1.0))], false);
    br.SetColor(&col(1.0, 1.0, 1.0, 0.28));
    dc.DrawRoundedRectangle(&rr(rf(r.left + 0.5, r.top + 0.5, r.right - 0.5, r.bottom - 0.5), 15.5, 15.5), br, 1.0, None);
    // o visor de cristal líquido
    let lcd = rf(r.left + 12.0, r.top + 14.0, r.right - 12.0, r.top + 56.0);
    grad(dc, lcd, 6.0, &[(0.0, col(0.62, 0.67, 0.60, 1.0)), (0.25, col(0.80, 0.85, 0.77, 1.0)), (1.0, col(0.86, 0.90, 0.83, 1.0))], false);
    br.SetColor(&col(0.0, 0.0, 0.0, 0.45));
    dc.DrawRoundedRectangle(&rr(rf(lcd.left + 0.5, lcd.top + 0.5, lcd.right - 0.5, lcd.bottom - 0.5), 5.5, 5.5), br, 1.0, None);
    txt(dc, br, &st.disp, &f(24.0, false, false), rf(lcd.left + 6.0, lcd.top, lcd.right - 8.0, lcd.bottom), col(0.10, 0.12, 0.10, 1.0));
    if st.mem != 0.0 {
        txt(dc, br, "M", &f(9.0, true, true), rf(lcd.left + 4.0, lcd.top + 2.0, lcd.left + 16.0, lcd.top + 14.0), col(0.1, 0.12, 0.1, 0.8));
    }
    let fk = f(11.0, true, true);
    for (i, key) in KEYS.iter().enumerate() {
        let k = key_rect(r, i);
        let op = i < 8 || i % 4 == 3 || i == 19;
        let down = st.press == Some(i);
        let (a, b, c) = if down { (0.20, 0.12, 0.16) } else if op { (0.55, 0.36, 0.30) } else { (0.42, 0.25, 0.18) };
        grad(dc, k, 6.0, &[(0.0, col(a, a, a + 0.01, 1.0)), (0.5, col(b, b, b + 0.01, 1.0)), (1.0, col(c, c, c + 0.01, 1.0))], false);
        br.SetColor(&col(0.0, 0.0, 0.0, 0.55));
        dc.DrawRoundedRectangle(&rr(rf(k.left + 0.5, k.top + 0.5, k.right - 0.5, k.bottom - 0.5), 5.5, 5.5), br, 1.0, None);
        txt(dc, br, key, &fk, k, col(1.0, 1.0, 1.0, 0.95));
    }
}
fn fmt(v: f64) -> String {
    if !v.is_finite() {
        return "Erro".into();
    }
    // %.10g
    let s_ = if v != 0.0 && (v.abs() >= 1e10 || v.abs() < 1e-5) {
        format!("{v:.9e}")
    } else {
        let p = 10 - (v.abs().log10().floor() as i32 + 1).max(1);
        let t = format!("{:.*}", p.max(0) as usize, v);
        if t.contains('.') {
            t.trim_end_matches('0').trim_end_matches('.').to_string()
        } else {
            t
        }
    };
    s_.replace('.', ",")
}
fn val() -> f64 {
    s().disp.replace(',', ".").parse().unwrap_or(0.0)
}
fn apply() {
    let st = s();
    let v = val();
    st.acc = match st.op {
        '+' => st.acc + v,
        '−' => st.acc - v,
        '×' => st.acc * v,
        '÷' => {
            if v != 0.0 {
                st.acc / v
            } else {
                f64::NAN
            }
        }
        _ => v,
    };
    st.disp = fmt(st.acc);
}
fn calc_key(k: &str) {
    let st = s();
    match k {
        d if d.len() == 1 && d.as_bytes()[0].is_ascii_digit() => {
            if st.fresh || st.disp == "0" {
                st.disp.clear();
            }
            if st.disp.chars().count() < 14 {
                st.disp.push_str(d);
            }
            st.fresh = false;
        }
        "." | "," => {
            if st.fresh {
                st.disp = "0".into();
                st.fresh = false;
            }
            if !st.disp.contains(',') {
                st.disp.push(',');
            }
        }
        "C" => {
            st.disp = "0".into();
            st.acc = 0.0;
            st.op = '\0';
            st.fresh = true;
        }
        "±" => {
            if st.disp != "0" {
                st.disp = match st.disp.strip_prefix('-') {
                    Some(r) => r.to_string(),
                    None => format!("-{}", st.disp),
                };
            }
        }
        "=" => {
            apply();
            st.op = '\0';
            st.fresh = true;
        }
        "mc" => st.mem = 0.0,
        "m+" => {
            st.mem += val();
            st.fresh = true;
        }
        "m-" => {
            st.mem -= val();
            st.fresh = true;
        }
        "mr" => {
            st.disp = fmt(st.mem);
            st.fresh = true;
        }
        "+" | "−" | "×" | "÷" => {
            if !st.fresh || st.op == '\0' {
                apply();
            }
            st.op = k.chars().next().unwrap();
            st.fresh = true;
        }
        _ => {}
    }
}
fn wrect(i: usize) -> RectF {
    let w_ = s().wd[i];
    rf(w_.x, w_.y, w_.x + w_.w, w_.y + w_.h)
}
fn plus_rect() -> RectF {
    let st = s();
    let lift = if st.bar { BAR_H } else { 0.0 };
    rf(18.0, st.h - 52.0 - lift, 52.0, st.h - 18.0 - lift)
}
fn bar_item(i: usize) -> RectF {
    let x = 100.0 + i as f32 * 170.0;
    rf(x, s().h - BAR_H + 14.0, x + 150.0, s().h - 14.0)
}
fn load_pos() {
    let st = s();
    let on = shell::setting("dashboard_on", "111");
    for (i, c) in on.chars().chain(std::iter::repeat('1')).take(W_COUNT).enumerate() {
        st.wd[i].on = c == '1';
    }
    let def = [(0.22, 0.26), (0.40, 0.30), (0.68, 0.24)];
    for i in 0..W_COUNT {
        st.wd[i].x = st.w * def[i].0;
        st.wd[i].y = st.h * def[i].1;
    }
    let p = shell::setting("dashboard_pos", "");
    for (i, part) in p.split(';').filter(|x| !x.is_empty()).take(W_COUNT).enumerate() {
        if let Some((a, b)) = part.split_once(',') {
            if let (Ok(fx), Ok(fy)) = (a.trim().parse::<f32>(), b.trim().parse::<f32>()) {
                st.wd[i].x = fx * st.w;
                st.wd[i].y = fy * st.h;
            }
        }
    }
    let (sw, sh) = (st.w, st.h);
    for w_ in st.wd.iter_mut() {
        w_.x = w_.x.clamp(0.0, (sw - w_.w).max(0.0));
        w_.y = w_.y.clamp(24.0, (sh - w_.h).max(24.0));
    }
}
fn save_pos() {
    let st = s();
    if st.foto {
        return;
    }
    let p: String = st.wd.iter().map(|w_| format!("{:.4},{:.4};", w_.x / st.w, w_.y / st.h)).collect();
    let on: String = st.wd.iter().map(|w_| if w_.on { '1' } else { '0' }).collect();
    shell::set_setting("dashboard_pos", &p);
    shell::set_setting("dashboard_on", &on);
}
fn progress() -> f32 {
    let st = s();
    if st.foto {
        return 1.0;
    }
    let k = anim::ease(((anim::now() - st.at) / 260.0).clamp(0.0, 1.0) as f32);
    if st.closing {
        1.0 - k
    } else {
        k
    }
}
fn layer(dc: &ID2D1DeviceContext, op: f32) {
    let lp = D2D1_LAYER_PARAMETERS1 { contentBounds: rf(-1e7, -1e7, 1e7, 1e7), geometricMask: std::mem::ManuallyDrop::new(None), maskAntialiasMode: D2D1_ANTIALIAS_MODE_PER_PRIMITIVE, maskTransform: mat::ident(), opacity: op, opacityBrush: std::mem::ManuallyDrop::new(None), layerOptions: D2D1_LAYER_OPTIONS1_NONE };
    unsafe { dc.PushLayer(&lp, None) };
}
unsafe fn paint_widget(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, i: usize, r: RectF) {
    match i {
        W_CLOCK => paint_clock(dc, br, r),
        W_CAL => paint_cal(dc, br, r),
        _ => paint_calc(dc, br, r),
    }
}
unsafe fn paint_on(dc: &ID2D1DeviceContext) {
    let st = s();
    let Ok(br) = dc.CreateSolidColorBrush(&c1(0.0), None) else { return };
    let k = progress();
    let mut base = mat::ident();
    dc.GetTransform(&mut base);
    br.SetColor(&col(0.0, 0.0, 0.0, 0.48 * k)); // a tela escurece por trás
    dc.FillRectangle(&rf(0.0, 0.0, st.w, st.h), &br);
    for i in 0..W_COUNT {
        if !st.wd[i].on {
            continue;
        }
        let r = wrect(i);
        let sz = 1.12 - 0.12 * k; // entram crescendo um pouco (e saem do mesmo jeito)
        dc.SetTransform(&mat::mul(&mat::scale(sz, sz, (r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0), &base));
        layer(dc, k);
        paint_widget(dc, &br, i, r);
        dc.PopLayer();
        dc.SetTransform(&base);
    }
    layer(dc, k);
    if st.bar {
        // a barra de widgets: faixa de metal escovado embaixo
        let b = rf(0.0, st.h - BAR_H, st.w, st.h);
        grad(dc, b, 0.0, &[(0.0, col(0.62, 0.62, 0.64, 1.0)), (0.08, col(0.50, 0.50, 0.52, 1.0)), (1.0, col(0.30, 0.30, 0.32, 1.0))], false);
        br.SetColor(&col(1.0, 1.0, 1.0, 0.5));
        dc.DrawLine(pt(0.0, b.top + 0.5), pt(st.w, b.top + 0.5), &br, 1.0, None);
        let nomes = ["Relógio", "Calendário", "Calculadora"];
        let fn_ = f(11.0, true, true);
        for i in 0..W_COUNT {
            let it = bar_item(i);
            let mini = rf(it.left + 40.0, it.top + 4.0, it.right - 40.0, it.bottom - 26.0);
            // miniatura: o próprio widget reduzido
            let (ww, hh) = (st.wd[i].w, st.wd[i].h);
            let sz = ((mini.right - mini.left) / ww).min((mini.bottom - mini.top) / hh);
            let m = mat::mul(&mat::scale(sz, sz, 0.0, 0.0), &mat::trans((mini.left + mini.right) / 2.0 - ww * sz / 2.0, (mini.top + mini.bottom) / 2.0 - hh * sz / 2.0));
            dc.SetTransform(&mat::mul(&m, &base));
            layer(dc, if st.wd[i].on { 0.45 } else { 1.0 });
            paint_widget(dc, &br, i, rf(0.0, 0.0, ww, hh));
            dc.PopLayer();
            dc.SetTransform(&base);
            txt(dc, &br, &format!("{}{}", tr(nomes[i]), if st.wd[i].on { " ✓" } else { "" }), &fn_, rf(it.left, it.bottom - 22.0, it.right, it.bottom), col(1.0, 1.0, 1.0, 0.95));
        }
    }
    // o "+" (ou o "×" com a barra aberta) no canto de baixo à esquerda
    let pr = plus_rect();
    shadow(dc, &br, pr, 17.0, true);
    grad(dc, pr, 0.0, &[(0.0, col(0.55, 0.55, 0.57, 1.0)), (1.0, col(0.20, 0.20, 0.21, 1.0))], true);
    let (cx, cy) = ((pr.left + pr.right) / 2.0, (pr.top + pr.bottom) / 2.0);
    br.SetColor(&col(1.0, 1.0, 1.0, 0.6));
    dc.DrawEllipse(&ell(pt(cx, cy), 16.5, 16.5), &br, 1.2, None);
    br.SetColor(&col(1.0, 1.0, 1.0, 0.95));
    if st.bar {
        dc.DrawLine(pt(cx - 6.0, cy - 6.0), pt(cx + 6.0, cy + 6.0), &br, 3.0, None);
        dc.DrawLine(pt(cx + 6.0, cy - 6.0), pt(cx - 6.0, cy + 6.0), &br, 3.0, None);
    } else {
        dc.DrawLine(pt(cx - 8.0, cy), pt(cx + 8.0, cy), &br, 3.0, None);
        dc.DrawLine(pt(cx, cy - 8.0), pt(cx, cy + 8.0), &br, 3.0, None);
    }
    dc.PopLayer();
}
fn paint() {
    let st = s();
    if !st.open {
        return;
    }
    let k = sc();
    let Some(dc) = ui::gpu_begin(&mut st.s, (st.w * k).round() as i32, (st.h * k).round() as i32, k) else { return };
    unsafe { paint_on(&dc) };
    ui::gpu_end(&mut st.s);
}
fn hide_now() {
    let st = s();
    ui::frame_clock(st.wnd, WM_DB_FRAME, false);
    unsafe {
        let _ = KillTimer(st.wnd, T_CLOCK);
        let _ = ShowWindow(st.wnd, SW_HIDE);
    }
    st.open = false;
    st.closing = false;
}
fn close() {
    let st = s();
    if !st.open || st.closing {
        return;
    }
    save_pos();
    st.closing = true;
    st.at = anim::now();
    ui::frame_clock(st.wnd, WM_DB_FRAME, true);
}
fn hit_widget(x: f32, y: f32) -> Option<usize> {
    (0..W_COUNT).rev().find(|&i| s().wd[i].on && in_rect(&wrect(i), x, y))
}
fn hit_key(x: f32, y: f32) -> Option<usize> {
    if !s().wd[W_CALC].on {
        return None;
    }
    (0..KEYS.len()).find(|&i| in_rect(&key_rect(wrect(W_CALC), i), x, y))
}
unsafe extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    let st = s();
    let k = sc();
    let (x, y) = (get_x_lparam(l) as f32 / k, get_y_lparam(l) as f32 / k);
    match m {
        WM_DB_FRAME => {
            ui::frame_ack(h, WM_DB_FRAME);
            paint();
            if anim::now() - st.at > 280.0 {
                if st.closing {
                    hide_now();
                } else {
                    ui::frame_clock(h, WM_DB_FRAME, false);
                }
            }
            LRESULT(0)
        }
        WM_TIMER => {
            if w_.0 == T_CLOCK {
                paint();
            }
            LRESULT(0)
        }
        WM_LBUTTONDOWN => {
            SetCapture(h);
            st.moved = false;
            if in_rect(&plus_rect(), x, y) {
                st.bar = !st.bar;
                paint();
                return LRESULT(0);
            }
            if st.bar && y >= st.h - BAR_H {
                for i in 0..W_COUNT {
                    if in_rect(&bar_item(i), x, y) {
                        st.wd[i].on = !st.wd[i].on;
                        save_pos();
                        paint();
                    }
                }
                return LRESULT(0);
            }
            if let Some(kk) = hit_key(x, y) {
                st.press = Some(kk);
                calc_key(KEYS[kk]);
                paint();
                return LRESULT(0);
            }
            if let Some(wi) = hit_widget(x, y) {
                st.drag = Some(wi);
                st.drag_off = pt(x - st.wd[wi].x, y - st.wd[wi].y);
                return LRESULT(0);
            }
            close(); // fora dos widgets: fecha, como no Mac
            LRESULT(0)
        }
        WM_MOUSEMOVE => {
            if let Some(d) = st.drag {
                if w_.0 & 1 != 0 {
                    // MK_LBUTTON
                    st.wd[d].x = (x - st.drag_off.x).clamp(0.0, st.w - st.wd[d].w);
                    st.wd[d].y = (y - st.drag_off.y).clamp(24.0, st.h - st.wd[d].h);
                    st.moved = true;
                    paint();
                }
            }
            LRESULT(0)
        }
        WM_LBUTTONUP => {
            let _ = ReleaseCapture();
            if st.press.take().is_some() {
                paint();
            }
            if st.drag.take().is_some() && st.moved {
                save_pos();
            }
            LRESULT(0)
        }
        WM_KEYDOWN => {
            let vk = VIRTUAL_KEY(w_.0 as u16);
            if vk == VK_ESCAPE || vk == VK_F12 {
                close();
                return LRESULT(0);
            }
            let shift = GetKeyState(VK_SHIFT.0 as i32) < 0;
            let v = vk.0;
            let kk: Option<String> = if (b'0' as u16..=b'9' as u16).contains(&v) && !shift {
                Some(((v as u8) as char).to_string())
            } else if (VK_NUMPAD0.0..=VK_NUMPAD9.0).contains(&v) {
                Some(((b'0' + (v - VK_NUMPAD0.0) as u8) as char).to_string())
            } else if vk == VK_ADD || (vk == VK_OEM_PLUS && shift) {
                Some("+".into())
            } else if vk == VK_SUBTRACT || vk == VK_OEM_MINUS {
                Some("−".into())
            } else if vk == VK_MULTIPLY {
                Some("×".into())
            } else if vk == VK_DIVIDE || vk == VK_OEM_2 {
                Some("÷".into())
            } else if vk == VK_RETURN || vk == VK_OEM_PLUS {
                Some("=".into())
            } else if vk == VK_DECIMAL || vk == VK_OEM_COMMA || vk == VK_OEM_PERIOD {
                Some(",".into())
            } else if vk == VK_BACK || vk == VK_DELETE {
                Some("C".into())
            } else {
                None
            };
            if let Some(kk) = kk {
                if st.wd[W_CALC].on {
                    calc_key(&kk);
                    paint();
                }
            }
            LRESULT(0)
        }
        WM_ACTIVATE => {
            if loword(w_.0) == WA_INACTIVE && st.open && !st.closing {
                close();
            }
            LRESULT(0)
        }
        WM_MOUSEACTIVATE => LRESULT(MA_ACTIVATE as isize),
        WM_CLOSE => {
            close(); // nunca destrói
            LRESULT(0)
        }
        _ => DefWindowProcW(h, m, w_, l),
    }
}
pub fn create(hi: HINSTANCE) -> bool {
    let st = s();
    unsafe {
        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hi, lpszClassName: w!("ShellDashboard"), hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), ..Default::default() });
        st.wnd = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP, w!("ShellDashboard"), w!("Dashboard"), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
    }
    if st.wnd.0.is_null() {
        return false;
    }
    apps::ours().push(st.wnd);
    st.s.hwnd = st.wnd;
    ui::gpu_soltar_escondida(&mut st.s); // escondido há 2 min: solta os buffers da tela cheia
    true
}
pub fn is_open() -> bool {
    s().open && !s().closing
}
pub fn toggle() {
    let st = s();
    if st.wnd.0.is_null() && !create(shell::inst()) {
        return;
    }
    if st.open && !st.closing {
        close();
        return;
    }
    unsafe {
        let mut c = POINT::default();
        let _ = GetCursorPos(&mut c);
        let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
        let _ = GetMonitorInfoW(MonitorFromPoint(c, MONITOR_DEFAULTTOPRIMARY), &mut mi);
        let r = mi.rcMonitor;
        let _ = SetWindowPos(st.wnd, HWND_TOPMOST, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOACTIVATE);
        let k = sc();
        st.w = (r.right - r.left) as f32 / k;
        st.h = (r.bottom - r.top) as f32 / k;
    }
    load_pos();
    st.open = true;
    st.closing = false;
    st.bar = false;
    st.at = anim::now();
    paint();
    unsafe {
        let _ = ShowWindow(st.wnd, SW_SHOW);
        let fg = GetForegroundWindow();
        let ft = if fg.0.is_null() { 0 } else { GetWindowThreadProcessId(fg, None) };
        let me = GetCurrentThreadId();
        let att = ft != 0 && ft != me && AttachThreadInput(me, ft, true).as_bool();
        let _ = SetForegroundWindow(st.wnd);
        let _ = SetFocus(st.wnd);
        if att {
            let _ = AttachThreadInput(me, ft, false);
        }
        SetTimer(st.wnd, T_CLOCK, 1000, None);
    }
    ui::frame_clock(st.wnd, WM_DB_FRAME, true);
}
/// modo foto: o Dashboard aberto (com `barra`, também a barra de widgets); a posição dos widgets é lida, nada é gravado
pub fn foto(tela_w: f32, tela_h: f32, barra: bool) {
    let st = s();
    st.foto = true;
    st.w = tela_w;
    st.h = tela_h;
    load_pos();
    st.open = true;
    st.bar = barra;
    st.disp = "1234,5".into();
    st.s.foto_pos = (0.0, 0.0);
    paint();
}