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
61.1 KB
Raw Blame
//! alertas.cpp: o alerta do Mac no lugar das confirmações do Windows, por fora (UI Automation e os textos das janelas):
//!  - confirmações de excluir do Explorer ("Delete File"...): ícone da Lixeira, "Você não pode desfazer esta ação.";
//!  - a de substituir de qualquer programa ("Confirm Save As": "“x.wav” já existe. Deseja substituí-lo?");
//!  - as caixas de mensagem comuns (MessageBox com um, dois ou três botões), com o ícone do programa; a resposta volta
//!    como o clique no botão original (WM_COMMAND com o id dele, sem depender do idioma).
//! A original sai da tela e fica esperando; se ela some sozinha, o alerta some junto. E as perguntas do próprio Shell
//! (Esvaziar Lixeira, Desligar...). Desenhos do Sequoia, do Tahoe (macOS 26), do Golden Gate (macOS 27) e do Leopard.
#![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::Dwm::*;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::Threading::{AttachThreadInput, GetCurrentThreadId, OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION};
use comum::windows::Win32::UI::Accessibility::*;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

use crate::{anim, apps, backdrop, dialogs, liquid, log, shell, ui};

const AW0: f32 = 260.0;
const APAD: f32 = 20.0;
const AICON: f32 = 64.0;
const ABTN: f32 = 28.0;
const AGAP: f32 = 8.0;
const RADIUS: f32 = 12.0;
const WM_AL_CHECK: u32 = WM_APP + 70;
const WM_AL_FRAME: u32 = WM_APP + 71;
// Tahoe (guia macOS26-Theme-Reference, seções 14 e 31): 260 de largura, ícone de 32 no meio em cima, título 13 em negrito
// e texto 11 centralizados, botões de 28 empilhados em largura total com 6 entre eles e 16 de margem; cantos de 26
const T_PAD: f32 = 20.0;
const T_TOP: f32 = 20.0;
const T_ICON: f32 = 32.0;
const T_BM: f32 = 16.0;
const T_BTN: f32 = 28.0;
const T_GAP: f32 = 6.0;
// macOS 27 Golden Gate: ícone de 64 em (20, 17); título e texto 13 à esquerda a 23 da borda; botões de 27,5 lado a lado
const G_ICON: f32 = 64.0;
const G_IX: f32 = 20.0;
const G_IY: f32 = 17.0;
const G_PAD: f32 = 23.0;
const G_BTN: f32 = 27.5;
const G_BM: f32 = 16.0;
const G_GAP: f32 = 8.0;
// Leopard (alerta do 10.5): janela cinza 232 de 420 de largura; ícone de 64 em (24, 15); texto a 104; pílulas Aqua de 20
const L_W: f32 = 420.0;
const L_TX: f32 = 104.0;
const L_TOP: f32 = 15.0;
const IDYES_: i32 = 6;
const IDNO_: i32 = 7;
const IDOK_: i32 = 1;
const IDCANCEL_: i32 = 2;

