A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! menus.cpp: os menus do Windows no visual do Mac, em todos os programas, sem injetar nada:
//! 1. O Windows avisa (WinEvent, fora do processo) quando um menu nativo (#32768) abre.
//! 2. Lemos os itens pelo HMENU (MN_GETHMENU), tiramos a janela nativa da tela e mostramos a nossa.
//! 3. O mouse é nosso (gancho de mouse só enquanto há menu aberto, numa thread só dele); ao escolher, selecionamos o
//! mesmo item no menu nativo (MN_SELECTITEM) e mandamos Enter: o programa recebe o comando como sempre recebeu.
//! 4. O teclado continua indo para o menu nativo; acompanhamos o destaque pelo evento de foco.
//! Programas que desenham o próprio menu (Chrome, Electron, WinUI) não usam #32768 e ficam como estão.
//! E o vidro atrás dos menus de contexto dos nossos apps ("WacOSMenuVidro"), com "Menus de vidro" ligado.
#![allow(dead_code)]
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::Mutex;
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::System::SystemInformation::GetTickCount;
use comum::windows::Win32::System::Threading::*;
use comum::windows::Win32::UI::Accessibility::*;
use comum::windows::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI};
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;
use crate::{anim, backdrop, log, shell, ui};
const MN_SELECT: u32 = 0x01E5; // MN_SELECTITEM (não documentada): destaca o item no menu nativo
const MN_GETHMENU: u32 = 0x01E1;
const MN_BTNDOWN: u32 = 0x01ED; // MN_BUTTONDOWN/UP (não documentadas): clique no item pela posição
const MN_BTNUP: u32 = 0x01EF;
const MN_OPENHIER: u32 = 0x01E3; // MN_OPENHIERARCHY (não documentada): abre o submenu do item destacado
const KEY_MARK: usize = 0x5348_4C4C; // o mesmo de principal.rs: teclas nossas não passam pelo gancho da tecla Windows
const T_SUBMENU: usize = 1;
const T_SUBCHECK: usize = 2;
const T_SCROLL: usize = 3;
const T_CHOOSECHECK: usize = 4;
const T_SHOWNOW: usize = 5;
const WM_MENU_MOVE: u32 = WM_APP + 1;
const WM_MENU_CLICK: u32 = WM_APP + 2;
const WM_MENU_WHEEL: u32 = WM_APP + 3;
const WM_MENU_SHOWNOW: u32 = WM_APP + 4;
const WM_HOOK_ON: u32 = WM_USER + 1;
const WM_HOOK_OFF: u32 = WM_USER + 2;
// medidas do menu do macOS: linhas de 22, 5 de folga, texto a 21 da borda (espaço do ✓), destaque com 5 de margem
const ROW: f32 = 22.0;
const SEP: f32 = 11.0;
const PADY: f32 = 5.0;
const TEXTL: f32 = 21.0;
const TEXTR: f32 = 14.0;
const INSET: f32 = 5.0;
const MENU_R_TAHOE: f32 = 12.0;
const ARROW: f32 = 18.0; // faixa com a setinha em cima/embaixo de um menu que rola
#[derive(Clone, Default)]
struct Item {
pos: u32,
label: String,
shortcut: String,
sep: bool,
disabled: bool,
checked: bool,
radio: bool,
sub: bool,
icon: u16,
r: RectF,
}
struct Level {
id: u32,
native: HWND,
menu: HMENU,
wnd: HWND,
back: HWND,
s: ui::GpuSurface,
glass: bool,
clipped: bool,
items: Vec<Item>,
hover: i32,
w: f32,
h: f32,
text_l: f32,
view: f32,
scroll: f32,
scale: f32,
}
#[derive(Default)]
struct MenuVidro {
back: HWND,
margin: i32,
radius: i32,
w: i32,
h: i32,
dark: bool,
born: u32,
fade_t0: u32,
fade_ms: i32,
}
#[derive(Default)]
struct S {
levels: Vec<Box<Level>>,
next_id: u32,
menu_hook: HWINEVENTHOOK,
focus_hook: HWINEVENTHOOK,
create_hook: HWINEVENTHOOK,
host: HWND,
self_pid: u32,
tf: Option<(IDWriteTextFormat, IDWriteTextFormat)>,
tf_icon: Option<IDWriteTextFormat>,
sub_wanted: i32,
sub_from: u32,
sub_idx: i32,
sub_try: i32,
choose_native: HWND,
choose_pos: u32,
choose_idx: i32,
choose_try: i32,
last_mouse: u32,
mv: HashMap<isize, MenuVidro>,
mv_timer: usize,
mv_reg: bool,
}
static SS: Global<Option<S>> = Global::new(None);
fn s() -> &'static mut S {
SS.get().get_or_insert_with(|| S { sub_wanted: -1, sub_idx: -1, choose_idx: -1, ..Default::default() })
}
/// o gancho de mouse roda numa thread só dele e não faz nada pesado: os retângulos dos nossos menus ficam aqui
static RECTS: Mutex<Vec<RECT>> = Mutex::new(Vec::new());
static MOVE_PENDING: AtomicBool = AtomicBool::new(false);
static HOOK_TID: AtomicU32 = AtomicU32::new(0);
static HOST: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);
/// Ajustes > "Menus de vidro (Liquid Glass)": o vidro claro do Dock em vez do vidro "regular" bem tingido
fn menu_glass_on() -> bool {
backdrop::liquid() && shell::setting("menu_vidro", "0") == "1"
}
fn clear_menu_tint(dark: bool) -> Cor {
if dark {
col(0.10, 0.10, 0.11, 0.24)
} else {
col(0.98, 0.98, 0.99, 0.30)
}
}
fn golden_menus() -> bool {
backdrop::liquid() && backdrop::current().golden
}
fn menu_r() -> f32 {
if golden_menus() {
11.0
} else {
MENU_R_TAHOE
}
}
/// macOS 27: o menu da Apple tem símbolo só nestes
fn golden_icon(label: &str) -> bool {
["Ajustes", "Settings", "System Settings", "Preferências", "Preferences", "Sobre Este", "About This", "App Store", "Microsoft Store"].iter().any(|k| label.starts_with(k))
}
/// Tahoe: um símbolo (Segoe Fluent Icons) pelo nome do item (o mesmo de menu/context_menu.cpp AutoIcon)
pub fn auto_icon(label: &str) -> u16 {
let s_ = label.to_lowercase();
let has = |k: &str| s_.contains(k);
let st = |k: &str| s_.starts_with(k);
let tab: &[(&dyn Fn() -> bool, u16)] = &[
(&|| has("nova aba") || has("new tab"), 0xE8A7),
(&|| has("nova janela") || has("new window"), 0xE78B),
(&|| has("todas as janelas") || has("all windows") || has("mission control"), 0xE7C4),
(&|| has("iniciar sessão") || has("login") || has("startup"), 0xE7E8),
(&|| has("nova pasta") || has("new folder"), 0xE8F4),
(&|| st("abrir com") || st("open with"), 0xE7AC),
(&|| has("mostrar no finder") || has("mostrar na pasta") || has("abrir local") || has("show in"), 0xE838),
(&|| st("abrir") || st("open"), 0xE8E5),
(&|| has("lixo") || has("excluir") || has("apagar") || has("delete") || has("trash"), 0xE74D),
(&|| has("remover do dock") || has("desafixar"), 0xE77A),
(&|| has("manter no dock") || has("fixar"), 0xE718),
(&|| st("sobre este") || st("about this"), 0xE7F8),
(&|| has("app store") || has("microsoft store"), 0xE719),
(&|| has("informaç") || has("propriedades") || has("properties") || st("sobre"), 0xE946),
(&|| has("renomear") || has("rename"), 0xE8AC),
(&|| has("comprimir") || has("compactar") || has("compress") || has("zip"), 0xF012),
(&|| has("duplicar") || has("duplicate"), 0xF413),
(&|| has("atalho") || has("alias") || has("shortcut"), 0xE71B),
(&|| has("visualização rápida") || has("quick look"), 0xE890),
(&|| st("recortar") || st("cut"), 0xE8C6),
(&|| st("copiar") || st("copy"), 0xE8C8),
(&|| st("colar") || st("paste"), 0xE77F),
(&|| has("compartilhar") || has("share"), 0xE72D),
(&|| has("etiqueta") || has("tag"), 0xE8EC),
(&|| has("ações rápidas") || has("mais ações") || has("quick actions"), 0xE945),
(&|| has("ordenar") || has("sort"), 0xE8CB),
(&|| has("terminal") || has("prompt") || has("powershell"), 0xE756),
(&|| has("administrador") || has("admin"), 0xEA18),
(&|| has("papel de parede") || has("wallpaper") || has("fundo da área"), 0xE91B),
(&|| has("configurações de tela") || has("exibição") || has("display"), 0xE7F4),
(&|| has("personalizar") || has("personalize") || has("aparência"), 0xE771),
(&|| has("ajustes") || has("configura") || has("preferências") || has("settings") || has("opções"), 0xE713),
(&|| st("encerrar") || st("sair") || st("quit") || has("forçar"), 0xE7E8),
(&|| st("fechar") || st("close"), 0xE8BB),
(&|| st("ocultar") || st("hide"), 0xED1A),
(&|| st("minimizar") || st("minimize"), 0xE921),
(&|| has("atualizar") || has("recarregar") || has("refresh") || has("reload"), 0xE72C),
(&|| st("desfazer") || st("undo"), 0xE7A7),
(&|| st("refazer") || st("redo"), 0xE7A6),
(&|| has("selecionar tudo") || has("select all"), 0xE8B3),
(&|| has("buscar") || has("procurar") || has("pesquisar") || has("search") || has("find"), 0xE721),
(&|| has("imprimir") || has("print"), 0xE749),
(&|| st("salvar") || st("save"), 0xE74E),
(&|| st("editar") || st("edit"), 0xE70F),
(&|| st("executar") || st("run"), 0xE768),
(&|| st("enviar para") || st("send to"), 0xE724),
(&|| st("novo") || st("nova") || st("new"), 0xE710),
(&|| has("todas as opções") || has("show more"), 0xE712),
(&|| has("pin to") || has("fixar"), 0xE718),
(&|| has("unpin"), 0xE77A),
(&|| has("give access") || has("conceder acesso") || has("acesso"), 0xE72D),
(&|| has("previous versions") || has("versões anteriores"), 0xE81C),
(&|| has("7-zip") || has("winrar") || has("extract") || has("extrair"), 0xF012),
(&|| has("git") || has("visual studio") || has("code"), 0xE943),
(&|| has("vlc") || has("reprodu") || has("play") || has("media"), 0xE768),
(&|| has("scan") || has("defender") || has("malware") || has("verificar"), 0xEA18),
(&|| has("ownership") || has("permiss"), 0xE72E),
(&|| has("linux") || has("shell"), 0xE756),
(&|| has("browse") || has("wiztree") || has("analy"), 0xE721),
(&|| has("mesa") || has("desktop"), 0xE7F4),
];
tab.iter().find(|(f, _)| f()).map(|x| x.1).unwrap_or(0)
}
fn level_idx_of(native: HWND) -> Option<usize> {
s().levels.iter().position(|l| l.native == native)
}
fn level_by_id(id: u32) -> Option<usize> {
s().levels.iter().position(|l| l.id == id)
}
fn clean(t: &str) -> (String, String) {
let (a, sc) = t.split_once('\t').unwrap_or((t, ""));
let mut out = String::new();
let mut it = a.chars().peekable();
while let Some(c) = it.next() {
if c == '&' {
if it.peek() == Some(&'&') {
out.push('&');
it.next();
}
continue;
}
out.push(c);
}
(out, sc.to_string())
}
fn read_items(l: &mut Level) {
l.items.clear();
unsafe {
let n = GetMenuItemCount(l.menu);
for k in 0..n.max(0) as u32 {
let mut buf = [0u16; 512];
let mut mi = MENUITEMINFOW { cbSize: std::mem::size_of::<MENUITEMINFOW>() as u32, fMask: MIIM_FTYPE | MIIM_STATE | MIIM_SUBMENU | MIIM_STRING, dwTypeData: PWSTR(buf.as_mut_ptr()), cch: 511, ..Default::default() };
if GetMenuItemInfoW(l.menu, k, true, &mut mi).is_err() {
continue;
}
let mut it = Item { pos: k, ..Default::default() };
if mi.fType.0 & MFT_SEPARATOR.0 != 0 {
if l.items.last().is_none_or(|x| x.sep) {
continue; // sem separadores repetidos
}
it.sep = true;
} else {
let t = from_w(&buf);
if t.is_empty() {
continue; // desenhado pelo próprio programa, sem texto: fica de fora
}
(it.label, it.shortcut) = clean(&t);
it.disabled = mi.fState.0 & (MFS_DISABLED.0 | MFS_GRAYED.0) != 0;
it.checked = mi.fState.0 & MFS_CHECKED.0 != 0;
it.radio = mi.fType.0 & MFT_RADIOCHECK.0 != 0;
it.sub = !mi.hSubMenu.is_invalid();
}
l.items.push(it);
}
}
while l.items.last().is_some_and(|x| x.sep) {
l.items.pop();
}
}
fn formats() -> (IDWriteTextFormat, IDWriteTextFormat) {
let st = s();
if st.tf_icon.is_none() {
st.tf_icon = cjk::format(ui::dw(), "Segoe Fluent Icons", DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, 13.0, "");
if let Some(f) = &st.tf_icon {
unsafe {
let _ = f.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
let _ = f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
}
}
}
st.tf.get_or_insert_with(|| (ui::fmt(13.0, DWRITE_FONT_WEIGHT_NORMAL), ui::format(13.0, DWRITE_FONT_WEIGHT_NORMAL, false, DWRITE_TEXT_ALIGNMENT_TRAILING))).clone()
}
fn scrolls(l: &Level) -> bool {
l.h > l.view + 0.5
}
fn max_scroll(l: &Level) -> f32 {
(l.h - l.view).max(0.0)
}
fn up_arrow(l: &Level) -> bool {
scrolls(l) && l.scroll > 0.5
}
fn down_arrow(l: &Level) -> bool {
scrolls(l) && l.scroll < max_scroll(l) - 0.5
}
/// deixa o item à vista (teclado descendo um menu longo)
fn reveal(l: &mut Level, i: usize) {
if !scrolls(l) {
return;
}
let (top, bot) = (l.items[i].r.top - l.scroll, l.items[i].r.bottom - l.scroll);
if top < ARROW {
l.scroll -= ARROW - top;
} else if bot > l.view - ARROW {
l.scroll += bot - (l.view - ARROW);
}
l.scroll = l.scroll.clamp(0.0, max_scroll(l));
}
fn measure(l: &mut Level) {
let (tf, _) = formats();
let (mut max_l, mut max_s) = (0f32, 0f32);
let (mut any_sub, mut any_icon, mut any_check) = (false, false, false);
let golden = golden_menus();
for it in l.items.iter_mut().filter(|i| !i.sep) {
any_check |= it.checked;
it.icon = if backdrop::liquid() && (!golden || golden_icon(&it.label)) { auto_icon(&it.label) } else { 0 }; // Tahoe: símbolo em cada item
any_icon |= it.icon != 0;
max_l = max_l.max(ui::text_width(&tf, &it.label));
if !it.shortcut.is_empty() {
max_s = max_s.max(ui::text_width(&tf, &it.shortcut));
}
any_sub |= it.sub;
}
// Golden Gate: o texto a 16 só quando nenhum item tem ✓; com ✓, 26
l.text_l = if golden {
if any_icon {
41.0
} else if any_check {
26.0
} else {
16.0
}
} else if any_icon {
34.0
} else {
TEXTL
};
l.w = 160.0f32.max(l.text_l + max_l + if max_s > 0.0 { 30.0 + max_s } else { 0.0 } + if any_sub { 22.0 } else { 0.0 } + TEXTR);
let tahoe = backdrop::liquid(); // medidas do menu do Tahoe: linhas de 20, separador de 9, 6 de folga
let pad = if golden { 5.5 } else if tahoe { 6.0 } else { PADY };
let mut y = pad;
for it in l.items.iter_mut() {
let h = if it.sep {
if golden {
11.0
} else if tahoe {
9.0
} else {
SEP
}
} else if golden {
24.0
} else if tahoe {
20.0
} else {
ROW
};
it.r = rf(0.0, y, l.w, y + h);
y += h;
}
l.h = y + pad;
l.view = l.h;
}
unsafe fn paint_on(l: &Level, rt: &ID2D1DeviceContext) {
let (tf, tf_r) = formats();
let tf_icon = s().tf_icon.clone();
let dark = ui::dark();
let clear = l.glass && menu_glass_on(); // vidro do Dock: a tinta fica quase toda no vidro
let Ok(br) = rt.CreateSolidColorBrush(&if dark { col(0.16, 0.16, 0.17, if clear { 0.22 } else { 0.40 }) } else { col(0.97, 0.97, 0.97, if clear { 0.24 } else { 0.45 }) }, None) else { return };
rt.FillRectangle(&rf(0.0, 0.0, l.w, l.view), &br);
let (up, down) = (up_arrow(l), down_arrow(l));
let mut base = mat::ident();
rt.GetTransform(&mut base);
rt.PushAxisAlignedClip(&rf(0.0, if up { ARROW } else { 0.0 }, l.w, l.view - if down { ARROW } else { 0.0 }), D2D1_ANTIALIAS_MODE_ALIASED);
rt.SetTransform(&mat::mul(&mat::trans(0.0, -l.scroll), &base));
let text = if dark { col(1.0, 1.0, 1.0, 0.92) } else { col(0.0, 0.0, 0.0, 0.88) };
let dim = if dark { col(1.0, 1.0, 1.0, 0.30) } else { col(0.0, 0.0, 0.0, 0.28) };
let gray = if dark { col(1.0, 1.0, 1.0, 0.45) } else { col(0.0, 0.0, 0.0, 0.45) };
let white = col(1.0, 1.0, 1.0, 1.0);
let golden = golden_menus();
for (i, it) in l.items.iter().enumerate() {
if it.sep {
let y = ((it.r.top + it.r.bottom) / 2.0).floor() + 0.5;
br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.12) } else { col(0.0, 0.0, 0.0, 0.10) });
rt.DrawLine(pt(INSET + 5.0, y), pt(l.w - INSET - 5.0, y), &br, 1.0, None);
continue;
}
let hot = i as i32 == l.hover && !it.disabled;
if hot {
br.SetColor(&if golden { col(0.0, 122.0 / 255.0, 1.0, 1.0) } else { col(0.04, 0.40, 0.95, 1.0) }); // azul de destaque do Mac
let (inn, rad) = if golden { (5.5, 7.0) } else { (INSET, 4.0) };
rt.FillRoundedRectangle(&rr(rf(inn, it.r.top, l.w - inn, it.r.bottom), rad, rad), &br);
}
br.SetColor(&if it.disabled { dim } else if hot { white } else { text });
let cy = (it.r.top + it.r.bottom) / 2.0;
if it.checked {
if it.radio {
rt.FillEllipse(&ell(pt(12.0, cy), 3.0, 3.0), &br);
} else {
rt.DrawLine(pt(8.0, cy), pt(11.0, cy + 3.5), &br, 1.6, None);
rt.DrawLine(pt(11.0, cy + 3.5), pt(16.5, cy - 4.0), &br, 1.6, None);
}
}
if it.icon != 0 && !it.checked {
if let Some(fi) = &tf_icon {
rt.DrawText(&[it.icon], fi, &rf(13.0, it.r.top, 33.0, it.r.bottom), &br, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
}
}
rt.DrawText(&w(&it.label), &tf, &rf(l.text_l, it.r.top, l.w - TEXTR, it.r.bottom), &br, D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
if !it.shortcut.is_empty() {
if !hot {
br.SetColor(&if it.disabled { dim } else { gray });
}
rt.DrawText(&w(&it.shortcut), &tf_r, &rf(l.text_l, it.r.top, l.w - TEXTR - if it.sub { 16.0 } else { 0.0 }, it.r.bottom), &br, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
}
if it.sub {
// ›
let x = l.w - TEXTR - 4.0;
br.SetColor(&if it.disabled { dim } else if hot { white } else { text });
rt.DrawLine(pt(x - 3.0, cy - 4.0), pt(x + 1.0, cy), &br, 1.5, None);
rt.DrawLine(pt(x + 1.0, cy), pt(x - 3.0, cy + 4.0), &br, 1.5, None);
}
}
rt.SetTransform(&base);
rt.PopAxisAlignedClip();
br.SetColor(&text); // setinhas de rolagem, como no Mac
let cx = l.w / 2.0;
if up {
rt.DrawLine(pt(cx - 4.0, ARROW / 2.0 + 2.0), pt(cx, ARROW / 2.0 - 2.0), &br, 1.5, None);
rt.DrawLine(pt(cx, ARROW / 2.0 - 2.0), pt(cx + 4.0, ARROW / 2.0 + 2.0), &br, 1.5, None);
}
if down {
let yy = l.view - ARROW / 2.0;
rt.DrawLine(pt(cx - 4.0, yy - 2.0), pt(cx, yy + 2.0), &br, 1.5, None);
rt.DrawLine(pt(cx, yy + 2.0), pt(cx + 4.0, yy - 2.0), &br, 1.5, None);
}
if l.glass {
// contorno fino no canto arredondado (no lugar da borda do Windows)
br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.14) } else { col(0.0, 0.0, 0.0, 0.12) });
let inn = 0.5 / l.scale;
let rad = menu_r() - inn;
rt.DrawRoundedRectangle(&rr(rf(inn, inn, l.w - inn, l.view - inn), rad, rad), &br, 1.0 / l.scale, None);
}
}
fn paint(l: &mut Level) {
let (wpx, hpx) = ((l.w * l.scale).ceil() as i32, (l.view * l.scale).ceil() as i32);
let Some(rt) = ui::gpu_begin(&mut l.s, wpx, hpx, l.scale) else { return };
unsafe { paint_on(l, &rt) };
ui::gpu_end(&mut l.s);
if l.glass && !l.clipped {
// o desenho recortado no mesmo canto do vidro
if let (Some(dev), Some(vis)) = (ui::comp(), &l.s.visual) {
unsafe {
if let Ok(clip) = dev.CreateRectangleClip() {
let r = menu_r() * l.scale;
let _ = clip.SetLeft2(0.0);
let _ = clip.SetTop2(0.0);
let _ = clip.SetRight2((l.w * l.scale).ceil());
let _ = clip.SetBottom2((l.view * l.scale).ceil());
let _ = clip.SetTopLeftRadiusX2(r);
let _ = clip.SetTopLeftRadiusY2(r);
let _ = clip.SetTopRightRadiusX2(r);
let _ = clip.SetTopRightRadiusY2(r);
let _ = clip.SetBottomLeftRadiusX2(r);
let _ = clip.SetBottomLeftRadiusY2(r);
let _ = clip.SetBottomRightRadiusX2(r);
let _ = clip.SetBottomRightRadiusY2(r);
let _ = vis.SetClip(&clip);
let _ = dev.Commit();
l.clipped = true;
}
}
}
}
}
fn paint_idx(i: usize) {
if let Some(l) = s().levels.get_mut(i) {
paint(l);
}
}
unsafe extern "system" fn popup_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
if m == WM_MOUSEACTIVATE {
return LRESULT(MA_NOACTIVATE as isize);
}
if m == WM_PAINT {
let mut ps = PAINTSTRUCT::default();
BeginPaint(h, &mut ps);
let _ = EndPaint(h, &ps);
if let Some(i) = s().levels.iter().position(|x| x.wnd == h) {
paint_idx(i);
}
return LRESULT(0);
}
DefWindowProcW(h, m, w_, l)
}
fn update_rects() {
let v: Vec<RECT> = s()
.levels
.iter()
.map(|l| {
let mut r = RECT::default();
unsafe {
let _ = GetWindowRect(l.wnd, &mut r);
}
r
})
.collect();
*RECTS.lock().unwrap() = v;
}
fn close_level(i: usize) {
let mut l = s().levels.remove(i);
if l.glass && !l.back.0.is_null() {
backdrop::detach(l.back);
}
ui::gpu_free(&mut l.s);
unsafe {
if !l.wnd.0.is_null() {
let _ = DestroyWindow(l.wnd);
}
if !l.back.0.is_null() {
let _ = DestroyWindow(l.back);
}
}
update_rects();
}
fn close_last() {
let n = s().levels.len();
if n > 0 {
close_level(n - 1);
}
}
/// fechando o menu inteiro (escolheu, Esc, clique fora): some em fade, como no Mac (~150 ms)
fn fade_all() {
if s().levels.is_empty() || shell::setting("menus_fade", "1") != "1" {
return;
}
let dev = ui::comp();
let mut fx = Vec::new();
unsafe {
for l in &s().levels {
if let (Some(d), Some(v)) = (&dev, &l.s.visual) {
if let Ok(e) = d.CreateEffectGroup() {
let _ = v.SetEffect(&e);
fx.push(e);
}
}
}
let t0 = anim::now();
loop {
let p = ((anim::now() - t0) / 150.0).min(1.0) as f32;
let a = (1.0 - p) * (1.0 - p);
for e in &fx {
let _ = e.SetOpacity2(a);
}
for l in &s().levels {
if l.glass && !l.back.0.is_null() {
backdrop::fade(l.back, a, 1.0, 0.0, 0.0);
}
}
if let Some(d) = &dev {
let _ = d.Commit();
}
if p >= 1.0 {
break;
}
let _ = DwmFlush();
}
}
}
fn close_all(fade: bool) {
if fade {
fade_all();
}
while !s().levels.is_empty() {
close_last();
}
stop_hooks();
}
/// item com o mouse em cima, em qualquer nível: (nível, índice; -1 = na setinha ou fora dos itens)
fn hit_at(p: POINT) -> Option<(usize, i32)> {
for (k, l) in s().levels.iter().enumerate().rev() {
let mut wr = RECT::default();
unsafe {
let _ = GetWindowRect(l.wnd, &mut wr);
}
if !(p.x >= wr.left && p.x < wr.right && p.y >= wr.top && p.y < wr.bottom) {
continue;
}
let y = (p.y - wr.top) as f32 / l.scale;
if (up_arrow(l) && y < ARROW) || (down_arrow(l) && y >= l.view - ARROW) {
return Some((k, -1)); // na setinha: rola, não escolhe
}
let y = y + l.scroll;
let idx = l.items.iter().position(|it| !it.sep && y >= it.r.top && y < it.r.bottom).map(|i| i as i32).unwrap_or(-1);
return Some((k, idx));
}
None
}
/// tecla direto na janela do menu nativo (o laço do menu lê a fila da thread dele): funciona mesmo quando o teclado não
/// está com aquele programa (menus de plug-ins, como o Omnisphere dentro do Ableton)
fn native_key(native: HWND, vk: VIRTUAL_KEY) {
unsafe {
let mut down = 1isize | ((MapVirtualKeyW(vk.0 as u32, MAPVK_VK_TO_VSC) as isize) << 16);
if vk == VK_LEFT || vk == VK_RIGHT {
down |= 1 << 24; // tecla estendida
}
let _ = PostMessageW(native, WM_KEYDOWN, WPARAM(vk.0 as usize), LPARAM(down));
let _ = PostMessageW(native, WM_KEYUP, WPARAM(vk.0 as usize), LPARAM(down | (1 << 30) | (1 << 31)));
}
}
fn key(vk: VIRTUAL_KEY) {
let mk = |f: KEYBD_EVENT_FLAGS| INPUT { r#type: INPUT_KEYBOARD, Anonymous: INPUT_0 { ki: KEYBDINPUT { wVk: vk, wScan: 0, dwFlags: f, time: 0, dwExtraInfo: KEY_MARK } } };
unsafe {
SendInput(&[mk(KEYBD_EVENT_FLAGS(0)), mk(KEYEVENTF_KEYUP)], std::mem::size_of::<INPUT>() as i32);
}
}
/// destaca o item no menu nativo também (o teclado continua coerente); níveis abaixo deste fecham antes
fn select_native(li: usize, idx: i32) {
while s().levels.len() > li + 1 {
native_key(s().levels.last().unwrap().native, VK_LEFT);
close_last();
}
let l = &s().levels[li];
let pos = if idx >= 0 { l.items[idx as usize].pos as usize } else { usize::MAX };
unsafe {
let _ = PostMessageW(l.native, MN_SELECT, WPARAM(pos), LPARAM(0)); // sem esperar o outro programa
}
}
fn open_sub(li: usize, idx: i32) {
select_native(li, idx);
let st = s();
let l = &st.levels[li];
log!("menu: abrindo submenu \"{}\"", l.items[idx as usize].label);
native_key(l.native, VK_RIGHT);
st.sub_from = l.id;
st.sub_idx = idx;
st.sub_try = 0;
unsafe { SetTimer(st.host, T_SUBCHECK, 250, None) };
}
/// itens do menu da Área de Trabalho (Explorer) que abrem o Ajustes do Windows: vão para o nosso Ajustes do Sistema
fn our_settings_page(native: HWND, it: &Item) -> &'static str {
unsafe {
let mut pid = 0u32;
GetWindowThreadProcessId(native, Some(&mut pid));
let Ok(hp) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) else { return "" };
let mut p = [0u16; 260];
let mut n = p.len() as u32;
let ok = QueryFullProcessImageNameW(hp, PROCESS_NAME_WIN32, PWSTR(p.as_mut_ptr()), &mut n).is_ok();
let _ = CloseHandle(hp);
if !ok || !String::from_utf16_lossy(&p[..n as usize]).to_lowercase().ends_with("\\explorer.exe") {
return "";
}
}
let t = it.label.replace('&', "").to_lowercase();
match t.as_str() {
"display settings" | "configurações de exibição" | "configurações de vídeo" | "configurações da tela" => "telas",
"personalize" | "personalizar" => "fundo",
_ => "",
}
}
fn choose(li: usize, idx: i32) {
let st = s();
let it = st.levels[li].items[idx as usize].clone();
if it.disabled || it.sep {
return;
}
let page = our_settings_page(st.levels[li].native, &it);
if !page.is_empty() {
// o nosso Ajustes no lugar do Windows
log!("menu: \"{}\" -> Ajustes do Sistema ({page})", it.label);
for _ in 0..st.levels.len() {
key(VK_ESCAPE); // fecha o menu nativo sem escolher nada
}
shell::open_settings(page);
return;
}
select_native(li, idx);
if it.sub {
open_sub(li, idx); // o nativo abre o submenu; o nosso aparece no evento
return;
}
// pisca o item escolhido, como no Mac, e confirma no nativo
let l = &mut st.levels[li];
l.hover = -1;
paint(l);
std::thread::sleep(std::time::Duration::from_millis(70));
l.hover = idx;
paint(l);
// alguns programas ignoram a tecla (Omnisphere): se o menu ainda estiver aberto em 250 ms, o clique interno
log!("menu: escolhido \"{}\"", it.label);
native_key(l.native, VK_RETURN);
st.choose_native = l.native;
st.choose_pos = it.pos;
st.choose_idx = idx;
st.choose_try = 0;
unsafe { SetTimer(st.host, T_CHOOSECHECK, 250, None) };
}
unsafe extern "system" fn mouse_hook(code: i32, w_: WPARAM, lp: LPARAM) -> LRESULT {
if code == HC_ACTION as i32 {
let ms = &*(lp.0 as *const MSLLHOOKSTRUCT);
let over = RECTS.lock().unwrap().iter().any(|r| ms.pt.x >= r.left && ms.pt.x < r.right && ms.pt.y >= r.top && ms.pt.y < r.bottom);
let host = HWND(HOST.load(Ordering::Relaxed) as *mut _);
let m = w_.0 as u32;
if m == WM_MOUSEWHEEL && over {
// roda do mouse rola o menu longo
let _ = PostMessageW(host, WM_MENU_WHEEL, WPARAM((ms.mouseData >> 16) as u16 as i16 as isize as usize), makelparam(ms.pt.x, ms.pt.y));
return LRESULT(1);
}
if m == WM_MOUSEMOVE {
if !MOVE_PENDING.swap(true, Ordering::SeqCst) {
let _ = PostMessageW(host, WM_MENU_MOVE, WPARAM(0), LPARAM(0)); // um aviso por vez
}
} else if over {
if m == WM_LBUTTONUP || m == WM_RBUTTONUP {
let _ = PostMessageW(host, WM_MENU_CLICK, WPARAM(ms.pt.x as isize as usize), LPARAM(ms.pt.y as isize));
}
return LRESULT(1); // clique nosso: o menu nativo não vê
}
// fora dos nossos: segue (o nativo, fora da tela, vê o clique fora e fecha)
}
CallNextHookEx(None, code, w_, lp)
}
fn hook_thread() {
shell::thread_de_gancho();
unsafe {
let mut m = MSG::default();
let _ = PeekMessageW(&mut m, None, 0, 0, PM_NOREMOVE); // cria a fila de mensagens da thread
HOOK_TID.store(GetCurrentThreadId(), Ordering::SeqCst);
let mut hk = HHOOK::default();
while GetMessageW(&mut m, None, 0, 0).as_bool() {
if m.message == WM_HOOK_ON && hk.is_invalid() {
hk = SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_hook), HINSTANCE(shell::inst().0), 0).unwrap_or_default();
}
if m.message == WM_HOOK_OFF && !hk.is_invalid() {
let _ = UnhookWindowsHookEx(hk);
hk = HHOOK::default();
}
}
}
}
/// mouse numa setinha: rola sozinho (timer), como no Mac
fn arrow_under(p: POINT) -> Option<(usize, f32)> {
for (k, l) in s().levels.iter().enumerate().rev() {
let mut wr = RECT::default();
unsafe {
let _ = GetWindowRect(l.wnd, &mut wr);
}
if !(p.x >= wr.left && p.x < wr.right && p.y >= wr.top && p.y < wr.bottom) {
continue;
}
let y = (p.y - wr.top) as f32 / l.scale;
if up_arrow(l) && y < ARROW {
return Some((k, -1.0));
}
if down_arrow(l) && y >= l.view - ARROW {
return Some((k, 1.0));
}
return None;
}
None
}
fn scroll_by(li: usize, dy: f32) {
let l = &mut s().levels[li];
let v = (l.scroll + dy).clamp(0.0, max_scroll(l));
if v == l.scroll {
return;
}
l.scroll = v;
// submenus abertos a partir deste nível fecham (o item que os abriu saiu do lugar)
while s().levels.len() > li + 1 {
native_key(s().levels.last().unwrap().native, VK_LEFT);
close_last();
}
paint_idx(li);
}
fn on_move() {
MOVE_PENDING.store(false, Ordering::SeqCst);
let st = s();
st.last_mouse = unsafe { GetTickCount() };
let mut p = POINT::default();
unsafe {
let _ = GetCursorPos(&mut p);
if arrow_under(p).is_some() {
SetTimer(st.host, T_SCROLL, 16, None);
}
}
let Some((li, idx)) = hit_at(p) else {
// fora: tira o destaque do nível mais fundo (como no Mac)
if let Some(l) = st.levels.last_mut() {
if l.hover >= 0 && !l.items[l.hover as usize].sub {
l.hover = -1;
paint(l);
}
}
return;
};
if idx == st.levels[li].hover {
return;
}
unsafe {
let _ = KillTimer(st.host, T_CHOOSECHECK);
}
st.levels[li].hover = idx;
paint_idx(li);
if idx >= 0 {
select_native(li, idx);
}
unsafe {
let _ = KillTimer(st.host, T_SUBMENU);
}
st.sub_wanted = -1;
if idx >= 0 {
let it = &st.levels[li].items[idx as usize];
if it.sub && !it.disabled {
// submenu abre com um pequeno atraso
st.sub_wanted = idx;
unsafe { SetTimer(st.host, T_SUBMENU, 200, None) };
}
}
}
fn on_click(p: POINT) {
if let Some((li, idx)) = hit_at(p) {
if idx >= 0 {
choose(li, idx);
}
}
}
fn show_native(h: HWND) {
// o nativo fica de verdade (não conseguimos ler os itens): a DLL dentro do programa para de mandá-lo para fora
unsafe {
let _ = SetPropW(h, w!("ShellMenuLivre"), HANDLE(1 as *mut _));
let mut a = 0u8;
let mut fl = LAYERED_WINDOW_ATTRIBUTES_FLAGS(0);
if GetLayeredWindowAttributes(h, None, Some(&mut a), Some(&mut fl)).is_ok() && fl.0 & LWA_ALPHA.0 != 0 && a == 0 {
let _ = SetLayeredWindowAttributes(h, COLORREF(0), 255, LWA_ALPHA);
}
}
}
fn open_level(native: HWND, menu: HMENU, nr: RECT) {
let st = s();
st.next_id += 1;
let mut l = Box::new(Level { id: st.next_id, native, menu, wnd: HWND::default(), back: HWND::default(), s: ui::GpuSurface::default(), glass: false, clipped: false, items: Vec::new(), hover: -1, w: 0.0, h: 0.0, text_l: TEXTL, view: 0.0, scroll: 0.0, scale: 1.0 });
read_items(&mut l);
unsafe {
if l.items.is_empty() {
log!("menu: sem itens com texto ({} no nativo), fica o nativo", GetMenuItemCount(menu));
let _ = SetPropW(native, w!("ShellMenuLivre"), HANDLE(1 as *mut _)); // antes de mover: a DLL não o manda de volta
if let Some(p) = st.levels.last() {
// o pai está fora da tela: o nativo vem para perto do nosso
let mut pr = RECT::default();
let _ = GetWindowRect(p.wnd, &mut pr);
let _ = SetWindowPos(native, HWND_TOPMOST, pr.right - 4, pr.top, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE);
} else {
let _ = SetWindowPos(native, None, nr.left, nr.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
show_native(native);
return;
}
let mut anchor = POINT { x: nr.left, y: nr.top };
if let Some(p) = st.levels.last() {
// submenu: ao lado do item do nível de cima
let mut pr = RECT::default();
let _ = GetWindowRect(p.wnd, &mut pr);
let top = if p.hover >= 0 { p.items[p.hover as usize].r.top - p.scroll } else { 0.0 };
anchor = POINT { x: pr.right - (4.0 * p.scale) as i32, y: pr.top + ((top - PADY) * p.scale) as i32 };
}
let mon = MonitorFromPoint(anchor, MONITOR_DEFAULTTONEAREST);
let (mut dx, mut dy) = (96u32, 96u32);
let _ = GetDpiForMonitor(mon, MDT_EFFECTIVE_DPI, &mut dx, &mut dy);
l.scale = dx as f32 / 96.0;
measure(&mut l);
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
let _ = GetMonitorInfoW(mon, &mut mi);
let room = (mi.rcWork.bottom - mi.rcWork.top) as f32 / l.scale - 8.0; // não cabe: fica da altura da tela e rola
if l.h > room {
l.view = room;
}
let (wpx, hpx) = ((l.w * l.scale).ceil() as i32, (l.view * l.scale).ceil() as i32);
let (mut x, mut y) = (anchor.x, anchor.y);
if x + wpx > mi.rcWork.right {
// não cabe à direita: submenu abre para a esquerda do pai; menu encosta na borda
match st.levels.last() {
None => x = mi.rcWork.right - wpx,
Some(p) => {
let mut pr = RECT::default();
let _ = GetWindowRect(p.wnd, &mut pr);
x = pr.left - wpx + (4.0 * l.scale) as i32;
}
}
}
if y + hpx > mi.rcWork.bottom {
y = mi.rcWork.bottom - (4.0 * l.scale) as i32 - hpx;
}
if y < mi.rcWork.top {
y = mi.rcWork.top + (4.0 * l.scale) as i32;
}
// tira o nativo da tela (continua aberto, recebendo o teclado); programa elevado: fica o nativo
if SetWindowPos(native, None, -32000, -32000, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE).is_err() {
show_native(native);
return;
}
// duas janelas: atrás o vidro (do Shell: recorte arredondado liso de 12; sem ele, o acrílico do Windows), na frente
// o menu desenhado na GPU
let hi = shell::inst();
let ex_back = WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_TRANSPARENT;
l.back = CreateWindowExW(ex_back | WS_EX_NOREDIRECTIONBITMAP, w!("ShellMenuMac"), w!(""), WS_POPUP, x, y, wpx, hpx, None, None, hi, None).unwrap_or_default();
l.glass = backdrop::attach(l.back);
let corner: u32 = if l.glass { 1 } else { 2 };
let dark = ui::dark();
if !l.glass {
let _ = DestroyWindow(l.back);
l.back = CreateWindowExW(ex_back, w!("ShellMenuMac"), w!(""), WS_POPUP, x, y, wpx, hpx, None, None, hi, None).unwrap_or_default();
let _ = DwmSetWindowAttribute(l.back, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const _, 4);
ui::acrylic(l.back, if dark { 0x6020_1E1E } else { 0x70F4_F4F4 });
} else {
let _ = DwmSetWindowAttribute(l.back, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const _, 4);
// bem fosco e com tinta firme: o texto não pode disputar com o que está atrás
let pcs = [backdrop::Piece { r: rf(0.0, 0.0, wpx as f32, hpx as f32), radius: menu_r() * l.scale, ..Default::default() }];
if menu_glass_on() {
backdrop::set_pieces(l.back, wpx as f32, hpx as f32, &pcs, clear_menu_tint(dark), 4.0);
} else {
backdrop::set_pieces(l.back, wpx as f32, hpx as f32, &pcs, if dark { col(0.13, 0.13, 0.14, 0.62) } else { col(0.97, 0.97, 0.98, 0.66) }, 18.0);
}
}
l.wnd = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP, w!("ShellMenuMac"), w!(""), WS_POPUP, x, y, wpx, hpx, None, None, hi, None).unwrap_or_default();
l.s.hwnd = l.wnd;
let _ = DwmSetWindowAttribute(l.wnd, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const _, 4);
let border: u32 = if l.glass {
0xFFFF_FFFE
} else if dark {
0x004A_4848
} else {
0x00CA_C6C6
};
let _ = DwmSetWindowAttribute(l.wnd, DWMWINDOWATTRIBUTE(34), &border as *const _ as *const _, 4);
let glass = l.glass;
let (wnd, back) = (l.wnd, l.back);
paint(&mut l); // desenha antes de aparecer: sem um quadro vazio piscando
st.levels.push(l);
update_rects();
// com o vidro do Shell: mostra só depois que o vidro desenhado chegou à tela (sem resposta em 60 ms, assim mesmo)
if glass {
backdrop::after_commit(st.host, WM_MENU_SHOWNOW);
SetTimer(st.host, T_SHOWNOW, 60, None);
} else {
let _ = ShowWindow(back, SW_SHOWNOACTIVATE);
let _ = ShowWindow(wnd, SW_SHOWNOACTIVATE);
}
}
}
unsafe extern "system" fn on_focus(_: HWINEVENTHOOK, _: u32, h: HWND, obj: i32, child: i32, _: u32, _: u32) {
// teclado no menu nativo: o destaque muda e o nosso acompanha (child = posição + 1)
let Some(li) = level_idx_of(h) else { return };
if obj != OBJID_CLIENT.0 || child <= 0 || GetTickCount().wrapping_sub(s().last_mouse) < 400 {
return; // < 400 ms do mouse: é o eco do nosso próprio destaque
}
let l = &mut s().levels[li];
if let Some(i) = l.items.iter().position(|it| it.pos == (child - 1) as u32) {
if l.hover != i as i32 {
l.hover = i as i32;
reveal(l, i);
paint(l);
}
}
}
/// submenu grande: o Windows mostra a janela antes do aviso de "abriu" chegar e ela piscava no canto; enquanto há menu
/// nosso aberto, todo menu nativo novo nasce invisível (alfa 0)
unsafe extern "system" fn on_create(_: HWINEVENTHOOK, _: u32, h: HWND, obj: i32, _: i32, _: u32, _: u32) {
if obj != OBJID_WINDOW.0 || h.0.is_null() {
return;
}
let mut c = [0u16; 16];
let n = GetClassNameW(h, &mut c);
if String::from_utf16_lossy(&c[..n.max(0) as usize]) != "#32768" {
return;
}
let ex = GetWindowLongPtrW(h, GWL_EXSTYLE);
if ex & WS_EX_LAYERED.0 as isize == 0 {
SetWindowLongPtrW(h, GWL_EXSTYLE, ex | WS_EX_LAYERED.0 as isize);
}
let _ = SetLayeredWindowAttributes(h, COLORREF(0), 0, LWA_ALPHA);
}
fn start_hooks() {
let st = s();
unsafe {
let t = HOOK_TID.load(Ordering::SeqCst);
if t != 0 {
let _ = PostThreadMessageW(t, WM_HOOK_ON, WPARAM(0), LPARAM(0));
}
if st.create_hook.is_invalid() {
st.create_hook = SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_CREATE, None, Some(on_create), 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
}
if st.focus_hook.is_invalid() {
st.focus_hook = SetWinEventHook(EVENT_OBJECT_FOCUS, EVENT_OBJECT_FOCUS, None, Some(on_focus), 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
}
}
}
fn stop_hooks() {
let st = s();
unsafe {
let t = HOOK_TID.load(Ordering::SeqCst);
if t != 0 {
let _ = PostThreadMessageW(t, WM_HOOK_OFF, WPARAM(0), LPARAM(0));
}
for hk in [&mut st.focus_hook, &mut st.create_hook] {
if !hk.is_invalid() {
let _ = UnhookWinEvent(*hk);
*hk = HWINEVENTHOOK::default();
}
}
for t in [T_SUBMENU, T_SUBCHECK, T_CHOOSECHECK, T_SCROLL] {
let _ = KillTimer(st.host, t);
}
}
}
unsafe extern "system" fn on_menu(_: HWINEVENTHOOK, ev: u32, h: HWND, _: i32, _: i32, _: u32, _: u32) {
let st = s();
match ev {
EVENT_SYSTEM_MENUPOPUPSTART => {
let mut c = [0u16; 16];
let n = GetClassNameW(h, &mut c);
if String::from_utf16_lossy(&c[..n.max(0) as usize]) != "#32768" {
return;
}
let mut pid = 0u32;
GetWindowThreadProcessId(h, Some(&mut pid));
if pid == st.self_pid {
return;
}
// tira o nativo da tela já, antes de perguntar qualquer coisa ao programa (o menu piscava no lugar dele)
let mut nr = RECT::default();
let _ = GetWindowRect(h, &mut nr);
// a DLL dentro do programa já o mandou para fora da tela antes de aparecer: o lugar dele ficou guardado
let px = GetPropW(h, w!("ShellMenuX"));
if !px.is_invalid() {
let (ox, oy) = (px.0 as isize as i32 - 40000, GetPropW(h, w!("ShellMenuY")).0 as isize as i32 - 40000);
let (ww, hh) = (nr.right - nr.left, nr.bottom - nr.top);
nr = RECT { left: ox, top: oy, right: ox + ww, bottom: oy + hh };
}
let moved = SetWindowPos(h, None, -32000, -32000, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE).is_ok();
let mut r = 0usize;
let ok = SendMessageTimeoutW(h, MN_GETHMENU, WPARAM(0), LPARAM(0), SMTO_ABORTIFHUNG, 600, Some(&mut r)).0 != 0;
let menu = HMENU(r as *mut _);
let valido = ok && r != 0 && IsMenu(menu).as_bool();
log!("menu: nativo abriu (pid {pid}, nível {}, {},{} {}x{}, {} itens{})", st.levels.len(), nr.left, nr.top, nr.right - nr.left, nr.bottom - nr.top, if valido { GetMenuItemCount(menu) } else { -1 }, if ok { "" } else { ", sem resposta" });
if !valido {
// submenu que não conseguimos ler: o nativo nasceu ao lado do pai, que está fora da tela; traz para perto
let _ = SetPropW(h, w!("ShellMenuLivre"), HANDLE(1 as *mut _));
if let Some(p) = st.levels.last() {
let mut pr = RECT::default();
let _ = GetWindowRect(p.wnd, &mut pr);
let _ = SetWindowPos(h, HWND_TOPMOST, pr.right - 4, pr.top, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE);
} else if moved {
let _ = SetWindowPos(h, None, nr.left, nr.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
show_native(h);
return;
}
start_hooks();
open_level(h, menu, nr);
}
EVENT_SYSTEM_MENUPOPUPEND => {
if let Some(li) = level_idx_of(h) {
while s().levels.len() > li + 1 {
close_last();
}
close_level(li);
if s().levels.is_empty() {
stop_hooks();
}
}
}
EVENT_SYSTEM_MENUEND => {
if !st.levels.is_empty() {
close_all(true);
}
}
_ => {}
}
}
unsafe extern "system" fn host_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
let st = s();
match m {
WM_MENU_MOVE => on_move(),
WM_MENU_CLICK => on_click(POINT { x: w_.0 as isize as i32, y: l.0 as i32 }),
WM_MENU_SHOWNOW => show_now(),
WM_MENU_WHEEL => {
let p = POINT { x: get_x_lparam(l), y: get_y_lparam(l) };
let li = st.levels.iter().position(|x| {
let mut wr = RECT::default();
let _ = GetWindowRect(x.wnd, &mut wr);
p.x >= wr.left && p.x < wr.right && p.y >= wr.top && p.y < wr.bottom
});
if let Some(li) = li.filter(|&i| scrolls(&st.levels[i])) {
scroll_by(li, -(w_.0 as isize as i16 as f32) / 120.0 * ROW * 3.0);
if let Some((hi, idx)) = hit_at(p) {
if hi == li {
st.levels[li].hover = idx;
paint_idx(li);
}
}
}
}
WM_TIMER => match w_.0 {
T_SHOWNOW => {
let _ = KillTimer(h, T_SHOWNOW);
show_now();
}
T_SCROLL => {
let mut p = POINT::default();
let _ = GetCursorPos(&mut p);
match arrow_under(p) {
None => {
let _ = KillTimer(h, T_SCROLL);
}
Some((li, dir)) => {
st.levels[li].hover = -1;
scroll_by(li, dir * 6.0);
}
}
}
T_CHOOSECHECK => {
let _ = KillTimer(h, T_CHOOSECHECK);
let nat = st.choose_native;
// fechou (o programa recebeu) ou o mouse já está em outro item: não insiste
let Some(li) = level_idx_of(nat) else { return LRESULT(0) };
if !IsWindow(nat).as_bool() || !IsWindowVisible(nat).as_bool() || st.levels[li].hover != st.choose_idx {
return LRESULT(0);
}
st.choose_try += 1;
if st.choose_try == 1 {
log!("menu: a tecla não escolheu; tentando o clique interno do menu");
let pos = WPARAM(st.choose_pos as usize);
let _ = PostMessageW(nat, MN_SELECT, pos, LPARAM(0));
let _ = PostMessageW(nat, MN_BTNDOWN, pos, LPARAM(0));
let _ = PostMessageW(nat, MN_BTNUP, pos, LPARAM(0));
SetTimer(h, T_CHOOSECHECK, 250, None);
} else {
log!("menu: o programa não aceitou a escolha");
}
}
T_SUBCHECK => {
let _ = KillTimer(h, T_SUBCHECK);
// abriu (há nível novo) ou o mouse saiu
let Some(li) = level_by_id(st.sub_from) else { return LRESULT(0) };
if li + 1 != st.levels.len() || st.levels[li].hover != st.sub_idx {
return LRESULT(0);
}
st.sub_try += 1;
let l = &st.levels[li];
let pos = WPARAM(l.items[st.sub_idx as usize].pos as usize);
if st.sub_try == 1 {
log!("menu: submenu não abriu pela tecla; tentando MN_OPENHIERARCHY");
let _ = PostMessageW(l.native, MN_SELECT, pos, LPARAM(0));
let _ = PostMessageW(l.native, MN_OPENHIER, WPARAM(0), LPARAM(0));
} else if st.sub_try == 2 {
log!("menu: tentando tecla simulada");
let _ = PostMessageW(l.native, MN_SELECT, pos, LPARAM(0));
key(VK_RIGHT);
} else {
log!("menu: submenu não abriu");
return LRESULT(0);
}
SetTimer(h, T_SUBCHECK, 250, None);
}
T_SUBMENU => {
let _ = KillTimer(h, T_SUBMENU);
if !st.levels.is_empty() && st.sub_wanted >= 0 {
// o pedido é sempre do nível de cima com o mouse; acha qual
let wnt = st.sub_wanted;
let li = st.levels.iter().rposition(|x| x.hover == wnt && x.items.get(wnt as usize).is_some_and(|i| i.sub)).unwrap_or(st.levels.len() - 1);
if st.levels[li].hover == wnt {
open_sub(li, wnt);
}
}
st.sub_wanted = -1;
}
_ => {}
},
_ => return DefWindowProcW(h, m, w_, l),
}
LRESULT(0)
}
/// o vidro já está na tela: mostra os níveis novos
fn show_now() {
for lv in &s().levels {
unsafe {
if !IsWindowVisible(lv.wnd).as_bool() {
let _ = ShowWindow(lv.back, SW_SHOWNOACTIVATE);
let _ = ShowWindow(lv.wnd, SW_SHOWNOACTIVATE);
}
}
}
}
// ---- vidro atrás dos menus de contexto dos nossos apps (menu/context_menu.cpp, em qualquer processo): o menu
// ("MenuTahoePopup") manda "WacOSMenuVidro" com wParam = a janela dele e lParam = bits 0-1 o pedido (1 abriu, 2 começou a
// sumir, 0 fechou), bit 2 escuro, bits 4-15 a margem da sombra (px), bits 16-27 o raio do canto, bits 28-39 o fade (ms)
unsafe extern "system" fn mv_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
match m {
WM_MOUSEACTIVATE => LRESULT(MA_NOACTIVATE as isize),
WM_NCHITTEST => LRESULT(HTTRANSPARENT as isize),
WM_PAINT => {
let mut ps = PAINTSTRUCT::default();
BeginPaint(h, &mut ps);
let _ = EndPaint(h, &ps);
LRESULT(0)
}
_ => DefWindowProcW(h, m, w_, l),
}
}
fn mv_free(v: &mut MenuVidro) {
if !v.back.0.is_null() {
backdrop::detach(v.back);
unsafe {
let _ = DestroyWindow(v.back);
}
}
v.back = HWND::default();
}
unsafe extern "system" fn mv_tick(_: HWND, _: u32, _: usize, _: u32) {
let st = s();
let now = GetTickCount();
st.mv.retain(|&menu, v| {
let mh = HWND(menu as *mut _);
// o menu sumiu sem avisar (app fechou, travou): o vidro vai junto
let mut gone = !IsWindow(mh).as_bool() || (!IsWindowVisible(mh).as_bool() && now.wrapping_sub(v.born) > 600);
if !gone && v.fade_t0 != 0 && now.wrapping_sub(v.fade_t0) > v.fade_ms as u32 + 40 {
gone = true; // o fade (da Composição) acabou
}
if gone {
mv_free(v);
return false;
}
// sempre logo atrás do menu (o Dock subindo ou outro "sempre por cima" passando entre os dois cobria o texto)
if v.fade_t0 == 0 && GetWindow(mh, GW_HWNDNEXT).unwrap_or_default() != v.back {
let _ = SetWindowPos(v.back, mh, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
}
true
});
if st.mv.is_empty() && st.mv_timer != 0 {
let _ = KillTimer(None, st.mv_timer);
st.mv_timer = 0;
}
}
/// o pedido "WacOSMenuVidro" de um menu de contexto nosso; None: não é essa mensagem
pub fn vidro_msg(m: u32, w_: WPARAM, l: LPARAM) -> Option<LRESULT> {
static MSG_ID: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
let id = *MSG_ID.get_or_init(|| unsafe { RegisterWindowMessageW(w!("WacOSMenuVidro")) });
if id == 0 || m != id {
return None;
}
let st = s();
let menu = HWND(w_.0 as *mut _);
let p = l.0 as usize;
let code = p & 3;
unsafe {
let mut c = [0u16; 32];
let n = GetClassNameW(menu, &mut c);
if !IsWindow(menu).as_bool() || String::from_utf16_lossy(&c[..n.max(0) as usize]) != "MenuTahoePopup" {
return Some(LRESULT(0)); // só menus nossos
}
let k = menu.0 as isize;
if code == 0 {
if let Some(mut v) = st.mv.remove(&k) {
mv_free(&mut v);
}
return Some(LRESULT(0));
}
if code == 2 {
if let Some(v) = st.mv.get_mut(&k).filter(|v| v.fade_t0 == 0) {
v.fade_t0 = GetTickCount() | 1;
v.fade_ms = ((p >> 28) & 0xFFF) as i32;
backdrop::fade_out_anim(v.back, v.fade_ms); // junto com o fade do menu, também na Composição
}
return Some(LRESULT(0));
}
if code != 1 || !menu_glass_on() || IsWindowVisible(menu).as_bool() {
return Some(LRESULT(0)); // já visível: o pedido chegou atrasado (o menu ficou com o vidro dele)
}
if let Some(mut v) = st.mv.remove(&k) {
mv_free(&mut v);
}
let mut v = MenuVidro { dark: p & 4 != 0, margin: ((p >> 4) & 0xFFF) as i32, radius: ((p >> 16) & 0xFFF) as i32, born: GetTickCount(), fade_ms: 160, ..Default::default() };
let mut r = RECT::default();
let _ = GetWindowRect(menu, &mut r);
r = RECT { left: r.left + v.margin, top: r.top + v.margin, right: r.right - v.margin, bottom: r.bottom - v.margin };
v.w = r.right - r.left;
v.h = r.bottom - r.top;
if v.w <= 0 || v.h <= 0 {
return Some(LRESULT(0));
}
let hi = shell::inst();
if !st.mv_reg {
RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(mv_proc), hInstance: hi, lpszClassName: w!("ShellMenuVidro"), ..Default::default() });
st.mv_reg = true;
}
v.back = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_TRANSPARENT | WS_EX_NOREDIRECTIONBITMAP, w!("ShellMenuVidro"), w!(""), WS_POPUP, r.left, r.top, v.w, v.h, None, None, hi, None).unwrap_or_default();
if v.back.0.is_null() || !backdrop::attach(v.back) {
if !v.back.0.is_null() {
let _ = DestroyWindow(v.back);
}
log!("menu de contexto: vidro indisponível");
return Some(LRESULT(0));
}
let nc: u32 = 1;
let _ = DwmSetWindowAttribute(v.back, DWMWINDOWATTRIBUTE(33), &nc as *const _ as *const _, 4); // sem o canto do DWM
backdrop::set_pieces(v.back, v.w as f32, v.h as f32, &[backdrop::Piece { r: rf(0.0, 0.0, v.w as f32, v.h as f32), radius: v.radius as f32, ..Default::default() }], clear_menu_tint(v.dark), 4.0);
let _ = SetWindowPos(v.back, menu, r.left, r.top, v.w, v.h, SWP_NOACTIVATE | SWP_SHOWWINDOW); // logo atrás do menu
st.mv.insert(k, v);
if st.mv_timer == 0 {
st.mv_timer = SetTimer(None, 0, 50, Some(mv_tick)); // o fade é da Composição: aqui só faxina e a ordem
}
Some(LRESULT(1))
}
}
pub fn start() {
if shell::setting("menus_do_windows", "1") != "1" {
return;
}
let st = s();
st.self_pid = unsafe { GetCurrentProcessId() };
unsafe {
let hi = shell::inst();
RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(popup_proc), hInstance: hi, lpszClassName: w!("ShellMenuMac"), hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), ..Default::default() });
RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(host_proc), hInstance: hi, lpszClassName: w!("ShellMenusHost"), ..Default::default() });
st.host = CreateWindowExW(WINDOW_EX_STYLE(0), w!("ShellMenusHost"), w!(""), WINDOW_STYLE(0), 0, 0, 0, 0, HWND_MESSAGE, None, hi, None).unwrap_or_default();
HOST.store(st.host.0 as isize, Ordering::Relaxed);
std::thread::spawn(hook_thread);
st.menu_hook = SetWinEventHook(EVENT_SYSTEM_MENUSTART, EVENT_SYSTEM_MENUPOPUPEND, None, Some(on_menu), 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
}
log!("menus do Windows: interceptando ({})", if st.menu_hook.is_invalid() { "falhou" } else { "ok" });
}
pub fn stop() {
close_all(false);
let st = s();
if !st.menu_hook.is_invalid() {
unsafe {
let _ = UnhookWinEvent(st.menu_hook);
}
st.menu_hook = HWINEVENTHOOK::default();
}
}
/// modo foto: um menu de exemplo (Abrir, Copiar, um marcado, um desativado, um submenu) no meio da tela
pub fn foto(tela_w: f32, tela_h: f32) {
let k = ui::foto_scale();
let mut l = Level { id: 1, native: HWND::default(), menu: HMENU::default(), wnd: HWND::default(), back: HWND::default(), s: ui::GpuSurface::default(), glass: true, clipped: true, items: Vec::new(), hover: 1, w: 0.0, h: 0.0, text_l: TEXTL, view: 0.0, scroll: 0.0, scale: k };
let it = |label: &str, sc: &str| Item { label: tr(label), shortcut: sc.into(), ..Default::default() };
l.items = vec![
it("Abrir", "Ctrl+O"),
it("Nova janela", "Ctrl+N"),
Item { sep: true, ..Default::default() },
Item { checked: true, ..it("Mostrar barra de status", "") },
Item { disabled: true, ..it("Colar", "Ctrl+V") },
Item { sub: true, ..it("Ordenar por", "") },
Item { sep: true, ..Default::default() },
it("Propriedades", "Alt+Enter"),
];
measure(&mut l);
let dark = ui::dark();
l.s.foto_pos = ((tela_w / 2.0 - l.w / 2.0) * k, (tela_h / 3.0) * k);
if let Some(dc) = ui::gpu_begin(&mut l.s, (l.w * k).ceil() as i32, (l.view * k).ceil() as i32, k) {
unsafe {
backdrop::foto_vidro(&dc, rf(0.0, 0.0, l.w, l.view), menu_r(), if dark { col(0.13, 0.13, 0.14, 0.62) } else { col(0.97, 0.97, 0.98, 0.66) });
paint_on(&l, &dc);
}
ui::gpu_end(&mut l.s);
}
}