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
11.3 KB
Raw Blame
//! notarapida.cpp: o canto ativo da Nota Rápida, como no Mac (canto inferior direito): encostar o ponteiro faz um quadrado
//! translúcido subir um pouco do canto; com o ponteiro em cima, sobe mais; clicar abre a Nota Rápida (Notas --nota-rapida).
//! A imagem é desenhada uma vez e o deslize é animado pelo compositor (ui::gpu_slide). canto_nota_rapida=0 desliga.
#![allow(dead_code)]

use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Gdi::{GetMonitorInfoW, MonitorFromPoint, HMONITOR, MONITORINFO, MONITOR_DEFAULTTONEAREST};
use comum::windows::Win32::System::SystemInformation::GetTickCount;
use comum::windows::Win32::UI::HiDpi::*;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

use crate::{anim, cantos, log, mesa, shell, ui};

const TILE: f32 = 84.0;
const SHADOW: f32 = 18.0;
const SHOWN: f32 = 30.0;
const HOVER: f32 = 44.0;
const T_POLL: usize = 1;
const T_HIDE: usize = 2;
struct S {
    w: HWND,
    s: ui::GpuSurface,
    on: bool,
    hover: bool,
    drawn: bool,
    drawn_dark: bool,
    anim_at: f64,
    from: f32,
    to: f32,
    vis: f32,
    corner_since: u32,
    away_since: u32,
    mon: RECT,
    sc: f32,
    ritmo: u32,
}
static SS: Global<Option<S>> = Global::new(None);
fn s() -> &'static mut S {
    SS.get().get_or_insert_with(|| S { w: HWND::default(), s: ui::GpuSurface::default(), on: false, hover: false, drawn: false, drawn_dark: false, anim_at: 0.0, from: 0.0, to: 0.0, vis: 0.0, corner_since: 0, away_since: 0, mon: RECT::default(), sc: 1.0, ritmo: 30 })
}
/// o canto pode ter outra ação (Cantos Ativos)
fn enabled() -> bool {
    shell::setting("canto_nota_rapida", "1") != "0" && cantos::nota_rapida()
}
fn fullscreen_in_front(m: &RECT) -> bool {
    unsafe {
        let fg = GetForegroundWindow();
        if fg.0.is_null() || mesa::is_desk_class(&shell::class_name(fg)) {
            return false;
        }
        let mut r = RECT::default();
        let _ = GetWindowRect(fg, &mut r);
        r.left <= m.left && r.top <= m.top && r.right >= m.right && r.bottom >= m.bottom && GetWindowLongW(fg, GWL_STYLE) as u32 & WS_CAPTION.0 == 0
    }
}
/// o quadrado (sombra, vidro translúcido, aro claro e o contorno escuro fino), em pt
unsafe fn draw_tile(rt: &ID2D1RenderTargetRef, dark: bool, r: RectF) {
    let rt = rt.0;
    let Ok(br) = rt.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None) else { return };
    for k in (1..=10).rev() {
        let k = k as f32;
        br.SetColor(&col(0.0, 0.0, 0.0, 0.018));
        rt.FillRoundedRectangle(&comum::rr(rf(r.left - k, r.top - k + 2.0, r.right + k, r.bottom + k + 2.0), 12.0 + k, 12.0 + k), &br);
    }
    br.SetColor(&if dark { col(0.30, 0.30, 0.32, 0.55) } else { col(1.0, 1.0, 1.0, 0.55) });
    rt.FillRoundedRectangle(&comum::rr(r, 12.0, 12.0), &br);
    br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.28) } else { col(1.0, 1.0, 1.0, 0.85) });
    rt.DrawRoundedRectangle(&comum::rr(rf(r.left + 0.5, r.top + 0.5, r.right - 0.5, r.bottom - 0.5), 11.5, 11.5), &br, 1.0, None);
    br.SetColor(&col(0.0, 0.0, 0.0, if dark { 0.35 } else { 0.10 }));
    rt.DrawRoundedRectangle(&comum::rr(rf(r.left - 0.5, r.top - 0.5, r.right + 0.5, r.bottom + 0.5), 12.5, 12.5), &br, 1.0, None);
}
struct ID2D1RenderTargetRef<'a>(&'a comum::windows::Win32::Graphics::Direct2D::ID2D1RenderTarget);
fn win_px() -> i32 {
    ((TILE + SHADOW * 2.0) * s().sc).round() as i32
}
/// desenha o quadrado uma vez (muda só com o tema ou a escala)
fn draw() {
    let st = s();
    let dark = ui::dark();
    let px = win_px();
    let Some(dc) = ui::gpu_begin(&mut st.s, px, px, st.sc) else { return };
    unsafe {
        let rt = dc.cast().unwrap();
        draw_tile(&ID2D1RenderTargetRef(&rt), dark, rf(SHADOW, SHADOW, SHADOW + TILE, SHADOW + TILE));
    }
    ui::gpu_end(&mut st.s);
    st.drawn = true;
    st.drawn_dark = dark;
}
/// deslocamento do conteúdo (px) para `vis` pt à mostra; escondido, a sombra também fica fora
fn offset_for(vis: f32) -> f32 {
    (HOVER - vis + if vis <= 0.0 { SHADOW } else { 0.0 }) * s().sc
}
/// onde o quadrado está agora (a animação corre no compositor; aqui a mesma conta, para emendar outra)
fn current_vis() -> f32 {
    let st = s();
    if st.anim_at == 0.0 {
        return st.vis;
    }
    let dur = if st.to > st.from { 240.0 } else { 170.0 };
    let k = ((anim::now() - st.anim_at) / dur).min(1.0) as f32;
    st.from + (st.to - st.from) * (1.0 - (1.0 - k).powi(3))
}
fn animate_to(vis: f32) {
    let st = s();
    if vis == st.to && st.anim_at != 0.0 {
        return;
    }
    st.from = current_vis();
    st.to = vis;
    st.anim_at = anim::now();
    let dur = if st.to > st.from { 240.0 } else { 170.0 };
    ui::gpu_slide(&st.s, offset_for(st.from), offset_for(st.from), offset_for(st.to), offset_for(st.to), dur);
    unsafe {
        if vis == 0.0 {
            SetTimer(st.w, T_HIDE, dur as u32 + 30, None);
        } else {
            let _ = KillTimer(st.w, T_HIDE);
        }
    }
}
fn show(mon: RECT, hm: HMONITOR) {
    let st = s();
    st.mon = mon;
    let (mut dx, mut dy) = (96u32, 96u32);
    let sc = unsafe {
        if GetDpiForMonitor(hm, MDT_EFFECTIVE_DPI, &mut dx, &mut dy).is_ok() {
            dx as f32 / 96.0
        } else {
            GetDpiForSystem() as f32 / 96.0
        }
    };
    let bx = ((SHADOW + HOVER) * sc).round() as i32;
    unsafe {
        let _ = SetWindowPos(st.w, HWND_TOPMOST, mon.right - bx, mon.bottom - bx, bx, bx, SWP_NOACTIVATE);
    }
    if !st.drawn || sc != st.sc || st.drawn_dark != ui::dark() {
        st.sc = sc;
        draw();
    }
    (st.on, st.hover, st.away_since, st.vis, st.from, st.to, st.anim_at) = (true, false, 0, 0.0, 0.0, 0.0, 0.0);
    ui::gpu_offset(&st.s, offset_for(0.0), offset_for(0.0));
    unsafe {
        let _ = ShowWindow(st.w, SW_SHOWNOACTIVATE);
    }
    animate_to(SHOWN);
}
fn hide() {
    let st = s();
    if !st.on {
        return;
    }
    st.on = false;
    st.hover = false;
    animate_to(0.0);
}
fn open_quick_note() {
    let exe = format!("{}\\{}", shell::dir(), nomes::EXE_NOTES);
    if !std::path::Path::new(&exe).exists() {
        log!("nota rápida: {} não encontrado", nomes::EXE_NOTES);
        return;
    }
    unsafe {
        let _ = AllowSetForegroundWindow(ASFW_ANY);
    }
    shell::abrir(Some("open"), &exe, "--nota-rapida", &shell::dir(), SW_SHOWNORMAL);
    log!("nota rápida: aberta pelo canto");
}
/// 30 ms com o quadrado à mostra ou o ponteiro a menos de 240 px do canto; longe, 150 ms (23/11/2026)
fn ritmo(ms: u32) {
    let st = s();
    if ms != st.ritmo && !st.w.0.is_null() {
        st.ritmo = ms;
        unsafe { SetTimer(st.w, T_POLL, ms, None) };
    }
}
fn poll() {
    let st = s();
    unsafe {
        let mut p = POINT::default();
        if GetCursorPos(&mut p).is_err() {
            return;
        }
        let hm = MonitorFromPoint(p, MONITOR_DEFAULTTONEAREST);
        let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
        let _ = GetMonitorInfoW(hm, &mut mi);
        let m = mi.rcMonitor;
        ritmo(if st.on || (p.x >= m.right - 240 && p.y >= m.bottom - 240) {
            30
        } else if crate::leve::economia() {
            300 // na bateria (issue #490)
        } else {
            150
        });
        let corner = p.x >= m.right - 3 && p.y >= m.bottom - 3;
        let button = GetAsyncKeyState(VK_LBUTTON.0 as i32) < 0 || GetAsyncKeyState(VK_RBUTTON.0 as i32) < 0;
        let now = GetTickCount();
        if !st.on {
            if corner && !button && enabled() && !fullscreen_in_front(&m) {
                if st.corner_since == 0 {
                    st.corner_since = now;
                }
                if now.wrapping_sub(st.corner_since) >= 60 {
                    st.corner_since = 0;
                    show(m, hm); // um instante no canto (não dispara de passagem)
                }
            } else {
                st.corner_since = 0;
            }
            return;
        }
        if m != st.mon {
            hide();
            return;
        }
        let (tile, pad) = ((HOVER * st.sc).round() as i32, (28.0 * st.sc).round() as i32);
        let over = p.x >= st.mon.right - tile && p.y >= st.mon.bottom - tile;
        let near = p.x >= st.mon.right - tile - pad && p.y >= st.mon.bottom - tile - pad;
        if over != st.hover {
            st.hover = over;
            animate_to(if over { HOVER } else { SHOWN });
        }
        if near {
            st.away_since = 0;
        } else if st.away_since == 0 {
            st.away_since = now;
        } else if now.wrapping_sub(st.away_since) > 300 {
            hide();
        }
    }
}
unsafe extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    let st = s();
    match m {
        WM_TIMER => {
            if w_.0 == T_POLL {
                poll();
            } else if w_.0 == T_HIDE {
                let _ = KillTimer(h, T_HIDE);
                if !st.on {
                    let _ = ShowWindow(h, SW_HIDE);
                    st.anim_at = 0.0;
                    st.vis = 0.0;
                }
            }
            LRESULT(0)
        }
        WM_NCHITTEST => {
            // só o pedaço do quadrado à mostra recebe o clique
            let (x, y) = (get_x_lparam(l), get_y_lparam(l));
            let vis = (current_vis() * st.sc).round() as i32;
            LRESULT(if st.on && x >= st.mon.right - vis && y >= st.mon.bottom - vis { HTCLIENT as isize } else { HTTRANSPARENT as isize })
        }
        WM_MOUSEACTIVATE => LRESULT(MA_NOACTIVATE as isize),
        WM_SETCURSOR => {
            SetCursor(LoadCursorW(None, IDC_ARROW).unwrap_or_default());
            LRESULT(1)
        }
        WM_LBUTTONUP => {
            if st.on {
                open_quick_note();
                st.on = false;
                st.hover = false;
                animate_to(0.0);
            }
            LRESULT(0)
        }
        _ => DefWindowProcW(h, m, w_, l),
    }
}
pub fn create(hi: HINSTANCE) -> bool {
    if shell::foto() {
        return true;
    }
    let st = s();
    unsafe {
        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hi, lpszClassName: w!("ShellNotaRapida"), ..Default::default() });
        st.w = CreateWindowExW(WS_EX_NOREDIRECTIONBITMAP | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, w!("ShellNotaRapida"), w!(""), WS_POPUP, 0, 0, 1, 1, None, None, hi, None).unwrap_or_default();
        if st.w.0.is_null() {
            log!("nota rápida: sem janela");
            return true;
        }
        st.s.hwnd = st.w;
        SetTimer(st.w, T_POLL, 30, None); // só lê a posição do ponteiro: barato
    }
    log!("nota rápida: canto inferior direito {}", if enabled() { "ligado" } else { "desligado" });
    true
}
/// modo foto: o quadrado subindo do canto inferior direito (com o ponteiro em cima)
pub fn foto(tela_w: f32, tela_h: f32) {
    let st = s();
    let k = ui::foto_scale();
    let bx = SHADOW + HOVER;
    st.s.foto_pos = ((tela_w - bx) * k, (tela_h - bx) * k);
    let Some(dc) = ui::gpu_begin(&mut st.s, (bx * k) as i32, (bx * k) as i32, k) else { return };
    unsafe {
        let rt = dc.cast().unwrap();
        // o conteúdo deslocado como no deslize: HOVER pt à mostra
        draw_tile(&ID2D1RenderTargetRef(&rt), ui::dark(), rf(SHADOW, SHADOW, SHADOW + TILE, SHADOW + TILE));
    }
    ui::gpu_end(&mut st.s);
}