#[derive(Default)]
struct S {
    wnd: HWND,
    back: HWND,
    shadow: HWND,
    glass: bool,
    s: ui::GpuSurface,
    hook: HWINEVENTHOOK,
    uia: Option<IUIAutomation>,
    open_at: f64,
    pendente: HWND,
    pendente_pos: RECT,
    tentando: HWND,
    tentativas: i32,
    // o alerta
    target: HWND,
    on_yes: Option<Box<dyn FnOnce()>>,
    title: String,
    info: String,
    yes: String,
    no: String,
    third: String,
    title_h: f32,
    info_h: f32,
    hover: i32,
    press: i32,
    /// botões: 0 = cancelar, 1 = confirmar (padrão), 2 = o terceiro
    focus: i32,
    btn: [RectF; 3],
    icon_img: Option<ui::Img>,
    icon: Option<ID2D1Bitmap>,
    /// de quem é o ícone guardado ("" = Lixeira, "sym:pc", "pack:...", ou o .exe)
    icon_of: String,
    id_yes: i32,
    id_no: i32,
    id_third: i32,
    single: bool,
    task_dlg: bool,
    foto: bool,
}
static SS: Global<Option<S>> = Global::new(None);
fn g() -> &'static mut S {
    SS.get().get_or_insert_with(|| S { hover: -1, press: -1, focus: 1, btn: [rf(0.0, 0.0, 0.0, 0.0); 3], ..Default::default() })
}
fn leo() -> bool {
    liquid::leopard()
}
fn tahoe() -> bool {
    liquid::on()
}
fn golden() -> bool {
    liquid::golden()
}
fn golden_wide() -> bool {
    golden() && g().id_third != 0
}
fn buttons() -> i32 {
    if g().single {
        1
    } else if g().id_third != 0 {
        3
    } else {
        2
    }
}
fn aw() -> f32 {
    if leo() {
        L_W
    } else if golden_wide() {
        404.0
    } else {
        AW0
    }
}
fn alert_r() -> f32 {
    if leo() {
        6.0
    } else if golden_wide() {
        16.0
    } else if tahoe() {
        26.0
    } else {
        RADIUS
    }
}
fn panel_h() -> f32 {
    let st = g();
    let info = |gap: f32| if st.info_h > 0.0 { gap + st.info_h } else { 0.0 };
    if leo() {
        return (L_TOP + 64.0).max(L_TOP + 2.0 + st.title_h + info(8.0)) + 18.0 + 20.0 + 18.0;
    }
    if golden_wide() {
        return 120.0f32.max(34.0 + st.title_h + info(2.0) + 14.0 + 19.5 + 13.0);
    }
    if golden() {
        let rows = if buttons() == 3 { 3.0 } else { 1.0 };
        return G_IY + G_ICON + 19.0 + st.title_h + info(10.0) + 17.0 + rows * G_BTN + (rows - 1.0) * G_GAP + G_BM;
    }
    if tahoe() {
        let n = buttons() as f32;
        return T_TOP + T_ICON + 12.0 + st.title_h + info(6.0) + 18.0 + n * T_BTN + (n - 1.0) * T_GAP + T_BM;
    }
    APAD + AICON + 12.0 + st.title_h + info(6.0) + 16.0 + ABTN + if st.id_third != 0 { 2.0 * (ABTN + AGAP) } else { 0.0 } + APAD
}
fn sc() -> f32 {
    if g().foto {
        ui::foto_scale()
    } else {
        ui::scale(g().wnd)
    }
}
/// o ícone do alerta: a Lixeira (apagar), o do programa que pergunta, um do pacote ("pack:") ou o computador ("sym:pc")
fn set_icon(exe: &str) {
    let st = g();
    if st.icon_img.is_some() && st.icon_of == exe {
        return;
    }
    st.icon = None;
    st.icon_img = None;
    st.icon_of = exe.to_string();
    if exe == "sym:pc" {
        return; // desenhado na hora
    }
    let png = |n: &str| {
        let p = ui::pack_icon(n);
        if p.is_empty() {
            None
        } else {
            ui::load_png(&p)
        }
    };
    st.icon_img = if let Some(n) = exe.strip_prefix("pack:") {
        png(n).or_else(|| ui::shell_image("shell:MyComputerFolder", 128, true))
    } else if exe.is_empty() {
        png("trashfull@2x").or_else(|| ui::shell_image("shell:RecycleBinFolder", 128, true))
    } else if leo() {
        // Leopard: o ícone do app no tema; sem ele, o "Alert Note" do 10.5
        let nm = exe.rsplit('\\').next().unwrap_or("");
        let nm = &nm[..nm.len().saturating_sub(4)];
        let p = apps::pack_icon_by_name(nm, exe);
        (if p.is_empty() { None } else { ui::load_png(&p) }).or_else(|| png("Alert Note")).or_else(|| {
            ui::shell_image(exe, 128, true).map(|mut i| {
                ui::trim_to_square(&mut i);
                i
            })
        })
    } else {
        ui::shell_image(exe, 128, true).map(|mut i| {
            ui::trim_to_square(&mut i);
            i
        })
    };
}
fn exe_of(h: HWND) -> String {
    unsafe {
        let mut pid = 0u32;
        GetWindowThreadProcessId(h, Some(&mut pid));
        let Ok(hp) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) else { return String::new() };
        let mut p = [0u16; 260];
        let mut n = p.len() as u32;
        let ok = QueryFullProcessImageNameW(hp, PROCESS_NAME_WIN32, PWSTR(p.as_mut_ptr()), &mut n).is_ok();
        let _ = CloseHandle(hp);
        if ok {
            String::from_utf16_lossy(&p[..n as usize])
        } else {
            String::new()
        }
    }
}
fn fmt(size: f32, wt: DWRITE_FONT_WEIGHT, a: DWRITE_TEXT_ALIGNMENT, wrap: bool) -> IDWriteTextFormat {
    let tf = ui::format(size, wt, false, a);
    unsafe {
        let _ = tf.SetWordWrapping(if wrap { DWRITE_WORD_WRAPPING_WRAP } else { DWRITE_WORD_WRAPPING_NO_WRAP });
        if wrap {
            let _ = tf.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
        }
    }
    tf
}
fn leo_fmt(size: f32, wt: DWRITE_FONT_WEIGHT) -> IDWriteTextFormat {
    let tf = ui::format_face("Lucida Sans Unicode", size, wt);
    unsafe {
        let _ = tf.SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
        let _ = tf.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
    }
    tf
}
fn text_h(s_: &str, tf: &IDWriteTextFormat, width: f32) -> f32 {
    if s_.is_empty() {
        return 0.0;
    }
    unsafe {
        ui::dw().CreateTextLayout(&w(s_), tf, width, 4000.0).ok().and_then(|l| {
            let mut m = DWRITE_TEXT_METRICS::default();
            l.GetMetrics(&mut m).ok().map(|_| m.height)
        })
    }
    .unwrap_or(0.0)
}
unsafe fn txt(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, t: &str, tf: &IDWriteTextFormat, r: RectF) {
    dc.DrawText(&w(t), tf, &r, br, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
}
/// o ícone no lugar r ("sym:pc": o computador em alumínio do Sobre Este Mac)
unsafe fn draw_icone(dc: &ID2D1DeviceContext, r: RectF) {
    let st = g();
    let rt: ID2D1RenderTarget = dc.cast().unwrap();
    if st.icon_of == "sym:pc" {
        let dark = ui::dark();
        let (a, b) = if dark { (col(0.86, 0.86, 0.88, 1.0), col(0.58, 0.58, 0.61, 1.0)) } else { (col(0.62, 0.62, 0.65, 1.0), col(0.36, 0.36, 0.39, 1.0)) };
        if let Some(lb) = linear(&rt, &[(0.0, a), (1.0, b)], pt(0.0, r.top), pt(0.0, r.bottom)) {
            simbolo::draw(&rt, "desktopcomputer", r, &lb.cast().unwrap());
        }
        return;
    }
    if st.icon.is_none() {
        if let Some(i) = &st.icon_img {
            st.icon = ui::bitmap(&rt, i.w, i.h, &i.px);
        }
    }
    if let Some(b) = &st.icon {
        dc.DrawBitmap(b, Some(&r), 1.0, D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC, None, None);
    }
}
fn label(i: usize) -> String {
    let st = g();
    [st.no.clone(), st.yes.clone(), st.third.clone()][i].clone()
}
fn focus_ring(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, r: RectF, rad: f32) {
    unsafe {
        br.SetColor(&col(0.04, 0.52, 1.0, 0.55));
        dc.DrawRoundedRectangle(&rr(rf(r.left - 1.5, r.top - 1.5, r.right + 1.5, r.bottom + 1.5), rad + 1.5, rad + 1.5), br, 3.0, None);
    }
}
/// Leopard: desenho próprio do alerta do 10.5
unsafe fn paint_leopard(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, h: f32, r_: f32) {
    let st = g();
    let w_ = aw();
    let rt: ID2D1RenderTarget = dc.cast().unwrap();
    let cinza = col(232.0 / 255.0, 232.0 / 255.0, 232.0 / 255.0, 1.0);
    br.SetColor(&cinza);
    dc.FillRoundedRectangle(&rr(rf(0.0, 0.0, w_, h), r_, r_), br);
    br.SetColor(&col(0.0, 0.0, 0.0, 0.40));
    dc.DrawRoundedRectangle(&rr(rf(0.5, 0.5, w_ - 0.5, h - 0.5), r_ - 0.5, r_ - 0.5), br, 1.0, None);
    draw_icone(dc, rf(24.0, L_TOP, 88.0, L_TOP + 64.0));
    let (tb, ti) = (leo_fmt(13.0, DWRITE_FONT_WEIGHT_BOLD), leo_fmt(11.0, DWRITE_FONT_WEIGHT_NORMAL));
    br.SetColor(&col(0.0, 0.0, 0.0, 0.9));
    let mut y = L_TOP + 2.0;
    txt(dc, br, &st.title, &tb, rf(L_TX, y, w_ - 20.0, y + st.title_h + 4.0));
    y += st.title_h + 8.0;
    if st.info_h > 0.0 {
        txt(dc, br, &st.info, &ti, rf(L_TX, y, w_ - 20.0, y + st.info_h + 4.0));
    }
    let tbtn = ui::format_face("Lucida Sans Unicode", 13.0, DWRITE_FONT_WEIGHT_NORMAL);
    let _ = tbtn.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
    let _ = tbtn.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
    g().btn = [rf(0.0, 0.0, 0.0, 0.0); 3];
    let pill = |i: usize, r: RectF, blue: bool| {
        let gg = g();
        gg.btn[i] = r;
        let down = gg.press == i as i32 && gg.hover == i as i32;
        let rad = (r.bottom - r.top) / 2.0;
        br.SetColor(&col(1.0, 1.0, 1.0, 0.6));
        dc.FillRoundedRectangle(&rr(rf(r.left, r.top + 1.0, r.right, r.bottom + 1.0), rad, rad), br);
        let b = blue || down;
        let stops = if b {
            [(0.0, col(0.66, 0.80, 0.98, 1.0)), (0.5, col(0.38, 0.60, 0.93, 1.0)), (0.5, col(0.24, 0.47, 0.87, 1.0)), (1.0, col(0.58, 0.82, 1.0, 1.0))]
        } else {
            [(0.0, col(1.0, 1.0, 1.0, 1.0)), (0.5, col(0.95, 0.95, 0.95, 1.0)), (0.5, col(0.88, 0.88, 0.88, 1.0)), (1.0, col(0.98, 0.98, 0.98, 1.0))]
        };
        if let Some(lb) = linear(&rt, &stops, pt(0.0, r.top), pt(0.0, r.bottom)) {
            dc.FillRoundedRectangle(&rr(r, rad, rad), &lb);
        }
        br.SetColor(&if b { col(0.12, 0.27, 0.58, 0.9) } else { col(0.0, 0.0, 0.0, 0.42) });
        dc.DrawRoundedRectangle(&rr(rf(r.left + 0.5, r.top + 0.5, r.right - 0.5, r.bottom - 0.5), rad - 0.5, rad - 0.5), br, 1.0, None);
        br.SetColor(&col(0.0, 0.0, 0.0, 0.9));
        txt(dc, br, &label(i), &tbtn, r);
    };
    let bw = |t: &str| 82.0f32.max(ui::text_width(&tbtn, t) + 32.0);
    let by = h - 18.0 - 20.0;
    let mut x = w_ - 20.0;
    let w1 = bw(&st.yes);
    pill(1, rf(x - w1, by, x, by + 20.0), true); // o padrão (gel azul) na direita
    x -= w1 + 12.0;
    if !st.single {
        let w0 = bw(&st.no);
        pill(0, rf(x - w0, by, x, by + 20.0), false);
    }
    if st.id_third != 0 {
        let w2 = bw(&st.third);
        pill(2, rf(L_TX, by, L_TX + w2, by + 20.0), false);
    }
}
/// macOS 27, três botões (o "já existe" do Finder): janela opaca de 404 com os botões da janela e três botões cinza
unsafe fn paint_golden_wide(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, h: f32) {
    let st = g();
    let w_ = aw();
    let dark = ui::dark();
    let rt: ID2D1RenderTarget = dc.cast().unwrap();
    let text = if dark { col(1.0, 1.0, 1.0, 0.92) } else { col(0.0, 0.0, 0.0, 0.88) };
    for k in 0..3 {
        // botões da janela: só o do meio aceso (como na captura)
        let c_ = pt(16.0 + k as f32 * 23.0, 16.0);
        br.SetColor(&if k == 1 {
            col(0.996, 0.737, 0.18, 1.0)
        } else if dark {
            col(1.0, 1.0, 1.0, 0.20)
        } else {
            col(0.86, 0.86, 0.86, 1.0)
        });
        dc.FillEllipse(&ell(c_, 7.0, 7.0), br);
        comum::semaforo::gloss(&rt, c_, 7.0, br);
    }
    draw_icone(dc, rf(20.0, 36.0, 52.0, 68.0));
    let ti = fmt(13.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING, true);
    br.SetColor(&text);
    let mut y = 34.0;
    txt(dc, br, &st.title, &ti, rf(62.0, y, w_ - 14.0, y + st.title_h));
    y += st.title_h + 2.0;
    if st.info_h > 0.0 {
        txt(dc, br, &st.info, &ti, rf(62.0, y, w_ - 14.0, y + st.info_h));
    }
    let tbtn = fmt(13.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_CENTER, false);
    let order = [2usize, 0, 1]; // da esquerda: o terceiro, Cancelar, o de confirmar
    let (bw, gap, by) = (85.5, 8.5, h - 13.0 - 19.5);
    let mut x = w_ - 12.5 - 3.0 * bw - 2.0 * gap;
    for &i in &order {
        let r = rf(x, by, x + bw, by + 19.5);
        st.btn[i] = r;
        let down = st.press == i as i32 && st.hover == i as i32;
        let hv = st.hover == i as i32;
        br.SetColor(&if dark { col(1.0, 1.0, 1.0, if down { 0.24 } else if hv { 0.18 } else { 0.13 }) } else { col(0.0, 0.0, 0.0, if down { 0.16 } else if hv { 0.12 } else { 0.085 }) });
        dc.FillRoundedRectangle(&rr(r, 5.5, 5.5), br);
        if st.focus == i as i32 {
            focus_ring(dc, br, r, 5.5);
        }
        br.SetColor(&text);
        txt(dc, br, &label(i), &tbtn, r);
        x += bw + gap;
    }
}
/// os botões em cápsula do Tahoe e do Golden Gate (o de confirmar em azul)
unsafe fn capsule(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, i: usize, r: RectF, bh: f32, azul: Cor, azul_down: Cor, text: Cor, tbtn: &IDWriteTextFormat, base_a: (f32, f32)) {
    let st = g();
    let dark = ui::dark();
    st.btn[i] = r;
    let down = st.press == i as i32 && st.hover == i as i32;
    let hv = st.hover == i as i32;
    let a = if dark { base_a.0 + if down { 0.09 } else if hv { 0.04 } else { 0.0 } } else { base_a.1 + if down { 0.08 } else if hv { 0.03 } else { 0.0 } };
    br.SetColor(&if dark { col(1.0, 1.0, 1.0, a) } else { col(0.0, 0.0, 0.0, a) });
    if i == 1 {
        br.SetColor(&if down { azul_down } else { Cor { a: if hv { 0.92 } else { 1.0 }, ..azul } });
    }
    dc.FillRoundedRectangle(&rr(r, bh / 2.0, bh / 2.0), br);
    if st.focus == i as i32 && i != 1 {
        focus_ring(dc, br, r, bh / 2.0);
    }
    br.SetColor(&if i == 1 { col(1.0, 1.0, 1.0, 1.0) } else { text });
    txt(dc, br, &label(i), tbtn, r);
}
unsafe fn paint_golden(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, h: f32) {
    let st = g();
    let w_ = aw();
    let dark = ui::dark();
    let text = if dark { col(1.0, 1.0, 1.0, 0.92) } else { col(0.0, 0.0, 0.0, 0.88) };
    draw_icone(dc, rf(G_IX, G_IY, G_IX + G_ICON, G_IY + G_ICON));
    let mut y = G_IY + G_ICON + 19.0;
    let (tb, ti) = (fmt(13.0, DWRITE_FONT_WEIGHT_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING, true), fmt(13.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING, true));
    br.SetColor(&text);
    txt(dc, br, &st.title, &tb, rf(G_PAD, y, w_ - G_PAD, y + st.title_h));
    y += st.title_h + 10.0;
    if st.info_h > 0.0 {
        txt(dc, br, &st.info, &ti, rf(G_PAD, y, w_ - G_PAD, y + st.info_h));
    }
    let tbtn = fmt(13.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_CENTER, false);
    st.btn = [rf(0.0, 0.0, 0.0, 0.0); 3];
    let bottom = h - G_BM;
    let mut rects: Vec<(usize, RectF)> = Vec::new();
    if st.id_third != 0 {
        // três: empilhados (confirmar, o terceiro, cancelar), de borda a borda
        for (k, &i) in [1usize, 2, 0].iter().enumerate() {
            let y0 = bottom - (3 - k) as f32 * G_BTN - (2 - k) as f32 * G_GAP;
            rects.push((i, rf(G_BM, y0, w_ - G_BM, y0 + G_BTN)));
        }
    } else if st.single {
        rects.push((1, rf(G_BM, bottom - G_BTN, w_ - G_BM, bottom)));
    } else {
        let bw = (w_ - 2.0 * G_BM - G_GAP) / 2.0;
        rects.push((0, rf(G_BM, bottom - G_BTN, G_BM + bw, bottom)));
        rects.push((1, rf(G_BM + bw + G_GAP, bottom - G_BTN, w_ - G_BM, bottom)));
    }
    for (i, r) in rects {
        capsule(dc, br, i, r, G_BTN, col(0.0, 122.0 / 255.0, 1.0, 1.0), col(0.0, 0.40, 0.86, 1.0), text, &tbtn, (0.12, 0.07));
    }
}
unsafe fn paint_tahoe(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, h: f32) {
    let st = g();
    let w_ = aw();
    let dark = ui::dark();
    let text = if dark { col(1.0, 1.0, 1.0, 0.92) } else { col(0.0, 0.0, 0.0, 0.88) };
    draw_icone(dc, rf(w_ / 2.0 - T_ICON / 2.0, T_TOP, w_ / 2.0 + T_ICON / 2.0, T_TOP + T_ICON));
    let mut y = T_TOP + T_ICON + 12.0;
    let (tb, ti) = (fmt(13.0, DWRITE_FONT_WEIGHT_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, true), fmt(11.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_CENTER, true));
    br.SetColor(&text);
    txt(dc, br, &st.title, &tb, rf(T_PAD, y, w_ - T_PAD, y + st.title_h));
    y += st.title_h + 6.0;
    if st.info_h > 0.0 {
        txt(dc, br, &st.info, &ti, rf(T_PAD, y, w_ - T_PAD, y + st.info_h));
    }
    let tbtn = fmt(13.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_CENTER, false);
    let n = buttons() as f32;
    let y0 = h - T_BM - n * T_BTN - (n - 1.0) * T_GAP;
    st.btn = [rf(0.0, 0.0, 0.0, 0.0); 3];
    let mut row = 0.0;
    for &i in &[1usize, 2, 0] {
        // confirmar, o terceiro, cancelar
        if (i == 0 && st.single) || (i == 2 && st.id_third == 0) {
            continue;
        }
        let r = rf(T_BM, y0 + row * (T_BTN + T_GAP), w_ - T_BM, y0 + row * (T_BTN + T_GAP) + T_BTN);
        row += 1.0;
        // o botão padrão leva a tinta de destaque do macOS 26: Bezel Tint #0086FF (guia, seção 31)
        capsule(dc, br, i, r, T_BTN, col(0.0, 0.525, 1.0, 1.0), col(0.0, 0.44, 0.86, 1.0), text, &tbtn, (0.13, 0.08));
    }
}
unsafe fn paint_sequoia(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, h: f32) {
    let st = g();
    let w_ = aw();
    let dark = ui::dark();
    let cx = w_ / 2.0;
    draw_icone(dc, rf(cx - AICON / 2.0, APAD, cx + AICON / 2.0, APAD + AICON));
    let text = if dark { col(1.0, 1.0, 1.0, 0.92) } else { col(0.0, 0.0, 0.0, 0.86) };
    let mut y = APAD + AICON + 12.0;
    let (tb, ti) = (fmt(13.0, DWRITE_FONT_WEIGHT_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, true), fmt(11.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_CENTER, true));
    br.SetColor(&text);
    txt(dc, br, &st.title, &tb, rf(APAD, y, w_ - APAD, y + st.title_h));
    y += st.title_h + 6.0;
    if st.info_h > 0.0 {
        txt(dc, br, &st.info, &ti, rf(APAD, y, w_ - APAD, y + st.info_h));
    }
    let y = h - APAD - ABTN;
    let bw = (w_ - 2.0 * APAD - AGAP) / 2.0;
    let tbtn = fmt(13.0, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_CENTER, false);
    let brr = 7.0;
    let n = if st.id_third != 0 { 3 } else { 2 };
    for i in 0..n {
        let mut r = rf(APAD + i as f32 * (bw + AGAP), y, APAD + i as f32 * (bw + AGAP) + bw, y + ABTN);
        if st.id_third != 0 {
            // três botões: empilhados (confirmar, o terceiro, cancelar), como no Mac
            let row = match i {
                1 => 0.0,
                2 => 1.0,
                _ => 2.0,
            };
            let y0 = h - APAD - 3.0 * ABTN - 2.0 * AGAP + row * (ABTN + AGAP);
            r = rf(APAD, y0, w_ - APAD, y0 + ABTN);
        }
        if st.single {
            // um botão só: ocupa a largura toda
            if i == 0 {
                st.btn[0] = rf(0.0, 0.0, 0.0, 0.0);
                continue;
            }
            r = rf(APAD, y, w_ - APAD, y + ABTN);
        }
        st.btn[i] = r;
        let (def, down) = (i == 1, st.press == i as i32 && st.hover == i as i32);
        let mut fill = if def {
            col(if dark { 0.04 } else { 0.0 }, if dark { 0.52 } else { 0.48 }, 1.0, 1.0)
        } else if dark {
            col(1.0, 1.0, 1.0, 0.20)
        } else {
            col(1.0, 1.0, 1.0, 1.0)
        };
        if down {
            fill.r *= 0.85;
            fill.g *= 0.85;
            fill.b *= 0.85;
        }
        if !dark && !def {
            br.SetColor(&col(0.0, 0.0, 0.0, 0.12));
            dc.FillRoundedRectangle(&rr(rf(r.left, r.top + 0.5, r.right, r.bottom + 0.8), brr, brr), br);
        }
        br.SetColor(&fill);
        dc.FillRoundedRectangle(&rr(r, brr, brr), br);
        if st.focus == i as i32 && !def {
            focus_ring(dc, br, r, brr); // anel de foco do Mac (Tab muda o foco)
        }
        br.SetColor(&if def { col(1.0, 1.0, 1.0, 1.0) } else { text });
        txt(dc, br, &label(i), &tbtn, r);
    }
}
fn tint() -> (Cor, f32) {
    let dark = ui::dark();
    if leo() {
        (col(232.0 / 255.0, 232.0 / 255.0, 232.0 / 255.0, 1.0), 0.0) // opaca
    } else if golden_wide() {
        (if dark { col(0.16, 0.16, 0.17, 0.98) } else { col(1.0, 1.0, 1.0, 0.98) }, 30.0)
    } else if golden() {
        (if dark { col(0.16, 0.16, 0.17, 0.82) } else { col(0.96, 0.95, 0.94, 0.80) }, 30.0)
    } else if tahoe() {
        (if dark { col(0.16, 0.16, 0.17, 0.82) } else { col(0.96, 0.96, 0.97, 0.86) }, 30.0)
    } else {
        (if dark { col(0.16, 0.16, 0.17, 0.80) } else { col(0.94, 0.94, 0.95, 0.70) }, 30.0)
    }
}
fn paint() {
    let st = g();
    let k = sc();
    let h = panel_h();
    let (wpx, hpx) = ((aw() * k).round() as i32, (h * k).round() as i32);
    let r_ = alert_r();
    let Some(dc) = ui::gpu_begin(&mut st.s, wpx, hpx, k) else { return };
    unsafe {
        let Ok(br) = dc.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None) else {
            ui::gpu_end(&mut st.s);
            return;
        };
        let rt: ID2D1RenderTarget = dc.cast().unwrap();
        if st.foto && !leo() {
            backdrop::foto_vidro(&dc, rf(0.0, 0.0, aw(), h), if golden_wide() { 16.0 } else { r_ }, tint().0);
        }
        if leo() {
            paint_leopard(&dc, &br, h, r_);
        } else {
            if !backdrop::liquid() || !backdrop::real() {
                // com o vidro real o próprio vidro desenha o contorno
                if liquid::on() {
                    liquid::rim0(&rt, rf(0.0, 0.0, aw(), h), r_, ui::dark());
                } else {
                    br.SetColor(&if ui::dark() { col(1.0, 1.0, 1.0, 0.14) } else { col(0.0, 0.0, 0.0, 0.12) });
                    dc.DrawRoundedRectangle(&rr(rf(0.5, 0.5, aw() - 0.5, h - 0.5), r_ - 0.5, r_ - 0.5), &br, 1.0, None);
                }
            }
            if golden_wide() {
                paint_golden_wide(&dc, &br, h);
            } else if golden() {
                paint_golden(&dc, &br, h);
            } else if tahoe() {
                paint_tahoe(&dc, &br, h);
            } else {
                paint_sequoia(&dc, &br, h);
            }
        }
    }
    ui::gpu_end(&mut st.s);
    if st.foto {
        return;
    }
    let (tn, frost) = tint();
    if st.glass {
        backdrop::set_pieces(st.back, wpx as f32, hpx as f32, &[backdrop::Piece { r: rf(0.0, 0.0, wpx as f32, hpx as f32), radius: if golden_wide() { 16.0 } else { r_ } * k, ..Default::default() }], tn, frost);
    }
    let mo = anim::panel_in(anim::now() - st.open_at); // aparece com a mola comum, em volta do centro
    ui::gpu_motion(&st.s, mo.scale, wpx as f32 / 2.0, hpx as f32 / 2.0, mo.fade);
    if st.glass {
        backdrop::fade(st.back, mo.fade, mo.scale, wpx as f32 / 2.0, hpx as f32 / 2.0);
    }
}
unsafe extern "system" fn def_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    DefWindowProcW(h, m, w_, l)
}
/// sombra do alerta (como a do Mac: larga, suave, caindo para baixo), numa janela em camadas logo abaixo do fundo,
/// seguindo o canto arredondado do cartão
fn shadow_show(x: i32, y: i32, w_: i32, h: i32, k: f32, radius: f32) {
    let st = g();
    unsafe {
        if st.shadow.0.is_null() {
            RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(def_proc), hInstance: shell::inst(), lpszClassName: w!("ShellAlertaSombra"), ..Default::default() });
            st.shadow = CreateWindowExW(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_TOPMOST, w!("ShellAlertaSombra"), w!(""), WS_POPUP, 0, 0, 1, 1, None, None, shell::inst(), None).unwrap_or_default();
            if !st.shadow.0.is_null() {
                apps::ours().push(st.shadow);
            }
        }
        if st.shadow.0.is_null() {
            return;
        }
        let (sigma, dy, amount, r) = (22.0 * k, 12.0 * k, if ui::dark() { 0.55 } else { 0.30 }, radius * k);
        let m = (70.0 * k) as i32;
        let (ww, hh) = (w_ + 2 * m, h + 2 * m + dy as i32);
        let bi = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: ww, biHeight: -hh, biPlanes: 1, biBitCount: 32, biCompression: BI_RGB.0, ..Default::default() }, ..Default::default() };
        let mem = CreateCompatibleDC(None);
        let mut bits = std::ptr::null_mut();
        let Ok(dib) = CreateDIBSection(None, &bi, DIB_RGB_COLORS, &mut bits, None, 0) else {
            let _ = DeleteDC(mem);
            return;
        };
        let old = SelectObject(mem, dib);
        // distância até o retângulo arredondado (negativa dentro)
        let dist = |px: f32, py: f32, cx: f32, cy: f32| {
            let qx = (px - cx).abs() - (w_ as f32 / 2.0 - r);
            let qy = (py - cy).abs() - (h as f32 / 2.0 - r);
            let (ox, oy) = (qx.max(0.0), qy.max(0.0));
            (ox * ox + oy * oy).sqrt() + qx.max(qy).min(0.0) - r
        };
        let px = std::slice::from_raw_parts_mut(bits as *mut u32, (ww * hh) as usize);
        let (cx, cy) = (m as f32 + w_ as f32 / 2.0, m as f32 + h as f32 / 2.0);
        for yy in 0..hh {
            for xx in 0..ww {
                let i = (yy * ww + xx) as usize;
                let (fx, fy) = (xx as f32 + 0.5, yy as f32 + 0.5);
                if dist(fx, fy, cx, cy) < -1.5 {
                    px[i] = 0; // embaixo do cartão: nada
                    continue;
                }
                let d = dist(fx, fy, cx, cy + dy);
                let a = if d <= 0.0 { amount } else { amount * (-(d * d) / (2.0 * sigma * sigma)).exp() };
                px[i] = ((a.min(1.0) * 255.0).round() as u32) << 24; // preto pré-multiplicado
            }
        }
        let pos = POINT { x: x - m, y: y - m };
        let zero = POINT::default();
        let size = SIZE { cx: ww, cy: hh };
        let bf = BLENDFUNCTION { BlendOp: AC_SRC_OVER as u8, BlendFlags: 0, SourceConstantAlpha: 255, AlphaFormat: AC_SRC_ALPHA as u8 };
        let _ = UpdateLayeredWindow(st.shadow, None, Some(&pos), Some(&size), mem, Some(&zero), COLORREF(0), Some(&bf), ULW_ALPHA);
        let _ = SetWindowPos(st.shadow, st.back, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW);
        SelectObject(mem, old);
        let _ = DeleteObject(dib);
        let _ = DeleteDC(mem);
    }
}
fn close() {
    let st = g();
    unsafe {
        if !st.shadow.0.is_null() {
            let _ = ShowWindow(st.shadow, SW_HIDE);
        }
        let _ = ShowWindow(st.wnd, SW_HIDE);
        let _ = ShowWindow(st.back, SW_HIDE);
        let _ = KillTimer(st.wnd, 1);
    }
    st.target = HWND::default();
    st.on_yes = None;
    st.id_yes = 0;
    st.id_no = 0;
    st.id_third = 0;
    st.task_dlg = false;
    st.third.clear();
    st.btn[2] = rf(0.0, 0.0, 0.0, 0.0);
    st.single = false;
}
/// alerta na tela (de outro programa ou do próprio Shell)
fn aberto() -> bool {
    !g().target.0.is_null() || g().on_yes.is_some()
}
/// responde na janela original (o botão dela) ou faz a pergunta do próprio Shell
fn answer(yes: bool, third: bool) {
    let st = g();
    let t = st.target;
    let on_yes = st.on_yes.take();
    let (id_yes, id_no, id_third, task_dlg) = (st.id_yes, st.id_no, st.id_third, st.task_dlg);
    let mut back = RECT::default();
    unsafe {
        let _ = GetWindowRect(st.wnd, &mut back);
    }
    close();
    if let Some(f) = on_yes {
        if yes {
            f();
        }
        return;
    }
    unsafe {
        // rede de segurança: se a original não fechar logo depois da resposta, ela volta para a tela no lugar do alerta
        if !t.0.is_null() && IsWindow(t).as_bool() {
            st.pendente = t;
            st.pendente_pos = back;
            SetTimer(st.wnd, 3, 1500, None);
        }
        if id_yes != 0 {
            // caixa de mensagem comum: o clique no botão original
            let id = if third && id_third != 0 {
                id_third
            } else if yes || id_no == 0 {
                id_yes
            } else {
                id_no
            };
            if !t.0.is_null() && IsWindow(t).as_bool() {
                if task_dlg {
                    // TaskDialog: o "clique" documentado (TDM_CLICK_BUTTON); se ela não fechar, volta para a tela
                    let _ = PostMessageW(t, WM_USER + 102, WPARAM(id as usize), LPARAM(0));
                    SetTimer(st.wnd, 3, 800, None);
                } else {
                    let _ = PostMessageW(t, WM_COMMAND, WPARAM((id as u32 | ((BN_CLICKED) << 16)) as usize), LPARAM(GetDlgItem(t, id).unwrap_or_default().0 as isize));
                }
            }
            return;
        }
        let Some(uia) = st.uia.clone() else { return };
        if t.0.is_null() || !IsWindow(t).as_bool() {
            return;
        }
        let Ok(root) = uia.ElementFromHandle(t) else { return };
        let v = VARIANT::from(UIA_ButtonControlTypeId.0);
        let Ok(cond) = uia.CreatePropertyCondition(UIA_ControlTypePropertyId, &v) else { return };
        let Ok(arr) = root.FindAll(TreeScope_Descendants, &cond) else { return };
        for i in 0..arr.Length().unwrap_or(0) {
            let Ok(e) = arr.GetElement(i) else { continue };
            let s_ = e.CurrentName().map(|b| b.to_string()).unwrap_or_default().replace('&', "").to_lowercase();
            // os nomes dos botões no idioma do Windows (os outros caem na rede de segurança: a original volta)
            let is_yes = ["yes", "sim", "sí", "si", "oui", "ja", "tak", "evet", "да"].contains(&s_.as_str());
            let is_no = ["no", "não", "nao", "non", "nein", "nie", "hayır", "нет"].contains(&s_.as_str());
            if (yes && is_yes) || (!yes && is_no) {
                if let Ok(inv) = e.GetCurrentPatternAs::<IUIAutomationInvokePattern>(UIA_InvokePatternId) {
                    let _ = inv.Invoke();
                }
                break;
            }
        }
    }
}
unsafe extern "system" fn collect_cb(h: HWND, l: LPARAM) -> BOOL {
    (*(l.0 as *mut Vec<HWND>)).push(h);
    TRUE
}
fn children(p: HWND) -> Vec<HWND> {
    let mut v: Vec<HWND> = Vec::new();
    unsafe {
        let _ = EnumChildWindows(p, Some(collect_cb), LPARAM(&mut v as *mut _ as isize));
    }
    v
}
fn class_of(h: HWND) -> String {
    let mut c = [0u16; 32];
    let n = unsafe { GetClassNameW(h, &mut c) };
    String::from_utf16_lossy(&c[..n.max(0) as usize])
}
fn wnd_text(h: HWND, max: usize) -> String {
    let mut b = vec![0u16; max];
    unsafe {
        let _ = SendMessageTimeoutW(h, WM_GETTEXT, WPARAM(max), LPARAM(b.as_mut_ptr() as isize), SMTO_ABORTIFHUNG, 200, None);
    }
    from_w(&b)
}
fn caption(h: HWND) -> String {
    let mut c = [0u16; 256];
    let n = unsafe { GetWindowTextW(h, &mut c) };
    String::from_utf16_lossy(&c[..n.max(0) as usize])
}
/// a posição original fica numa propriedade da própria janela: um Shell encerrado à força deixava a caixa em -32000
fn guarda_lugar(dlg: HWND, wr: &RECT) {
    if wr.left <= -30000 {
        return;
    }
    unsafe {
        let _ = SetPropW(dlg, w!("ShellAlertaX"), HANDLE((wr.left + 40000) as isize as *mut _));
        let _ = SetPropW(dlg, w!("ShellAlertaY"), HANDLE((wr.top + 40000) as isize as *mut _));
    }
}
/// a original sai da tela (continua viva, esperando a resposta), sem esperar a thread dela
fn tira_da_tela(dlg: HWND) -> Option<RECT> {
    let mut wr = RECT::default();
    unsafe {
        let _ = GetWindowRect(dlg, &mut wr);
        guarda_lugar(dlg, &wr);
        SetWindowPos(dlg, None, -32000, -32000, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS).ok()?;
    }
    Some(wr)
}
/// textos da janela original (pergunta, nome do arquivo) e o alerta do Mac no lugar
fn take(dlg: HWND) {
    let st = g();
    if !st.target.0.is_null() {
        return;
    }
    // os textos direto dos Static da janela (a UI Automation voltava vazia nas caixas de mensagem do Ableton); uma linha
    // de cada vez
    let mut texts: Vec<String> = Vec::new();
    for c in children(dlg) {
        if !class_of(c).eq_ignore_ascii_case("Static") {
            continue;
        }
        texts.extend(wnd_text(c, 1024).split(['\n', '\r']).filter(|l| !l.is_empty()).map(|l| l.to_string()));
    }
    if let Some(uia) = &st.uia {
        unsafe {
            if let Ok(root) = uia.ElementFromHandle(dlg) {
                let v = VARIANT::from(UIA_TextControlTypeId.0);
                if let Ok(cond) = uia.CreatePropertyCondition(UIA_ControlTypePropertyId, &v) {
                    if let Ok(arr) = root.FindAll(TreeScope_Descendants, &cond) {
                        for i in 0..arr.Length().unwrap_or(0) {
                            if let Some(n) = arr.GetElement(i).ok().and_then(|e| e.CurrentName().ok()).map(|b| b.to_string()).filter(|s_| !s_.is_empty()) {
                                texts.push(n);
                            }
                        }
                    }
                }
            }
        }
    }
    // substituir: "x.wav already exists." / "x.wav já existe." + "Do you want to replace it?"
    let cap = caption(dlg);
    let save_as = cap.eq_ignore_ascii_case("Confirm Save As")
        || cap.eq_ignore_ascii_case("Confirmar Salvar como")
        || (!sis().salvar.is_empty() && cap.to_lowercase() == sis().salvar.to_lowercase());
    let mut achou = false;
    let mut name = String::new();
    for t in &texts {
        let l = t.to_lowercase();
        let at = l.find(" already exists").or_else(|| l.find(" já existe"));
        if let Some(at) = at.filter(|&a| a > 0) {
            name = l.get(..at).and_then(|_| t.get(..at)).unwrap_or(&l[..at]).to_string();
            achou = true;
            break;
        }
        // no idioma do Windows: "<antes>nome<depois>" ("x.png ya existe.")
        let s_ = sis();
        if s_.existe_depois.is_empty() || !l.starts_with(s_.existe_antes.as_str()) {
            continue;
        }
        let ini = s_.existe_antes.len();
        if let Some(at) = l[ini..].find(s_.existe_depois.as_str()).filter(|&a| a > 0) {
            name = l[ini..ini + at].to_string();
            if let Some(orig) = t.get(ini..ini + at) {
                name = orig.to_string(); // com as maiúsculas do original quando os índices batem
            }
            achou = true;
            break;
        }
    }
    // a do Abrir/Salvar novo (a do Ableton) é um TaskDialog: nem o texto nem a UI Automation leem por fora; olha de novo
    // algumas vezes; sem texto, o nome vem do que foi escolhido no Finder
    if !achou && save_as {
        if texts.is_empty() && (st.tentando != dlg || st.tentativas < 3) {
            if st.tentando != dlg {
                st.tentando = dlg;
                st.tentativas = 0;
            }
            st.tentativas += 1;
            unsafe { SetTimer(st.wnd, 2, 150, None) };
            return;
        }
        let last = dialogs::last_saved();
        if !last.is_empty() {
            name = last.rsplit('\\').next().unwrap_or("").to_string();
        }
        achou = true;
    }
    if achou {
        st.title = if name.is_empty() { tr("Já existe um item com este nome. Deseja substituí-lo?") } else { format!("“{name}{}", tr("” já existe. Deseja substituí-lo?")) };
        st.info = tr("Já existe um arquivo com o mesmo nome. Substituí-lo irá sobrescrever o conteúdo atual.");
        st.yes = tr("Substituir");
        st.no = tr("Cancelar");
        st.target = dlg;
        st.on_yes = None;
        // caixa de mensagem com Sim/Não de verdade: responde pelo id do botão; TaskDialog: TDM_CLICK_BUTTON com Sim/Não
        unsafe {
            if GetDlgItem(dlg, IDYES_).is_ok() && GetDlgItem(dlg, IDNO_).is_ok() {
                st.id_yes = IDYES_;
                st.id_no = IDNO_;
            } else if children(dlg).iter().any(|c| class_of(*c) == "DirectUIHWND") {
                st.id_yes = IDYES_;
                st.id_no = IDNO_;
                st.task_dlg = true;
            }
        }
        set_icon(&exe_of(dlg));
        if let Some(wr) = tira_da_tela(dlg) {
            show((wr.left + wr.right) / 2, (wr.top + wr.bottom) / 2);
        }
        log!("alertas: confirmação de substituir no alerta do Mac ({name}{})", if st.task_dlg { ", TaskDialog" } else { "" });
        return;
    }
    let (mut q, mut file) = (String::new(), String::new());
    for (i, t) in texts.iter().enumerate() {
        let l = t.to_lowercase();
        if q.is_empty() && (l.contains("are you sure") || l.contains("tem certeza") || comeca_com(&l, &sis().apagar) || comeca_com(&l, &sis().lixeira)) {
            q = t.clone();
            if let Some(n) = texts.get(i + 1).filter(|n| !n.contains(':')) {
                file = n.clone();
            }
        }
    }
    if q.is_empty() {
        // não é a confirmação que conhecemos: fica a do Windows
        log!("alertas: confirmação não reconhecida ({} textos)", texts.len());
        return;
    }
    let lq = q.to_lowercase();
    let permanent = lq.contains("permanent") || comeca_com(&lq, &sis().apagar);
    let to_bin = !permanent && (lq.contains("recycle bin") || lq.contains("lixeira") || comeca_com(&lq, &sis().lixeira));
    let count: u32 = lq.chars().skip_while(|c| !c.is_ascii_digit()).take_while(|c| c.is_ascii_digit()).collect::<String>().parse().unwrap_or(0);
    let what = if !file.is_empty() && count == 0 {
        format!("“{file}”")
    } else if count > 1 {
        format!("{}{count}{}", tr("estes "), tr(" itens"))
    } else {
        tr("este item")
    };
    if permanent {
        st.title = format!("{}{what}{}", tr("Tem certeza de que deseja apagar "), tr(" permanentemente?"));
        st.info = tr("Você não pode desfazer esta ação.");
        st.yes = tr("Apagar");
    } else if to_bin {
        st.title = format!("{}{what}{}", tr("Tem certeza de que deseja mover "), tr(" para a Lixeira?"));
        st.info.clear();
        st.yes = tr("Mover para a Lixeira");
    } else {
        st.title = q; // pergunta que não reconhecemos: o texto do Windows, no alerta do Mac
        st.info.clear();
        st.yes = tr("Sim");
    }
    st.no = tr("Cancelar");
    st.target = dlg;
    st.on_yes = None;
    set_icon("");
    if let Some(wr) = tira_da_tela(dlg) {
        show((wr.left + wr.right) / 2, (wr.top + wr.bottom) / 2);
    }
    log!("alertas: confirmação do Explorer no alerta do Mac ({})", st.title);
}
/// botões do Windows em inglês → os do projeto
fn rotulo(s_: &str) -> String {
    let t = [("ok", "OK"), ("yes", "Sim"), ("no", "Não"), ("cancel", "Cancelar"), ("retry", "Tentar Novamente"), ("try again", "Tentar Novamente"), ("continue", "Continuar"), ("close", "Fechar"), ("ignore", "Ignorar"), ("abort", "Anular")];
    let l = s_.to_lowercase();
    t.iter().find(|(en, _)| *en == l).map(|(_, pt_)| tr(pt_)).unwrap_or_else(|| s_.to_string())
}
/// caixa de mensagem comum (MessageBox) de qualquer programa → alerta do Mac
fn take_message(dlg: HWND) {
    let st = g();
    if !st.target.0.is_null() || !unsafe { IsWindowVisible(dlg).as_bool() } {
        return;
    }
    let (mut text_w, mut outro) = (HWND::default(), false);
    let mut btns: Vec<(HWND, i32)> = Vec::new();
    for c in children(dlg) {
        let cls = class_of(c);
        let id = unsafe { GetDlgCtrlID(c) };
        if cls.eq_ignore_ascii_case("Static") {
            if id == 0xFFFF {
                text_w = c;
            } else if id != 20 {
                outro = true; // 20 = o ícone
            }
        } else if cls.eq_ignore_ascii_case("Button") && ((1..=7).contains(&id) || id == 10 || id == 11) {
            btns.push((c, id));
        } else {
            outro = true;
        }
    }
    if text_w.0.is_null() || outro || btns.is_empty() || btns.len() > 3 {
        return; // não é uma caixa de mensagem simples: fica a do Windows
    }
    let texto = wnd_text(text_w, 2048).trim_end().to_string();
    if texto.is_empty() {
        return; // programa elevado (não deixa ler) ou caixa vazia
    }
    let cap = caption(dlg);
    // título em negrito = o primeiro parágrafo; o resto vira o texto menor
    let mut br_ = texto.find("\n\n").map(|i| (i, 2)).or_else(|| texto.find("\r\n\r\n").map(|i| (i, 4)));
    if br_.is_none() && leo() {
        // Leopard: a 1ª linha é o texto em negrito, o resto o informativo (10.5)
        br_ = texto.find('\n').map(|i| if i > 0 && texto.as_bytes()[i - 1] == b'\r' { (i - 1, 2) } else { (i, 1) });
    }
    if let Some((b, skip)) = br_ {
        st.title = texto[..b].to_string();
        st.info = texto[b + skip..].to_string();
    } else if texto.chars().count() > 140 && !cap.is_empty() {
        st.title = cap.clone();
        st.info = texto;
    } else {
        st.title = texto;
        st.info.clear();
    }
    let afirma = |id: i32| id == IDOK_ || id == IDYES_ || id == 4 || id == 10 || id == 11; // OK, Sim, Repetir, Tentar, Continuar
    let y = btns.iter().position(|b| afirma(b.1)).unwrap_or(0);
    let mut n = btns.iter().enumerate().position(|(i, b)| i != y && b.1 == IDCANCEL_);
    if n.is_none() {
        n = btns.iter().enumerate().position(|(i, b)| i != y && (b.1 == 3 || b.1 == IDNO_)); // Anular, Não
    }
    if n.is_none() {
        n = (0..btns.len()).find(|&i| i != y);
    }
    let t = (0..btns.len()).find(|&i| i != y && Some(i) != n);
    st.id_yes = btns[y].1;
    st.yes = rotulo(&wnd_text(btns[y].0, 256).replace('&', ""));
    st.single = btns.len() == 1;
    st.id_no = n.map(|i| btns[i].1).unwrap_or(0);
    st.no = n.map(|i| rotulo(&wnd_text(btns[i].0, 256).replace('&', ""))).unwrap_or_default();
    st.id_third = t.map(|i| btns[i].1).unwrap_or(0);
    st.third = t.map(|i| rotulo(&wnd_text(btns[i].0, 256).replace('&', ""))).unwrap_or_default();
    st.target = dlg;
    st.on_yes = None;
    set_icon(&exe_of(dlg));
    // sem esperar a thread do programa (o Ableton ocupado deixava o Shell parado)
    let Some(wr) = tira_da_tela(dlg) else {
        st.target = HWND::default(); // não deixou mexer (elevado)
        st.id_yes = 0;
        st.id_no = 0;
        st.single = false;
        return;
    };
    show((wr.left + wr.right) / 2, (wr.top + wr.bottom) / 2);
    log!("alertas: caixa de mensagem de {cap} no alerta do Mac ({} botão(ões))", btns.len());
}
fn medir() {
    let st = g();
    let inner = if leo() {
        L_W - L_TX - 20.0
    } else if golden_wide() {
        aw() - 62.0 - 14.0
    } else if golden() {
        aw() - 2.0 * G_PAD
    } else if tahoe() {
        aw() - 2.0 * T_PAD
    } else {
        aw() - 2.0 * APAD
    };
    let (tt, ti) = if leo() {
        (leo_fmt(13.0, DWRITE_FONT_WEIGHT_BOLD), leo_fmt(11.0, DWRITE_FONT_WEIGHT_NORMAL))
    } else {
        let al = if golden() { DWRITE_TEXT_ALIGNMENT_LEADING } else { DWRITE_TEXT_ALIGNMENT_CENTER };
        (fmt(13.0, if golden_wide() { DWRITE_FONT_WEIGHT_NORMAL } else { DWRITE_FONT_WEIGHT_BOLD }, al, true), fmt(if golden() { 13.0 } else { 11.0 }, DWRITE_FONT_WEIGHT_NORMAL, al, true))
    };
    st.title_h = text_h(&st.title, &tt, inner);
    st.info_h = text_h(&st.info, &ti, inner);
    st.hover = -1;
    st.press = -1;
    st.focus = 1;
    if st.icon_img.is_none() {
        let i = st.icon_of.clone();
        st.icon_of = "\u{0}".into();
        set_icon(&i);
    }
}
fn show(mut cx: i32, mut cy: i32) {
    let st = g();
    medir();
    let k = sc();
    let (wpx, hpx) = ((aw() * k).round() as i32, (panel_h() * k).round() as i32);
    unsafe {
        // a dona da pergunta saiu da tela (a janela de Salvar trocada pelo Finder fica em -32000), ou fora de qualquer
        // monitor: no meio do monitor do ponteiro, a um terço da altura, como o Mac (Firefox, issue #8)
        let own = if st.target.0.is_null() { HWND::default() } else { GetWindow(st.target, GW_OWNER).unwrap_or_default() };
        let mut orc = RECT::default();
        if !own.0.is_null() {
            let _ = GetWindowRect(GetAncestor(own, GA_ROOT), &mut orc);
        }
        if (!own.0.is_null() && orc.left <= -30000) || MonitorFromPoint(POINT { x: cx, y: cy }, MONITOR_DEFAULTTONULL).is_invalid() {
            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);
            cx = (mi.rcWork.left + mi.rcWork.right) / 2;
            cy = mi.rcWork.top + (mi.rcWork.bottom - mi.rcWork.top) / 3;
        }
        let (x, y) = (cx - wpx / 2, cy - hpx / 2);
        let _ = SetWindowPos(st.wnd, HWND_TOPMOST, x, y, wpx, hpx, SWP_NOACTIVATE);
        let _ = SetWindowPos(st.back, st.wnd, x, y, wpx, hpx, SWP_NOACTIVATE | SWP_SHOWWINDOW);
        shadow_show(x, y, wpx, hpx, k, alert_r());
        st.open_at = anim::now();
        paint();
        let _ = ShowWindow(st.wnd, SW_SHOW);
        ui::frame_clock(st.wnd, WM_AL_FRAME, true);
        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);
        }
        if !st.target.0.is_null() {
            SetTimer(st.wnd, 1, 300, None); // a original sumiu? o alerta some junto
        }
    }
}
/// pergunta do próprio Shell (Esvaziar Lixeira do Dock, Desligar...): o mesmo alerta, no meio da tela
pub fn confirm(titulo: &str, texto: &str, botao: &str, ok: Box<dyn FnOnce()>, icone: &str) {
    let st = g();
    if !st.target.0.is_null() {
        return; // já tem um alerta aberto
    }
    st.title = titulo.into();
    st.info = texto.into();
    st.yes = botao.into();
    st.no = tr("Cancelar");
    st.on_yes = Some(ok);
    set_icon(icone);
    let mut c = POINT::default();
    let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
    unsafe {
        let _ = GetCursorPos(&mut c);
        let _ = GetMonitorInfoW(MonitorFromPoint(c, MONITOR_DEFAULTTOPRIMARY), &mut mi);
    }
    show((mi.rcWork.left + mi.rcWork.right) / 2, mi.rcWork.top + (mi.rcWork.bottom - mi.rcWork.top) / 3);
    g().target = HWND::default();
}
/// aviso do próprio Shell com um botão só (o "Sobre" dos apps do WacOS, issue #548): fecha no OK, Esc ou Enter
pub fn informar(titulo: &str, texto: &str, icone: &str) {
    confirm(titulo, texto, &tr("OK"), Box::new(|| {}), icone);
    g().single = true;
    paint();
}
fn is_delete_dialog(h: HWND) -> bool {
    if class_of(h) != "#32770" {
        return false;
    }
    let t = caption(h);
    ["Delete File", "Delete Folder", "Delete Multiple Items", "Delete Shortcut", "Excluir Arquivo", "Excluir Pasta", "Excluir Vários Itens", "Excluir Atalho", "Confirm Save As", "Confirmar Salvar como", "Confirmar Salvar Como"].iter().any(|s_| t.eq_ignore_ascii_case(s_))
        || sis().titulos.iter().any(|s_| t.to_lowercase() == s_.to_lowercase()) // no idioma do Windows
}

