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
117 KB
Raw Blame
//! notificacoes.cpp: a Central de Notificações (clique na data/hora): a coluna desliza da direita com as notificações
//! do Windows (UserNotificationListener) em cartões de vidro, empilhadas por app, e os widgets embaixo. E o banner do
//! Mac (até 3) quando chega notificação com o painel fechado; o toast do Windows sai da tela. Os avisos do Lembretes,
//! Calendário e Relógio saem daqui também.
#![allow(dead_code)]

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::ffi::c_void;
use std::rc::Rc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Condvar, Mutex};

use comum::ctxmenu::{self, Item as MItem};
use comum::windows::core::*;
use comum::windows::Foundation::Numerics::{Matrix3x2, Vector2, Vector3};
use comum::windows::Foundation::Size;
use comum::windows::UI::Notifications::Management::*;
use comum::windows::UI::Notifications::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct2D::Common::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Graphics::Gdi::{BeginPaint, EndPaint, GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTOPRIMARY, PAINTSTRUCT};
use comum::windows::Win32::Graphics::Imaging::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::SystemInformation::*;
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::System::WinRT::Composition::ICompositorDesktopInterop;
use comum::windows::Win32::System::WinRT::CreateStreamOverRandomAccessStream;
use comum::windows::Win32::UI::Accessibility::*;
use comum::windows::Win32::UI::Controls::WM_MOUSELEAVE;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::Shell::{IEnumShellItems, IShellItem, IShellItem2, SHCreateItemFromParsingName, BHID_EnumItems, SIGDN_NORMALDISPLAY, SIGDN_PARENTRELATIVEPARSING};
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::windows::UI::Color;
use comum::windows::UI::Composition::Desktop::DesktopWindowTarget;
use comum::windows::UI::Composition::*;
use comum::*;

use crate::widgets;
use crate::jogo;
use crate::ilha;
use crate::{anim, apps, backdrop, dock, liquid, log, menubar, shell, ui};

