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
46.2 KB
Raw Blame
//! Relógio (src\relogio\main.cpp): Relógio Mundial, Alarmes, Cronômetro e Timer.
//! Dados em %APPDATA%\Shell\relogio.txt (o mesmo arquivo; quem toca os alarmes é o Shell).
#![windows_subsystem = "windows"]

use std::f64::consts::PI;

use comum::app2d::{self, *};
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct2D::Common::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
use comum::windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM;
use comum::windows::Win32::Media::Audio::*;
use comum::windows::Win32::System::LibraryLoader::*;
use comum::windows::Win32::System::SystemInformation::*;
use comum::windows::Win32::System::Time::*;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

static MAPA: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mapa.bin"));
const MAPA_W: u32 = 768;
const MAPA_H: u32 = 375;
const MAPA_LAT_BAIXO: f64 = -85.957;

const WM_FIELDLOST: u32 = WM_APP + 77;
const WM_CITYFOUND: u32 = WM_APP + 8;

const CITIES: [(&str, &str); 34] = [
    ("São Paulo", "E. South America Standard Time"),
    ("Rio de Janeiro", "E. South America Standard Time"),
    ("Manaus", "SA Western Standard Time"),
    ("Fortaleza", "SA Eastern Standard Time"),
    ("Lisboa", "GMT Standard Time"),
    ("Londres", "GMT Standard Time"),
    ("Paris", "Romance Standard Time"),
    ("Berlim", "W. Europe Standard Time"),
    ("Madri", "Romance Standard Time"),
    ("Roma", "W. Europe Standard Time"),
    ("Atenas", "GTB Standard Time"),
    ("Istambul", "Turkey Standard Time"),
    ("Moscou", "Russian Standard Time"),
    ("Dubai", "Arabian Standard Time"),
    ("Mumbai", "India Standard Time"),
    ("Singapura", "Singapore Standard Time"),
    ("Pequim", "China Standard Time"),
    ("Tóquio", "Tokyo Standard Time"),
    ("Seul", "Korea Standard Time"),
    ("Sydney", "AUS Eastern Standard Time"),
    ("Auckland", "New Zealand Standard Time"),
    ("Honolulu", "Hawaiian Standard Time"),
    ("Los Angeles", "Pacific Standard Time"),
    ("Denver", "Mountain Standard Time"),
    ("Chicago", "Central Standard Time"),
    ("Nova York", "Eastern Standard Time"),
    ("Cidade do México", "Central Standard Time (Mexico)"),
    ("Bogotá", "SA Pacific Standard Time"),
    ("Buenos Aires", "Argentina Standard Time"),
    ("Santiago", "Pacific SA Standard Time"),
    ("Joanesburgo", "South Africa Standard Time"),
    ("Cairo", "Egypt Standard Time"),
    ("Nairóbi", "E. Africa Standard Time"),
    ("UTC", "UTC"),
];
const COORDS: [(f64, f64); 34] = [
    (-23.55, -46.63), (-22.91, -43.17), (-3.12, -60.02), (-3.73, -38.53), (38.72, -9.14), (51.51, -0.13), (48.86, 2.35),
    (52.52, 13.40), (40.42, -3.70), (41.90, 12.50), (37.98, 23.73), (41.01, 28.98), (55.76, 37.62), (25.20, 55.27), (19.08, 72.88),
    (1.35, 103.82), (39.90, 116.41), (35.68, 139.69), (37.57, 126.98), (-33.87, 151.21), (-36.85, 174.76), (21.31, -157.86),
    (34.05, -118.24), (39.74, -104.99), (41.88, -87.63), (40.71, -74.01), (19.43, -99.13), (4.71, -74.07), (-34.60, -58.38),
    (-33.45, -70.67), (-26.20, 28.05), (30.04, 31.24), (-1.29, 36.82), (51.48, 0.0),
];
const CUSTOM0: i32 = 1000;

#[derive(Clone)]
struct Custom {
    name: String,
    tz: String,
}
#[derive(Clone)]
struct Alarm {
    id: i32,
    hh: i32,
    mm: i32,
    on: bool,
    label: String,
    days: i32,
}

#[derive(Clone, Copy, PartialEq)]
enum H {
    Tab,
    Add,
    World,
    Alarm,
    AlarmTime,
    Switch,
    SwA,
    SwB,
    TmPreset,
    TmMinus,
    TmPlus,
    TmA,
    TmB,
}
#[derive(Clone, Copy)]
struct Hit {
    kind: H,
    arg: i32,
    r: RectF,
}

#[derive(Default)]
struct App {
    tb: f32,
    tab: i32,
    custom: Vec<Custom>,
    world: Vec<i32>,
    tz_cache: Vec<(String, DYNAMIC_TIME_ZONE_INFORMATION)>,
    tz_missing: Vec<String>,
    alarms: Vec<Alarm>,
    next_id: i32,
    file: std::path::PathBuf,
    sw_run: bool,
    sw_start: u64,
    sw_acc: u64,
    laps: Vec<u64>,
    tm_min: i32,
    tm_run: bool,
    tm_paused: bool,
    tm_end: u64,
    tm_left: u64,
    hits: Vec<Hit>,
    map: Option<(usize, ID2D1Bitmap)>,
    tf: Vec<IDWriteTextFormat>,
    last_alarm_min: i32,
    tick_n: u32,
}
static A: Global<Option<App>> = Global::new(None);
fn a() -> &'static mut App {
    A.get().as_mut().unwrap()
}
// índices em a().tf
const SEG: usize = 0;
const BIG: usize = 1;
const BIGR: usize = 2;
const HUGE: usize = 3;
const ROW: usize = 4;
const SUB: usize = 5;
const BTN: usize = 6;
const ICON: usize = 7;
const MONO: usize = 8;
const CITYB: usize = 9;
const CITYT: usize = 10;
const DIAL: usize = 11;
const CARD: usize = 12;
const CARDSUB: usize = 13;
const CARDSUBL: usize = 14;
fn tf(i: usize) -> &'static IDWriteTextFormat {
    &a().tf[i]
}