// Os textos dessas confirmações no idioma do Windows, lidos do shell32/comdlg32: antes só reconhecia inglês e
// português, e no Windows em espanhol a caixa ficava a do Windows com a barra do Mac por cima (#441, #451).
fn texto_sis(dll: &str, id: u32) -> String {
    use comum::windows::Win32::System::LibraryLoader::*;
    let w: Vec<u16> = dll.encode_utf16().chain(Some(0)).collect();
    unsafe {
        let m = GetModuleHandleW(PCWSTR(w.as_ptr())).or_else(|_| {
            LoadLibraryExW(PCWSTR(w.as_ptr()), None, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE | LOAD_LIBRARY_SEARCH_SYSTEM32)
        });
        let Ok(m) = m else { return String::new() };
        let mut b = [0u16; 2048];
        let n = LoadStringW(HINSTANCE(m.0), id, PWSTR(b.as_mut_ptr()), b.len() as i32);
        if n > 0 { String::from_utf16_lossy(&b[..n as usize]) } else { String::new() }
    }
}
fn comeco(s: &str) -> String {
    s.split(['%', '\n', '\r']).next().unwrap_or("").to_lowercase() // até o 1º %n
}
#[derive(Default)]
struct TextosSis {
    titulos: Vec<String>,
    apagar: Vec<String>,
    lixeira: Vec<String>,
    salvar: String,
    existe_antes: String, // "%1 already exists." → "" e " already exists"
    existe_depois: String,
}
fn sis() -> &'static TextosSis {
    static T: std::sync::OnceLock<TextosSis> = std::sync::OnceLock::new();
    T.get_or_init(|| {
        let mut r = TextosSis::default();
        for id in [16792, 16793, 16877, 16884, 16934, 16979] {
            let s = texto_sis("shell32.dll", id); // Delete File/Folder/Multiple Items/Shortcut/Item
            if !s.is_empty() {
                r.titulos.push(s);
            }
        }
        r.salvar = texto_sis("comdlg32.dll", 435); // Confirm Save As
        if !r.salvar.is_empty() {
            r.titulos.push(r.salvar.clone());
        }
        for id in [16724, 16725, 16731, 16800, 16855, 16977, 16983, 16984] {
            let s = comeco(&texto_sis("shell32.dll", id)); // "...permanently delete..."
            if s.chars().count() > 8 {
                r.apagar.push(s);
            }
        }
        for id in [16722, 16723, 16730, 16798] {
            let s = comeco(&texto_sis("shell32.dll", id)); // "...move ... to the Recycle Bin?"
            if s.chars().count() > 8 {
                r.lixeira.push(s);
            }
        }
        let e = texto_sis("comdlg32.dll", 257); // "%1 already exists.\nDo you want to replace it?"
        if let Some(a) = e.find("%1") {
            let resto = &e[a + 2..];
            let depois = resto.split(['\n', '\r']).next().unwrap_or("");
            r.existe_antes = e[..a].to_lowercase();
            r.existe_depois = depois.trim_end_matches(['.', ' ']).to_lowercase();
            if r.existe_depois.chars().count() < 4 {
                r.existe_depois.clear();
            }
        }
        r
    })
}
fn comeca_com(l: &str, v: &[String]) -> bool {
    v.iter().any(|p| l.starts_with(p.as_str()))
}
unsafe extern "system" fn on_show(_: HWINEVENTHOOK, _: u32, h: HWND, obj: i32, _: i32, _: u32, _: u32) {
    if obj != OBJID_WINDOW.0 || h.0.is_null() || GetAncestor(h, GA_ROOT) != h {
        return;
    }
    // fora do evento: a UI Automation não pode rodar dentro dele
    if is_delete_dialog(h) {
        let _ = PostMessageW(g().wnd, WM_AL_CHECK, WPARAM(0), LPARAM(h.0 as isize));
    } else if class_of(h) == "#32770" && shell::setting("alertas_mac", "1") != "0" {
        let _ = PostMessageW(g().wnd, WM_AL_CHECK, WPARAM(1), LPARAM(h.0 as isize)); // talvez uma caixa de mensagem
    }
}
unsafe extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    let st = g();
    match m {
        WM_AL_CHECK => {
            let t = HWND(l.0 as *mut _);
            if IsWindow(t).as_bool() {
                if w_.0 == 1 {
                    take_message(t);
                } else {
                    take(t);
                }
            }
            LRESULT(0)
        }
        WM_AL_FRAME => {
            ui::frame_ack(h, WM_AL_FRAME);
            if aberto() {
                paint();
            }
            if !aberto() || anim::panel_in(anim::now() - st.open_at).done {
                ui::frame_clock(h, WM_AL_FRAME, false);
            }
            LRESULT(0)
        }
        WM_PAINT => {
            let mut ps = PAINTSTRUCT::default();
            BeginPaint(h, &mut ps);
            let _ = EndPaint(h, &ps);
            if aberto() {
                paint();
            }
            LRESULT(0)
        }
        WM_TIMER => {
            match w_.0 {
                2 => {
                    let _ = KillTimer(h, 2);
                    if IsWindow(st.tentando).as_bool() {
                        take(st.tentando);
                    }
                }
                3 => {
                    let _ = KillTimer(h, 3);
                    if IsWindow(st.pendente).as_bool() {
                        // não fechou com a resposta: devolve à tela para o usuário responder nela
                        log!("alertas: a confirmação original não respondeu; voltou para a tela");
                        let _ = SetWindowPos(st.pendente, HWND_TOP, st.pendente_pos.left, st.pendente_pos.top, 0, 0, SWP_NOSIZE | SWP_ASYNCWINDOWPOS);
                    }
                    st.pendente = HWND::default();
                }
                _ => {
                    if !st.target.0.is_null() && !IsWindow(st.target).as_bool() {
                        close();
                    }
                }
            }
            LRESULT(0)
        }
        WM_KEYDOWN => {
            let vk = VIRTUAL_KEY(w_.0 as u16);
            if vk == VK_ESCAPE {
                answer(false, false);
            } else if vk == VK_RETURN {
                answer(true, false);
            } else if vk == VK_SPACE {
                if st.focus == 2 {
                    answer(false, true);
                } else {
                    answer(st.focus == 1, false);
                }
            } else if [VK_TAB, VK_LEFT, VK_RIGHT, VK_DOWN, VK_UP].contains(&vk) && !st.single {
                st.focus = if st.id_third != 0 {
                    match st.focus {
                        1 => 2,
                        2 => 0,
                        _ => 1,
                    }
                } else {
                    1 - st.focus
                };
                paint();
            }
            LRESULT(0)
        }
        WM_MOUSEMOVE | WM_LBUTTONDOWN | WM_LBUTTONUP => {
            let k = sc();
            let (x, y) = (get_x_lparam(l) as f32 / k, get_y_lparam(l) as f32 / k);
            let hit = (0..3).rev().find(|&i| in_rect(&st.btn[i], x, y)).map(|i| i as i32).unwrap_or(-1);
            if m == WM_LBUTTONDOWN {
                if hit < 0 {
                    // arrasta pelo fundo
                    let _ = ReleaseCapture();
                    SendMessageW(h, WM_NCLBUTTONDOWN, WPARAM(HTCAPTION as usize), LPARAM(0));
                    return LRESULT(0);
                }
                st.press = hit;
                SetCapture(h);
            } else if m == WM_LBUTTONUP {
                let was = st.press;
                st.press = -1;
                let _ = ReleaseCapture();
                if was >= 0 && was == hit {
                    if hit == 2 {
                        answer(false, true);
                    } else {
                        answer(hit == 1, false);
                    }
                    return LRESULT(0);
                }
            }
            if hit != st.hover || m != WM_MOUSEMOVE {
                st.hover = hit;
                paint();
            }
            LRESULT(0)
        }
        WM_MOVE => {
            if IsWindowVisible(st.back).as_bool() {
                let mut r = RECT::default();
                let _ = GetWindowRect(h, &mut r);
                let _ = SetWindowPos(st.back, h, r.left, r.top, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE);
                if !st.shadow.0.is_null() && IsWindowVisible(st.shadow).as_bool() {
                    let m_ = (70.0 * sc()) as i32;
                    let _ = SetWindowPos(st.shadow, st.back, r.left - m_, r.top - m_, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE);
                }
            }
            LRESULT(0)
        }
        _ => DefWindowProcW(h, m, w_, l),
    }
}
unsafe extern "system" fn back_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    if m == WM_MOUSEACTIVATE {
        return LRESULT(MA_NOACTIVATE as isize);
    }
    DefWindowProcW(h, m, w_, l)
}
unsafe extern "system" fn volta_cb(h: HWND, _: LPARAM) -> BOOL {
    // caixas que um Shell encerrado à força deixou fora da tela voltam para onde estavam
    let (x, y) = (GetPropW(h, w!("ShellAlertaX")), GetPropW(h, w!("ShellAlertaY")));
    let mut r = RECT::default();
    if !x.is_invalid() && !y.is_invalid() && IsWindowVisible(h).as_bool() && !IsIconic(h).as_bool() && GetWindowRect(h, &mut r).is_ok() && r.left <= -30000 {
        let _ = SetWindowPos(h, HWND_TOP, x.0 as isize as i32 - 40000, y.0 as isize as i32 - 40000, 0, 0, SWP_NOSIZE | SWP_ASYNCWINDOWPOS);
        log!("alertas: caixa deixada fora da tela por um Shell anterior voltou");
    }
    TRUE
}
pub fn create(hi: HINSTANCE) -> bool {
    let st = g();
    unsafe {
        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hi, lpszClassName: w!("ShellAlerta"), hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), ..Default::default() });
        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(back_proc), hInstance: hi, lpszClassName: w!("ShellAlertaFundo"), ..Default::default() });
        st.wnd = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP, w!("ShellAlerta"), w!("Alerta"), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
        st.back = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP, w!("ShellAlertaFundo"), w!(""), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
        if st.wnd.0.is_null() || st.back.0.is_null() {
            return false;
        }
        let _ = EnumWindows(Some(volta_cb), LPARAM(0));
        st.glass = backdrop::attach(st.back);
        let corner: u32 = if st.glass { 1 } else { 2 };
        if !st.glass {
            let _ = DestroyWindow(st.back);
            st.back = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, w!("ShellAlertaFundo"), w!(""), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
            ui::acrylic(st.back, if ui::dark() { 0xE020_1E1E } else { 0xE0F6_F6F6 });
        }
        let _ = DwmSetWindowAttribute(st.back, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const _, 4);
        let none: u32 = 0xFFFF_FFFE;
        let _ = DwmSetWindowAttribute(st.back, DWMWINDOWATTRIBUTE(34), &none as *const _ as *const _, 4);
        apps::ours().push(st.wnd);
        apps::ours().push(st.back);
        st.s.hwnd = st.wnd;
        st.uia = CoCreateInstance(&CUIAutomation, None, CLSCTX_INPROC_SERVER).ok();
        // programa ocupado: a UI Automation esperava até 20 s na thread do Shell; o vigia derruba em 10 s
        if let Some(u2) = st.uia.as_ref().and_then(|u| u.cast::<IUIAutomation2>().ok()) {
            let _ = u2.SetConnectionTimeout(500);
            let _ = u2.SetTransactionTimeout(1000);
        }
        st.hook = SetWinEventHook(EVENT_OBJECT_SHOW, EVENT_OBJECT_SHOW, None, Some(on_show), 0, 0, WINEVENT_OUTOFCONTEXT | shell::sem_proprio());
    }
    true
}
pub fn stop() {
    let st = g();
    unsafe {
        if !st.hook.is_invalid() {
            let _ = UnhookWinEvent(st.hook);
            st.hook = HWINEVENTHOOK::default();
        }
        if !st.target.0.is_null() && IsWindow(st.target).as_bool() {
            // devolve a janela original à tela
            let mut r = RECT::default();
            let _ = GetWindowRect(st.wnd, &mut r);
            let _ = SetWindowPos(st.target, HWND_TOP, r.left, r.top, 0, 0, SWP_NOSIZE | SWP_ASYNCWINDOWPOS);
        }
    }
    st.uia = None;
}
/// modo foto: o alerta de Esvaziar Lixeira (ou, com `tres`, uma caixa de três botões) no meio da tela
pub fn foto(tela_w: f32, tela_h: f32, tres: bool) {
    let st = g();
    st.foto = true;
    st.on_yes = Some(Box::new(|| {}));
    if tres {
        st.title = tr("Deseja salvar as alterações feitas no documento?");
        st.info = tr("Suas alterações serão perdidas se você não salvá-las.");
        st.yes = tr("Salvar");
        st.no = tr("Cancelar");
        st.third = tr("Não Salvar");
        st.id_third = 7;
        set_icon("sym:pc");
    } else {
        st.title = tr("Tem certeza de que deseja apagar permanentemente os itens da Lixeira?");
        st.info = tr("Você não pode desfazer esta ação.");
        st.yes = tr("Esvaziar Lixeira");
        st.no = tr("Cancelar");
        set_icon("");
    }
    medir();
    let k = ui::foto_scale();
    st.s.foto_pos = ((tela_w - aw()) / 2.0 * k, (tela_h / 3.0 - panel_h() / 2.0) * k);
    paint();
}