// ---- medidas (pt), das capturas do Sequoia (cartão de 344, 55 de altura mínima, linhas de 16, pilha de 7)
const CARD_W: f32 = 344.0;
const PAD_L: f32 = 22.0;
const MARGIN_R: f32 = 16.0;
const COL_W: f32 = PAD_L + CARD_W + MARGIN_R;
const ICON: f32 = 34.0;
const ICON_X: f32 = 13.0;
const TEXT_X: f32 = ICON_X + ICON + 10.0;
const PAD_V: f32 = 11.0;
const PAD_R: f32 = 14.0;
const TITLE_H: f32 = 17.0;
const LINE_H: f32 = 16.0;
const MIN_H: f32 = 55.0;
const MAX_LINES: i32 = 3;
const GAP: f32 = 8.0;
const GROUP_GAP: f32 = 10.0;
const PEEK: f32 = 7.0;
const PEEK_INSET: f32 = 10.0;
const HEADER_H: f32 = 26.0;
const PILL_H: f32 = 24.0;
const CIRCLE: f32 = 24.0;
const WIDGET_S: f32 = 164.0;
const WIDGET_GAP: f32 = 16.0;
const MAX_GROUPS: usize = 6;
const WM_NC_FRAME: u32 = WM_APP + 90;
const WM_NC_DATA: u32 = WM_APP + 91;
const WM_NC_NEW: u32 = WM_APP + 92;
const WM_NC_BFRAME: u32 = WM_APP + 93;
const T_TICK: usize = 1;
const T_FOCO: usize = 2;
const T_ANIM: usize = 3;
const T_BANNER: usize = 2;
const MAX_BANS: usize = 3;
const BAN_GAP: f32 = 8.0;
const BAN_OUT_MS: f64 = 300.0;
const AVISO_ID: u32 = 0xF000_0000;
/// Tahoe (seção 65): o banner fica 16 abaixo da barra
fn top() -> f32 {
    if liquid::on() {
        16.0
    } else {
        8.0
    }
}
fn card_r() -> f32 {
    if liquid::golden() {
        18.0
    } else if liquid::on() {
        22.0
    } else {
        17.0
    }
}
fn widget_r() -> f32 {
    if liquid::on() {
        26.0
    } else {
        20.0
    }
}
// ================= dados (thread de leitura)
#[derive(Clone, Default)]
pub struct Note {
    pub id: u32,
    pub aumid: String,
    pub app: String,
    pub title: String,
    pub body: String,
    /// FILETIME (100 ns, UTC)
    pub time: i64,
}
#[derive(Clone, Default)]
struct LogoPx {
    w: u32,
    h: u32,
    px: Vec<u8>,
}
struct Dados {
    data: Vec<Note>,
    logos: BTreeMap<String, LogoPx>,
    to_remove: Vec<u32>,
    access: i32,
    wake: bool,
}
static DADOS: Mutex<Dados> = Mutex::new(Dados { data: Vec::new(), logos: BTreeMap::new(), to_remove: Vec::new(), access: -1, wake: false });
static CV: Condvar = Condvar::new();
static RAPIDO_ATE: AtomicU32 = AtomicU32::new(0);
static WND: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);
fn wnd_post(m: u32, l: isize) {
    let w = WND.load(Ordering::Relaxed);
    if w != 0 {
        unsafe {
            let _ = PostMessageW(HWND(w as *mut c_void), m, WPARAM(0), LPARAM(l));
        }
    }
}
fn decode_stream(stream: &comum::windows::Storage::Streams::IRandomAccessStreamWithContentType) -> Option<LogoPx> {
    unsafe {
        let is: IStream = CreateStreamOverRandomAccessStream(stream).ok()?;
        let f: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).ok()?;
        let dec = f.CreateDecoderFromStream(&is, std::ptr::null(), WICDecodeMetadataCacheOnDemand).ok()?;
        let cv = f.CreateFormatConverter().ok()?;
        cv.Initialize(&dec.GetFrame(0).ok()?, &GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).ok()?;
        let (mut w, mut h) = (0, 0);
        cv.GetSize(&mut w, &mut h).ok()?;
        let mut px = vec![0u8; (w * h * 4) as usize];
        cv.CopyPixels(std::ptr::null(), w * 4, &mut px).ok()?;
        Some(LogoPx { w, h, px })
    }
}
fn now_ft() -> i64 {
    unsafe {
        let f = GetSystemTimeAsFileTime();
        (f.dwHighDateTime as i64) << 32 | f.dwLowDateTime as i64
    }
}
/// lê uma notificação do Windows (texto do XML, app, hora)
fn parse(n: &UserNotification) -> Note {
    let mut x = Note { id: n.Id().unwrap_or(0), ..Default::default() };
    x.time = n.CreationTime().map(|d| d.UniversalTime).unwrap_or(0);
    if x.time <= 0 {
        x.time = now_ft(); // sem a hora: a hora em que a vimos
    }
    if let Ok(ai) = n.AppInfo() {
        x.aumid = ai.AppUserModelId().map(|s| s.to_string()).unwrap_or_default();
        x.app = ai.DisplayInfo().and_then(|d| d.DisplayName()).map(|s| s.to_string()).unwrap_or_default();
    }
    if x.aumid.is_empty() {
        x.aumid = "?".into();
    }
    if x.app.is_empty() {
        x.app = x.aumid.clone();
    }
    let _ = (|| -> Result<()> {
        let b = n.Notification()?.Visual()?.GetBinding(&KnownNotificationBindings::ToastGeneric()?)?;
        let mut i = 0;
        for e in b.GetTextElements()? {
            let t = e.Text()?.to_string();
            if t.is_empty() {
                continue;
            }
            if i == 0 {
                x.title = t;
            } else {
                if !x.body.is_empty() {
                    x.body.push('\n');
                }
                x.body += &t;
            }
            i += 1;
        }
        Ok(())
    })();
    if x.title.is_empty() {
        x.title = x.app.clone();
    }
    if x.body.chars().count() > 600 {
        x.body = x.body.chars().take(600).collect();
    }
    x
}
fn worker() {
    let l = UserNotificationListener::Current().ok();
    let mut last_sig = String::new();
    let mut seen: BTreeSet<u32> = BTreeSet::new();
    let mut first = true;
    // notificações já lidas, por id: só as novas são lidas (ler o XML de todas a cada segundo era o grosso do gasto)
    let mut parsed: HashMap<u32, Note> = HashMap::new();
    loop {
        let rm = std::mem::take(&mut DADOS.lock().unwrap().to_remove);
        if let Some(l) = &l {
            for id in rm {
                let _ = l.RemoveNotification(id);
            }
        }
        let mut access = 0;
        let mut notes: Vec<Note> = Vec::new();
        let mut logos: HashMap<String, LogoPx> = HashMap::new();
        if let Some(l) = &l {
            if let Ok(mut st) = l.GetAccessStatus() {
                if st == UserNotificationListenerAccessStatus::Unspecified {
                    st = l.RequestAccessAsync().and_then(|o| o.get()).unwrap_or(st);
                }
                access = (st == UserNotificationListenerAccessStatus::Allowed) as i32;
            }
        }
        if access == 1 {
            if let Some(l) = &l {
                if let Ok(list) = l.GetNotificationsAsync(NotificationKinds::Toast).and_then(|o| o.get()) {
                    let mut still = HashMap::new();
                    for n in list {
                        let nid = n.Id().unwrap_or(0);
                        if let Some(x) = parsed.remove(&nid) {
                            notes.push(x.clone());
                            still.insert(nid, x);
                            continue;
                        }
                        let x = parse(&n);
                        let known = DADOS.lock().unwrap().logos.contains_key(&x.aumid);
                        if !known && !logos.contains_key(&x.aumid) {
                            let lp = n
                                .AppInfo()
                                .and_then(|a| a.DisplayInfo())
                                .and_then(|d| d.GetLogo(Size { Width: 64.0, Height: 64.0 }))
                                .and_then(|r| r.OpenReadAsync())
                                .and_then(|o| o.get())
                                .ok()
                                .and_then(|s| decode_stream(&s))
                                .unwrap_or_default();
                            logos.insert(x.aumid.clone(), lp);
                        }
                        still.insert(x.id, x.clone());
                        notes.push(x);
                    }
                    parsed = still;
                }
            }
            let fresh = notes.iter().filter(|n| !first && !seen.contains(&n.id)).max_by_key(|n| n.time).map(|n| n.id);
            seen = notes.iter().map(|n| n.id).collect();
            first = false;
            if let Some(fid) = fresh {
                {
                    let mut d = DADOS.lock().unwrap();
                    d.data = notes.clone();
                    d.access = access;
                    for (a, p) in &logos {
                        d.logos.insert(a.clone(), p.clone());
                    }
                }
                wnd_post(WM_NC_NEW, fid as isize);
            }
        }
        let sig = format!("{access}:{}", notes.iter().map(|n| n.id.to_string()).collect::<Vec<_>>().join(","));
        let changed = sig != last_sig || !logos.is_empty();
        last_sig = sig;
        if changed {
            {
                let mut d = DADOS.lock().unwrap();
                d.data = notes;
                d.access = access;
                d.logos.extend(logos);
            }
            wnd_post(WM_NC_DATA, 0);
        }
        // painel aberto: 1 s; toast novo na tela: 0,4 s por 3 s; fora isso, 10 s (cada leitura monta TODAS de novo)
        let mut espera = 10000u64;
        let w = WND.load(Ordering::Relaxed);
        if w != 0 && unsafe { IsWindowVisible(HWND(w as *mut c_void)).as_bool() } {
            espera = 1000;
        }
        if (RAPIDO_ATE.load(Ordering::Relaxed).wrapping_sub(unsafe { GetTickCount() }) as i32) > 0 {
            espera = 400;
        }
        let g = DADOS.lock().unwrap();
        let (mut g, _) = CV.wait_timeout_while(g, std::time::Duration::from_millis(espera), |d| !d.wake).unwrap();
        g.wake = false;
    }
}
fn wake() {
    DADOS.lock().unwrap().wake = true;
    CV.notify_all();
}
// ================= estado da tela
#[derive(Clone)]
struct Group {
    aumid: String,
    app: String,
    notes: Vec<Note>,
}
/// um widget embaixo das notificações (o widgets.cpp pode trocar a lista)
pub struct Widget {
    pub w: f32,
    pub h: f32,
    pub paint: Box<dyn Fn(&ID2D1DeviceContext, f32, f32, bool)>,
    pub click: Option<Rc<dyn Fn()>>,
}
#[derive(Clone, Copy, PartialEq)]
enum Kind {
    Card,
    Under,
    Header,
    Pill,
    Circle,
    Widget,
    Label,
    Empty,
}
#[derive(Clone, Copy, PartialEq)]
enum Act {
    None,
    Card,
    Stack,
    ShowLess,
    ClearGroup,
    ClearAll,
    More,
    Edit,
    Settings,
    Permission,
    Widget,
}
#[derive(Clone)]
struct El {
    key: String,
    kind: Kind,
    r: RectF,
    act: Act,
    group: i32,
    note: i32,
    layer: i32,
    widget: i32,
    text: String,
    from: Option<RectF>,
    cut_top: f32,
}
impl El {
    fn new(key: String, kind: Kind, r: RectF, act: Act) -> El {
        El { key, kind, r, act, group: -1, note: -1, layer: 0, widget: -1, text: String::new(), from: None, cut_top: -1e9 }
    }
}
#[derive(Clone, Copy, Default)]
struct Spring1 {
    x: f32,
    v: f32,
}
#[derive(Clone)]
struct Anim {
    el: El,
    l: Spring1,
    t: Spring1,
    r: Spring1,
    b: Spring1,
    a: Spring1,
    live: bool,
    anchor: String,
    emerge: bool,
    from_top: f32,
}
#[derive(Clone)]
struct Hit {
    r: RectF,
    act: Act,
    group: i32,
    note: i32,
    widget: i32,
    key: String,
}
#[derive(Clone)]
struct Ban {
    n: Note,
    at: f64,
    out_at: f64,
    until: u64,
    y: f32,
}
/// vidro: um recorte arredondado de desfoque por cartão (Windows.UI.Composition)
struct Glass {
    outer: ContainerVisual,
    body: ContainerVisual,
    geo: CompositionRoundedRectangleGeometry,
    tint: CompositionColorBrush,
    cut: InsetClip,
    blur: SpriteVisual,
}
#[derive(Default)]
struct GlassHost {
    target: Option<DesktopWindowTarget>,
    root: Option<ContainerVisual>,
    pool: Vec<Glass>,
    used: usize,
}
struct N {
    wnd: HWND,
    back: HWND,
    s: ui::GpuSurface,
    open: bool,
    closing: bool,
    menu: bool,
    slide_at: f64,
    slide: f32,
    closed_at: u32,
    scroll: f32,
    scroll_target: f32,
    content_h: f32,
    last_frame: f64,
    click_at: u32,
    snap: bool,
    running: bool,
    frame_msg_at: f64,
    tf: Option<[IDWriteTextFormat; 6]>,
    groups: Vec<Group>,
    expanded: BTreeSet<String>,
    show_all: bool,
    access_ui: i32,
    icons: HashMap<String, Option<ID2D1Bitmap>>,
    bodies: HashMap<u32, (Option<IDWriteTextLayout>, i32)>,
    widgets: Vec<Widget>,
    widget_kind: Vec<usize>,
    edit_widgets: Option<Rc<dyn Fn()>>,
    custom_widgets: bool,
    anim: BTreeMap<String, Anim>,
    order: Vec<String>,
    hits: Vec<Hit>,
    hover: String,
    hover_part: String,
    expanded_at: u32,
    fundo_claro: bool,
    host_panel: GlassHost,
    host_banner: GlassHost,
    banner_host: bool,
    has_glass: bool,
    /// o banner tem o vidro dele: antes dependia do vidro do painel e, com o vidro real, ficava sem (issue #138)
    has_banner_glass: bool,
    real: bool,
    pecas: Vec<backdrop::Piece>,
    peca_tinta: Cor,
    // banner
    bwnd: HWND,
    bback: HWND,
    bs: ui::GpuSurface,
    bans: Vec<Ban>,
    bhover: i32,
    bhover_x: bool,
    blast: f64,
    bh_px: i32,
    toast: HWND,
    toast_rect: RECT,
    toast_moved: bool,
    avisados: BTreeSet<String>,
    avisados_lidos: bool,
    /// modo foto: onde a coluna estaria (px de tela) e o tamanho (DIP)
    foto: Option<(f32, f32, f32)>,
}
static NS: Global<Option<N>> = Global::new(None);
fn n() -> &'static mut N {
    NS.get().get_or_insert_with(|| N {
        wnd: HWND::default(),
        back: HWND::default(),
        s: ui::GpuSurface::default(),
        open: false,
        closing: false,
        menu: false,
        slide_at: 0.0,
        slide: 1.0,
        closed_at: 0,
        scroll: 0.0,
        scroll_target: 0.0,
        content_h: 0.0,
        last_frame: 0.0,
        click_at: 0,
        snap: false,
        running: false,
        frame_msg_at: 0.0,
        tf: None,
        groups: Vec::new(),
        expanded: BTreeSet::new(),
        show_all: false,
        access_ui: -1,
        icons: HashMap::new(),
        bodies: HashMap::new(),
        widgets: Vec::new(),
        widget_kind: Vec::new(),
        edit_widgets: None,
        custom_widgets: false,
        anim: BTreeMap::new(),
        order: Vec::new(),
        hits: Vec::new(),
        hover: String::new(),
        hover_part: String::new(),
        expanded_at: 0,
        fundo_claro: false,
        host_panel: GlassHost::default(),
        host_banner: GlassHost::default(),
        banner_host: false,
        has_glass: false,
        has_banner_glass: false,
        real: false,
        pecas: Vec::new(),
        peca_tinta: col(0.13, 0.13, 0.14, 0.5),
        bwnd: HWND::default(),
        bback: HWND::default(),
        bs: ui::GpuSurface::default(),
        bans: Vec::new(),
        bhover: -1,
        bhover_x: false,
        blast: 0.0,
        bh_px: 0,
        toast: HWND::default(),
        toast_rect: RECT::default(),
        toast_moved: false,
        avisados: BTreeSet::new(),
        avisados_lidos: false,
        foto: None,
    })
}
fn tf(i: usize) -> IDWriteTextFormat {
    n().tf.as_ref().unwrap()[i].clone()
}
const TF_TITLE: usize = 0;
const TF_BODY: usize = 1;
const TF_TIME: usize = 2;
const TF_PILL: usize = 3;
const TF_HEADER: usize = 4;
const TF_EMPTY: usize = 5;
fn rebuild() {
    let st = n();
    let mut data;
    {
        let d = DADOS.lock().unwrap();
        data = d.data.clone();
        st.access_ui = d.access;
    }
    // as mais novas em cima (issue #8); mesma hora: a de id maior vem antes
    data.sort_by(|a, b| b.time.cmp(&a.time).then(b.id.cmp(&a.id)));
    st.groups.clear();
    for nt in &data {
        if let Some(g) = st.groups.iter_mut().find(|g| g.aumid == nt.aumid) {
            g.notes.push(nt.clone());
        } else {
            st.groups.push(Group { aumid: nt.aumid.clone(), app: nt.app.clone(), notes: vec![nt.clone()] });
        }
    }
    let gs = st.groups.clone();
    st.expanded.retain(|a| gs.iter().any(|g| &g.aumid == a && g.notes.len() >= 2));
    let live: BTreeSet<u32> = data.iter().map(|x| x.id).collect();
    st.bodies.retain(|k, _| live.contains(k));
}
fn remove_ids(ids: &[u32]) {
    {
        let mut d = DADOS.lock().unwrap();
        for &id in ids {
            d.to_remove.push(id);
            d.data.retain(|x| x.id != id);
        }
    }
    wake();
    rebuild();
}
// ---- vidro
/// vidro do host atual (fosco do Composition)
fn host_glass() -> bool {
    let st = n();
    if st.banner_host {
        st.has_banner_glass
    } else {
        st.has_glass
    }
}
/// o cartão já tem vidro de algum tipo (inclui o vidro real do painel)
fn card_glass() -> bool {
    host_glass() || (n().real && !n().banner_host)
}
fn glass_init(h: HWND, banner: bool) -> bool {
    let Some(comp) = backdrop::compositor() else { return false };
    let r = (|| -> Result<GlassHost> {
        unsafe {
            let on = BOOL(1);
            let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(17), &on as *const _ as *const c_void, 4);
        }
        let interop: ICompositorDesktopInterop = comp.cast()?;
        let target = unsafe { interop.CreateDesktopWindowTarget(h, false)? };
        let root = comp.CreateContainerVisual()?;
        root.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;
        target.SetRoot(&root)?;
        Ok(GlassHost { target: Some(target), root: Some(root), pool: Vec::new(), used: 0 })
    })();
    match r {
        Ok(g) => {
            if banner {
                n().host_banner = g;
            } else {
                n().host_panel = g;
            }
            true
        }
        Err(_) => false,
    }
}
fn host() -> &'static mut GlassHost {
    if n().banner_host {
        &mut n().host_banner
    } else {
        &mut n().host_panel
    }
}
fn ucol(t: Cor) -> Color {
    let c8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
    Color { A: c8(t.a), R: c8(t.r), G: c8(t.g), B: c8(t.b) }
}
/// um retângulo de vidro (DIP, com a transformação da superfície); cut_top: só abaixo dessa linha (camadas da pilha)
unsafe fn glass_rect(dc: &ID2D1DeviceContext, r: RectF, radius: f32, tint: Cor, alpha: f32, cut_top: f32) {
    let st = n();
    let k = sc();
    if st.foto.is_some() {
        // na foto: o fundo desfocado do papel de parede, com a mesma tinta
        let clip = cut_top > r.top;
        if clip {
            dc.PushAxisAlignedClip(&rf(-1e5, cut_top, 1e5, 1e5), D2D1_ANTIALIAS_MODE_ALIASED);
        }
        let fade = alpha < 0.999;
        if fade {
            let lp = D2D1_LAYER_PARAMETERS1 { contentBounds: rf(-1e7, -1e7, 1e7, 1e7), geometricMask: std::mem::ManuallyDrop::new(None), maskAntialiasMode: D2D1_ANTIALIAS_MODE_PER_PRIMITIVE, maskTransform: mat::ident(), opacity: alpha, opacityBrush: std::mem::ManuallyDrop::new(None), layerOptions: D2D1_LAYER_OPTIONS1_NONE };
            dc.PushLayer(&lp, None);
        }
        backdrop::foto_vidro(dc, r, radius, tint);
        if fade {
            dc.PopLayer();
        }
        if clip {
            dc.PopAxisAlignedClip();
        }
        return;
    }
    let mut pr = rf(r.left * k, r.top * k, r.right * k, r.bottom * k);
    let cut = cut_top * k;
    if st.real && !st.banner_host {
        // vidro real (issue #51): só junta a peça (o recorte das camadas da pilha vira o topo dela)
        if cut > pr.top {
            pr.top = cut;
        }
        if pr.bottom - pr.top > 2.0 && alpha > 0.05 {
            if st.pecas.is_empty() {
                st.peca_tinta = tint;
            }
            st.pecas.push(backdrop::Piece { r: pr, radius: radius * k, ..Default::default() });
        }
        return;
    }
    if !host_glass() {
        return;
    }
    let h = host();
    let Some(root) = h.root.clone() else { return };
    let Some(comp) = backdrop::compositor() else { return };
    let _ = (|| -> Result<()> {
        if h.used == h.pool.len() {
            let outer = comp.CreateContainerVisual()?;
            outer.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;
            let cut = comp.CreateInsetClip()?;
            outer.SetClip(&cut)?;
            let body = comp.CreateContainerVisual()?;
            let blur = comp.CreateSpriteVisual()?;
            blur.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;
            blur.SetBrush(&comp.CreateHostBackdropBrush()?)?;
            let tv = comp.CreateSpriteVisual()?;
            tv.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;
            let tint_b = comp.CreateColorBrush()?;
            tv.SetBrush(&tint_b)?;
            body.Children()?.InsertAtTop(&blur)?;
            body.Children()?.InsertAtTop(&tv)?;
            let geo = comp.CreateRoundedRectangleGeometry()?;
            body.SetClip(&comp.CreateGeometricClipWithGeometry(&geo)?)?;
            outer.Children()?.InsertAtTop(&body)?;
            root.Children()?.InsertAtTop(&outer)?;
            h.pool.push(Glass { outer, body, geo, tint: tint_b, cut, blur });
        }
        let g = &h.pool[h.used];
        h.used += 1;
        g.outer.SetIsVisible(true)?;
        if liquid::on() {
            if let Some(f) = backdrop::frost() {
                g.blur.SetBrush(&f)?; // Tahoe: o mesmo fosco + vibrância do Dock
            }
        }
        g.outer.SetOpacity(alpha.clamp(0.0, 1.0))?;
        g.cut.SetTopInset(cut.max(0.0))?;
        g.body.SetOffset(Vector3 { X: pr.left, Y: pr.top, Z: 0.0 })?;
        let sz = Vector2 { X: pr.right - pr.left, Y: pr.bottom - pr.top };
        g.body.SetSize(sz)?;
        g.geo.SetSize(sz)?;
        g.geo.SetCornerRadius(Vector2 { X: radius * k, Y: radius * k })?;
        g.tint.SetColor(ucol(tint))?;
        Ok(())
    })();
}
fn glass_end() {
    let st = n();
    if st.foto.is_some() {
        return;
    }
    if st.real && !st.banner_host {
        let mut wr = RECT::default();
        unsafe {
            let _ = GetClientRect(st.back, &mut wr);
        }
        backdrop::set_pieces(st.back, wr.right as f32, wr.bottom as f32, &st.pecas, st.peca_tinta, 0.0);
        st.pecas.clear();
        return;
    }
    if !host_glass() {
        return;
    }
    let h = host();
    for g in h.pool.iter().skip(h.used) {
        let _ = g.outer.SetIsVisible(false);
    }
}
// ================= cores
#[derive(Clone, Copy)]
struct Pal {
    tint: Cor,
    tint_pill: Cor,
    text: Cor,
    text2: Cor,
    line: Cor,
    close: Cor,
    close_glyph: Cor,
    chip: Cor,
    header: Cor,
}
fn colors() -> Pal {
    let p = |a: [Cor; 9]| Pal { tint: a[0], tint_pill: a[1], text: a[2], text2: a[3], line: a[4], close: a[5], close_glyph: a[6], chip: a[7], header: a[8] };
    if liquid::leopard() {
        return p([col(0.97, 0.97, 0.97, 0.95), col(0.95, 0.95, 0.95, 0.95), col(0.0, 0.0, 0.0, 0.90), col(0.0, 0.0, 0.0, 0.60), col(0.0, 0.0, 0.0, 0.25), col(0.93, 0.93, 0.93, 1.0), col(0.0, 0.0, 0.0, 0.70), col(0.0, 0.0, 0.0, 0.08), col(1.0, 1.0, 1.0, 0.97)]);
    }
    let dark = ui::dark();
    if liquid::on() {
        return if dark {
            p([col(0.10, 0.10, 0.11, 0.40), col(0.16, 0.16, 0.17, 0.36), col(1.0, 1.0, 1.0, 0.95), col(1.0, 1.0, 1.0, 0.62), col(1.0, 1.0, 1.0, 0.10), col(0.24, 0.24, 0.25, 0.98), col(1.0, 1.0, 1.0, 0.85), col(1.0, 1.0, 1.0, 0.14), col(1.0, 1.0, 1.0, 0.97)])
        } else {
            p([col(1.0, 1.0, 1.0, 0.50), col(1.0, 1.0, 1.0, 0.42), col(0.0, 0.0, 0.0, 0.88), col(0.0, 0.0, 0.0, 0.55), col(1.0, 1.0, 1.0, 0.45), col(0.98, 0.98, 0.98, 0.98), col(0.0, 0.0, 0.0, 0.62), col(0.0, 0.0, 0.0, 0.07), col(1.0, 1.0, 1.0, 0.97)])
        };
    }
    if dark {
        p([col(0.13, 0.13, 0.14, 0.68), col(0.20, 0.20, 0.21, 0.62), col(1.0, 1.0, 1.0, 0.92), col(1.0, 1.0, 1.0, 0.55), col(1.0, 1.0, 1.0, 0.10), col(0.24, 0.24, 0.25, 0.98), col(1.0, 1.0, 1.0, 0.85), col(1.0, 1.0, 1.0, 0.12), col(1.0, 1.0, 1.0, 0.95)])
    } else {
        p([col(0.97, 0.97, 0.98, 0.72), col(0.97, 0.97, 0.98, 0.62), col(0.0, 0.0, 0.0, 0.86), col(0.0, 0.0, 0.0, 0.50), col(1.0, 1.0, 1.0, 0.45), col(0.98, 0.98, 0.98, 0.98), col(0.0, 0.0, 0.0, 0.62), col(0.0, 0.0, 0.0, 0.07), col(1.0, 1.0, 1.0, 0.97)])
    }
}
// ================= textos
fn ft_to_st(ft: i64) -> SYSTEMTIME {
    unsafe {
        let f = FILETIME { dwLowDateTime: ft as u32, dwHighDateTime: (ft >> 32) as u32 };
        let mut lf = FILETIME::default();
        let mut t = SYSTEMTIME::default();
        let _ = comum::windows::Win32::Storage::FileSystem::FileTimeToLocalFileTime(&f, &mut lf);
        let _ = comum::windows::Win32::System::Time::FileTimeToSystemTime(&lf, &mut t);
        t
    }
}
fn when(ft: i64) -> String {
    if ft == 0 {
        return String::new();
    }
    let now = now_ft();
    let mins = (now - ft) / 600_000_000;
    if mins < 1 {
        return tr("agora");
    }
    if mins < 60 {
        return format!("{mins}{}", tr(" min atrás"));
    }
    let (t, tn) = (ft_to_st(ft), ft_to_st(now));
    let day = |s: &SYSTEMTIME| {
        let d = SYSTEMTIME { wYear: s.wYear, wMonth: s.wMonth, wDay: s.wDay, wDayOfWeek: s.wDayOfWeek, ..Default::default() };
        let mut x = FILETIME::default();
        unsafe {
            let _ = comum::windows::Win32::System::Time::SystemTimeToFileTime(&d, &mut x);
        }
        ((x.dwHighDateTime as i64) << 32 | x.dwLowDateTime as i64) / 864_000_000_000
    };
    let days = day(&tn) - day(&t);
    let hm = shell::hora(&t, false, true);
    if days <= 0 {
        hm
    } else if days == 1 {
        tr("Ontem, ") + &hm
    } else if days < 7 {
        format!("{days}{}", tr(" dias atrás"))
    } else {
        format!("{:02}/{:02}", t.wDay, t.wMonth)
    }
}
fn fmt(size: f32, wt: DWRITE_FONT_WEIGHT, family: Option<&str>, wrap: bool) -> IDWriteTextFormat {
    let tf = match family {
        Some(f) => ui::format_face(f, size, wt),
        None => ui::fmt(size, wt),
    };
    unsafe {
        let _ = tf.SetWordWrapping(if wrap { DWRITE_WORD_WRAPPING_WRAP } else { DWRITE_WORD_WRAPPING_NO_WRAP });
        let ell = ui::dw().CreateEllipsisTrimmingSign(&tf).ok();
        let t = DWRITE_TRIMMING { granularity: if wrap { DWRITE_TRIMMING_GRANULARITY_WORD } else { DWRITE_TRIMMING_GRANULARITY_CHARACTER }, delimiter: 0, delimiterCount: 0 };
        let _ = tf.SetTrimming(&t, ell.as_ref());
    }
    tf
}
/// o título e os avisos soltos ficam direto sobre o que está atrás: escuros se o fundo for claro (issue #8)
fn cor_solta() -> Cor {
    if n().fundo_claro {
        col(0.0, 0.0, 0.0, 0.85)
    } else {
        col(1.0, 1.0, 1.0, 0.97)
    }
}
#[allow(clippy::too_many_arguments)]
unsafe fn text(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, s: &str, tf: &IDWriteTextFormat, r: RectF, c: Cor, al: DWRITE_TEXT_ALIGNMENT, shadow: bool) {
    if s.is_empty() {
        return;
    }
    let _ = tf.SetTextAlignment(al);
    let _ = tf.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
    let w_ = w(s);
    if shadow {
        for (dy, a) in [(1.0, 0.22), (0.0, 0.10)] {
            br.SetColor(&col(0.0, 0.0, 0.0, a * c.a));
            dc.DrawText(&w_, tf, &rf(r.left, r.top + dy, r.right, r.bottom + dy), br, D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
        }
    }
    br.SetColor(&c);
    dc.DrawText(&w_, tf, &r, br, D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
}
const LEAD: DWRITE_TEXT_ALIGNMENT = DWRITE_TEXT_ALIGNMENT_LEADING;
const CENTER: DWRITE_TEXT_ALIGNMENT = DWRITE_TEXT_ALIGNMENT_CENTER;
fn text_w(tf: &IDWriteTextFormat, s: &str) -> f32 {
    ui::text_width(tf, s)
}
/// o corpo da notificação quebrado em até 3 linhas
fn body(nt: &Note) -> (Option<IDWriteTextLayout>, i32) {
    let st = n();
    if let Some(b) = st.bodies.get(&nt.id) {
        return b.clone();
    }
    let mut e = (None, 0);
    if !nt.body.is_empty() {
        let w_ = CARD_W - TEXT_X - PAD_R;
        unsafe {
            if let Ok(lay) = ui::dw().CreateTextLayout(&w(&nt.body), &tf(TF_BODY), w_, 10000.0) {
                let mut m = DWRITE_TEXT_METRICS::default();
                let _ = lay.GetMetrics(&mut m);
                let lines = (m.lineCount as i32).clamp(1, MAX_LINES);
                let _ = lay.SetMaxHeight(lines as f32 * LINE_H);
                e = (Some(lay), lines);
            }
        }
    }
    st.bodies.insert(nt.id, e.clone());
    e
}
fn card_h(nt: &Note) -> f32 {
    let b = body(nt);
    if liquid::on() {
        return 57f32.max(12.0 + 16.0 + b.1 as f32 * 16.0 + 13.0);
    }
    MIN_H.max(PAD_V + TITLE_H + b.1 as f32 * LINE_H + PAD_V)
}
// ================= layout com animação: cada peça tem uma chave e anda com mola até o lugar novo
fn layout() -> Vec<El> {
    let st = n();
    let mut out = Vec::new();
    let mut y = top();
    let tp = tf(TF_PILL);
    if st.access_ui == 0 {
        out.push(El::new("empty".into(), Kind::Empty, rf(0.0, y, CARD_W, y + 118.0), Act::None));
        y += 118.0 + GROUP_GAP;
        let mut p = El::new("perm".into(), Kind::Pill, rf(0.0, 0.0, 0.0, 0.0), Act::Permission);
        p.text = tr("Permitir Acesso às Notificações…");
        let w_ = text_w(&tp, &p.text) + 28.0;
        p.r = rf((CARD_W - w_) / 2.0, y - 48.0, (CARD_W + w_) / 2.0, y - 48.0 + PILL_H);
        out.push(p);
    } else if st.access_ui == 1 && st.groups.is_empty() {
        let mut e = El::new("none".into(), Kind::Label, rf(0.0, y, CARD_W, y + 30.0), Act::None);
        e.text = tr("Sem Notificações");
        out.push(e);
        y += 30.0 + GROUP_GAP;
    }
    if liquid::golden() && !st.groups.is_empty() {
        // macOS 27: título "Central de Notificações" e, à direita, o × num círculo que limpa tudo
        let mut h = El::new("h:central".into(), Kind::Header, rf(0.0, y, CARD_W, y + 30.0), Act::None);
        h.text = tr("Central de Notificações");
        h.layer = 7;
        out.push(h);
        out.push(El::new("hx:central".into(), Kind::Circle, rf(CARD_W - 20.0, y + 5.0, CARD_W, y + 25.0), Act::ClearAll));
        y += 36.0;
    }
    let (mut shown, mut hidden_notes) = (0usize, 0usize);
    for (gi, g) in st.groups.clone().iter().enumerate() {
        if !st.show_all && shown >= MAX_GROUPS {
            hidden_notes += g.notes.len();
            continue;
        }
        shown += 1;
        let expanded = g.notes.len() > 1 && st.expanded.contains(&g.aumid);
        let top_key = format!("n:{}", g.notes[0].id);
        if expanded {
            let mut h = El::new(format!("h:{}", g.aumid), Kind::Header, rf(0.0, y, CARD_W, y + HEADER_H), Act::None);
            h.text = g.app.clone();
            h.group = gi as i32;
            out.push(h);
            let mut x = El::new(format!("hx:{}", g.aumid), Kind::Circle, rf(CARD_W - CIRCLE, y + (HEADER_H - CIRCLE) / 2.0, CARD_W, y + (HEADER_H + CIRCLE) / 2.0), Act::ClearGroup);
            x.group = gi as i32;
            let xl = x.r.left;
            out.push(x);
            let mut p = El::new(format!("hp:{}", g.aumid), Kind::Pill, rf(0.0, 0.0, 0.0, 0.0), Act::ShowLess);
            p.text = tr("Mostrar menos");
            p.group = gi as i32;
            let w_ = text_w(&tp, &p.text) + 26.0;
            p.r = rf(xl - 8.0 - w_, y + (HEADER_H - PILL_H) / 2.0, xl - 8.0, y + (HEADER_H + PILL_H) / 2.0);
            out.push(p);
            y += HEADER_H + GAP;
            // pilha com centenas (o Chrome guarda todas): mostra as 20 mais novas
            const MAX_OPEN: usize = 20;
            let n_open = g.notes.len().min(MAX_OPEN);
            let mut first = rf(0.0, 0.0, 0.0, 0.0);
            let mut cards = Vec::new();
            for ni in 0..n_open {
                let h2 = card_h(&g.notes[ni]);
                let mut c = El::new(format!("n:{}", g.notes[ni].id), Kind::Card, rf(0.0, y, CARD_W, y + h2), Act::Card);
                c.group = gi as i32;
                c.note = ni as i32;
                if ni == 0 {
                    first = c.r;
                } else {
                    c.from = Some(rf(first.left, first.top, first.right, first.top + h2));
                }
                cards.push(c);
                y += h2 + GAP;
            }
            // as de baixo são desenhadas antes: ao abrir saem de trás do cartão de cima
            out.extend(cards.into_iter().rev());
            if g.notes.len() > n_open {
                let rest = g.notes.len() - n_open;
                let mut more = El::new(format!("hm:{}", g.aumid), Kind::Label, rf(0.0, y, CARD_W, y + 22.0), Act::None);
                more.text = format!("{rest}{}", tr(if rest == 1 { " notificação mais antiga" } else { " notificações mais antigas" }));
                out.push(more);
                y += 22.0 + GAP;
            }
            y += GROUP_GAP - GAP;
        } else {
            let h2 = card_h(&g.notes[0]);
            let tr_ = rf(0.0, y, CARD_W, y + h2);
            let layers = 2.min(g.notes.len() as i32 - 1);
            for kk in (1..=layers).rev() {
                let kf = kk as f32;
                let mut u = El::new(format!("u:{}:{kk}", g.aumid), Kind::Under, rf(PEEK_INSET * kf, tr_.bottom + PEEK * kf - h2, CARD_W - PEEK_INSET * kf, tr_.bottom + PEEK * kf), Act::Stack);
                u.group = gi as i32;
                u.layer = kk;
                u.cut_top = tr_.bottom + PEEK * (kf - 1.0) - 0.5;
                u.from = Some(rf(u.r.left, tr_.top, u.r.right, tr_.bottom));
                out.push(u);
            }
            let mut c = El::new(top_key, Kind::Card, tr_, if layers > 0 { Act::Stack } else { Act::Card });
            c.group = gi as i32;
            c.note = 0;
            out.push(c);
            y += h2 + PEEK * layers as f32 + GROUP_GAP;
        }
    }
    if hidden_notes > 0 || (st.groups.len() > 1 && !liquid::golden()) {
        let mut p = El::new("p:list".into(), Kind::Pill, rf(0.0, 0.0, 0.0, 0.0), Act::None);
        if hidden_notes > 0 {
            p.act = Act::More;
            p.text = format!("{hidden_notes}{}", tr(if hidden_notes == 1 { " notificação a mais" } else { " notificações a mais" }));
        } else {
            p.act = Act::ClearAll;
            p.text = tr("Limpar");
        }
        let w_ = text_w(&tp, &p.text) + 26.0;
        p.r = rf((CARD_W - w_) / 2.0, y, (CARD_W + w_) / 2.0, y + PILL_H);
        out.push(p);
        y += PILL_H + GROUP_GAP;
    }
    // widgets em linhas de 344 (pequeno 164 × 164, médio 344 × 164)
    y += 6.0;
    let (mut x, mut row_h) = (0.0f32, 0.0f32);
    for (i, w_) in st.widgets.iter().enumerate() {
        if x > 0.0 && x + w_.w > CARD_W + 0.5 {
            y += row_h + WIDGET_GAP;
            x = 0.0;
            row_h = 0.0;
        }
        let mut e = El::new(format!("w:{i}"), Kind::Widget, rf(x, y, x + w_.w, y + w_.h), Act::Widget);
        e.widget = i as i32;
        out.push(e);
        x += w_.w + WIDGET_GAP;
        row_h = row_h.max(w_.h);
    }
    if !st.widgets.is_empty() {
        y += row_h + 14.0;
    }
    let mut ed = El::new("b:edit".into(), Kind::Pill, rf(0.0, 0.0, 0.0, 0.0), Act::Edit);
    ed.text = tr("Editar Widgets…");
    let ew = text_w(&tp, &ed.text) + 26.0;
    let bx = (CARD_W - (ew + 8.0 + CIRCLE)) / 2.0;
    ed.r = rf(bx, y, bx + ew, y + PILL_H);
    out.push(ed);
    out.push(El::new("b:gear".into(), Kind::Circle, rf(bx + ew + 8.0, y, bx + ew + 8.0 + CIRCLE, y + CIRCLE), Act::Settings));
    y += PILL_H + 16.0;
    st.content_h = y;
    out
}
fn sync(els: &[El]) {
    let st = n();
    for a in st.anim.values_mut() {
        a.live = false;
    }
    let mut top_of_group: HashMap<i32, String> = HashMap::new();
    for e in els {
        if e.kind == Kind::Card && e.note == 0 {
            top_of_group.insert(e.group, e.key.clone());
        }
    }
    st.order.clear();
    for e in els {
        st.order.push(e.key.clone());
        let snap = st.snap;
        let a = st.anim.entry(e.key.clone()).or_insert_with(|| {
            let f = if let (Some(fr), false) = (e.from, snap) { fr } else { e.r };
            Anim {
                el: e.clone(),
                l: Spring1 { x: f.left, v: 0.0 },
                t: Spring1 { x: f.top, v: 0.0 },
                r: Spring1 { x: f.right, v: 0.0 },
                b: Spring1 { x: f.bottom, v: 0.0 },
                a: Spring1 { x: if snap { 1.0 } else { 0.0 }, v: 0.0 },
                live: true,
                anchor: String::new(),
                emerge: e.from.is_some() && !snap && e.kind == Kind::Card,
                from_top: e.from.map(|f| f.top).unwrap_or(0.0),
            }
        });
        a.el = e.clone();
        a.live = true;
        if e.group >= 0 {
            if let Some(t) = top_of_group.get(&e.group) {
                a.anchor = t.clone();
            }
        }
    }
    // as que saíram ficam no fim da ordem e somem (as de um grupo que fechou sobem para o cartão de cima)
    let keys: Vec<String> = st.anim.keys().cloned().collect();
    for k in keys {
        let a = st.anim.get_mut(&k).unwrap();
        if a.live {
            continue;
        }
        if !st.order.contains(&k) {
            st.order.insert(0, k.clone());
        }
        if !a.anchor.is_empty() {
            if let Some(t) = els.iter().find(|e| e.key == a.anchor) {
                let h = a.el.r.bottom - a.el.r.top;
                a.el.r = rf(t.r.left, t.r.top, t.r.right, t.r.top + h);
            }
        }
    }
    if st.snap {
        for a in st.anim.values_mut() {
            a.l = Spring1 { x: a.el.r.left, v: 0.0 };
            a.t = Spring1 { x: a.el.r.top, v: 0.0 };
            a.r = Spring1 { x: a.el.r.right, v: 0.0 };
            a.b = Spring1 { x: a.el.r.bottom, v: 0.0 };
        }
    }
    st.snap = false;
}
fn step(s: &mut Spring1, target: f32, dt: f32) -> bool {
    let w_ = 2.0 * std::f32::consts::PI / 0.38;
    let acc = -w_ * w_ * (s.x - target) - 2.0 * w_ * s.v;
    s.v += acc * dt;
    s.x += s.v * dt;
    if (s.x - target).abs() < 0.05 && s.v.abs() < 0.5 {
        *s = Spring1 { x: target, v: 0.0 };
        return false;
    }
    true
}
fn settled() -> bool {
    let st = n();
    for a in st.anim.values() {
        if (a.l.x - a.el.r.left).abs() > 0.05 || (a.t.x - a.el.r.top).abs() > 0.05 || (a.r.x - a.el.r.right).abs() > 0.05 || (a.b.x - a.el.r.bottom).abs() > 0.05 {
            return false;
        }
        if (a.a.x - if a.live { 1.0 } else { 0.0 }).abs() > 0.01 {
            return false;
        }
    }
    (st.scroll - st.scroll_target).abs() < 0.3
}
fn advance(dt: f32) -> bool {
    let st = n();
    let mut busy = false;
    let mut gone = Vec::new();
    for (k, a) in st.anim.iter_mut() {
        let r = a.el.r;
        busy |= step(&mut a.l, r.left, dt);
        busy |= step(&mut a.t, r.top, dt);
        busy |= step(&mut a.r, r.right, dt);
        busy |= step(&mut a.b, r.bottom, dt);
        let ta = if a.live { 1.0 } else { 0.0 };
        a.a.x += (ta - a.a.x) * (dt * if a.live { 14.0 } else { 18.0 }).min(1.0);
        if (a.a.x - ta).abs() < 0.01 {
            a.a.x = ta;
        } else {
            busy = true;
        }
        if !a.live && a.a.x <= 0.0 {
            gone.push(k.clone());
        }
    }
    for k in gone {
        st.anim.remove(&k);
        st.order.retain(|x| *x != k);
    }
    let before = st.scroll;
    st.scroll += (st.scroll_target - st.scroll) * (dt * 16.0).min(1.0);
    if (st.scroll - st.scroll_target).abs() < 0.3 {
        st.scroll = st.scroll_target;
    } else {
        busy = true;
    }
    busy | (before != st.scroll)
}
// ================= desenho
fn sc() -> f32 {
    if n().foto.is_some() {
        return ui::foto_scale();
    }
    ui::scale(n().wnd)
}
fn icon_for(dc: &ID2D1DeviceContext, g: &Group) -> Option<ID2D1Bitmap> {
    let st = n();
    if let Some(b) = st.icons.get(&g.aumid) {
        return b.clone();
    }
    let exe = if g.aumid.contains('!') { String::new() } else { format!("\\{}.exe", g.aumid) };
    // issue #8: o ícone próprio escolhido no Dock vale também aqui
    let mut own = String::new();
    for a in apps::list().iter() {
        let same = a.name.eq_ignore_ascii_case(&g.app) || a.id.eq_ignore_ascii_case(&format!("aumid:{}", g.aumid)) || (!exe.is_empty() && a.exe.to_lowercase().ends_with(&exe.to_lowercase()));
        if same {
            own = apps::custom_icon(if a.finder { "Finder" } else { &a.name }, if a.finder { "" } else if a.exe.is_empty() { &a.id } else { &a.exe });
            break;
        }
    }
    if own.is_empty() {
        own = apps::custom_icon(&g.app, &exe);
    }
    let mut img = if own.is_empty() { None } else { ui::load_png(&own) };
    if img.is_none() {
        let png = apps::pack_icon_by_name(&g.app, &exe);
        if !png.is_empty() {
            img = ui::load_png(&png);
        }
    }
    if img.is_none() {
        // app sem ícone do pacote: o do Windows (pela lista de apps), senão o logo da notificação
        if let Some(a) = apps::list().iter_mut().find(|a| a.name.eq_ignore_ascii_case(&g.app) || a.id.eq_ignore_ascii_case(&format!("aumid:{}", g.aumid))) {
            apps::ensure_icon(a, 64);
            if !a.icon.is_empty() {
                img = Some(ui::Img { w: a.iw, h: a.ih, px: a.icon.clone() });
            }
        }
    }
    if img.is_none() && g.aumid.contains('!') {
        if let Some(mut i) = ui::shell_image(&format!("shell:AppsFolder\\{}", g.aumid), 64, true) {
            ui::trim_to_square(&mut i);
            img = Some(i);
        }
    }
    if img.is_none() {
        let d = DADOS.lock().unwrap();
        match d.logos.get(&g.aumid) {
            Some(lg) if !lg.px.is_empty() => img = Some(ui::Img { w: lg.w, h: lg.h, px: lg.px.clone() }),
            None if st.foto.is_none() => return None, // logo ainda não lido: tenta de novo depois
            _ => {}
        }
    }
    let bmp = img.and_then(|i| ui::bitmap(&dc.cast().unwrap(), i.w, i.h, &i.px));
    st.icons.insert(g.aumid.clone(), bmp.clone());
    bmp
}
unsafe fn draw_icon(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, g: &Group, r: RectF) {
    if let Some(b) = icon_for(dc, g) {
        dc.DrawBitmap(&b, Some(&r), 1.0, D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC, None, None);
        return;
    }
    br.SetColor(&col(0.55, 0.55, 0.58, 1.0));
    let s = r.right - r.left;
    dc.FillRoundedRectangle(&comum::rr(rf(r.left + s * 0.08, r.top + s * 0.08, r.right - s * 0.08, r.bottom - s * 0.08), s * 0.2, s * 0.2), br);
    br.SetColor(&col(1.0, 1.0, 1.0, 1.0));
    simbolo::draw(&dc.cast().unwrap(), "bell.badge.fill", rf(r.left + s * 0.28, r.top + s * 0.26, r.right - s * 0.28, r.bottom - s * 0.28), &br.cast().unwrap());
}
unsafe fn draw_x(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, c: Ponto, arm: f32, stroke: f32, cl: Cor) {
    br.SetColor(&cl);
    let props = D2D1_STROKE_STYLE_PROPERTIES { startCap: D2D1_CAP_STYLE_ROUND, endCap: D2D1_CAP_STYLE_ROUND, ..Default::default() };
    let ss = ui::d2d().CreateStrokeStyle(&props, None).ok();
    dc.DrawLine(pt(c.x - arm, c.y - arm), pt(c.x + arm, c.y + arm), br, stroke, ss.as_ref());
    dc.DrawLine(pt(c.x - arm, c.y + arm), pt(c.x + arm, c.y - arm), br, stroke, ss.as_ref());
}
unsafe fn border(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, p: &Pal, r: RectF, rad: f32) {
    if liquid::on() {
        liquid::rim(&dc.cast().unwrap(), r, rad, ui::dark(), 0.9, 1.0, -1.0, -1.0);
        return;
    }
    br.SetColor(&p.line);
    dc.DrawRoundedRectangle(&comum::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);
}
unsafe fn grad(dc: &ID2D1DeviceContext, r: RectF, stops: &[(f32, Cor)]) -> Option<ID2D1LinearGradientBrush> {
    let rt: ID2D1RenderTarget = dc.cast().ok()?;
    let st: Vec<D2D1_GRADIENT_STOP> = stops.iter().map(|(p, c)| D2D1_GRADIENT_STOP { position: *p, color: *c }).collect();
    let gs = rt.CreateGradientStopCollection(&st, D2D1_GAMMA_2_2, D2D1_EXTEND_MODE_CLAMP).ok()?;
    rt.CreateLinearGradientBrush(&D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES { startPoint: pt(0.0, r.top), endPoint: pt(0.0, r.bottom) }, None, &gs).ok()
}
/// Leopard: o cartão claro do Aqua (degradê branco -> cinza bem claro, fio cinza, luz no alto e sombra leve)
unsafe fn leo_card(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, r: RectF, rad: f32, a: f32) {
    br.SetColor(&col(0.0, 0.0, 0.0, 0.18 * a));
    dc.FillRoundedRectangle(&comum::rr(rf(r.left, r.top + 1.5, r.right, r.bottom + 2.0), rad, rad), br);
    if let Some(lb) = grad(dc, r, &[(0.0, col(1.0, 1.0, 1.0, 0.97 * a)), (1.0, col(0.89, 0.89, 0.90, 0.97 * a))]) {
        dc.FillRoundedRectangle(&comum::rr(r, rad, rad), &lb);
    }
    br.SetColor(&col(0.0, 0.0, 0.0, 0.30 * a));
    dc.DrawRoundedRectangle(&comum::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(1.0, 1.0, 1.0, 0.9 * a));
    dc.DrawLine(pt(r.left + rad, r.top + 1.5), pt(r.right - rad, r.top + 1.5), br, 1.0, None);
}
unsafe fn draw_card(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, p: &Pal, g: &Group, nt: &Note, r: RectF, key: &str) {
    let (tt, ttime, tpill) = (tf(TF_TITLE), tf(TF_TIME), tf(TF_PILL));
    if liquid::leopard() {
        leo_card(dc, br, r, 8.0, 1.0);
        let cy0 = (r.top + r.bottom) / 2.0;
        draw_icon(dc, br, g, rf(r.left + ICON_X, cy0 - ICON / 2.0, r.left + ICON_X + ICON, cy0 + ICON / 2.0));
        let (tx0, top0) = (r.left + TEXT_X, r.top + PAD_V);
        text(dc, br, &nt.title, &tt, rf(tx0, top0, r.right - PAD_R, top0 + TITLE_H), col(0.0, 0.0, 0.0, 0.92), LEAD, false);
        if let (Some(l), _) = body(nt) {
            br.SetColor(&col(0.0, 0.0, 0.0, 0.78));
            dc.DrawTextLayout(pt(tx0, top0 + TITLE_H), &l, br, D2D1_DRAW_TEXT_OPTIONS_CLIP);
        }
        return;
    }
    border(dc, br, p, r, card_r());
    let cy = (r.top + r.bottom) / 2.0;
    draw_icon(dc, br, g, rf(r.left + ICON_X, cy - ICON / 2.0, r.left + ICON_X + ICON, cy + ICON / 2.0));
    let hover = n().hover == key;
    let right = r.right - PAD_R;
    let tx = r.left + TEXT_X;
    let row_top = r.top + PAD_V;
    let time_left;
    if hover {
        // "Opções ⌄" no lugar da hora
        let o = tr("Opções");
        let w_ = text_w(&tpill, &o) + 30.0;
        let b = rf(right - w_ + 4.0, row_top - 1.0, right + 4.0, row_top + 19.0);
        br.SetColor(&if n().hover_part == "opt" { col(p.chip.r, p.chip.g, p.chip.b, p.chip.a * 2.0) } else { p.chip });
        dc.FillRoundedRectangle(&comum::rr(b, 10.0, 10.0), br);
        text(dc, br, &o, &tpill, rf(b.left + 10.0, b.top, b.right - 18.0, b.bottom), p.text, LEAD, false);
        br.SetColor(&p.text);
        simbolo::draw(&dc.cast().unwrap(), "chevron.down", rf(b.right - 16.0, b.top + 7.0, b.right - 9.0, b.bottom - 7.0), &br.cast().unwrap());
        n().hits.push(Hit { r: b, act: Act::None, group: -2, note: 0, widget: -1, key: "opt".into() });
        time_left = b.left;
    } else {
        let t = when(nt.time);
        let w_ = text_w(&ttime, &t);
        text(dc, br, &t, &ttime, rf(right - w_ - 2.0, row_top, right, row_top + TITLE_H), p.text2, DWRITE_TEXT_ALIGNMENT_TRAILING, false);
        time_left = right - w_ - 2.0;
    }
    text(dc, br, &nt.title, &tt, rf(tx, row_top, time_left - 6.0, row_top + TITLE_H), p.text, LEAD, false);
    if let (Some(l), _) = body(nt) {
        br.SetColor(&p.text);
        dc.DrawTextLayout(pt(tx, row_top + TITLE_H), &l, br, D2D1_DRAW_TEXT_OPTIONS_CLIP);
    }
}
unsafe fn draw_circle_button(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, p: &Pal, r: RectF, gear: bool, hover: bool) {
    let rad = (r.right - r.left) / 2.0;
    let c = pt((r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0);
    if hover {
        br.SetColor(&p.chip);
        dc.FillEllipse(&ell(c, rad, rad), br);
    }
    br.SetColor(&p.line);
    dc.DrawEllipse(&ell(c, rad - 0.5, rad - 0.5), br, 1.0, None);
    if gear {
        br.SetColor(&p.text);
        simbolo::draw(&dc.cast().unwrap(), "gearshape.fill", rf(c.x - 7.0, c.y - 7.0, c.x + 7.0, c.y + 7.0), &br.cast().unwrap());
    } else {
        draw_x(dc, br, c, 3.6, 1.6, p.text);
    }
}
// ---- widgets que vêm junto: Calendário e Relógio (até o widgets.cpp registrar os dele)
fn paint_calendar(dc: &ID2D1DeviceContext, w_: f32, h: f32, dark: bool) {
    unsafe {
        let Ok(br) = dc.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None) else { return };
        let t = GetLocalTime();
        const DAYS: [&str; 7] = ["DOMINGO", "SEGUNDA", "TERÇA", "QUARTA", "QUINTA", "SEXTA", "SÁBADO"];
        text(dc, &br, &tr(DAYS[t.wDayOfWeek as usize]), &tf(TF_PILL), rf(16.0, 14.0, w_ - 12.0, 30.0), col(1.0, 0.23, 0.19, 1.0), LEAD, false);
        let big = fmt(46.0, DWRITE_FONT_WEIGHT_LIGHT, Some("SF Pro Display"), false);
        text(dc, &br, &t.wDay.to_string(), &big, rf(14.0, 28.0, w_ - 12.0, 82.0), if dark { col(1.0, 1.0, 1.0, 0.95) } else { col(0.0, 0.0, 0.0, 0.88) }, LEAD, false);
        text(dc, &br, &tr("Nenhum evento hoje"), &tf(TF_TIME), rf(16.0, h - 36.0, w_ - 12.0, h - 18.0), if dark { col(1.0, 1.0, 1.0, 0.55) } else { col(0.0, 0.0, 0.0, 0.5) }, LEAD, false);
    }
}
unsafe fn hand(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, c: Ponto, ang: f32, len: f32, width: f32, cl: Cor, tail: f32) {
    let props = D2D1_STROKE_STYLE_PROPERTIES { startCap: D2D1_CAP_STYLE_ROUND, endCap: D2D1_CAP_STYLE_ROUND, ..Default::default() };
    let ss = ui::d2d().CreateStrokeStyle(&props, None).ok();
    br.SetColor(&cl);
    let (dx, dy) = (ang.sin(), -ang.cos());
    dc.DrawLine(pt(c.x - dx * tail, c.y - dy * tail), pt(c.x + dx * len, c.y + dy * len), br, width, ss.as_ref());
}
fn paint_clock(dc: &ID2D1DeviceContext, w_: f32, h: f32, dark: bool) {
    unsafe {
        let Ok(br) = dc.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None) else { return };
        let c = pt(w_ / 2.0, h / 2.0);
        let r_ = w_.min(h) / 2.0 - 12.0;
        br.SetColor(&if dark { col(0.07, 0.07, 0.08, 1.0) } else { col(1.0, 1.0, 1.0, 1.0) });
        dc.FillEllipse(&ell(c, r_, r_), &br);
        let ink = if dark { col(1.0, 1.0, 1.0, 0.95) } else { col(0.0, 0.0, 0.0, 0.9) };
        let num = fmt(r_ * 0.22, DWRITE_FONT_WEIGHT_MEDIUM, Some("SF Pro Rounded"), false);
        for i in 1..=12 {
            let a = i as f32 * std::f32::consts::PI / 6.0;
            let (x, y) = (c.x + a.sin() * r_ * 0.78, c.y - a.cos() * r_ * 0.78);
            text(dc, &br, &i.to_string(), &num, rf(x - 12.0, y - 10.0, x + 12.0, y + 10.0), ink, CENTER, false);
        }
        let t = GetLocalTime();
        let sec = t.wSecond as f32 + t.wMilliseconds as f32 / 1000.0;
        let mn = t.wMinute as f32 + sec / 60.0;
        let hr = (t.wHour % 12) as f32 + mn / 60.0;
        let pi = std::f32::consts::PI;
        hand(dc, &br, c, hr * pi / 6.0, r_ * 0.48, 3.2, ink, 0.0);
        hand(dc, &br, c, mn * pi / 30.0, r_ * 0.72, 2.4, ink, 0.0);
        hand(dc, &br, c, t.wSecond as f32 * pi / 30.0, r_ * 0.80, 1.0, col(1.0, 0.58, 0.0, 1.0), r_ * 0.15);
        br.SetColor(&col(1.0, 0.58, 0.0, 1.0));
        dc.FillEllipse(&ell(c, 2.6, 2.6), &br);
    }
}
unsafe fn leo_grad_fill(dc: &ID2D1DeviceContext, r: RectF, rad: f32, st: &[(f32, Cor)], ellipse: bool) {
    let Some(lb) = grad(dc, r, st) else { return };
    if ellipse {
        dc.FillEllipse(&ell(pt((r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0), (r.right - r.left) / 2.0, (r.bottom - r.top) / 2.0), &lb);
    } else {
        dc.FillRoundedRectangle(&comum::rr(r, rad, rad), &lb);
    }
}
/// Leopard: o iCal do Dashboard do 10.5 (folha de calendário com a faixa vermelha)
fn paint_calendar_leo(dc: &ID2D1DeviceContext, w_: f32, h: f32, _: bool) {
    unsafe {
        let Ok(br) = dc.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None) else { return };
        let t = GetLocalTime();
        let pg = rf(14.0, 12.0, w_ - 14.0, h - 16.0);
        br.SetColor(&col(0.0, 0.0, 0.0, 0.35));
        dc.FillRoundedRectangle(&comum::rr(rf(pg.left, pg.top + 3.0, pg.right, pg.bottom + 4.0), 9.0, 9.0), &br);
        leo_grad_fill(dc, pg, 9.0, &[(0.0, col(1.0, 1.0, 1.0, 1.0)), (1.0, col(0.88, 0.88, 0.89, 1.0))], false);
        let band = (pg.bottom - pg.top) * 0.30;
        if let Ok(rg) = ui::d2d().CreateRoundedRectangleGeometry(&comum::rr(pg, 9.0, 9.0)) {
            let lp = D2D1_LAYER_PARAMETERS1 { contentBounds: rf(-1e7, -1e7, 1e7, 1e7), geometricMask: std::mem::ManuallyDrop::new(Some(rg.cast().unwrap())), maskAntialiasMode: D2D1_ANTIALIAS_MODE_PER_PRIMITIVE, maskTransform: mat::ident(), opacity: 1.0, opacityBrush: std::mem::ManuallyDrop::new(None), layerOptions: D2D1_LAYER_OPTIONS1_NONE };
            dc.PushLayer(&lp, None);
            leo_grad_fill(dc, rf(pg.left, pg.top, pg.right, pg.top + band), 0.0, &[(0.0, col(0.93, 0.36, 0.33, 1.0)), (0.5, col(0.82, 0.13, 0.12, 1.0)), (1.0, col(0.70, 0.06, 0.06, 1.0))], false);
            dc.PopLayer();
        }
        const MESES: [&str; 12] = ["JAN", "FEV", "MAR", "ABR", "MAI", "JUN", "JUL", "AGO", "SET", "OUT", "NOV", "DEZ"];
        let tm = fmt(band * 0.55, DWRITE_FONT_WEIGHT_BOLD, Some("Lucida Sans Unicode"), false);
        text(dc, &br, &tr(MESES[(t.wMonth as usize + 11) % 12]), &tm, rf(pg.left, pg.top, pg.right, pg.top + band), col(1.0, 1.0, 1.0, 1.0), CENTER, false);
        let big = fmt((pg.bottom - pg.top - band) * 0.66, DWRITE_FONT_WEIGHT_BOLD, Some("Lucida Sans Unicode"), false);
        text(dc, &br, &t.wDay.to_string(), &big, rf(pg.left, pg.top + band, pg.right, pg.bottom), col(0.1, 0.1, 0.1, 1.0), CENTER, false);
        br.SetColor(&col(0.0, 0.0, 0.0, 0.35));
        dc.DrawRoundedRectangle(&comum::rr(rf(pg.left + 0.5, pg.top + 0.5, pg.right - 0.5, pg.bottom - 0.5), 8.5, 8.5), &br, 1.0, None);
    }
}
/// Leopard: o relógio redondo do Dashboard (aro cromado, mostrador branco, ponteiro vermelho)
fn paint_clock_leo(dc: &ID2D1DeviceContext, w_: f32, h: f32, _: bool) {
    unsafe {
        let Ok(br) = dc.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None) else { return };
        let c = pt(w_ / 2.0, h / 2.0 - 2.0);
        let r_ = w_.min(h) / 2.0 - 12.0;
        br.SetColor(&col(0.0, 0.0, 0.0, 0.35));
        dc.FillEllipse(&ell(pt(c.x, c.y + 3.0), r_ + 1.0, r_ + 1.0), &br);
        leo_grad_fill(dc, rf(c.x - r_, c.y - r_, c.x + r_, c.y + r_), 0.0, &[(0.0, col(0.97, 0.97, 0.98, 1.0)), (0.5, col(0.62, 0.63, 0.66, 1.0)), (1.0, col(0.92, 0.92, 0.94, 1.0))], true);
        let r2 = r_ * 0.88;
        leo_grad_fill(dc, rf(c.x - r2, c.y - r2, c.x + r2, c.y + r2), 0.0, &[(0.0, col(0.86, 0.86, 0.87, 1.0)), (1.0, col(1.0, 1.0, 1.0, 1.0))], true);
        let ink = col(0.08, 0.08, 0.08, 1.0);
        let num = fmt(r2 * 0.24, DWRITE_FONT_WEIGHT_BOLD, Some("Lucida Sans Unicode"), false);
        for i in 1..=12 {
            let a = i as f32 * std::f32::consts::PI / 6.0;
            let (x, y) = (c.x + a.sin() * r2 * 0.76, c.y - a.cos() * r2 * 0.76);
            text(dc, &br, &i.to_string(), &num, rf(x - 14.0, y - 10.0, x + 14.0, y + 10.0), ink, CENTER, false);
        }
        let t = GetLocalTime();
        let mn = t.wMinute as f32 + t.wSecond as f32 / 60.0;
        let hr = (t.wHour % 12) as f32 + mn / 60.0;
        let pi = std::f32::consts::PI;
        let red = col(0.85, 0.10, 0.08, 1.0);
        hand(dc, &br, c, hr * pi / 6.0, r2 * 0.50, 3.6, ink, r2 * 0.08);
        hand(dc, &br, c, mn * pi / 30.0, r2 * 0.74, 2.6, ink, r2 * 0.08);
        hand(dc, &br, c, t.wSecond as f32 * pi / 30.0, r2 * 0.80, 1.2, red, r2 * 0.18);
        br.SetColor(&red);
        dc.FillEllipse(&ell(c, 2.8, 2.8), &br);
    }
}
/// os widgets da Central (central_<id>=0 tira)
const CENTRAL_W: [(&str, &str); 2] = [("calendario", "Calendário"), ("relogio", "Relógio")];
fn central_on(k: usize) -> bool {
    shell::setting(&format!("central_{}", CENTRAL_W[k].0), "1") != "0"
}
fn default_widgets() {
    let st = n();
    st.widgets.clear();
    st.widget_kind.clear();
    if central_on(0) {
        st.widgets.push(Widget {
            w: WIDGET_S,
            h: WIDGET_S,
            paint: Box::new(|dc, w_, h, d| if liquid::leopard() { paint_calendar_leo(dc, w_, h, d) } else { paint_calendar(dc, w_, h, d) }),
            click: Some(Rc::new(|| {
                // o Calendário do WacOS, não o Outlook (PR #262)
                let app = format!("{}\\{}", shell::dir(), comum::nomes::EXE_CALENDAR);
                if std::path::Path::new(&app).exists() {
                    shell::abrir(Some("open"), &app, "", &shell::dir(), SW_SHOWNORMAL);
                } else {
                    shell::abrir(Some("open"), "outlookcal:", "", "", SW_SHOWNORMAL);
                }
            })),
        });
        st.widget_kind.push(0);
    }
    if central_on(1) {
        st.widgets.push(Widget {
            w: WIDGET_S,
            h: WIDGET_S,
            paint: Box::new(|dc, w_, h, d| if liquid::leopard() { paint_clock_leo(dc, w_, h, d) } else { paint_clock(dc, w_, h, d) }),
            click: Some(Rc::new(|| shell::abrir(Some("open"), "ms-clock:", "", "", SW_SHOWNORMAL))),
        });
        st.widget_kind.push(1);
    }
}
fn cur(a: &Anim) -> RectF {
    rf(a.l.x, a.t.x, a.r.x, a.b.x)
}
fn off(r: RectF, dx: f32, dy: f32) -> RectF {
    rf(r.left + dx, r.top + dy, r.right + dx, r.bottom + dy)
}
fn view_h() -> f32 {
    let st = n();
    if let Some((_, _, h)) = st.foto {
        return h;
    }
    let mut wr = RECT::default();
    unsafe {
        let _ = GetClientRect(st.wnd, &mut wr);
    }
    wr.bottom as f32 / sc()
}
fn paint() {
    let st = n();
    if !st.open && !st.closing {
        return;
    }
    let k = sc();
    let vh = view_h();
    let (wpx, hpx) = ((COL_W * k).round() as i32, (vh * k).round() as i32);
    let els = layout();
    st.scroll_target = st.scroll_target.clamp(0.0, (st.content_h - vh).max(0.0));
    st.scroll = st.scroll.clamp(0.0, (st.content_h - vh).max(0.0));
    sync(&els);
    if let Some((x, y, _)) = st.foto {
        st.s.foto_pos = (x, y);
    }
    let Some(dc) = ui::gpu_begin(&mut st.s, wpx, hpx, k) else { return };
    st.banner_host = false;
    st.host_panel.used = 0;
    st.hits.clear();
    unsafe {
        paint_on(&dc, k, vh);
    }
    ui::gpu_end(&mut st.s);
    glass_end();
}
unsafe fn paint_on(dc: &ID2D1DeviceContext, _k: f32, vh: f32) {
    let st = n();
    let p = colors();
    let dark = ui::dark();
    let Ok(br) = dc.CreateSolidColorBrush(&p.text, None) else { return };
    let (ox, oy) = (PAD_L + st.slide * COL_W, -st.scroll);
    let leo = liquid::leopard();
    let order = st.order.clone();
    for key in &order {
        let Some(a) = st.anim.get_mut(key) else { continue };
        let e = a.el.clone();
        let r = off(cur(a), ox, oy);
        if r.bottom < -20.0 || r.top > vh + 20.0 {
            continue;
        }
        let mut alpha = a.a.x;
        if a.emerge && a.live {
            // saindo de baixo do de cima: só aparece conforme desce (o texto não se mistura)
            let span = e.r.top - a.from_top;
            let kk = if span > 1.0 { ((a.t.x - a.from_top) / span).clamp(0.0, 1.0) } else { 1.0 };
            if kk >= 0.999 && a.a.x >= 0.999 {
                a.emerge = false;
            }
            alpha *= kk * kk;
        }
        if alpha <= 0.003 {
            continue;
        }
        let fade = alpha < 0.999;
        let clip = e.kind == Kind::Under;
        let cut = e.cut_top + oy;
        if fade {
            let lp = D2D1_LAYER_PARAMETERS1 { contentBounds: rf(-1e7, -1e7, 1e7, 1e7), geometricMask: std::mem::ManuallyDrop::new(None), maskAntialiasMode: D2D1_ANTIALIAS_MODE_PER_PRIMITIVE, maskTransform: mat::ident(), opacity: alpha, opacityBrush: std::mem::ManuallyDrop::new(None), layerOptions: D2D1_LAYER_OPTIONS1_NONE };
            dc.PushLayer(&lp, None);
        }
        if clip {
            dc.PushAxisAlignedClip(&rf(-1000.0, cut, 10000.0, 10000.0), D2D1_ANTIALIAS_MODE_ALIASED);
        }
        let g = if e.group >= 0 { st.groups.get(e.group as usize).cloned() } else { None };
        let no_glass = !card_glass() && st.foto.is_none();
        let fill_solid = |r: RectF, rad: f32, c1: Cor, c2: Cor| {
            br.SetColor(&if dark { c1 } else { c2 });
            dc.FillRoundedRectangle(&comum::rr(r, rad, rad), &br);
        };
        let hit = |r: RectF, act: Act, group: i32, note: i32, widget: i32, key: String| n().hits.push(Hit { r, act, group, note, widget, key });
        match e.kind {
            Kind::Card => {
                let Some(g) = &g else { continue_layer(dc, clip, fade); continue };
                let Some(nt) = g.notes.get(e.note as usize).cloned() else { continue_layer(dc, clip, fade); continue };
                if !leo {
                    glass_rect(dc, r, card_r(), p.tint, alpha, -1e9);
                    if no_glass {
                        fill_solid(r, card_r(), col(0.17, 0.17, 0.18, 0.96), col(0.95, 0.95, 0.96, 0.96));
                    }
                }
                draw_card(dc, &br, &p, g, &nt, r, &e.key);
                hit(r, e.act, e.group, e.note, -1, e.key.clone());
            }
            Kind::Under => {
                let top_id = g.as_ref().map(|g| g.notes[0].id).unwrap_or(0);
                if leo {
                    leo_card(dc, &br, r, 8.0, (if e.layer == 1 { 0.62f32 } else { 0.48 } + 0.2).min(1.0));
                } else {
                    let mut t = p.tint;
                    t.a *= if e.layer == 1 { 0.85 } else { 0.7 };
                    glass_rect(dc, r, card_r(), t, alpha * if e.layer == 1 { 0.9 } else { 0.75 }, cut);
                    if no_glass {
                        fill_solid(r, card_r(), col(0.2, 0.2, 0.21, 0.9), col(0.9, 0.9, 0.91, 0.9));
                    }
                    border(dc, &br, &p, r, card_r());
                }
                hit(rf(r.left, cut, r.right, r.bottom), e.act, e.group, 0, -1, format!("n:{top_id}"));
            }
            Kind::Header => {
                thread_local!(static BIG: IDWriteTextFormat = fmt(17.0, DWRITE_FONT_WEIGHT_BOLD, Some("SF Pro Display"), false));
                let tfh = if e.layer == 7 { BIG.with(|b| b.clone()) } else { tf(TF_HEADER) };
                text(dc, &br, &e.text, &tfh, rf(r.left + 2.0, r.top, r.right - 150.0, r.bottom), cor_solta(), LEAD, !st.fundo_claro);
            }
            Kind::Pill => {
                let rad = (r.bottom - r.top) / 2.0;
                let hv = st.hover == e.key;
                if leo {
                    leo_card(dc, &br, r, rad, (if hv { 0.85f32 } else { 0.70 } + 0.2).min(1.0));
                    text(dc, &br, &e.text, &tf(TF_PILL), r, col(0.0, 0.0, 0.0, 0.85), CENTER, false);
                } else {
                    glass_rect(dc, r, rad, p.tint_pill, alpha, -1e9);
                    if hv {
                        br.SetColor(&p.chip);
                        dc.FillRoundedRectangle(&comum::rr(r, rad, rad), &br);
                    }
                    if no_glass {
                        fill_solid(r, rad, col(0.2, 0.2, 0.21, 0.9), col(0.92, 0.92, 0.93, 0.9));
                    }
                    border(dc, &br, &p, r, rad);
                    text(dc, &br, &e.text, &tf(TF_PILL), r, p.text, CENTER, false);
                }
                hit(r, e.act, e.group, -1, -1, e.key.clone());
            }
            Kind::Circle => {
                let rad = (r.right - r.left) / 2.0;
                if leo {
                    leo_card(dc, &br, r, rad, 0.9);
                } else {
                    glass_rect(dc, r, rad, p.tint_pill, alpha, -1e9);
                    if no_glass {
                        br.SetColor(&if dark { col(0.2, 0.2, 0.21, 0.9) } else { col(0.92, 0.92, 0.93, 0.9) });
                        dc.FillEllipse(&ell(pt((r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0), rad, rad), &br);
                    }
                }
                draw_circle_button(dc, &br, &p, r, e.act == Act::Settings, st.hover == e.key);
                hit(r, e.act, e.group, -1, -1, e.key.clone());
            }
            Kind::Widget => {
                if e.widget < 0 || e.widget as usize >= st.widgets.len() {
                    continue_layer(dc, clip, fade);
                    continue;
                }
                if !leo {
                    glass_rect(dc, r, widget_r(), p.tint, alpha, -1e9);
                    if no_glass {
                        fill_solid(r, widget_r(), col(0.17, 0.17, 0.18, 0.96), col(0.95, 0.95, 0.96, 0.96));
                    }
                    border(dc, &br, &p, r, widget_r());
                }
                let mut old = Matrix3x2::default();
                dc.GetTransform(&mut old);
                dc.PushAxisAlignedClip(&r, D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
                dc.SetTransform(&mat::mul(&mat::trans(r.left, r.top), &old));
                (st.widgets[e.widget as usize].paint)(dc, r.right - r.left, r.bottom - r.top, dark);
                dc.SetTransform(&old);
                dc.PopAxisAlignedClip();
                hit(r, e.act, -1, -1, e.widget, e.key.clone());
            }
            Kind::Label => text(dc, &br, &e.text, &tf(TF_EMPTY), r, cor_solta(), CENTER, !st.fundo_claro),
            Kind::Empty => {
                if leo {
                    leo_card(dc, &br, r, 8.0, 0.95);
                } else {
                    glass_rect(dc, r, card_r(), p.tint, alpha, -1e9);
                    if no_glass {
                        fill_solid(r, card_r(), col(0.17, 0.17, 0.18, 0.96), col(0.95, 0.95, 0.96, 0.96));
                    }
                    border(dc, &br, &p, r, card_r());
                }
                br.SetColor(&p.text2);
                let cx = (r.left + r.right) / 2.0;
                simbolo::draw(&dc.cast().unwrap(), "bell.badge.fill", rf(cx - 11.0, r.top + 14.0, cx + 11.0, r.top + 36.0), &br.cast().unwrap());
                text(dc, &br, &tr("Sem Notificações"), &tf(TF_TITLE), rf(r.left, r.top + 40.0, r.right, r.top + 58.0), p.text, CENTER, false);
                text(dc, &br, &tr("Permita que o Shell leia as notificações do Windows."), &tf(TF_TIME), rf(r.left, r.top + 58.0, r.right, r.top + 74.0), p.text2, CENTER, false);
            }
        }
        continue_layer(dc, clip, fade);
    }
    // ✕ do cartão sob o mouse, no canto de cima à esquerda (por cima de tudo)
    if st.hover.starts_with("n:") {
        if let Some(a) = st.anim.get(&st.hover) {
            if a.live && a.a.x > 0.5 {
                let r = off(cur(a), ox, oy);
                let c = pt(r.left + 4.0, r.top + 4.0);
                let rad = 9.5;
                br.SetColor(&col(0.0, 0.0, 0.0, if dark { 0.35 } else { 0.12 }));
                dc.FillEllipse(&ell(pt(c.x, c.y + 0.5), rad + 0.8, rad + 0.8), &br);
                br.SetColor(&p.close);
                dc.FillEllipse(&ell(c, rad, rad), &br);
                draw_x(dc, &br, c, 3.2, 1.5, if st.hover_part == "x" { p.text } else { p.close_glyph });
                if let Some(card) = st.hits.iter().find(|h| h.key == st.hover && h.note >= 0).cloned() {
                    st.hits.push(Hit { r: rf(c.x - rad - 2.0, c.y - rad - 2.0, c.x + rad + 2.0, c.y + rad + 2.0), act: Act::None, group: card.group, note: card.note, widget: -1, key: "x".into() });
                }
            }
        }
    }
}
unsafe fn continue_layer(dc: &ID2D1DeviceContext, clip: bool, fade: bool) {
    if clip {
        dc.PopAxisAlignedClip();
    }
    if fade {
        dc.PopLayer();
    }
}
// ================= abrir e fechar
fn place() {
    let st = n();
    let k = sc();
    unsafe {
        let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
        let _ = GetMonitorInfoW(MonitorFromPoint(POINT::default(), MONITOR_DEFAULTTOPRIMARY), &mut mi);
        let tp = mi.rcMonitor.top + menubar::top_inset();
        let (w_, h) = ((COL_W * k).round() as i32, 100.max(mi.rcWork.bottom - tp));
        let x = mi.rcMonitor.right - w_;
        let _ = SetWindowPos(st.wnd, HWND_TOPMOST, x, tp, w_, h, SWP_NOACTIVATE);
        let _ = SetWindowPos(st.back, st.wnd, x, tp, w_, h, SWP_NOACTIVATE | SWP_SHOWWINDOW);
    }
}
fn animate() {
    let st = n();
    if !st.running {
        st.last_frame = anim::now();
        st.running = true;
    }
    ui::frame_clock(st.wnd, WM_NC_FRAME, true);
    unsafe {
        SetTimer(st.wnd, T_ANIM, 33, None);
    }
}
fn hide() {
    let st = n();
    st.open = false;
    st.closing = false;
    st.hover.clear();
    st.hover_part.clear();
    unsafe {
        let _ = KillTimer(st.wnd, T_TICK);
        let _ = KillTimer(st.wnd, T_ANIM);
        let _ = ShowWindow(st.wnd, SW_HIDE);
        let _ = ShowWindow(st.back, SW_HIDE);
    }
    ui::frame_clock(st.wnd, WM_NC_FRAME, false);
    st.running = false;
    for g in &st.host_panel.pool {
        let _ = g.outer.SetIsVisible(false);
    }
}
fn close(why: &str) {
    let st = n();
    if !st.open {
        return;
    }
    if !why.is_empty() {
        log!("notificações: fechou ({why})");
    }
    st.open = false;
    menubar::sound_changed(false);
    st.closing = true;
    st.closed_at = unsafe { GetTickCount() };
    st.slide_at = anim::now();
    st.hover.clear();
    st.hover_part.clear();
    animate();
}
fn frame() {
    let st = n();
    let now = anim::now();
    let dt = ((now - st.last_frame) / 1000.0).clamp(0.0, 0.034) as f32;
    st.last_frame = now;
    let t = ((now - st.slide_at) / 1000.0) as f32;
    let slide_busy;
    // Tahoe (seção 53): abre deslizando em ~0,30 s (out-expo) e fecha em ~0,20 s; Reduzir Movimento: na hora
    let th = liquid::on();
    if st.closing {
        let d = if anim::reduce_motion() {
            0.001
        } else if th {
            0.20
        } else {
            0.30
        };
        let kk = (t / d).min(1.0);
        st.slide = anim::bezier(kk, 0.4, 0.0, 0.9, 0.6);
        if kk >= 1.0 {
            hide();
            return;
        }
        slide_busy = true;
    } else if anim::reduce_motion() {
        st.slide = 0.0;
        slide_busy = false;
    } else if th {
        let kk = (t / 0.30).min(1.0);
        st.slide = 1.0 - anim::bezier(kk, 0.16, 1.0, 0.3, 1.0);
        slide_busy = kk < 1.0;
    } else {
        st.slide = 1.0 - anim::spring(t, 0.48, 1.0);
        slide_busy = t < 0.9;
        if !slide_busy {
            st.slide = 0.0;
        }
    }
    let mut busy = advance(dt);
    paint();
    // o layout novo (sync, no paint) só entra agora: só para se, depois do desenho, tudo já estiver no alvo
    if !busy && !slide_busy {
        busy = !settled();
    }
    if !busy && !slide_busy {
        ui::frame_clock(st.wnd, WM_NC_FRAME, false);
        unsafe {
            let _ = KillTimer(st.wnd, T_ANIM);
        }
        st.running = false;
    }
}
// apps de desktop que mandam notificação com um AUMID só para os avisos (Thunderbird/Firefox:
// "ThunderbirdToast-D78BF5DD33499EC2", registrado em HKCU\Software\Classes\AppUserModelId com um ativador COM). Esse
// AUMID não existe no shell:AppsFolder: abrir "shell:AppsFolder\<AUMID do aviso>" dava a janela de erro do Windows
// (PR #262). Aqui o aviso é ligado ao app de verdade da pasta Aplicativos: pelo fim do AUMID ou pelo nome. "" = nenhum.
fn no_apps_folder(parsing: &str) -> bool {
    if parsing.is_empty() {
        return false;
    }
    let t = wz(&format!("shell:AppsFolder\\{parsing}"));
    unsafe { SHCreateItemFromParsingName::<_, _, IShellItem>(pc(&t), None).is_ok() }
}
fn nome_registrado(aumid: &str) -> String {
    use comum::windows::Win32::System::Registry::*;
    let k = wz(&format!("Software\\Classes\\AppUserModelId\\{aumid}"));
    for raiz in [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE] {
        let mut b = [0u16; 512];
        let mut cb = (b.len() * 2) as u32;
        let ok = unsafe { RegGetValueW(raiz, pc(&k), w!("DisplayName"), RRF_RT_REG_SZ, None, Some(b.as_mut_ptr() as *mut c_void), Some(&mut cb)).is_ok() };
        if ok && b[0] != 0 {
            return from_w(&b);
        }
    }
    String::new()
}
fn app_do_aviso(nt: &Note) -> String {
    if no_apps_folder(&nt.aumid) {
        return nt.aumid.clone();
    }
    let nomes = [nt.app.to_lowercase(), nome_registrado(&nt.aumid).to_lowercase()];
    let aumid_l = nt.aumid.to_lowercase();
    let contem_palavra = |todo: &str, parte: &str| -> bool {
        // "mozilla thunderbird" contém "thunderbird"
        if parte.chars().count() < 4 {
            return false;
        }
        let mut ini = 0;
        while let Some(p) = todo[ini..].find(parte) {
            let p = ini + p;
            let antes = todo[..p].chars().last().map_or(true, |c| !c.is_alphanumeric());
            let depois = todo[p + parte.len()..].chars().next().map_or(true, |c| !c.is_alphanumeric());
            if antes && depois {
                return true;
            }
            ini = p + parte.len().max(1);
            if ini >= todo.len() {
                break;
            }
        }
        false
    };
    let (mut melhor, mut nota) = (String::new(), 0);
    unsafe {
        let Ok(pasta) = SHCreateItemFromParsingName::<_, _, IShellItem>(w!("shell:AppsFolder"), None) else { return melhor };
        let Ok(en) = pasta.BindToHandler::<_, IEnumShellItems>(None, &BHID_EnumItems) else { return melhor };
        let mut it = [None];
        while nota < 3 && en.Next(&mut it, None).is_ok() {
            let Some(item) = it[0].take() else { break };
            let (Ok(pp), Ok(pn)) = (item.GetDisplayName(SIGDN_PARENTRELATIVEPARSING), item.GetDisplayName(SIGDN_NORMALDISPLAY)) else { continue };
            let (parsing, nome) = (from_w(pp.as_wide()), from_w(pn.as_wide()).to_lowercase());
            CoTaskMemFree(Some(pp.0 as *const c_void));
            CoTaskMemFree(Some(pn.0 as *const c_void));
            if parsing.is_empty() {
                continue;
            }
            let pl = parsing.to_lowercase();
            let mut v = 0;
            if pl.len() >= 4 && aumid_l.len() > pl.len() && aumid_l.ends_with(&pl) {
                let sep = aumid_l.as_bytes()[aumid_l.len() - pl.len() - 1];
                if b"-_.!".contains(&sep) {
                    v = 3; // "ThunderbirdToast-D78BF5DD33499EC2" termina com o AUMID do app
                }
            }
            for l in &nomes {
                if l.is_empty() {
                    continue;
                }
                if *l == nome {
                    v = v.max(2);
                } else if contem_palavra(l, &nome) || contem_palavra(&nome, l) {
                    v = v.max(1);
                }
            }
            if v > nota {
                nota = v;
                melhor = parsing;
            }
        }
    }
    melhor
}
fn exe_do_item(parsing: &str) -> String {
    // o .exe por trás do item (minúsculas), "" se não souber
    let t = wz(&format!("shell:AppsFolder\\{parsing}"));
    unsafe {
        if let Ok(si) = SHCreateItemFromParsingName::<_, _, IShellItem2>(pc(&t), None) {
            if let Ok(p) = si.GetString(&comum::windows::Win32::Storage::EnhancedStorage::PKEY_Link_TargetParsingPath) {
                let r = from_w(p.as_wide()).to_lowercase();
                CoTaskMemFree(Some(p.0 as *const c_void));
                return r;
            }
        }
    }
    String::new()
}
fn open_app(nt: &Note) {
    if nt.aumid == "WacOS.Atualizacao" {
        shell::open_settings("atualizacao");
        return;
    }
    let id = format!("aumid:{}", nt.aumid);
    if let Some(a) = apps::list().iter_mut().find(|a| !a.wins.is_empty() && (a.id.eq_ignore_ascii_case(&id) || a.name.eq_ignore_ascii_case(&nt.app))) {
        apps::activate(a);
        return;
    }
    if let Some(a) = apps::list().iter_mut().find(|a| a.name.eq_ignore_ascii_case(&nt.app)) {
        apps::launch(a, "");
        return;
    }
    let alvo = app_do_aviso(nt);
    if alvo.is_empty() {
        log!("notificação: app de {} ({}) não achado na pasta Aplicativos; nada aberto", nt.app, nt.aumid);
        return;
    }
    if alvo != nt.aumid {
        log!("notificação: {} -> app {alvo}", nt.aumid);
        let exe = exe_do_item(&alvo);
        let id = format!("aumid:{alvo}");
        if let Some(a) = apps::list().iter_mut().find(|a| !a.wins.is_empty() && (a.id.eq_ignore_ascii_case(&id) || (!exe.is_empty() && a.exe.eq_ignore_ascii_case(&exe)))) {
            apps::activate(a); // o app já está aberto: traz as janelas
            return;
        }
    }
    let t = format!("shell:AppsFolder\\{alvo}");
    if !apps::activate_packaged(&t, "") {
        shell::abrir(Some("open"), &t, "", "", SW_SHOWNORMAL);
    }
}
fn clear_group(gi: i32) {
    let st = n();
    let Some(g) = st.groups.get(gi as usize).cloned() else { return };
    st.expanded.remove(&g.aumid);
    remove_ids(&g.notes.iter().map(|x| x.id).collect::<Vec<_>>());
}
fn menu_pt(r: RectF) -> POINT {
    let mut wr = RECT::default();
    unsafe {
        let _ = GetWindowRect(n().wnd, &mut wr);
    }
    let k = sc();
    POINT { x: wr.left + (r.left * k) as i32, y: wr.top + ((r.bottom + 4.0) * k) as i32 }
}
fn options(gi: i32, ni: i32, r: RectF) {
    let st = n();
    let Some(g) = st.groups.get(gi as usize).cloned() else { return };
    let Some(nt) = g.notes.get(ni as usize).cloned() else { return };
    let stack = g.notes.len() > 1 && !st.expanded.contains(&g.aumid);
    let mut items = vec![MItem::new(tr("Abrir ") + &nt.app, 1), MItem::new(tr(if stack { "Limpar Tudo" } else { "Limpar" }), 2)];
    if !stack && g.notes.len() > 1 {
        items.push(MItem::new(tr("Limpar Tudo de ") + &nt.app, 3));
    }
    items.push(MItem::sep());
    items.push(MItem::new(tr("Ajustes de Notificações…"), 4));
    st.menu = true;
    let id = ctxmenu::show_items(st.wnd, menu_pt(r), &items);
    st.menu = false;
    match id {
        1 => {
            remove_ids(&[nt.id]);
            close("");
            open_app(&nt);
            return;
        }
        2 => {
            if stack {
                clear_group(gi);
            } else {
                remove_ids(&[nt.id]);
            }
        }
        3 => clear_group(gi),
        4 => {
            close("");
            shell::open_settings("notificacoes");
            return;
        }
        _ => {}
    }
    unsafe {
        let _ = SetForegroundWindow(st.wnd);
    }
    animate();
}
/// "Editar Widgets…" da Central (e o botão direito num widget dela)
fn widgets_menu(r: RectF, widget: i32) {
    let st = n();
    let mut items: Vec<MItem> = (0..CENTRAL_W.len()).map(|kk| MItem::new(tr(CENTRAL_W[kk].1), 10 + kk as i32).checked(central_on(kk))).collect();
    items.push(MItem::sep());
    if widget >= 0 && (widget as usize) < st.widget_kind.len() {
        items.push(MItem::new(tr("Remover Widget"), 1));
    }
    items.push(MItem::new(tr("Widgets da Mesa…"), 2));
    st.menu = true;
    let id = ctxmenu::show_items(st.wnd, menu_pt(r), &items);
    st.menu = false;
    let mut desliga: Option<usize> = None;
    if id == 1 {
        desliga = Some(st.widget_kind[widget as usize]);
    } else if (10..10 + CENTRAL_W.len() as i32).contains(&id) {
        let kk = (id - 10) as usize;
        if central_on(kk) {
            desliga = Some(kk);
        } else {
            shell::set_setting(&format!("central_{}", CENTRAL_W[kk].0), "1");
        }
    } else if id == 2 {
        close("");
        let mut c = POINT::default();
        unsafe {
            let _ = GetCursorPos(&mut c);
        }
        widgets::edit_menu(c);
        return;
    }
    if let Some(kk) = desliga {
        shell::set_setting(&format!("central_{}", CENTRAL_W[kk].0), "0");
    }
    if id > 0 && !st.custom_widgets {
        default_widgets();
    }
    unsafe {
        let _ = SetForegroundWindow(st.wnd);
    }
    animate();
}
fn hit_at(p: Ponto) -> Option<Hit> {
    n().hits.iter().rev().find(|h| p.x >= h.r.left && p.x < h.r.right && p.y >= h.r.top && p.y < h.r.bottom).cloned()
}
fn click(p: Ponto) {
    let st = n();
    st.click_at = unsafe { GetTickCount() };
    let Some(hit) = hit_at(p) else {
        close("clique no vazio");
        return;
    };
    if hit.key == "x" {
        // ✕ do cartão: numa pilha fechada limpa o grupo todo
        if let Some(g) = st.groups.get(hit.group as usize).cloned() {
            if g.notes.len() > 1 && !st.expanded.contains(&g.aumid) {
                clear_group(hit.group);
            } else if let Some(nt) = g.notes.get(hit.note as usize) {
                remove_ids(&[nt.id]);
            }
        }
        st.hover.clear();
        animate();
        return;
    }
    if hit.key == "opt" {
        if let Some(card) = st.hits.iter().find(|c| c.key == st.hover && c.note >= 0).cloned() {
            options(card.group, card.note, hit.r);
        }
        return;
    }
    match hit.act {
        Act::Stack => {
            if let Some(g) = st.groups.get(hit.group as usize) {
                st.expanded.insert(g.aumid.clone());
                st.expanded_at = unsafe { GetTickCount() };
                log!("notificações: abriu a pilha de {} ({} notificações)", g.app, g.notes.len());
            }
        }
        Act::Card => {
            // segundo clique de um clique duplo na pilha: só abre o grupo
            if unsafe { GetTickCount() }.wrapping_sub(st.expanded_at) >= 500 {
                if let Some(nt) = st.groups.get(hit.group as usize).and_then(|g| g.notes.get(hit.note as usize)).cloned() {
                    remove_ids(&[nt.id]);
                    close("clique no cartão: abre o app");
                    open_app(&nt);
                    return;
                }
            }
        }
        Act::ShowLess => {
            if let Some(g) = st.groups.get(hit.group as usize) {
                let a = g.aumid.clone();
                st.expanded.remove(&a);
            }
        }
        Act::ClearGroup => clear_group(hit.group),
        Act::ClearAll => {
            let ids: Vec<u32> = st.groups.iter().flat_map(|g| g.notes.iter().map(|x| x.id)).collect();
            st.expanded.clear();
            st.show_all = false;
            remove_ids(&ids);
        }
        Act::More => st.show_all = true,
        Act::Edit => {
            if let Some(f) = st.edit_widgets.clone() {
                close("");
                f();
                return;
            }
            widgets_menu(hit.r, -1);
            return;
        }
        Act::Settings => {
            close("");
            shell::open_settings("notificacoes");
            return;
        }
        Act::Permission => {
            close("");
            shell::abrir(Some("open"), "ms-settings:privacy-notifications", "", "", SW_SHOWNORMAL);
            return;
        }
        Act::Widget => {
            if let Some(f) = st.widgets.get(hit.widget as usize).and_then(|w_| w_.click.clone()) {
                close("");
                f();
                return;
            }
        }
        Act::None => {}
    }
    animate();
}
fn hover(p: Ponto) {
    let st = n();
    let (mut hv, mut part) = (String::new(), String::new());
    if let Some(h) = hit_at(p) {
        if h.key == "x" || h.key == "opt" {
            hv = st.hover.clone();
            part = h.key;
        } else {
            hv = h.key;
        }
    }
    if hv != st.hover || part != st.hover_part {
        st.hover = hv;
        st.hover_part = part;
        paint();
    }
}
fn lp_pt(h: HWND, l: LPARAM) -> Ponto {
    let k = ui::scale(h);
    pt(get_x_lparam(l) as f32 / k, get_y_lparam(l) as f32 / k)
}
unsafe extern "system" fn proc_(h: HWND, m: u32, w: WPARAM, l: LPARAM) -> LRESULT {
    let st = n();
    match m {
        WM_PAINT => {
            let mut ps = PAINTSTRUCT::default();
            BeginPaint(h, &mut ps);
            let _ = EndPaint(h, &ps);
            paint();
            return LRESULT(0);
        }
        WM_NC_FRAME => {
            st.frame_msg_at = anim::now();
            frame();
            ui::frame_ack(h, WM_NC_FRAME);
            return LRESULT(0);
        }
        WM_NC_NEW => {
            banner_show(l.0 as u32);
            return LRESULT(0);
        }
        WM_NC_DATA => {
            dock::badges_changed();
            rebuild();
            if st.open {
                animate();
            }
            return LRESULT(0);
        }
        WM_TIMER => {
            if w.0 == T_TICK && st.open {
                paint();
            }
            if w.0 == T_ANIM {
                // relógio de quadros parado (19/11/2026): o temporizador de reserva desenha
                if anim::now() - st.frame_msg_at > 50.0 {
                    frame();
                }
                return LRESULT(0);
            }
            if w.0 == T_FOCO {
                let _ = KillTimer(h, T_FOCO);
                if !st.open || st.menu {
                    return LRESULT(0);
                }
                let f = GetForegroundWindow();
                let mut pid = 0;
                if !f.0.is_null() {
                    GetWindowThreadProcessId(f, Some(&mut pid));
                }
                if !f.0.is_null() && pid != GetCurrentProcessId() && GetTickCount().wrapping_sub(st.click_at) >= 800 {
                    log!("notificações: fechou (outro programa na frente: {})", shell::class_name(f));
                    close("");
                } else {
                    let _ = SetForegroundWindow(st.wnd);
                }
            }
            return LRESULT(0);
        }
        WM_LBUTTONDOWN => {
            if st.open {
                click(lp_pt(h, l));
            }
            return LRESULT(0);
        }
        WM_RBUTTONUP => {
            if !st.open || st.custom_widgets {
                return LRESULT(0);
            }
            if let Some(hh) = hit_at(lp_pt(h, l)) {
                if hh.act == Act::Widget {
                    widgets_menu(hh.r, hh.widget);
                }
            }
            return LRESULT(0);
        }
        WM_MOUSEMOVE => {
            if !st.open {
                return LRESULT(0);
            }
            let mut t = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };
            let _ = TrackMouseEvent(&mut t);
            hover(lp_pt(h, l));
            return LRESULT(0);
        }
        WM_MOUSELEAVE => {
            if !st.hover.is_empty() && !st.menu {
                st.hover.clear();
                st.hover_part.clear();
                paint();
            }
            return LRESULT(0);
        }
        WM_MOUSEWHEEL => {
            st.scroll_target -= ((w.0 >> 16) as u16 as i16) as f32 / 120.0 * 60.0;
            animate();
            return LRESULT(0);
        }
        WM_KEYDOWN => {
            if w.0 == VK_ESCAPE.0 as usize {
                close("Esc");
            }
            return LRESULT(0);
        }
        WM_ACTIVATE => {
            if w.0 & 0xFFFF == WA_INACTIVE as usize && !st.menu {
                // a ativação foi para outra janela do próprio Shell (o vidro, o banner, a barra): não fecha
                let to = HWND(l.0 as *mut c_void);
                let mut pid = 0;
                if !to.0.is_null() {
                    GetWindowThreadProcessId(to, Some(&mut pid));
                }
                let cls = shell::class_name(to);
                if !to.0.is_null() && pid == GetCurrentProcessId() && (to == st.back || GetAncestor(to, GA_ROOTOWNER) == st.wnd || cls.contains("Notifica") || cls.contains("Banner")) {
                    let _ = SetForegroundWindow(st.wnd);
                    return LRESULT(0);
                }
                if to.0.is_null() || GetTickCount().wrapping_sub(st.click_at) < 800 {
                    SetTimer(h, T_FOCO, 150, None);
                    return LRESULT(0);
                }
                log!("notificações: fechou (perdeu o foco para {cls})");
                close("");
            }
            return LRESULT(0);
        }
        WM_DPICHANGED => {
            if st.open {
                place();
                paint();
            }
            return LRESULT(0);
        }
        _ => {}
    }
    DefWindowProcW(h, m, w, l)
}
// ================= banner: a notificação que chega com o painel fechado (até 3, um embaixo do outro)
fn banner_ms() -> u64 {
    (shell::setting("notif_duracao", "5").parse::<f64>().unwrap_or(5.0).clamp(2.0, 30.0) * 1000.0) as u64
}
fn banners_on() -> bool {
    shell::setting("banners_mac", "1") != "0"
}
/// a Ilha Dinâmica mostra as notificações: o toast do Windows também sai, mesmo com os banners do Mac desligados
/// (issue #567: o do Windows aparecia embaixo à direita e depois o da Ilha)
fn avisos_na_ilha() -> bool {
    ilha::on() && shell::setting("ilha_notificacoes", "1") != "0"
}
fn ban_target_y(i: usize) -> f32 {
    let mut y = top();
    for b in n().bans.iter().take(i) {
        y += card_h(&b.n) + BAN_GAP;
    }
    y
}
fn ban_slide(b: &Ban, now: f64) -> f32 {
    if b.out_at >= 0.0 {
        let kk = ((now - b.out_at) / BAN_OUT_MS).min(1.0) as f32;
        return anim::bezier(kk, 0.4, 0.0, 0.9, 0.6);
    }
    if anim::reduce_motion() {
        return 0.0;
    }
    // Tahoe (seção 65): mola de 0,24 s sem passar do ponto
    let t = ((now - b.at) / 1000.0) as f32;
    1.0 - if liquid::on() { anim::spring(t, 0.24, 1.0) } else { anim::spring(t, 0.42, 0.82) }
}
fn ban_rect(i: usize) -> RectF {
    let b = &n().bans[i];
    let ox = PAD_L + ban_slide(b, anim::now()) * COL_W;
    let y = if b.y < 0.0 { ban_target_y(i) } else { b.y };
    rf(ox, y, ox + CARD_W, y + card_h(&b.n))
}
fn banner_h() -> f32 {
    let mut h = top();
    for (i, b) in n().bans.iter().enumerate() {
        h = h.max(b.y.max(ban_target_y(i)) + card_h(&b.n));
    }
    h + 14.0
}
fn ban_any_in() -> bool {
    n().bans.iter().any(|b| b.out_at < 0.0)
}
fn banner_place() {
    let st = n();
    let k = ui::scale(st.bwnd);
    unsafe {
        let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
        let _ = GetMonitorInfoW(MonitorFromPoint(POINT::default(), MONITOR_DEFAULTTOPRIMARY), &mut mi);
        let tp = mi.rcMonitor.top + menubar::top_inset();
        let (w_, h) = ((COL_W * k).round() as i32, (banner_h() * k).round() as i32);
        let x = mi.rcMonitor.right - w_;
        st.bh_px = h;
        let _ = SetWindowPos(st.bwnd, HWND_TOPMOST, x, tp, w_, h, SWP_NOACTIVATE);
        let _ = SetWindowPos(st.bback, st.bwnd, x, tp, w_, h, SWP_NOACTIVATE | SWP_SHOWWINDOW);
    }
}
fn banner_paint() {
    let st = n();
    if st.bans.is_empty() {
        return;
    }
    let k = if st.foto.is_some() { ui::foto_scale() } else { ui::scale(st.bwnd) };
    let (wpx, hpx) = ((COL_W * k).round() as i32, (banner_h() * k).round() as i32);
    if let Some((x, y, _)) = st.foto {
        st.bs.foto_pos = (x, y);
    }
    let Some(dc) = ui::gpu_begin(&mut st.bs, wpx, hpx, k) else { return };
    let p = colors();
    let dark = ui::dark();
    st.banner_host = true;
    st.host_banner.used = 0;
    let saved = std::mem::take(&mut st.hover);
    unsafe {
        if let Ok(br) = dc.CreateSolidColorBrush(&p.text, None) {
            for i in (0..st.bans.len()).rev() {
                let b = st.bans[i].clone();
                let r = ban_rect(i);
                if r.left >= COL_W {
                    continue;
                }
                if !liquid::leopard() {
                    glass_rect(&dc, r, card_r(), p.tint, 1.0, -1e9);
                    if !card_glass() && st.foto.is_none() {
                        br.SetColor(&if dark { col(0.17, 0.17, 0.18, 0.97) } else { col(0.95, 0.95, 0.96, 0.97) });
                        dc.FillRoundedRectangle(&comum::rr(r, card_r(), card_r()), &br);
                    }
                }
                let g = Group { aumid: b.n.aumid.clone(), app: b.n.app.clone(), notes: Vec::new() };
                draw_card(&dc, &br, &p, &g, &b.n, r, &format!("banner:{}", b.n.id));
                if st.bhover == i as i32 && b.out_at < 0.0 {
                    let c = pt(r.left + 4.0, r.top + 4.0);
                    br.SetColor(&col(0.0, 0.0, 0.0, if dark { 0.35 } else { 0.12 }));
                    dc.FillEllipse(&ell(pt(c.x, c.y + 0.5), 10.3, 10.3), &br);
                    br.SetColor(&p.close);
                    dc.FillEllipse(&ell(c, 9.5, 9.5), &br);
                    draw_x(&dc, &br, c, 3.2, 1.5, if st.bhover_x { p.text } else { p.close_glyph });
                }
            }
        }
    }
    st.hover = saved;
    ui::gpu_end(&mut st.bs);
    glass_end();
    st.banner_host = false;
}
fn banner_hide() {
    let st = n();
    let was = !st.bans.is_empty();
    st.bans.clear();
    st.bhover = -1;
    st.bhover_x = false;
    st.blast = 0.0;
    if was {
        menubar::sound_changed(false);
    }
    unsafe {
        let _ = KillTimer(st.bwnd, T_BANNER);
        let _ = ShowWindow(st.bwnd, SW_HIDE);
        let _ = ShowWindow(st.bback, SW_HIDE);
    }
    ui::frame_clock(st.bwnd, WM_NC_BFRAME, false);
    for g in &st.host_banner.pool {
        let _ = g.outer.SetIsVisible(false);
    }
}
fn banner_out(i: usize) {
    let st = n();
    if i >= st.bans.len() || st.bans[i].out_at >= 0.0 {
        return;
    }
    st.bans[i].out_at = anim::now();
    if !ban_any_in() {
        menubar::sound_changed(false);
    }
    ui::frame_clock(st.bwnd, WM_NC_BFRAME, true);
}
fn banner_show(id: u32) {
    let st = n();
    if st.open || st.closing || !banners_on() || st.bwnd.0.is_null() {
        return;
    }
    let nt = DADOS.lock().unwrap().data.iter().find(|x| x.id == id).cloned();
    if let Some(nt) = nt {
        banner_show_note(nt);
    }
}
fn shell_data(nome: &str) -> String {
    format!("{}\\Shell\\{nome}", menubar::known_folder(&comum::windows::Win32::UI::Shell::FOLDERID_RoamingAppData))
}
fn read_tsv(path: &str) -> Vec<Vec<String>> {
    let Ok(b) = std::fs::read(path) else { return Vec::new() };
    let b = b.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(&b);
    String::from_utf8_lossy(b)
        .lines()
        .map(|l| {
            l.split('\t')
                .map(|x| {
                    let mut o = String::new();
                    let mut it = x.chars();
                    while let Some(c) = it.next() {
                        if c == '\\' {
                            match it.next() {
                                Some('n') | Some('t') => o.push(' '),
                                Some(c2) => o.push(c2),
                                None => o.push('\\'),
                            }
                        } else {
                            o.push(c);
                        }
                    }
                    o
                })
                .collect()
        })
        .collect()
}
/// avisos dos apps do Shell (Lembretes, Calendário, alarmes do Relógio), conferidos a cada 30 s
fn checar_avisos() {
    if shell::foto() {
        return;
    }
    let st = n();
    let done = shell_data("avisos-feitos.txt");
    if !st.avisados_lidos {
        st.avisados_lidos = true;
        for v in read_tsv(&done) {
            if let Some(k) = v.first() {
                st.avisados.insert(k.clone());
            }
        }
    }
    let now = (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) / 60) as i64;
    let mut due: Vec<(String, Note)> = Vec::new();
    static SEQ: AtomicU32 = AtomicU32::new(0);
    let dir = shell::dir();
    let mut add = |key: String, app: &str, exe: &str, title: String, body: String| {
        if st.avisados.contains(&key) || due.iter().any(|d| d.0 == key) {
            return;
        }
        let id = AVISO_ID + (SEQ.fetch_add(1, Ordering::Relaxed) + 1 & 0xFF_FFFF);
        due.push((key, Note { id, aumid: format!("{dir}\\{exe}"), app: tr(app), title, body, time: now_ft() }));
    };
    for v in read_tsv(&shell_data("lembretes.txt")) {
        // R id lista feito data título notas sinal
        if v.len() >= 8 && v[0] == "R" && v[3] != "1" {
            let m: i64 = v[4].parse().unwrap_or(0);
            if m != 0 && m <= now && m > now - 24 * 60 {
                add(format!("R{}@{}", v[1], v[4]), "Lembretes", nomes::EXE_REMINDERS, v[5].clone(), v[6].clone());
            }
        }
    }
    for v in read_tsv(&shell_data("calendario.txt")) {
        // E id início fim diaInteiro título cor notas
        if v.len() >= 6 && v[0] == "E" && v[4] != "1" {
            let s: i64 = v[2].parse().unwrap_or(0);
            if s != 0 && s <= now && s > now - 10 {
                let lt = local_tm(s * 60);
                add(format!("E{}@{}", v[1], v[2]), "Calendário", nomes::EXE_CALENDAR, v[5].clone(), format!("{} · {}:{:02}", tr("Agora"), lt.wHour, lt.wMinute));
            }
        }
    }
    // alarmes do Relógio: A id hora minuto ligado nome dias (bits: 0 = domingo; 0 = uma vez só)
    let lt = unsafe { GetLocalTime() };
    let mut once: Vec<String> = Vec::new();
    for v in read_tsv(&shell_data("relogio.txt")) {
        if v.len() >= 7 && v[0] == "A" && v[4] == "1" {
            let (hh, mm, days): (i32, i32, i32) = (v[2].parse().unwrap_or(0), v[3].parse().unwrap_or(0), v[6].parse().unwrap_or(0));
            if days != 0 && days & (1 << lt.wDayOfWeek) == 0 {
                continue;
            }
            let diff = (lt.wHour as i32 * 60 + lt.wMinute as i32) - (hh * 60 + mm);
            if !(0..=2).contains(&diff) {
                continue;
            }
            let key = format!("A{}@{:04}{:02}{:02}{:02}{:02}", v[1], lt.wYear, lt.wMonth, lt.wDay, hh, mm);
            if !st.avisados.contains(&key) {
                add(key, "Relógio", nomes::EXE_CLOCK, if v[5].is_empty() { tr("Alarme") } else { v[5].clone() }, format!("{hh}:{mm:02}"));
                if days == 0 {
                    once.push(v[1].clone());
                }
            }
        }
    }
    if !once.is_empty() {
        // alarmes de uma vez só que tocaram: desligam no arquivo (atômico: são os alarmes do usuário)
        let path = shell_data("relogio.txt");
        if let Ok(b) = std::fs::read(&path) {
            let txt = String::from_utf8_lossy(b.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(&b)).into_owned();
            let mut out = String::new();
            for line in txt.lines() {
                let mut l = line.to_string();
                if once.iter().any(|id| l.starts_with(&format!("A\t{id}\t"))) {
                    let mut f: Vec<String> = l.split('\t').map(String::from).collect();
                    if f.len() > 4 && f[4] == "1" {
                        f[4] = "0".into();
                    }
                    l = f.join("\t");
                }
                out += &l;
                out.push('\n');
            }
            let tmp = format!("{path}.tmp");
            if std::fs::write(&tmp, [&[0xEF, 0xBB, 0xBF][..], out.as_bytes()].concat()).is_ok() {
                let _ = std::fs::rename(&tmp, &path);
            }
        }
    }
    if due.is_empty() {
        return;
    }
    {
        use std::io::Write;
        if let Ok(mut f) = std::fs::OpenOptions::new().append(true).create(true).open(&done) {
            for (k, _) in &due {
                let _ = writeln!(f, "{k}");
            }
        }
    }
    for (k, nt) in due {
        st.avisados.insert(k);
        log!("aviso: {} — {}", nt.app, nt.title);
        banner_show_note(nt);
        shell::sound("notificacao");
    }
}
fn local_tm(secs: i64) -> SYSTEMTIME {
    // segundos Unix → FILETIME (100 ns desde 1601) → hora local
    ft_to_st((secs + 11_644_473_600) * 10_000_000)
}
fn banner_show_note(nt: Note) {
    let st = n();
    // jogo ou vídeo em tela cheia: sem banner (a notificação fica na Central)
    if crate::principal::nao_incomodar(Default::default()) {
        log!("notificação: banner calado (app em tela cheia)");
        return;
    }
    // Ilha Dinâmica ligada: a notificação aparece nela, no lugar do banner do canto
    if !st.open && !st.closing && ilha::notificacao(&nt.app, &nt.title, &nt.body) {
        log!("notificação na ilha: {}", nt.app);
        return;
    }
    let nosso = !nt.aumid.is_empty() && nt.aumid.starts_with(&format!("{}\\", shell::dir()));
    if st.open || st.closing || (!banners_on() && !nosso) || (st.bwnd.0.is_null() && st.foto.is_none()) {
        return;
    }
    let first = st.bans.is_empty();
    st.bans.insert(0, Ban { n: nt, at: anim::now(), out_at: -1.0, until: unsafe { GetTickCount64() } + banner_ms(), y: top() });
    if st.bhover >= 0 {
        st.bhover += 1;
    }
    let mut live = st.bans.iter().filter(|b| b.out_at < 0.0).count();
    for i in (0..st.bans.len()).rev() {
        if live <= MAX_BANS {
            break;
        }
        if st.bans[i].out_at < 0.0 {
            st.bans[i].out_at = anim::now();
            live -= 1;
        }
    }
    if first {
        st.bhover = -1;
        st.bhover_x = false;
        st.blast = 0.0;
    }
    if st.foto.is_some() {
        return;
    }
    banner_place();
    banner_paint();
    unsafe {
        let _ = ShowWindow(st.bwnd, SW_SHOWNOACTIVATE);
        SetTimer(st.bwnd, T_BANNER, 250, None);
    }
    menubar::sound_changed(false);
    ui::frame_clock(st.bwnd, WM_NC_BFRAME, true);
}
fn banner_frame() {
    let st = n();
    let now = anim::now();
    let dt = if st.blast > 0.0 { (now - st.blast) as f32 } else { 16.0 };
    st.blast = now;
    let mut i = 0;
    while i < st.bans.len() {
        if st.bans[i].out_at >= 0.0 && now - st.bans[i].out_at >= BAN_OUT_MS {
            st.bans.remove(i);
            if st.bhover == i as i32 {
                st.bhover = -1;
                st.bhover_x = false;
            } else if st.bhover > i as i32 {
                st.bhover -= 1;
            }
        } else {
            i += 1;
        }
    }
    if st.bans.is_empty() {
        banner_hide();
        return;
    }
    let mut moving = false;
    for i in 0..st.bans.len() {
        let tg = ban_target_y(i);
        let b = &mut st.bans[i];
        if b.y < 0.0 {
            b.y = tg;
        } else if b.y != tg {
            b.y += (tg - b.y) * (1.0 - (-dt / 70.0).exp());
            if (tg - b.y).abs() < 0.25 {
                b.y = tg;
            } else {
                moving = true;
            }
        }
        if b.out_at >= 0.0 || now - b.at < if liquid::on() { 450.0 } else { 900.0 } {
            moving = true;
        }
    }
    let k = ui::scale(st.bwnd);
    if (banner_h() * k).round() as i32 != st.bh_px {
        banner_place();
    }
    if !moving {
        st.blast = 0.0;
        ui::frame_clock(st.bwnd, WM_NC_BFRAME, false);
    }
    banner_paint();
}
unsafe extern "system" fn banner_proc(h: HWND, m: u32, w: WPARAM, l: LPARAM) -> LRESULT {
    let st = n();
    match m {
        WM_PAINT => {
            let mut ps = PAINTSTRUCT::default();
            BeginPaint(h, &mut ps);
            let _ = EndPaint(h, &ps);
            banner_paint();
            return LRESULT(0);
        }
        WM_MOUSEACTIVATE => return LRESULT(MA_NOACTIVATE as isize),
        WM_NC_BFRAME => {
            banner_frame();
            ui::frame_ack(h, WM_NC_BFRAME);
            return LRESULT(0);
        }
        WM_TIMER => {
            if w.0 == T_BANNER {
                let now = GetTickCount64();
                for i in 0..st.bans.len() {
                    if st.bans[i].out_at >= 0.0 {
                        continue;
                    }
                    if i as i32 == st.bhover {
                        st.bans[i].until = st.bans[i].until.max(now + 1500); // com o ponteiro em cima não some
                    } else if now >= st.bans[i].until {
                        banner_out(i);
                    }
                }
                if st.bans.is_empty() {
                    let _ = KillTimer(h, T_BANNER);
                }
            }
            if w.0 == 7 {
                checar_avisos();
            }
            return LRESULT(0);
        }
        WM_MOUSEMOVE | WM_LBUTTONDOWN => {
            if st.bans.is_empty() {
                return LRESULT(0);
            }
            let p = lp_pt(h, l);
            let (mut hv, mut on_x) = (-1i32, false);
            for i in 0..st.bans.len() {
                if st.bans[i].out_at >= 0.0 {
                    continue;
                }
                let r = ban_rect(i);
                let (dx, dy) = (p.x - (r.left + 4.0), p.y - (r.top + 4.0));
                let x = i as i32 == st.bhover && dx * dx + dy * dy <= 144.0;
                if x || (p.x >= r.left && p.x < r.right && p.y >= r.top && p.y < r.bottom) {
                    hv = i as i32;
                    on_x = x;
                    break;
                }
            }
            if m == WM_LBUTTONDOWN {
                if hv < 0 {
                    return LRESULT(0);
                }
                if on_x {
                    banner_out(hv as usize);
                    return LRESULT(0);
                }
                let nt = st.bans[hv as usize].n.clone();
                banner_out(hv as usize);
                if nt.id >= AVISO_ID {
                    shell::abrir(Some("open"), &nt.aumid, "", "", SW_SHOWNORMAL);
                    return LRESULT(0);
                }
                remove_ids(&[nt.id]);
                open_app(&nt);
                return LRESULT(0);
            }
            let mut t = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };
            let _ = TrackMouseEvent(&mut t);
            if hv != st.bhover || on_x != st.bhover_x {
                st.bhover = hv;
                st.bhover_x = on_x;
                banner_paint();
            }
            return LRESULT(0);
        }
        WM_MOUSELEAVE => {
            if st.bhover >= 0 {
                st.bhover = -1;
                st.bhover_x = false;
                banner_paint();
            }
            return LRESULT(0);
        }
        _ => {}
    }
    DefWindowProcW(h, m, w, l)
}
// ================= o toast do Windows: a janela "New notification" do ShellExperienceHost vai para fora da tela
fn is_toast(h: HWND) -> bool {
    let st = n();
    if h == st.toast {
        return true;
    }
    if shell::class_name(h) != "Windows.UI.Core.CoreWindow" {
        return false;
    }
    // o título da janela do toast no idioma do Windows ("New notification", "Nova notificação", "Neue Benachrichtigung"...):
    // antes só inglês e português, e nos outros o toast do Windows aparecia junto com o do WacOS (issue #567)
    let t = shell::window_text(h).to_lowercase();
    const TITULOS: [&str; 14] = ["notification", "notifica", "benachrichtigung", "уведомлен", "通知", "알림", "thông báo", "bildirim", "powiadomien", "notificación", "melding", "ilmoitus", "oznámení", "értesítés"];
    if !TITULOS.iter().any(|x| t.contains(x)) {
        return false;
    }
    let mut pid = 0;
    unsafe { GetWindowThreadProcessId(h, Some(&mut pid)) };
    if !apps::exe_of_pid(pid).to_lowercase().contains("shellexperiencehost.exe") {
        return false;
    }
    st.toast = h;
    true
}
unsafe extern "system" fn on_toast(_: HWINEVENTHOOK, _: u32, h: HWND, obj: i32, _: i32, _: u32, _: u32) {
    if obj != OBJID_WINDOW.0 || h.0.is_null() || !is_toast(h) || !(banners_on() || avisos_na_ilha()) {
        return;
    }
    let mut r = RECT::default();
    let _ = GetWindowRect(h, &mut r);
    if r.left <= -30000 {
        return;
    }
    let st = n();
    st.toast_rect = r;
    st.toast_moved = true;
    let _ = SetWindowPos(h, None, -32000, -32000, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
    RAPIDO_ATE.store(GetTickCount().wrapping_add(3000), Ordering::Relaxed); // a leitura vem já, e depressa por 3 s
    wake();
}
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)
}
fn formats() {
    let body = fmt(13.0, DWRITE_FONT_WEIGHT_NORMAL, None, true);
    unsafe {
        let _ = body.SetLineSpacing(DWRITE_LINE_SPACING_METHOD_UNIFORM, LINE_H, 12.5);
    }
    n().tf = Some([
        fmt(13.0, DWRITE_FONT_WEIGHT_SEMI_BOLD, None, false),
        body,
        fmt(12.0, DWRITE_FONT_WEIGHT_NORMAL, None, false),
        fmt(12.0, DWRITE_FONT_WEIGHT_MEDIUM, None, false),
        fmt(21.0, DWRITE_FONT_WEIGHT_BOLD, Some("SF Pro Display"), false),
        fmt(15.0, DWRITE_FONT_WEIGHT_SEMI_BOLD, Some("SF Pro Display"), false),
    ]);
}
pub fn create(hi: HINSTANCE) -> bool {
    let st = n();
    unsafe {
        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hi, lpszClassName: w!("ShellNotificacoes"), hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), ..Default::default() });
        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(back_proc), hInstance: hi, lpszClassName: w!("ShellNotificacoesFundo"), ..Default::default() });
        let ex = WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP;
        st.wnd = CreateWindowExW(ex, w!("ShellNotificacoes"), w!("Central de Notificações"), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
        st.back = CreateWindowExW(ex | WS_EX_NOACTIVATE, w!("ShellNotificacoesFundo"), 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;
        }
        WND.store(st.wnd.0 as isize, Ordering::Relaxed);
        st.real = backdrop::liquid() && backdrop::real() && backdrop::attach(st.back); // issue #51
        if !st.real {
            st.has_glass = glass_init(st.back, false);
        }
        log!("notificações: vidro {}", if st.real { "real (Liquid Glass, como a Central)" } else { "fosco" });
        let corner = 1u32;
        let none = 0xFFFF_FFFEu32;
        let _ = DwmSetWindowAttribute(st.back, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const c_void, 4);
        let _ = DwmSetWindowAttribute(st.back, DWMWINDOWATTRIBUTE(34), &none as *const _ as *const c_void, 4);
        apps::ours().push(st.wnd);
        apps::ours().push(st.back);
        st.s.hwnd = st.wnd;
        formats();
        if !st.custom_widgets {
            default_widgets();
        }
        // o banner do Mac
        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(banner_proc), hInstance: hi, lpszClassName: w!("ShellBanner"), hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), ..Default::default() });
        st.bwnd = CreateWindowExW(ex | WS_EX_NOACTIVATE, w!("ShellBanner"), w!("Notificação"), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
        st.bback = CreateWindowExW(ex | WS_EX_NOACTIVATE, w!("ShellNotificacoesFundo"), w!(""), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
        if !st.bwnd.0.is_null() && !st.bback.0.is_null() {
            st.has_banner_glass = glass_init(st.bback, true);
            let _ = DwmSetWindowAttribute(st.bback, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const c_void, 4);
            let _ = DwmSetWindowAttribute(st.bback, DWMWINDOWATTRIBUTE(34), &none as *const _ as *const c_void, 4);
            apps::ours().push(st.bwnd);
            apps::ours().push(st.bback);
            st.bs.hwnd = st.bwnd;
            SetTimer(st.bwnd, 7, 30000, None); // avisos do Lembretes e do Calendário
        }
        // o toast do Windows sai da tela assim que aparece (o banner do Mac fica no lugar)
        let _ = SetWinEventHook(EVENT_OBJECT_SHOW, EVENT_OBJECT_SHOW, None, Some(on_toast), 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
        jogo::gancho_posicao(on_toast, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
    }
    std::thread::spawn(|| {
        let _ = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
        worker();
    });
    true
}
pub fn is_open() -> bool {
    n().open
}
/// ícone próprio escolhido/restaurado no Dock: solta os ícones guardados
pub fn icons_changed() {
    n().icons.clear();
}
pub fn banner_visible() -> bool {
    ban_any_in()
}
pub fn toggle() {
    let st = n();
    if st.open {
        close("clique no relógio / canto ativo");
        return;
    }
    if unsafe { GetTickCount() }.wrapping_sub(st.closed_at) < 300 {
        return;
    }
    banner_hide();
    st.open = true;
    menubar::sound_changed(false);
    st.closing = false;
    st.show_all = false;
    st.expanded.clear();
    st.scroll = 0.0;
    st.scroll_target = 0.0;
    st.anim.clear();
    st.order.clear();
    st.snap = true;
    st.slide_at = anim::now();
    st.slide = 1.0;
    rebuild();
    wake();
    place();
    mede_fundo();
    paint();
    unsafe {
        let _ = ShowWindow(st.wnd, SW_SHOWNOACTIVATE);
        let _ = SetForegroundWindow(st.wnd);
        let _ = SetFocus(st.wnd);
        SetTimer(st.wnd, T_TICK, 1000, None);
    }
    animate();
}
/// o fundo do topo da coluna (ainda escondida): claro → título escuro (issue #8)
fn mede_fundo() {
    use comum::windows::Win32::Graphics::Gdi::*;
    let st = n();
    st.fundo_claro = false;
    unsafe {
        let mut wr = RECT::default();
        if GetWindowRect(st.wnd, &mut wr).is_err() {
            return;
        }
        let dpi = comum::windows::Win32::UI::HiDpi::GetDpiForWindow(st.wnd).max(96);
        let (w_, h) = (wr.right - wr.left, (wr.bottom - wr.top).min((160 * dpi / 96) as i32));
        if w_ <= 0 || h <= 0 {
            return;
        }
        const BW: i32 = 24;
        const BH: i32 = 12;
        let s = GetDC(None);
        let m = CreateCompatibleDC(s);
        let bi = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: BW, biHeight: -BH, biPlanes: 1, biBitCount: 32, biCompression: BI_RGB.0, ..Default::default() }, ..Default::default() };
        let mut bits = std::ptr::null_mut();
        if let Ok(b) = CreateDIBSection(s, &bi, DIB_RGB_COLORS, &mut bits, None, 0) {
            if !bits.is_null() {
                let o = SelectObject(m, b);
                SetStretchBltMode(m, HALFTONE);
                let _ = StretchBlt(m, 0, 0, BW, BH, s, wr.left, wr.top, w_, h, SRCCOPY);
                let _ = GdiFlush();
                let px = std::slice::from_raw_parts(bits as *const u8, (BW * BH * 4) as usize);
                let soma: f64 = px.chunks_exact(4).map(|p| (0.0722 * p[0] as f64 + 0.7152 * p[1] as f64 + 0.2126 * p[2] as f64) / 255.0).sum();
                st.fundo_claro = soma / (BW * BH) as f64 > 0.62;
                SelectObject(m, o);
            }
            let _ = DeleteObject(b);
        }
        let _ = DeleteDC(m);
        ReleaseDC(None, s);
    }
}
pub fn set_widgets(list: Vec<Widget>, on_edit: Option<Rc<dyn Fn()>>) {
    let st = n();
    st.custom_widgets = true;
    st.widgets = list;
    st.edit_widgets = on_edit;
    if st.open {
        paint();
    }
}
pub fn stop() {
    let st = n();
    unsafe {
        if st.toast_moved && !st.toast.0.is_null() && IsWindow(st.toast).as_bool() {
            let _ = SetWindowPos(st.toast, None, st.toast_rect.left, st.toast_rect.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
        }
    }
    st.toast_moved = false;
}
/// as notificações da Central agora (para o badge do Dock)
pub fn recentes() -> Vec<Brief> {
    DADOS.lock().unwrap().data.iter().map(|x| Brief { aumid: x.aumid.clone(), app: x.app.clone(), time: x.time }).collect()
}
#[derive(Clone, Default)]
pub struct Brief {
    pub aumid: String,
    pub app: String,
    pub time: i64,
}
/// exemplos da foto (as notificações de verdade da pessoa não entram na foto)
fn exemplos() -> Vec<Note> {
    let agora = now_ft();
    let min = 600_000_000i64;
    let nota = |id: u32, aumid: &str, app: &str, title: &str, body: &str, mins: i64| Note { id, aumid: aumid.into(), app: app.into(), title: title.into(), body: body.into(), time: agora - mins * min };
    vec![
        nota(1, "exemplo.mensagens", &tr("Mensagens"), "Ana", &tr("Chego em 10 minutos, pode ir pedindo o café."), 2),
        nota(2, "exemplo.mensagens", &tr("Mensagens"), "Ana", &tr("Você viu o e-mail da reunião?"), 15),
        nota(3, "exemplo.mensagens", &tr("Mensagens"), "Bruno", &tr("Fotos da viagem chegaram!"), 40),
        nota(4, "exemplo.calendario", &tr("Calendário"), &tr("Reunião de equipe"), &tr("Hoje às 15:00 · Sala 2"), 25),
        nota(5, "exemplo.mail", "Mail", &tr("Fatura de novembro"), &tr("Sua fatura está disponível. Toque para ver os detalhes."), 90),
    ]
}
/// modo foto: a Central aberta (`banner`: em vez dela, os banners da foto) com notificações de exemplo
pub fn foto(tela_w: f32, tela_h: f32, banner: bool) {
    let st = n();
    formats();
    default_widgets();
    let k = ui::foto_scale();
    {
        let mut d = DADOS.lock().unwrap();
        d.data = exemplos();
        d.access = 1;
    }
    let y0 = menubar::bar_pt();
    st.foto = Some(((tela_w - COL_W) * k, y0 * k, tela_h - y0));
    if banner {
        for nt in exemplos().into_iter().take(2).rev() {
            banner_show_note(nt);
        }
        for i in 0..st.bans.len() {
            let y = ban_target_y(i);
            st.bans[i].at = -1e9; // já assentados
            st.bans[i].y = y;
        }
        banner_paint();
        return;
    }
    rebuild();
    st.open = true;
    st.snap = true;
    st.slide = 0.0;
    paint();
}