fn city_tz(i: i32) -> String {
    if i >= CUSTOM0 {
        a().custom[(i - CUSTOM0) as usize].tz.clone()
    } else {
        CITIES[i as usize].1.into()
    }
}
fn city_name(i: i32) -> String {
    if i >= CUSTOM0 {
        a().custom[(i - CUSTOM0) as usize].name.clone()
    } else {
        tr(CITIES[i as usize].0)
    }
}
fn tz_info(nome: &str) -> Option<DYNAMIC_TIME_ZONE_INFORMATION> {
    if let Some((_, d)) = a().tz_cache.iter().find(|c| c.0 == nome) {
        return Some(*d);
    }
    if a().tz_missing.iter().any(|m| m == nome) {
        return None;
    }
    let mut k = 0;
    loop {
        let mut d = DYNAMIC_TIME_ZONE_INFORMATION::default();
        if unsafe { EnumDynamicTimeZoneInformation(k, &mut d) } != 0 {
            break;
        }
        if from_w(&d.TimeZoneKeyName) == nome {
            a().tz_cache.push((nome.into(), d));
            return Some(d);
        }
        k += 1;
    }
    a().tz_missing.push(nome.into());
    None
}
fn city_time(i: i32) -> Option<SYSTEMTIME> {
    let d = tz_info(&city_tz(i))?;
    unsafe {
        let utc = GetSystemTime();
        let mut out = SYSTEMTIME::default();
        SystemTimeToTzSpecificLocalTimeEx(Some(&d), &utc, &mut out).ok()?;
        Some(out)
    }
}
fn ft(st: &SYSTEMTIME) -> i64 {
    let mut f = FILETIME::default();
    unsafe {
        let _ = SystemTimeToFileTime(st, &mut f);
    }
    ((f.dwHighDateTime as i64) << 32) | f.dwLowDateTime as i64
}

fn save() {
    let a = a();
    let mut out = vec!["# Relógio do WacOS: W = cidade do Relógio Mundial, C = cidade própria (nome, fuso do Windows), A = alarme (id, hora, minuto, ligado, nome, dias)".to_string()];
    for c in &a.custom {
        out.push(format!("C\t{}\t{}", esc(&c.name), c.tz));
    }
    for i in &a.world {
        out.push(format!("W\t{i}"));
    }
    for x in &a.alarms {
        out.push(format!("A\t{}\t{}\t{}\t{}\t{}\t{}", x.id, x.hh, x.mm, if x.on { 1 } else { 0 }, esc(&x.label), x.days));
    }
    write_lines(&a.file, &out);
}
fn load() {
    let a = a();
    a.world.clear();
    a.alarms.clear();
    a.custom.clear();
    let mut any = false;
    let lines = read_lines(&a.file);
    for l in &lines {
        let f = split(l);
        if f.len() >= 3 && f[0] == "C" {
            a.custom.push(Custom { name: unesc(&f[1]), tz: f[2].clone() });
        }
    }
    for l in &lines {
        let f = split(l);
        let n = |i: usize| f[i].parse::<i32>().unwrap_or(0);
        if f.len() >= 2 && f[0] == "W" {
            let i = n(1);
            if (0..CITIES.len() as i32).contains(&i) || (i >= CUSTOM0 && ((i - CUSTOM0) as usize) < a.custom.len()) {
                a.world.push(i);
            }
            any = true;
        } else if f.len() >= 7 && f[0] == "A" {
            a.alarms.push(Alarm { id: n(1), hh: n(2), mm: n(3), on: f[4] == "1", label: unesc(&f[5]), days: n(6) });
        }
    }
    if !any && a.world.is_empty() {
        a.world = vec![0, 5, 25, 17];
    }
    for x in &a.alarms {
        a.next_id = a.next_id.max(x.id + 1);
    }
}

fn tick64() -> u64 {
    unsafe { GetTickCount64() }
}
fn sw_now() -> u64 {
    a().sw_acc + if a().sw_run { tick64() - a().sw_start } else { 0 }
}
fn fmt_time(ms: u64, cs: bool) -> String {
    let s = ms / 1000;
    if s >= 3600 {
        format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
    } else if cs {
        format!("{:02}:{:02},{:02}", s / 60, s % 60, ms / 10 % 100)
    } else {
        format!("{:02}:{:02}", s / 60, s % 60)
    }
}
fn tm_left() -> u64 {
    let a = a();
    if !a.tm_run {
        return a.tm_min as u64 * 60000;
    }
    if a.tm_paused {
        return a.tm_left;
    }
    a.tm_end.saturating_sub(tick64())
}

fn hit(kind: H, arg: i32, r: RectF) {
    a().hits.push(Hit { kind, arg, r });
}
fn button(r: RectF, t: &str, bg: Cor, fg: Cor, kind: H, arg: i32) {
    fill(r, bg, (r.bottom - r.top) / 2.0);
    text(t, tf(BTN), r, fg);
    hit(kind, arg, r);
}

fn map_bitmap() -> Option<ID2D1Bitmap> {
    let rt_id = app2d::rt().as_raw() as usize;
    if let Some((id, b)) = &a().map {
        if *id == rt_id {
            return Some(b.clone());
        }
    }
    let mut px = vec![0u8; (MAPA_W * MAPA_H * 4) as usize];
    for y in 0..MAPA_H {
        for x in 0..MAPA_W {
            if MAPA[(y * (MAPA_W / 8) + x / 8) as usize] & (0x80 >> (x % 8)) != 0 {
                let p = ((y * MAPA_W + x) * 4) as usize;
                px[p] = 63;
                px[p + 1] = 63;
                px[p + 2] = 63;
                px[p + 3] = 255;
            }
        }
    }
    let bp = D2D1_BITMAP_PROPERTIES { pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED }, dpiX: 0.0, dpiY: 0.0 };
    let b = unsafe { app2d::rt().CreateBitmap(D2D_SIZE_U { width: MAPA_W, height: MAPA_H }, Some(px.as_ptr() as *const _), MAPA_W * 4, &bp).ok()? };
    a().map = Some((rt_id, b.clone()));
    Some(b)
}

fn dia_do_ano(u: &SYSTEMTIME) -> f64 {
    let j = SYSTEMTIME { wYear: u.wYear, wMonth: 1, wDay: 1, ..Default::default() };
    (ft(u) - ft(&j)) as f64 / 864e9
}
fn sub_solar() -> (f64, f64) {
    let u = unsafe { GetSystemTime() };
    let day = dia_do_ano(&u);
    let decl = 23.44 * (2.0 * PI * (284.0 + day) / 365.0).sin();
    let h = u.wHour as f64 + u.wMinute as f64 / 60.0 + u.wSecond as f64 / 3600.0;
    (decl, -15.0 * (h - 12.0))
}
fn sun_times(lat: f64, lon: f64, off_h: f64) -> Option<(f64, f64)> {
    let u = unsafe { GetSystemTime() };
    let n = dia_do_ano(&u) + 1.0;
    let decl = 23.44 * (2.0 * PI * (284.0 + n) / 365.0).sin() * PI / 180.0;
    let b = 2.0 * PI * (n - 81.0) / 364.0;
    let eot = 9.87 * (2.0 * b).sin() - 7.53 * b.cos() - 1.5 * b.sin();
    let c = ((-0.83 * PI / 180.0).sin() - (lat * PI / 180.0).sin() * decl.sin()) / ((lat * PI / 180.0).cos() * decl.cos());
    if !(-1.0..=1.0).contains(&c) {
        return None;
    }
    let h0 = c.acos() * 180.0 / PI / 15.0;
    let noon = 12.0 - lon / 15.0 - eot / 60.0 + off_h;
    Some(((noon - h0 + 48.0) % 24.0, (noon + h0 + 48.0) % 24.0))
}
fn diff_texto(t: &SYSTEMTIME, here: &SYSTEMTIME) -> (String, String) {
    let diff_min = (ft(t) - ft(here)) / 600000000;
    let dh = (diff_min + if diff_min >= 0 { 15 } else { -15 }) / 30;
    let day = if t.wDay == here.wDay {
        tr("Hoje")
    } else if diff_min > 0 {
        tr("Amanhã")
    } else {
        tr("Ontem")
    };
    let off = if dh == 0 {
        String::new()
    } else if dh % 2 != 0 {
        format!(", {:+} h 30", dh / 2)
    } else {
        format!(", {:+} h", dh / 2)
    };
    (day, off)
}

