A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! src\menu\context_menu.cpp: o menu de contexto próprio, no estilo do macOS (vidro, cantos arredondados, no máximo 3
//! grupos, submenus de um nível), por cima das extensões reais do Windows (IContextMenu), que executam o comando
//! escolhido. Também os menus com itens do próprio app (`show_items`), no mesmo visual.
//! Desenho: com a composição do Windows (Windows.UI.Composition), um cartão de cantos 12 (11 no Golden Gate) com o
//! desfoque do que está atrás e a sombra própria; sem ela, uma janela com o acrílico do DWM e cantos de 8.
#![allow(dead_code)]
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::Mutex;
use windows::core::*;
use windows::Foundation::Numerics::{Vector2, Vector3};
use windows::Foundation::{Size, TimeSpan};
use windows::Graphics::DirectX::{DirectXAlphaMode, DirectXPixelFormat};
use windows::System::DispatcherQueueController;
use windows::UI::Composition::Desktop::DesktopWindowTarget;
use windows::UI::Composition::*;
use windows::Win32::Foundation::*;
use windows::Win32::Graphics::Direct2D::Common::*;
use windows::Win32::Graphics::Direct2D::*;
use windows::Win32::Graphics::DirectWrite::*;
use windows::Win32::Graphics::Dwm::*;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM;
use windows::Win32::Graphics::Dxgi::IDXGIDevice;
use windows::Win32::Graphics::Gdi::*;
use windows::Win32::System::Com::*;
use windows::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
use windows::Win32::System::SystemInformation::GetTickCount;
use windows::Win32::System::Threading::{GetCurrentThreadId, INFINITE};
use windows::Win32::System::WinRT::Composition::*;
use windows::Win32::System::WinRT::*;
use windows::Win32::UI::Controls::WM_MOUSELEAVE;
use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI};
use windows::Win32::UI::Input::KeyboardAndMouse::*;
use windows::Win32::UI::Shell::Common::ITEMIDLIST;
use windows::Win32::UI::Shell::*;
use windows::Win32::UI::WindowsAndMessaging::*;
use crate::*;
// ---------------------------------------------------------------------------- interface (context_menu.h)
#[derive(Clone, Default, Debug)]
pub struct Dot {
pub id: i32,
/// 0xRRGGBB
pub rgb: u32,
/// marcada (✓)
pub on: bool,
}
/// amostra "Automática" (metade preta, metade branca)
pub const SWATCH_AUTO: u32 = 0xFE000000;
#[derive(Clone, Default, Debug)]
pub struct Item {
pub label: String,
pub id: i32,
pub checked: bool,
pub disabled: bool,
pub separator: bool,
/// atalho mostrado à direita, cinza (ex.: "Ctrl+C")
pub shortcut: String,
pub sub: Vec<Item>,
/// ícone à esquerda (glifo da Segoe Fluent Icons), como os símbolos do menu do Tahoe
pub icon: u16,
/// não vazio: a linha é a fileira de bolinhas (sem texto)
pub dots: Vec<Dot>,
/// amostra de cor à esquerda do nome: 0xFFRRGGBB; SWATCH_AUTO = "Automática"; 0 = nenhuma
pub swatch: u32,
/// imagem na coluna do ícone: img x img pixels BGRA pré-multiplicados, desenhada em 16 pt
pub img_px: Vec<u8>,
pub img: u32,
}
impl Item {
pub fn new(label: impl Into<String>, id: i32) -> Self {
Item { label: label.into(), id, ..Default::default() }
}
pub fn sep() -> Self {
Item { separator: true, ..Default::default() }
}
pub fn checked(mut self, c: bool) -> Self {
self.checked = c;
self
}
pub fn disabled(mut self, d: bool) -> Self {
self.disabled = d;
self
}
pub fn shortcut(mut self, s: impl Into<String>) -> Self {
self.shortcut = s.into();
self
}
pub fn sub(mut self, s: Vec<Item>) -> Self {
self.sub = s;
self
}
pub fn icon(mut self, i: u16) -> Self {
self.icon = i;
self
}
}
/// vidro dos menus (o Shell repassa Ajustes > Transparência e Efeitos). alpha: opacidade final da tinta a partir da
/// original (None = sem mudança)
#[derive(Clone, Copy, Default)]
pub struct Glass {
/// Liquid Glass (Tahoe): reflexo e contorno especular
pub liquid: bool,
/// macOS 27 Golden Gate: medidas do menu do macOS 27 e quase sem símbolos
pub golden: bool,
/// Mac OS X Leopard: branco translúcido e destaque azul em degradê de ponta a ponta
pub leopard: bool,
pub alpha: Option<fn(f32) -> f32>,
}
#[derive(Clone, Default, Debug)]
pub struct Resultado {
/// um comando foi escolhido
pub chosen: bool,
/// escolheu Renomear: a janela dona faz a edição no lugar
pub rename: bool,
/// verbo canônico ("copy", "delete", ...) quando a extensão informa
pub verb: String,
pub hr: i32,
/// id do item do app escolhido (extra_next); 0 = nenhum
pub extra: i32,
}
// ---------------------------------------------------------------------------- estado
static LOG: Global<Option<fn(&str)>> = Global::new(None);
/// o app passa a função de log dele (o C++ recebia um FILE*)
pub fn set_log(f: fn(&str)) {
*LOG.get() = Some(f);
}
fn log(s: &str) {
if let Some(f) = LOG.get() {
f(s);
}
}
/// o log do menu, para os módulos vizinhos (modernos)
pub(crate) fn log_pub(s: &str) {
log(s);
}
static FONT: Global<String> = Global::new(String::new());
static INIT: Global<bool> = Global::new(false);
static FADE_MS: AtomicI32 = AtomicI32::new(160);
static DEMO: Global<bool> = Global::new(false);
static GLASS: Global<Glass> = Global::new(Glass { liquid: false, golden: false, leopard: false, alpha: None });
static GLASS_SET: Global<bool> = Global::new(false);
static PLAIN_NEXT: Global<bool> = Global::new(false);
static PLAIN: Global<bool> = Global::new(false);
static ABOVE_NEXT: Global<bool> = Global::new(false);
static ABOVE: Global<bool> = Global::new(false);
static EXTRA_NEXT: Global<Vec<Item>> = Global::new(Vec::new());
static OPEN_TICK: Global<u32> = Global::new(0);
static OPEN_PT: Global<POINT> = Global::new(POINT { x: 0, y: 0 });
/// Uma vez no início (opcional: o primeiro menu chama). demo: abre já com um item destacado (captura de tela).
pub fn init() {
init_with(false, 160);
}
pub fn init_with(demo: bool, fade_ms: i32) {
*DEMO.get() = demo;
FADE_MS.store(fade_ms, Ordering::SeqCst);
ensure_init();
}
fn ensure_init() {
if *INIT.get() {
return;
}
*INIT.get() = true;
// SF Pro só se instalada
let mut font = "Segoe UI".to_string();
unsafe {
let mut fc: Option<IDWriteFontCollection> = None;
if app2d::dw().GetSystemFontCollection(&mut fc, false).is_ok() {
if let Some(fc) = fc {
// issue #283: no tema Mac OS X (Leopard), Lucida (a do Windows: Lucida Sans Unicode)
let primeira = if crate::semaforo::leopard() { "Lucida Sans Unicode" } else { "SF Pro Text" };
for f in [primeira, "SF Pro Text", "Inter", "Segoe UI Variable Text", "Segoe UI"] {
let (mut idx, mut ex) = (0u32, BOOL(0));
if fc.FindFamilyName(pc(&wz(f)), &mut idx, &mut ex).is_ok() && ex.as_bool() {
font = f.to_string();
break;
}
}
}
}
let hi: HINSTANCE = GetModuleHandleW(None).map(|m| m.into()).unwrap_or_default();
let mut wc = WNDCLASSEXW { cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32, lpfnWndProc: Some(popup_proc), hInstance: hi, hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), lpszClassName: w!("MenuTestePopup"), style: CS_DROPSHADOW, ..Default::default() };
RegisterClassExW(&wc);
wc.lpszClassName = w!("MenuTahoePopup");
wc.style = WNDCLASS_STYLES(0);
RegisterClassExW(&wc);
}
*FONT.get() = font;
}
pub fn set_glass(g: Glass) {
*GLASS.get() = g;
*GLASS_SET.get() = true;
}
/// o próximo menu sai sem ícones automáticos (o menu do Dock, que no Mac não tem)
pub fn plain_next() {
*PLAIN_NEXT.get() = true;
}
/// o próximo menu abre para cima, centrado: o ponto passado é o meio da borda de baixo (o menu do Dock, como no Mac)
pub fn above_next() {
*ABOVE_NEXT.get() = true;
}
/// o próximo `show` ganha estes itens do app logo após o primeiro grupo; escolhido um deles, `show` devolve
/// chosen = true e extra = id, sem executar nada
pub fn extra_next(items: Vec<Item>) {
*EXTRA_NEXT.get() = items;
}
// ---------------------------------------------------------------------------- tema (Tahoe, Golden Gate, Leopard)
static FILE_THEME: Mutex<(u32, bool, bool, bool)> = Mutex::new((0, false, false, false));
/// Tema Tahoe ligado (liquid_glass=1 no ajustes.txt). O Shell avisa pelo set_glass; os outros apps leem o arquivo, no
/// máximo a cada 2 s.
fn tahoe() -> bool {
if *GLASS_SET.get() {
return GLASS.get().liquid;
}
let mut t = FILE_THEME.lock().unwrap();
let now = unsafe { GetTickCount() };
if t.0 != 0 && now.wrapping_sub(t.0) < 2000 {
return t.1;
}
t.0 = now | 1;
let m = ajustes::ler_padrao();
if let Some(v) = m.get("liquid_glass") {
t.1 = v == "1";
}
if let Some(v) = m.get("golden_gate") {
t.2 = v == "1";
}
if let Some(v) = m.get("leopard") {
t.3 = v == "1";
}
t.1
}
/// macOS 27 Golden Gate: linhas de 24, separador de 11, 5,5 de folga e de recuo do destaque, destaque com canto 7, menu
/// com canto 11, texto a 16 da borda (41 com símbolo) e símbolo só em Ajustes…
fn golden() -> bool {
let t = tahoe();
t && if *GLASS_SET.get() { GLASS.get().golden } else { FILE_THEME.lock().unwrap().2 }
}
/// Mac OS X Leopard (sem o Liquid Glass): menus brancos translúcidos e o item escolhido num degradê azul
fn leopard() -> bool {
let t = tahoe();
!t && if *GLASS_SET.get() { GLASS.get().leopard } else { FILE_THEME.lock().unwrap().3 }
}
fn golden_icon(l: &str) -> bool {
["Ajustes", "Settings", "System Settings", "Preferências", "Preferences", "Sobre Este", "About This", "App Store", "Microsoft Store"].iter().any(|k| l.starts_with(k))
}
/// Ícone do Tahoe (glifo da Segoe Fluent Icons) pelo nome do item, para os menus que não escolhem os seus; 0 = nenhum
pub fn auto_icon(label: &str) -> u16 {
let s = label.to_lowercase();
let has = |k: &str| s.contains(k);
let starts = |k: &str| s.starts_with(k);
if has("nova aba") || has("new tab") {
return 0xE8A7;
}
if has("nova janela") || has("new window") {
return 0xE78B;
}
if has("todas as janelas") || has("all windows") || has("mission control") {
return 0xE7C4;
}
if has("iniciar sessão") || has("login") || has("startup") {
return 0xE7E8;
}
if has("nova pasta") || has("new folder") {
return 0xE8F4;
}
if starts("abrir com") || starts("open with") {
return 0xE7AC;
}
if has("mostrar no finder") || has("mostrar na pasta") || has("abrir local") || has("show in") {
return 0xE838;
}
if starts("abrir") || starts("open") {
return 0xE8E5;
}
if has("lixo") || has("excluir") || has("apagar") || has("delete") || has("trash") {
return 0xE74D;
}
if has("remover do dock") || has("desafixar") {
return 0xE77A;
}
if has("manter no dock") || has("fixar") {
return 0xE718;
}
if starts("sobre este") || starts("about this") {
return 0xE7F8; // notebook (menu da Apple do macOS 27)
}
if has("app store") || has("microsoft store") {
return 0xE719; // sacola da loja
}
if has("informaç") || has("propriedades") || has("properties") || starts("sobre") {
return 0xE946;
}
if has("renomear") || has("rename") {
return 0xE8AC;
}
if has("comprimir") || has("compactar") || has("compress") || has("zip") {
return 0xF012;
}
if has("duplicar") || has("duplicate") {
return 0xF413;
}
if has("atalho") || has("alias") || has("shortcut") {
return 0xE71B;
}
if has("visualização rápida") || has("quick look") {
return 0xE890;
}
if starts("recortar") || starts("cut") {
return 0xE8C6;
}
if starts("copiar") || starts("copy") {
return 0xE8C8;
}
if starts("colar") || starts("paste") {
return 0xE77F;
}
if has("compartilhar") || has("share") {
return 0xE72D;
}
if has("etiqueta") || has("tag") {
return 0xE8EC;
}
if has("ações rápidas") || has("mais ações") || has("quick actions") {
return 0xE945;
}
if has("ordenar") || has("sort") {
return 0xE8CB;
}
if has("terminal") || has("prompt") || has("powershell") {
return 0xE756;
}
if has("administrador") || has("admin") {
return 0xEA18;
}
if has("papel de parede") || has("wallpaper") || has("fundo da área") {
return 0xE91B;
}
if has("configurações de tela") || has("exibição") || has("display") {
return 0xE7F4;
}
if has("personalizar") || has("personalize") || has("aparência") {
return 0xE771;
}
if has("ajustes") || has("configura") || has("preferências") || has("settings") || has("opções") {
return 0xE713;
}
if starts("encerrar") || starts("sair") || starts("quit") || has("forçar") {
return 0xE7E8;
}
if starts("fechar") || starts("close") {
return 0xE8BB;
}
if starts("ocultar") || starts("hide") {
return 0xED1A;
}
if starts("minimizar") || starts("minimize") {
return 0xE921;
}
if has("atualizar") || has("recarregar") || has("refresh") || has("reload") {
return 0xE72C;
}
if starts("desfazer") || starts("undo") {
return 0xE7A7;
}
if starts("refazer") || starts("redo") {
return 0xE7A6;
}
if has("selecionar tudo") || has("select all") {
return 0xE8B3;
}
if has("buscar") || has("procurar") || has("pesquisar") || has("search") || has("find") {
return 0xE721;
}
if has("imprimir") || has("print") {
return 0xE749;
}
if starts("salvar") || starts("save") {
return 0xE74E;
}
if starts("editar") || starts("edit") {
return 0xE70F;
}
if starts("executar") || starts("run") {
return 0xE768;
}
if starts("enviar para") || starts("send to") {
return 0xE724;
}
if starts("novo") || starts("nova") || starts("new") {
return 0xE710;
}
if has("todas as opções") || has("show more") {
return 0xE712;
}
// o menu completo do Windows (Shift+clique), em inglês e das extensões
if has("pin to") || has("fixar") {
return 0xE718;
}
if has("unpin") {
return 0xE77A;
}
if has("give access") || has("conceder acesso") || has("acesso") {
return 0xE72D;
}
if has("previous versions") || has("versões anteriores") {
return 0xE81C;
}
if has("7-zip") || has("winrar") || has("extract") || has("extrair") {
return 0xF012;
}
if has("git") || has("visual studio") || has("code") {
return 0xE943;
}
if has("vlc") || has("reprodu") || has("play") || has("media") {
return 0xE768;
}
if has("scan") || has("defender") || has("malware") || has("verificar") {
return 0xEA18;
}
if has("ownership") || has("permiss") {
return 0xE72E;
}
if has("linux") || has("shell") {
return 0xE756;
}
if has("browse") || has("wiztree") || has("analy") {
return 0xE721;
}
if has("mesa") || has("desktop") {
return 0xE7F4;
}
0
}
// ---------------------------------------------------------------------------- menu do shell (IContextMenu)
const ID_FIRST: u32 = 1;
const ID_LAST: u32 = 0x7FFF;
struct ShellMenu {
cm: IContextMenu,
hmenu: HMENU,
}
impl Drop for ShellMenu {
fn drop(&mut self) {
unsafe {
let _ = DestroyMenu(self.hmenu);
}
}
}
/// menu cujas mensagens WM_INITMENUPOPUP etc. vão para a extensão
static ACTIVE: Global<Option<IContextMenu>> = Global::new(None);
fn forward_menu_msg(m: u32, w_: WPARAM, l: LPARAM) -> Option<LRESULT> {
let cm = ACTIVE.get().clone()?;
unsafe {
if let Ok(c3) = cm.cast::<IContextMenu3>() {
let mut r = LRESULT(0);
return c3.HandleMenuMsg2(m, w_, l, Some(&mut r)).is_ok().then_some(r);
}
if let Ok(c2) = cm.cast::<IContextMenu2>() {
return c2.HandleMenuMsg(m, w_, l).is_ok().then_some(LRESULT(0));
}
}
None
}
/// A janela dona repassa WM_INITMENUPOPUP, WM_DRAWITEM, WM_MEASUREITEM e WM_MENUCHAR; Some = a extensão tratou
pub fn forward_owner_msg(m: u32, w_: WPARAM, l: LPARAM) -> Option<LRESULT> {
let r = forward_menu_msg(m, w_, l)?;
if m == WM_DRAWITEM || m == WM_MEASUREITEM {
return Some(LRESULT(1));
}
Some(r)
}
unsafe fn pidl(p: &str) -> Option<*mut ITEMIDLIST> {
let w_ = wz(p);
let mut id: *mut ITEMIDLIST = std::ptr::null_mut();
SHParseDisplayName(pc(&w_), None, &mut id, 0, None).ok()?;
Some(id)
}
/// objeto de interface do shell para vários itens da mesma pasta (IDataObject para arrastar, IDropTarget para soltar...)
pub fn get_ui_object<T: Interface>(owner: HWND, paths: &[String]) -> Result<T> {
if paths.is_empty() {
return Err(E_INVALIDARG.into());
}
unsafe {
let mut abs = Vec::new();
let mut res: Result<T> = Err(E_FAIL.into());
for p in paths {
match pidl(p) {
Some(id) => abs.push(id),
None => break,
}
}
if abs.len() == paths.len() {
let mut child: *mut ITEMIDLIST = std::ptr::null_mut();
if let Ok(parent) = SHBindToParent::<IShellFolder>(abs[0], Some(&mut child as *mut _ as *mut *mut ITEMIDLIST)) {
let kids: Vec<*const ITEMIDLIST> = abs.iter().map(|a| ILFindLastID(*a) as *const ITEMIDLIST).collect();
res = parent.GetUIObjectOf::<_, T>(owner, &kids, None);
}
}
for a in &abs {
CoTaskMemFree(Some(*a as *const _));
}
res
}
}
unsafe fn background_menu(owner: HWND, folder: &str) -> Result<IContextMenu> {
let id = pidl(folder).ok_or(Error::from(E_FAIL))?;
let sf: Result<IShellFolder> = SHBindToObject(None, id, None);
CoTaskMemFree(Some(id as *const _));
sf?.CreateViewObject(owner)
}
fn load_shell_menu(owner: HWND, folder: &str, paths: &[String], flags: u32) -> Option<ShellMenu> {
unsafe {
let cm: IContextMenu = match if paths.is_empty() { background_menu(owner, folder) } else { get_ui_object(owner, paths) } {
Ok(c) => c,
Err(e) => {
log(&format!("erro: IContextMenu 0x{:08X} para {}", e.code().0 as u32, paths.first().map(|s| s.as_str()).unwrap_or(folder)));
return None;
}
};
let hmenu = CreatePopupMenu().ok()?;
let sm = ShellMenu { cm, hmenu };
if let Err(e) = sm.cm.QueryContextMenu(sm.hmenu, 0, ID_FIRST, ID_LAST, flags) {
log(&format!("erro: QueryContextMenu 0x{:08X}", e.code().0 as u32));
return None;
}
Some(sm)
}
}
/// os itens do menu moderno (issue #559) usam special a partir daqui
const MODERNO: i32 = 1_000_000;
fn verb_of(cm: &IContextMenu, cmd: u32) -> String {
if !(ID_FIRST..=ID_LAST).contains(&cmd) {
return String::new();
}
let mut v = [0u16; 256];
unsafe {
if cm.GetCommandString((cmd - ID_FIRST) as usize, GCS_VERBW, None, PSTR(v.as_mut_ptr() as *mut u8), 255).is_ok() {
return from_w(&v).to_lowercase();
}
}
String::new()
}
// ---------------------------------------------------------------------------- modelo do menu próprio
#[derive(Clone, Default)]
struct MItem {
label: String,
verb: String,
shortcut: String,
cmd: u32,
sep: bool,
header: bool,
disabled: bool,
checked: bool,
/// 1 = abrir o menu clássico do Windows; >= 100: item do app (extra_next)
special: i32,
sub: Vec<MItem>,
icon: u16,
swatch: u32,
img_px: Vec<u8>,
img: u32,
dots: Vec<Dot>,
/// submenu original, relido ao abrir (extensões que completam depois)
src: isize,
}
/// tem submenu, mesmo que ainda não lido (extensão que preenche depois)
fn has_sub(m: &MItem) -> bool {
!m.sub.is_empty() || m.src != 0
}
fn msep() -> MItem {
MItem { sep: true, ..Default::default() }
}
fn header(s: &str) -> MItem {
MItem { header: true, label: s.to_string(), ..Default::default() }
}
/// remove aceleradores (&) e o atalho depois do Tab: no macOS o menu de contexto não mostra atalhos
fn clean_label(s: &str) -> String {
let mut r = String::new();
let mut it = s.chars().peekable();
while let Some(c) = it.next() {
if c == '\t' {
break;
}
if c == '&' {
if it.peek() == Some(&'&') {
r.push('&');
it.next();
}
continue;
}
r.push(c);
}
r.trim_matches(' ').to_string()
}
/// envia WM_INITMENUPOPUP a todos os submenus ("Enviar para", "Abrir com" só se preenchem assim)
unsafe fn init_submenus(h: HMENU, depth: i32, all: &mut Vec<HMENU>) {
let n = GetMenuItemCount(h);
for i in 0..n {
let sub = GetSubMenu(h, i);
if sub.0.is_null() {
continue;
}
let _ = forward_menu_msg(WM_INITMENUPOPUP, WPARAM(sub.0 as usize), makelparam(i, 0));
all.push(sub);
if depth < 4 {
init_submenus(sub, depth + 1, all);
}
}
}
fn read_menu(cm: &IContextMenu, h: HMENU, depth: i32, no_text: &mut i32) -> Vec<MItem> {
let t0 = unsafe { GetTickCount() };
let mut subs = Vec::new();
unsafe { init_submenus(h, depth, &mut subs) };
// sem esperar: os submenus são relidos quando abrem (open_sub); a espera atrasava cada menu ~150 ms
let out = read_menu_items(cm, h, depth, no_text);
log(&format!(" leitura do menu: {} ms ({} submenus)", unsafe { GetTickCount() }.wrapping_sub(t0), subs.len()));
out
}
fn read_menu_items(cm: &IContextMenu, h: HMENU, depth: i32, no_text: &mut i32) -> Vec<MItem> {
let mut out = Vec::new();
unsafe {
let n = GetMenuItemCount(h);
for i in 0..n {
let mut buf = [0u16; 512];
let mut mi = MENUITEMINFOW { cbSize: std::mem::size_of::<MENUITEMINFOW>() as u32, fMask: MIIM_FTYPE | MIIM_STATE | MIIM_ID | MIIM_SUBMENU | MIIM_STRING, dwTypeData: PWSTR(buf.as_mut_ptr()), cch: 511, ..Default::default() };
if GetMenuItemInfoW(h, i as u32, true, &mut mi).is_err() {
continue;
}
if mi.fType.0 & MFT_SEPARATOR.0 != 0 {
out.push(msep());
continue;
}
let owner_draw = mi.fType.0 & MFT_OWNERDRAW.0 != 0;
let mut it = MItem { label: if owner_draw { String::new() } else { clean_label(&from_w(&buf)) }, disabled: mi.fState.0 & (MFS_DISABLED.0 | MFS_GRAYED.0) != 0, checked: mi.fState.0 & MFS_CHECKED.0 != 0, ..Default::default() };
if !mi.hSubMenu.0.is_null() {
it.src = mi.hSubMenu.0 as isize;
if depth < 4 {
it.sub = read_menu_items(cm, mi.hSubMenu, depth + 1, no_text);
}
// some só o submenu cujos itens legíveis estão todos desativados ("Retrieving libraries..."); sem
// itens legíveis ("Enviar para" ainda com o item provisório) ele fica, e é relido quando abre
let readable = it.sub.iter().any(|c| !c.sep);
let enabled = it.sub.iter().any(|c| !c.sep && !c.disabled);
if if readable { !enabled } else { GetMenuItemCount(mi.hSubMenu) == 0 } {
continue;
}
} else {
it.cmd = mi.wID;
it.verb = verb_of(cm, it.cmd);
}
if it.label.is_empty() && it.cmd != 0 {
// issue #559: extensões que desenham o próprio item (antivírus, editores) não têm texto legível; o
// texto de ajuda delas costuma ser o nome do comando
let mut v = [0u16; 256];
if (ID_FIRST..=ID_LAST).contains(&it.cmd) && cm.GetCommandString((it.cmd - ID_FIRST) as usize, GCS_HELPTEXTW, None, PSTR(v.as_mut_ptr() as *mut u8), 255).is_ok() {
let t = clean_label(&from_w(&v));
if !t.is_empty() && t.chars().count() <= 60 {
log(&format!(" item sem texto (id={}): usando o texto de ajuda \"{t}\"", it.cmd));
it.label = t;
}
}
}
if it.label.is_empty() {
*no_text += 1;
log(&format!(" aviso: item sem texto (id={} verbo={} ownerdraw={})", it.cmd, it.verb, owner_draw as i32));
continue;
}
out.push(it);
}
}
out
}
fn clean_seps(v: &mut Vec<MItem>) {
let mut r: Vec<MItem> = Vec::new();
for m in v.drain(..) {
if m.sep && r.last().is_none_or(|l| l.sep || l.header) {
continue;
}
r.push(m);
}
while r.last().is_some_and(|l| l.sep || l.header) {
r.pop();
}
*v = r;
}
/// submenus de um nível só: níveis mais fundos viram seções com cabeçalho
fn flatten_into(dst: &mut Vec<MItem>, src: &[MItem]) {
for m in src {
if !m.sub.is_empty() {
dst.push(msep());
dst.push(header(&m.label));
flatten_into(dst, &m.sub);
dst.push(msep());
} else {
dst.push(m.clone());
}
}
}
fn flatten(src: &[MItem]) -> Vec<MItem> {
let mut r = Vec::new();
flatten_into(&mut r, src);
clean_seps(&mut r);
r
}
fn starts_with(s: &str, p: &str) -> bool {
s.to_lowercase().starts_with(&p.to_lowercase())
}
const G_OPEN: usize = 0;
const G_ORG: usize = 1;
const G_MORE: usize = 2;
fn classify(m: &MItem) -> (usize, i32) {
const OPEN: [(&str, i32); 11] = [("open", 0), ("opennewwindow", 1), ("opennewtab", 1), ("opennewprocess", 1), ("explore", 2), ("runas", 3), ("openas", 4), ("edit", 5), ("print", 6), ("play", 7), ("preview", 8)];
const ORG: [(&str, i32); 9] = [("cut", 0), ("copy", 1), ("paste", 2), ("pastelink", 3), ("copyaspath", 4), ("link", 5), ("rename", 6), ("delete", 8), ("properties", 9)];
if let Some(v) = OPEN.iter().find(|v| m.verb == v.0) {
return (G_OPEN, v.1);
}
if let Some(v) = ORG.iter().find(|v| m.verb == v.0) {
return (G_ORG, v.1);
}
if has_sub(m) {
if starts_with(&m.label, "Novo") || starts_with(&m.label, "New") {
return (G_OPEN, -1);
}
if starts_with(&m.label, "Abrir com") || starts_with(&m.label, "Open with") {
return (G_OPEN, 4);
}
if starts_with(&m.label, "Enviar para") || starts_with(&m.label, "Send to") {
return (G_ORG, 7);
}
}
(G_MORE, 50)
}
/// reorganiza no estilo macOS: no máximo 3 grupos (abrir / organizar / extras)
fn organize(raw: &[MItem]) -> Vec<MItem> {
let mut rs: Vec<(MItem, usize, i32)> = Vec::new();
for m in raw {
if m.sep || m.header {
continue;
}
let mut it = m.clone();
if !it.sub.is_empty() {
it.sub = flatten(&it.sub);
}
let (g, rank) = classify(&it);
rs.push((it, g, rank));
}
rs.sort_by(|a, b| (a.1, a.2).cmp(&(b.1, b.2))); // estável
let mut groups: [Vec<MItem>; 3] = [Vec::new(), Vec::new(), Vec::new()];
for (it, g, _) in rs {
groups[g].push(it);
}
if groups[G_MORE].len() > 6 {
// muitos extras: mantém até 4 submenus (7-Zip, Git...) e guarda o resto em "Mais ações"
let (mut keep, mut rest) = (Vec::new(), Vec::new());
for m in groups[G_MORE].drain(..) {
if has_sub(&m) && keep.len() < 4 {
keep.push(m);
} else if !m.sub.is_empty() {
rest.push(msep());
rest.push(header(&m.label));
rest.extend(m.sub.iter().cloned());
rest.push(msep());
} else {
rest.push(m);
}
}
clean_seps(&mut rest);
keep.push(MItem { label: tr("Mais ações"), sub: rest, ..Default::default() });
groups[G_MORE] = keep;
}
groups[G_ORG].push(MItem { label: tr("Mostrar todas as opções"), special: 1, ..Default::default() });
let mut out = Vec::new();
for g in groups {
if g.is_empty() {
continue;
}
if !out.is_empty() {
out.push(msep());
}
out.extend(g);
}
out
}
fn dump_tree(v: &[MItem], d: usize) {
let pad = " ".repeat(d * 2 + 2);
for m in v {
if m.sep {
log(&format!("{pad}----"));
} else if m.header {
log(&format!("{pad}[{}]", m.label));
} else {
log(&format!("{pad}{}{}{} {{verbo={} id={}}}", m.label, if has_sub(m) { " ›" } else { "" }, if m.disabled { " (desativado)" } else { "" }, m.verb, m.cmd));
}
if !m.sub.is_empty() {
dump_tree(&m.sub, d + 1);
}
}
}
/// lista completa na ordem do Windows, já no visual próprio: só achata submenus para um nível
fn full_list(raw: &[MItem]) -> Vec<MItem> {
let mut out: Vec<MItem> = raw
.iter()
.map(|m| {
let mut x = m.clone();
if !x.sub.is_empty() {
x.sub = flatten(&x.sub);
}
x
})
.collect();
clean_seps(&mut out);
out
}
// ---------------------------------------------------------------------------- janela do menu
const PAD_Y: f32 = 5.0;
const INSET: f32 = 5.0;
const ITEM_H: f32 = 22.0;
const SEP_H: f32 = 9.0;
const HDR_H: f32 = 20.0;
const FONT_SZ: f32 = 13.0;
const HDR_FONT: f32 = 11.0;
const RADIUS: f32 = 4.0;
const MIN_W: f32 = 190.0;
const MAX_W: f32 = 380.0;
const DOT_D: f32 = 12.0;
const DOT_PITCH: f32 = 20.0;
const DOT_ROW_H: f32 = 22.0;
const ICON_CX: f32 = 23.0;
const ICON_TEXT_L: f32 = 34.0;
const T_DYING: usize = 3;
/// Medidas do menu do Tahoe (guia macOS26-Theme-Reference, seção 31): item de 24, separador de 11, 5 de folga, texto em
/// x 14 sem ícones e em x 33 com a coluna de ícones, destaque em cápsula de raio ~8
fn sep_h() -> f32 {
if tahoe() {
11.0
} else {
SEP_H
}
}
fn item_h() -> f32 {
if tahoe() {
24.0
} else {
ITEM_H
}
}
fn pad_y() -> f32 {
if golden() {
5.5
} else if tahoe() {
5.0
} else {
PAD_Y
}
}
fn inset() -> f32 {
if golden() {
5.5
} else {
INSET
}
}
fn icon_cx() -> f32 {
if golden() {
23.0
} else if tahoe() {
22.5
} else {
ICON_CX
}
}
fn hot_r() -> f32 {
if golden() {
7.0
} else if tahoe() {
8.0
} else {
RADIUS
}
}
/// raio do canto do menu (macOS 27: 11; Tahoe: 12)
fn card_r() -> f32 {
if golden() {
11.0
} else {
12.0
}
}
fn selectable(m: &MItem) -> bool {
!m.sep && !m.header && !m.disabled && m.dots.is_empty()
}
#[derive(Default)]
struct Level {
hwnd: HWND,
items: *mut Vec<MItem>,
rects: Vec<RectF>,
hover: i32,
open_child: i32,
scale: f32,
/// margens do texto em pixels
text_l: f32,
text_r: f32,
/// bolinha sob o mouse (fileira de etiquetas)
dot_hover: i32,
rt: Option<ID2D1DCRenderTarget>,
/// desenhamos numa DIB de 32 bits e copiamos para a janela (alfa preservado)
mem: HDC,
dib: HBITMAP,
tf: Option<IDWriteTextFormat>,
tf_hdr: Option<IDWriteTextFormat>,
tf_icon: Option<IDWriteTextFormat>,
// composição: a janela tem uma margem em volta para a sombra; o menu é um cartão recortado arredondado com o
// desfoque do que está atrás e o desenho por cima
comp: bool,
margin: i32,
mw: f32,
mh: f32,
target: Option<DesktopWindowTarget>,
root: Option<ContainerVisual>,
content_s: Option<CompositionDrawingSurface>,
shadow_s: Option<CompositionDrawingSurface>,
back_v: Option<SpriteVisual>,
/// o Shell pôs o Liquid Glass do Dock atrás deste menu (menu_vidro=1): sem desfoque próprio
ext: bool,
}
impl Level {
fn items(&self) -> &'static mut Vec<MItem> {
unsafe { &mut *self.items }
}
}
#[derive(Default)]
struct Session {
levels: Vec<Level>,
owner: HWND,
done: bool,
dark: bool,
result: *mut MItem,
pend_level: i32,
pend_item: i32,
/// início do show (medição)
t_show: u32,
}
static SES: Global<Option<Session>> = Global::new(None);
fn ses() -> Option<&'static mut Session> {
SES.get().as_mut()
}
static DYING: Global<Vec<Level>> = Global::new(Vec::new());
// ---- composição do Windows
struct Comp {
dq: Option<DispatcherQueueController>,
wc: Compositor,
gfx: CompositionGraphicsDevice,
}
static COMP: Global<Option<Comp>> = Global::new(None);
static COMP_TRIED: Global<bool> = Global::new(false);
struct EnviaD2d(ID2D1Device);
unsafe impl Send for EnviaD2d {}
/// 0 nada, 1 criando, 2 pronto, 3 falhou: o dispositivo D3D/D2D do vidro numa thread (o D3D11CreateDevice passa pelo
/// driver e com o disco ocupado parou a interface do Shell 17,6 s: issue #32)
static PRE_ESTADO: AtomicI32 = AtomicI32::new(0);
static PRE_D2D: Mutex<Option<EnviaD2d>> = Mutex::new(None);
fn criar_d2d_device() -> Option<ID2D1Device> {
let d3d = gpu::criar_na_tela()?;
let dx: IDXGIDevice = d3d.cast().ok()?;
unsafe {
let f1: ID2D1Factory1 = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, None).ok()?;
f1.CreateDevice(&dx).ok()
}
}
fn prepara_dispositivo() {
if PRE_ESTADO.swap(1, Ordering::SeqCst) != 0 {
return;
}
std::thread::spawn(|| {
let d = criar_d2d_device();
let ok = d.is_some();
*PRE_D2D.lock().unwrap() = d.map(EnviaD2d);
PRE_ESTADO.store(if ok { 2 } else { 3 }, Ordering::SeqCst);
});
}
fn comp_ready() -> bool {
if *COMP_TRIED.get() {
return COMP.get().is_some();
}
*COMP_TRIED.get() = true;
let r = (|| -> Result<Comp> {
let mut dq = None;
if windows::System::DispatcherQueue::GetForCurrentThread().is_err() {
let o = DispatcherQueueOptions { dwSize: std::mem::size_of::<DispatcherQueueOptions>() as u32, threadType: DQTYPE_THREAD_CURRENT, apartmentType: DQTAT_COM_NONE };
dq = Some(unsafe { CreateDispatcherQueueController(o)? });
}
let wc = Compositor::new()?;
let pre = if PRE_ESTADO.load(Ordering::SeqCst) == 2 { PRE_D2D.lock().unwrap().take().map(|x| x.0) } else { None }; // veio pronto da thread
let d2d = match pre {
Some(d) => d,
None => criar_d2d_device().ok_or(Error::from(E_FAIL))?,
};
let ci: ICompositorInterop = wc.cast()?;
let gfx = unsafe { ci.CreateGraphicsDevice(&d2d)? };
Ok(Comp { dq, wc, gfx })
})();
match r {
Ok(c) => {
*COMP.get() = Some(c);
true
}
Err(_) => {
log("menu: composição indisponível; cantos do Windows");
false
}
}
}
/// espera ms processando o que não é teclado/mouse (a composição só desenha com a fila andando)
fn pump_for(ms: u32) {
unsafe {
let t0 = GetTickCount();
loop {
let el = GetTickCount().wrapping_sub(t0);
if el >= ms {
break;
}
MsgWaitForMultipleObjects(None, false, ms - el, QS_ALLINPUT);
let mut msg = MSG::default();
while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
if msg.message == WM_QUIT {
PostQuitMessage(msg.wParam.0 as i32);
return;
}
if (WM_KEYFIRST..=WM_KEYLAST).contains(&msg.message) || (WM_MOUSEFIRST..=WM_MOUSELAST).contains(&msg.message) {
continue;
}
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
}
}
fn v2(x: f32, y: f32) -> Vector2 {
Vector2 { X: x, Y: y }
}
fn dark_session() -> bool {
ses().is_some_and(|s| s.dark)
}
/// sombra do cartão: o retângulo arredondado borrado, um pouco para baixo (como a do menu do Mac)
fn draw_shadow(l: &Level) {
let Some(s) = &l.shadow_s else { return };
let Ok(si) = s.cast::<ICompositionDrawingSurfaceInterop>() else { return };
unsafe {
let mut off = POINT::default();
let Ok(dc) = si.BeginDraw::<ID2D1DeviceContext>(None, &mut off) else { return };
let (sc, m) = (l.scale, l.margin as f32);
let r = card_r() * sc;
dc.SetTransform(&mat::trans(off.x as f32, off.y as f32));
dc.PushAxisAlignedClip(&rf(0.0, 0.0, l.mw + 2.0 * m, l.mh + 2.0 * m), D2D1_ANTIALIAS_MODE_ALIASED);
dc.Clear(Some(&col(0.0, 0.0, 0.0, 0.0)));
let orig = dc.GetTarget().ok();
if let Ok(cl) = dc.CreateCommandList() {
dc.SetTarget(&cl);
// Tahoe (guia, seções 51 e 61): escuro preto 29 %, σ 7,5, +4; claro 39 %, σ 6,5, +2
let light = !dark_session();
let dy = if tahoe() {
if light {
2.0
} else {
4.0
}
} else {
5.0
};
if let Ok(b) = dc.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None) {
dc.FillRoundedRectangle(&rr(rf(m, m + dy * sc, m + l.mw, m + l.mh + dy * sc), r, r), &b);
}
let _ = cl.Close();
dc.SetTarget(orig.as_ref());
if let Ok(fx) = dc.CreateEffect(&CLSID_D2D1Shadow) {
fx.SetInput(0, &cl, true);
let sd = (if tahoe() {
if light {
6.5f32
} else {
7.5
}
} else {
9.0
}) * sc;
let _ = fx.SetValue(0, D2D1_PROPERTY_TYPE_FLOAT, &sd.to_le_bytes());
let a = if tahoe() {
if light {
0.39f32
} else {
0.29
}
} else {
0.30
};
let c4: Vec<u8> = [0f32, 0.0, 0.0, a].iter().flat_map(|f| f.to_le_bytes()).collect();
let _ = fx.SetValue(1, D2D1_PROPERTY_TYPE_VECTOR4, &c4);
if let Ok(img) = fx.GetOutput() {
dc.DrawImage(&img, None, None, D2D1_INTERPOLATION_MODE_LINEAR, D2D1_COMPOSITE_MODE_SOURCE_OVER);
}
}
}
dc.PopAxisAlignedClip();
let _ = si.EndDraw();
}
}
fn setup_comp(l: &mut Level) -> bool {
let Some(c) = COMP.get().as_ref() else { return false };
let r = (|| -> Result<()> {
unsafe {
let on = BOOL(1);
let _ = DwmSetWindowAttribute(l.hwnd, DWMWINDOWATTRIBUTE(17), &on as *const _ as *const _, 4); // DWMWA_USE_HOSTBACKDROPBRUSH
let nc = 1u32;
let _ = DwmSetWindowAttribute(l.hwnd, DWMWINDOWATTRIBUTE(33), &nc as *const _ as *const _, 4); // não arredondar
}
let interop: ICompositorDesktopInterop = c.wc.cast()?;
let target = unsafe { interop.CreateDesktopWindowTarget(l.hwnd, true)? };
let m = l.margin as f32;
let r = card_r() * l.scale;
let root = c.wc.CreateContainerVisual()?;
root.SetSize(v2(l.mw + 2.0 * m, l.mh + 2.0 * m))?;
let shadow_s = c.gfx.CreateDrawingSurface(Size { Width: l.mw + 2.0 * m, Height: l.mh + 2.0 * m }, DirectXPixelFormat::B8G8R8A8UIntNormalized, DirectXAlphaMode::Premultiplied)?;
l.shadow_s = Some(shadow_s.clone());
draw_shadow(l);
let shadow_v = c.wc.CreateSpriteVisual()?;
shadow_v.SetSize(v2(l.mw + 2.0 * m, l.mh + 2.0 * m))?;
shadow_v.SetBrush(&c.wc.CreateSurfaceBrushWithSurface(&shadow_s)?)?;
let card = c.wc.CreateContainerVisual()?;
card.SetOffset(Vector3 { X: m, Y: m, Z: 0.0 })?;
card.SetSize(v2(l.mw, l.mh))?;
let geo = c.wc.CreateRoundedRectangleGeometry()?;
geo.SetSize(v2(l.mw, l.mh))?;
geo.SetCornerRadius(v2(r, r))?;
card.SetClip(&c.wc.CreateGeometricClipWithGeometry(&geo)?)?;
let back = c.wc.CreateSpriteVisual()?; // o que está atrás, desfocado (o vidro)
back.SetSize(v2(l.mw, l.mh))?;
back.SetBrush(&c.wc.CreateHostBackdropBrush()?)?;
let content_s = c.gfx.CreateDrawingSurface(Size { Width: l.mw, Height: l.mh }, DirectXPixelFormat::B8G8R8A8UIntNormalized, DirectXAlphaMode::Premultiplied)?;
let content = c.wc.CreateSpriteVisual()?;
content.SetSize(v2(l.mw, l.mh))?;
content.SetBrush(&c.wc.CreateSurfaceBrushWithSurface(&content_s)?)?;
card.Children()?.InsertAtTop(&back)?;
card.Children()?.InsertAtTop(&content)?;
root.Children()?.InsertAtTop(&shadow_v)?;
root.Children()?.InsertAtTop(&card)?;
target.SetRoot(&root)?;
l.target = Some(target);
l.root = Some(root);
l.content_s = Some(content_s);
l.back_v = Some(back);
Ok(())
})();
r.is_ok()
}
/// retângulo do menu na tela (sem a margem da sombra)
fn menu_rect(l: &Level) -> RECT {
let mut r = RECT::default();
unsafe {
let _ = GetWindowRect(l.hwnd, &mut r);
}
RECT { left: r.left + l.margin, top: r.top + l.margin, right: r.right - l.margin, bottom: r.bottom - l.margin }
}
fn find_level(h: HWND) -> i32 {
ses().and_then(|s| s.levels.iter().position(|l| l.hwnd == h)).map(|i| i as i32).unwrap_or(-1)
}
fn invalidate(l: &Level) {
unsafe {
let _ = InvalidateRect(l.hwnd, None, false);
}
}
fn apply_effects(h: HWND, dark: bool) {
unsafe {
let corner = 2u32; // DWMWCP_ROUND
let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(33), &corner as *const _ as *const _, 4);
let border: u32 = if dark { 0x00484646 } else { 0x00CCC8C8 };
let _ = DwmSetWindowAttribute(h, DWMWINDOWATTRIBUTE(34), &border as *const _ as *const _, 4);
// desfoque acrílico atrás da janela (API não documentada, usada por Seelen UI, YASB etc.)
#[repr(C)]
struct AccentPolicy {
state: i32,
flags: i32,
gradient: u32,
anim: i32,
}
#[repr(C)]
struct WcaData {
attr: i32,
data: *mut core::ffi::c_void,
size: usize,
}
let Ok(u32_) = GetModuleHandleW(w!("user32.dll")) else { return };
let Some(f) = GetProcAddress(u32_, s!("SetWindowCompositionAttribute")) else { return };
let f: unsafe extern "system" fn(HWND, *mut WcaData) -> BOOL = std::mem::transmute(f);
let mut ap = AccentPolicy { state: 4, flags: 0, gradient: if dark { 0x01202020 } else { 0x01F2F2F2 }, anim: 0 };
let mut d = WcaData { attr: 19, data: &mut ap as *mut _ as *mut _, size: std::mem::size_of::<AccentPolicy>() };
let _ = f(h, &mut d);
}
}
fn text_width(tf: &IDWriteTextFormat, s: &str) -> f32 {
unsafe {
let Ok(tl) = app2d::dw().CreateTextLayout(&w(s), tf, 10000.0, 100.0) else { return 0.0 };
let mut tm = DWRITE_TEXT_METRICS::default();
let _ = tl.GetMetrics(&mut tm);
tm.widthIncludingTrailingWhitespace
}
}
fn make_format(size: f32, wt: DWRITE_FONT_WEIGHT) -> Option<IDWriteTextFormat> {
let tf = cjk::format(app2d::dw(), FONT.get(), wt, DWRITE_FONT_STYLE_NORMAL, size, "pt-br")?;
unsafe {
let _ = tf.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
let _ = tf.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
let ell = app2d::dw().CreateEllipsisTrimmingSign(&tf).ok();
let trim = DWRITE_TRIMMING { granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER, delimiter: 0, delimiterCount: 0 };
let _ = tf.SetTrimming(&trim, ell.as_ref());
}
Some(tf)
}
// ---- Liquid Glass do Shell atrás do menu (Ajustes > Transparência e Efeitos > "Menus de vidro", menu_vidro=1): o
// Shell põe uma janela de vidro logo atrás deste menu e o menu tira o desfoque próprio. Protocolo em shell/menus
fn vidro_msg_id() -> u32 {
reg_msg("WacOSMenuVidro")
}
fn vidro_param(l: &Level, code: i32, dark: bool) -> LPARAM {
let mut r = (code & 3) as usize | if dark { 4 } else { 0 } | ((l.margin as usize & 0xFFF) << 4) | (((card_r() * l.scale).round() as usize & 0xFFF) << 16);
r |= (FADE_MS.load(Ordering::SeqCst) as usize & 0xFFF) << 28;
LPARAM(r as isize)
}
fn ask_shell_glass(l: &Level, dark: bool) -> bool {
if !l.comp || !tahoe() {
return false;
}
let Some(sh) = find_window("ShellMensagens") else { return false };
let mut r = 0usize;
unsafe { SendMessageTimeoutW(sh, vidro_msg_id(), WPARAM(l.hwnd.0 as usize), vidro_param(l, 1, dark), SMTO_ABORTIFHUNG, 250, Some(&mut r)).0 != 0 && r == 1 }
}
fn tell_shell_glass(l: &Level, code: i32) {
if !l.ext {
return;
}
let Some(sh) = find_window("ShellMensagens") else { return };
unsafe {
// menu do próprio Shell (Dock, mesa): na hora, sem fila (postado, o vidro ficava na tela sem o menu enquanto a
// ação escolhida rodava nesta mesma thread)
if GetWindowThreadProcessId(sh, None) == GetCurrentThreadId() {
SendMessageW(sh, vidro_msg_id(), WPARAM(l.hwnd.0 as usize), vidro_param(l, code, false));
} else {
let _ = PostMessageW(sh, vidro_msg_id(), WPARAM(l.hwnd.0 as usize), vidro_param(l, code, false));
}
}
}
/// medidas do nível: formatos de texto, ícones automáticos do Tahoe, margens do texto e o retângulo de cada linha;
/// devolve a largura e a altura sem a folga de baixo (px)
unsafe fn layout(l: &mut Level, sc: f32) -> (f32, f32) {
l.tf = make_format(FONT_SZ * sc, DWRITE_FONT_WEIGHT_NORMAL);
l.tf_hdr = make_format(HDR_FONT * sc, DWRITE_FONT_WEIGHT_SEMI_BOLD);
let its = l.items();
if tahoe() && !*PLAIN.get() {
for m in its.iter_mut() {
if !m.sep && !m.header && m.icon == 0 && m.img == 0 && m.swatch == 0 && m.dots.is_empty() && (!golden() || golden_icon(&m.label)) {
m.icon = auto_icon(&m.label);
}
}
}
let (mut has_check, mut has_sub_, mut has_icon) = (false, false, false);
let (mut max_w, mut max_short) = (0f32, 0f32);
for m in its.iter() {
has_check |= m.checked;
has_sub_ |= has_sub(m);
has_icon |= m.icon != 0 || m.img != 0 || m.swatch != 0; // a amostra usa a coluna do ícone
if !m.sep {
if let Some(tf) = if m.header { &l.tf_hdr } else { &l.tf } {
max_w = max_w.max(text_width(tf, &m.label));
}
}
if !m.dots.is_empty() {
max_w = max_w.max((m.dots.len() as f32 * DOT_PITCH + 4.0) * sc);
}
if !m.shortcut.is_empty() {
if let Some(tf) = &l.tf {
max_short = max_short.max(text_width(tf, &m.shortcut));
}
}
}
if max_short > 0.0 {
max_w += max_short + 28.0 * sc; // atalhos alinhados à direita, como na barra de menus do Mac
}
if has_icon {
// ícones do Tahoe: coluna de ícones à esquerda, texto depois dela
l.tf_icon = cjk::format(app2d::dw(), "Segoe Fluent Icons", DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, 13.0 * sc, "");
if let Some(t) = &l.tf_icon {
let _ = t.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
let _ = t.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
}
}
l.text_l = (if has_icon {
if golden() {
41.0
} else if tahoe() {
33.0
} else {
ICON_TEXT_L
}
} else if has_check {
26.0
} else if golden() {
16.0
} else if tahoe() {
14.0
} else {
16.0
}) * sc;
l.text_r = (if has_sub_ {
34.0
} else if tahoe() {
14.0
} else {
18.0
}) * sc;
let ww = (l.text_l + max_w.ceil() + 2.0 * sc + l.text_r).clamp(MIN_W * sc, MAX_W * sc);
let mut y = pad_y() * sc;
for m in its.iter() {
let h = (if m.sep {
sep_h()
} else if m.header {
HDR_H
} else if !m.dots.is_empty() {
DOT_ROW_H
} else {
item_h()
}) * sc;
l.rects.push(rf(0.0, y, ww, y + h));
y += h;
}
(ww, y)
}
/// abre um nível. Raiz: no ponteiro. Submenu: ao lado do item pai (parent_win/item_top em pixels de tela)
fn open_level(items: *mut Vec<MItem>, anchor: POINT, parent_win: Option<RECT>, item_top: i32) {
let Some(s) = ses() else { return };
let mut l = Level { items, hover: -1, open_child: -1, dot_hover: -1, ..Default::default() };
unsafe {
let mon = MonitorFromPoint(anchor, MONITOR_DEFAULTTONEAREST);
let (mut dx, mut dy) = (96u32, 96u32);
let _ = GetDpiForMonitor(mon, MDT_EFFECTIVE_DPI, &mut dx, &mut dy);
let sc = dx as f32 / 96.0;
l.scale = sc;
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
let _ = GetMonitorInfoW(mon, &mut mi);
let mut wa = mi.rcWork;
// como no Mac, o menu não passa por cima do Dock: o vidro dele (propriedade "WacOSDockVidro" na janela dos
// ícones) sai da área em que o menu cabe, e um menu aberto perto dele sobe ou anda de lado
if let Some(dk) = find_window("ShellDock") {
let pk = GetPropW(dk, w!("WacOSDockVidro")).0 as usize as u64; // 4 valores de 16 bits (só em 64 bits)
let mut wr = RECT::default();
if IsWindowVisible(dk).as_bool() && pk != 0 && cfg!(target_pointer_width = "64") && GetWindowRect(dk, &mut wr).is_ok() {
let d = RECT { left: wr.left + (pk & 0xFFFF) as i32, top: wr.top + ((pk >> 16) & 0xFFFF) as i32, right: wr.left + ((pk >> 32) & 0xFFFF) as i32, bottom: wr.top + ((pk >> 48) & 0xFFFF) as i32 };
let mut x = RECT::default();
if IntersectRect(&mut x, &d, &mi.rcMonitor).as_bool() && x == d {
let gap = (4.0 * sc) as i32;
// issue #362: menu da barra de menus (raiz logo abaixo do topo da tela) fica embaixo do título, como
// no Mac, por cima do Dock do lado. Andando para o lado do Dock, a maçã abria longe do ícone
let da_barra = parent_win.is_none() && anchor.y - mi.rcMonitor.top < (60.0 * sc) as i32;
if d.right - d.left >= d.bottom - d.top {
if d.top > (mi.rcMonitor.top + mi.rcMonitor.bottom) / 2 {
wa.bottom = wa.bottom.min(d.top - gap);
}
} else if da_barra {
} else if d.left < (mi.rcMonitor.left + mi.rcMonitor.right) / 2 {
wa.left = wa.left.max(d.right + gap);
} else {
wa.right = wa.right.min(d.left - gap);
}
if wa.bottom - wa.top < 200 || wa.right - wa.left < 200 {
wa = mi.rcWork; // não sobra lugar: como antes
}
}
}
}
let (ww, y) = layout(&mut l, sc);
let w_ = ww.ceil() as i32;
let h = ((y + pad_y() * sc).ceil() as i32).min(wa.bottom - wa.top);
let (mut x, mut top);
match parent_win {
None => {
x = anchor.x + 1;
top = anchor.y + 1;
if *ABOVE.get() {
x = anchor.x - w_ / 2;
top = anchor.y - h;
*ABOVE.get() = false;
}
// só o Dock no caminho (caberia na tela sem ele): o menu sobe/anda só o que falta, como no Mac
if x + w_ > wa.right {
x = if x + w_ <= mi.rcWork.right { wa.right - w_ } else { anchor.x - w_ };
}
if top + h > wa.bottom {
top = if top + h <= mi.rcWork.bottom { wa.bottom - h } else { anchor.y - h };
}
}
Some(pw) => {
x = pw.right - (3.0 * sc) as i32;
top = item_top - (pad_y() * sc) as i32;
if x + w_ > wa.right {
x = pw.left - w_ + (3.0 * sc) as i32;
}
if top + h > wa.bottom {
top = wa.bottom - h;
}
}
}
x = x.max(wa.left);
top = top.max(wa.top);
l.comp = comp_ready();
l.margin = if l.comp { (24.0 * sc).ceil() as i32 } else { 0 };
l.mw = w_ as f32;
l.mh = h as f32;
let m = l.margin;
let hi: HINSTANCE = GetModuleHandleW(None).map(|m| m.into()).unwrap_or_default();
let ex = WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | if l.comp { WS_EX_NOREDIRECTIONBITMAP } else { WINDOW_EX_STYLE(0) };
l.hwnd = CreateWindowExW(ex, if l.comp { w!("MenuTahoePopup") } else { w!("MenuTestePopup") }, w!(""), WS_POPUP, x - m, top - m, w_ + 2 * m, h + 2 * m, s.owner, None, hi, None).unwrap_or_default();
if l.comp && !setup_comp(&mut l) {
// não deu: janela do jeito antigo
let _ = DestroyWindow(l.hwnd);
l.comp = false;
l.margin = 0;
l.target = None;
l.root = None;
l.content_s = None;
l.shadow_s = None;
l.hwnd = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, w!("MenuTestePopup"), w!(""), WS_POPUP, x, top, w_, h, s.owner, None, hi, None).unwrap_or_default();
}
if !l.comp {
apply_effects(l.hwnd, s.dark); // antes de mostrar: depois deixava o menu em branco às vezes
}
if l.comp && ask_shell_glass(&l, s.dark) {
// o vidro do Shell já está atrás: o desfoque do Windows sai
l.ext = true;
if let Some(b) = &l.back_v {
let _ = b.SetIsVisible(false);
}
}
let hwnd = l.hwnd;
let comp = l.comp;
s.levels.push(l);
if comp {
draw_level(s.levels.len() - 1); // desenha antes de aparecer
}
let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE);
let _ = UpdateWindow(hwnd);
SetTimer(hwnd, 2, 30, None); // segunda pintura de garantia
if s.levels.len() == 1 && s.t_show != 0 {
log(&format!(" menu na tela em {} ms ({})", GetTickCount().wrapping_sub(s.t_show), if comp { "vidro" } else { "simples" }));
s.t_show = 0;
}
if *DEMO.get() {
log(&format!(" abriu nível em {x},{top} {w_}x{h}"));
}
}
}
fn free_level(l: &mut Level) {
tell_shell_glass(l, 0);
l.rt = None;
unsafe {
if !l.mem.is_invalid() {
let _ = DeleteDC(l.mem);
}
if !l.dib.is_invalid() {
let _ = DeleteObject(l.dib);
}
l.target = None;
l.root = None;
l.content_s = None;
l.shadow_s = None;
l.back_v = None;
if IsWindow(l.hwnd).as_bool() {
let _ = DestroyWindow(l.hwnd);
}
}
}
fn close_levels_after(li: i32) {
let Some(s) = ses() else { return };
while s.levels.len() as i32 > li + 1 {
let mut l = s.levels.pop().unwrap();
free_level(&mut l);
}
if li >= 0 && (li as usize) < s.levels.len() {
s.levels[li as usize].open_child = -1;
invalidate(&s.levels[li as usize]);
}
}
fn open_sub(li: usize, i: usize) {
let Some(s) = ses() else { return };
let l = &mut s.levels[li];
let it = &mut l.items()[i];
if it.src != 0 {
// relê: "Enviar para" pode ter ganhado itens depois da abertura
if let Some(cm) = ACTIVE.get().clone() {
let mut nt = 0;
let fresh = flatten(&read_menu_items(&cm, HMENU(it.src as *mut _), 1, &mut nt));
if !fresh.is_empty() {
it.sub = fresh;
}
}
}
if it.sub.is_empty() || it.disabled {
return;
}
let wr = menu_rect(l);
let item_top = wr.top + l.rects[i].top as i32;
l.open_child = i as i32;
invalidate(l);
let sub: *mut Vec<MItem> = &mut it.sub;
open_level(sub, POINT { x: wr.right, y: item_top }, Some(wr), item_top);
}
fn cancel_pending() {
let Some(s) = ses() else { return };
if s.pend_level >= 0 && !s.levels.is_empty() {
unsafe {
let _ = KillTimer(s.levels[0].hwnd, 1);
}
}
s.pend_level = -1;
}
fn schedule(li: i32, item: i32, ms: u32) {
let Some(s) = ses() else { return };
if s.pend_level == li && s.pend_item == item {
return;
}
s.pend_level = li;
s.pend_item = item;
unsafe {
SetTimer(s.levels[0].hwnd, 1, ms, None);
}
}
fn on_timer() {
let Some(s) = ses() else { return };
unsafe {
let _ = KillTimer(s.levels[0].hwnd, 1);
}
let (pl, pi) = (s.pend_level, s.pend_item);
s.pend_level = -1;
if pl < 0 || pl as usize >= s.levels.len() {
return;
}
close_levels_after(pl);
if pi >= 0 {
open_sub(pl as usize, pi as usize);
}
}
fn hit_item(l: &Level, p: POINT) -> i32 {
let wr = menu_rect(l);
if !(p.x >= wr.left && p.x < wr.right && p.y >= wr.top && p.y < wr.bottom) {
return -2;
}
let y = (p.y - wr.top) as f32;
l.rects.iter().position(|r| y >= r.top && y < r.bottom).map(|i| i as i32).unwrap_or(-1)
}
/// bolinha da fileira sob o x (pixels da janela) ou -1
fn dot_at(l: &Level, m: &MItem, x: f32) -> i32 {
for k in 0..m.dots.len() {
let cx = l.text_l + (DOT_D / 2.0 + 1.5 + k as f32 * DOT_PITCH) * l.scale;
if (x - cx).abs() <= DOT_PITCH / 2.0 * l.scale {
return k as i32;
}
}
-1
}
fn on_mouse_move(li: usize, p: POINT) {
let Some(s) = ses() else { return };
let mut i = hit_item(&s.levels[li], p);
{
// fileira de bolinhas: destaca a bolinha, não a linha
let l = &mut s.levels[li];
let wr = menu_rect(l);
let d = if i >= 0 && !l.items()[i as usize].dots.is_empty() { dot_at(l, &l.items()[i as usize], (p.x - wr.left) as f32) } else { -1 };
if d != l.dot_hover {
l.dot_hover = d;
invalidate(l);
}
}
if i >= 0 && !selectable(&s.levels[li].items()[i as usize]) {
i = -1;
}
for k in 0..li {
// chegou no submenu: o item pai continua destacado
let lk = &mut s.levels[k];
if lk.hover != lk.open_child {
lk.hover = lk.open_child;
invalidate(lk);
}
}
if s.pend_level >= 0 && (s.pend_level as usize) < li {
cancel_pending();
}
let l = &mut s.levels[li];
if i != l.hover {
l.hover = i;
invalidate(l);
}
if i < 0 {
return;
}
if has_sub(&l.items()[i as usize]) {
if l.open_child == i {
cancel_pending();
return;
}
schedule(li as i32, i, 140);
} else if s.levels.len() > li + 1 {
schedule(li as i32, -1, 260);
} else {
cancel_pending();
}
}
/// o soltar do mesmo clique que abriu o menu (quem abre no apertar: os Ajustes) não escolhe nada; como no Mac, só vale se
/// o ponteiro andou (perto da borda o menu abria por cima do ponteiro e "abria e fechava": issue #40)
fn on_button_up(li: usize, p: POINT) {
let Some(s) = ses() else { return };
let op = *OPEN_PT.get();
if li == 0 && unsafe { GetTickCount() }.wrapping_sub(*OPEN_TICK.get()) < 500 && (p.x - op.x).abs() <= 3 && (p.y - op.y).abs() <= 3 {
log(" soltar do clique que abriu o menu: ignorado");
return;
}
let l = &mut s.levels[li];
let i = hit_item(l, p);
log(&format!(" clique solto no nível {li}, item {i}"));
if i < 0 {
return;
}
let it = &mut l.items()[i as usize];
if !it.dots.is_empty() {
// clicou numa bolinha: devolve o id dela
let wr = menu_rect(l);
let d = dot_at(l, it, (p.x - wr.left) as f32);
if d < 0 {
return;
}
it.cmd = it.dots[d as usize].id as u32;
s.result = it;
s.done = true;
return;
}
if !selectable(it) {
return;
}
if has_sub(it) {
cancel_pending();
if l.open_child != i {
close_levels_after(li as i32);
open_sub(li, i as usize);
}
return;
}
s.result = it;
s.done = true;
}
fn on_key(vk: VIRTUAL_KEY) {
cancel_pending();
let Some(s) = ses() else { return };
let li = s.levels.len() - 1;
let l = &mut s.levels[li];
let n = l.items().len() as i32;
let mv = |l: &mut Level, dir: i32| {
let mut i = if l.hover < 0 {
if dir > 0 {
-1
} else {
0
}
} else {
l.hover
};
for _ in 0..n {
i = (i + dir + n) % n;
if selectable(&l.items()[i as usize]) {
l.hover = i;
break;
}
}
invalidate(l);
};
match vk {
VK_ESCAPE => {
if li > 0 {
close_levels_after(li as i32 - 1);
} else {
s.done = true;
}
}
VK_LEFT => {
if li > 0 {
close_levels_after(li as i32 - 1);
}
}
VK_DOWN => mv(l, 1),
VK_UP => mv(l, -1),
VK_RIGHT | VK_RETURN | VK_SPACE => {
if l.hover >= 0 {
let hv = l.hover as usize;
let it = &mut l.items()[hv];
if has_sub(it) {
open_sub(li, hv);
let c = s.levels.last_mut().unwrap();
if let Some(k) = c.items().iter().position(selectable) {
c.hover = k as i32;
}
invalidate(c);
} else if vk != VK_RIGHT && selectable(it) {
s.result = it;
s.done = true;
}
}
}
_ => {}
}
}
fn brush(rt: &ID2D1RenderTarget, c: Cor) -> Option<ID2D1SolidColorBrush> {
unsafe { rt.CreateSolidColorBrush(&c, None).ok() }
}
/// o conteúdo do menu (fundo, borda do vidro, itens) num alvo qualquer: a janela, a superfície da composição ou a foto
unsafe fn paint_body(rt: &ID2D1RenderTarget, l: &Level, dk: bool, begin: bool, clear: bool) {
let sc = l.scale;
let mut bg = if dk { col(0.17, 0.17, 0.18, 0.80) } else { col(0.965, 0.965, 0.965, 0.80) };
// Tahoe: o vidro "regular" da Apple (menus, avisos): tingido e bem menos transparente que o Dock (guia, 52 e 60)
if tahoe() {
bg = if dk { col(0.165, 0.165, 0.172, 0.85) } else { col(0.96, 0.96, 0.965, 0.77) };
}
if let Some(a) = GLASS.get().alpha {
bg.a = a(bg.a);
}
// macOS 27 Golden Gate: o menu de contexto é vidro fosco (leitoso)
if golden() {
bg = if dk { col(0.17, 0.165, 0.165, 0.88) } else { col(0.95, 0.945, 0.94, 0.84) };
}
// Liquid Glass do Shell atrás (menu_vidro=1): a tinta forte fica no vidro, aqui só um véu para o texto
if l.ext {
bg = if dk { col(0.12, 0.12, 0.13, 0.26) } else { col(0.98, 0.98, 0.985, 0.30) };
}
let leo = leopard();
if leo {
bg = col(1.0, 1.0, 1.0, 0.94); // Leopard: sempre claro
}
let dkt = dk && !leo;
let (Some(text), Some(dim), Some(sep), Some(hdr), Some(accent), Some(white)) = (
brush(rt, if dkt { col(1.0, 1.0, 1.0, 0.92) } else { col(0.0, 0.0, 0.0, if leo { 1.0 } else { 0.88 }) }),
brush(rt, if dkt { col(1.0, 1.0, 1.0, 0.30) } else { col(0.0, 0.0, 0.0, 0.30) }),
brush(rt, if dkt { col(1.0, 1.0, 1.0, 0.12) } else { col(0.0, 0.0, 0.0, if leo { 0.14 } else { 0.10 }) }),
brush(rt, if dkt { col(1.0, 1.0, 1.0, 0.45) } else { col(0.0, 0.0, 0.0, 0.45) }),
brush(rt, col(0.0, 0.39, 0.88, 1.0)),
brush(rt, col(1.0, 1.0, 1.0, 1.0)),
) else {
return;
};
if begin {
rt.BeginDraw();
}
if clear {
rt.Clear(Some(&bg));
} else if let Some(b) = brush(rt, bg) {
// modo foto: o cartão sobre o que já está desenhado
rt.FillRoundedRectangle(&rr(rf(0.0, 0.0, l.mw, l.mh), card_r() * l.scale, card_r() * l.scale), &b);
}
let ww = l.rects.first().map(|r| r.right).unwrap_or(0.0);
if tahoe() {
// Liquid Glass: borda escurecida e brilho especular nos cantos
let sz = if l.comp { D2D_SIZE_F { width: l.mw, height: l.mh } } else { rt.GetSize() };
vidro::borda(rt, rf(0.0, 0.0, sz.width, sz.height), (if l.comp { card_r() } else { 8.0 }) * sc, sc, dk, 1.0, false, 1.0, -1.0, -1.0);
}
let (tf, tf_hdr) = (l.tf.clone(), l.tf_hdr.clone());
for (i, m) in l.items().iter().enumerate() {
let r = l.rects[i];
if m.sep {
let yy = ((r.top + r.bottom) / 2.0).floor() + 0.5;
rt.DrawLine(pt(inset() * sc + 5.0 * sc, yy), pt(ww - inset() * sc - 5.0 * sc, yy), &sep, 1.0, None);
continue;
}
let trc = rf(l.text_l, r.top, ww - l.text_r, r.bottom);
if !m.dots.is_empty() {
// fileira de etiquetas: bolinhas coloridas, ✓ nas marcadas, anel na do mouse
let cy = (r.top + r.bottom) / 2.0;
let rad = DOT_D / 2.0 * sc;
for (k, d) in m.dots.iter().enumerate() {
let cx = l.text_l + (DOT_D / 2.0 + 1.5 + k as f32 * DOT_PITCH) * sc;
let c = d.rgb;
let Some(b) = brush(rt, col(((c >> 16) & 255) as f32 / 255.0, ((c >> 8) & 255) as f32 / 255.0, (c & 255) as f32 / 255.0, 1.0)) else { continue };
rt.FillEllipse(&ell(pt(cx, cy), rad, rad), &b);
if k as i32 == l.dot_hover {
rt.DrawEllipse(&ell(pt(cx, cy), rad + 2.5 * sc, rad + 2.5 * sc), &b, 1.3 * sc, None);
}
if d.on {
rt.DrawLine(pt(cx - 2.6 * sc, cy), pt(cx - 0.6 * sc, cy + 2.2 * sc), &white, 1.4 * sc, None);
rt.DrawLine(pt(cx - 0.6 * sc, cy + 2.2 * sc), pt(cx + 2.8 * sc, cy - 2.4 * sc), &white, 1.4 * sc, None);
}
}
continue;
}
if m.header {
if let Some(t) = &tf_hdr {
rt.DrawText(&w(&m.label), t, &trc, &hdr, D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
}
continue;
}
let hot = i as i32 == l.hover || (i as i32 == l.open_child && l.hover < 0);
if hot && !m.disabled && leo {
// Leopard: degradê azul de ponta a ponta, com o fio claro em cima
let st = [D2D1_GRADIENT_STOP { position: 0.0, color: col(0.39, 0.56, 0.96, 1.0) }, D2D1_GRADIENT_STOP { position: 1.0, color: col(0.13, 0.35, 0.88, 1.0) }];
if let Ok(gs) = rt.CreateGradientStopCollection(&st, D2D1_GAMMA_2_2, D2D1_EXTEND_MODE_CLAMP) {
if let Ok(lb) = rt.CreateLinearGradientBrush(&D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES { startPoint: pt(0.0, r.top), endPoint: pt(0.0, r.bottom) }, None, &gs) {
rt.FillRectangle(&rf(0.0, r.top, ww, r.bottom), &lb);
}
}
white.SetOpacity(0.35);
rt.FillRectangle(&rf(0.0, r.top, ww, r.top + sc), &white);
white.SetOpacity(1.0);
} else if hot && !m.disabled {
rt.FillRoundedRectangle(&rr(rf(inset() * sc, r.top, ww - inset() * sc, r.bottom), hot_r() * sc, hot_r() * sc), &accent);
}
let fg = if m.disabled {
&dim
} else if hot {
&white
} else {
&text
};
if let Some(t) = &tf {
rt.DrawText(&w(&m.label), t, &trc, fg, D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
if !m.shortcut.is_empty() {
let sw = text_width(t, &m.shortcut);
let sr = rf(ww - l.text_r - sw, r.top, ww - l.text_r + 2.0 * sc, r.bottom);
rt.DrawText(&w(&m.shortcut), t, &sr, if hot && !m.disabled { &white } else { &dim }, D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
}
}
let cy = (r.top + r.bottom) / 2.0;
if m.icon != 0 && !m.checked {
if let Some(ti) = &l.tf_icon {
// ícone do Tahoe na coluna da esquerda
rt.DrawText(&[m.icon], ti, &rf((icon_cx() - 10.0) * sc, r.top, (icon_cx() + 10.0) * sc, r.bottom), fg, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
}
}
if m.img != 0 && !m.checked {
// imagem (ícone do app): 16 pt na coluna do ícone
let bp = D2D1_BITMAP_PROPERTIES { pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED }, dpiX: 96.0, dpiY: 96.0 };
if let Ok(bm) = rt.CreateBitmap(D2D_SIZE_U { width: m.img, height: m.img }, Some(m.img_px.as_ptr() as *const _), m.img * 4, &bp) {
rt.DrawBitmap(&bm, Some(&rf((icon_cx() - 8.0) * sc, cy - 8.0 * sc, (icon_cx() + 8.0) * sc, cy + 8.0 * sc)), if m.disabled { 0.4 } else { 1.0 }, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
}
}
if m.swatch != 0 && !m.checked {
// amostra de cor: quadradinho de 12 com canto 3 e contorno fino
let swr = rr(rf((icon_cx() - 6.0) * sc, cy - 6.0 * sc, (icon_cx() + 6.0) * sc, cy + 6.0 * sc), 3.0 * sc, 3.0 * sc);
let v = m.swatch;
let c = if v == SWATCH_AUTO { col(0.0, 0.0, 0.0, 1.0) } else { col(((v >> 16) & 255) as f32 / 255.0, ((v >> 8) & 255) as f32 / 255.0, (v & 255) as f32 / 255.0, 1.0) };
if let Some(cb) = brush(rt, c) {
rt.FillRoundedRectangle(&swr, &cb);
if v == SWATCH_AUTO {
// "Automática": metade de baixo branca
cb.SetColor(&col(1.0, 1.0, 1.0, 1.0));
rt.PushAxisAlignedClip(&rf(swr.rect.left, cy, swr.rect.right, swr.rect.bottom), D2D1_ANTIALIAS_MODE_ALIASED);
rt.FillRoundedRectangle(&swr, &cb);
rt.PopAxisAlignedClip();
}
cb.SetColor(&if hot && !m.disabled { col(1.0, 1.0, 1.0, 0.85) } else { col(0.5, 0.5, 0.5, 0.55) });
rt.DrawRoundedRectangle(&swr, &cb, 0.75 * sc, None);
}
}
if m.checked {
let x = INSET * sc + 7.0 * sc;
rt.DrawLine(pt(x, cy), pt(x + 3.5 * sc, cy + 3.5 * sc), fg, 1.6 * sc, None);
rt.DrawLine(pt(x + 3.5 * sc, cy + 3.5 * sc), pt(x + 10.0 * sc, cy - 4.0 * sc), fg, 1.6 * sc, None);
}
if has_sub(m) {
// seta ›
let x = ww - INSET * sc - 12.0 * sc;
rt.DrawLine(pt(x, cy - 4.0 * sc), pt(x + 4.0 * sc, cy), fg, 1.5 * sc, None);
rt.DrawLine(pt(x + 4.0 * sc, cy), pt(x, cy + 4.0 * sc), fg, 1.5 * sc, None);
}
}
if l.comp && !tahoe() {
// contorno fino no canto arredondado (o DWM fazia isso na janela)
let inn = 0.5;
let rad = card_r() * sc - inn;
rt.DrawRoundedRectangle(&rr(rf(inn, inn, l.mw - inn, l.mh - inn), rad, rad), &sep, 1.0, None);
}
}
fn draw_level(li: usize) {
let Some(s) = ses() else { return };
let dk = s.dark;
let l = &mut s.levels[li];
unsafe {
let mut rc = RECT::default();
let _ = GetClientRect(l.hwnd, &mut rc);
let mut csi: Option<ICompositionDrawingSurfaceInterop> = None;
let rt: ID2D1RenderTarget;
if l.comp {
let Some(cs) = &l.content_s else { return };
let Ok(si) = cs.cast::<ICompositionDrawingSurfaceInterop>() else { return };
let mut off = POINT::default();
let Ok(cdc) = si.BeginDraw::<ID2D1DeviceContext>(None, &mut off) else { return };
cdc.SetTransform(&mat::trans(off.x as f32, off.y as f32));
cdc.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
cdc.PushAxisAlignedClip(&rf(0.0, 0.0, l.mw, l.mh), D2D1_ANTIALIAS_MODE_ALIASED);
rt = cdc.cast().unwrap();
csi = Some(si);
} else {
if l.mem.is_invalid() {
let bi = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: rc.right, biHeight: -rc.bottom, biPlanes: 1, biBitCount: 32, ..Default::default() }, ..Default::default() };
let mut bits: *mut core::ffi::c_void = std::ptr::null_mut();
l.dib = CreateDIBSection(None, &bi, DIB_RGB_COLORS, &mut bits, None, 0).unwrap_or_default();
l.mem = CreateCompatibleDC(None);
SelectObject(l.mem, l.dib);
}
if l.rt.is_none() {
let props = D2D1_RENDER_TARGET_PROPERTIES { r#type: D2D1_RENDER_TARGET_TYPE_DEFAULT, pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED }, dpiX: 96.0, dpiY: 96.0, ..Default::default() };
let Ok(r) = app2d::d2d().CreateDCRenderTarget(&props) else { return };
r.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
l.rt = Some(r);
}
let dcrt = l.rt.clone().unwrap();
let _ = dcrt.BindDC(l.mem, &rc);
rt = dcrt.cast().unwrap();
}
paint_body(&rt, l, dk, !l.comp, true);
if let Some(si) = csi {
rt.PopAxisAlignedClip();
let _ = si.EndDraw();
return;
}
if let Err(e) = rt.EndDraw(None, None) {
log(&format!(" aviso: EndDraw falhou (hr=0x{:08X}), repintando", e.code().0 as u32));
l.rt = None;
SetTimer(l.hwnd, 2, 16, None);
return;
}
// cópia direta para a janela: os bytes de alfa vão junto e o DWM compõe sobre o acrílico
let dc = GetDC(l.hwnd);
let _ = BitBlt(dc, 0, 0, rc.right, rc.bottom, l.mem, 0, 0, SRCCOPY);
ReleaseDC(l.hwnd, dc);
}
}
/// animação de saída no estilo macOS: o item escolhido pisca uma vez e o menu some em fade
fn blink() {
let Some(s) = ses() else { return };
for li in (0..s.levels.len()).rev() {
let l = &mut s.levels[li];
if let Some(k) = l.items().iter().position(|m| std::ptr::eq(m, s.result)) {
l.hover = -1;
draw_level(li);
pump_for(50);
ses().unwrap().levels[li].hover = k as i32;
draw_level(li);
pump_for(50);
return;
}
}
}
fn is_dying(h: HWND) -> bool {
DYING.get().iter().any(|l| l.hwnd == h)
}
fn kill_dying(h: HWND) {
let d = DYING.get();
if let Some(i) = d.iter().position(|l| l.hwnd == h) {
let mut l = d.remove(i);
free_level(&mut l);
}
}
fn opacity_anim(l: &Level) -> bool {
let (Some(c), Some(root)) = (COMP.get().as_ref(), &l.root) else { return false };
(|| -> Result<()> {
let a = c.wc.CreateScalarKeyFrameAnimation()?;
let e = c.wc.CreateCubicBezierEasingFunction(v2(0.3, 0.0), v2(0.6, 1.0))?;
a.InsertKeyFrameWithEasingFunction(1.0, 0.0, &e)?;
a.SetDuration(TimeSpan { Duration: FADE_MS.load(Ordering::SeqCst) as i64 * 10_000 })?;
root.StartAnimation(&HSTRING::from("Opacity"), &a)?;
Ok(())
})()
.is_ok()
}
/// menus que estão sumindo sozinhos: a ação escolhida já roda e o programa já responde a cliques enquanto o fade
/// acontece. true: os níveis passaram para DYING e somem sozinhos (só com composição)
fn fade_out_async() -> bool {
let Some(s) = ses() else { return false };
if s.levels.is_empty() || !s.levels[0].comp {
return false;
}
// a janela dona fechou antes do fim: o Windows já destruiu o menu
let d = DYING.get();
let mut i = 0;
while i < d.len() {
if !unsafe { IsWindow(d[i].hwnd) }.as_bool() {
let mut l = d.remove(i);
free_level(&mut l);
} else {
i += 1;
}
}
let fade = FADE_MS.load(Ordering::SeqCst) as u32;
for l in s.levels.drain(..) {
opacity_anim(&l);
tell_shell_glass(&l, 2); // o vidro do Shell some junto
unsafe {
let ex = crate::util::get_wlp(l.hwnd, GWL_EXSTYLE);
crate::util::set_wlp(l.hwnd, GWL_EXSTYLE, ex | WS_EX_TRANSPARENT.0 as isize); // cliques passam
SetTimer(l.hwnd, T_DYING, fade + 30, None);
}
d.push(l);
}
true
}
fn fade_out() {
let Some(s) = ses() else { return };
let fade = FADE_MS.load(Ordering::SeqCst);
if !s.levels.is_empty() && s.levels[0].comp {
// composição: a opacidade anima sozinha
for l in &s.levels {
opacity_anim(l);
tell_shell_glass(l, 2);
}
pump_for(fade as u32 + 16);
return;
}
unsafe {
for l in &s.levels {
let ex = crate::util::get_wlp(l.hwnd, GWL_EXSTYLE);
crate::util::set_wlp(l.hwnd, GWL_EXSTYLE, ex | WS_EX_LAYERED.0 as isize);
let _ = SetLayeredWindowAttributes(l.hwnd, COLORREF(0), 255, LWA_ALPHA);
}
let t0 = std::time::Instant::now();
loop {
let p = t0.elapsed().as_secs_f64() * 1000.0 / fade as f64;
if p >= 1.0 {
break;
}
let a = (255.0 * (1.0 - p) * (1.0 - p)) as u8; // desacelera no fim, como no macOS
for l in &s.levels {
let _ = SetLayeredWindowAttributes(l.hwnd, COLORREF(0), a, LWA_ALPHA);
}
let _ = DwmFlush();
}
}
}
unsafe extern "system" fn popup_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
if m == WM_TIMER && w_.0 == T_DYING {
let _ = KillTimer(h, T_DYING);
kill_dying(h);
return LRESULT(0);
}
if m == WM_NCHITTEST && is_dying(h) {
return LRESULT(HTTRANSPARENT as isize);
}
if m == WM_PAINT && is_dying(h) {
let mut ps = PAINTSTRUCT::default();
BeginPaint(h, &mut ps);
let _ = EndPaint(h, &ps);
return LRESULT(0);
}
let li = find_level(h);
match m {
WM_PAINT => {
let mut ps = PAINTSTRUCT::default();
BeginPaint(h, &mut ps);
if li >= 0 {
draw_level(li as usize);
}
let _ = EndPaint(h, &ps);
LRESULT(0)
}
WM_ERASEBKGND => LRESULT(1),
WM_NCHITTEST => {
if li >= 0 {
let lv = &ses().unwrap().levels[li as usize];
if lv.comp {
let p = POINT { x: get_x_lparam(l), y: get_y_lparam(l) };
let r = menu_rect(lv);
if !(p.x >= r.left && p.x < r.right && p.y >= r.top && p.y < r.bottom) {
return LRESULT(HTTRANSPARENT as isize);
}
}
}
DefWindowProcW(h, m, w_, l)
}
WM_MOUSEACTIVATE => LRESULT(MA_NOACTIVATE as isize),
WM_MOUSEMOVE if li >= 0 => {
let mut tme = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };
let _ = TrackMouseEvent(&mut tme);
let mut p = POINT { x: get_x_lparam(l), y: get_y_lparam(l) };
let _ = ClientToScreen(h, &mut p);
on_mouse_move(li as usize, p);
LRESULT(0)
}
WM_MOUSELEAVE => {
if li >= 0 {
let lv = &mut ses().unwrap().levels[li as usize];
if lv.open_child < 0 && lv.hover >= 0 {
lv.hover = -1;
invalidate(lv);
}
}
LRESULT(0)
}
WM_LBUTTONUP | WM_RBUTTONUP if li >= 0 => {
let mut p = POINT { x: get_x_lparam(l), y: get_y_lparam(l) };
let _ = ClientToScreen(h, &mut p);
on_button_up(li as usize, p);
LRESULT(0)
}
WM_LBUTTONDOWN | WM_RBUTTONDOWN => LRESULT(0),
WM_TIMER => {
if w_.0 == 2 {
let _ = KillTimer(h, 2);
let _ = InvalidateRect(h, None, false);
} else if li == 0 {
on_timer();
}
LRESULT(0)
}
_ => DefWindowProcW(h, m, w_, l),
}
}
fn is_dark_mode() -> bool {
app2d::dark()
}
/// mostra o menu e devolve o item escolhido (ou None). Laço modal próprio, como o TrackPopupMenu.
fn run_menu(owner: HWND, items: &mut Vec<MItem>, p: POINT, t_show: u32) -> Option<MItem> {
ensure_init();
if ses().is_some() {
return None; // já há um menu aberto
}
*SES.get() = Some(Session { owner, dark: is_dark_mode() && !leopard(), pend_level: -1, pend_item: -1, result: std::ptr::null_mut(), t_show, ..Default::default() });
*PLAIN.get() = std::mem::take(PLAIN_NEXT.get());
*ABOVE.get() = std::mem::take(ABOVE_NEXT.get());
unsafe {
*OPEN_TICK.get() = GetTickCount();
let _ = GetCursorPos(OPEN_PT.get());
}
open_level(items, p, None, 0);
let demo = *DEMO.get();
if demo {
let s = ses().unwrap();
if let Some(l) = s.levels.first_mut() {
l.hover = 2;
invalidate(l);
}
}
unsafe {
let mut msg = MSG::default();
while !ses().unwrap().done {
if GetForegroundWindow() != owner && !demo {
break;
}
if !GetMessageW(&mut msg, None, 0, 0).as_bool() {
PostQuitMessage(msg.wParam.0 as i32);
break;
}
let on_popup = find_level(msg.hwnd) >= 0;
match msg.message {
WM_KEYDOWN | WM_SYSKEYDOWN => {
on_key(VIRTUAL_KEY(msg.wParam.0 as u16));
continue;
}
WM_KEYUP | WM_SYSKEYUP | WM_CHAR | WM_SYSCHAR => continue,
WM_RBUTTONDOWN => {
// botão direito em outro ponto da mesma janela: fecha este e deixa o clique seguir (a janela abre o
// menu do novo item, como no macOS)
if !on_popup && (msg.hwnd == owner || IsChild(owner, msg.hwnd).as_bool()) {
ses().unwrap().done = true;
} else if !on_popup {
ses().unwrap().done = true;
continue;
}
}
WM_LBUTTONDOWN | WM_MBUTTONDOWN | WM_NCLBUTTONDOWN | WM_NCRBUTTONDOWN => {
if !on_popup {
// clique na barra de menus (outro título, relógio...): fecha este e o clique segue para a barra
let mut c = [0u16; 64];
let n = GetClassNameW(msg.hwnd, &mut c);
ses().unwrap().done = true;
if String::from_utf16_lossy(&c[..n.max(0) as usize]) == "ShellBarraDeMenus" {
let _ = PostMessageW(msg.hwnd, msg.message, msg.wParam, msg.lParam);
}
continue; // clique fora fecha e é consumido, como no macOS
}
}
_ => {}
}
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
cancel_pending();
let s = ses().unwrap();
let res = if s.result.is_null() { None } else { Some(unsafe { (*s.result).clone() }) };
log(&match &res {
Some(r) => format!(" menu fechado: escolheu \"{}\" id={}", r.label, r.cmd),
None => format!(" menu fechado: {}", if s.done { "cancelado (Esc ou clique fora)" } else { "perdeu o foco" }),
});
if res.is_some() {
blink();
}
if demo || !fade_out_async() {
fade_out(); // a bancada (demo) ainda espera, para a captura
}
close_levels_after(-1);
*SES.get() = None;
res
}
pub fn is_open() -> bool {
ses().is_some()
}
/// fecha o menu aberto (ex.: a janela dona recebeu WM_ACTIVATEAPP com wParam = FALSE)
pub fn close() {
let Some(s) = ses() else { return };
s.done = true;
unsafe {
let _ = PostMessageW(s.owner, WM_NULL, WPARAM(0), LPARAM(0)); // acorda o laço modal
}
}
fn to_mitems(items: &[Item]) -> Vec<MItem> {
items
.iter()
.map(|it| {
if it.separator {
return msep();
}
let mut m = MItem { label: it.label.clone(), cmd: it.id as u32, checked: it.checked, disabled: it.disabled, shortcut: it.shortcut.clone(), icon: it.icon, swatch: it.swatch, dots: it.dots.clone(), sub: to_mitems(&it.sub), ..Default::default() };
if it.img != 0 && it.img_px.len() == (it.img * it.img * 4) as usize {
m.img = it.img;
m.img_px = it.img_px.clone();
}
m
})
.collect()
}
/// Menu com itens do próprio app (Agrupar por, Ações...), no mesmo visual. Devolve o id escolhido ou 0.
pub fn show_items(owner: HWND, p: POINT, items: &[Item]) -> i32 {
let t = unsafe { GetTickCount() };
let mut m = to_mitems(items);
run_menu(owner, &mut m, p, t).map(|r| r.cmd as i32).unwrap_or(0)
}
unsafe fn invoke_cmd(owner: HWND, cm: &IContextMenu, cmd: u32, p: POINT, folder: &str) -> HRESULT {
let dir = wz(folder);
let mut mask = 0x4000 /* CMIC_MASK_UNICODE */ | CMIC_MASK_PTINVOKE;
if GetKeyState(VK_CONTROL.0 as i32) < 0 {
mask |= CMIC_MASK_CONTROL_DOWN;
}
if GetKeyState(VK_SHIFT.0 as i32) < 0 {
mask |= CMIC_MASK_SHIFT_DOWN;
}
let ici = CMINVOKECOMMANDINFOEX {
cbSize: std::mem::size_of::<CMINVOKECOMMANDINFOEX>() as u32,
fMask: mask,
hwnd: owner,
lpVerb: PCSTR((cmd - ID_FIRST) as usize as *const u8),
lpVerbW: PCWSTR((cmd - ID_FIRST) as usize as *const u16),
lpDirectoryW: pc(&dir),
nShow: SW_SHOWNORMAL.0,
ptInvoke: p,
..Default::default()
};
match cm.InvokeCommand(&ici as *const _ as *const CMINVOKECOMMANDINFO) {
Ok(()) => S_OK,
Err(e) => e.code(),
}
}
/// Menu dos itens `paths` (todos da mesma pasta) ou, com `paths` vazio, do fundo de `folder`, no visual do macOS
/// (as extensões do Windows reorganizadas em até 3 grupos). full = todas as opções na ordem do Windows (Shift).
pub fn show(owner: HWND, p: POINT, folder: &str, paths: &[String], full: bool) -> Resultado {
let mut res = Resultado::default();
let bg = paths.is_empty();
let mut flags = CMF_NORMAL | if bg { 0 } else { CMF_CANRENAME };
// Alt = tecla Option do Mac: revela itens extras
if full || unsafe { GetKeyState(VK_MENU.0 as i32) } < 0 {
flags |= CMF_EXTENDEDVERBS;
}
let t_show = unsafe { GetTickCount() };
let Some(sm) = load_shell_menu(owner, folder, paths, flags) else {
res.hr = E_FAIL.0;
return res;
};
log(&format!(" QueryContextMenu: {} ms", unsafe { GetTickCount() }.wrapping_sub(t_show)));
*ACTIVE.get() = Some(sm.cm.clone());
let mut no_text = 0;
log(&format!("--- menu de {} ({} itens){}{}", if bg { folder } else { &paths[0] }, paths.len(), if bg { " (fundo)" } else { "" }, if full { " (todas as opções)" } else { "" }));
let raw = read_menu(&sm.cm, sm.hmenu, 0, &mut no_text);
dump_tree(&raw, 0);
let mut items = if full { full_list(&raw) } else { organize(&raw) };
// itens do próprio app (extra_next): logo depois do primeiro grupo (Abrir / Abrir com)
let extra = std::mem::take(EXTRA_NEXT.get());
if !extra.is_empty() {
let mut add: Vec<MItem> = extra.iter().map(|it| MItem { label: it.label.clone(), special: 100 + it.id, icon: it.icon, disabled: it.disabled, shortcut: it.shortcut.clone(), ..Default::default() }).collect();
match items.iter().position(|m| m.sep) {
Some(at) => {
add.push(msep());
items.splice(at + 1..at + 1, add);
}
None => {
items.push(msep());
items.extend(add);
}
}
}
// issue #559: os comandos do menu moderno do Windows 11 (IExplorerCommand dos apps empacotados), no fim
let ja: Vec<String> = items.iter().filter(|m| !m.sep && !m.header).map(|m| m.label.clone()).collect();
let modernos = crate::modernos::para(owner, folder, paths, &ja);
if let Some(m) = &modernos {
let mut add: Vec<MItem> = m.comandos.iter().enumerate().map(|(k, c)| MItem { label: c.titulo.clone(), special: MODERNO + k as i32, disabled: c.desativado, ..Default::default() }).collect();
match items.iter().position(|x| x.special == 1) {
// antes de "Mostrar todas as opções", no grupo dos extras
Some(at) => {
add.push(msep());
items.splice(at..at, add);
}
None => {
items.push(msep());
items.extend(add);
}
}
}
let r = run_menu(owner, &mut items, p, t_show);
if let (Some(r), Some(m)) = (&r, &modernos) {
if r.special >= MODERNO && ((r.special - MODERNO) as usize) < m.comandos.len() {
let c = &m.comandos[(r.special - MODERNO) as usize];
let hr = unsafe { c.cmd.Invoke(&m.itens, None) };
log(&format!("Executado (menu moderno): {} → {:?}", c.titulo, hr));
res.chosen = true;
res.hr = hr.map(|_| 0).unwrap_or_else(|e| e.code().0);
*ACTIVE.get() = None;
return res;
}
}
if let Some(r) = &r {
if r.special >= 100 && r.special < MODERNO {
res.chosen = true;
res.extra = r.special - 100;
*ACTIVE.get() = None;
return res;
}
}
let show_all = r.as_ref().is_some_and(|r| r.special == 1);
if let Some(r) = &r {
if (ID_FIRST..=ID_LAST).contains(&r.cmd) {
res.chosen = true;
res.verb = verb_of(&sm.cm, r.cmd);
if res.verb == "rename" && !bg {
res.rename = true;
} else {
res.hr = unsafe { invoke_cmd(owner, &sm.cm, r.cmd, p, folder) }.0;
}
log(&format!("Executado: {} (id {}) → {} 0x{:08X}", if res.verb.is_empty() { "(sem verbo)" } else { &res.verb }, r.cmd, if res.hr >= 0 { "OK" } else { "erro" }, res.hr as u32));
}
}
*ACTIVE.get() = None;
drop(sm);
if show_all {
return show(owner, p, folder, paths, true); // menu novo: há extensões que só preenchem submenus uma vez
}
res
}
/// Executa um verbo canônico ("copy", "cut", "delete", "properties"...) sem mostrar menu.
pub fn invoke_verb(owner: HWND, folder: &str, paths: &[String], verb: &str) -> HRESULT {
let Some(sm) = load_shell_menu(owner, folder, paths, CMF_NORMAL | CMF_CANRENAME) else { return E_FAIL };
let va = std::ffi::CString::new(verb).unwrap_or_default();
let (vw, dir) = (wz(verb), wz(folder));
let ici = CMINVOKECOMMANDINFOEX {
cbSize: std::mem::size_of::<CMINVOKECOMMANDINFOEX>() as u32,
fMask: 0x4000, // CMIC_MASK_UNICODE
hwnd: owner,
lpVerb: PCSTR(va.as_ptr() as *const u8),
lpVerbW: pc(&vw),
lpDirectoryW: pc(&dir),
nShow: SW_SHOWNORMAL.0,
..Default::default()
};
let hr = match unsafe { sm.cm.InvokeCommand(&ici as *const _ as *const CMINVOKECOMMANDINFO) } {
Ok(()) => S_OK,
Err(e) => e.code(),
};
log(&format!("Executado (atalho): {verb} → 0x{:08X}", hr.0 as u32));
hr
}
/// Grava no log a árvore original e a reorganizada (diagnóstico).
pub fn dump_to_log(owner: HWND, path: &str, background: bool) -> bool {
let paths: Vec<String> = if background { Vec::new() } else { vec![path.to_string()] };
let Some(sm) = load_shell_menu(owner, path, &paths, CMF_NORMAL | if background { 0 } else { CMF_CANRENAME }) else { return false };
*ACTIVE.get() = Some(sm.cm.clone());
let mut nt = 0;
log(&format!("--- dump de {path}{}", if background { " (fundo)" } else { "" }));
let raw = read_menu(&sm.cm, sm.hmenu, 0, &mut nt);
log(&format!("== original ({} no topo, {nt} sem texto) ==", raw.len()));
dump_tree(&raw, 0);
log("== organizado ==");
dump_tree(&organize(&raw), 0);
let ja: Vec<String> = raw.iter().map(|m| m.label.clone()).collect();
match crate::modernos::para(owner, path, &paths, &ja) {
Some(m) => {
log(&format!("== menu moderno ({}) ==", m.comandos.len()));
for c in &m.comandos {
log(&format!(" {}{}", c.titulo, if c.desativado { " (desativado)" } else { "" }));
}
}
None => log("== menu moderno: nenhum =="),
}
*ACTIVE.get() = None;
true
}
/// Carrega as extensões de menu de contexto antes do primeiro uso (o primeiro menu fica rápido).
pub fn warmup(owner: HWND, folder: &str, file: &str) {
let t0 = unsafe { GetTickCount() };
crate::modernos::preparar(); // os manifestos do menu moderno (issue #559)
let prev = ACTIVE.get().take();
if let Some(sm) = load_shell_menu(owner, folder, &[], CMF_NORMAL) {
let mut subs = Vec::new();
unsafe { init_submenus(sm.hmenu, 0, &mut subs) };
}
if !file.is_empty() {
if let Some(sm) = load_shell_menu(owner, folder, &[file.to_string()], CMF_NORMAL | CMF_CANRENAME) {
let mut subs = Vec::new();
unsafe { init_submenus(sm.hmenu, 0, &mut subs) };
}
}
*ACTIVE.get() = prev;
log(&format!("menus pré-carregados em {} ms", unsafe { GetTickCount() }.wrapping_sub(t0)));
}
unsafe extern "system" fn termina_vidro(_: HWND, _: u32, id: usize, _: u32) {
if PRE_ESTADO.load(Ordering::SeqCst) == 1 {
return; // a thread ainda está criando o dispositivo
}
let _ = KillTimer(None, id);
if *COMP_TRIED.get() {
return; // um menu já abriu e montou tudo
}
let t0 = GetTickCount();
let ok = comp_ready();
log(&format!("vidro do menu pronto em {} ms na interface ({})", GetTickCount().wrapping_sub(t0), if ok { "ok" } else { "sem composição" }));
}
/// O mesmo, numa thread própria: as extensões ficam carregadas no processo sem travar a janela; o vidro do menu (D3D,
/// D2D) é preparado antes do primeiro menu.
pub fn warmup_async(folder: String, file: String) {
ensure_init();
if tahoe() && !*COMP_TRIED.get() {
prepara_dispositivo();
unsafe {
SetTimer(None, 0, 100, Some(termina_vidro));
}
}
std::thread::spawn(move || unsafe {
if CoInitializeEx(None, COINIT_APARTMENTTHREADED).is_err() {
return;
}
let hi: HINSTANCE = GetModuleHandleW(None).map(|m| m.into()).unwrap_or_default();
let owner = CreateWindowExW(WINDOW_EX_STYLE(0), w!("STATIC"), w!(""), WINDOW_STYLE(0), 0, 0, 0, 0, HWND_MESSAGE, None, hi, None).unwrap_or_default();
// as extensões desta thread não usam o ACTIVE da interface: só carregam
if let Some(sm) = load_shell_menu(owner, &folder, &[], CMF_NORMAL) {
let _ = sm;
}
if !file.is_empty() {
if let Some(sm) = load_shell_menu(owner, &folder, &[file.clone()], CMF_NORMAL | CMF_CANRENAME) {
let _ = sm;
}
}
let mut msg = MSG::default();
while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
if !owner.0.is_null() {
let _ = DestroyWindow(owner);
}
CoUninitialize();
});
}
#[allow(unused)]
fn _infinite() -> u32 {
INFINITE
}
/// Modo foto: desenha o menu (só o primeiro nível) em `rt` com o canto de cima à esquerda em (x, y), sem criar janela.
/// hover: a linha destacada (-1 = nenhuma). Devolve o tamanho do cartão.
pub unsafe fn draw_on(rt: &ID2D1RenderTarget, x: f32, y: f32, items: &[Item], dark: bool, hover: i32, sc: f32) -> (f32, f32) {
ensure_init();
let mut m = to_mitems(items);
let mut l = Level { items: &mut m, hover, open_child: -1, dot_hover: -1, scale: sc, comp: true, ..Default::default() };
let (ww, yy) = layout(&mut l, sc);
l.mw = ww.ceil();
l.mh = (yy + pad_y() * sc).ceil();
let mut old = mat::ident();
rt.GetTransform(&mut old);
rt.SetTransform(&mat::mul(&mat::trans(x, y), &old));
// sombra curta embaixo (no Shell é a do D2D borrada; aqui camadas leves)
if let Some(b) = brush(rt, col(0.0, 0.0, 0.0, if dark { 0.10 } else { 0.06 })) {
let r = card_r() * sc;
for k in (1..=6).rev() {
let k = k as f32 * sc;
rt.FillRoundedRectangle(&rr(rf(-k * 0.8, -k * 0.2 + 2.0 * sc, l.mw + k * 0.8, l.mh + k * 1.2 + 2.0 * sc), r + k, r + k), &b);
}
}
let clip = app2d::d2d().CreateRoundedRectangleGeometry(&rr(rf(0.0, 0.0, l.mw, l.mh), card_r() * sc, card_r() * sc)).ok();
if let Some(c) = &clip {
let lp = D2D1_LAYER_PARAMETERS { contentBounds: rf(-1e7, -1e7, 1e7, 1e7), geometricMask: std::mem::ManuallyDrop::new(c.cast().ok()), maskAntialiasMode: D2D1_ANTIALIAS_MODE_PER_PRIMITIVE, maskTransform: mat::ident(), opacity: 1.0, opacityBrush: std::mem::ManuallyDrop::new(None), layerOptions: D2D1_LAYER_OPTIONS_NONE };
rt.PushLayer(&lp, None);
std::mem::ManuallyDrop::into_inner(lp.geometricMask);
}
paint_body(rt, &l, dark && !leopard(), false, false);
if clip.is_some() {
rt.PopLayer();
}
rt.SetTransform(&old);
(l.mw, l.mh)
}