fn paint_world_golden(sz: D2D_SIZE_F, dark: bool) {
    let map_h = sz.width * MAPA_H as f32 / MAPA_W as f32;
    let top = a().tb;
    fill(rf(0.0, top, sz.width, top + map_h), rgb(0, 0, 0, 1.0), 0.0);
    unsafe {
        if let Some(b) = map_bitmap() {
            app2d::rt().DrawBitmap(&b, Some(&rf(0.0, top, sz.width, top + map_h)), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
        }
    }
    let xf = |lon: f64| ((lon + 180.0) / 360.0 * sz.width as f64) as f32;
    let yf = |lat: f64| (top as f64 + (90.0 - lat) / (90.0 - MAPA_LAT_BAIXO) * map_h as f64) as f32;
    for k in 1..24 {
        let x = k as f32 * sz.width / 24.0;
        fill(rf(x, top, x + 0.5, top + map_h), rgb(255, 255, 255, 0.06), 0.0);
    }
    let (mut decl, slon) = sub_solar();
    if decl.abs() < 0.1 {
        decl = if decl < 0.0 { -0.1 } else { 0.1 };
    }
    unsafe {
        if let (Ok(g), Ok(line)) = (d2d().CreatePathGeometry(), d2d().CreatePathGeometry()) {
            if let (Ok(s), Ok(ls)) = (g.Open(), line.Open()) {
                let north_lit = decl > 0.0;
                let edge = if north_lit { top + map_h } else { top };
                let n = 180;
                for i in 0..=n {
                    let lon = -180.0 + 360.0 * i as f64 / n as f64;
                    let hh = (lon - slon) * PI / 180.0;
                    let lat = (-hh.cos() / (decl * PI / 180.0).tan()).atan() * 180.0 / PI;
                    let p = pt(xf(lon), yf(lat).clamp(top, top + map_h));
                    if i == 0 {
                        s.BeginFigure(pt(p.x, edge), D2D1_FIGURE_BEGIN_FILLED);
                        ls.BeginFigure(p, D2D1_FIGURE_BEGIN_HOLLOW);
                    }
                    s.AddLine(p);
                    if i > 0 {
                        ls.AddLine(p);
                    }
                }
                s.AddLine(pt(sz.width, edge));
                s.EndFigure(D2D1_FIGURE_END_CLOSED);
                ls.EndFigure(D2D1_FIGURE_END_OPEN);
                let _ = s.Close();
                let _ = ls.Close();
                push_clip(rf(0.0, top, sz.width, top + map_h));
                br().SetColor(&rgb(0, 0, 0, 0.6));
                app2d::rt().FillGeometry(&g, br(), None);
                br().SetColor(&rgb(255, 255, 255, 0.55));
                app2d::rt().DrawGeometry(&line, br(), 1.0, None);
                pop_clip();
            }
        }
    }
    let world = a().world.clone();
    for &i in &world {
        if i < 0 || i as usize >= COORDS.len() {
            continue;
        }
        let Some(t) = city_time(i) else { continue };
        let (x, y) = (xf(COORDS[i as usize].1), yf(COORDS[i as usize].0));
        circle(pt(x, y), 4.2, rgb(255, 255, 255, 0.9), true, 1.5);
        circle(pt(x, y), 3.2, rgb(255, 149, 0, 1.0), true, 1.5);
        text(&city_name(i), tf(CITYB), rf(x + 7.0, y - 9.0, x + 160.0, y + 5.0), rgb(255, 255, 255, 1.0));
        text(&format!("{}:{:02}", t.wHour, t.wMinute), tf(CITYT), rf(x + 7.0, y + 4.0, x + 160.0, y + 15.0), rgb(255, 255, 255, 0.85));
    }
    let here = local_now();
    let cy0 = top + map_h + 14.0;
    for (k, &i) in world.iter().enumerate() {
        let Some(t) = city_time(i) else { continue };
        let x0 = 14.0 + k as f32 * 184.0;
        if x0 + 170.0 > sz.width {
            break;
        }
        let card = rf(x0, cy0, x0 + 170.0, cy0 + 196.0);
        fill(card, if dark { rgb(255, 255, 255, 0.08) } else { rgb(0, 0, 0, 0.05) }, 12.0);
        let day = t.wHour >= 6 && t.wHour < 18;
        let c = pt(x0 + 85.0, cy0 + 72.0);
        circle(c, 55.0, if day { rgb(255, 255, 255, 1.0) } else { rgb(0, 0, 0, 1.0) }, true, 1.5);
        if !day {
            circle(c, 55.0, rgb(255, 255, 255, 0.25), false, 0.75);
        }
        let ink = if day { rgb(0, 0, 0, 1.0) } else { rgb(255, 255, 255, 1.0) };
        for n in 1..=12 {
            let an = n as f64 * PI / 6.0;
            let (nx, ny) = (c.x + an.sin() as f32 * 43.0, c.y - an.cos() as f32 * 43.0);
            text(&n.to_string(), tf(DIAL), rf(nx - 10.0, ny - 8.0, nx + 10.0, ny + 8.0), ink);
        }
        let hm = (t.wHour as f64 % 12.0 + t.wMinute as f64 / 60.0) * PI / 6.0;
        let mm = (t.wMinute as f64 + t.wSecond as f64 / 60.0) * PI / 30.0;
        let ss = t.wSecond as f64 * PI / 30.0;
        let ponta = |a_: f64, r: f32| pt(c.x + a_.sin() as f32 * r, c.y - a_.cos() as f32 * r);
        line(c, ponta(hm, 26.0), ink, 3.2);
        line(c, ponta(mm, 40.0), ink, 2.4);
        line(pt(c.x - ss.sin() as f32 * 8.0, c.y + ss.cos() as f32 * 8.0), ponta(ss, 46.0), rgb(255, 149, 0, 1.0), 1.0);
        circle(c, 3.0, rgb(255, 149, 0, 1.0), true, 1.5);
        circle(c, 1.4, if day { rgb(255, 255, 255, 1.0) } else { rgb(0, 0, 0, 1.0) }, true, 1.5);
        let txt = if dark { rgb(245, 245, 247, 1.0) } else { rgb(29, 29, 31, 1.0) };
        let gray = if dark { rgb(152, 152, 157, 1.0) } else { rgb(134, 134, 139, 1.0) };
        text(&format!("{}, {}:{:02}", city_name(i), t.wHour, t.wMinute), tf(CARD), rf(x0 + 6.0, cy0 + 136.0, x0 + 164.0, cy0 + 154.0), txt);
        let (d, off) = diff_texto(&t, &here);
        text(&(d + &off), tf(CARDSUB), rf(x0 + 6.0, cy0 + 154.0, x0 + 164.0, cy0 + 170.0), gray);
        // nascer e pôr do sol
        let ut = unsafe { GetSystemTime() };
        let off_h = ((ft(&t) - ft(&ut)) as f64 / 36e9 * 4.0).round() / 4.0;
        if (i as usize) < COORDS.len() {
            if let Some((rise, set)) = sun_times(COORDS[i as usize].0, COORDS[i as usize].1, off_h) {
                let hm2 = |h: f64| {
                    let m = ((h * 60.0).round() as i64).rem_euclid(1440);
                    format!("{}:{:02}", m / 60, m % 60)
                };
                let (a1, a2) = (hm2(rise), hm2(set));
                let (w1, w2) = (text_w(tf(CARDSUB), &a1), text_w(tf(CARDSUB), &a2));
                let (gap, iw) = (14.0, 12.0);
                let total = iw + 3.0 + w1 + gap + iw + 3.0 + w2;
                let sx = x0 + 85.0 - total / 2.0;
                let yy = cy0 + 178.0;
                let sun = |x: f32, up: bool| unsafe {
                    br().SetColor(&gray);
                    let r = app2d::rt();
                    r.DrawLine(pt(x, yy + 4.0), pt(x + iw, yy + 4.0), br(), 1.1, None);
                    push_clip(rf(x - 1.0, yy - 1.0, x + iw + 1.0, yy + 4.0));
                    r.DrawEllipse(&ell(pt(x + iw / 2.0, yy + 4.0), 3.0, 3.0), br(), 1.1, None);
                    pop_clip();
                    let (ax, ay0, ay1) = (x + iw / 2.0, yy - 4.5, yy - 1.0);
                    if up {
                        r.DrawLine(pt(ax, ay1), pt(ax, ay0), br(), 1.0, None);
                        r.DrawLine(pt(ax - 1.8, ay0 + 1.8), pt(ax, ay0), br(), 1.0, None);
                        r.DrawLine(pt(ax + 1.8, ay0 + 1.8), pt(ax, ay0), br(), 1.0, None);
                    } else {
                        r.DrawLine(pt(ax, ay0), pt(ax, ay1), br(), 1.0, None);
                        r.DrawLine(pt(ax - 1.8, ay1 - 1.8), pt(ax, ay1), br(), 1.0, None);
                        r.DrawLine(pt(ax + 1.8, ay1 - 1.8), pt(ax, ay1), br(), 1.0, None);
                    }
                };
                sun(sx, true);
                text(&a1, tf(CARDSUBL), rf(sx + iw + 3.0, yy - 8.0, sx + iw + 3.0 + w1 + 2.0, yy + 8.0), gray);
                let sx2 = sx + iw + 3.0 + w1 + gap;
                sun(sx2, false);
                text(&a2, tf(CARDSUBL), rf(sx2 + iw + 3.0, yy - 8.0, sx2 + iw + 3.0 + w2 + 2.0, yy + 8.0), gray);
            }
        }
        hit(H::World, k as i32, card);
    }
}

const TABS: [&str; 4] = ["Relógio Mundial", "Alarmes", "Cronômetro", "Timer"];

fn paint_tabs_golden(sz: D2D_SIZE_F, dark: bool) {
    let txt = if dark { rgb(245, 245, 247, 1.0) } else { rgb(29, 29, 31, 1.0) };
    let mut ws = [0f32; 4];
    let mut total = 8.0;
    for i in 0..4 {
        ws[i] = text_w(tf(SEG), &tr(TABS[i])) + 34.0;
        total += ws[i];
    }
    let seg = rf(sz.width / 2.0 - total / 2.0, 10.0, sz.width / 2.0 + total / 2.0, 42.0);
    glass_button(seg, dark, false);
    bar_button(seg);
    let mut x = seg.left + 4.0;
    for i in 0..4 {
        let r = rf(x, seg.top + 3.0, x + ws[i], seg.bottom - 3.0);
        if a().tab == i as i32 {
            fill(r, if dark { rgb(255, 255, 255, 0.14) } else { rgb(0, 0, 0, 0.08) }, 13.0);
        }
        text(&tr(TABS[i]), tf(SEG), r, txt);
        hit(H::Tab, i as i32, r);
        x += ws[i];
    }
    if a().tab <= 1 {
        let add = rf(sz.width - 8.0 - 36.0, 8.0, sz.width - 8.0, 44.0);
        glass_button(add, dark, false);
        icon_plus(pt((add.left + add.right) / 2.0, 26.0), txt, 7.0);
        hit(H::Add, 0, add);
        bar_button(add);
    }
}

fn paint() {
    if !begin_paint() {
        return;
    }
    a().hits.clear();
    let dark = dark();
    let sz = size();
    let txt = if dark { rgb(245, 245, 247, 1.0) } else { rgb(29, 29, 31, 1.0) };
    let gray = if dark { rgb(152, 152, 157, 1.0) } else { rgb(134, 134, 139, 1.0) };
    let linha = if dark { rgb(255, 255, 255, 0.10) } else { rgb(0, 0, 0, 0.10) };
    let neutro = if dark { rgb(58, 58, 60, 1.0) } else { rgb(229, 229, 234, 1.0) };
    clear(if dark { rgb(30, 30, 30, 1.0) } else { rgb(255, 255, 255, 1.0) });
    let gg = bar() > 0.0;
    let tb = a().tb;
    if gg {
        paint_tabs_golden(sz, dark);
    } else {
        let seg_w = 120.0;
        let sx = sz.width / 2.0 - seg_w * 2.0;
        fill(rf(sx, 14.0, sx + seg_w * 4.0, 40.0), if dark { rgb(58, 58, 60, 1.0) } else { rgb(232, 232, 237, 1.0) }, 7.0);
        for i in 0..4 {
            let r = rf(sx + i as f32 * seg_w + 2.0, 16.0, sx + (i + 1) as f32 * seg_w - 2.0, 38.0);
            if a().tab == i {
                fill(r, if dark { rgb(99, 99, 102, 1.0) } else { rgb(255, 255, 255, 1.0) }, 6.0);
            }
            text(&tr(TABS[i as usize]), tf(SEG), r, txt);
            hit(H::Tab, i, r);
        }
        if a().tab <= 1 {
            let add = rf(sz.width - 46.0, 12.0, sz.width - 14.0, 42.0);
            text("\u{E710}", tf(ICON), add, txt);
            hit(H::Add, 0, add);
        }
    }
    fill(rf(0.0, tb - 1.0, sz.width, tb), linha, 0.0);
    let (x, w_) = (28.0, sz.width - 28.0);
    match a().tab {
        0 if gg => paint_world_golden(sz, dark),
        0 => {
            let here = local_now();
            let mut y = tb + 8.0;
            for (k, &i) in a().world.clone().iter().enumerate() {
                let Some(t) = city_time(i) else { continue };
                let (day, off) = diff_texto(&t, &here);
                let row = rf(x, y, w_, y + 74.0);
                text(&(day + &off), tf(SUB), rf(x, y + 10.0, w_ - 200.0, y + 30.0), gray);
                text(&city_name(i), tf(ROW), rf(x, y + 30.0, w_ - 200.0, y + 60.0), txt);
                text(&format!("{}:{:02}", t.wHour, t.wMinute), tf(BIGR), rf(w_ - 220.0, y, w_, y + 74.0), txt);
                fill(rf(x, y + 74.0, w_, y + 75.0), linha, 0.0);
                hit(H::World, k as i32, row);
                y += 75.0;
            }
        }
        1 => {
            let mut y = tb + 8.0;
            if a().alarms.is_empty() {
                text(&tr("Nenhum Alarme"), tf(ROW), rf(0.0, tb, sz.width, sz.height * 0.6), gray);
            }
            for (k, al) in a().alarms.clone().iter().enumerate() {
                let k = k as i32;
                let trr = rf(x, y, x + 220.0, y + 60.0);
                text(&format!("{}:{:02}", al.hh, al.mm), tf(BIG), trr, if al.on { txt } else { gray });
                let mut sub = if al.label.is_empty() { tr("Alarme") } else { al.label.clone() };
                match al.days {
                    0x7F => sub += &format!(", {}", tr("todos os dias")),
                    0x3E => sub += &format!(", {}", tr("dias de semana")),
                    0x41 => sub += &format!(", {}", tr("fins de semana")),
                    _ => {}
                }
                text(&sub, tf(SUB), rf(x, y + 56.0, w_ - 100.0, y + 76.0), gray);
                hit(H::AlarmTime, k, trr);
                let sw = rf(w_ - 60.0, y + 26.0, w_ - 10.0, y + 54.0);
                fill(sw, if al.on { rgb(48, 209, 88, 1.0) } else if dark { rgb(72, 72, 74, 1.0) } else { rgb(229, 229, 234, 1.0) }, 14.0);
                circle(pt(if al.on { sw.right - 14.0 } else { sw.left + 14.0 }, (sw.top + sw.bottom) / 2.0), 12.0, rgb(255, 255, 255, 1.0), true, 1.5);
                hit(H::Switch, k, sw);
                hit(H::Alarm, k, rf(x, y, w_ - 70.0, y + 84.0));
                fill(rf(x, y + 84.0, w_, y + 85.0), linha, 0.0);
                y += 86.0;
            }
        }
        2 => {
            let now = sw_now();
            text(&fmt_time(now, true), tf(HUGE), rf(0.0, tb + 20.0, sz.width, tb + 150.0), txt);
            let (by, cx) = (tb + 170.0, sz.width / 2.0);
            let running = a().sw_run;
            button(rf(cx - 190.0, by, cx - 30.0, by + 44.0), &if running { tr("Volta") } else { tr("Zerar") }, neutro, txt, H::SwA, 0);
            let (cb, cf_) = if running { (rgb(255, 69, 58, 0.25), rgb(255, 69, 58, 1.0)) } else { (rgb(48, 209, 88, 0.25), rgb(48, 209, 88, 1.0)) };
            button(rf(cx + 30.0, by, cx + 190.0, by + 44.0), &if running { tr("Parar") } else { tr("Iniciar") }, cb, cf_, H::SwB, 0);
            let g_laps = a().laps.clone();
            let mut laps = g_laps.clone();
            let done: u64 = g_laps.iter().sum();
            if now > 0 || !laps.is_empty() {
                laps.push(now - done);
            }
            let (mut best, mut worst) = (-1i32, -1i32);
            if g_laps.len() >= 2 {
                for i in 0..g_laps.len() as i32 {
                    if best < 0 || g_laps[i as usize] < g_laps[best as usize] {
                        best = i;
                    }
                    if worst < 0 || g_laps[i as usize] > g_laps[worst as usize] {
                        worst = i;
                    }
                }
            }
            let mut y = by + 70.0;
            let mut i = laps.len() as i32 - 1;
            while i >= 0 && y < sz.height - 20.0 {
                let c = if i == best {
                    rgb(48, 209, 88, 1.0)
                } else if i == worst {
                    rgb(255, 69, 58, 1.0)
                } else {
                    txt
                };
                text(&cf!(tr("Volta %d"), i + 1), tf(ROW), rf(x + 60.0, y, w_, y + 34.0), c);
                text(&fmt_time(laps[i as usize], true), tf(MONO), rf(x, y, w_ - 60.0, y + 34.0), c);
                fill(rf(x + 60.0, y + 34.0, w_ - 60.0, y + 35.0), linha, 0.0);
                y += 35.0;
                i -= 1;
            }
        }
        _ => {
            let left = tm_left();
            let (run, paused) = (a().tm_run, a().tm_paused);
            text(&fmt_time(left + 999, false), tf(HUGE), rf(0.0, tb + 20.0, sz.width, tb + 150.0), if run && !paused { rgb(255, 159, 10, 1.0) } else { txt });
            let cx = sz.width / 2.0;
            let mut y = tb + 160.0;
            if !run {
                let presets = [1, 3, 5, 10, 15, 30, 60];
                let pw = 64.0;
                let px = cx - pw * 3.5 - 9.0;
                for (i, &p) in presets.iter().enumerate() {
                    let r = rf(px + i as f32 * (pw + 3.0), y, px + i as f32 * (pw + 3.0) + pw, y + 34.0);
                    let on = a().tm_min == p;
                    let b = if p >= 60 { format!("{} h", p / 60) } else { format!("{p} min") };
                    fill(r, if on { rgb(255, 159, 10, 0.3) } else { neutro }, 8.0);
                    text(&b, tf(BTN), r, if on { rgb(255, 159, 10, 1.0) } else { txt });
                    hit(H::TmPreset, p, r);
                }
                button(rf(cx - 90.0, y + 50.0, cx - 50.0, y + 84.0), "−", neutro, txt, H::TmMinus, 0);
                button(rf(cx + 50.0, y + 50.0, cx + 90.0, y + 84.0), "+", neutro, txt, H::TmPlus, 0);
                text(&format!("{} min", a().tm_min), tf(ROW), rf(cx - 50.0, y + 50.0, cx + 50.0, y + 84.0), txt);
                y += 110.0;
            }
            button(rf(cx - 190.0, y, cx - 30.0, y + 44.0), &tr("Cancelar"), neutro, if run { txt } else { gray }, H::TmA, 0);
            let b = if !run {
                tr("Iniciar")
            } else if paused {
                tr("Retomar")
            } else {
                tr("Pausar")
            };
            let (cb, cf_) = if run && !paused { (rgb(255, 159, 10, 0.25), rgb(255, 159, 10, 1.0)) } else { (rgb(48, 209, 88, 0.25), rgb(48, 209, 88, 1.0)) };
            button(rf(cx + 30.0, y, cx + 190.0, y + 44.0), &b, cb, cf_, H::TmB, 0);
        }
    }
    end_paint();
}

fn flash() {
    unsafe {
        let fw = FLASHWINFO { cbSize: std::mem::size_of::<FLASHWINFO>() as u32, hwnd: wnd(), dwFlags: FLASHW_ALL | FLASHW_TIMERNOFG, uCount: 6, dwTimeout: 0 };
        let _ = FlashWindowEx(&fw);
        let _ = PlaySoundW(w!("SystemExclamation"), None, SND_ALIAS | SND_ASYNC);
    }
}

fn check_alarms() {
    let t = local_now();
    let now = t.wHour as i32 * 60 + t.wMinute as i32;
    if now == a().last_alarm_min {
        return;
    }
    let first = a().last_alarm_min < 0;
    a().last_alarm_min = now;
    if first {
        return;
    }
    if find_window("ShellMensagens").is_some() {
        return; // o Shell toca
    }
    let mut changed = false;
    for k in 0..a().alarms.len() {
        let al = a().alarms[k].clone();
        if !al.on || al.hh != t.wHour as i32 || al.mm != t.wMinute as i32 {
            continue;
        }
        if al.days != 0 && al.days & (1 << t.wDayOfWeek) == 0 {
            continue;
        }
        if al.days == 0 {
            a().alarms[k].on = false;
            changed = true;
        }
        flash();
        if changed {
            save();
        }
        let msg = format!("{}\n{}:{:02}", if al.label.is_empty() { tr("Alarme") } else { al.label.clone() }, al.hh, al.mm);
        message_box(&msg, &tr("Relógio"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST);
    }
    if changed {
        save();
        invalidate();
    }
}

fn tick() {
    check_alarms();
    if a().tm_run && !a().tm_paused && tm_left() == 0 {
        a().tm_run = false;
        flash();
        unsafe {
            let _ = ShowWindow(wnd(), SW_RESTORE);
            let _ = SetForegroundWindow(wnd());
        }
        message_box(&tr("O timer terminou."), &tr("Relógio"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST);
    }
    a().tick_n += 1;
    if a().sw_run || (a().tm_run && !a().tm_paused) || a().tick_n % 20 == 0 {
        invalidate();
    }
}

/// Fuso IANA -> nome do fuso do Windows, pelo ICU do Windows (icu.dll)
fn windows_tz(iana: &str) -> String {
    unsafe {
        let Ok(icu) = LoadLibraryExW(w!("icu.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) else { return String::new() };
        let Some(f) = GetProcAddress(icu, s!("ucal_getWindowsTimeZoneID")) else { return String::new() };
        let f: unsafe extern "C" fn(*const u16, i32, *mut u16, i32, *mut i32) -> i32 = std::mem::transmute(f);
        let w_ = w(iana);
        let mut out = [0u16; 128];
        let mut st = 0i32;
        let n = f(w_.as_ptr(), w_.len() as i32, out.as_mut_ptr(), 127, &mut st);
        if st > 0 || n <= 0 {
            String::new()
        } else {
            String::from_utf16_lossy(&out[..n as usize])
        }
    }
}

fn find_city(q: String) {
    if q.is_empty() {
        return;
    }
    let h = wnd().0 as usize;
    std::thread::spawn(move || {
        let path = format!("/v1/search?count=1&language={}&name={}", idioma::code(), rede::url_encode(&q));
        let body = rede::get("geocoding-api.open-meteo.com", &path, "WacOS-Clock/1.0", 64 * 1024).unwrap_or_default();
        let body = String::from_utf8_lossy(&body).into_owned();
        let c = if body.contains("\"results\"") {
            Custom { name: rede::json_field(&body, "name"), tz: rede::json_field(&body, "timezone") }
        } else {
            Custom { name: String::new(), tz: String::new() }
        };
        let p = Box::into_raw(Box::new(c));
        unsafe {
            if PostMessageW(HWND(h as *mut _), WM_CITYFOUND, WPARAM(0), LPARAM(p as isize)).is_err() {
                drop(Box::from_raw(p));
            }
        }
    });
}
fn city_found(c: Box<Custom>) {
    let tz = if c.tz.is_empty() { String::new() } else { windows_tz(&c.tz) };
    if c.name.is_empty() || tz.is_empty() {
        message_box(&tr("Cidade não encontrada."), &tr("Relógio"), MB_OK | MB_ICONINFORMATION);
    } else {
        let a = a();
        let idx = match a.custom.iter().position(|x| x.name == c.name && x.tz == tz) {
            Some(i) => i,
            None => {
                a.custom.push(Custom { name: c.name.clone(), tz });
                a.custom.len() - 1
            }
        };
        let id = CUSTOM0 + idx as i32;
        if !a.world.contains(&id) {
            a.world.push(id);
        }
        save();
    }
    invalidate();
}
fn add_city(scr: POINT) {
    unsafe {
        let Ok(m) = CreatePopupMenu() else { return };
        append_menu(m, MF_STRING, 9999, &tr("Outra Cidade…"));
        let _ = AppendMenuW(m, MF_SEPARATOR, 0, PCWSTR::null());
        for (i, c) in CITIES.iter().enumerate() {
            append_menu(m, MF_STRING | if a().world.contains(&(i as i32)) { MF_CHECKED } else { MF_UNCHECKED }, i + 1, &tr(c.0));
        }
        let c = TrackPopupMenu(m, TPM_RETURNCMD, scr.x, scr.y, 0, wnd(), None).0;
        let _ = DestroyMenu(m);
        if c == 9999 {
            let sz = size();
            let tb = a().tb;
            field_open(rf(sz.width - 300.0, tb + 12.0, sz.width - 24.0, tb + 36.0), "", 14.0, false, |t, key| {
                if key == VK_RETURN.0 as i32 {
                    find_city(t);
                }
            });
            return;
        }
        if c > 0 && (c as usize) <= CITIES.len() && !a().world.contains(&(c - 1)) {
            a().world.push(c - 1);
            save();
        }
    }
}
fn parse_time(s: &str) -> Option<(i32, i32)> {
    let d: String = s.chars().filter(|c| c.is_ascii_digit()).collect();
    if d.is_empty() {
        return None;
    }
    let (hh, mm) = if d.len() <= 2 { (d.parse().ok()?, 0) } else { (d[..d.len() - 2].parse().ok()?, d[d.len() - 2..].parse().ok()?) };
    ((0..24).contains(&hh) && (0..60).contains(&mm)).then_some((hh, mm))
}
fn edit_alarm_time(k: i32) {
    let Some(h) = a().hits.iter().find(|h| h.kind == H::AlarmTime && h.arg == k).copied() else { return };
    let al = a().alarms[k as usize].clone();
    let id = al.id;
    field_open(rf(h.r.left, h.r.top + 10.0, h.r.left + 160.0, h.r.bottom - 10.0), &format!("{}:{:02}", al.hh, al.mm), 30.0, false, move |t, key| {
        if key == VK_ESCAPE.0 as i32 {
            return;
        }
        if let Some((hh, mm)) = parse_time(&t) {
            for x in a().alarms.iter_mut().filter(|x| x.id == id) {
                x.hh = hh;
                x.mm = mm;
                x.on = true;
            }
            save();
        }
    });
}
fn add_alarm() {
    let t = local_now();
    let id = a().next_id;
    a().next_id += 1;
    a().alarms.push(Alarm { id, hh: (t.wHour as i32 + 1) % 24, mm: 0, on: true, label: String::new(), days: 0 });
    save();
    paint();
    edit_alarm_time(a().alarms.len() as i32 - 1);
}
fn alarm_menu(k: i32, scr: POINT) {
    unsafe {
        let (Ok(m), Ok(rep)) = (CreatePopupMenu(), CreatePopupMenu()) else { return };
        let d = a().alarms[k as usize].days;
        let ck = |on: bool| if on { MF_CHECKED } else { MF_UNCHECKED };
        append_menu(rep, MF_STRING | ck(d == 0), 10, &tr("Nunca"));
        append_menu(rep, MF_STRING | ck(d == 0x7F), 11, &tr("Todos os Dias"));
        append_menu(rep, MF_STRING | ck(d == 0x3E), 12, &tr("Dias de Semana"));
        append_menu(rep, MF_STRING | ck(d == 0x41), 13, &tr("Fins de Semana"));
        append_menu(m, MF_STRING, 1, &tr("Editar Hora"));
        append_menu(m, MF_STRING, 2, &tr("Renomear"));
        append_menu(m, MF_POPUP, rep.0 as usize, &tr("Repetir"));
        let _ = AppendMenuW(m, MF_SEPARATOR, 0, PCWSTR::null());
        append_menu(m, MF_STRING, 3, &tr("Apagar"));
        let c = TrackPopupMenu(m, TPM_RETURNCMD | TPM_RIGHTBUTTON, scr.x, scr.y, 0, wnd(), None).0;
        let _ = DestroyMenu(m);
        match c {
            1 => edit_alarm_time(k),
            2 => {
                if let Some(h) = a().hits.iter().find(|h| h.kind == H::Alarm && h.arg == k).copied() {
                    let al = a().alarms[k as usize].clone();
                    let id = al.id;
                    field_open(rf(h.r.left, h.r.top + 56.0, h.r.right, h.r.top + 76.0), &al.label, 13.0, false, move |t, key| {
                        if key == VK_ESCAPE.0 as i32 {
                            return;
                        }
                        for x in a().alarms.iter_mut().filter(|x| x.id == id) {
                            x.label = t.clone();
                        }
                        save();
                    });
                }
            }
            3 => {
                a().alarms.remove(k as usize);
                save();
            }
            10..=13 => {
                a().alarms[k as usize].days = [0, 0x7F, 0x3E, 0x41][(c - 10) as usize];
                save();
            }
            _ => {}
        }
        invalidate();
    }
}
fn sw_toggle() {
    let a = a();
    if a.sw_run {
        a.sw_acc = sw_now();
        a.sw_run = false;
    } else {
        a.sw_start = tick64();
        a.sw_run = true;
    }
}

/// outra instância pedindo uma aba (a Central de Controle abre o Relógio na aba do controle, issue #99)
static MSG_ABA: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    unsafe {
        let ma = MSG_ABA.load(std::sync::atomic::Ordering::Relaxed);
        if ma != 0 && m == ma {
            if w_.0 <= 3 {
                a().tab = w_.0 as i32;
                let _ = comum::windows::Win32::Graphics::Gdi::InvalidateRect(h, None, false);
            }
            return LRESULT(0);
        }
        match m {
            WM_PAINT => return wm_paint(h, paint),
            WM_ERASEBKGND => return LRESULT(1),
            WM_SIZE => {
                on_size(l);
                return LRESULT(0);
            }
            WM_DPICHANGED => {
                on_dpi(w_, l);
                return LRESULT(0);
            }
            WM_SETTINGCHANGE => {
                invalidate();
                return LRESULT(0);
            }
            WM_TIMECHANGE => {
                a().tz_cache.clear();
                a().tz_missing.clear();
                invalidate();
                return LRESULT(0);
            }
            WM_CTLCOLOREDIT => return field_colors(comum::windows::Win32::Graphics::Gdi::HDC(w_.0 as *mut _), if dark() { colorref(30, 30, 30) } else { colorref(255, 255, 255) }),
            WM_FIELDLOST => {
                let fh = app2d::s().field.h;
                if !fh.0.is_null() && GetFocus() != fh {
                    field_close();
                }
                return LRESULT(0);
            }
            WM_TIMER => {
                tick();
                return LRESULT(0);
            }
            WM_CITYFOUND => {
                city_found(Box::from_raw(l.0 as *mut Custom));
                return LRESULT(0);
            }
            WM_LBUTTONDOWN | WM_RBUTTONUP => {
                if !app2d::s().field.h.0.is_null() {
                    field_close();
                }
                let s_ = sc();
                let (x, y) = (get_x_lparam(l) as f32 / s_, get_y_lparam(l) as f32 / s_);
                let scr = to_screen(h, get_x_lparam(l), get_y_lparam(l));
                let right = m == WM_RBUTTONUP;
                for ht in a().hits.clone() {
                    if !in_rect(&ht.r, x, y) {
                        continue;
                    }
                    let a = a();
                    match ht.kind {
                        H::Tab => a.tab = ht.arg,
                        H::Add => {
                            if a.tab == 0 {
                                add_city(scr)
                            } else {
                                add_alarm()
                            }
                        }
                        H::World => {
                            if right {
                                if let Ok(mm) = CreatePopupMenu() {
                                    append_menu(mm, MF_STRING, 1, &tr("Apagar"));
                                    if TrackPopupMenu(mm, TPM_RETURNCMD | TPM_RIGHTBUTTON, scr.x, scr.y, 0, h, None).0 == 1 {
                                        a.world.remove(ht.arg as usize);
                                        save();
                                    }
                                    let _ = DestroyMenu(mm);
                                }
                            }
                        }
                        H::Switch => {
                            let al = &mut a.alarms[ht.arg as usize];
                            al.on = !al.on;
                            save();
                        }
                        H::AlarmTime => {
                            if right {
                                alarm_menu(ht.arg, scr)
                            } else {
                                edit_alarm_time(ht.arg)
                            }
                        }
                        H::Alarm => {
                            if right {
                                alarm_menu(ht.arg, scr)
                            } else {
                                continue;
                            }
                        }
                        H::SwA => {
                            if a.sw_run {
                                let done: u64 = a.laps.iter().sum();
                                let n = sw_now();
                                a.laps.push(n - done);
                            } else {
                                a.sw_acc = 0;
                                a.laps.clear();
                            }
                        }
                        H::SwB => sw_toggle(),
                        H::TmPreset => a.tm_min = ht.arg,
                        H::TmMinus => a.tm_min = (a.tm_min - 1).max(1),
                        H::TmPlus => a.tm_min = (a.tm_min + 1).min(24 * 60),
                        H::TmA => {
                            a.tm_run = false;
                            a.tm_paused = false;
                        }
                        H::TmB => {
                            if !a.tm_run {
                                a.tm_run = true;
                                a.tm_paused = false;
                                a.tm_end = tick64() + a.tm_min as u64 * 60000;
                            } else if a.tm_paused {
                                a.tm_paused = false;
                                a.tm_end = tick64() + a.tm_left;
                            } else {
                                a.tm_left = tm_left();
                                a.tm_paused = true;
                            }
                        }
                    }
                    invalidate();
                    return LRESULT(0);
                }
                return LRESULT(0);
            }
            WM_KEYDOWN => {
                let ctrl = key_down(VK_CONTROL.0);
                let k = w_.0 as u32;
                if ctrl && ('1' as u32..='4' as u32).contains(&k) {
                    a().tab = (k - '1' as u32) as i32;
                    invalidate();
                } else if ctrl && k == 'W' as u32 {
                    let _ = DestroyWindow(h);
                } else if k == VK_SPACE.0 as u32 && a().tab == 2 {
                    sw_toggle();
                    invalidate();
                }
                return LRESULT(0);
            }
            WM_DESTROY => {
                PostQuitMessage(0);
                return LRESULT(0);
            }
            _ => {}
        }
        DefWindowProcW(h, m, w_, l)
    }
}

fn main() {
    if !app2d::init() {
        std::process::exit(1);
    }
    *A.get() = Some(App { tb: 56.0, next_id: 1, tm_min: 5, file: data_path("relogio.txt"), last_alarm_min: -1, ..Default::default() });
    if let Some(p) = arg_valor("--dados") {
        a().file = p.into();
    }
    if let Some(t) = arg_valor("--aba") {
        a().tab = t.parse().unwrap_or(0);
    }
    // a aba pode vir na linha de comando, por nome: alarme, cronometro ou temporizador (issue #99)
    let cmd: String = std::env::args().skip(1).collect::<Vec<_>>().join(" ").to_lowercase();
    let aba = if cmd.contains("alarme") {
        1
    } else if cmd.contains("cronometro") || cmd.contains("cronômetro") {
        2
    } else if cmd.contains("temporizador") || cmd.contains("timer") {
        3
    } else {
        -1
    };
    if aba >= 0 {
        a().tab = aba;
    }
    MSG_ABA.store(reg_msg("WacOSRelogioAba"), std::sync::atomic::Ordering::Relaxed);
    if !tem_arg("--foto") {
        // uma janela só, como no Mac (e na Calculadora): já aberto, troca para a aba pedida e traz para a frente
        unsafe {
            let _one = comum::windows::Win32::System::Threading::CreateMutexW(None, true, w!("WacOSRelogioUmaJanela"));
            if GetLastError() == ERROR_ALREADY_EXISTS {
                if let Ok(w) = FindWindowW(w!("RelogioJanela"), PCWSTR::null()) {
                    let _ = PostMessageW(w, reg_msg("WacOSRelogioAba"), WPARAM(aba.max(0) as usize), LPARAM(0));
                    if IsIconic(w).as_bool() {
                        let _ = ShowWindow(w, SW_RESTORE);
                    }
                    let _ = SetForegroundWindow(w);
                }
                std::process::exit(0);
            }
            std::mem::forget(_one);
        }
    }
    load();
    let disp = if has_font("SF Pro Display") { "SF Pro Display".to_string() } else { family() };
    let ic = icon_family();
    use DWRITE_TEXT_ALIGNMENT_CENTER as C;
    use DWRITE_TEXT_ALIGNMENT_LEADING as L;
    use DWRITE_TEXT_ALIGNMENT_TRAILING as T;
    let f = |s: f32, w_: DWRITE_FONT_WEIGHT, al: DWRITE_TEXT_ALIGNMENT, fam: Option<&str>| fmt_full(s, w_, al, false, fam);
    a().tf = vec![
        f(12.5, DWRITE_FONT_WEIGHT_MEDIUM, C, None),     // SEG
        f(44.0, DWRITE_FONT_WEIGHT_LIGHT, L, Some(&disp)), // BIG (à esquerda, como no fim do wWinMain do C++)
        f(44.0, DWRITE_FONT_WEIGHT_LIGHT, T, Some(&disp)), // BIGR
        f(84.0, DWRITE_FONT_WEIGHT_LIGHT, C, Some(&disp)), // HUGE
        f(16.0, DWRITE_FONT_WEIGHT_NORMAL, L, None),     // ROW
        f(13.0, DWRITE_FONT_WEIGHT_NORMAL, L, None),     // SUB
        f(15.0, DWRITE_FONT_WEIGHT_MEDIUM, C, None),     // BTN
        f(16.0, DWRITE_FONT_WEIGHT_NORMAL, C, Some(&ic)), // ICON
        f(16.0, DWRITE_FONT_WEIGHT_NORMAL, T, None),     // MONO
        f(11.0, DWRITE_FONT_WEIGHT_BOLD, L, None),       // CITYB
        f(9.0, DWRITE_FONT_WEIGHT_NORMAL, L, None),      // CITYT
        f(12.5, DWRITE_FONT_WEIGHT_SEMI_BOLD, C, None),  // DIAL
        f(12.5, DWRITE_FONT_WEIGHT_MEDIUM, C, None),     // CARD
        f(12.0, DWRITE_FONT_WEIGHT_NORMAL, C, None),     // CARDSUB
        f(12.0, DWRITE_FONT_WEIGHT_NORMAL, L, None),     // CARDSUBL
    ];
    set_bar_wanted(52.0);
    let aq = semaforo::aqua();
    let Some(h) = create_main("RelogioJanela", &tr("Relógio"), proc_, if aq { 1046 } else { 720 }, if aq { 768 } else { 640 }) else { std::process::exit(1) };
    if bar() > 0.0 {
        a().tb = 52.0;
    }
    unsafe {
        SetTimer(h, 1, 50, None);
    }
    show(h, SW_SHOWNORMAL);
    std::process::exit(run());
}