A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
Siri: working glow animation, menu bar icon with a text field, fallback model when the quota runs out
Eternity070628d8c7704a49be
diff --git a/docs/registro-mudancas.txt b/docs/registro-mudancas.txtindex 4b81c8b..5d5c20e 100644--- a/docs/registro-mudancas.txt+++ b/docs/registro-mudancas.txt@@ -1630,3 +1630,21 @@ Compilado (tudo), instalado, Shell e reserva do Finder reiniciados às 23:07 semgemini-flash-latest durante os testes (do lado deles). NÃO visto na tela: a animação nova (o usuário estava jogando; o testeconfere jogo/tela cheia na frente e parou), F14/F15 (sem apertar teclas), os segundos, Codex/Claude Code (Codex não instalado).DESFAZER: reverter o commit.++[2026-11-23 17:15, hora do PC] Siri: animação acertada, ícone na barra com campo de digitar, reserva quando a cota acaba.+ - src/shell/siri.cpp: a primeira versão da animação não aparecia: o traço de pontas redondas vinha da fábrica do ui::d2d e o+ desenho dentro do vidro usa outra (o quadro inteiro era descartado no EndDraw). Agora o traço é criado na fábrica do contexto.+ O desenho dentro do vidro é recortado no formato do painel: o brilho foi para a janela da frente (transparente, com a folga).+ Camadas de brilho com pontas retas (as redondas somavam e faziam "contas"). Visto nas fotos: borda colorida e brilho+ pensando, apagando quando a resposta chega, texto entrando.+ - Cota zerada (429) no preferido: tenta um reserva estável da mesma família (cada modelo do Gemini tem a sua cota), só naquela+ pergunta (Reserva()).+ - Ícone da Siri na barra de menus (pedido do usuário: "a Siri no canto, no lugar do Spotlight"): a bolinha colorida entre o+ relógio e a Central de Controle, como no macOS, só com um serviço escolhido (barra_siri; Ajustes > Central de Controle >+ Siri). Clicar abre o painel com o campo "Pergunte à Siri…" (cursor piscando, Ctrl+V cola, Enter pergunta, Esc fecha);+ depois de uma resposta, digitar começa outra pergunta.+ - Testes: WM_COPYDATA 'SIRT' (pergunta sem pegar a frente, fecha em 8 s) e 'SIRA' (abre o campo sem pegar a frente), para+ testar com um jogo em tela cheia na frente (o usuário liberou). Visto: o campo vazio com o convite e o cursor. NÃO visto:+ digitar no campo (as letras mandadas pelo teste não chegaram; o usuário estava usando a Siri ao mesmo tempo), o ícone na+ barra (escondida pela tela cheia do jogo). A cota grátis do Gemini da conta acabou durante os testes (429 em todos os Flash).+ DESFAZER: reverter o commit.diff --git a/src/ajustes/paginas.cpp b/src/ajustes/paginas.cppindex 8317dc0..cca6c13 100644--- a/src/ajustes/paginas.cpp+++ b/src/ajustes/paginas.cpp@@ -1609,7 +1609,10 @@ Page CentralControle() {auto som = showHide(L"barra_som", L"0"), bt = showHide(L"barra_bluetooth", L"0");Row so = Popup(L"Som", { L"Mostrar na Barra de Menus", L"Não Mostrar na Barra de Menus" }, som.first, som.second); so.icon = 0xE767; so.iconColor = C_PURPLE;Row b = Popup(L"Bluetooth", { L"Mostrar na Barra de Menus", L"Não Mostrar na Barra de Menus" }, bt.first, bt.second); b.icon = 0xE702; b.iconColor = C_BLUE;- p.groups.push_back(G({ w, b, so, s }, L"Módulos da Central de Controle", L"Estes módulos ficam na Central de Controle. Você pode escolher quando eles também aparecem na barra de menus."));+ // a Siri no canto da barra (aparece com um serviço escolhido em Apple Intelligence e Siri)+ auto siriB = showHide(L"barra_siri", L"1");+ Row si = Popup(L"Siri", { L"Mostrar na Barra de Menus", L"Não Mostrar na Barra de Menus" }, siriB.first, siriB.second); si.icon = 0xE720; si.iconColor = C_PURPLE;+ p.groups.push_back(G({ w, b, so, s, si }, L"Módulos da Central de Controle", L"Estes módulos ficam na Central de Controle. Você pode escolher quando eles também aparecem na barra de menus."));// ícones da bandeja: guardados (lista no botão direito da Central de Controle, como o Mac sem setinha),// na setinha » ou todos na barraRow tray = Popup(L"Ícones dos aplicativos", { L"Guardados (botão direito na Central de Controle)", L"Agrupados no menu »", L"Sempre na barra de menus" },diff --git a/src/comum/idioma_de.inc b/src/comum/idioma_de.incindex 4a068f4..7b5409d 100644--- a/src/comum/idioma_de.inc+++ b/src/comum/idioma_de.inc@@ -1689,3 +1689,4 @@{ L"Pegue a chave no site do serviço e use \"Colar chave\". A chave fica cifrada nesta conta do Windows, e as perguntas vão direto do PC para o serviço.", L"Hol dir den Schlüssel auf der Website des Dienstes und nutze „Schlüssel einfügen“. Der Schlüssel wird für dieses Windows-Konto verschlüsselt, und die Fragen gehen direkt vom PC an den Dienst." },{ L"Roda no próprio PC: as perguntas não saem dele. Abra o app antes de perguntar.", L"Läuft auf diesem PC: Deine Fragen verlassen ihn nicht. Öffne die App, bevor du fragst." },{ L"Mostrar os segundos", L"Sekunden anzeigen" },+{ L"Pergunte à Siri…", L"Siri fragen …" },diff --git a/src/comum/idioma_en.inc b/src/comum/idioma_en.incindex 2e91410..20298fe 100644--- a/src/comum/idioma_en.inc+++ b/src/comum/idioma_en.inc@@ -1689,3 +1689,4 @@{ L"Pegue a chave no site do serviço e use \"Colar chave\". A chave fica cifrada nesta conta do Windows, e as perguntas vão direto do PC para o serviço.", L"Get the key on the service's website and use \"Paste key\". The key is encrypted for this Windows account, and questions go straight from this PC to the service." },{ L"Roda no próprio PC: as perguntas não saem dele. Abra o app antes de perguntar.", L"Runs on this PC: your questions don't leave it. Open the app before asking." },{ L"Mostrar os segundos", L"Show seconds" },+{ L"Pergunte à Siri…", L"Ask Siri…" },diff --git a/src/comum/idioma_es.inc b/src/comum/idioma_es.incindex acd7ed7..e549f1f 100644--- a/src/comum/idioma_es.inc+++ b/src/comum/idioma_es.inc@@ -1689,3 +1689,4 @@{ L"Pegue a chave no site do serviço e use \"Colar chave\". A chave fica cifrada nesta conta do Windows, e as perguntas vão direto do PC para o serviço.", L"Obtén la clave en la web del servicio y usa \"Pegar clave\". La clave se cifra para esta cuenta de Windows y las preguntas van directamente del PC al servicio." },{ L"Roda no próprio PC: as perguntas não saem dele. Abra o app antes de perguntar.", L"Se ejecuta en este PC: tus preguntas no salen de él. Abre la app antes de preguntar." },{ L"Mostrar os segundos", L"Mostrar los segundos" },+{ L"Pergunte à Siri…", L"Pregunta a Siri…" },diff --git a/src/comum/idioma_fr.inc b/src/comum/idioma_fr.incindex b957a78..3e7c2b7 100644--- a/src/comum/idioma_fr.inc+++ b/src/comum/idioma_fr.inc@@ -1689,3 +1689,4 @@{ L"Pegue a chave no site do serviço e use \"Colar chave\". A chave fica cifrada nesta conta do Windows, e as perguntas vão direto do PC para o serviço.", L"Récupérez la clé sur le site du service et utilisez « Coller la clé ». La clé est chiffrée pour ce compte Windows, et les questions vont directement du PC au service." },{ L"Roda no próprio PC: as perguntas não saem dele. Abra o app antes de perguntar.", L"Fonctionne sur ce PC : vos questions n'en sortent pas. Ouvrez l'app avant de poser une question." },{ L"Mostrar os segundos", L"Afficher les secondes" },+{ L"Pergunte à Siri…", L"Demandez à Siri…" },diff --git a/src/comum/idioma_it.inc b/src/comum/idioma_it.incindex ddb0c97..fe34764 100644--- a/src/comum/idioma_it.inc+++ b/src/comum/idioma_it.inc@@ -1689,3 +1689,4 @@{ L"Pegue a chave no site do serviço e use \"Colar chave\". A chave fica cifrada nesta conta do Windows, e as perguntas vão direto do PC para o serviço.", L"Prendi la chiave dal sito del servizio e usa \"Incolla chiave\". La chiave è cifrata per questo account Windows e le domande vanno direttamente dal PC al servizio." },{ L"Roda no próprio PC: as perguntas não saem dele. Abra o app antes de perguntar.", L"Funziona su questo PC: le domande non escono da qui. Apri l'app prima di chiedere." },{ L"Mostrar os segundos", L"Mostra i secondi" },+{ L"Pergunte à Siri…", L"Chiedi a Siri…" },diff --git a/src/comum/idioma_ja.inc b/src/comum/idioma_ja.incindex 7997ef9..c5d2513 100644--- a/src/comum/idioma_ja.inc+++ b/src/comum/idioma_ja.inc@@ -1689,3 +1689,4 @@{ L"Pegue a chave no site do serviço e use \"Colar chave\". A chave fica cifrada nesta conta do Windows, e as perguntas vão direto do PC para o serviço.", L"サービスのサイトでキーを取得し、「キーをペースト」を使います。キーはこの Windows アカウント用に暗号化され、質問は PC から直接サービスに送られます。" },{ L"Roda no próprio PC: as perguntas não saem dele. Abra o app antes de perguntar.", L"この PC で動作します: 質問は PC の外に出ません。質問する前にアプリを開いてください。" },{ L"Mostrar os segundos", L"秒を表示" },+{ L"Pergunte à Siri…", L"Siri に聞く…" },diff --git a/src/comum/idioma_ko.inc b/src/comum/idioma_ko.incindex a0ac460..fa1131d 100644--- a/src/comum/idioma_ko.inc+++ b/src/comum/idioma_ko.inc@@ -1689,3 +1689,4 @@{ L"Pegue a chave no site do serviço e use \"Colar chave\". A chave fica cifrada nesta conta do Windows, e as perguntas vão direto do PC para o serviço.", L"서비스 웹사이트에서 키를 받아 \"키 붙여넣기\"를 사용하세요. 키는 이 Windows 계정용으로 암호화되며, 질문은 PC에서 서비스로 바로 전송됩니다." },{ L"Roda no próprio PC: as perguntas não saem dele. Abra o app antes de perguntar.", L"이 PC에서 실행됩니다: 질문이 PC 밖으로 나가지 않습니다. 질문하기 전에 앱을 여세요." },{ L"Mostrar os segundos", L"초 표시" },+{ L"Pergunte à Siri…", L"Siri에게 묻기…" },diff --git a/src/comum/idioma_pl.inc b/src/comum/idioma_pl.incindex b62e2f9..d812928 100644--- a/src/comum/idioma_pl.inc+++ b/src/comum/idioma_pl.inc@@ -1689,3 +1689,4 @@{ L"Pegue a chave no site do serviço e use \"Colar chave\". A chave fica cifrada nesta conta do Windows, e as perguntas vão direto do PC para o serviço.", L"Pobierz klucz ze strony usługi i użyj \"Wklej klucz\". Klucz jest szyfrowany dla tego konta Windows, a pytania trafiają prosto z komputera do usługi." },{ L"Roda no próprio PC: as perguntas não saem dele. Abra o app antes de perguntar.", L"Działa na tym komputerze: pytania go nie opuszczają. Otwórz aplikację przed pytaniem." },{ L"Mostrar os segundos", L"Pokazuj sekundy" },+{ L"Pergunte à Siri…", L"Zapytaj Siri…" },diff --git a/src/comum/idioma_ru.inc b/src/comum/idioma_ru.incindex 67e003e..6d93ad3 100644--- a/src/comum/idioma_ru.inc+++ b/src/comum/idioma_ru.inc@@ -1689,3 +1689,4 @@{ L"Pegue a chave no site do serviço e use \"Colar chave\". A chave fica cifrada nesta conta do Windows, e as perguntas vão direto do PC para o serviço.", L"Получите ключ на сайте сервиса и нажмите «Вставить ключ». Ключ шифруется для этой учётной записи Windows, а вопросы идут с ПК прямо в сервис." },{ L"Roda no próprio PC: as perguntas não saem dele. Abra o app antes de perguntar.", L"Работает на этом ПК: вопросы не покидают его. Откройте приложение перед вопросом." },{ L"Mostrar os segundos", L"Показывать секунды" },+{ L"Pergunte à Siri…", L"Спросите Siri…" },diff --git a/src/comum/idioma_tr.inc b/src/comum/idioma_tr.incindex 26ef37a..247602b 100644--- a/src/comum/idioma_tr.inc+++ b/src/comum/idioma_tr.inc@@ -1689,3 +1689,4 @@{ L"Pegue a chave no site do serviço e use \"Colar chave\". A chave fica cifrada nesta conta do Windows, e as perguntas vão direto do PC para o serviço.", L"Anahtarı hizmetin web sitesinden alın ve \"Anahtarı yapıştır\"ı kullanın. Anahtar bu Windows hesabı için şifrelenir ve sorular doğrudan bilgisayardan hizmete gider." },{ L"Roda no próprio PC: as perguntas não saem dele. Abra o app antes de perguntar.", L"Bu bilgisayarda çalışır: sorularınız dışarı çıkmaz. Sormadan önce uygulamayı açın." },{ L"Mostrar os segundos", L"Saniyeleri göster" },+{ L"Pergunte à Siri…", L"Siri'ye sorun…" },diff --git a/src/comum/idioma_zh.inc b/src/comum/idioma_zh.incindex e04c75f..6d737da 100644--- a/src/comum/idioma_zh.inc+++ b/src/comum/idioma_zh.inc@@ -1689,3 +1689,4 @@{ L"Pegue a chave no site do serviço e use \"Colar chave\". A chave fica cifrada nesta conta do Windows, e as perguntas vão direto do PC para o serviço.", L"在服务网站上获取密钥,然后使用\"粘贴密钥\"。密钥会为此 Windows 账户加密,问题会直接从电脑发送到服务。" },{ L"Roda no próprio PC: as perguntas não saem dele. Abra o app antes de perguntar.", L"在此电脑上运行:你的问题不会离开电脑。提问前请先打开应用。" },{ L"Mostrar os segundos", L"显示秒" },+{ L"Pergunte à Siri…", L"询问 Siri…" },diff --git a/src/shell/main.cpp b/src/shell/main.cppindex 254772a..afb65e3 100644--- a/src/shell/main.cpp+++ b/src/shell/main.cpp@@ -1,507 +1,507 @@-// Shell.exe: barra de menus + Dock + bandeja no estilo do macOS Sequoia, por cima do Explorador.-// Enquanto roda, esconde a barra de tarefas do Windows e ajusta a área de trabalho; ao sair-// (menu do logo → Sair do Shell, Ctrl+Alt+Shift+F12, ou erro), devolve tudo como estava.-#include "shell.h"-#include "../comum/simbolos.h"-#include "../comum/ajustes_arquivo.h"-#include "../menu/context_menu.h"-#include <shlobj.h>-#include <dwmapi.h>-#include <share.h>-#include <cstdarg>-#include <map>-#include <thread>-#include <atomic>-#include <mutex>-#include <condition_variable>-#include <mmsystem.h>-#pragma comment(lib, "winmm.lib")--HINSTANCE shell::inst;-std::wstring shell::dir;-bool shell::nativo;--DWORD shell::SemProprio() { return nativo ? 0 : WINEVENT_SKIPOWNPROCESS; }--// Gancho global (WH_MOUSE_LL / WH_KEYBOARD_LL): o Windows segura cada tecla e cada clique do PC INTEIRO até a thread do-// gancho responder. Numa CPU fraca e ocupada (i3, notebook na bateria) uma thread de prioridade normal esperava a vez-// atrás do resto e o ponteiro/teclado engasgavam (issues #10 e #33). No modo jogo o processo vai para o EcoQoS (núcleos-// lentos, jogo.cpp): a thread do gancho fica fora dele, senão cada tecla do jogo esperava um núcleo de eficiência acordar.-void shell::ThreadDeGancho() {- SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);- THREAD_POWER_THROTTLING_STATE s{ THREAD_POWER_THROTTLING_CURRENT_VERSION, THREAD_POWER_THROTTLING_EXECUTION_SPEED, 0 };- SetThreadInformation(GetCurrentThread(), ThreadPowerThrottling, &s, sizeof(s));-}--// Janela do próprio Shell. Fora do modo nativo: qualquer janela deste processo. No nativo o processo é o-// explorer.exe: as janelas dele (pastas, Executar, avisos de copiar/apagar) são de app; nossas são só as-// criadas com o módulo do Shell (a MacBarra.dll).-bool shell::Nossa(HWND h) {- DWORD pid = 0; GetWindowThreadProcessId(h, &pid);- if (pid != GetCurrentProcessId()) return false;- if (!nativo) return true;- return (HINSTANCE)GetWindowLongPtrW(h, GWLP_HINSTANCE) == inst || apps::IsShellWindow(h);-}--static FILE* g_log;-static HWND g_msg;-static UINT WM_SHELLHOOK;-static RECT g_origWork;-static std::vector<HWND> g_hiddenBars;-static std::map<std::wstring, std::wstring> g_settings;-static bool g_quitting;-static bool g_crashed, g_sessionEnding; // Restore() sem abrir o Explorador (o vigia ou o logoff cuidam)--// ---- tecla Windows: sozinha abre o Launchpad; com outra tecla (Win+E, Win+D, Win+L...) segue para o-// Windows normalmente. O gancho roda numa thread própria para nunca atrasar o teclado.-const ULONG_PTR KEY_MARK = 0x53484C4C; // teclas que nós mesmos injetamos-const UINT WM_APP_LAUNCHPAD = WM_APP + 30, WM_APP_SETTINGS = WM_APP + 31, WM_APP_MISSION = WM_APP + 32, WM_APP_SNAP = WM_APP + 33, WM_APP_SPOTLIGHT = WM_APP + 34, WM_APP_MONITOR = WM_APP + 35, WM_APP_SWITCH = WM_APP + 36, WM_APP_SWITCH_KEY = WM_APP + 37, WM_APP_SWITCH_END = WM_APP + 38;-static std::atomic<bool> g_altTab; // seletor de apps aberto (Alt seguro desde o primeiro Tab)-static HHOOK g_kbHook;-static bool g_winDown, g_winCombo, g_winEaten, g_spaceHeld, g_tabHeld; // eaten: a combinação foi nossa (Win+I)-static DWORD g_winVk, g_winAt; // At: quando a tecla Win desceu (ms do gancho)-static bool g_winPassed; // uma tecla de combinação foi para o Windows (Win+V, Win+.): ele não abre o Iniciar ao soltar---static void Inject(DWORD vk, bool up) {- INPUT in{ INPUT_KEYBOARD };- in.ki.wVk = (WORD)vk;- in.ki.dwFlags = (up ? KEYEVENTF_KEYUP : 0) | (vk == VK_LWIN || vk == VK_RWIN ? KEYEVENTF_EXTENDEDKEY : 0);- in.ki.dwExtraInfo = KEY_MARK;- SendInput(1, &in, sizeof(in));-}--const UINT WM_APP_LOCK = WM_APP + 39, WM_APP_WINKEY = WM_APP + 40, WM_APP_CAPTURA = WM_APP + 41;-static bool g_capturaExe; // WacOSScreenshot.exe existe: Win+Shift+3/4/5/S são dela-// Win+Q / Win+H / Win+W = Cmd+Q / Cmd+H / Cmd+W do Mac (encerrar o app, ocultar, fechar a janela).-// Ajustes > Teclado > "Atalhos do Mac para apps" (atalhos_mac); desligado, os atalhos voltam ao Windows-const UINT WM_APP_MACKEY = WM_APP + 43;-const UINT WM_APP_EXPOSE = WM_APP + 44; // Ctrl+Win+↓: Exposé do app da frente (Ctrl+↓ no Mac)-static volatile bool g_macKeys = true;-static DWORD g_macKeyVk; // a tecla do atalho: soltar também é nosso (o app não vê uma letra solta)-static DWORD g_capKey; // tecla do atalho da Captura de Tela ainda segurada-static bool g_fullHook = true; // false: o gancho só existe para a tela de bloqueio (tecla Windows do Launchpad desligada)-const UINT WM_APP_VOLUME = WM_APP + 42;-static bool g_volumeKeys = true; // ajuste volume_mac: teclas de volume com o aviso do Mac (0 = o Windows trata)--static LRESULT CALLBACK KeyHook(int code, WPARAM w, LPARAM l) {- if (code == HC_ACTION && w == WM_KEYDOWN && ((KBDLLHOOKSTRUCT*)l)->vkCode == VK_CAPITAL) ilha::CapsLock(); // Ilha Dinâmica: aviso do Caps Lock- if (code == HC_ACTION && g_volumeKeys && !bloqueio::Active()) {- // teclas de volume (Fn + F-teclas): o Shell muda o volume em 16 passos e mostra o aviso do Mac- // (o painel do Windows não aparece). Só essas três teclas: os atalhos Ctrl+Alt+Shift+F11/F12 seguem livres.- auto* k = (KBDLLHOOKSTRUCT*)l;+// Shell.exe: barra de menus + Dock + bandeja no estilo do macOS Sequoia, por cima do Explorador.+// Enquanto roda, esconde a barra de tarefas do Windows e ajusta a área de trabalho; ao sair+// (menu do logo → Sair do Shell, Ctrl+Alt+Shift+F12, ou erro), devolve tudo como estava.+#include "shell.h"+#include "../comum/simbolos.h"+#include "../comum/ajustes_arquivo.h"+#include "../menu/context_menu.h"+#include <shlobj.h>+#include <dwmapi.h>+#include <share.h>+#include <cstdarg>+#include <map>+#include <thread>+#include <atomic>+#include <mutex>+#include <condition_variable>+#include <mmsystem.h>+#pragma comment(lib, "winmm.lib")++HINSTANCE shell::inst;+std::wstring shell::dir;+bool shell::nativo;++DWORD shell::SemProprio() { return nativo ? 0 : WINEVENT_SKIPOWNPROCESS; }++// Gancho global (WH_MOUSE_LL / WH_KEYBOARD_LL): o Windows segura cada tecla e cada clique do PC INTEIRO até a thread do+// gancho responder. Numa CPU fraca e ocupada (i3, notebook na bateria) uma thread de prioridade normal esperava a vez+// atrás do resto e o ponteiro/teclado engasgavam (issues #10 e #33). No modo jogo o processo vai para o EcoQoS (núcleos+// lentos, jogo.cpp): a thread do gancho fica fora dele, senão cada tecla do jogo esperava um núcleo de eficiência acordar.+void shell::ThreadDeGancho() {+ SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);+ THREAD_POWER_THROTTLING_STATE s{ THREAD_POWER_THROTTLING_CURRENT_VERSION, THREAD_POWER_THROTTLING_EXECUTION_SPEED, 0 };+ SetThreadInformation(GetCurrentThread(), ThreadPowerThrottling, &s, sizeof(s));+}++// Janela do próprio Shell. Fora do modo nativo: qualquer janela deste processo. No nativo o processo é o+// explorer.exe: as janelas dele (pastas, Executar, avisos de copiar/apagar) são de app; nossas são só as+// criadas com o módulo do Shell (a MacBarra.dll).+bool shell::Nossa(HWND h) {+ DWORD pid = 0; GetWindowThreadProcessId(h, &pid);+ if (pid != GetCurrentProcessId()) return false;+ if (!nativo) return true;+ return (HINSTANCE)GetWindowLongPtrW(h, GWLP_HINSTANCE) == inst || apps::IsShellWindow(h);+}++static FILE* g_log;+static HWND g_msg;+static UINT WM_SHELLHOOK;+static RECT g_origWork;+static std::vector<HWND> g_hiddenBars;+static std::map<std::wstring, std::wstring> g_settings;+static bool g_quitting;+static bool g_crashed, g_sessionEnding; // Restore() sem abrir o Explorador (o vigia ou o logoff cuidam)++// ---- tecla Windows: sozinha abre o Launchpad; com outra tecla (Win+E, Win+D, Win+L...) segue para o+// Windows normalmente. O gancho roda numa thread própria para nunca atrasar o teclado.+const ULONG_PTR KEY_MARK = 0x53484C4C; // teclas que nós mesmos injetamos+const UINT WM_APP_LAUNCHPAD = WM_APP + 30, WM_APP_SETTINGS = WM_APP + 31, WM_APP_MISSION = WM_APP + 32, WM_APP_SNAP = WM_APP + 33, WM_APP_SPOTLIGHT = WM_APP + 34, WM_APP_MONITOR = WM_APP + 35, WM_APP_SWITCH = WM_APP + 36, WM_APP_SWITCH_KEY = WM_APP + 37, WM_APP_SWITCH_END = WM_APP + 38;+static std::atomic<bool> g_altTab; // seletor de apps aberto (Alt seguro desde o primeiro Tab)+static HHOOK g_kbHook;+static bool g_winDown, g_winCombo, g_winEaten, g_spaceHeld, g_tabHeld; // eaten: a combinação foi nossa (Win+I)+static DWORD g_winVk, g_winAt; // At: quando a tecla Win desceu (ms do gancho)+static bool g_winPassed; // uma tecla de combinação foi para o Windows (Win+V, Win+.): ele não abre o Iniciar ao soltar+++static void Inject(DWORD vk, bool up) {+ INPUT in{ INPUT_KEYBOARD };+ in.ki.wVk = (WORD)vk;+ in.ki.dwFlags = (up ? KEYEVENTF_KEYUP : 0) | (vk == VK_LWIN || vk == VK_RWIN ? KEYEVENTF_EXTENDEDKEY : 0);+ in.ki.dwExtraInfo = KEY_MARK;+ SendInput(1, &in, sizeof(in));+}++const UINT WM_APP_LOCK = WM_APP + 39, WM_APP_WINKEY = WM_APP + 40, WM_APP_CAPTURA = WM_APP + 41;+static bool g_capturaExe; // WacOSScreenshot.exe existe: Win+Shift+3/4/5/S são dela+// Win+Q / Win+H / Win+W = Cmd+Q / Cmd+H / Cmd+W do Mac (encerrar o app, ocultar, fechar a janela).+// Ajustes > Teclado > "Atalhos do Mac para apps" (atalhos_mac); desligado, os atalhos voltam ao Windows+const UINT WM_APP_MACKEY = WM_APP + 43;+const UINT WM_APP_EXPOSE = WM_APP + 44; // Ctrl+Win+↓: Exposé do app da frente (Ctrl+↓ no Mac)+static volatile bool g_macKeys = true;+static DWORD g_macKeyVk; // a tecla do atalho: soltar também é nosso (o app não vê uma letra solta)+static DWORD g_capKey; // tecla do atalho da Captura de Tela ainda segurada+static bool g_fullHook = true; // false: o gancho só existe para a tela de bloqueio (tecla Windows do Launchpad desligada)+const UINT WM_APP_VOLUME = WM_APP + 42;+static bool g_volumeKeys = true; // ajuste volume_mac: teclas de volume com o aviso do Mac (0 = o Windows trata)++static LRESULT CALLBACK KeyHook(int code, WPARAM w, LPARAM l) {+ if (code == HC_ACTION && w == WM_KEYDOWN && ((KBDLLHOOKSTRUCT*)l)->vkCode == VK_CAPITAL) ilha::CapsLock(); // Ilha Dinâmica: aviso do Caps Lock+ if (code == HC_ACTION && g_volumeKeys && !bloqueio::Active()) {+ // teclas de volume (Fn + F-teclas): o Shell muda o volume em 16 passos e mostra o aviso do Mac+ // (o painel do Windows não aparece). Só essas três teclas: os atalhos Ctrl+Alt+Shift+F11/F12 seguem livres.+ auto* k = (KBDLLHOOKSTRUCT*)l;// F14/F15: as teclas de brilho do teclado do Mac (e um atalho para teclados de PC com teclas programáveis); issue #38if (k->dwExtraInfo != KEY_MARK && (k->vkCode == VK_F14 || k->vkCode == VK_F15)) {if (w == WM_KEYDOWN || w == WM_SYSKEYDOWN) PostMessageW(g_msg, WM_APP_VOLUME, k->vkCode, 0);return 1;}- if (k->dwExtraInfo != KEY_MARK && (k->vkCode == VK_VOLUME_UP || k->vkCode == VK_VOLUME_DOWN || k->vkCode == VK_VOLUME_MUTE)) {- if (w == WM_KEYDOWN || w == WM_SYSKEYDOWN) {- bool fine = GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_MENU) < 0;- PostMessageW(g_msg, WM_APP_VOLUME, k->vkCode, fine);- }- return 1;- }- }- if (code == HC_ACTION && bloqueio::Active()) {- // tela travada: nada de Iniciar, Alt+Tab, Ctrl+Esc, Alt+Esc, Alt+F4, Ctrl+Shift+Esc (Ctrl+Alt+Del não dá para barrar)- auto* k = (KBDLLHOOKSTRUCT*)l;- bool alt = (k->flags & LLKHF_ALTDOWN) != 0, ctrl = GetAsyncKeyState(VK_CONTROL) < 0;- DWORD vk = k->vkCode;- if (vk == VK_LWIN || vk == VK_RWIN || vk == VK_APPS) { g_winDown = false; return 1; }- if ((alt && (vk == VK_TAB || vk == VK_ESCAPE || vk == VK_F4 || vk == VK_SPACE)) || (ctrl && vk == VK_ESCAPE)) return 1;- g_altTab = false;- return CallNextHookEx(g_kbHook, code, w, l);- }- if (!g_fullHook) return CallNextHookEx(g_kbHook, code, w, l);- if (code == HC_ACTION) {- auto* k = (KBDLLHOOKSTRUCT*)l;- if (k->dwExtraInfo != KEY_MARK) {- bool down = w == WM_KEYDOWN || w == WM_SYSKEYDOWN;- bool win = k->vkCode == VK_LWIN || k->vkCode == VK_RWIN;- if (win) {- auto mods = [] { return GetAsyncKeyState(VK_CONTROL) < 0 || GetAsyncKeyState(VK_SHIFT) < 0 || GetAsyncKeyState(VK_MENU) < 0; };- if (shell::nativo) {- // modo nativo (dentro do explorer): a tecla segue para o Windows; o atalho reinjetado daqui não- // valia (Win+R não abria). Sozinha, ao soltar, abre o Launchpad- if (down) {- if (!g_winDown) { g_winDown = true; g_winCombo = mods(); g_winEaten = false; g_spaceHeld = false; g_tabHeld = false; g_winVk = k->vkCode; g_winAt = k->time; }- } else if (g_winDown) {- g_winDown = false;- if (!g_winCombo && k->time - g_winAt <= 1000) PostMessageW(g_msg, WM_APP_LAUNCHPAD, 0, 0);- }- return CallNextHookEx(g_kbHook, code, w, l);- }- // A tecla segue para o Windows desde que desce (como no modo nativo): AltSnap e afins (Win + arrastar) a veem- // segurada, sem atraso e sem o Shell mexer no clique (issue #21: segurar o clique e devolver dava um tranco,- // o cursor não mudava e o clique direito às vezes travava). Os nossos atalhos (Win+Espaço, Win+I...) comem só a- // letra. Ao soltar, a tecla muda (0xE8) antes do Win: o Windows não vê um Win "sozinho" e o Iniciar não abre.- if (down) {- if (!g_winDown) {- g_winDown = true; g_winCombo = mods(); g_winEaten = false; g_spaceHeld = false; g_tabHeld = false; g_winVk = k->vkCode; g_winAt = k->time;- g_winPassed = false;- }- return CallNextHookEx(g_kbHook, code, w, l);- }- if (g_winDown) {- g_winDown = false;- if (!g_winCombo && k->time - g_winAt <= 1000) PostMessageW(g_msg, WM_APP_LAUNCHPAD, 0, 0); // sozinha: Launchpad/Spotlight- // Combinação que foi para o Windows (Win+V, Win+.): ele mesmo não abre o Iniciar, e a tecla muda chegava- // ao painel que acabou de abrir: o histórico da Área de Transferência piscava e fechava (issue #27, 22/11/2026)- if (g_winPassed && !g_winEaten) return CallNextHookEx(g_kbHook, code, w, l);- // a tecla muda e o soltar do Win vão juntos, nesta ordem: deixando o soltar de verdade passar, a muda- // (mandada daqui de dentro) chegava depois dele e o Iniciar abria- Inject(0xE8, false); Inject(0xE8, true);- Inject(k->vkCode, true);- return 1;- }- return CallNextHookEx(g_kbHook, code, w, l);- } else if (k->vkCode == VK_TAB && down && !g_winDown && GetAsyncKeyState(VK_MENU) < 0 && GetAsyncKeyState(VK_CONTROL) >= 0) {- // Alt+Tab: o seletor de apps do Mac no lugar do Alternar Tarefas do Windows. A tecla "muda"- // (0xE8) evita que o app da frente veja um Alt sozinho ao soltar e abra o menu dele- if (!g_altTab) { Inject(0xE8, false); Inject(0xE8, true); }- g_altTab = true;- PostMessageW(g_msg, WM_APP_SWITCH, GetAsyncKeyState(VK_SHIFT) < 0 ? (WPARAM)-1 : 1, 0);- return 1;- } else if (g_altTab && down && (k->vkCode == 'Q' || k->vkCode == 'H' || k->vkCode == VK_ESCAPE || k->vkCode == VK_LEFT || k->vkCode == VK_RIGHT)) {- if (k->vkCode == VK_ESCAPE) g_altTab = false;- PostMessageW(g_msg, WM_APP_SWITCH_KEY, k->vkCode, 0);- return 1;- } else if (g_altTab && !down && (k->vkCode == VK_LMENU || k->vkCode == VK_RMENU || k->vkCode == VK_MENU)) {- g_altTab = false;- PostMessageW(g_msg, WM_APP_SWITCH_END, 0, 0); // o Alt solto segue para o Windows normalmente- } else if (k->vkCode == VK_ESCAPE && down && GetAsyncKeyState(VK_CONTROL) < 0 && GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_MENU) >= 0) {- // Ctrl+Shift+Esc: o nosso Monitor de Atividade no lugar do Gerenciador de Tarefas- PostMessageW(g_msg, WM_APP_MONITOR, 0, 0);- return 1;- } else if (k->vkCode == VK_ESCAPE && down && GetAsyncKeyState(VK_CONTROL) < 0 && GetAsyncKeyState(VK_MENU) < 0 && GetAsyncKeyState(VK_SHIFT) >= 0) {- // Ctrl+Alt+Esc: Forçar Encerrar Aplicativos (Command+Option+Esc do Mac)- PostMessageW(g_msg, WM_APP_MONITOR, 1, 0);- return 1;- } else if (k->vkCode == VK_SPACE && g_winDown && (!g_winCombo || g_winEaten)) {- // Win+Espaço: o Spotlight (Cmd+Espaço no Mac; no Windows trocaria o idioma do teclado).- // Segurando o Win, cada Espaço abre/fecha de novo; repetição de tecla segurada não conta e- // nenhum Espaço chega ao app de baixo- if (down && !g_spaceHeld) PostMessageW(g_msg, WM_APP_SPOTLIGHT, 0, 0);- g_spaceHeld = down;- g_winCombo = g_winEaten = true;- return 1;- } else if (k->vkCode == VK_TAB && g_winDown && (!g_winCombo || g_winEaten)) {- // Win+Tab: o Mission Control (no lugar da Visão de Tarefas). Segurando o Win, cada Tab abre/fecha- // de novo (igual ao Espaço); repetição de tecla segurada não conta- if (down && !g_tabHeld) PostMessageW(g_msg, WM_APP_MISSION, 0, 0);- g_tabHeld = down;- g_winCombo = g_winEaten = true;- return 1;- } else if (g_winDown && down && (k->vkCode == VK_F12 || k->vkCode == VK_F8) && liquid::Leopard()) {- // Leopard: Win+F12 = Dashboard (o F12 do Mac), Win+F8 = Spaces (o F8 do Mac). Só com o Win: o F12 sozinho- // continua dos apps (ferramentas do navegador)- static UINT openPanel = RegisterWindowMessageW(L"ShellAbrirPainel");- PostMessageW(g_msg, openPanel, k->vkCode == VK_F12 ? 16 : 17, 0);- g_winCombo = g_winEaten = true;- return 1;- } else if (g_winDown && down && !g_winCombo && (k->vkCode == 'I' || k->vkCode == VK_TAB)) {- // Win+I: o nosso Ajustes do Sistema; Win+Tab: o Mission Control (no lugar da Visão de Tarefas)- g_winCombo = g_winEaten = true;- PostMessageW(g_msg, k->vkCode == VK_TAB ? WM_APP_MISSION : WM_APP_SETTINGS, 0, 0);- return 1;- } else if (!shell::nativo && g_winDown && down && (k->vkCode == VK_LEFT || k->vkCode == VK_RIGHT) && GetAsyncKeyState(VK_CONTROL) >= 0 &&- GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_MENU) >= 0) {- // Win+←/→: metade da tela (o encaixe do Windows fica desligado enquanto o Shell roda: encaixe.cpp)- if (!g_winCombo) g_winCombo = g_winEaten = true;- PostMessageW(g_msg, WM_APP_SNAP, k->vkCode, 0);- return 1;- } else if (g_winDown && down && !g_winCombo && (k->vkCode == VK_UP || k->vkCode == VK_DOWN) &&- GetPropW(GetForegroundWindow(), L"MacJanela")) {- // Win+↑/↓ em janela com a barra do Mac: sem o botão de maximizar o Windows ignora; fazemos nós- g_winCombo = g_winEaten = true;- PostMessageW(g_msg, WM_APP_SNAP, k->vkCode, 0);- return 1;- } else if (!shell::nativo && g_winDown && down && k->vkCode == 'Q' && GetAsyncKeyState(VK_CONTROL) < 0 && GetAsyncKeyState(VK_MENU) >= 0) {- // Ctrl+Win+Q: o atalho do Mac (Control+Command+Q) para bloquear (o bloqueio do Windows)- if (!g_winCombo) g_winCombo = g_winEaten = true;- PostMessageW(g_msg, WM_APP_LOCK, 0, 0);- return 1;- } else if (g_winDown && (k->vkCode == VK_UP || k->vkCode == VK_DOWN) && GetAsyncKeyState(VK_CONTROL) < 0 &&- GetAsyncKeyState(VK_MENU) >= 0 && GetAsyncKeyState(VK_SHIFT) >= 0) {- // Ctrl+Win+↑ / ↓ = Ctrl+↑ / ↓ do Mac: Mission Control / Exposé do app da frente (Ctrl+Win+←/→- // já trocam de Mesa, como Ctrl+←/→ no Mac). A repetição da tecla segurada não abre de novo- if (down && g_macKeyVk != k->vkCode) PostMessageW(g_msg, k->vkCode == VK_UP ? WM_APP_MISSION : WM_APP_EXPOSE, 0, 0);- g_macKeyVk = down ? k->vkCode : 0;- if (!g_winCombo) g_winCombo = g_winEaten = true;- return 1;- } else if (g_macKeyVk && k->vkCode == g_macKeyVk && !down) {- g_macKeyVk = 0;- return 1;- } else if (g_macKeys && g_winDown && down && (!g_winCombo || g_winEaten) && (k->vkCode == 'Q' || k->vkCode == 'H' || k->vkCode == 'W') &&- GetAsyncKeyState(VK_CONTROL) >= 0 && GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_MENU) >= 0) {- // Win+Q encerra o app da frente, Win+H oculta, Win+W fecha a janela (como Cmd no Mac). Segurando o- // Win, cada toque vale de novo; a repetição da tecla segurada não conta- if (g_macKeyVk != k->vkCode) PostMessageW(g_msg, WM_APP_MACKEY, k->vkCode, 0);- g_macKeyVk = k->vkCode;- g_winCombo = g_winEaten = true;- return 1;- } else if (g_capKey && k->vkCode == g_capKey && !down) {- g_capKey = 0; // fim do atalho da Captura de Tela: a tecla solta também é nossa- return 1;- } else if (g_winDown && down && GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_MENU) >= 0 &&- (k->vkCode == '3' || k->vkCode == '4' || k->vkCode == '5' || k->vkCode == 'S') && g_capturaExe) {- // Win+Shift+3/4/5 (Cmd+Shift+3/4/5 do Mac) e Win+Shift+S: a nossa Captura de Tela- // (WacOSScreenshot.exe) no lugar da Ferramenta de Captura; com Ctrl, só área de transferência.- // A tecla segurada (repetição) não abre de novo; a tecla muda (0xE8) faz o Windows não ver- // um Win sozinho ao soltar (o Win e o Shift já foram devolvidos a ele: combinação)- if (g_capKey != k->vkCode) {- g_capKey = k->vkCode;- Inject(0xE8, false); Inject(0xE8, true);- int kind = k->vkCode == 'S' ? 4 : (int)(k->vkCode - '0');- PostMessageW(g_msg, WM_APP_CAPTURA, kind, GetAsyncKeyState(VK_CONTROL) < 0 ? 1 : 0);- }- return 1;- } else if (g_winDown && down && k->vkCode == 'S' && GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_CONTROL) >= 0 && mesa::Standalone()) {- // Win+Shift+S sem a nossa Captura de Tela: a Ferramenta de Captura do Windows (quem atende é- // o Explorador quando ele é o shell; sem ele, fazemos nós)- PostMessageW(g_msg, WM_APP_WINKEY, 'S', 0);- return 1;- } else if (g_winDown && down && !g_winCombo && !shell::nativo && k->vkCode == 'E' && GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_CONTROL) >= 0) {- // Win+E com o Explorador rodando (explorer=fundo): ele abria a página "Início" dele, que não é pasta de- // disco e o Finder não trocava (17/11/2026). O Shell atende sempre: Finder (ou o Explorador, se- // "Abrir pastas no Finder" estiver desligado — mesa::WinKey decide)- g_winCombo = g_winEaten = true;- PostMessageW(g_msg, WM_APP_WINKEY, 'E', 0);- return 1;- } else if (g_winDown && down && !g_winCombo && !shell::nativo && k->vkCode == 'D') {- // Win+D é sempre nosso: com o Explorador de fundo, o "mostrar a área de trabalho" dele punha a mesa- // DELE na frente e a nossa voltava por cima em seguida (piscava, os widgets sumiam e voltavam)- g_winCombo = g_winEaten = true;- PostMessageW(g_msg, WM_APP_WINKEY, 'D', 0);- return 1;- } else if (g_winDown && down && !g_winCombo && mesa::Standalone() && (k->vkCode == 'E' || k->vkCode == 'R' || k->vkCode == 'D')) {- // sem o Explorador ninguém trata Win+E/R/D: fazemos nós (Finder, Executar, mostrar a mesa)- g_winCombo = g_winEaten = true;- PostMessageW(g_msg, WM_APP_WINKEY, k->vkCode, 0);- return 1;- } else if (g_winDown && down && !g_winCombo && shell::nativo) {- g_winCombo = true; // nativo: a tecla Windows já foi para o Windows; esta segue também- } else if (g_winDown && down && !g_winCombo) {- // combinação do Windows: a tecla Win já foi para ele; esta segue também- g_winCombo = true;- g_winPassed = true;- }- }- }- return CallNextHookEx(g_kbHook, code, w, l);-}--static void KeyThread() {- shell::ThreadDeGancho();- g_kbHook = SetWindowsHookExW(WH_KEYBOARD_LL, KeyHook, GetModuleHandleW(nullptr), 0);- MSG m;- while (GetMessageW(&m, nullptr, 0, 0)) {}- if (g_kbHook) UnhookWindowsHookEx(g_kbHook);-}--// O log vai para o disco numa thread própria. Gravando direto (fwprintf + fflush a cada linha), a thread da interface-// ficava presa no WriteFile quando o disco demorava (torrent, antivírus, agente de monitoramento): o vigia via o Shell-// sem responder por 5 s e o reiniciava, várias vezes seguidas (22/11/2026: as duas pilhas tiradas no travamento-// estavam no Log -> fflush -> WriteFile, chamado pelo vidro real).-static std::mutex g_logMx, g_logDisco;-static std::condition_variable g_logCv;-static std::wstring g_logFila;-static void LogGrava() { // o que está na fila vai para o arquivo (só uma thread grava de cada vez)- std::wstring s;- { std::lock_guard<std::mutex> l(g_logMx); s.swap(g_logFila); }- if (s.empty() || !g_log) return;- std::lock_guard<std::mutex> d(g_logDisco);- fputws(s.c_str(), g_log); fflush(g_log);-}-static void EsperaAjustes();-static void LogDescarrega() { EsperaAjustes(); LogGrava(); } // fim do Shell: o que faltou vai junto (log e ajustes.txt)--void Log(const wchar_t* fmt, ...) {- if (!g_log) return;- SYSTEMTIME st; GetLocalTime(&st);- wchar_t pre[16]; swprintf_s(pre, L"%02d:%02d:%02d ", st.wHour, st.wMinute, st.wSecond);- va_list a; va_start(a, fmt);- va_list b; va_copy(b, a);- int n = _vscwprintf(fmt, a);- std::wstring linha;- if (n > 0) { linha.resize((size_t)n + 1); vswprintf_s(linha.data(), linha.size(), fmt, b); linha.resize((size_t)n); }- va_end(b); va_end(a);- static std::once_flag once;- std::call_once(once, [] {- std::thread([] {- for (;;) {- { std::unique_lock<std::mutex> l(g_logMx); g_logCv.wait(l, [] { return !g_logFila.empty(); }); }- LogGrava();- }- }).detach();- });- {- std::lock_guard<std::mutex> l(g_logMx);- if (g_logFila.size() < 4 * 1024 * 1024) { g_logFila += pre; g_logFila += linha; g_logFila += L'\n'; } // disco parado de vez: não cresce sem fim- }- g_logCv.notify_one();-}--// g_settings é lido de várias threads (vidro, índice, ilha, widgets...) enquanto a interface relê o arquivo-// (LoadSettings troca o mapa inteiro): sem trava, a leitura podia pegar o mapa no meio da troca e derrubar o Shell-static SRWLOCK g_settingsLock = SRWLOCK_INIT;-std::wstring shell::Setting(const wchar_t* key, const wchar_t* def) {- AcquireSRWLockShared(&g_settingsLock);- auto it = g_settings.find(key);- std::wstring r = it != g_settings.end() ? it->second : (def ? def : L"");- ReleaseSRWLockShared(&g_settingsLock);- return r;-}--static std::wstring SettingsPath() {- PWSTR p = nullptr;- std::wstring f;- if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) { f = std::wstring(p) + L"\\Shell"; CoTaskMemFree(p); }- CreateDirectoryW(f.c_str(), nullptr);- return f + L"\\ajustes.txt";-}--// O ajustes.txt vai para o disco numa thread (como o log). Gravando aqui, cada mudança (Dock, Central de Controle,-// Launchpad, widgets...) esperava o disco na thread da interface: num HD com o antivírus olhando, 20 a 200 ms de tela-// parada a cada clique (issue #10, Core i3 com HD). O valor vale na hora (g_settings); o arquivo segue logo depois, e-// várias mudanças seguidas viram uma gravação só. Quem relê o arquivo (LoadSettings) e a saída do Shell esperam a fila.-static std::mutex g_ajMx;-static std::condition_variable g_ajCv;-static std::map<std::wstring, std::wstring> g_ajMapa; // os ajustes inteiros a gravar (os mais novos)-static bool g_ajTem = false, g_ajOcupado = false;-static void EsperaAjustes() {- std::unique_lock<std::mutex> l(g_ajMx);- g_ajCv.wait_for(l, std::chrono::seconds(3), [] { return !g_ajTem && !g_ajOcupado; });-}-void shell::SetSetting(const wchar_t* key, const std::wstring& value) {- std::map<std::wstring, std::wstring> copia;- AcquireSRWLockExclusive(&g_settingsLock);- g_settings[key] = value;- copia = g_settings;- ReleaseSRWLockExclusive(&g_settingsLock);- // na thread de gravação, atômico (.tmp + troca): quem lê no meio não vê o arquivo vazio- { std::lock_guard<std::mutex> l(g_ajMx); g_ajMapa = std::move(copia); g_ajTem = true; }- static std::once_flag umaVez;- std::call_once(umaVez, [] {- std::thread([] {- for (;;) {- std::map<std::wstring, std::wstring> m;- {- std::unique_lock<std::mutex> l(g_ajMx);- g_ajCv.wait(l, [] { return g_ajTem; });- m.swap(g_ajMapa); g_ajTem = false; g_ajOcupado = true;- }- ajarq::Gravar(SettingsPath(), m);- { std::lock_guard<std::mutex> l(g_ajMx); g_ajOcupado = false; }- g_ajCv.notify_all();- }- }).detach();- });- g_ajCv.notify_all();-}--// Calculadora (Calculadora.exe) no lugar da Calculadora do Windows: Launchpad, Spotlight e Dock passam-// o alvo (AUMID, atalho ou .exe) por aqui. Sem o Calculadora.exe, segue a do Windows (devolve false).-bool shell::OpenCalculator(const std::wstring& target) {- std::wstring t = target;- for (auto& c : t) c = towlower(c);- auto ends = [&](const wchar_t* s) { size_t n = wcslen(s); return t.size() >= n && t.compare(t.size() - n, n, s) == 0; };- bool calc = t.find(L"microsoft.windowscalculator") != std::wstring::npos || t == L"calc.exe" || t == L"calc" ||- ends(L"\\calc.exe") || ends(L"calculatorapp.exe") || ends(L"\\calculadora.exe") || ends(L"\\wacoscalculator.exe");- if (!calc) return false;- std::wstring exe = shell::dir + L"\\" EXE_CALCULATOR;- if (GetFileAttributesW(exe.c_str()) == INVALID_FILE_ATTRIBUTES) return false;- shell::Abrir(L"open", exe.c_str());- return true;-}--// Monitor de Atividade (MonitorAtividade.exe); sem ele, o Gerenciador de Tarefas do Windows-void shell::OpenMonitor() {- std::wstring exe = shell::dir + L"\\" EXE_MONITOR;- if (GetFileAttributesW(exe.c_str()) == INVALID_FILE_ATTRIBUTES) exe = L"taskmgr.exe";- shell::Abrir(L"open", exe.c_str(), nullptr, nullptr, SW_SHOWNORMAL);-}--// Forçar Encerrar Aplicativos (WacOSForceQuit.exe); sem ele, o Monitor de Atividade-void shell::OpenForceQuit(bool memory) {- std::wstring exe = shell::dir + L"\\" EXE_FORCEQUIT;- if (GetFileAttributesW(exe.c_str()) == INVALID_FILE_ATTRIBUTES) { shell::OpenMonitor(); return; }- AllowSetForegroundWindow(ASFW_ANY); // aberta pela pressão de memória, sem clique: precisa vir para a frente- shell::Abrir(L"open", exe.c_str(), memory ? L"--memoria" : nullptr, nullptr, SW_SHOWNORMAL);-}--void shell::Sound(const wchar_t* name) {- std::wstring root = shell::dir.substr(0, shell::dir.find_last_of(L'\\')); // a pasta do projeto (bin fica dentro dela)- PlaySoundW((root + L"\\sons\\mac\\" + name + L".wav").c_str(), nullptr, SND_FILENAME | SND_ASYNC | SND_NODEFAULT);-}--void shell::OpenSettings(const std::wstring& page) {- std::wstring args = page.empty() ? L"" : (page.rfind(L"ms-settings:", 0) == 0 ? page : L"--pagina=" + page);- shell::Abrir(L"open", (shell::dir + L"\\" EXE_SETTINGS).c_str(), args.c_str());-}--// ShellExecute numa thread: na thread da interface ele chegou a segurar o Shell 3,2 s (abrir o Ajustes pela Ilha com o-// disco ocupado; pilha de 22/11/2026 19:54, issue #32). A thread espera o ShellExecute terminar (SEE_MASK_NOASYNC).-void shell::Abrir(const wchar_t* verb, const wchar_t* file, const wchar_t* args, const wchar_t* dir, int show) {- if (!file) return;- AllowSetForegroundWindow(ASFW_ANY); // o app aberto pela thread vem para a frente como antes- std::wstring v = verb ? verb : L"", f = file, a = args ? args : L"", d = dir ? dir : L"";- bool temVerbo = verb != nullptr;- std::thread([v, f, a, d, show, temVerbo] {- HRESULT ci = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);- SHELLEXECUTEINFOW se{ sizeof(se) };- se.fMask = SEE_MASK_NOASYNC;- se.lpVerb = temVerbo ? v.c_str() : nullptr;- se.lpFile = f.c_str();- se.lpParameters = a.empty() ? nullptr : a.c_str();- se.lpDirectory = d.empty() ? nullptr : d.c_str();- se.nShow = show;- if (!ShellExecuteExW(&se)) Log(L"abrir: não abriu %ls (%lu)", f.c_str(), GetLastError());- if (SUCCEEDED(ci)) CoUninitialize();- }).detach();-}--// trabalho feito numa thread devolve o resultado para a interface (dock: a Lixeira cheia ou vazia)-static const UINT WM_NA_INTERFACE = WM_APP + 60;-void shell::NaInterface(std::function<void()> f) {- auto* p = new std::function<void()>(std::move(f));- if (!g_msg || !PostMessageW(g_msg, WM_NA_INTERFACE, 0, (LPARAM)p)) delete p;-}--static void LoadSettings() {- EsperaAjustes(); // uma gravação nossa ainda na fila: ela vai antes (senão a releitura traria o valor antigo)- PWSTR p = nullptr;- if (FAILED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) return;- std::wstring f = std::wstring(p) + L"\\Shell\\ajustes.txt";- CoTaskMemFree(p);- // Do zero a cada leitura: uma linha tirada do arquivo (ajuste de volta ao padrão) continuava valendo com o valor- // antigo até reiniciar o Shell (23/11/2026: ocultar=1 apagado deixava o Dock sem reserva na área de trabalho).- // Linhas de qualquer tamanho (apps_ordem passava de 512 caracteres e era cortada).- std::map<std::wstring, std::wstring> novo;- if (!ajarq::Ler(f, novo)) return;- AcquireSRWLockExclusive(&g_settingsLock);- g_settings.swap(novo);- ReleaseSRWLockExclusive(&g_settingsLock);- backdrop::Reload(); // Transparência e Efeitos (Liquid Glass, reduzir transparência, tinta)- anim::reduceMotion = shell::Setting(L"reduzir_movimento", L"0") == L"1";-}--// ---- barra de tarefas do Windows: escondida enquanto o shell roda-static void HideTaskbars() {- if (shell::nativo) return; // nativo: a barra do Windows é o próprio Shell (a MacBarra a mantém escondida)- EnumWindows([](HWND h, LPARAM) -> BOOL {- wchar_t c[64]; GetClassNameW(h, c, 64);- if ((!wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd")) && !apps::IsShellWindow(h)) {- // sem esperar o Explorador: travado ou ainda subindo, ele segurava o Shell aqui (o vigia reiniciava o- // Shell em ciclo, 09/11/2026)- if (IsWindowVisible(h)) ShowWindowAsync(h, SW_HIDE);- if (std::find(g_hiddenBars.begin(), g_hiddenBars.end(), h) == g_hiddenBars.end()) g_hiddenBars.push_back(h);- }- return TRUE;- }, 0);-}-+ if (k->dwExtraInfo != KEY_MARK && (k->vkCode == VK_VOLUME_UP || k->vkCode == VK_VOLUME_DOWN || k->vkCode == VK_VOLUME_MUTE)) {+ if (w == WM_KEYDOWN || w == WM_SYSKEYDOWN) {+ bool fine = GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_MENU) < 0;+ PostMessageW(g_msg, WM_APP_VOLUME, k->vkCode, fine);+ }+ return 1;+ }+ }+ if (code == HC_ACTION && bloqueio::Active()) {+ // tela travada: nada de Iniciar, Alt+Tab, Ctrl+Esc, Alt+Esc, Alt+F4, Ctrl+Shift+Esc (Ctrl+Alt+Del não dá para barrar)+ auto* k = (KBDLLHOOKSTRUCT*)l;+ bool alt = (k->flags & LLKHF_ALTDOWN) != 0, ctrl = GetAsyncKeyState(VK_CONTROL) < 0;+ DWORD vk = k->vkCode;+ if (vk == VK_LWIN || vk == VK_RWIN || vk == VK_APPS) { g_winDown = false; return 1; }+ if ((alt && (vk == VK_TAB || vk == VK_ESCAPE || vk == VK_F4 || vk == VK_SPACE)) || (ctrl && vk == VK_ESCAPE)) return 1;+ g_altTab = false;+ return CallNextHookEx(g_kbHook, code, w, l);+ }+ if (!g_fullHook) return CallNextHookEx(g_kbHook, code, w, l);+ if (code == HC_ACTION) {+ auto* k = (KBDLLHOOKSTRUCT*)l;+ if (k->dwExtraInfo != KEY_MARK) {+ bool down = w == WM_KEYDOWN || w == WM_SYSKEYDOWN;+ bool win = k->vkCode == VK_LWIN || k->vkCode == VK_RWIN;+ if (win) {+ auto mods = [] { return GetAsyncKeyState(VK_CONTROL) < 0 || GetAsyncKeyState(VK_SHIFT) < 0 || GetAsyncKeyState(VK_MENU) < 0; };+ if (shell::nativo) {+ // modo nativo (dentro do explorer): a tecla segue para o Windows; o atalho reinjetado daqui não+ // valia (Win+R não abria). Sozinha, ao soltar, abre o Launchpad+ if (down) {+ if (!g_winDown) { g_winDown = true; g_winCombo = mods(); g_winEaten = false; g_spaceHeld = false; g_tabHeld = false; g_winVk = k->vkCode; g_winAt = k->time; }+ } else if (g_winDown) {+ g_winDown = false;+ if (!g_winCombo && k->time - g_winAt <= 1000) PostMessageW(g_msg, WM_APP_LAUNCHPAD, 0, 0);+ }+ return CallNextHookEx(g_kbHook, code, w, l);+ }+ // A tecla segue para o Windows desde que desce (como no modo nativo): AltSnap e afins (Win + arrastar) a veem+ // segurada, sem atraso e sem o Shell mexer no clique (issue #21: segurar o clique e devolver dava um tranco,+ // o cursor não mudava e o clique direito às vezes travava). Os nossos atalhos (Win+Espaço, Win+I...) comem só a+ // letra. Ao soltar, a tecla muda (0xE8) antes do Win: o Windows não vê um Win "sozinho" e o Iniciar não abre.+ if (down) {+ if (!g_winDown) {+ g_winDown = true; g_winCombo = mods(); g_winEaten = false; g_spaceHeld = false; g_tabHeld = false; g_winVk = k->vkCode; g_winAt = k->time;+ g_winPassed = false;+ }+ return CallNextHookEx(g_kbHook, code, w, l);+ }+ if (g_winDown) {+ g_winDown = false;+ if (!g_winCombo && k->time - g_winAt <= 1000) PostMessageW(g_msg, WM_APP_LAUNCHPAD, 0, 0); // sozinha: Launchpad/Spotlight+ // Combinação que foi para o Windows (Win+V, Win+.): ele mesmo não abre o Iniciar, e a tecla muda chegava+ // ao painel que acabou de abrir: o histórico da Área de Transferência piscava e fechava (issue #27, 22/11/2026)+ if (g_winPassed && !g_winEaten) return CallNextHookEx(g_kbHook, code, w, l);+ // a tecla muda e o soltar do Win vão juntos, nesta ordem: deixando o soltar de verdade passar, a muda+ // (mandada daqui de dentro) chegava depois dele e o Iniciar abria+ Inject(0xE8, false); Inject(0xE8, true);+ Inject(k->vkCode, true);+ return 1;+ }+ return CallNextHookEx(g_kbHook, code, w, l);+ } else if (k->vkCode == VK_TAB && down && !g_winDown && GetAsyncKeyState(VK_MENU) < 0 && GetAsyncKeyState(VK_CONTROL) >= 0) {+ // Alt+Tab: o seletor de apps do Mac no lugar do Alternar Tarefas do Windows. A tecla "muda"+ // (0xE8) evita que o app da frente veja um Alt sozinho ao soltar e abra o menu dele+ if (!g_altTab) { Inject(0xE8, false); Inject(0xE8, true); }+ g_altTab = true;+ PostMessageW(g_msg, WM_APP_SWITCH, GetAsyncKeyState(VK_SHIFT) < 0 ? (WPARAM)-1 : 1, 0);+ return 1;+ } else if (g_altTab && down && (k->vkCode == 'Q' || k->vkCode == 'H' || k->vkCode == VK_ESCAPE || k->vkCode == VK_LEFT || k->vkCode == VK_RIGHT)) {+ if (k->vkCode == VK_ESCAPE) g_altTab = false;+ PostMessageW(g_msg, WM_APP_SWITCH_KEY, k->vkCode, 0);+ return 1;+ } else if (g_altTab && !down && (k->vkCode == VK_LMENU || k->vkCode == VK_RMENU || k->vkCode == VK_MENU)) {+ g_altTab = false;+ PostMessageW(g_msg, WM_APP_SWITCH_END, 0, 0); // o Alt solto segue para o Windows normalmente+ } else if (k->vkCode == VK_ESCAPE && down && GetAsyncKeyState(VK_CONTROL) < 0 && GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_MENU) >= 0) {+ // Ctrl+Shift+Esc: o nosso Monitor de Atividade no lugar do Gerenciador de Tarefas+ PostMessageW(g_msg, WM_APP_MONITOR, 0, 0);+ return 1;+ } else if (k->vkCode == VK_ESCAPE && down && GetAsyncKeyState(VK_CONTROL) < 0 && GetAsyncKeyState(VK_MENU) < 0 && GetAsyncKeyState(VK_SHIFT) >= 0) {+ // Ctrl+Alt+Esc: Forçar Encerrar Aplicativos (Command+Option+Esc do Mac)+ PostMessageW(g_msg, WM_APP_MONITOR, 1, 0);+ return 1;+ } else if (k->vkCode == VK_SPACE && g_winDown && (!g_winCombo || g_winEaten)) {+ // Win+Espaço: o Spotlight (Cmd+Espaço no Mac; no Windows trocaria o idioma do teclado).+ // Segurando o Win, cada Espaço abre/fecha de novo; repetição de tecla segurada não conta e+ // nenhum Espaço chega ao app de baixo+ if (down && !g_spaceHeld) PostMessageW(g_msg, WM_APP_SPOTLIGHT, 0, 0);+ g_spaceHeld = down;+ g_winCombo = g_winEaten = true;+ return 1;+ } else if (k->vkCode == VK_TAB && g_winDown && (!g_winCombo || g_winEaten)) {+ // Win+Tab: o Mission Control (no lugar da Visão de Tarefas). Segurando o Win, cada Tab abre/fecha+ // de novo (igual ao Espaço); repetição de tecla segurada não conta+ if (down && !g_tabHeld) PostMessageW(g_msg, WM_APP_MISSION, 0, 0);+ g_tabHeld = down;+ g_winCombo = g_winEaten = true;+ return 1;+ } else if (g_winDown && down && (k->vkCode == VK_F12 || k->vkCode == VK_F8) && liquid::Leopard()) {+ // Leopard: Win+F12 = Dashboard (o F12 do Mac), Win+F8 = Spaces (o F8 do Mac). Só com o Win: o F12 sozinho+ // continua dos apps (ferramentas do navegador)+ static UINT openPanel = RegisterWindowMessageW(L"ShellAbrirPainel");+ PostMessageW(g_msg, openPanel, k->vkCode == VK_F12 ? 16 : 17, 0);+ g_winCombo = g_winEaten = true;+ return 1;+ } else if (g_winDown && down && !g_winCombo && (k->vkCode == 'I' || k->vkCode == VK_TAB)) {+ // Win+I: o nosso Ajustes do Sistema; Win+Tab: o Mission Control (no lugar da Visão de Tarefas)+ g_winCombo = g_winEaten = true;+ PostMessageW(g_msg, k->vkCode == VK_TAB ? WM_APP_MISSION : WM_APP_SETTINGS, 0, 0);+ return 1;+ } else if (!shell::nativo && g_winDown && down && (k->vkCode == VK_LEFT || k->vkCode == VK_RIGHT) && GetAsyncKeyState(VK_CONTROL) >= 0 &&+ GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_MENU) >= 0) {+ // Win+←/→: metade da tela (o encaixe do Windows fica desligado enquanto o Shell roda: encaixe.cpp)+ if (!g_winCombo) g_winCombo = g_winEaten = true;+ PostMessageW(g_msg, WM_APP_SNAP, k->vkCode, 0);+ return 1;+ } else if (g_winDown && down && !g_winCombo && (k->vkCode == VK_UP || k->vkCode == VK_DOWN) &&+ GetPropW(GetForegroundWindow(), L"MacJanela")) {+ // Win+↑/↓ em janela com a barra do Mac: sem o botão de maximizar o Windows ignora; fazemos nós+ g_winCombo = g_winEaten = true;+ PostMessageW(g_msg, WM_APP_SNAP, k->vkCode, 0);+ return 1;+ } else if (!shell::nativo && g_winDown && down && k->vkCode == 'Q' && GetAsyncKeyState(VK_CONTROL) < 0 && GetAsyncKeyState(VK_MENU) >= 0) {+ // Ctrl+Win+Q: o atalho do Mac (Control+Command+Q) para bloquear (o bloqueio do Windows)+ if (!g_winCombo) g_winCombo = g_winEaten = true;+ PostMessageW(g_msg, WM_APP_LOCK, 0, 0);+ return 1;+ } else if (g_winDown && (k->vkCode == VK_UP || k->vkCode == VK_DOWN) && GetAsyncKeyState(VK_CONTROL) < 0 &&+ GetAsyncKeyState(VK_MENU) >= 0 && GetAsyncKeyState(VK_SHIFT) >= 0) {+ // Ctrl+Win+↑ / ↓ = Ctrl+↑ / ↓ do Mac: Mission Control / Exposé do app da frente (Ctrl+Win+←/→+ // já trocam de Mesa, como Ctrl+←/→ no Mac). A repetição da tecla segurada não abre de novo+ if (down && g_macKeyVk != k->vkCode) PostMessageW(g_msg, k->vkCode == VK_UP ? WM_APP_MISSION : WM_APP_EXPOSE, 0, 0);+ g_macKeyVk = down ? k->vkCode : 0;+ if (!g_winCombo) g_winCombo = g_winEaten = true;+ return 1;+ } else if (g_macKeyVk && k->vkCode == g_macKeyVk && !down) {+ g_macKeyVk = 0;+ return 1;+ } else if (g_macKeys && g_winDown && down && (!g_winCombo || g_winEaten) && (k->vkCode == 'Q' || k->vkCode == 'H' || k->vkCode == 'W') &&+ GetAsyncKeyState(VK_CONTROL) >= 0 && GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_MENU) >= 0) {+ // Win+Q encerra o app da frente, Win+H oculta, Win+W fecha a janela (como Cmd no Mac). Segurando o+ // Win, cada toque vale de novo; a repetição da tecla segurada não conta+ if (g_macKeyVk != k->vkCode) PostMessageW(g_msg, WM_APP_MACKEY, k->vkCode, 0);+ g_macKeyVk = k->vkCode;+ g_winCombo = g_winEaten = true;+ return 1;+ } else if (g_capKey && k->vkCode == g_capKey && !down) {+ g_capKey = 0; // fim do atalho da Captura de Tela: a tecla solta também é nossa+ return 1;+ } else if (g_winDown && down && GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_MENU) >= 0 &&+ (k->vkCode == '3' || k->vkCode == '4' || k->vkCode == '5' || k->vkCode == 'S') && g_capturaExe) {+ // Win+Shift+3/4/5 (Cmd+Shift+3/4/5 do Mac) e Win+Shift+S: a nossa Captura de Tela+ // (WacOSScreenshot.exe) no lugar da Ferramenta de Captura; com Ctrl, só área de transferência.+ // A tecla segurada (repetição) não abre de novo; a tecla muda (0xE8) faz o Windows não ver+ // um Win sozinho ao soltar (o Win e o Shift já foram devolvidos a ele: combinação)+ if (g_capKey != k->vkCode) {+ g_capKey = k->vkCode;+ Inject(0xE8, false); Inject(0xE8, true);+ int kind = k->vkCode == 'S' ? 4 : (int)(k->vkCode - '0');+ PostMessageW(g_msg, WM_APP_CAPTURA, kind, GetAsyncKeyState(VK_CONTROL) < 0 ? 1 : 0);+ }+ return 1;+ } else if (g_winDown && down && k->vkCode == 'S' && GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_CONTROL) >= 0 && mesa::Standalone()) {+ // Win+Shift+S sem a nossa Captura de Tela: a Ferramenta de Captura do Windows (quem atende é+ // o Explorador quando ele é o shell; sem ele, fazemos nós)+ PostMessageW(g_msg, WM_APP_WINKEY, 'S', 0);+ return 1;+ } else if (g_winDown && down && !g_winCombo && !shell::nativo && k->vkCode == 'E' && GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_CONTROL) >= 0) {+ // Win+E com o Explorador rodando (explorer=fundo): ele abria a página "Início" dele, que não é pasta de+ // disco e o Finder não trocava (17/11/2026). O Shell atende sempre: Finder (ou o Explorador, se+ // "Abrir pastas no Finder" estiver desligado — mesa::WinKey decide)+ g_winCombo = g_winEaten = true;+ PostMessageW(g_msg, WM_APP_WINKEY, 'E', 0);+ return 1;+ } else if (g_winDown && down && !g_winCombo && !shell::nativo && k->vkCode == 'D') {+ // Win+D é sempre nosso: com o Explorador de fundo, o "mostrar a área de trabalho" dele punha a mesa+ // DELE na frente e a nossa voltava por cima em seguida (piscava, os widgets sumiam e voltavam)+ g_winCombo = g_winEaten = true;+ PostMessageW(g_msg, WM_APP_WINKEY, 'D', 0);+ return 1;+ } else if (g_winDown && down && !g_winCombo && mesa::Standalone() && (k->vkCode == 'E' || k->vkCode == 'R' || k->vkCode == 'D')) {+ // sem o Explorador ninguém trata Win+E/R/D: fazemos nós (Finder, Executar, mostrar a mesa)+ g_winCombo = g_winEaten = true;+ PostMessageW(g_msg, WM_APP_WINKEY, k->vkCode, 0);+ return 1;+ } else if (g_winDown && down && !g_winCombo && shell::nativo) {+ g_winCombo = true; // nativo: a tecla Windows já foi para o Windows; esta segue também+ } else if (g_winDown && down && !g_winCombo) {+ // combinação do Windows: a tecla Win já foi para ele; esta segue também+ g_winCombo = true;+ g_winPassed = true;+ }+ }+ }+ return CallNextHookEx(g_kbHook, code, w, l);+}++static void KeyThread() {+ shell::ThreadDeGancho();+ g_kbHook = SetWindowsHookExW(WH_KEYBOARD_LL, KeyHook, GetModuleHandleW(nullptr), 0);+ MSG m;+ while (GetMessageW(&m, nullptr, 0, 0)) {}+ if (g_kbHook) UnhookWindowsHookEx(g_kbHook);+}++// O log vai para o disco numa thread própria. Gravando direto (fwprintf + fflush a cada linha), a thread da interface+// ficava presa no WriteFile quando o disco demorava (torrent, antivírus, agente de monitoramento): o vigia via o Shell+// sem responder por 5 s e o reiniciava, várias vezes seguidas (22/11/2026: as duas pilhas tiradas no travamento+// estavam no Log -> fflush -> WriteFile, chamado pelo vidro real).+static std::mutex g_logMx, g_logDisco;+static std::condition_variable g_logCv;+static std::wstring g_logFila;+static void LogGrava() { // o que está na fila vai para o arquivo (só uma thread grava de cada vez)+ std::wstring s;+ { std::lock_guard<std::mutex> l(g_logMx); s.swap(g_logFila); }+ if (s.empty() || !g_log) return;+ std::lock_guard<std::mutex> d(g_logDisco);+ fputws(s.c_str(), g_log); fflush(g_log);+}+static void EsperaAjustes();+static void LogDescarrega() { EsperaAjustes(); LogGrava(); } // fim do Shell: o que faltou vai junto (log e ajustes.txt)++void Log(const wchar_t* fmt, ...) {+ if (!g_log) return;+ SYSTEMTIME st; GetLocalTime(&st);+ wchar_t pre[16]; swprintf_s(pre, L"%02d:%02d:%02d ", st.wHour, st.wMinute, st.wSecond);+ va_list a; va_start(a, fmt);+ va_list b; va_copy(b, a);+ int n = _vscwprintf(fmt, a);+ std::wstring linha;+ if (n > 0) { linha.resize((size_t)n + 1); vswprintf_s(linha.data(), linha.size(), fmt, b); linha.resize((size_t)n); }+ va_end(b); va_end(a);+ static std::once_flag once;+ std::call_once(once, [] {+ std::thread([] {+ for (;;) {+ { std::unique_lock<std::mutex> l(g_logMx); g_logCv.wait(l, [] { return !g_logFila.empty(); }); }+ LogGrava();+ }+ }).detach();+ });+ {+ std::lock_guard<std::mutex> l(g_logMx);+ if (g_logFila.size() < 4 * 1024 * 1024) { g_logFila += pre; g_logFila += linha; g_logFila += L'\n'; } // disco parado de vez: não cresce sem fim+ }+ g_logCv.notify_one();+}++// g_settings é lido de várias threads (vidro, índice, ilha, widgets...) enquanto a interface relê o arquivo+// (LoadSettings troca o mapa inteiro): sem trava, a leitura podia pegar o mapa no meio da troca e derrubar o Shell+static SRWLOCK g_settingsLock = SRWLOCK_INIT;+std::wstring shell::Setting(const wchar_t* key, const wchar_t* def) {+ AcquireSRWLockShared(&g_settingsLock);+ auto it = g_settings.find(key);+ std::wstring r = it != g_settings.end() ? it->second : (def ? def : L"");+ ReleaseSRWLockShared(&g_settingsLock);+ return r;+}++static std::wstring SettingsPath() {+ PWSTR p = nullptr;+ std::wstring f;+ if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) { f = std::wstring(p) + L"\\Shell"; CoTaskMemFree(p); }+ CreateDirectoryW(f.c_str(), nullptr);+ return f + L"\\ajustes.txt";+}++// O ajustes.txt vai para o disco numa thread (como o log). Gravando aqui, cada mudança (Dock, Central de Controle,+// Launchpad, widgets...) esperava o disco na thread da interface: num HD com o antivírus olhando, 20 a 200 ms de tela+// parada a cada clique (issue #10, Core i3 com HD). O valor vale na hora (g_settings); o arquivo segue logo depois, e+// várias mudanças seguidas viram uma gravação só. Quem relê o arquivo (LoadSettings) e a saída do Shell esperam a fila.+static std::mutex g_ajMx;+static std::condition_variable g_ajCv;+static std::map<std::wstring, std::wstring> g_ajMapa; // os ajustes inteiros a gravar (os mais novos)+static bool g_ajTem = false, g_ajOcupado = false;+static void EsperaAjustes() {+ std::unique_lock<std::mutex> l(g_ajMx);+ g_ajCv.wait_for(l, std::chrono::seconds(3), [] { return !g_ajTem && !g_ajOcupado; });+}+void shell::SetSetting(const wchar_t* key, const std::wstring& value) {+ std::map<std::wstring, std::wstring> copia;+ AcquireSRWLockExclusive(&g_settingsLock);+ g_settings[key] = value;+ copia = g_settings;+ ReleaseSRWLockExclusive(&g_settingsLock);+ // na thread de gravação, atômico (.tmp + troca): quem lê no meio não vê o arquivo vazio+ { std::lock_guard<std::mutex> l(g_ajMx); g_ajMapa = std::move(copia); g_ajTem = true; }+ static std::once_flag umaVez;+ std::call_once(umaVez, [] {+ std::thread([] {+ for (;;) {+ std::map<std::wstring, std::wstring> m;+ {+ std::unique_lock<std::mutex> l(g_ajMx);+ g_ajCv.wait(l, [] { return g_ajTem; });+ m.swap(g_ajMapa); g_ajTem = false; g_ajOcupado = true;+ }+ ajarq::Gravar(SettingsPath(), m);+ { std::lock_guard<std::mutex> l(g_ajMx); g_ajOcupado = false; }+ g_ajCv.notify_all();+ }+ }).detach();+ });+ g_ajCv.notify_all();+}++// Calculadora (Calculadora.exe) no lugar da Calculadora do Windows: Launchpad, Spotlight e Dock passam+// o alvo (AUMID, atalho ou .exe) por aqui. Sem o Calculadora.exe, segue a do Windows (devolve false).+bool shell::OpenCalculator(const std::wstring& target) {+ std::wstring t = target;+ for (auto& c : t) c = towlower(c);+ auto ends = [&](const wchar_t* s) { size_t n = wcslen(s); return t.size() >= n && t.compare(t.size() - n, n, s) == 0; };+ bool calc = t.find(L"microsoft.windowscalculator") != std::wstring::npos || t == L"calc.exe" || t == L"calc" ||+ ends(L"\\calc.exe") || ends(L"calculatorapp.exe") || ends(L"\\calculadora.exe") || ends(L"\\wacoscalculator.exe");+ if (!calc) return false;+ std::wstring exe = shell::dir + L"\\" EXE_CALCULATOR;+ if (GetFileAttributesW(exe.c_str()) == INVALID_FILE_ATTRIBUTES) return false;+ shell::Abrir(L"open", exe.c_str());+ return true;+}++// Monitor de Atividade (MonitorAtividade.exe); sem ele, o Gerenciador de Tarefas do Windows+void shell::OpenMonitor() {+ std::wstring exe = shell::dir + L"\\" EXE_MONITOR;+ if (GetFileAttributesW(exe.c_str()) == INVALID_FILE_ATTRIBUTES) exe = L"taskmgr.exe";+ shell::Abrir(L"open", exe.c_str(), nullptr, nullptr, SW_SHOWNORMAL);+}++// Forçar Encerrar Aplicativos (WacOSForceQuit.exe); sem ele, o Monitor de Atividade+void shell::OpenForceQuit(bool memory) {+ std::wstring exe = shell::dir + L"\\" EXE_FORCEQUIT;+ if (GetFileAttributesW(exe.c_str()) == INVALID_FILE_ATTRIBUTES) { shell::OpenMonitor(); return; }+ AllowSetForegroundWindow(ASFW_ANY); // aberta pela pressão de memória, sem clique: precisa vir para a frente+ shell::Abrir(L"open", exe.c_str(), memory ? L"--memoria" : nullptr, nullptr, SW_SHOWNORMAL);+}++void shell::Sound(const wchar_t* name) {+ std::wstring root = shell::dir.substr(0, shell::dir.find_last_of(L'\\')); // a pasta do projeto (bin fica dentro dela)+ PlaySoundW((root + L"\\sons\\mac\\" + name + L".wav").c_str(), nullptr, SND_FILENAME | SND_ASYNC | SND_NODEFAULT);+}++void shell::OpenSettings(const std::wstring& page) {+ std::wstring args = page.empty() ? L"" : (page.rfind(L"ms-settings:", 0) == 0 ? page : L"--pagina=" + page);+ shell::Abrir(L"open", (shell::dir + L"\\" EXE_SETTINGS).c_str(), args.c_str());+}++// ShellExecute numa thread: na thread da interface ele chegou a segurar o Shell 3,2 s (abrir o Ajustes pela Ilha com o+// disco ocupado; pilha de 22/11/2026 19:54, issue #32). A thread espera o ShellExecute terminar (SEE_MASK_NOASYNC).+void shell::Abrir(const wchar_t* verb, const wchar_t* file, const wchar_t* args, const wchar_t* dir, int show) {+ if (!file) return;+ AllowSetForegroundWindow(ASFW_ANY); // o app aberto pela thread vem para a frente como antes+ std::wstring v = verb ? verb : L"", f = file, a = args ? args : L"", d = dir ? dir : L"";+ bool temVerbo = verb != nullptr;+ std::thread([v, f, a, d, show, temVerbo] {+ HRESULT ci = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);+ SHELLEXECUTEINFOW se{ sizeof(se) };+ se.fMask = SEE_MASK_NOASYNC;+ se.lpVerb = temVerbo ? v.c_str() : nullptr;+ se.lpFile = f.c_str();+ se.lpParameters = a.empty() ? nullptr : a.c_str();+ se.lpDirectory = d.empty() ? nullptr : d.c_str();+ se.nShow = show;+ if (!ShellExecuteExW(&se)) Log(L"abrir: não abriu %ls (%lu)", f.c_str(), GetLastError());+ if (SUCCEEDED(ci)) CoUninitialize();+ }).detach();+}++// trabalho feito numa thread devolve o resultado para a interface (dock: a Lixeira cheia ou vazia)+static const UINT WM_NA_INTERFACE = WM_APP + 60;+void shell::NaInterface(std::function<void()> f) {+ auto* p = new std::function<void()>(std::move(f));+ if (!g_msg || !PostMessageW(g_msg, WM_NA_INTERFACE, 0, (LPARAM)p)) delete p;+}++static void LoadSettings() {+ EsperaAjustes(); // uma gravação nossa ainda na fila: ela vai antes (senão a releitura traria o valor antigo)+ PWSTR p = nullptr;+ if (FAILED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) return;+ std::wstring f = std::wstring(p) + L"\\Shell\\ajustes.txt";+ CoTaskMemFree(p);+ // Do zero a cada leitura: uma linha tirada do arquivo (ajuste de volta ao padrão) continuava valendo com o valor+ // antigo até reiniciar o Shell (23/11/2026: ocultar=1 apagado deixava o Dock sem reserva na área de trabalho).+ // Linhas de qualquer tamanho (apps_ordem passava de 512 caracteres e era cortada).+ std::map<std::wstring, std::wstring> novo;+ if (!ajarq::Ler(f, novo)) return;+ AcquireSRWLockExclusive(&g_settingsLock);+ g_settings.swap(novo);+ ReleaseSRWLockExclusive(&g_settingsLock);+ backdrop::Reload(); // Transparência e Efeitos (Liquid Glass, reduzir transparência, tinta)+ anim::reduceMotion = shell::Setting(L"reduzir_movimento", L"0") == L"1";+}++// ---- barra de tarefas do Windows: escondida enquanto o shell roda+static void HideTaskbars() {+ if (shell::nativo) return; // nativo: a barra do Windows é o próprio Shell (a MacBarra a mantém escondida)+ EnumWindows([](HWND h, LPARAM) -> BOOL {+ wchar_t c[64]; GetClassNameW(h, c, 64);+ if ((!wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd")) && !apps::IsShellWindow(h)) {+ // sem esperar o Explorador: travado ou ainda subindo, ele segurava o Shell aqui (o vigia reiniciava o+ // Shell em ciclo, 09/11/2026)+ if (IsWindowVisible(h)) ShowWindowAsync(h, SW_HIDE);+ if (std::find(g_hiddenBars.begin(), g_hiddenBars.end(), h) == g_hiddenBars.end()) g_hiddenBars.push_back(h);+ }+ return TRUE;+ }, 0);+}+// A barra do Explorador que ele mostra de novo (Win, notificação, Explorador reiniciado) some na hora. Antes só o tique de// 1 s a escondia: ela "aparecia às vezes" por até um segundo (issue #40)static void CALLBACK OnBarraWindows(HWINEVENTHOOK, DWORD, HWND h, LONG obj, LONG child, DWORD, DWORD) {@@ -514,968 +514,970 @@ static void CALLBACK OnBarraWindows(HWINEVENTHOOK, DWORD, HWND h, LONG obj, LONGif (std::find(g_hiddenBars.begin(), g_hiddenBars.end(), h) == g_hiddenBars.end()) g_hiddenBars.push_back(h);}-static void ShowTaskbars() {- for (HWND h : g_hiddenBars) if (IsWindow(h)) ShowWindowAsync(h, SW_SHOWNOACTIVATE);- g_hiddenBars.clear();- // issue #37 (a barra do Windows sumia ao sair): o Explorador que reiniciou com o Shell aberto cria uma barra nova,- // que não está na lista acima. Toda barra do Explorador escondida volta.- EnumWindows([](HWND h, LPARAM) -> BOOL {- wchar_t c[64] = {}; GetClassNameW(h, c, 64);- if ((!wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd")) && !apps::IsShellWindow(h) && !IsWindowVisible(h)) {- DWORD pid = 0; GetWindowThreadProcessId(h, &pid);- if (pid != GetCurrentProcessId()) ShowWindowAsync(h, SW_SHOWNOACTIVATE);- }- return TRUE;- }, 0);-}--// Barra do Windows nos outros monitores: só esconder não segurava (o Explorador a mostrava de novo e ela-// reservava espaço). Enquanto o Shell roda, desliga "Mostrar a barra de tarefas em todos os monitores"-// (HKCU ...\Explorer\Advanced\MMTaskbarEnabled = 0, a mesma chave da Configuração do Windows). O valor de antes-// fica em ajustes.txt (barra_windows_monitores_antes: 0, 1 ou "x" = não existia) e volta ao sair.-static const wchar_t* MM_KEY = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";--static void TellExplorerTray() { // o Explorador relê o ajuste da barra (como a Configuração faz)- std::thread([] {- EnumWindows([](HWND h, LPARAM) -> BOOL {- wchar_t c[64] = {}; GetClassNameW(h, c, 64);- if (!wcscmp(c, L"Shell_TrayWnd") && !apps::IsShellWindow(h))- SendMessageTimeoutW(h, WM_SETTINGCHANGE, 0, (LPARAM)L"TraySettings", SMTO_ABORTIFHUNG, 1000, nullptr);- return TRUE;- }, 0);- }).detach();-}--static void SecondaryTaskbarsOff() {- if (shell::nativo) return;- DWORD v = 0, cb = sizeof(v);- bool had = RegGetValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled", RRF_RT_REG_DWORD, nullptr, &v, &cb) == ERROR_SUCCESS;- if (had && v == 0) return; // já desligado (pelo usuário ou por nós antes)- if (shell::Setting(L"barra_windows_monitores_antes", L"").empty())- shell::SetSetting(L"barra_windows_monitores_antes", had ? std::to_wstring(v) : L"x");- DWORD zero = 0;- if (RegSetKeyValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled", REG_DWORD, &zero, sizeof(zero)) == ERROR_SUCCESS) {- Log(L"registro: HKCU\\%ls\\MMTaskbarEnabled = 0 (antes: %ls) - barra do Windows só no monitor principal", MM_KEY, had ? std::to_wstring(v).c_str() : L"não existia");- TellExplorerTray();- }-}--static void SecondaryTaskbarsRestore() {- std::wstring before = shell::Setting(L"barra_windows_monitores_antes", L"");- if (before.empty()) return;- if (before == L"x") RegDeleteKeyValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled");- else { DWORD v = (DWORD)_wtoi(before.c_str()); RegSetKeyValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled", REG_DWORD, &v, sizeof(v)); }- shell::SetSetting(L"barra_windows_monitores_antes", L"");- Log(L"registro: MMTaskbarEnabled devolvido (%ls)", before == L"x" ? L"apagado, não existia" : before.c_str());- TellExplorerTray();-}--// Área de trabalho de cada monitor: a barra de menus em cima (todos têm a sua) e o Dock embaixo (só no-// monitor dele). O SPI_SETWORKAREA vale para o monitor que contém o retângulo.-std::vector<HWND> shell::AlheiasNoTopo() {- std::vector<HWND> v; // de cima para baixo- DWORD eu = GetCurrentProcessId();- for (HWND w = GetTopWindow(nullptr); w && v.size() < 32; w = GetWindow(w, GW_HWNDNEXT)) {- if (!(GetWindowLongW(w, GWL_EXSTYLE) & WS_EX_TOPMOST)) break; // acabou a faixa das "sempre por cima"- if (!IsWindowVisible(w)) continue;- DWORD pid = 0; GetWindowThreadProcessId(w, &pid);- if (pid == eu) break; // daqui para baixo já estavam abaixo das nossas- DWORD cloak = 0; DwmGetWindowAttribute(w, DWMWA_CLOAKED, &cloak, sizeof(cloak));- if (cloak) continue;- wchar_t c[64] = {}; GetClassNameW(w, c, 64);- if (!wcscmp(c, L"tooltips_class32") || !wcscmp(c, L"#32768") || !wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd")) continue;- RECT r; if (!GetWindowRect(w, &r) || r.right - r.left < 2 || r.bottom - r.top < 2) continue;- v.push_back(w);- }- return v;-}--void shell::DevolveAlheias(const std::vector<HWND>& v) {- for (auto it = v.rbegin(); it != v.rend(); ++it) // de baixo para cima: a de cima termina por cima- if (IsWindow(*it) && IsWindowVisible(*it))- SetWindowPos(*it, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_ASYNCWINDOWPOS);-}--RECT shell::WorkAreaFor(HMONITOR hm) {- MONITORINFO mi{ sizeof(mi) };- if (!GetMonitorInfoW(hm, &mi)) return {};- RECT want = mi.rcMonitor;- want.top += menubar::ReservedOn(hm); // secundário sem barra (barra_todos_monitores=0): o topo é das janelas- if (hm == dock::MonitorHandle()) { // o Dock na borda escolhida (Ajustes > Posição na tela)- int r = dock::ReservedHeight();- if (dock::Posicao() == 1) want.left += r;- else if (dock::Posicao() == 2) want.right -= r;- else want.bottom -= std::max(r, menubar::ReservedBottom(hm)); // barra embaixo: com o Dock oculto, a altura dela- }- return want;-}--void shell::ApplyWorkArea() {- if (g_quitting) return;- struct Ctx { HMONITOR dock; bool changed; } ctx{ dock::MonitorHandle(), false };- EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hm, HDC, LPRECT, LPARAM p) -> BOOL {- auto* c = (Ctx*)p;- MONITORINFO mi{ sizeof(mi) };- if (!GetMonitorInfoW(hm, &mi)) return TRUE;- RECT want = shell::WorkAreaFor(hm), cur = mi.rcWork;- (void)c;- if (EqualRect(&want, &cur)) return TRUE;- static int times;- Log(L"área de trabalho estava %d,%d-%d,%d; agora %d,%d-%d,%d (vez %d)", cur.left, cur.top, cur.right, cur.bottom,- want.left, want.top, want.right, want.bottom, ++times);- // Sem SPIF_SENDCHANGE: o aviso geral fazia o Explorador recalcular e desfazer (briga a cada 2 s).- SystemParametersInfoW(SPI_SETWORKAREA, 0, &want, 0);- c->changed = true;- return TRUE;- }, (LPARAM)&ctx);- if (!ctx.changed) return;- // Avisa só as janelas dos apps: o DefWindowProc reencaixa as maximizadas na área nova.- EnumWindows([](HWND h, LPARAM) -> BOOL {- if (!IsWindowVisible(h) || apps::IsShellWindow(h)) return TRUE;- wchar_t c[64]; GetClassNameW(h, c, 64);- if (!wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd") || mesa::IsDeskClass(c)) return TRUE;- if (IsZoomed(h)) SendMessageTimeoutW(h, WM_SETTINGCHANGE, SPI_SETWORKAREA, 0, SMTO_ABORTIFHUNG, 200, nullptr);- return TRUE;- }, 0);-}--static void Restore() {- if (g_quitting) return;- g_quitting = true;- tray::Stop();- menus::Stop();- dialogs::Stop();- janelas::Stop();- encaixe::Stop();- memoria::Stop();- barras::Stop();- sombras::Stop();- alertas::Stop();- progresso::Stop(); // as janelas de progresso do Windows voltam para a tela- if (!shell::nativo) { // no nativo a tela de bloqueio continua do Windows (não foi trocada)- bloqueio::Stop(); // Win+L volta para o Windows (política apagada)- mesa::Stop(!g_crashed && !g_sessionEnding); // sem Explorador: ele volta (ao cair, quem abre é o vigia)- } else mesa::Stop(true); // nativo: a nossa mesa some e a do Explorador (que ficou atrás) reaparece- revelar::Stop(); // janelas que estavam nas bordas voltam- ponteiro::Stop(); // o cursor volta ao tamanho do esquema- palco::Stop(); // Organizador Visual: as janelas escondidas por ele voltam- genio::Stop(); // a animação de minimizar do Windows volta como estava- notificacoes::Stop(); // o banner de notificação do Windows volta- ShowTaskbars();- SecondaryTaskbarsRestore();- // os outros monitores voltam inteiros (a barra do Windows, se voltar lá, reserva o espaço dela)- EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hm, HDC, LPRECT, LPARAM) -> BOOL {- MONITORINFO mi{ sizeof(mi) };- if (GetMonitorInfoW(hm, &mi) && !(mi.dwFlags & MONITORINFOF_PRIMARY)) SystemParametersInfoW(SPI_SETWORKAREA, 0, &mi.rcMonitor, 0);- return TRUE;- }, 0);- SystemParametersInfoW(SPI_SETWORKAREA, 0, &g_origWork, SPIF_SENDCHANGE);- Log(L"saindo: barra do Windows e área de trabalho devolvidas");-}--// Saindo de verdade (não o reiniciar): o WacOS fecha por inteiro (issue #37: depois de sair, o Win+E e as pastas-// ainda abriam o Finder, e o Finder reserva e a Captura residente continuavam abertos, escondidos).-// As pastas voltam para o Explorador e finder_volta=1 faz o Shell, ao abrir de novo, devolvê-las ao Finder (o mesmo-// caminho do "Desligar o WacOS"). Quem desligou "Abrir pastas no Finder" à mão (finder_padrao=0) não é mexido.-static void SaiPorInteiro() {- static UINT capMsg = RegisterWindowMessageW(L"SequoiaCaptura");- if (HWND w = FindWindowW(L"SequoiaCapturaMsg", nullptr)) PostMessageW(w, capMsg, 0, 0); // wParam 0 = sair- if (HWND w = FindWindowW(L"ArquivosJanela", L"ArquivosReserva")) // a reserva nunca foi usada: não tem nada do usuário- PostThreadMessageW(GetWindowThreadProcessId(w, nullptr), WM_QUIT, 0, 0);- std::wstring finder = shell::dir + L"\\" EXE_FINDER;- if (shell::Setting(L"finder_padrao", L"1") == L"1" && GetFileAttributesW(finder.c_str()) != INVALID_FILE_ATTRIBUTES) {- shell::SetSetting(L"finder_volta", L"1");- std::wstring cmd = L"\"" + finder + L"\" --padrao off --quieto";- STARTUPINFOW si{ sizeof(si) }; si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;- PROCESS_INFORMATION pi{};- if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, shell::dir.c_str(), &si, &pi)) {- WaitForSingleObject(pi.hProcess, 3000); // antes de uma atualização abrir o Shell novo (que religa)- CloseHandle(pi.hThread); CloseHandle(pi.hProcess);- Log(L"saindo: pastas e Win+E de volta ao Explorador (o Finder volta ao abrir o WacOS)");- }- }-}--void shell::Quit(const wchar_t* why) {- Log(L"pedido para sair: %ls", why);- if (wcscmp(why, L"reiniciar")) SaiPorInteiro();- pastas::Stop();- limites::Stop();- bloqueio::Fallback(); // saiu com a tela travada (ex.: Ctrl+Alt+Shift+F12): o Windows bloqueia- Restore();- PostQuitMessage(0);-}--static LONG WINAPI OnCrash(EXCEPTION_POINTERS* ep) {- HMODULE mod = nullptr;- void* at = ep->ExceptionRecord->ExceptionAddress;- GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)at, &mod);- wchar_t name[MAX_PATH] = L"?"; if (mod) GetModuleFileNameW(mod, name, MAX_PATH);- Log(L"ERRO 0x%08X em %ls+0x%llX", ep->ExceptionRecord->ExceptionCode, name, (unsigned long long)((BYTE*)at - (BYTE*)mod));- bloqueio::Fallback(); // caiu com a tela travada: o Windows bloqueia de verdade- g_crashed = true;- Restore(); // nunca deixar o usuário sem barra de tarefas- return EXCEPTION_CONTINUE_SEARCH;-}--// Finder reserva: um Arquivos.exe já inicializado e escondido. Abrir uma pasta, o Win+E ou a janela-// de Abrir/Salvar entregam o pedido a ele (aparece na hora); quando é usado, preparamos outro.-// Captura de Tela (WacOSScreenshot.exe) sempre aberta e escondida: a mira do Win+Shift+4 aparece na hora-bool shell::SoDock() { static int v = -1; if (v < 0) v = shell::Setting(L"modo", L"completo") == L"dock" ? 1 : 0; return v == 1; }--static void EnsureScreenshot() {- static DWORD lastSpawn;- if (g_quitting || !g_capturaExe || FindWindowW(L"SequoiaCapturaMsg", nullptr)) return;- if (lastSpawn && GetTickCount() - lastSpawn < 10000) return;- lastSpawn = GetTickCount();- std::wstring cmd = L"\"" + shell::dir + L"\\" EXE_SCREENSHOT L"\" /residente";- STARTUPINFOW si{ sizeof(si) };- PROCESS_INFORMATION pi{};- std::thread([cmd, si, pi]() mutable { // como o Finder reserva: abrir programa espera o disco- if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) {- CloseHandle(pi.hProcess); CloseHandle(pi.hThread);- Log(L"Captura de Tela residente aberta");- }- }).detach();-}--// pedido do atalho: 3 tela inteira, 4 região/janela, 5 barra de ferramentas; clip = Ctrl seguro-static void Screenshot(int kind, bool clip) {- static UINT msg = RegisterWindowMessageW(L"SequoiaCaptura");- if (HWND w = FindWindowW(L"SequoiaCapturaMsg", nullptr)) {- DWORD pid = 0; GetWindowThreadProcessId(w, &pid);- AllowSetForegroundWindow(pid);- PostMessageW(w, msg, kind, clip ? 1 : 0);- return;- }- std::wstring args = L"/" + std::to_wstring(kind) + (clip ? L" /c" : L"");- shell::Abrir(L"open", (shell::dir + L"\\" EXE_SCREENSHOT).c_str(), args.c_str(), nullptr, SW_SHOWNORMAL);- Log(L"Captura de Tela aberta agora (%ls)", args.c_str());-}--void shell::AbrirFinder(const std::wstring& args) {- if (shell::nativo) {- HMODULE m = GetModuleHandleW(L"MacFinder.dll");- auto pedir = m ? (BOOL(WINAPI*)(const wchar_t*))GetProcAddress(m, "FinderPedir") : nullptr;- if (pedir && pedir(args.c_str())) { Log(L"Finder (nativo): %ls", args.c_str()); return; }- Log(L"Finder nativo indisponível, abrindo o exe: %ls", args.c_str());- }- shell::Abrir(L"open", (shell::dir + L"\\" EXE_FINDER).c_str(), args.c_str(), nullptr, SW_SHOWNORMAL);-}--static void EnsureReserve() {- if (shell::nativo) return; // no nativo a reserva é a janela do Finder dentro do explorer (MacFinder.dll)- static DWORD lastSpawn;- if (g_quitting || FindWindowW(L"ArquivosJanela", L"ArquivosReserva")) return;- if (lastSpawn && GetTickCount() - lastSpawn < 4000) return; // um por vez- lastSpawn = GetTickCount();- std::wstring cmd = L"\"" + shell::dir + L"\\" EXE_FINDER L"\" --reserva";- STARTUPINFOW si{ sizeof(si) };- si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;- PROCESS_INFORMATION pi{};- // numa thread: com o disco cheio o CreateProcess levou 2,9 s e a interface esperava (pilha de 22/11/2026, 15:25)- std::thread([cmd, si, pi]() mutable {- if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) {- CloseHandle(pi.hProcess); CloseHandle(pi.hThread);- Log(L"Finder reserva preparado");- }- }).detach();-}--// Pré-carga: lê os .exe dos outros apps do projeto para o cache de arquivos do Windows (memória de-// espera, que o sistema devolve quando precisa). Assim o primeiro clique abre como se já tivesse sido-// aberto antes, sem deixar nenhum processo rodando. Prioridade de fundo, depois que o Shell está pronto.-// os painéis que montam coisa cara na primeira abertura: prepara com o Shell já parado, na thread-// principal (o compositor e a GPU são dela)-static void CALLBACK WarmPanels(HWND, UINT, UINT_PTR id, DWORD) {- KillTimer(nullptr, id);- missioncontrol::Warm();- launchpad::Warm();-}--static void PreloadApps() {- SetTimer(nullptr, 0, 4000, WarmPanels);- std::thread([] {- SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);- Sleep(3000);- static const wchar_t* files[] = { EXE_SETTINGS, EXE_NOTES, EXE_CALCULATOR, EXE_TERMINAL, EXE_MONITOR, DLL_WINDOW32 };- std::vector<char> buf(1 << 20);- size_t total = 0;- for (auto* f : files) {- HANDLE h = CreateFileW((shell::dir + L"\\" + f).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr,- OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);- if (h == INVALID_HANDLE_VALUE) continue;- DWORD got = 0;- while (ReadFile(h, buf.data(), (DWORD)buf.size(), &got, nullptr) && got) total += got;- CloseHandle(h);- }- Log(L"pré-carga: %zu KB dos apps no cache", total / 1024);- SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);- }).detach();-}--// App da frente cobrindo o monitor inteiro (vídeo, jogo, F11): Dock e barra de menus somem, como no Mac.-static bool IsFullscreen(HWND fg) {- if (!fg || !IsWindowVisible(fg) || IsIconic(fg) || apps::IsShellWindow(fg)) return false;- // Trocadores de papel de parede com transição (YASB, Lively...) põem a janela da animação DENTRO da mesa do Windows- // (filha da WorkerW/Progman) e ela fica sendo a "janela da frente". Cobrindo o monitor, parecia um app em tela- // cheia: o Dock e a barra de menus sumiam e o vidro ficava sem fundo, e como o YASB mantém a janela viva depois da- // transição, ficava assim até reiniciar o WacOS (Reddit, 23/11/2026; reproduzido com o mesmo truque do YASB).- // Janela filha conta pela de topo dela: sendo a mesa, não é tela cheia.- if (HWND root = GetAncestor(fg, GA_ROOT); root && root != fg) {- wchar_t rc[64] = {}; GetClassNameW(root, rc, 64);- if (mesa::IsDeskClass(rc)) return false;- fg = root;- if (!IsWindowVisible(fg) || IsIconic(fg) || apps::IsShellWindow(fg)) return false;- }- wchar_t cls[64] = {}; GetClassNameW(fg, cls, 64);- if (mesa::IsDeskClass(cls) || !wcscmp(cls, L"Shell_TrayWnd")) return false;- if (IsZoomed(fg) && (GetWindowLongW(fg, GWL_STYLE) & WS_CAPTION) == WS_CAPTION) return false; // só maximizada- MONITORINFO mi{ sizeof(mi) };- if (!GetMonitorInfoW(MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST), &mi)) return false;- RECT r; if (!GetWindowRect(fg, &r)) return false;- return r.left <= mi.rcMonitor.left && r.top <= mi.rcMonitor.top && r.right >= mi.rcMonitor.right && r.bottom >= mi.rcMonitor.bottom;-}--// Jogo/vídeo em tela cheia no monitor `mon` (ou o Windows em modo "não incomodar": Direct3D exclusivo,-// apresentação): os banners de notificação não aparecem, só vão para a Central. Uma janela "sempre no topo" por cima-// do jogo tirava ele da tela cheia (17/11/2026, Fortnite caindo a cada notificação).-bool shell::NaoIncomodar(HMONITOR mon) {- QUERY_USER_NOTIFICATION_STATE q{};- if (SUCCEEDED(SHQueryUserNotificationState(&q)) && (q == QUNS_RUNNING_D3D_FULL_SCREEN || q == QUNS_PRESENTATION_MODE || q == QUNS_BUSY))- return true;- HWND fg = GetForegroundWindow();- if (!IsFullscreen(fg)) return false;- return !mon || MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST) == mon;-}--// Com mais de um monitor, só some o que está no monitor do app em tela cheia (a barra daquele monitor; o Dock-// se ele estiver lá). Tela travada: tudo some.-static void CheckFullscreen() {- HWND fg = GetForegroundWindow();- bool locked = bloqueio::Active();- bool fs = !locked && IsFullscreen(fg);- HMONITOR fm = fs ? MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST) : nullptr;- { // registro: quem fez o Dock e a barra de menus sumirem (uma vez por janela)- static HWND visto;- if (fs && fg != visto) {- wchar_t c[80] = {}, t[80] = {}; GetClassNameW(fg, c, 80); GetWindowTextW(fg, t, 80);- DWORD pid = 0; GetWindowThreadProcessId(fg, &pid);- Log(L"tela cheia: janela %p classe '%ls' título '%ls' pid %lu estilo %08lX ex %08lX", fg, c, t, pid, GetWindowLongW(fg, GWL_STYLE), GetWindowLongW(fg, GWL_EXSTYLE));- }- visto = fs ? fg : nullptr;- }- dock::SetFullscreen(locked || (fs && fm == dock::MonitorHandle()));- menubar::SetFullscreen(locked || fs, fm);- ilha::SetFullscreen(locked); // a ilha confere sozinha a tela cheia do monitor principal (jogo, vídeo, app)-}--static void CALLBACK OnWinEvent(HWINEVENTHOOK, DWORD ev, HWND h, LONG obj, LONG, DWORD, DWORD) {- // maximizada por cima da barra/do Dock (issue #24): qualquer janela de topo (a conferência é barata e sai cedo)- if (ev == EVENT_OBJECT_LOCATIONCHANGE && obj == OBJID_WINDOW && !shell::nativo && h && GetAncestor(h, GA_ROOT) == h) limites::Maximizada(h);- if (ev == EVENT_OBJECT_LOCATIONCHANGE && (obj != OBJID_WINDOW || h != GetForegroundWindow())) return;- if (ev == EVENT_SYSTEM_FOREGROUND) { revelar::Foreground(h); jogo::Foreground(h); }- CheckFullscreen();-}--static void Changed() {- if (apps::Refresh()) dock::Update();- menubar::Update();-}--// Aparência "Automático" (Ajustes do Sistema): claro das 7h às 19h, escuro no resto do dia.-static void AutoAppearance() {- if (shell::Setting(L"aparencia_auto", L"0") != L"1") return;- SYSTEMTIME st; GetLocalTime(&st);- DWORD want = st.wHour >= 7 && st.wHour < 19 ? 1 : 0, cur = 1, cb = sizeof(cur);- const wchar_t* key = L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";- RegGetValueW(HKEY_CURRENT_USER, key, L"AppsUseLightTheme", RRF_RT_REG_DWORD, nullptr, &cur, &cb);- if (cur == want) return;- RegSetKeyValueW(HKEY_CURRENT_USER, key, L"AppsUseLightTheme", REG_DWORD, &want, sizeof(want));- RegSetKeyValueW(HKEY_CURRENT_USER, key, L"SystemUsesLightTheme", REG_DWORD, &want, sizeof(want));- Log(L"aparência automática: %ls", want ? L"clara" : L"escura");- // numa thread, como na Central (central.cpp): para todas as janelas, o limite de 200 ms vale para CADA uma ocupada,- // e a interface do Shell ficava parada esse tempo todo- std::thread([] { SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)L"ImmersiveColorSet", SMTO_ABORTIFHUNG, 200, nullptr); }).detach();-}--static LRESULT CALLBACK MsgProc(HWND h, UINT m, WPARAM w, LPARAM l) {- if (m == WM_NA_INTERFACE) { auto* p = (std::function<void()>*)l; if (p) { (*p)(); delete p; } return 0; }- // Outro programa (o Explorador, com a barra do Windows escondida ou em ocultar automaticamente) devolveu a área de- // trabalho para a tela inteira: reaplica a nossa NA HORA. Antes esperava o tique de 1 s, e nesse meio-tempo as- // janelas maximizadas e os ícones da mesa subiam para baixo da barra de menus e voltavam (issue #1: "a área- // pula sem parar"). O nosso próprio SPI_SETWORKAREA vai sem aviso (sem SPIF_SENDCHANGE), então não volta aqui.- if (m == WM_SETTINGCHANGE && w == SPI_SETWORKAREA && !g_quitting) {- static DWORD win = 0; static int n = 0;- DWORD now = GetTickCount();- if (now - win > 1000) { win = now; n = 0; }- if (++n <= 8) shell::ApplyWorkArea(); // no máximo 8 por segundo (se alguém brigar sem parar, não gira em laço)- }- static UINT reload = RegisterWindowMessageW(L"ShellAjustesMudaram");- static UINT openCC = RegisterWindowMessageW(L"ShellAbrirCentral"); // abre/fecha a Central de Controle de fora- static UINT restart = RegisterWindowMessageW(L"ShellReiniciar"); // reiniciar: sai sem abrir o Explorador e abre o Shell de novo- if (m == restart && restart) {- // o Shell novo abre já (no mesmo caminho: depois de compilar, é a versão nova) e espera este sair- wchar_t exe[MAX_PATH]; GetModuleFileNameW(nullptr, exe, MAX_PATH);- std::wstring dir = exe; dir = dir.substr(0, dir.find_last_of(L'\\'));- std::wstring cmd = std::wstring(L"\"") + exe + L"\" --depois-de " + std::to_wstring(GetCurrentProcessId());- STARTUPINFOW si{ sizeof(si) }; PROCESS_INFORMATION pi{};- if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, dir.c_str(), &si, &pi)) { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); }- else Log(L"reiniciar: não abriu o Shell novo (%lu)", GetLastError());- mesa::NoExplorerOnExit();- tray::SemAvisoAoSair();- janelas::ManterAoReiniciar(); // as janelas ficam com a barra do Mac (o Shell novo assume; ver janelas::Stop)- shell::Quit(L"reiniciar");- return 0;- }- if (m == openCC && openCC) { central::Toggle(); return 0; }- static UINT openNC = RegisterWindowMessageW(L"ShellAbrirNotificacoes"); // abre/fecha a Central de Notificações de fora- if (m == openNC && openNC) { notificacoes::Toggle(); return 0; }- static UINT openSP = RegisterWindowMessageW(L"ShellAbrirSpotlight"); // abre/fecha o Spotlight de fora (como o Win+Espaço)- if (m == openSP && openSP) { PostMessageW(h, WM_APP_SPOTLIGHT, 0, 0); return 0; }- // abre um painel de fora (fotos do README, testes): 1 Launchpad/Apps, 2 Mission Control, 3..6 Spotlight no modo 1..4,- // 7 Spotlight, 8 Sobre Este Mac- static UINT openPanel = RegisterWindowMessageW(L"ShellAbrirPainel");- if (m == openPanel && openPanel) {- // pedido de fora: o Windows não deixa o Shell vir para a frente sozinho (o Spotlight e o Launchpad fechavam na- // hora, sem foco). Entra na fila de entrada da janela da frente enquanto abre, como os alertas fazem.- HWND fg = GetForegroundWindow();- DWORD ft = fg ? GetWindowThreadProcessId(fg, nullptr) : 0, me = GetCurrentThreadId();- bool att = ft && ft != me && AttachThreadInput(me, ft, TRUE);- if (w == 1) launchpad::Toggle();- else if (w == 2) missioncontrol::Toggle();- else if (w >= 3 && w <= 6) spotlight::OpenMode((int)w - 2);- else if (w == 7) spotlight::Toggle();- else if (w == 8) sobre::Show(); // Sobre Este Mac- else if (w == 9) central::Toggle(); // Central de Controle (testes)- else if (w == 10) notificacoes::Toggle(); // Central de Notificações (testes)- else if (w == 12) dock::OpenAppsStack(); // Leopard: a pilha Aplicativos (testes)- else if (w == 13) seletor::Step(1); // o seletor de apps sem segurar o Alt (testes; 14 fecha)- else if (w == 14) seletor::Key(VK_ESCAPE);- else if (w == 15) dock::OpenDownloadsStack(); // a pilha Downloads (testes)- else if (w == 16) dashboard::Toggle(); // Leopard: Dashboard (Win+F12)- else if (w == 17) espacos::Toggle(); // Leopard: Spaces (Win+F8)- else if (w == 18) tempo::Enter(); // Leopard: a viagem no tempo do Time Machine- else if (w == 11) { // Quick Look de uma foto do macOS 27 (testes)- wchar_t p[MAX_PATH] = {}; GetEnvironmentVariableW(L"USERPROFILE", p, MAX_PATH);- quicklook::Toggle(std::wstring(p) + L"\\Pictures\\Wallpapers macOS\\macOS 27\\macos-27-golden-4096x2160-27635.jpg");- }- if (att) AttachThreadInput(me, ft, FALSE);- return 0;- }- if (atualizacao::Handle(m)) return 0;- // Ajustes > Aparência > "Reiniciar o Liquid Glass": refaz o vidro real do zero (se ele desistiu ou travou)- static UINT redoGlass = RegisterWindowMessageW(L"ShellReiniciarVidro");- if (m == redoGlass && redoGlass) { backdrop::Restart(); return 1; }- static UINT capVis = RegisterWindowMessageW(L"ShellCapturaVisivel"); // a Captura de Tela vai tirar a foto- if (m == capVis && capVis) { backdrop::CaptureVisible(w != 0); return 1; }- static UINT capDone = RegisterWindowMessageW(L"ShellCapturaFeita"); // a Captura salvou (0) ou copiou (1): aviso na ilha- if (m == capDone && capDone) { ilha::Captura(w != 0); return 0; }- if (m == WM_COPYDATA && l && ((COPYDATASTRUCT*)l)->dwData == 0x4C504150 /*'PAPL'*/) { // Ajustes: papel de parede escolhido- auto* cd = (COPYDATASTRUCT*)l;- if (!cd->lpData || cd->cbData < sizeof(wchar_t) || cd->cbData > 4096) return FALSE;- std::wstring p((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t));- while (!p.empty() && !p.back()) p.pop_back();- mesa::WallpaperNow(p);- return TRUE;- }- if (m == WM_COPYDATA && l && ((COPYDATASTRUCT*)l)->dwData == 0x514C4F4B /*'QLOK'*/) { // Finder: Quick Look (vazio = fechar)- auto* cd = (COPYDATASTRUCT*)l;- if (cd->cbData > 8192) return FALSE;- std::wstring p = cd->lpData ? std::wstring((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t)) : L"";- while (!p.empty() && !p.back()) p.pop_back();- // responde já e abre logo depois: o vídeo leva mais que o tempo de espera do Finder (0,8 s), e ele achava- // que tinha falhado e abria também o painel antigo dele- auto* copy = new std::wstring(p);- PostMessageW(h, WM_APP + 77, 0, (LPARAM)copy);- return TRUE;- }- // 'SIRI': pergunta à Siri (texto UTF-16) vinda de fora (atalhos, scripts, testes); 'BRIL': mostra o brilho n (0-100)- // na Ilha como se a tela tivesse mudado (teste do aviso num PC de mesa, que não manda o evento do WMI)- if (m == WM_COPYDATA && l && (((COPYDATASTRUCT*)l)->dwData == 0x49524953 /*'SIRI'*/ || ((COPYDATASTRUCT*)l)->dwData == 0x4C495242 /*'BRIL'*/)) {- auto* cd = (COPYDATASTRUCT*)l;- if (!cd->lpData || cd->cbData < sizeof(wchar_t) || cd->cbData > 16384) return FALSE;- std::wstring t((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t));- while (!t.empty() && !t.back()) t.pop_back();- if (cd->dwData == 0x4C495242) { ilha::Brilho(_wtoi(t.c_str())); return TRUE; }- PostMessageW(h, WM_APP + 78, 0, (LPARAM)new std::wstring(t)); // depois de responder: quem mandou não fica esperando- return TRUE;- }- if (m == WM_APP + 78 && l) { std::unique_ptr<std::wstring> q((std::wstring*)l); siri::Perguntar(*q); return 0; }- if (m == WM_APP + 77 && l) { // o Quick Look pedido pelo Finder (acima)- std::unique_ptr<std::wstring> p((std::wstring*)l);- if (p->empty()) quicklook::Close();- else quicklook::Toggle(*p, false); // o Finder fica com o foco- return 0;- }- if (m == WM_COPYDATA && l && ((COPYDATASTRUCT*)l)->dwData == 0x414D504C /*'AMPL'*/) { // MacJanela.dll: ampliar animado- struct Msg { unsigned long long hwnd; RECT from, to; int flags; COLORREF cap; };- auto* cd = (COPYDATASTRUCT*)l;- if (cd->cbData != sizeof(Msg) || !cd->lpData) return FALSE;- auto* mm = (Msg*)cd->lpData;- // nativo: janelas de barra própria (flags 8: Chrome, Edge, Electron...) têm a barra do Mac por fora (barras.cpp).- // A animação usa uma foto da janela de verdade, com a barra e os botões do Windows: por meio segundo as- // bolinhas sumiam e apareciam os botões antigos (vídeo do usuário de 12/11/2026). Sem animação: muda na hora.- if (shell::nativo && (mm->flags & 8)) return FALSE;- return ampliar::Start((HWND)(UINT_PTR)mm->hwnd, mm->from, mm->to, mm->flags, mm->cap) ? TRUE : FALSE;- }- static UINT ampFoto = RegisterWindowMessageW(L"ShellAmpliarFoto"); // MacJanela.dll: a janela já mudou de tamanho- if (m == ampFoto && ampFoto) { ampliar::SecondPhoto((HWND)w); return 0; }- static UINT iconeMudou = RegisterWindowMessageW(L"ShellIconeMudou"); // ícone próprio de um app escolhido/restaurado (apps.cpp)- if (m == iconeMudou && iconeMudou) { apps::ReloadIcons(); Log(L"ícone próprio: Dock, Alt+Tab e Launchpad recarregados"); return 0; }- static UINT ampPronto = RegisterWindowMessageW(L"ShellAmpliarPronto"); // a janela já reapareceu- if (m == ampPronto && ampPronto) { ampliar::Shown((HWND)w); return 0; }- static UINT menuVerde = RegisterWindowMessageW(L"ShellMenuVerde"); // ponteiro parado no botão verde (DLL ou app nosso)- if (m == menuVerde && menuVerde) { verde::Show((HWND)w, POINT{ (short)LOWORD(l), (short)HIWORD(l) }); return 0; }- static UINT jAbrir = RegisterWindowMessageW(L"ShellJanelaAbrir"); // WacOSWindow.dll: janela nova, escondida e pintada- if (m == jAbrir && jAbrir) { abrir::Open((HWND)w, (HWND)l); return 0; }- static UINT jFechar = RegisterWindowMessageW(L"ShellJanelaFechar"); // WacOSWindow.dll: a janela vai sumir agora- if (m == jFechar && jFechar) return ampliar::Fechar((HWND)w, l) ? 1 : 0;- if (m == WM_COPYDATA && l) { // o Ajustes do Sistema manda "chave=valor": o Shell grava no arquivo que ele mesmo lê- // (o Ajustes pode estar num contêiner que desvia o %APPDATA% dele para outra cópia do ajustes.txt)- auto* cd = (COPYDATASTRUCT*)l;- if (cd->dwData == 0x534A5354 /*'SJST'*/ && cd->lpData && cd->cbData >= sizeof(wchar_t)) {- std::wstring kv((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t));- while (!kv.empty() && !kv.back()) kv.pop_back();- size_t eq = kv.find(L'=');- if (eq != std::wstring::npos && eq > 0 && eq < 128 && kv.find(L'\n') == std::wstring::npos) {- shell::SetSetting(kv.substr(0, eq).c_str(), kv.substr(eq + 1));- PostMessageW(h, reload, 0, 0);- }- return TRUE;- }- }- if (m == reload && reload) { // o Ajustes do Sistema gravou ajustes.txt- g_macKeys = !shell::SoDock() && shell::Setting(L"atalhos_mac", L"1") == L"1";- static int lastLiquid = -1;- if (lastLiquid < 0) lastLiquid = liquid::Leopard() ? 3 : liquid::Golden() ? 2 : liquid::On();- static int lastTheme = -1; // 0 Sequoia, 1 Tahoe, 2 Golden Gate, 3 Leopard- auto themeNow = [] { return liquid::Leopard() ? 3 : liquid::Golden() ? 2 : (int)liquid::On(); };- if (lastTheme < 0) lastTheme = themeNow();- LoadSettings();- ilha::Reload();- { // barra_todos_monitores mudou: cria ou tira as barras dos monitores secundários (e a área de trabalho deles)- static std::wstring lastAll = L"?";- std::wstring all = shell::Setting(L"barra_todos_monitores", L"1");- if (lastAll != L"?" && all != lastAll) { menubar::Displays(); dock::ReloadSettings(); }- lastAll = all;- static std::wstring lastBaixo = L"?"; // barra de menus em cima ou na linha do Dock (issue #29)- std::wstring baixo = shell::Setting(L"barra_embaixo", L"0");- if (baixo != lastBaixo) { menubar::Displays(); dock::ReloadSettings(); }- lastBaixo = baixo;- static std::wstring lastOcultar = L"?"; // ocultar a barra de menus automaticamente (issue #40)- std::wstring ocultar = shell::Setting(L"barra_ocultar", L"0");- if (lastOcultar != L"?" && ocultar != lastOcultar) { menubar::Displays(); dock::ReloadSettings(); }- lastOcultar = ocultar;- }- static int lastLang = -1;- if (lastLang < 0) lastLang = idioma::Current();- if (int lang = idioma::FromCode(shell::Setting(L"idioma", L"en")); lang != lastLang) { // Ajustes > Geral > Idioma- lastLang = lang;- idioma::Set(lang);- apps::Relabel();- dock::IconsChanged();- Log(L"idioma: %ls", idioma::Code());- }- if ((liquid::Leopard() ? 3 : liquid::Golden() ? 2 : (int)liquid::On()) != lastLiquid) { // tema Sequoia/Tahoe/Golden Gate/Leopard: outro pacote de ícones- lastLiquid = liquid::Leopard() ? 3 : liquid::Golden() ? 2 : liquid::On();- for (auto& a : apps::list) { a.icon.clear(); a.iw = a.ih = 0; a.mac = false; }- dock::IconsChanged();- seletor::IconsChanged();- Log(L"tema mudou: ícones do Dock e do seletor recarregados");- }- if (themeNow() != lastTheme) {- // tema trocado: as janelas com a barra do Mac (WacOSWindow.dll) redesenham já (barra metálica e botões de gel- // do Leopard, ou de volta) em vez de esperar a próxima ativação- lastTheme = themeNow();- EnumWindows([](HWND w, LPARAM msg) -> BOOL {- if (GetPropW(w, L"MacJanela")) PostMessageW(w, (UINT)msg, 0, 0);- return TRUE;- }, (LPARAM)reload);- Log(L"tema: %d (janelas avisadas)", lastTheme);- ponteiro::TemaLeopard(lastTheme == 3); // Leopard: cursor do Mac OS X; saindo, o cursor de antes- }- dock::ReloadSettings();- dock::ApplyTheme();- menubar::ApplyTheme();- menubar::Update();- shell::ApplyWorkArea();- mesa::SettingsChanged();- widgets::SettingsChanged(); // Personalizar a Mesa: widgets ligados/desligados- jogo::Reload(); // modo_jogo e jogos.txt- palco::Sync();- // "Clicar no papel de parede para mostrar a mesa" saiu de "Nunca": com o Shell aberto em "Nunca" o gancho do mouse- // nunca era criado e a opção nova só valia depois de reiniciar (Start não faz nada se já estiver ligado)- if (!shell::SoDock() && !jogo::Ativo()) revelar::Start();- return 0;- }- if (m == WM_SHELLHOOK && WM_SHELLHOOK) {- switch (w & 0x7FFF) {- case HSHELL_WINDOWCREATED: case HSHELL_WINDOWDESTROYED: case HSHELL_WINDOWACTIVATED: case HSHELL_REDRAW:- Changed();- if ((w & 0x7FFF) == HSHELL_REDRAW && (w & 0x8000)) { // HSHELL_FLASH: app pedindo atenção- apps::Refresh();- if (App* a = apps::OfWindow((HWND)l)) { a->attentionAt = GetTickCount(); dock::Update(); }- }- break;- case HSHELL_GETMINRECT: { // para onde a janela encolhe ao minimizar: o Dock, antes da Lixeira- auto* shi = (SHELLHOOKINFO*)l;- RECT r{};- if (shi && genio::OnMinRect(shi->hwnd, &r)) { shi->rc = r; return TRUE; } // o gênio já começou, com a janela ainda na tela- r = dock::MinimizeTarget(shi ? shi->hwnd : nullptr);- if (shi && r.right > r.left) { shi->rc = r; SetTimer(g_msg, 7, 450, nullptr); return TRUE; } // e o Dock se atualiza logo depois- break;- }- }- return 0;- }- switch (m) {- case WM_TIMER:- if (w == 7) { KillTimer(g_msg, 7); Changed(); return 0; }- if (w == 1) {- static int ticks;- if (ticks++ % 60 == 0) AutoAppearance();- Changed(); CheckFullscreen(); HideTaskbars(); shell::ApplyWorkArea(); if (shell::Setting(L"finder_reserva", L"1") == L"1") EnsureReserve(); EnsureScreenshot();- }- if (w == 2) tray::Keepalive();- if (w == 9) { // extensões do menu de contexto carregadas cedo: o 1º botão direito na mesa/Spotlight/Launchpad sai rápido- KillTimer(g_msg, 9);- wchar_t* p = nullptr; std::wstring desk;- if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Desktop, 0, nullptr, &p))) { desk = p; CoTaskMemFree(p); }- std::wstring file;- WIN32_FIND_DATAW fd; HANDLE fh = desk.empty() ? INVALID_HANDLE_VALUE : FindFirstFileW((desk + L"\\*").c_str(), &fd);- if (fh != INVALID_HANDLE_VALUE) {- do if (!(fd.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_HIDDEN))) { file = desk + L"\\" + fd.cFileName; break; }- while (FindNextFileW(fh, &fd));- FindClose(fh);- }- if (!desk.empty()) ctxmenu::WarmupAsync(desk, file);- }- return 0;- case WM_HOTKEY: shell::Quit(L"atalho Ctrl+Alt+Shift+F12"); return 0;- case WM_APP_SETTINGS: shell::OpenSettings(L""); return 0;- case WM_APP_SNAP: {- HWND fg = GetForegroundWindow();- if (!fg) return 0;- if (w == VK_LEFT || w == VK_RIGHT) {- HWND root = GetAncestor(fg, GA_ROOT);- if (root && !apps::IsShellWindow(root) && (GetWindowLongW(root, GWL_STYLE) & WS_THICKFRAME)) encaixe::Half(root, w == VK_RIGHT);- return 0;- }- // o "ampliar" do Mac (MacJanela.dll): ocupa a área de trabalho e mantém cantos e sombra- static UINT zoom = RegisterWindowMessageW(L"MacJanelaAmpliar");- bool ampliada = GetPropW(fg, L"MacJanelaAmpliada") != nullptr;- if (w == VK_UP) { if (!ampliada) PostMessageW(fg, zoom, 0, 0); }- else if (ampliada) PostMessageW(fg, zoom, 0, 0);- else ShowWindowAsync(fg, SW_MINIMIZE);- return 0;- }- case WM_APP_MISSION:- if (launchpad::IsOpen()) launchpad::Toggle();- shell::LiberaFrente(); // permite ao Mission Control vir para a frente- missioncontrol::Toggle();- return 0;- case WM_APP_EXPOSE: {- HWND fg = GetForegroundWindow();- HWND root = fg ? GetAncestor(fg, GA_ROOTOWNER) : nullptr;- apps::Refresh();- App* a = root && !apps::IsShellWindow(root) ? apps::OfWindow(root) : nullptr;- if (!a) { Log(L"Exposé do app: a janela da frente não é de um app do Dock"); return 0; }- if (launchpad::IsOpen()) launchpad::Toggle();- shell::LiberaFrente(); // permite ao Exposé vir para a frente- missioncontrol::ToggleApp(a->id, a->name);- return 0;- }- case WM_APP_MACKEY: {- HWND fg = GetForegroundWindow();- HWND root = fg ? GetAncestor(fg, GA_ROOT) : nullptr;- if (!root || apps::IsShellWindow(root) || apps::IsShellWindow(GetAncestor(root, GA_ROOTOWNER))) return 0; // Dock, mesa, painéis- if (w == 'W') { // fecha só a janela da frente (o app continua aberto)- Log(L"atalho Win+W: fechando a janela %p", root);- PostMessageW(root, WM_SYSCOMMAND, SC_CLOSE, 0);- return 0;- }- apps::Refresh();- App* a = apps::OfWindow(GetAncestor(root, GA_ROOTOWNER));- if (!a) a = apps::OfWindow(root);- if (!a) { Log(L"atalho Win+%lc: janela da frente sem app no Dock", (wchar_t)w); return 0; }- if (w == 'Q') {- if (a->finder) return 0; // como no Mac: o Finder não se encerra- Log(L"atalho Win+Q: encerrando %ls", a->name.c_str());- apps::Quit(*a);- } else {- Log(L"atalho Win+H: ocultando %ls", a->name.c_str());- apps::Hide(*a);- }- dock::Update();- return 0;- }- case WM_APP_LOCK:- bloqueio::Lock(); // o bloqueio do Windows (a tela do WacOS saiu)- return 0;- case WM_APP_MONITOR:- if (w == 1) shell::OpenForceQuit(false); else shell::OpenMonitor();- return 0;- case WM_APP_SWITCH: seletor::Step((int)(INT_PTR)w); return 0;- case WM_APP_SWITCH_KEY: seletor::Key((UINT)w); return 0;- case WM_APP_SWITCH_END: seletor::Release(); return 0;- case WM_APP_SPOTLIGHT:- if (launchpad::IsOpen()) launchpad::Toggle();- shell::LiberaFrente(); // permite ao Spotlight vir para a frente e receber o teclado- spotlight::Toggle();- return 0;- case WM_APP_LAUNCHPAD:- shell::LiberaFrente(); // permite ao Launchpad vir para a frente- launchpad::Toggle();- return 0;- case WM_APP_WINKEY: mesa::WinKey((UINT)w); return 0;- case WM_APP_CAPTURA: Screenshot((int)w, l != 0); return 0;+static void ShowTaskbars() {+ for (HWND h : g_hiddenBars) if (IsWindow(h)) ShowWindowAsync(h, SW_SHOWNOACTIVATE);+ g_hiddenBars.clear();+ // issue #37 (a barra do Windows sumia ao sair): o Explorador que reiniciou com o Shell aberto cria uma barra nova,+ // que não está na lista acima. Toda barra do Explorador escondida volta.+ EnumWindows([](HWND h, LPARAM) -> BOOL {+ wchar_t c[64] = {}; GetClassNameW(h, c, 64);+ if ((!wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd")) && !apps::IsShellWindow(h) && !IsWindowVisible(h)) {+ DWORD pid = 0; GetWindowThreadProcessId(h, &pid);+ if (pid != GetCurrentProcessId()) ShowWindowAsync(h, SW_SHOWNOACTIVATE);+ }+ return TRUE;+ }, 0);+}++// Barra do Windows nos outros monitores: só esconder não segurava (o Explorador a mostrava de novo e ela+// reservava espaço). Enquanto o Shell roda, desliga "Mostrar a barra de tarefas em todos os monitores"+// (HKCU ...\Explorer\Advanced\MMTaskbarEnabled = 0, a mesma chave da Configuração do Windows). O valor de antes+// fica em ajustes.txt (barra_windows_monitores_antes: 0, 1 ou "x" = não existia) e volta ao sair.+static const wchar_t* MM_KEY = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";++static void TellExplorerTray() { // o Explorador relê o ajuste da barra (como a Configuração faz)+ std::thread([] {+ EnumWindows([](HWND h, LPARAM) -> BOOL {+ wchar_t c[64] = {}; GetClassNameW(h, c, 64);+ if (!wcscmp(c, L"Shell_TrayWnd") && !apps::IsShellWindow(h))+ SendMessageTimeoutW(h, WM_SETTINGCHANGE, 0, (LPARAM)L"TraySettings", SMTO_ABORTIFHUNG, 1000, nullptr);+ return TRUE;+ }, 0);+ }).detach();+}++static void SecondaryTaskbarsOff() {+ if (shell::nativo) return;+ DWORD v = 0, cb = sizeof(v);+ bool had = RegGetValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled", RRF_RT_REG_DWORD, nullptr, &v, &cb) == ERROR_SUCCESS;+ if (had && v == 0) return; // já desligado (pelo usuário ou por nós antes)+ if (shell::Setting(L"barra_windows_monitores_antes", L"").empty())+ shell::SetSetting(L"barra_windows_monitores_antes", had ? std::to_wstring(v) : L"x");+ DWORD zero = 0;+ if (RegSetKeyValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled", REG_DWORD, &zero, sizeof(zero)) == ERROR_SUCCESS) {+ Log(L"registro: HKCU\\%ls\\MMTaskbarEnabled = 0 (antes: %ls) - barra do Windows só no monitor principal", MM_KEY, had ? std::to_wstring(v).c_str() : L"não existia");+ TellExplorerTray();+ }+}++static void SecondaryTaskbarsRestore() {+ std::wstring before = shell::Setting(L"barra_windows_monitores_antes", L"");+ if (before.empty()) return;+ if (before == L"x") RegDeleteKeyValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled");+ else { DWORD v = (DWORD)_wtoi(before.c_str()); RegSetKeyValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled", REG_DWORD, &v, sizeof(v)); }+ shell::SetSetting(L"barra_windows_monitores_antes", L"");+ Log(L"registro: MMTaskbarEnabled devolvido (%ls)", before == L"x" ? L"apagado, não existia" : before.c_str());+ TellExplorerTray();+}++// Área de trabalho de cada monitor: a barra de menus em cima (todos têm a sua) e o Dock embaixo (só no+// monitor dele). O SPI_SETWORKAREA vale para o monitor que contém o retângulo.+std::vector<HWND> shell::AlheiasNoTopo() {+ std::vector<HWND> v; // de cima para baixo+ DWORD eu = GetCurrentProcessId();+ for (HWND w = GetTopWindow(nullptr); w && v.size() < 32; w = GetWindow(w, GW_HWNDNEXT)) {+ if (!(GetWindowLongW(w, GWL_EXSTYLE) & WS_EX_TOPMOST)) break; // acabou a faixa das "sempre por cima"+ if (!IsWindowVisible(w)) continue;+ DWORD pid = 0; GetWindowThreadProcessId(w, &pid);+ if (pid == eu) break; // daqui para baixo já estavam abaixo das nossas+ DWORD cloak = 0; DwmGetWindowAttribute(w, DWMWA_CLOAKED, &cloak, sizeof(cloak));+ if (cloak) continue;+ wchar_t c[64] = {}; GetClassNameW(w, c, 64);+ if (!wcscmp(c, L"tooltips_class32") || !wcscmp(c, L"#32768") || !wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd")) continue;+ RECT r; if (!GetWindowRect(w, &r) || r.right - r.left < 2 || r.bottom - r.top < 2) continue;+ v.push_back(w);+ }+ return v;+}++void shell::DevolveAlheias(const std::vector<HWND>& v) {+ for (auto it = v.rbegin(); it != v.rend(); ++it) // de baixo para cima: a de cima termina por cima+ if (IsWindow(*it) && IsWindowVisible(*it))+ SetWindowPos(*it, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_ASYNCWINDOWPOS);+}++RECT shell::WorkAreaFor(HMONITOR hm) {+ MONITORINFO mi{ sizeof(mi) };+ if (!GetMonitorInfoW(hm, &mi)) return {};+ RECT want = mi.rcMonitor;+ want.top += menubar::ReservedOn(hm); // secundário sem barra (barra_todos_monitores=0): o topo é das janelas+ if (hm == dock::MonitorHandle()) { // o Dock na borda escolhida (Ajustes > Posição na tela)+ int r = dock::ReservedHeight();+ if (dock::Posicao() == 1) want.left += r;+ else if (dock::Posicao() == 2) want.right -= r;+ else want.bottom -= std::max(r, menubar::ReservedBottom(hm)); // barra embaixo: com o Dock oculto, a altura dela+ }+ return want;+}++void shell::ApplyWorkArea() {+ if (g_quitting) return;+ struct Ctx { HMONITOR dock; bool changed; } ctx{ dock::MonitorHandle(), false };+ EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hm, HDC, LPRECT, LPARAM p) -> BOOL {+ auto* c = (Ctx*)p;+ MONITORINFO mi{ sizeof(mi) };+ if (!GetMonitorInfoW(hm, &mi)) return TRUE;+ RECT want = shell::WorkAreaFor(hm), cur = mi.rcWork;+ (void)c;+ if (EqualRect(&want, &cur)) return TRUE;+ static int times;+ Log(L"área de trabalho estava %d,%d-%d,%d; agora %d,%d-%d,%d (vez %d)", cur.left, cur.top, cur.right, cur.bottom,+ want.left, want.top, want.right, want.bottom, ++times);+ // Sem SPIF_SENDCHANGE: o aviso geral fazia o Explorador recalcular e desfazer (briga a cada 2 s).+ SystemParametersInfoW(SPI_SETWORKAREA, 0, &want, 0);+ c->changed = true;+ return TRUE;+ }, (LPARAM)&ctx);+ if (!ctx.changed) return;+ // Avisa só as janelas dos apps: o DefWindowProc reencaixa as maximizadas na área nova.+ EnumWindows([](HWND h, LPARAM) -> BOOL {+ if (!IsWindowVisible(h) || apps::IsShellWindow(h)) return TRUE;+ wchar_t c[64]; GetClassNameW(h, c, 64);+ if (!wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd") || mesa::IsDeskClass(c)) return TRUE;+ if (IsZoomed(h)) SendMessageTimeoutW(h, WM_SETTINGCHANGE, SPI_SETWORKAREA, 0, SMTO_ABORTIFHUNG, 200, nullptr);+ return TRUE;+ }, 0);+}++static void Restore() {+ if (g_quitting) return;+ g_quitting = true;+ tray::Stop();+ menus::Stop();+ dialogs::Stop();+ janelas::Stop();+ encaixe::Stop();+ memoria::Stop();+ barras::Stop();+ sombras::Stop();+ alertas::Stop();+ progresso::Stop(); // as janelas de progresso do Windows voltam para a tela+ if (!shell::nativo) { // no nativo a tela de bloqueio continua do Windows (não foi trocada)+ bloqueio::Stop(); // Win+L volta para o Windows (política apagada)+ mesa::Stop(!g_crashed && !g_sessionEnding); // sem Explorador: ele volta (ao cair, quem abre é o vigia)+ } else mesa::Stop(true); // nativo: a nossa mesa some e a do Explorador (que ficou atrás) reaparece+ revelar::Stop(); // janelas que estavam nas bordas voltam+ ponteiro::Stop(); // o cursor volta ao tamanho do esquema+ palco::Stop(); // Organizador Visual: as janelas escondidas por ele voltam+ genio::Stop(); // a animação de minimizar do Windows volta como estava+ notificacoes::Stop(); // o banner de notificação do Windows volta+ ShowTaskbars();+ SecondaryTaskbarsRestore();+ // os outros monitores voltam inteiros (a barra do Windows, se voltar lá, reserva o espaço dela)+ EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hm, HDC, LPRECT, LPARAM) -> BOOL {+ MONITORINFO mi{ sizeof(mi) };+ if (GetMonitorInfoW(hm, &mi) && !(mi.dwFlags & MONITORINFOF_PRIMARY)) SystemParametersInfoW(SPI_SETWORKAREA, 0, &mi.rcMonitor, 0);+ return TRUE;+ }, 0);+ SystemParametersInfoW(SPI_SETWORKAREA, 0, &g_origWork, SPIF_SENDCHANGE);+ Log(L"saindo: barra do Windows e área de trabalho devolvidas");+}++// Saindo de verdade (não o reiniciar): o WacOS fecha por inteiro (issue #37: depois de sair, o Win+E e as pastas+// ainda abriam o Finder, e o Finder reserva e a Captura residente continuavam abertos, escondidos).+// As pastas voltam para o Explorador e finder_volta=1 faz o Shell, ao abrir de novo, devolvê-las ao Finder (o mesmo+// caminho do "Desligar o WacOS"). Quem desligou "Abrir pastas no Finder" à mão (finder_padrao=0) não é mexido.+static void SaiPorInteiro() {+ static UINT capMsg = RegisterWindowMessageW(L"SequoiaCaptura");+ if (HWND w = FindWindowW(L"SequoiaCapturaMsg", nullptr)) PostMessageW(w, capMsg, 0, 0); // wParam 0 = sair+ if (HWND w = FindWindowW(L"ArquivosJanela", L"ArquivosReserva")) // a reserva nunca foi usada: não tem nada do usuário+ PostThreadMessageW(GetWindowThreadProcessId(w, nullptr), WM_QUIT, 0, 0);+ std::wstring finder = shell::dir + L"\\" EXE_FINDER;+ if (shell::Setting(L"finder_padrao", L"1") == L"1" && GetFileAttributesW(finder.c_str()) != INVALID_FILE_ATTRIBUTES) {+ shell::SetSetting(L"finder_volta", L"1");+ std::wstring cmd = L"\"" + finder + L"\" --padrao off --quieto";+ STARTUPINFOW si{ sizeof(si) }; si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;+ PROCESS_INFORMATION pi{};+ if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, shell::dir.c_str(), &si, &pi)) {+ WaitForSingleObject(pi.hProcess, 3000); // antes de uma atualização abrir o Shell novo (que religa)+ CloseHandle(pi.hThread); CloseHandle(pi.hProcess);+ Log(L"saindo: pastas e Win+E de volta ao Explorador (o Finder volta ao abrir o WacOS)");+ }+ }+}++void shell::Quit(const wchar_t* why) {+ Log(L"pedido para sair: %ls", why);+ if (wcscmp(why, L"reiniciar")) SaiPorInteiro();+ pastas::Stop();+ limites::Stop();+ bloqueio::Fallback(); // saiu com a tela travada (ex.: Ctrl+Alt+Shift+F12): o Windows bloqueia+ Restore();+ PostQuitMessage(0);+}++static LONG WINAPI OnCrash(EXCEPTION_POINTERS* ep) {+ HMODULE mod = nullptr;+ void* at = ep->ExceptionRecord->ExceptionAddress;+ GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)at, &mod);+ wchar_t name[MAX_PATH] = L"?"; if (mod) GetModuleFileNameW(mod, name, MAX_PATH);+ Log(L"ERRO 0x%08X em %ls+0x%llX", ep->ExceptionRecord->ExceptionCode, name, (unsigned long long)((BYTE*)at - (BYTE*)mod));+ bloqueio::Fallback(); // caiu com a tela travada: o Windows bloqueia de verdade+ g_crashed = true;+ Restore(); // nunca deixar o usuário sem barra de tarefas+ return EXCEPTION_CONTINUE_SEARCH;+}++// Finder reserva: um Arquivos.exe já inicializado e escondido. Abrir uma pasta, o Win+E ou a janela+// de Abrir/Salvar entregam o pedido a ele (aparece na hora); quando é usado, preparamos outro.+// Captura de Tela (WacOSScreenshot.exe) sempre aberta e escondida: a mira do Win+Shift+4 aparece na hora+bool shell::SoDock() { static int v = -1; if (v < 0) v = shell::Setting(L"modo", L"completo") == L"dock" ? 1 : 0; return v == 1; }++static void EnsureScreenshot() {+ static DWORD lastSpawn;+ if (g_quitting || !g_capturaExe || FindWindowW(L"SequoiaCapturaMsg", nullptr)) return;+ if (lastSpawn && GetTickCount() - lastSpawn < 10000) return;+ lastSpawn = GetTickCount();+ std::wstring cmd = L"\"" + shell::dir + L"\\" EXE_SCREENSHOT L"\" /residente";+ STARTUPINFOW si{ sizeof(si) };+ PROCESS_INFORMATION pi{};+ std::thread([cmd, si, pi]() mutable { // como o Finder reserva: abrir programa espera o disco+ if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) {+ CloseHandle(pi.hProcess); CloseHandle(pi.hThread);+ Log(L"Captura de Tela residente aberta");+ }+ }).detach();+}++// pedido do atalho: 3 tela inteira, 4 região/janela, 5 barra de ferramentas; clip = Ctrl seguro+static void Screenshot(int kind, bool clip) {+ static UINT msg = RegisterWindowMessageW(L"SequoiaCaptura");+ if (HWND w = FindWindowW(L"SequoiaCapturaMsg", nullptr)) {+ DWORD pid = 0; GetWindowThreadProcessId(w, &pid);+ AllowSetForegroundWindow(pid);+ PostMessageW(w, msg, kind, clip ? 1 : 0);+ return;+ }+ std::wstring args = L"/" + std::to_wstring(kind) + (clip ? L" /c" : L"");+ shell::Abrir(L"open", (shell::dir + L"\\" EXE_SCREENSHOT).c_str(), args.c_str(), nullptr, SW_SHOWNORMAL);+ Log(L"Captura de Tela aberta agora (%ls)", args.c_str());+}++void shell::AbrirFinder(const std::wstring& args) {+ if (shell::nativo) {+ HMODULE m = GetModuleHandleW(L"MacFinder.dll");+ auto pedir = m ? (BOOL(WINAPI*)(const wchar_t*))GetProcAddress(m, "FinderPedir") : nullptr;+ if (pedir && pedir(args.c_str())) { Log(L"Finder (nativo): %ls", args.c_str()); return; }+ Log(L"Finder nativo indisponível, abrindo o exe: %ls", args.c_str());+ }+ shell::Abrir(L"open", (shell::dir + L"\\" EXE_FINDER).c_str(), args.c_str(), nullptr, SW_SHOWNORMAL);+}++static void EnsureReserve() {+ if (shell::nativo) return; // no nativo a reserva é a janela do Finder dentro do explorer (MacFinder.dll)+ static DWORD lastSpawn;+ if (g_quitting || FindWindowW(L"ArquivosJanela", L"ArquivosReserva")) return;+ if (lastSpawn && GetTickCount() - lastSpawn < 4000) return; // um por vez+ lastSpawn = GetTickCount();+ std::wstring cmd = L"\"" + shell::dir + L"\\" EXE_FINDER L"\" --reserva";+ STARTUPINFOW si{ sizeof(si) };+ si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;+ PROCESS_INFORMATION pi{};+ // numa thread: com o disco cheio o CreateProcess levou 2,9 s e a interface esperava (pilha de 22/11/2026, 15:25)+ std::thread([cmd, si, pi]() mutable {+ if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) {+ CloseHandle(pi.hProcess); CloseHandle(pi.hThread);+ Log(L"Finder reserva preparado");+ }+ }).detach();+}++// Pré-carga: lê os .exe dos outros apps do projeto para o cache de arquivos do Windows (memória de+// espera, que o sistema devolve quando precisa). Assim o primeiro clique abre como se já tivesse sido+// aberto antes, sem deixar nenhum processo rodando. Prioridade de fundo, depois que o Shell está pronto.+// os painéis que montam coisa cara na primeira abertura: prepara com o Shell já parado, na thread+// principal (o compositor e a GPU são dela)+static void CALLBACK WarmPanels(HWND, UINT, UINT_PTR id, DWORD) {+ KillTimer(nullptr, id);+ missioncontrol::Warm();+ launchpad::Warm();+}++static void PreloadApps() {+ SetTimer(nullptr, 0, 4000, WarmPanels);+ std::thread([] {+ SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);+ Sleep(3000);+ static const wchar_t* files[] = { EXE_SETTINGS, EXE_NOTES, EXE_CALCULATOR, EXE_TERMINAL, EXE_MONITOR, DLL_WINDOW32 };+ std::vector<char> buf(1 << 20);+ size_t total = 0;+ for (auto* f : files) {+ HANDLE h = CreateFileW((shell::dir + L"\\" + f).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr,+ OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);+ if (h == INVALID_HANDLE_VALUE) continue;+ DWORD got = 0;+ while (ReadFile(h, buf.data(), (DWORD)buf.size(), &got, nullptr) && got) total += got;+ CloseHandle(h);+ }+ Log(L"pré-carga: %zu KB dos apps no cache", total / 1024);+ SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);+ }).detach();+}++// App da frente cobrindo o monitor inteiro (vídeo, jogo, F11): Dock e barra de menus somem, como no Mac.+static bool IsFullscreen(HWND fg) {+ if (!fg || !IsWindowVisible(fg) || IsIconic(fg) || apps::IsShellWindow(fg)) return false;+ // Trocadores de papel de parede com transição (YASB, Lively...) põem a janela da animação DENTRO da mesa do Windows+ // (filha da WorkerW/Progman) e ela fica sendo a "janela da frente". Cobrindo o monitor, parecia um app em tela+ // cheia: o Dock e a barra de menus sumiam e o vidro ficava sem fundo, e como o YASB mantém a janela viva depois da+ // transição, ficava assim até reiniciar o WacOS (Reddit, 23/11/2026; reproduzido com o mesmo truque do YASB).+ // Janela filha conta pela de topo dela: sendo a mesa, não é tela cheia.+ if (HWND root = GetAncestor(fg, GA_ROOT); root && root != fg) {+ wchar_t rc[64] = {}; GetClassNameW(root, rc, 64);+ if (mesa::IsDeskClass(rc)) return false;+ fg = root;+ if (!IsWindowVisible(fg) || IsIconic(fg) || apps::IsShellWindow(fg)) return false;+ }+ wchar_t cls[64] = {}; GetClassNameW(fg, cls, 64);+ if (mesa::IsDeskClass(cls) || !wcscmp(cls, L"Shell_TrayWnd")) return false;+ if (IsZoomed(fg) && (GetWindowLongW(fg, GWL_STYLE) & WS_CAPTION) == WS_CAPTION) return false; // só maximizada+ MONITORINFO mi{ sizeof(mi) };+ if (!GetMonitorInfoW(MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST), &mi)) return false;+ RECT r; if (!GetWindowRect(fg, &r)) return false;+ return r.left <= mi.rcMonitor.left && r.top <= mi.rcMonitor.top && r.right >= mi.rcMonitor.right && r.bottom >= mi.rcMonitor.bottom;+}++// Jogo/vídeo em tela cheia no monitor `mon` (ou o Windows em modo "não incomodar": Direct3D exclusivo,+// apresentação): os banners de notificação não aparecem, só vão para a Central. Uma janela "sempre no topo" por cima+// do jogo tirava ele da tela cheia (17/11/2026, Fortnite caindo a cada notificação).+bool shell::NaoIncomodar(HMONITOR mon) {+ QUERY_USER_NOTIFICATION_STATE q{};+ if (SUCCEEDED(SHQueryUserNotificationState(&q)) && (q == QUNS_RUNNING_D3D_FULL_SCREEN || q == QUNS_PRESENTATION_MODE || q == QUNS_BUSY))+ return true;+ HWND fg = GetForegroundWindow();+ if (!IsFullscreen(fg)) return false;+ return !mon || MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST) == mon;+}++// Com mais de um monitor, só some o que está no monitor do app em tela cheia (a barra daquele monitor; o Dock+// se ele estiver lá). Tela travada: tudo some.+static void CheckFullscreen() {+ HWND fg = GetForegroundWindow();+ bool locked = bloqueio::Active();+ bool fs = !locked && IsFullscreen(fg);+ HMONITOR fm = fs ? MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST) : nullptr;+ { // registro: quem fez o Dock e a barra de menus sumirem (uma vez por janela)+ static HWND visto;+ if (fs && fg != visto) {+ wchar_t c[80] = {}, t[80] = {}; GetClassNameW(fg, c, 80); GetWindowTextW(fg, t, 80);+ DWORD pid = 0; GetWindowThreadProcessId(fg, &pid);+ Log(L"tela cheia: janela %p classe '%ls' título '%ls' pid %lu estilo %08lX ex %08lX", fg, c, t, pid, GetWindowLongW(fg, GWL_STYLE), GetWindowLongW(fg, GWL_EXSTYLE));+ }+ visto = fs ? fg : nullptr;+ }+ dock::SetFullscreen(locked || (fs && fm == dock::MonitorHandle()));+ menubar::SetFullscreen(locked || fs, fm);+ ilha::SetFullscreen(locked); // a ilha confere sozinha a tela cheia do monitor principal (jogo, vídeo, app)+}++static void CALLBACK OnWinEvent(HWINEVENTHOOK, DWORD ev, HWND h, LONG obj, LONG, DWORD, DWORD) {+ // maximizada por cima da barra/do Dock (issue #24): qualquer janela de topo (a conferência é barata e sai cedo)+ if (ev == EVENT_OBJECT_LOCATIONCHANGE && obj == OBJID_WINDOW && !shell::nativo && h && GetAncestor(h, GA_ROOT) == h) limites::Maximizada(h);+ if (ev == EVENT_OBJECT_LOCATIONCHANGE && (obj != OBJID_WINDOW || h != GetForegroundWindow())) return;+ if (ev == EVENT_SYSTEM_FOREGROUND) { revelar::Foreground(h); jogo::Foreground(h); }+ CheckFullscreen();+}++static void Changed() {+ if (apps::Refresh()) dock::Update();+ menubar::Update();+}++// Aparência "Automático" (Ajustes do Sistema): claro das 7h às 19h, escuro no resto do dia.+static void AutoAppearance() {+ if (shell::Setting(L"aparencia_auto", L"0") != L"1") return;+ SYSTEMTIME st; GetLocalTime(&st);+ DWORD want = st.wHour >= 7 && st.wHour < 19 ? 1 : 0, cur = 1, cb = sizeof(cur);+ const wchar_t* key = L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";+ RegGetValueW(HKEY_CURRENT_USER, key, L"AppsUseLightTheme", RRF_RT_REG_DWORD, nullptr, &cur, &cb);+ if (cur == want) return;+ RegSetKeyValueW(HKEY_CURRENT_USER, key, L"AppsUseLightTheme", REG_DWORD, &want, sizeof(want));+ RegSetKeyValueW(HKEY_CURRENT_USER, key, L"SystemUsesLightTheme", REG_DWORD, &want, sizeof(want));+ Log(L"aparência automática: %ls", want ? L"clara" : L"escura");+ // numa thread, como na Central (central.cpp): para todas as janelas, o limite de 200 ms vale para CADA uma ocupada,+ // e a interface do Shell ficava parada esse tempo todo+ std::thread([] { SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)L"ImmersiveColorSet", SMTO_ABORTIFHUNG, 200, nullptr); }).detach();+}++static LRESULT CALLBACK MsgProc(HWND h, UINT m, WPARAM w, LPARAM l) {+ if (m == WM_NA_INTERFACE) { auto* p = (std::function<void()>*)l; if (p) { (*p)(); delete p; } return 0; }+ // Outro programa (o Explorador, com a barra do Windows escondida ou em ocultar automaticamente) devolveu a área de+ // trabalho para a tela inteira: reaplica a nossa NA HORA. Antes esperava o tique de 1 s, e nesse meio-tempo as+ // janelas maximizadas e os ícones da mesa subiam para baixo da barra de menus e voltavam (issue #1: "a área+ // pula sem parar"). O nosso próprio SPI_SETWORKAREA vai sem aviso (sem SPIF_SENDCHANGE), então não volta aqui.+ if (m == WM_SETTINGCHANGE && w == SPI_SETWORKAREA && !g_quitting) {+ static DWORD win = 0; static int n = 0;+ DWORD now = GetTickCount();+ if (now - win > 1000) { win = now; n = 0; }+ if (++n <= 8) shell::ApplyWorkArea(); // no máximo 8 por segundo (se alguém brigar sem parar, não gira em laço)+ }+ static UINT reload = RegisterWindowMessageW(L"ShellAjustesMudaram");+ static UINT openCC = RegisterWindowMessageW(L"ShellAbrirCentral"); // abre/fecha a Central de Controle de fora+ static UINT restart = RegisterWindowMessageW(L"ShellReiniciar"); // reiniciar: sai sem abrir o Explorador e abre o Shell de novo+ if (m == restart && restart) {+ // o Shell novo abre já (no mesmo caminho: depois de compilar, é a versão nova) e espera este sair+ wchar_t exe[MAX_PATH]; GetModuleFileNameW(nullptr, exe, MAX_PATH);+ std::wstring dir = exe; dir = dir.substr(0, dir.find_last_of(L'\\'));+ std::wstring cmd = std::wstring(L"\"") + exe + L"\" --depois-de " + std::to_wstring(GetCurrentProcessId());+ STARTUPINFOW si{ sizeof(si) }; PROCESS_INFORMATION pi{};+ if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, dir.c_str(), &si, &pi)) { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); }+ else Log(L"reiniciar: não abriu o Shell novo (%lu)", GetLastError());+ mesa::NoExplorerOnExit();+ tray::SemAvisoAoSair();+ janelas::ManterAoReiniciar(); // as janelas ficam com a barra do Mac (o Shell novo assume; ver janelas::Stop)+ shell::Quit(L"reiniciar");+ return 0;+ }+ if (m == openCC && openCC) { central::Toggle(); return 0; }+ static UINT openNC = RegisterWindowMessageW(L"ShellAbrirNotificacoes"); // abre/fecha a Central de Notificações de fora+ if (m == openNC && openNC) { notificacoes::Toggle(); return 0; }+ static UINT openSP = RegisterWindowMessageW(L"ShellAbrirSpotlight"); // abre/fecha o Spotlight de fora (como o Win+Espaço)+ if (m == openSP && openSP) { PostMessageW(h, WM_APP_SPOTLIGHT, 0, 0); return 0; }+ // abre um painel de fora (fotos do README, testes): 1 Launchpad/Apps, 2 Mission Control, 3..6 Spotlight no modo 1..4,+ // 7 Spotlight, 8 Sobre Este Mac+ static UINT openPanel = RegisterWindowMessageW(L"ShellAbrirPainel");+ if (m == openPanel && openPanel) {+ // pedido de fora: o Windows não deixa o Shell vir para a frente sozinho (o Spotlight e o Launchpad fechavam na+ // hora, sem foco). Entra na fila de entrada da janela da frente enquanto abre, como os alertas fazem.+ HWND fg = GetForegroundWindow();+ DWORD ft = fg ? GetWindowThreadProcessId(fg, nullptr) : 0, me = GetCurrentThreadId();+ bool att = ft && ft != me && AttachThreadInput(me, ft, TRUE);+ if (w == 1) launchpad::Toggle();+ else if (w == 2) missioncontrol::Toggle();+ else if (w >= 3 && w <= 6) spotlight::OpenMode((int)w - 2);+ else if (w == 7) spotlight::Toggle();+ else if (w == 8) sobre::Show(); // Sobre Este Mac+ else if (w == 9) central::Toggle(); // Central de Controle (testes)+ else if (w == 10) notificacoes::Toggle(); // Central de Notificações (testes)+ else if (w == 12) dock::OpenAppsStack(); // Leopard: a pilha Aplicativos (testes)+ else if (w == 13) seletor::Step(1); // o seletor de apps sem segurar o Alt (testes; 14 fecha)+ else if (w == 14) seletor::Key(VK_ESCAPE);+ else if (w == 15) dock::OpenDownloadsStack(); // a pilha Downloads (testes)+ else if (w == 16) dashboard::Toggle(); // Leopard: Dashboard (Win+F12)+ else if (w == 17) espacos::Toggle(); // Leopard: Spaces (Win+F8)+ else if (w == 18) tempo::Enter(); // Leopard: a viagem no tempo do Time Machine+ else if (w == 11) { // Quick Look de uma foto do macOS 27 (testes)+ wchar_t p[MAX_PATH] = {}; GetEnvironmentVariableW(L"USERPROFILE", p, MAX_PATH);+ quicklook::Toggle(std::wstring(p) + L"\\Pictures\\Wallpapers macOS\\macOS 27\\macos-27-golden-4096x2160-27635.jpg");+ }+ if (att) AttachThreadInput(me, ft, FALSE);+ return 0;+ }+ if (atualizacao::Handle(m)) return 0;+ // Ajustes > Aparência > "Reiniciar o Liquid Glass": refaz o vidro real do zero (se ele desistiu ou travou)+ static UINT redoGlass = RegisterWindowMessageW(L"ShellReiniciarVidro");+ if (m == redoGlass && redoGlass) { backdrop::Restart(); return 1; }+ static UINT capVis = RegisterWindowMessageW(L"ShellCapturaVisivel"); // a Captura de Tela vai tirar a foto+ if (m == capVis && capVis) { backdrop::CaptureVisible(w != 0); return 1; }+ static UINT capDone = RegisterWindowMessageW(L"ShellCapturaFeita"); // a Captura salvou (0) ou copiou (1): aviso na ilha+ if (m == capDone && capDone) { ilha::Captura(w != 0); return 0; }+ if (m == WM_COPYDATA && l && ((COPYDATASTRUCT*)l)->dwData == 0x4C504150 /*'PAPL'*/) { // Ajustes: papel de parede escolhido+ auto* cd = (COPYDATASTRUCT*)l;+ if (!cd->lpData || cd->cbData < sizeof(wchar_t) || cd->cbData > 4096) return FALSE;+ std::wstring p((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t));+ while (!p.empty() && !p.back()) p.pop_back();+ mesa::WallpaperNow(p);+ return TRUE;+ }+ if (m == WM_COPYDATA && l && ((COPYDATASTRUCT*)l)->dwData == 0x514C4F4B /*'QLOK'*/) { // Finder: Quick Look (vazio = fechar)+ auto* cd = (COPYDATASTRUCT*)l;+ if (cd->cbData > 8192) return FALSE;+ std::wstring p = cd->lpData ? std::wstring((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t)) : L"";+ while (!p.empty() && !p.back()) p.pop_back();+ // responde já e abre logo depois: o vídeo leva mais que o tempo de espera do Finder (0,8 s), e ele achava+ // que tinha falhado e abria também o painel antigo dele+ auto* copy = new std::wstring(p);+ PostMessageW(h, WM_APP + 77, 0, (LPARAM)copy);+ return TRUE;+ }+ // 'SIRI': pergunta à Siri (texto UTF-16) vinda de fora (atalhos, scripts, testes); 'BRIL': mostra o brilho n (0-100)+ // na Ilha como se a tela tivesse mudado (teste do aviso num PC de mesa, que não manda o evento do WMI)+ if (m == WM_COPYDATA && l && (((COPYDATASTRUCT*)l)->dwData == 0x49524953 /*'SIRI'*/ || ((COPYDATASTRUCT*)l)->dwData == 0x54524953 /*'SIRT': teste, sem pegar a frente*/ || ((COPYDATASTRUCT*)l)->dwData == 0x41524953 /*'SIRA': abre o campo (teste)*/ || ((COPYDATASTRUCT*)l)->dwData == 0x4C495242 /*'BRIL'*/)) {+ auto* cd = (COPYDATASTRUCT*)l;+ if (!cd->lpData || cd->cbData < sizeof(wchar_t) || cd->cbData > 16384) return FALSE;+ std::wstring t((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t));+ while (!t.empty() && !t.back()) t.pop_back();+ if (cd->dwData == 0x4C495242) { ilha::Brilho(_wtoi(t.c_str())); return TRUE; }+ if (cd->dwData == 0x41524953) { PostMessageW(h, WM_APP + 79, 0, 0); return TRUE; }+ PostMessageW(h, WM_APP + 78, cd->dwData == 0x54524953, (LPARAM)new std::wstring(t)); // depois de responder: quem mandou não fica esperando+ return TRUE;+ }+ if (m == WM_APP + 79) { siri::Abrir(true); return 0; }+ if (m == WM_APP + 78 && l) { std::unique_ptr<std::wstring> q((std::wstring*)l); siri::Perguntar(*q, w != 0); return 0; }+ if (m == WM_APP + 77 && l) { // o Quick Look pedido pelo Finder (acima)+ std::unique_ptr<std::wstring> p((std::wstring*)l);+ if (p->empty()) quicklook::Close();+ else quicklook::Toggle(*p, false); // o Finder fica com o foco+ return 0;+ }+ if (m == WM_COPYDATA && l && ((COPYDATASTRUCT*)l)->dwData == 0x414D504C /*'AMPL'*/) { // MacJanela.dll: ampliar animado+ struct Msg { unsigned long long hwnd; RECT from, to; int flags; COLORREF cap; };+ auto* cd = (COPYDATASTRUCT*)l;+ if (cd->cbData != sizeof(Msg) || !cd->lpData) return FALSE;+ auto* mm = (Msg*)cd->lpData;+ // nativo: janelas de barra própria (flags 8: Chrome, Edge, Electron...) têm a barra do Mac por fora (barras.cpp).+ // A animação usa uma foto da janela de verdade, com a barra e os botões do Windows: por meio segundo as+ // bolinhas sumiam e apareciam os botões antigos (vídeo do usuário de 12/11/2026). Sem animação: muda na hora.+ if (shell::nativo && (mm->flags & 8)) return FALSE;+ return ampliar::Start((HWND)(UINT_PTR)mm->hwnd, mm->from, mm->to, mm->flags, mm->cap) ? TRUE : FALSE;+ }+ static UINT ampFoto = RegisterWindowMessageW(L"ShellAmpliarFoto"); // MacJanela.dll: a janela já mudou de tamanho+ if (m == ampFoto && ampFoto) { ampliar::SecondPhoto((HWND)w); return 0; }+ static UINT iconeMudou = RegisterWindowMessageW(L"ShellIconeMudou"); // ícone próprio de um app escolhido/restaurado (apps.cpp)+ if (m == iconeMudou && iconeMudou) { apps::ReloadIcons(); Log(L"ícone próprio: Dock, Alt+Tab e Launchpad recarregados"); return 0; }+ static UINT ampPronto = RegisterWindowMessageW(L"ShellAmpliarPronto"); // a janela já reapareceu+ if (m == ampPronto && ampPronto) { ampliar::Shown((HWND)w); return 0; }+ static UINT menuVerde = RegisterWindowMessageW(L"ShellMenuVerde"); // ponteiro parado no botão verde (DLL ou app nosso)+ if (m == menuVerde && menuVerde) { verde::Show((HWND)w, POINT{ (short)LOWORD(l), (short)HIWORD(l) }); return 0; }+ static UINT jAbrir = RegisterWindowMessageW(L"ShellJanelaAbrir"); // WacOSWindow.dll: janela nova, escondida e pintada+ if (m == jAbrir && jAbrir) { abrir::Open((HWND)w, (HWND)l); return 0; }+ static UINT jFechar = RegisterWindowMessageW(L"ShellJanelaFechar"); // WacOSWindow.dll: a janela vai sumir agora+ if (m == jFechar && jFechar) return ampliar::Fechar((HWND)w, l) ? 1 : 0;+ if (m == WM_COPYDATA && l) { // o Ajustes do Sistema manda "chave=valor": o Shell grava no arquivo que ele mesmo lê+ // (o Ajustes pode estar num contêiner que desvia o %APPDATA% dele para outra cópia do ajustes.txt)+ auto* cd = (COPYDATASTRUCT*)l;+ if (cd->dwData == 0x534A5354 /*'SJST'*/ && cd->lpData && cd->cbData >= sizeof(wchar_t)) {+ std::wstring kv((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t));+ while (!kv.empty() && !kv.back()) kv.pop_back();+ size_t eq = kv.find(L'=');+ if (eq != std::wstring::npos && eq > 0 && eq < 128 && kv.find(L'\n') == std::wstring::npos) {+ shell::SetSetting(kv.substr(0, eq).c_str(), kv.substr(eq + 1));+ PostMessageW(h, reload, 0, 0);+ }+ return TRUE;+ }+ }+ if (m == reload && reload) { // o Ajustes do Sistema gravou ajustes.txt+ g_macKeys = !shell::SoDock() && shell::Setting(L"atalhos_mac", L"1") == L"1";+ static int lastLiquid = -1;+ if (lastLiquid < 0) lastLiquid = liquid::Leopard() ? 3 : liquid::Golden() ? 2 : liquid::On();+ static int lastTheme = -1; // 0 Sequoia, 1 Tahoe, 2 Golden Gate, 3 Leopard+ auto themeNow = [] { return liquid::Leopard() ? 3 : liquid::Golden() ? 2 : (int)liquid::On(); };+ if (lastTheme < 0) lastTheme = themeNow();+ LoadSettings();+ ilha::Reload();+ { // barra_todos_monitores mudou: cria ou tira as barras dos monitores secundários (e a área de trabalho deles)+ static std::wstring lastAll = L"?";+ std::wstring all = shell::Setting(L"barra_todos_monitores", L"1");+ if (lastAll != L"?" && all != lastAll) { menubar::Displays(); dock::ReloadSettings(); }+ lastAll = all;+ static std::wstring lastBaixo = L"?"; // barra de menus em cima ou na linha do Dock (issue #29)+ std::wstring baixo = shell::Setting(L"barra_embaixo", L"0");+ if (baixo != lastBaixo) { menubar::Displays(); dock::ReloadSettings(); }+ lastBaixo = baixo;+ static std::wstring lastOcultar = L"?"; // ocultar a barra de menus automaticamente (issue #40)+ std::wstring ocultar = shell::Setting(L"barra_ocultar", L"0");+ if (lastOcultar != L"?" && ocultar != lastOcultar) { menubar::Displays(); dock::ReloadSettings(); }+ lastOcultar = ocultar;+ }+ static int lastLang = -1;+ if (lastLang < 0) lastLang = idioma::Current();+ if (int lang = idioma::FromCode(shell::Setting(L"idioma", L"en")); lang != lastLang) { // Ajustes > Geral > Idioma+ lastLang = lang;+ idioma::Set(lang);+ apps::Relabel();+ dock::IconsChanged();+ Log(L"idioma: %ls", idioma::Code());+ }+ if ((liquid::Leopard() ? 3 : liquid::Golden() ? 2 : (int)liquid::On()) != lastLiquid) { // tema Sequoia/Tahoe/Golden Gate/Leopard: outro pacote de ícones+ lastLiquid = liquid::Leopard() ? 3 : liquid::Golden() ? 2 : liquid::On();+ for (auto& a : apps::list) { a.icon.clear(); a.iw = a.ih = 0; a.mac = false; }+ dock::IconsChanged();+ seletor::IconsChanged();+ Log(L"tema mudou: ícones do Dock e do seletor recarregados");+ }+ if (themeNow() != lastTheme) {+ // tema trocado: as janelas com a barra do Mac (WacOSWindow.dll) redesenham já (barra metálica e botões de gel+ // do Leopard, ou de volta) em vez de esperar a próxima ativação+ lastTheme = themeNow();+ EnumWindows([](HWND w, LPARAM msg) -> BOOL {+ if (GetPropW(w, L"MacJanela")) PostMessageW(w, (UINT)msg, 0, 0);+ return TRUE;+ }, (LPARAM)reload);+ Log(L"tema: %d (janelas avisadas)", lastTheme);+ ponteiro::TemaLeopard(lastTheme == 3); // Leopard: cursor do Mac OS X; saindo, o cursor de antes+ }+ dock::ReloadSettings();+ dock::ApplyTheme();+ menubar::ApplyTheme();+ menubar::Update();+ shell::ApplyWorkArea();+ mesa::SettingsChanged();+ widgets::SettingsChanged(); // Personalizar a Mesa: widgets ligados/desligados+ jogo::Reload(); // modo_jogo e jogos.txt+ palco::Sync();+ // "Clicar no papel de parede para mostrar a mesa" saiu de "Nunca": com o Shell aberto em "Nunca" o gancho do mouse+ // nunca era criado e a opção nova só valia depois de reiniciar (Start não faz nada se já estiver ligado)+ if (!shell::SoDock() && !jogo::Ativo()) revelar::Start();+ return 0;+ }+ if (m == WM_SHELLHOOK && WM_SHELLHOOK) {+ switch (w & 0x7FFF) {+ case HSHELL_WINDOWCREATED: case HSHELL_WINDOWDESTROYED: case HSHELL_WINDOWACTIVATED: case HSHELL_REDRAW:+ Changed();+ if ((w & 0x7FFF) == HSHELL_REDRAW && (w & 0x8000)) { // HSHELL_FLASH: app pedindo atenção+ apps::Refresh();+ if (App* a = apps::OfWindow((HWND)l)) { a->attentionAt = GetTickCount(); dock::Update(); }+ }+ break;+ case HSHELL_GETMINRECT: { // para onde a janela encolhe ao minimizar: o Dock, antes da Lixeira+ auto* shi = (SHELLHOOKINFO*)l;+ RECT r{};+ if (shi && genio::OnMinRect(shi->hwnd, &r)) { shi->rc = r; return TRUE; } // o gênio já começou, com a janela ainda na tela+ r = dock::MinimizeTarget(shi ? shi->hwnd : nullptr);+ if (shi && r.right > r.left) { shi->rc = r; SetTimer(g_msg, 7, 450, nullptr); return TRUE; } // e o Dock se atualiza logo depois+ break;+ }+ }+ return 0;+ }+ switch (m) {+ case WM_TIMER:+ if (w == 7) { KillTimer(g_msg, 7); Changed(); return 0; }+ if (w == 1) {+ static int ticks;+ if (ticks++ % 60 == 0) AutoAppearance();+ Changed(); CheckFullscreen(); HideTaskbars(); shell::ApplyWorkArea(); if (shell::Setting(L"finder_reserva", L"1") == L"1") EnsureReserve(); EnsureScreenshot();+ }+ if (w == 2) tray::Keepalive();+ if (w == 9) { // extensões do menu de contexto carregadas cedo: o 1º botão direito na mesa/Spotlight/Launchpad sai rápido+ KillTimer(g_msg, 9);+ wchar_t* p = nullptr; std::wstring desk;+ if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Desktop, 0, nullptr, &p))) { desk = p; CoTaskMemFree(p); }+ std::wstring file;+ WIN32_FIND_DATAW fd; HANDLE fh = desk.empty() ? INVALID_HANDLE_VALUE : FindFirstFileW((desk + L"\\*").c_str(), &fd);+ if (fh != INVALID_HANDLE_VALUE) {+ do if (!(fd.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_HIDDEN))) { file = desk + L"\\" + fd.cFileName; break; }+ while (FindNextFileW(fh, &fd));+ FindClose(fh);+ }+ if (!desk.empty()) ctxmenu::WarmupAsync(desk, file);+ }+ return 0;+ case WM_HOTKEY: shell::Quit(L"atalho Ctrl+Alt+Shift+F12"); return 0;+ case WM_APP_SETTINGS: shell::OpenSettings(L""); return 0;+ case WM_APP_SNAP: {+ HWND fg = GetForegroundWindow();+ if (!fg) return 0;+ if (w == VK_LEFT || w == VK_RIGHT) {+ HWND root = GetAncestor(fg, GA_ROOT);+ if (root && !apps::IsShellWindow(root) && (GetWindowLongW(root, GWL_STYLE) & WS_THICKFRAME)) encaixe::Half(root, w == VK_RIGHT);+ return 0;+ }+ // o "ampliar" do Mac (MacJanela.dll): ocupa a área de trabalho e mantém cantos e sombra+ static UINT zoom = RegisterWindowMessageW(L"MacJanelaAmpliar");+ bool ampliada = GetPropW(fg, L"MacJanelaAmpliada") != nullptr;+ if (w == VK_UP) { if (!ampliada) PostMessageW(fg, zoom, 0, 0); }+ else if (ampliada) PostMessageW(fg, zoom, 0, 0);+ else ShowWindowAsync(fg, SW_MINIMIZE);+ return 0;+ }+ case WM_APP_MISSION:+ if (launchpad::IsOpen()) launchpad::Toggle();+ shell::LiberaFrente(); // permite ao Mission Control vir para a frente+ missioncontrol::Toggle();+ return 0;+ case WM_APP_EXPOSE: {+ HWND fg = GetForegroundWindow();+ HWND root = fg ? GetAncestor(fg, GA_ROOTOWNER) : nullptr;+ apps::Refresh();+ App* a = root && !apps::IsShellWindow(root) ? apps::OfWindow(root) : nullptr;+ if (!a) { Log(L"Exposé do app: a janela da frente não é de um app do Dock"); return 0; }+ if (launchpad::IsOpen()) launchpad::Toggle();+ shell::LiberaFrente(); // permite ao Exposé vir para a frente+ missioncontrol::ToggleApp(a->id, a->name);+ return 0;+ }+ case WM_APP_MACKEY: {+ HWND fg = GetForegroundWindow();+ HWND root = fg ? GetAncestor(fg, GA_ROOT) : nullptr;+ if (!root || apps::IsShellWindow(root) || apps::IsShellWindow(GetAncestor(root, GA_ROOTOWNER))) return 0; // Dock, mesa, painéis+ if (w == 'W') { // fecha só a janela da frente (o app continua aberto)+ Log(L"atalho Win+W: fechando a janela %p", root);+ PostMessageW(root, WM_SYSCOMMAND, SC_CLOSE, 0);+ return 0;+ }+ apps::Refresh();+ App* a = apps::OfWindow(GetAncestor(root, GA_ROOTOWNER));+ if (!a) a = apps::OfWindow(root);+ if (!a) { Log(L"atalho Win+%lc: janela da frente sem app no Dock", (wchar_t)w); return 0; }+ if (w == 'Q') {+ if (a->finder) return 0; // como no Mac: o Finder não se encerra+ Log(L"atalho Win+Q: encerrando %ls", a->name.c_str());+ apps::Quit(*a);+ } else {+ Log(L"atalho Win+H: ocultando %ls", a->name.c_str());+ apps::Hide(*a);+ }+ dock::Update();+ return 0;+ }+ case WM_APP_LOCK:+ bloqueio::Lock(); // o bloqueio do Windows (a tela do WacOS saiu)+ return 0;+ case WM_APP_MONITOR:+ if (w == 1) shell::OpenForceQuit(false); else shell::OpenMonitor();+ return 0;+ case WM_APP_SWITCH: seletor::Step((int)(INT_PTR)w); return 0;+ case WM_APP_SWITCH_KEY: seletor::Key((UINT)w); return 0;+ case WM_APP_SWITCH_END: seletor::Release(); return 0;+ case WM_APP_SPOTLIGHT:+ if (launchpad::IsOpen()) launchpad::Toggle();+ shell::LiberaFrente(); // permite ao Spotlight vir para a frente e receber o teclado+ spotlight::Toggle();+ return 0;+ case WM_APP_LAUNCHPAD:+ shell::LiberaFrente(); // permite ao Launchpad vir para a frente+ launchpad::Toggle();+ return 0;+ case WM_APP_WINKEY: mesa::WinKey((UINT)w); return 0;+ case WM_APP_CAPTURA: Screenshot((int)w, l != 0); return 0;case WM_APP_VOLUME:if (w == VK_F14 || w == VK_F15) { central::BrilhoPasso(w == VK_F15 ? 1 : -1); return 0; } // brilho (issue #38)- som::Key((UINT)w, l != 0); return 0;- case WM_SYSCOMMAND:- if ((w & 0xFFF0) == SC_TASKLIST) { // Ctrl+Esc com o Shell como Taskman (sem Explorador): Launchpad- shell::LiberaFrente();- launchpad::Toggle();- return 0;- }- break;- case WM_QUERYENDSESSION: return TRUE;- case WM_ENDSESSION: if (w) { Log(L"fim da sessão do Windows"); g_sessionEnding = true; Restore(); } return 0;- }- return DefWindowProcW(h, m, w, l);-}--int AjudanteRodar(const wchar_t* cmd); // ajudante.cpp: --sair, --aplicar-cursor... (para os scripts do instalador)--int WINAPI wWinMain(HINSTANCE hi, HINSTANCE, PWSTR, int) {- if (int r = AjudanteRodar(GetCommandLineW()); r >= 0) return r;- if (migrar::TrocarPeloNovo()) return 0; // nome velho (SequoiaShell.exe): o WacOSShell.exe ao lado assume- if (const wchar_t* a = wcsstr(GetCommandLineW(), L"--depois-de ")) { // reinício: espera o Shell antigo sair (até 20 s)- if (HANDLE old = OpenProcess(SYNCHRONIZE, FALSE, wcstoul(a + 12, nullptr, 10))) { WaitForSingleObject(old, 20000); CloseHandle(old); }- }- if (bloqueio::Watchdog(GetCommandLineW())) return 0; // vigia da tela de bloqueio (outro processo)- if (mesa::Watchdog(GetCommandLineW())) return 0; // vigia da mesa: Shell caiu sem Explorador → abre o Explorador- if (wcsstr(GetCommandLineW(), L"--bloqueio-png ")) { // imagem de teste da tela de bloqueio- SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);- OleInitialize(nullptr);- LoadSettings(); // o tema (Tahoe/Sequoia) e o idioma valem também na imagem de teste- if (ui::Init()) bloqueio::RenderPng(GetCommandLineW());- return 0;- }- if (wcsstr(GetCommandLineW(), L"--senha-bloqueio")) { // define a senha própria da tela de bloqueio- SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);- return bloqueio::SetPasswordUi(hi);- }- if (wcsstr(GetCommandLineW(), L"--testar-bloqueio")) { // a tela de bloqueio por ~3,5 s, sem conferir senha- SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);- OleInitialize(nullptr);- return ui::Init() ? bloqueio::Preview(hi) : 1;- }- if (wcsstr(GetCommandLineW(), L"--testar-boot")) { SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); return boot::Preview(hi); }- HANDLE single = CreateMutexW(nullptr, TRUE, L"ShellProprioUmaInstancia");- if (GetLastError() == ERROR_ALREADY_EXISTS) {- // reinício: o Shell antigo ainda não largou (preso no relatório de erro do Windows, por exemplo).- // Antes o novo desistia e ficava sem Shell nenhum; agora espera ele sair (até 60 s)- DWORD w = wcsstr(GetCommandLineW(), L"--depois-de ") && single ? WaitForSingleObject(single, 60000) : WAIT_TIMEOUT;- if (w != WAIT_OBJECT_0 && w != WAIT_ABANDONED) return 0;- }- SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);- shell::inst = hi;- wchar_t exe[MAX_PATH]; GetModuleFileNameW(nullptr, exe, MAX_PATH);- shell::dir = exe; shell::dir = shell::dir.substr(0, shell::dir.find_last_of(L'\\'));- // o log da sessão anterior fica em shell-anterior.log (o vigia escreve lá o motivo de um reinício)- MoveFileExW((shell::dir + L"\\shell.log").c_str(), (shell::dir + L"\\shell-anterior.log").c_str(), MOVEFILE_REPLACE_EXISTING);- g_log = _wfsopen((shell::dir + L"\\shell.log").c_str(), L"w, ccs=UTF-8", _SH_DENYNO);- Log(L"Shell iniciando");- OleInitialize(nullptr);- ctxmenu::Init(hi, nullptr); // sem log: o menu gravava e esperava o disco na thread da interface (mesma trava do arquivo do Log)- if (!ui::Init()) { Log(L"erro: Direct2D/DirectWrite"); return 1; }- LoadSettings();- migrar::Registro(); // caminhos com o nome velho (Sequoia) no registro do Windows (depois dos ajustes: grava um)- // Voltando depois de "Desligar o WacOS" (Ajustes > Geral): o desligar mandou as pastas e o Win+E de volta para o- // Explorador (finder_padrao=0). Abrir o WacOS de novo devolve ao Finder; antes o 0 ficava e o Win+E abria o- // Explorador até apagar os ajustes (issue #1). Quem desligar "Abrir pastas no Finder" à mão continua com o 0.- if (shell::Setting(L"finder_volta", L"") == L"1") {- shell::SetSetting(L"finder_volta", L"");- std::wstring finder = shell::dir + L"\\" EXE_FINDER;- if (GetFileAttributesW(finder.c_str()) != INVALID_FILE_ATTRIBUTES) {- shell::SetSetting(L"finder_padrao", L"1");- shell::Abrir(L"open", finder.c_str(), L"--quieto --padrao on", nullptr, SW_HIDE);- Log(L"finder: de volta depois do Desligar (finder_padrao=1, --padrao on)");- }- }- boot::Show(hi); // tela de inicialização do Mac (só logo depois do login)- SetUnhandledExceptionFilter(OnCrash);- SystemParametersInfoW(SPI_GETWORKAREA, 0, &g_origWork, 0);-- simbolo::Dir() = shell::dir.substr(0, shell::dir.find_last_of(L'\\')) + L"\\icones\\simbolos"; // SF Symbols da barra de menus- apps::Load(shell::dir + L"\\" EXE_FINDER);- apps::Refresh();-- WNDCLASSW mc{}; mc.lpfnWndProc = MsgProc; mc.hInstance = hi; mc.lpszClassName = L"ShellMensagens";- RegisterClassW(&mc);- g_msg = CreateWindowExW(WS_EX_TOOLWINDOW, mc.lpszClassName, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, hi, nullptr);- apps::ours.push_back(g_msg);- atualizacao::Start(g_msg); // aviso de versão nova no GitHub (90 s depois e a cada 6 h)- boot::Progress(0.2f);-- if (!menubar::Create(hi) || !dock::Create(hi) || !launchpad::Create(hi) || !missioncontrol::Create(hi) || !central::Create(hi) || !spotlight::Create(hi) || !alertas::Create(hi) || !sobre::Create(hi) || !seletor::Create(hi) || !som::Create(hi)) { Log(L"erro criando as janelas"); Restore(); return 1; }- // "Só Dock e barra de menus" (Reddit, anybody001): o que não é a barra nem o Dock fica de fora (ver shell::SoDock)- const bool soDock = shell::SoDock();- if (soDock) Log(L"modo: só Dock e barra de menus (a área de trabalho, o Alt+Tab, as pastas e as barras de título ficam com o Windows)");- instalados::Start(); // programa instalado ou removido: o Spotlight e o Launchpad releem os apps- indice::Start(); // índice de arquivos do Spotlight (thread de fundo)- if (!soDock) revelar::Start(); // clique no vazio da área de trabalho mostra a mesa- if (!soDock) ponteiro::Start(); // sacudir o mouse: o ponteiro cresce para achar- ponteiro::TemaLeopard(liquid::Leopard()); // tema Leopard: o cursor do Mac OS X (ou devolve o de antes)- genio::Create(hi); // efeito gênio ao minimizar- if (!soDock) palco::Sync(); // Organizador Visual (Stage Manager), se ligado- if (!soDock) widgets::Create(hi); // widgets na mesa (abaixo de todas as janelas)- // a tela de bloqueio do WacOS saiu (21/11/2026): bloquear usa o do Windows (bloqueio::Lock)- notificacoes::Create(hi); // Central de Notificações (clique no relógio da barra de menus)- ilha::Create(hi); // Ilha Dinâmica (ajuste ilha=1)- if (!soDock) notarapida::Create(hi); // canto inferior direito: Nota Rápida- if (!soDock) progresso::Create(hi); // copiar/mover/apagar: a janela de progresso do Finder no lugar da do Windows- if (!soDock) cantos::Start(); // Cantos Ativos (Mission Control, mesa, Launchpad... por canto)- jogo::Start(); // Modo Jogo: jogo na frente desliga o que mais pesa (vidro real, ganchos do mouse...)- leve::Start(); // Modo leve: PC fraco ou na bateria (sem vidro real, ~60 quadros/s); vigia tomada/bateria- brilho::Start(); // brilho da tela do notebook na Ilha (issue #39)- boot::Progress(0.7f);- tray::Start([] { menubar::Update(); });- mesa::Start(hi, g_msg); // ajuste explorer=0: a mesa é nossa e o explorer.exe sai (só Dock: a do Windows, mas o vigia fica)- menus::Start();- if (!soDock) dialogs::Start();- if (!soDock) janelas::Start();- if (!soDock) encaixe::Start(); // arrastar até a borda: metade, quarto, preencher (com a prévia)- if (!soDock) memoria::Start(); // pressão de memória, soneca de apps (App Nap), memória descartável- if (!soDock) pastas::Start(); // janelas de pasta do Explorador viram o Finder- limites::Start(); // janelas não cruzam a barra de menus nem o Dock- if (!soDock) sombras::Start();- HideTaskbars();- if (!shell::nativo) SetWinEventHook(EVENT_OBJECT_SHOW, EVENT_OBJECT_SHOW, nullptr, OnBarraWindows, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);- SecondaryTaskbarsOff(); // barra do Windows nos outros monitores: desligada enquanto o Shell roda- shell::ApplyWorkArea();-- WM_SHELLHOOK = RegisterWindowMessageW(L"SHELLHOOK");- RegisterShellHookWindow(g_msg);- RegisterHotKey(g_msg, 1, MOD_CONTROL | MOD_ALT | MOD_SHIFT | MOD_NOREPEAT, VK_F12); // era Q: fácil de apertar sem querer- // só Dock: a tecla Windows, o Alt+Tab e a captura de tela ficam com o Windows (o gancho só deixa passar)- g_fullHook = !soDock && shell::Setting(L"tecla_windows_launchpad", L"1") == L"1";- g_macKeys = !soDock && shell::Setting(L"atalhos_mac", L"1") == L"1";- g_capturaExe = !soDock && GetFileAttributesW((shell::dir + L"\\" EXE_SCREENSHOT).c_str()) != INVALID_FILE_ATTRIBUTES;- if (!soDock) EnsureScreenshot();- g_volumeKeys = shell::Setting(L"volume_mac", L"1") == L"1";- if (g_fullHook || g_volumeKeys || (!soDock && shell::Setting(L"bloqueio", L"1") != L"0")) std::thread(KeyThread).detach(); // sem o Launchpad: só barra teclas com a tela travada- SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr, OnWinEvent, 0, 0, WINEVENT_OUTOFCONTEXT);- jogo::GanchoPosicao(OnWinEvent, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS); // sai no modo jogo (jogo.cpp)- SetTimer(g_msg, 1, 1000, nullptr);- SetTimer(g_msg, 2, 200, nullptr);- SetTimer(g_msg, 9, 3000, nullptr); // pré-carregar o menu de contexto (depois que o Shell já apareceu)- Log(L"pronto: %zu apps no Dock", apps::list.size());- boot::Done();- mesa::RunStartupApps(); // só quando o Shell é o shell do Windows (o Explorador não abre no login)- PreloadApps();-- MSG msg;- sentinela::Start(g_msg); // interface parada 1 s ou mais: o shell.log diz onde (issue #32)- while (GetMessageW(&msg, nullptr, 0, 0)) { mesa::Pulse(); sentinela::ultimaMsg = msg.message; sentinela::ultimaJanela = msg.hwnd; TranslateMessage(&msg); DispatchMessageW(&msg); } // pulso: ver mesa::Pulse- Restore();- DeregisterShellHookWindow(g_msg);- // Sai daqui direto (TerminateProcess), com tudo já devolvido ao Windows. Voltar do wWinMain roda o- // encerramento do C++ (fecha todos os arquivos, inclusive o log; OleUninitialize desmonta o COM) com as- // threads de fundo (vidro real, índice, notificações) ainda rodando: elas escreviam no log fechado e o- // Shell caía ao reiniciar (0xC0000005), e o Windows segurava o processo morto no relatório de erro.- LogDescarrega();- if (g_log) fflush(g_log);- ReleaseMutex(single);- TerminateProcess(GetCurrentProcess(), 0);- return 0;-}--// ---- modo nativo: o Shell como a barra de tarefas do Windows (barra-nativa\MacBarra.dll, dentro do explorer.exe).-// A MacBarra chama numa thread própria quando o explorer cria a barra (ITrayUI::OnCreate) e esta função só-// volta quando a barra é destruída. Mesmas peças do WacOSShell.exe, menos as que são de processo:-// mutex de instância única, DPI do processo, tela de inicialização, filtro de falhas, TerminateProcess,-// mesa própria (a mesa é do explorer), tela de bloqueio própria (é o AuthUX), ganchos com DLL nos outros-// programas (janelas.cpp) e esconder a barra do Windows (ela somos nós).-int shell::RodarNativo(HINSTANCE hi, const std::wstring& dirBin, const std::wstring& logPath) {- nativo = true;- SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);- shell::inst = hi;- shell::dir = dirBin;- g_log = _wfsopen(logPath.c_str(), L"w, ccs=UTF-8", _SH_DENYNO);- Log(L"Shell nativo iniciando dentro do explorer (pid %lu), pasta %ls", GetCurrentProcessId(), dirBin.c_str());- OleInitialize(nullptr);- ctxmenu::Init(hi, nullptr); // sem log: o menu gravava e esperava o disco na thread da interface (mesma trava do arquivo do Log)- if (!ui::Init()) { Log(L"erro: Direct2D/DirectWrite"); return 1; }- LoadSettings();- SystemParametersInfoW(SPI_GETWORKAREA, 0, &g_origWork, 0);-- simbolo::Dir() = shell::dir.substr(0, shell::dir.find_last_of(L'\\')) + L"\\icones\\simbolos";- simbolo::Preload(); // os SF Symbols numa thread: desenhar nunca espera o disco (simbolos.h)- apps::Load(shell::dir + L"\\" EXE_FINDER);- apps::Refresh();-- WNDCLASSW mc{}; mc.lpfnWndProc = MsgProc; mc.hInstance = hi; mc.lpszClassName = L"ShellMensagens";- RegisterClassW(&mc);- g_msg = CreateWindowExW(WS_EX_TOOLWINDOW, mc.lpszClassName, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, hi, nullptr);- apps::ours.push_back(g_msg);- atualizacao::Start(g_msg); // aviso de versão nova no GitHub (90 s depois e a cada 6 h)-- if (!menubar::Create(hi) || !dock::Create(hi) || !launchpad::Create(hi) || !missioncontrol::Create(hi) || !central::Create(hi) || !spotlight::Create(hi) || !alertas::Create(hi) || !sobre::Create(hi) || !seletor::Create(hi) || !som::Create(hi)) { Log(L"erro criando as janelas"); Restore(); return 1; }- instalados::Start();- indice::Start();- revelar::Start();- ponteiro::Start();- ponteiro::TemaLeopard(liquid::Leopard());- genio::Create(hi);- widgets::Create(hi);- notificacoes::Create(hi);- ilha::Create(hi);- notarapida::Create(hi);- progresso::Create(hi);- cantos::Start();- tray::Start([] { menubar::Update(); }); // nativo: sem janela; os ícones chegam por tray::DoExplorer- menus::Start();- dialogs::Start();- pastas::Start();- if (GetFileAttributesW(L"C:\\Users\\Public\\MacMesa-desligada.txt") == INVALID_FILE_ATTRIBUTES)- mesa::Start(hi, g_msg); // nativo: a mesa do projeto por cima da do Explorador (mesmo processo)- else Log(L"MacMesa-desligada.txt: a mesa fica com o Windows");- limites::Start();- sombras::Start();- // Cantos do Mac (maiores que os 8 px do Windows), sombra e animações nas janelas com a barra padrão: só a- // WacOSWindow.dll DENTRO dos programas consegue (autorizado pelo usuário em 12/11/2026, "pode injetar").- // Ela cuida das janelas de barra padrão; as de barra própria (Chrome, Bloco de Notas...) continuam com barras.cpp.- // C:\Users\Public\MacInjecao-desligada.txt volta a não carregar nada nos outros programas.- if (GetFileAttributesW(L"C:\\Users\\Public\\MacInjecao-desligada.txt") == INVALID_FILE_ATTRIBUTES) janelas::Start();- else Log(L"MacInjecao-desligada.txt: nada é carregado nos outros programas (cantos de 8 px)");- barras::Start(); // nativo: barra de título do Mac por fora (sem nada dentro dos outros programas)- shell::ApplyWorkArea();-- WM_SHELLHOOK = RegisterWindowMessageW(L"SHELLHOOK");- RegisterShellHookWindow(g_msg);- g_fullHook = shell::Setting(L"tecla_windows_launchpad", L"1") == L"1";- g_macKeys = shell::Setting(L"atalhos_mac", L"1") == L"1";- g_capturaExe = GetFileAttributesW((shell::dir + L"\\" EXE_SCREENSHOT).c_str()) != INVALID_FILE_ATTRIBUTES;- EnsureScreenshot();- g_volumeKeys = shell::Setting(L"volume_mac", L"1") == L"1";- if (g_fullHook || g_volumeKeys) std::thread(KeyThread).detach();- SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr, OnWinEvent, 0, 0, WINEVENT_OUTOFCONTEXT);- jogo::GanchoPosicao(OnWinEvent, WINEVENT_OUTOFCONTEXT); // sai no modo jogo (jogo.cpp)- SetTimer(g_msg, 1, 1000, nullptr);- SetTimer(g_msg, 9, 3000, nullptr);- Log(L"pronto (nativo): %zu apps no Dock", apps::list.size());- PreloadApps();-- MSG msg;- sentinela::Start(g_msg); // interface parada 1 s ou mais: o shell.log diz onde (issue #32)- while (GetMessageW(&msg, nullptr, 0, 0)) { mesa::Pulse(); sentinela::ultimaMsg = msg.message; sentinela::ultimaJanela = msg.hwnd; TranslateMessage(&msg); DispatchMessageW(&msg); } // pulso: ver mesa::Pulse- Restore();- DeregisterShellHookWindow(g_msg);- Log(L"Shell nativo encerrado");- LogDescarrega();- if (g_log) fflush(g_log);- return 0;-}+ som::Key((UINT)w, l != 0); return 0;+ case WM_SYSCOMMAND:+ if ((w & 0xFFF0) == SC_TASKLIST) { // Ctrl+Esc com o Shell como Taskman (sem Explorador): Launchpad+ shell::LiberaFrente();+ launchpad::Toggle();+ return 0;+ }+ break;+ case WM_QUERYENDSESSION: return TRUE;+ case WM_ENDSESSION: if (w) { Log(L"fim da sessão do Windows"); g_sessionEnding = true; Restore(); } return 0;+ }+ return DefWindowProcW(h, m, w, l);+}++int AjudanteRodar(const wchar_t* cmd); // ajudante.cpp: --sair, --aplicar-cursor... (para os scripts do instalador)++int WINAPI wWinMain(HINSTANCE hi, HINSTANCE, PWSTR, int) {+ if (int r = AjudanteRodar(GetCommandLineW()); r >= 0) return r;+ if (migrar::TrocarPeloNovo()) return 0; // nome velho (SequoiaShell.exe): o WacOSShell.exe ao lado assume+ if (const wchar_t* a = wcsstr(GetCommandLineW(), L"--depois-de ")) { // reinício: espera o Shell antigo sair (até 20 s)+ if (HANDLE old = OpenProcess(SYNCHRONIZE, FALSE, wcstoul(a + 12, nullptr, 10))) { WaitForSingleObject(old, 20000); CloseHandle(old); }+ }+ if (bloqueio::Watchdog(GetCommandLineW())) return 0; // vigia da tela de bloqueio (outro processo)+ if (mesa::Watchdog(GetCommandLineW())) return 0; // vigia da mesa: Shell caiu sem Explorador → abre o Explorador+ if (wcsstr(GetCommandLineW(), L"--bloqueio-png ")) { // imagem de teste da tela de bloqueio+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);+ OleInitialize(nullptr);+ LoadSettings(); // o tema (Tahoe/Sequoia) e o idioma valem também na imagem de teste+ if (ui::Init()) bloqueio::RenderPng(GetCommandLineW());+ return 0;+ }+ if (wcsstr(GetCommandLineW(), L"--senha-bloqueio")) { // define a senha própria da tela de bloqueio+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);+ return bloqueio::SetPasswordUi(hi);+ }+ if (wcsstr(GetCommandLineW(), L"--testar-bloqueio")) { // a tela de bloqueio por ~3,5 s, sem conferir senha+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);+ OleInitialize(nullptr);+ return ui::Init() ? bloqueio::Preview(hi) : 1;+ }+ if (wcsstr(GetCommandLineW(), L"--testar-boot")) { SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); return boot::Preview(hi); }+ HANDLE single = CreateMutexW(nullptr, TRUE, L"ShellProprioUmaInstancia");+ if (GetLastError() == ERROR_ALREADY_EXISTS) {+ // reinício: o Shell antigo ainda não largou (preso no relatório de erro do Windows, por exemplo).+ // Antes o novo desistia e ficava sem Shell nenhum; agora espera ele sair (até 60 s)+ DWORD w = wcsstr(GetCommandLineW(), L"--depois-de ") && single ? WaitForSingleObject(single, 60000) : WAIT_TIMEOUT;+ if (w != WAIT_OBJECT_0 && w != WAIT_ABANDONED) return 0;+ }+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);+ shell::inst = hi;+ wchar_t exe[MAX_PATH]; GetModuleFileNameW(nullptr, exe, MAX_PATH);+ shell::dir = exe; shell::dir = shell::dir.substr(0, shell::dir.find_last_of(L'\\'));+ // o log da sessão anterior fica em shell-anterior.log (o vigia escreve lá o motivo de um reinício)+ MoveFileExW((shell::dir + L"\\shell.log").c_str(), (shell::dir + L"\\shell-anterior.log").c_str(), MOVEFILE_REPLACE_EXISTING);+ g_log = _wfsopen((shell::dir + L"\\shell.log").c_str(), L"w, ccs=UTF-8", _SH_DENYNO);+ Log(L"Shell iniciando");+ OleInitialize(nullptr);+ ctxmenu::Init(hi, nullptr); // sem log: o menu gravava e esperava o disco na thread da interface (mesma trava do arquivo do Log)+ if (!ui::Init()) { Log(L"erro: Direct2D/DirectWrite"); return 1; }+ LoadSettings();+ migrar::Registro(); // caminhos com o nome velho (Sequoia) no registro do Windows (depois dos ajustes: grava um)+ // Voltando depois de "Desligar o WacOS" (Ajustes > Geral): o desligar mandou as pastas e o Win+E de volta para o+ // Explorador (finder_padrao=0). Abrir o WacOS de novo devolve ao Finder; antes o 0 ficava e o Win+E abria o+ // Explorador até apagar os ajustes (issue #1). Quem desligar "Abrir pastas no Finder" à mão continua com o 0.+ if (shell::Setting(L"finder_volta", L"") == L"1") {+ shell::SetSetting(L"finder_volta", L"");+ std::wstring finder = shell::dir + L"\\" EXE_FINDER;+ if (GetFileAttributesW(finder.c_str()) != INVALID_FILE_ATTRIBUTES) {+ shell::SetSetting(L"finder_padrao", L"1");+ shell::Abrir(L"open", finder.c_str(), L"--quieto --padrao on", nullptr, SW_HIDE);+ Log(L"finder: de volta depois do Desligar (finder_padrao=1, --padrao on)");+ }+ }+ boot::Show(hi); // tela de inicialização do Mac (só logo depois do login)+ SetUnhandledExceptionFilter(OnCrash);+ SystemParametersInfoW(SPI_GETWORKAREA, 0, &g_origWork, 0);++ simbolo::Dir() = shell::dir.substr(0, shell::dir.find_last_of(L'\\')) + L"\\icones\\simbolos"; // SF Symbols da barra de menus+ apps::Load(shell::dir + L"\\" EXE_FINDER);+ apps::Refresh();++ WNDCLASSW mc{}; mc.lpfnWndProc = MsgProc; mc.hInstance = hi; mc.lpszClassName = L"ShellMensagens";+ RegisterClassW(&mc);+ g_msg = CreateWindowExW(WS_EX_TOOLWINDOW, mc.lpszClassName, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, hi, nullptr);+ apps::ours.push_back(g_msg);+ atualizacao::Start(g_msg); // aviso de versão nova no GitHub (90 s depois e a cada 6 h)+ boot::Progress(0.2f);++ if (!menubar::Create(hi) || !dock::Create(hi) || !launchpad::Create(hi) || !missioncontrol::Create(hi) || !central::Create(hi) || !spotlight::Create(hi) || !alertas::Create(hi) || !sobre::Create(hi) || !seletor::Create(hi) || !som::Create(hi)) { Log(L"erro criando as janelas"); Restore(); return 1; }+ // "Só Dock e barra de menus" (Reddit, anybody001): o que não é a barra nem o Dock fica de fora (ver shell::SoDock)+ const bool soDock = shell::SoDock();+ if (soDock) Log(L"modo: só Dock e barra de menus (a área de trabalho, o Alt+Tab, as pastas e as barras de título ficam com o Windows)");+ instalados::Start(); // programa instalado ou removido: o Spotlight e o Launchpad releem os apps+ indice::Start(); // índice de arquivos do Spotlight (thread de fundo)+ if (!soDock) revelar::Start(); // clique no vazio da área de trabalho mostra a mesa+ if (!soDock) ponteiro::Start(); // sacudir o mouse: o ponteiro cresce para achar+ ponteiro::TemaLeopard(liquid::Leopard()); // tema Leopard: o cursor do Mac OS X (ou devolve o de antes)+ genio::Create(hi); // efeito gênio ao minimizar+ if (!soDock) palco::Sync(); // Organizador Visual (Stage Manager), se ligado+ if (!soDock) widgets::Create(hi); // widgets na mesa (abaixo de todas as janelas)+ // a tela de bloqueio do WacOS saiu (21/11/2026): bloquear usa o do Windows (bloqueio::Lock)+ notificacoes::Create(hi); // Central de Notificações (clique no relógio da barra de menus)+ ilha::Create(hi); // Ilha Dinâmica (ajuste ilha=1)+ if (!soDock) notarapida::Create(hi); // canto inferior direito: Nota Rápida+ if (!soDock) progresso::Create(hi); // copiar/mover/apagar: a janela de progresso do Finder no lugar da do Windows+ if (!soDock) cantos::Start(); // Cantos Ativos (Mission Control, mesa, Launchpad... por canto)+ jogo::Start(); // Modo Jogo: jogo na frente desliga o que mais pesa (vidro real, ganchos do mouse...)+ leve::Start(); // Modo leve: PC fraco ou na bateria (sem vidro real, ~60 quadros/s); vigia tomada/bateria+ brilho::Start(); // brilho da tela do notebook na Ilha (issue #39)+ boot::Progress(0.7f);+ tray::Start([] { menubar::Update(); });+ mesa::Start(hi, g_msg); // ajuste explorer=0: a mesa é nossa e o explorer.exe sai (só Dock: a do Windows, mas o vigia fica)+ menus::Start();+ if (!soDock) dialogs::Start();+ if (!soDock) janelas::Start();+ if (!soDock) encaixe::Start(); // arrastar até a borda: metade, quarto, preencher (com a prévia)+ if (!soDock) memoria::Start(); // pressão de memória, soneca de apps (App Nap), memória descartável+ if (!soDock) pastas::Start(); // janelas de pasta do Explorador viram o Finder+ limites::Start(); // janelas não cruzam a barra de menus nem o Dock+ if (!soDock) sombras::Start();+ HideTaskbars();+ if (!shell::nativo) SetWinEventHook(EVENT_OBJECT_SHOW, EVENT_OBJECT_SHOW, nullptr, OnBarraWindows, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);+ SecondaryTaskbarsOff(); // barra do Windows nos outros monitores: desligada enquanto o Shell roda+ shell::ApplyWorkArea();++ WM_SHELLHOOK = RegisterWindowMessageW(L"SHELLHOOK");+ RegisterShellHookWindow(g_msg);+ RegisterHotKey(g_msg, 1, MOD_CONTROL | MOD_ALT | MOD_SHIFT | MOD_NOREPEAT, VK_F12); // era Q: fácil de apertar sem querer+ // só Dock: a tecla Windows, o Alt+Tab e a captura de tela ficam com o Windows (o gancho só deixa passar)+ g_fullHook = !soDock && shell::Setting(L"tecla_windows_launchpad", L"1") == L"1";+ g_macKeys = !soDock && shell::Setting(L"atalhos_mac", L"1") == L"1";+ g_capturaExe = !soDock && GetFileAttributesW((shell::dir + L"\\" EXE_SCREENSHOT).c_str()) != INVALID_FILE_ATTRIBUTES;+ if (!soDock) EnsureScreenshot();+ g_volumeKeys = shell::Setting(L"volume_mac", L"1") == L"1";+ if (g_fullHook || g_volumeKeys || (!soDock && shell::Setting(L"bloqueio", L"1") != L"0")) std::thread(KeyThread).detach(); // sem o Launchpad: só barra teclas com a tela travada+ SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr, OnWinEvent, 0, 0, WINEVENT_OUTOFCONTEXT);+ jogo::GanchoPosicao(OnWinEvent, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS); // sai no modo jogo (jogo.cpp)+ SetTimer(g_msg, 1, 1000, nullptr);+ SetTimer(g_msg, 2, 200, nullptr);+ SetTimer(g_msg, 9, 3000, nullptr); // pré-carregar o menu de contexto (depois que o Shell já apareceu)+ Log(L"pronto: %zu apps no Dock", apps::list.size());+ boot::Done();+ mesa::RunStartupApps(); // só quando o Shell é o shell do Windows (o Explorador não abre no login)+ PreloadApps();++ MSG msg;+ sentinela::Start(g_msg); // interface parada 1 s ou mais: o shell.log diz onde (issue #32)+ while (GetMessageW(&msg, nullptr, 0, 0)) { mesa::Pulse(); sentinela::ultimaMsg = msg.message; sentinela::ultimaJanela = msg.hwnd; TranslateMessage(&msg); DispatchMessageW(&msg); } // pulso: ver mesa::Pulse+ Restore();+ DeregisterShellHookWindow(g_msg);+ // Sai daqui direto (TerminateProcess), com tudo já devolvido ao Windows. Voltar do wWinMain roda o+ // encerramento do C++ (fecha todos os arquivos, inclusive o log; OleUninitialize desmonta o COM) com as+ // threads de fundo (vidro real, índice, notificações) ainda rodando: elas escreviam no log fechado e o+ // Shell caía ao reiniciar (0xC0000005), e o Windows segurava o processo morto no relatório de erro.+ LogDescarrega();+ if (g_log) fflush(g_log);+ ReleaseMutex(single);+ TerminateProcess(GetCurrentProcess(), 0);+ return 0;+}++// ---- modo nativo: o Shell como a barra de tarefas do Windows (barra-nativa\MacBarra.dll, dentro do explorer.exe).+// A MacBarra chama numa thread própria quando o explorer cria a barra (ITrayUI::OnCreate) e esta função só+// volta quando a barra é destruída. Mesmas peças do WacOSShell.exe, menos as que são de processo:+// mutex de instância única, DPI do processo, tela de inicialização, filtro de falhas, TerminateProcess,+// mesa própria (a mesa é do explorer), tela de bloqueio própria (é o AuthUX), ganchos com DLL nos outros+// programas (janelas.cpp) e esconder a barra do Windows (ela somos nós).+int shell::RodarNativo(HINSTANCE hi, const std::wstring& dirBin, const std::wstring& logPath) {+ nativo = true;+ SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);+ shell::inst = hi;+ shell::dir = dirBin;+ g_log = _wfsopen(logPath.c_str(), L"w, ccs=UTF-8", _SH_DENYNO);+ Log(L"Shell nativo iniciando dentro do explorer (pid %lu), pasta %ls", GetCurrentProcessId(), dirBin.c_str());+ OleInitialize(nullptr);+ ctxmenu::Init(hi, nullptr); // sem log: o menu gravava e esperava o disco na thread da interface (mesma trava do arquivo do Log)+ if (!ui::Init()) { Log(L"erro: Direct2D/DirectWrite"); return 1; }+ LoadSettings();+ SystemParametersInfoW(SPI_GETWORKAREA, 0, &g_origWork, 0);++ simbolo::Dir() = shell::dir.substr(0, shell::dir.find_last_of(L'\\')) + L"\\icones\\simbolos";+ simbolo::Preload(); // os SF Symbols numa thread: desenhar nunca espera o disco (simbolos.h)+ apps::Load(shell::dir + L"\\" EXE_FINDER);+ apps::Refresh();++ WNDCLASSW mc{}; mc.lpfnWndProc = MsgProc; mc.hInstance = hi; mc.lpszClassName = L"ShellMensagens";+ RegisterClassW(&mc);+ g_msg = CreateWindowExW(WS_EX_TOOLWINDOW, mc.lpszClassName, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, hi, nullptr);+ apps::ours.push_back(g_msg);+ atualizacao::Start(g_msg); // aviso de versão nova no GitHub (90 s depois e a cada 6 h)++ if (!menubar::Create(hi) || !dock::Create(hi) || !launchpad::Create(hi) || !missioncontrol::Create(hi) || !central::Create(hi) || !spotlight::Create(hi) || !alertas::Create(hi) || !sobre::Create(hi) || !seletor::Create(hi) || !som::Create(hi)) { Log(L"erro criando as janelas"); Restore(); return 1; }+ instalados::Start();+ indice::Start();+ revelar::Start();+ ponteiro::Start();+ ponteiro::TemaLeopard(liquid::Leopard());+ genio::Create(hi);+ widgets::Create(hi);+ notificacoes::Create(hi);+ ilha::Create(hi);+ notarapida::Create(hi);+ progresso::Create(hi);+ cantos::Start();+ tray::Start([] { menubar::Update(); }); // nativo: sem janela; os ícones chegam por tray::DoExplorer+ menus::Start();+ dialogs::Start();+ pastas::Start();+ if (GetFileAttributesW(L"C:\\Users\\Public\\MacMesa-desligada.txt") == INVALID_FILE_ATTRIBUTES)+ mesa::Start(hi, g_msg); // nativo: a mesa do projeto por cima da do Explorador (mesmo processo)+ else Log(L"MacMesa-desligada.txt: a mesa fica com o Windows");+ limites::Start();+ sombras::Start();+ // Cantos do Mac (maiores que os 8 px do Windows), sombra e animações nas janelas com a barra padrão: só a+ // WacOSWindow.dll DENTRO dos programas consegue (autorizado pelo usuário em 12/11/2026, "pode injetar").+ // Ela cuida das janelas de barra padrão; as de barra própria (Chrome, Bloco de Notas...) continuam com barras.cpp.+ // C:\Users\Public\MacInjecao-desligada.txt volta a não carregar nada nos outros programas.+ if (GetFileAttributesW(L"C:\\Users\\Public\\MacInjecao-desligada.txt") == INVALID_FILE_ATTRIBUTES) janelas::Start();+ else Log(L"MacInjecao-desligada.txt: nada é carregado nos outros programas (cantos de 8 px)");+ barras::Start(); // nativo: barra de título do Mac por fora (sem nada dentro dos outros programas)+ shell::ApplyWorkArea();++ WM_SHELLHOOK = RegisterWindowMessageW(L"SHELLHOOK");+ RegisterShellHookWindow(g_msg);+ g_fullHook = shell::Setting(L"tecla_windows_launchpad", L"1") == L"1";+ g_macKeys = shell::Setting(L"atalhos_mac", L"1") == L"1";+ g_capturaExe = GetFileAttributesW((shell::dir + L"\\" EXE_SCREENSHOT).c_str()) != INVALID_FILE_ATTRIBUTES;+ EnsureScreenshot();+ g_volumeKeys = shell::Setting(L"volume_mac", L"1") == L"1";+ if (g_fullHook || g_volumeKeys) std::thread(KeyThread).detach();+ SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr, OnWinEvent, 0, 0, WINEVENT_OUTOFCONTEXT);+ jogo::GanchoPosicao(OnWinEvent, WINEVENT_OUTOFCONTEXT); // sai no modo jogo (jogo.cpp)+ SetTimer(g_msg, 1, 1000, nullptr);+ SetTimer(g_msg, 9, 3000, nullptr);+ Log(L"pronto (nativo): %zu apps no Dock", apps::list.size());+ PreloadApps();++ MSG msg;+ sentinela::Start(g_msg); // interface parada 1 s ou mais: o shell.log diz onde (issue #32)+ while (GetMessageW(&msg, nullptr, 0, 0)) { mesa::Pulse(); sentinela::ultimaMsg = msg.message; sentinela::ultimaJanela = msg.hwnd; TranslateMessage(&msg); DispatchMessageW(&msg); } // pulso: ver mesa::Pulse+ Restore();+ DeregisterShellHookWindow(g_msg);+ Log(L"Shell nativo encerrado");+ LogDescarrega();+ if (g_log) fflush(g_log);+ return 0;+}diff --git a/src/shell/menubar.cpp b/src/shell/menubar.cppindex 4891201..540b67b 100644--- a/src/shell/menubar.cpp+++ b/src/shell/menubar.cpp@@ -1,1516 +1,1529 @@-// Barra de menus no topo, como no macOS Sequoia: logo (menu do sistema), nome do app ativo em-// negrito, menus do app; à direita os ícones de status (bandeja), rede, Spotlight, Central de-// Controle e relógio. Ver docs/dock-e-barra-de-menus.md.-#include "shell.h"-#include "../comum/simbolos.h"-static const wchar_t* IconePC() { return shell::Setting(L"sobre_mac", L"pc") == L"macstudio" ? L"pack:macstudio" : L"sym:pc"; }-#include "../menu/context_menu.h"-#include <shellapi.h>-#include <dwmapi.h>-#include <wincodec.h>-#include <shlobj.h>-#include <powrprof.h>-#include <wlanapi.h>-#include <mmdeviceapi.h>-#include <endpointvolume.h>-#include <bluetoothapis.h>-#include <propsys.h>-#pragma comment(lib, "bthprops.lib")-#include <shellscalingapi.h>-#include <iphlpapi.h>-#pragma comment(lib, "iphlpapi.lib")-#include <algorithm>-#include <cmath>-#include <map>-#include <atomic>-#include <mutex>-#include <thread>-#include "../comum/idioma.h"--static void TiqueOcultar(); // ocultar a barra automaticamente (mais abaixo, fora do namespace)-namespace {--const float BAR_PT_SEQUOIA = 26; // altura da barra (telas sem entalhe; um pouco maior que os 24 pt do Mac, para telas grandes)-// Tahoe: 30 pt, medido no macOS 26 (guia macOS26-Theme-Reference, seções 13 e 35: frame.maxY − visibleFrame.maxY)-// Leopard: 22 pt, a barra do Mac OS X 10.5-#define BAR_PT (liquid::On() ? 30.f : liquid::Leopard() ? 22.f : BAR_PT_SEQUOIA)-const float PAD_SEQUOIA = 10; // espaço de cada lado de um ícone de status (Mac: ~10 pt, um item a cada ~38 pt)-// Tahoe (guia, seção 35): cada item da direita = o ícone + ~8 pt de respiro de cada lado (31–42 pt por item)-#define PAD (liquid::On() ? 8.f : PAD_SEQUOIA)--bool g_overflow; // macOS 27: algum ícone da bandeja não coube na barra (mostra a »)-enum Kind { K_LOGO, K_APP, K_MENU, K_TRAY, K_NET, K_SPOT, K_CC, K_CLOCK, K_MORE, K_BATT, K_SOUND, K_BT, K_INPUT };-struct Hit { D2D1_RECT_F r; Kind kind; int index; };--HWND g_bar, g_owner; // g_bar: a barra do monitor principal-// Uma barra em cada monitor (como no Mac), todas com o mesmo conteúdo. Cada uma tem a sua superfície e os-// seus itens clicáveis; g_cur é a que está sendo desenhada/clicada agora (nullptr = a principal), e g_s/g_hits-// apontam para as dela.-struct BarState { ui::Surface s; std::vector<Hit> hits; };-std::map<HWND, BarState> g_state;-std::vector<HWND> g_extras; // barras dos outros monitores-HWND g_cur, g_openBar;-HWND Cur() { return g_cur ? g_cur : g_bar; }-#define g_s (g_state[Cur()].s)-#define g_hits (g_state[Cur()].hits)-int g_open = -1; // índice em g_hits do item com menu aberto (na barra g_openBar)-int g_vaoE = 0, g_vaoD = 0; // barra embaixo: o trecho do Dock na linha dela (px da janela da barra); 0-0 = em cima-HWND g_fg; // janela do app ativo (fora as nossas)-std::wstring g_appName = L"Finder";-std::vector<std::wstring> g_titles; // menus do app ativo-HMENU g_hmenu; // menu Win32 real do app (se tiver)-bool g_finderActive = true;-IDWriteTextFormat *g_tf, *g_tfBold, *g_tfIcon, *g_tfBadge;--// Como no Mac, a barra mostra pouca coisa: os ícones de bandeja só aparecem se o usuário fixar-// ("Mostrar na barra de menus"); os outros ficam na lista da setinha. Guardados pelo nome (dica).-std::vector<std::wstring> Shown() {- std::vector<std::wstring> v;- std::wstring s = shell::Setting(L"barra_icones", L"");- size_t a = 0, b;- while ((b = s.find(L'|', a)) != std::wstring::npos) { if (b > a) v.push_back(s.substr(a, b - a)); a = b + 1; }- if (a < s.size()) v.push_back(s.substr(a));- return v;-}-// Apps Electron (Discord) põem o ícone sem dica: aparecia "(sem nome)" na lista e não dava para fixar, porque o nome-// vazio some ao ler barra_icones (issue #30). Sem dica vale o nome do programa dono (Discord.exe -> Discord): é estável-// e sai sem ler o disco. Guardado por janela e processo (o número de uma janela fechada pode voltar em outro app).-std::wstring ProgramaDoIcone(HWND h) {- DWORD pid = 0;- if (!h || !GetWindowThreadProcessId(h, &pid) || !pid) return L"";- static std::map<std::pair<HWND, DWORD>, std::wstring> nomes;- auto chave = std::make_pair(h, pid);- if (auto it = nomes.find(chave); it != nomes.end()) return it->second;- std::wstring nome;- if (HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid)) {- wchar_t b[MAX_PATH]; DWORD n = MAX_PATH;- if (QueryFullProcessImageNameW(p, 0, b, &n)) {- nome = b;- nome = nome.substr(nome.find_last_of(L'\\') + 1);- if (nome.size() > 4 && !_wcsicmp(nome.c_str() + nome.size() - 4, L".exe")) nome.resize(nome.size() - 4);- if (!nome.empty()) nome[0] = towupper(nome[0]);- }- CloseHandle(p);- }- if (nomes.size() > 256) nomes.clear();- return nomes[chave] = nome;-}-std::wstring TrayKey(const TrayIcon& t) { // nome estável: a dica até a primeira quebra de linha ou ":"; sem dica, o programa- std::wstring k = t.tip.substr(0, t.tip.find_first_of(L"\r\n:"));- while (!k.empty() && k.back() == L' ') k.pop_back();- return k.empty() ? ProgramaDoIcone(t.hwnd) : k;-}-bool IsShown(const TrayIcon& t) {- if (shell::Setting(L"barra_icones_todos", L"0") == L"1") return true; // Central de Controle: "Sempre na barra de menus"- std::wstring k = TrayKey(t);- for (auto& s : Shown()) if (!_wcsicmp(s.c_str(), k.c_str())) return true;- return false;-}-void SetShown(const TrayIcon& t, bool on) {- auto v = Shown();- std::wstring k = TrayKey(t);- v.erase(std::remove_if(v.begin(), v.end(), [&](const std::wstring& x) { return !_wcsicmp(x.c_str(), k.c_str()); }), v.end());- if (on) v.push_back(k);- std::wstring out;- for (auto& x : v) { if (!out.empty()) out += L"|"; out += x; }- shell::SetSetting(L"barra_icones", out);-}--std::wstring Clean(const wchar_t* s, std::wstring* shortcut = nullptr) {- std::wstring out;- for (const wchar_t* p = s; *p; p++) {- if (*p == L'\t') { if (shortcut) *shortcut = p + 1; break; }- if (*p == L'&') { if (p[1] == L'&') { out += L'&'; p++; } continue; }- out += *p;- }- return out;-}--// ---- teclas para os menus genéricos (apps sem menu Win32): mandadas ao app ativo-void SendKeys(std::initializer_list<WORD> keys) {- std::vector<INPUT> in;- for (WORD k : keys) { INPUT i{ INPUT_KEYBOARD }; i.ki.wVk = k; in.push_back(i); }- for (auto it = std::rbegin(keys); it != std::rend(keys); ++it) { INPUT i{ INPUT_KEYBOARD }; i.ki.wVk = *it; i.ki.dwFlags = KEYEVENTF_KEYUP; in.push_back(i); }- SendInput((UINT)in.size(), in.data(), sizeof(INPUT));-}--struct KeyCmd { int id; const wchar_t* label; const wchar_t* shortcut; std::initializer_list<WORD> keys; };-// ids 1000+: atalhos de teclado mandados ao app-const KeyCmd g_keyCmds[] = {- { 1001, L"Nova Janela", L"Ctrl+N", { VK_CONTROL, 'N' } },- { 1002, L"Abrir…", L"Ctrl+O", { VK_CONTROL, 'O' } },- { 1003, L"Fechar Janela", L"Ctrl+W", { VK_CONTROL, 'W' } },- { 1004, L"Salvar", L"Ctrl+S", { VK_CONTROL, 'S' } },- { 1005, L"Imprimir…", L"Ctrl+P", { VK_CONTROL, 'P' } },- { 1010, L"Desfazer", L"Ctrl+Z", { VK_CONTROL, 'Z' } },- { 1011, L"Refazer", L"Ctrl+Y", { VK_CONTROL, 'Y' } },- { 1012, L"Recortar", L"Ctrl+X", { VK_CONTROL, 'X' } },- { 1013, L"Copiar", L"Ctrl+C", { VK_CONTROL, 'C' } },- { 1014, L"Colar", L"Ctrl+V", { VK_CONTROL, 'V' } },- { 1015, L"Selecionar Tudo", L"Ctrl+A", { VK_CONTROL, 'A' } },- { 1016, L"Buscar", L"Ctrl+F", { VK_CONTROL, 'F' } },- { 1020, L"Nova Aba", L"Ctrl+T", { VK_CONTROL, 'T' } },- { 1021, L"Nova Pasta", L"Ctrl+Shift+N", { VK_CONTROL, VK_SHIFT, 'N' } },- { 1022, L"Obter Informações", L"Ctrl+I", { VK_CONTROL, 'I' } },- { 1023, L"Mover para o Lixo", L"Delete", { VK_DELETE } },- { 1030, L"como Ícones", L"Ctrl+1", { VK_CONTROL, '1' } },- { 1031, L"como Lista", L"Ctrl+2", { VK_CONTROL, '2' } },- { 1032, L"como Colunas", L"Ctrl+3", { VK_CONTROL, '3' } },- { 1033, L"como Galeria", L"Ctrl+4", { VK_CONTROL, '4' } },- { 1034, L"Mostrar Opções de Visualização", L"Ctrl+J", { VK_CONTROL, 'J' } },- { 1040, L"Voltar", L"Alt+←", { VK_MENU, VK_LEFT } },- { 1041, L"Avançar", L"Alt+→", { VK_MENU, VK_RIGHT } },- { 1042, L"Pasta Superior", L"Ctrl+↑", { VK_CONTROL, VK_UP } },- { 1043, L"Ir para a Pasta…", L"Ctrl+Shift+G", { VK_CONTROL, VK_SHIFT, 'G' } },- { 1050, L"Ajuda", L"F1", { VK_F1 } },- { 1051, L"Ajustes…", L"Ctrl+,", { VK_CONTROL, VK_OEM_COMMA } },- // menus próprios dos apps sem menu Win32 (AppMenus): os atalhos do Windows de cada um- { 5001, L"Nova Janela Anônima", L"Ctrl+Shift+N", { VK_CONTROL, VK_SHIFT, 'N' } },- { 5002, L"Reabrir Aba Fechada", L"Ctrl+Shift+T", { VK_CONTROL, VK_SHIFT, 'T' } },- { 5003, L"Abrir Arquivo…", L"Ctrl+O", { VK_CONTROL, 'O' } },- { 5004, L"Abrir Local…", L"Ctrl+L", { VK_CONTROL, 'L' } },- { 5005, L"Fechar Janela", L"Ctrl+Shift+W", { VK_CONTROL, VK_SHIFT, 'W' } },- { 5006, L"Fechar Aba", L"Ctrl+W", { VK_CONTROL, 'W' } },- { 5007, L"Salvar Página Como…", L"Ctrl+S", { VK_CONTROL, 'S' } },- { 5010, L"Sempre Mostrar a Barra de Favoritos", L"Ctrl+Shift+B", { VK_CONTROL, VK_SHIFT, 'B' } },- { 5011, L"Parar", L"Esc", { VK_ESCAPE } },- { 5012, L"Recarregar Esta Página", L"Ctrl+R", { VK_CONTROL, 'R' } },- { 5013, L"Forçar Recarregamento", L"Ctrl+Shift+R", { VK_CONTROL, VK_SHIFT, 'R' } },- { 5014, L"Entrar em Tela Cheia", L"F11", { VK_F11 } },- { 5015, L"Tamanho Real", L"Ctrl+0", { VK_CONTROL, '0' } },- { 5016, L"Ampliar", L"Ctrl+=", { VK_CONTROL, VK_OEM_PLUS } },- { 5017, L"Reduzir", L"Ctrl+-", { VK_CONTROL, VK_OEM_MINUS } },- { 5018, L"Ferramentas do Desenvolvedor", L"Ctrl+Shift+I", { VK_CONTROL, VK_SHIFT, 'I' } },- { 5019, L"Ver Código-Fonte", L"Ctrl+U", { VK_CONTROL, 'U' } },- { 5020, L"Página Inicial", L"Alt+Home", { VK_MENU, VK_HOME } },- { 5021, L"Mostrar Histórico Completo", L"Ctrl+H", { VK_CONTROL, 'H' } },- { 5022, L"Limpar Dados de Navegação…", L"Ctrl+Shift+Del", { VK_CONTROL, VK_SHIFT, VK_DELETE } },- { 5030, L"Gerenciador de Favoritos", L"Ctrl+Shift+O", { VK_CONTROL, VK_SHIFT, 'O' } },- { 5031, L"Adicionar Esta Página aos Favoritos…", L"Ctrl+D", { VK_CONTROL, 'D' } },- { 5032, L"Adicionar Todas as Abas aos Favoritos…", L"Ctrl+Shift+D", { VK_CONTROL, VK_SHIFT, 'D' } },- { 5040, L"Selecionar Próxima Aba", L"Ctrl+Tab", { VK_CONTROL, VK_TAB } },- { 5041, L"Selecionar Aba Anterior", L"Ctrl+Shift+Tab", { VK_CONTROL, VK_SHIFT, VK_TAB } },- { 5050, L"Downloads", L"Ctrl+J", { VK_CONTROL, 'J' } },- { 5051, L"Gerenciador de Tarefas", L"Shift+Esc", { VK_SHIFT, VK_ESCAPE } },- { 5060, L"Central de Ajuda", L"F1", { VK_F1 } },- { 5070, L"Refazer", L"Ctrl+Shift+Z", { VK_CONTROL, VK_SHIFT, 'Z' } },- { 5071, L"Recarregar", L"Ctrl+R", { VK_CONTROL, 'R' } },- { 5072, L"Busca Rápida", L"Ctrl+K", { VK_CONTROL, 'K' } },- { 5073, L"Atalhos de Teclado", L"Ctrl+/", { VK_CONTROL, VK_DIVIDE } },- { 5080, L"Nova Conversa", L"Ctrl+N", { VK_CONTROL, 'N' } },- { 5081, L"Novo Grupo", L"Ctrl+Shift+N", { VK_CONTROL, VK_SHIFT, 'N' } },- // Spotify- { 5100, L"Nova Playlist", L"Ctrl+N", { VK_CONTROL, 'N' } },- { 5101, L"Reproduzir/Pausar", L"Espaço", { VK_SPACE } },- { 5102, L"Próxima", L"Ctrl+→", { VK_CONTROL, VK_RIGHT } },- { 5103, L"Anterior", L"Ctrl+←", { VK_CONTROL, VK_LEFT } },- { 5104, L"Aumentar Volume", L"Ctrl+↑", { VK_CONTROL, VK_UP } },- { 5105, L"Diminuir Volume", L"Ctrl+↓", { VK_CONTROL, VK_DOWN } },- { 5106, L"Repetir", L"Ctrl+R", { VK_CONTROL, 'R' } },- { 5107, L"Aleatório", L"Ctrl+S", { VK_CONTROL, 'S' } },- { 5108, L"Buscar", L"Ctrl+K", { VK_CONTROL, 'K' } },- // VS Code- { 5120, L"Novo Arquivo", L"Ctrl+N", { VK_CONTROL, 'N' } },- { 5121, L"Nova Janela", L"Ctrl+Shift+N", { VK_CONTROL, VK_SHIFT, 'N' } },- { 5122, L"Salvar Como…", L"Ctrl+Shift+S", { VK_CONTROL, VK_SHIFT, 'S' } },- { 5123, L"Fechar Editor", L"Ctrl+W", { VK_CONTROL, 'W' } },- { 5124, L"Substituir", L"Ctrl+H", { VK_CONTROL, 'H' } },- { 5125, L"Buscar nos Arquivos", L"Ctrl+Shift+F", { VK_CONTROL, VK_SHIFT, 'F' } },- { 5126, L"Paleta de Comandos…", L"Ctrl+Shift+P", { VK_CONTROL, VK_SHIFT, 'P' } },- { 5127, L"Explorador", L"Ctrl+Shift+E", { VK_CONTROL, VK_SHIFT, 'E' } },- { 5128, L"Controle do Código-Fonte", L"Ctrl+Shift+G", { VK_CONTROL, VK_SHIFT, 'G' } },- { 5129, L"Extensões", L"Ctrl+Shift+X", { VK_CONTROL, VK_SHIFT, 'X' } },- { 5130, L"Ir para Arquivo…", L"Ctrl+P", { VK_CONTROL, 'P' } },- { 5131, L"Ir para Linha…", L"Ctrl+G", { VK_CONTROL, 'G' } },- { 5132, L"Iniciar Depuração", L"F5", { VK_F5 } },- { 5133, L"Executar sem Depurar", L"Ctrl+F5", { VK_CONTROL, VK_F5 } },- { 5134, L"Barra Lateral", L"Ctrl+B", { VK_CONTROL, 'B' } },-};--ctxmenu::Item K(int id) {- for (auto& k : g_keyCmds) if (k.id == id) { ctxmenu::Item i; i.label = Tr(k.label); i.id = id; i.shortcut = k.shortcut; return i; }- return {};-}-ctxmenu::Item I(const std::wstring& label, int id, bool disabled = false, bool checked = false) {- ctxmenu::Item i; i.label = label; i.id = id; i.disabled = disabled; i.checked = checked; return i;-}-ctxmenu::Item Sep() { ctxmenu::Item i; i.separator = true; return i; }--// ---- menu Win32 real do app → itens do nosso menu-std::vector<ctxmenu::Item> FromHmenu(HMENU m, int depth) {- std::vector<ctxmenu::Item> out;- int n = GetMenuItemCount(m);- for (int k = 0; k < n; k++) {- wchar_t buf[256] = {};- MENUITEMINFOW mi{ sizeof(mi) };- mi.fMask = MIIM_STRING | MIIM_FTYPE | MIIM_STATE | MIIM_ID | MIIM_SUBMENU;- mi.dwTypeData = buf; mi.cch = 255;- if (!GetMenuItemInfoW(m, k, TRUE, &mi)) continue;- if (mi.fType & MFT_SEPARATOR) { if (!out.empty() && !out.back().separator) out.push_back(Sep()); continue; }- if (mi.fType & MFT_OWNERDRAW || !buf[0]) continue;- ctxmenu::Item it;- it.label = Clean(buf, &it.shortcut);- it.id = (int)mi.wID;- it.disabled = (mi.fState & (MFS_DISABLED | MFS_GRAYED)) != 0;- it.checked = (mi.fState & MFS_CHECKED) != 0;- if (mi.hSubMenu) {- if (g_fg) {- // alguns apps só preenchem o submenu quando o item dele é destacado (o Ableton deixa "*" nos- // sets recentes até receber WM_MENUSELECT); depois espera um pouco se ainda for o marcador- SendMessageTimeoutW(g_fg, WM_MENUSELECT, MAKEWPARAM(k, MF_POPUP | MF_HILITE), (LPARAM)m, SMTO_ABORTIFHUNG, 200, nullptr);- SendMessageTimeoutW(g_fg, WM_INITMENUPOPUP, (WPARAM)mi.hSubMenu, k, SMTO_ABORTIFHUNG, 200, nullptr);- for (int t = 0; t < 12; t++) {- wchar_t first[8] = {};- GetMenuStringW(mi.hSubMenu, 0, first, 8, MF_BYPOSITION);- if (wcscmp(first, L"*")) break;- SendMessageTimeoutW(g_fg, WM_NULL, 0, 0, SMTO_ABORTIFHUNG, 100, nullptr);- Sleep(15);- }- }- if (depth == 0) it.sub = FromHmenu(mi.hSubMenu, 1);- else { // nosso menu tem um nível de submenu: os mais fundos entram achatados- out.push_back(Sep());- for (auto& c : FromHmenu(mi.hSubMenu, 2)) out.push_back(c);- out.push_back(Sep());- continue;- }- }- out.push_back(it);- }- while (!out.empty() && out.back().separator) out.pop_back();- return out;-}--App* ActiveApp() {- if (g_finderActive || !g_fg) for (auto& a : apps::list) if (a.finder) return &a;- return g_fg ? apps::OfWindow(g_fg) : nullptr;-}--// ---- estado do sistema para a direita da barra-bool WifiName(std::wstring& ssid) {- HANDLE h = nullptr; DWORD ver = 0;- if (WlanOpenHandle(2, nullptr, &ver, &h) != ERROR_SUCCESS) return false;- bool ok = false;- PWLAN_INTERFACE_INFO_LIST list = nullptr;- if (WlanEnumInterfaces(h, nullptr, &list) == ERROR_SUCCESS) {- for (DWORD i = 0; i < list->dwNumberOfItems && !ok; i++) {- auto& info = list->InterfaceInfo[i];- if (info.isState != wlan_interface_state_connected) continue;- // Conectado é o estado da placa. O nome da rede, desde o Windows 11 24H2, só sai com a permissão de- // localização ligada (sem ela a consulta falha): antes isso virava "não conectado" (issue #40)- ok = true;- PWLAN_CONNECTION_ATTRIBUTES ca = nullptr; DWORD sz = 0;- if (WlanQueryInterface(h, &info.InterfaceGuid, wlan_intf_opcode_current_connection, nullptr, &sz, (PVOID*)&ca, nullptr) == ERROR_SUCCESS && ca) {- auto& s = ca->wlanAssociationAttributes.dot11Ssid;- std::string a((const char*)s.ucSSID, s.uSSIDLength); // o nome vem em UTF-8- int n = MultiByteToWideChar(CP_UTF8, 0, a.c_str(), (int)a.size(), nullptr, 0);- ssid.resize(n);- MultiByteToWideChar(CP_UTF8, 0, a.c_str(), (int)a.size(), ssid.data(), n);- WlanFreeMemory(ca);- }- }- WlanFreeMemory(list);- }- WlanCloseHandle(h, nullptr);- return ok;-}--// Estado do sistema para os ícones da direita (relido a cada segundo; o Bluetooth a cada 10 s)-struct Status {- bool wlan = false, wifiOn = false, wired = false;- bool batt = false, charging = false; int pct = 100;- bool bt = false;- bool sound = false, muted = false, phones = false; float vol = 0;- HKL hkl = nullptr;- DWORD btAt = 0;- std::wstring ssid;-} g_st;--bool WifiName(std::wstring& ssid);-std::atomic<bool> g_audioStale{ false }; // a saída padrão mudou: relê o objeto de áudio já--void LerStatus(Status& st) {- static DWORD wifiAt, audioAt;- static IAudioEndpointVolume* vol; // o mesmo objeto de áudio entre as leituras (antes: criado e solto a cada segundo)- DWORD now = GetTickCount();- // Wi-Fi: existe placa? está conectada? (a cada 5 s)- if (!wifiAt || now - wifiAt > 5000) {- wifiAt = now;- st.wlan = false;- HANDLE h = nullptr; DWORD ver = 0;- if (WlanOpenHandle(2, nullptr, &ver, &h) == ERROR_SUCCESS) {- PWLAN_INTERFACE_INFO_LIST list = nullptr;- if (WlanEnumInterfaces(h, nullptr, &list) == ERROR_SUCCESS) { st.wlan = list->dwNumberOfItems > 0; WlanFreeMemory(list); }- WlanCloseHandle(h, nullptr);- }- st.ssid.clear();- st.wifiOn = st.wlan && WifiName(st.ssid);- // cabo ligado (placa Ethernet com rede)? Aí o Wi-Fi desconectado não aparece na barra- st.wired = false;- ULONG sz = 16 * 1024;- std::vector<BYTE> buf(sz);- DWORD rc = GetAdaptersInfo((IP_ADAPTER_INFO*)buf.data(), &sz);- if (rc == ERROR_BUFFER_OVERFLOW) { buf.resize(sz); rc = GetAdaptersInfo((IP_ADAPTER_INFO*)buf.data(), &sz); }- if (rc == NO_ERROR) // placa Ethernet com gateway = cabo conectado à rede- for (auto* a = (IP_ADAPTER_INFO*)buf.data(); a; a = a->Next)- if (a->Type == MIB_IF_TYPE_ETHERNET && strcmp(a->GatewayList.IpAddress.String, "0.0.0.0") && a->GatewayList.IpAddress.String[0]) { st.wired = true; break; }- }- // bateria (só em quem tem)- SYSTEM_POWER_STATUS ps{};- if (GetSystemPowerStatus(&ps) && !(ps.BatteryFlag & 128) && ps.BatteryFlag != 255 && ps.BatteryLifePercent <= 100) {- st.batt = true; st.pct = ps.BatteryLifePercent; st.charging = ps.ACLineStatus == 1;- } else st.batt = false;- // Bluetooth: tem rádio?- if (!st.btAt || GetTickCount() - st.btAt > 10000) {- st.btAt = GetTickCount();- BLUETOOTH_FIND_RADIO_PARAMS fp{ sizeof(fp) }; HANDLE radio = nullptr;- HBLUETOOTH_RADIO_FIND f = BluetoothFindFirstRadio(&fp, &radio);- st.bt = f != nullptr;- if (radio) CloseHandle(radio);- if (f) BluetoothFindRadioClose(f);- }- // som: volume e mudo a cada segundo (barato, no objeto guardado); a saída padrão e se é um fone a cada 10 s- bool fresh = false;- if (g_audioStale.exchange(false)) audioAt = 0;- if (vol && audioAt && now - audioAt < 10000) {- BOOL mute = FALSE;- if (SUCCEEDED(vol->GetMute(&mute)) && SUCCEEDED(vol->GetMasterVolumeLevelScalar(&st.vol))) { st.muted = mute; fresh = true; }- }- if (!fresh) {- audioAt = now;- if (vol) { vol->Release(); vol = nullptr; }- st.sound = false;- IMMDeviceEnumerator* en = nullptr;- if (SUCCEEDED(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&en)))) {- IMMDevice* dev = nullptr;- if (SUCCEEDED(en->GetDefaultAudioEndpoint(eRender, eConsole, &dev))) {- if (SUCCEEDED(dev->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, nullptr, (void**)&vol))) {- BOOL mute = FALSE; vol->GetMute(&mute); vol->GetMasterVolumeLevelScalar(&st.vol);- st.muted = mute; st.sound = true;- }- IPropertyStore* ps2 = nullptr;- st.phones = false;- if (SUCCEEDED(dev->OpenPropertyStore(STGM_READ, &ps2))) {- static const PROPERTYKEY formFactor = { { 0x1da5d803, 0xd492, 0x4edd, { 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e } }, 0 };- PROPVARIANT v; PropVariantInit(&v);- if (SUCCEEDED(ps2->GetValue(formFactor, &v)) && v.vt == VT_UI4) st.phones = v.ulVal == 3 || v.ulVal == 5; // fone / headset- PropVariantClear(&v);- ps2->Release();- }- dev->Release();- }- en->Release();- }- }-}--// Tudo acima pergunta a um serviço do Windows (WLAN, rede, Bluetooth, áudio) e espera a resposta. Na thread da-// interface, com o PC ocupado, o Shell inteiro parava: o WlanOpenHandle levou 3,6 s (pilha de 22/11/2026, 15:14).-// Uma thread só lê; a interface pega a última resposta e redesenha quando chega uma diferente.-const UINT WM_BARSTATUS = WM_APP + 42;-std::mutex g_stMx;-Status g_stLido;--void PedeStatus() {- static HANDLE pedido = CreateEventW(nullptr, FALSE, FALSE, nullptr);- static std::once_flag uma;- std::call_once(uma, [] {- std::thread([] {- CoInitializeEx(nullptr, COINIT_MULTITHREADED);- Status st;- while (WaitForSingleObject(pedido, INFINITE) == WAIT_OBJECT_0) {- LerStatus(st);- bool mudou;- {- std::lock_guard<std::mutex> l(g_stMx);- const Status& a = g_stLido;- mudou = a.wlan != st.wlan || a.wifiOn != st.wifiOn || a.wired != st.wired || a.batt != st.batt || a.charging != st.charging ||- a.pct != st.pct || a.bt != st.bt || a.sound != st.sound || a.muted != st.muted || a.phones != st.phones ||- a.vol != st.vol || a.ssid != st.ssid;- g_stLido = st;- }- if (mudou && g_bar) PostMessageW(g_bar, WM_BARSTATUS, 0, 0);- }- }).detach();- });- SetEvent(pedido);-}--void PegaStatus() {- { std::lock_guard<std::mutex> l(g_stMx); g_st = g_stLido; }- // fonte de entrada (teclado) do app da frente- HWND fg = GetForegroundWindow();- g_st.hkl = GetKeyboardLayout(fg ? GetWindowThreadProcessId(fg, nullptr) : 0);-}--void RefreshStatus() {- PedeStatus();- PegaStatus();-}--// "A" para o teclado americano (o "ABC" do Mac), senão a sigla do país do layout (BR, PT, ES…)-std::wstring InputBadge(HKL hkl) {- WORD layout = HIWORD((ULONG_PTR)hkl), lang = LOWORD((ULONG_PTR)hkl);- if ((layout & 0xF000) == 0xF000) layout = lang; // layout alternativo: usa o idioma- if (layout == 0x0409) return L"A";- wchar_t name[LOCALE_NAME_MAX_LENGTH] = {};- if (LCIDToLocaleName(MAKELCID(layout, SORT_DEFAULT), name, LOCALE_NAME_MAX_LENGTH, 0) ||- LCIDToLocaleName(MAKELCID(lang, SORT_DEFAULT), name, LOCALE_NAME_MAX_LENGTH, 0)) {- std::wstring n = name;- size_t d = n.find(L'-');- std::wstring c = d != std::wstring::npos ? n.substr(d + 1, 2) : n.substr(0, 2);- for (auto& ch : c) ch = towupper(ch);- return c;- }- return L"?";-}-std::wstring LayoutName(HKL hkl) {- wchar_t name[LOCALE_NAME_MAX_LENGTH] = {}, disp[128] = {};- LCIDToLocaleName(MAKELCID(LOWORD((ULONG_PTR)hkl), SORT_DEFAULT), name, LOCALE_NAME_MAX_LENGTH, 0);- GetLocaleInfoEx(name, LOCALE_SLOCALIZEDDISPLAYNAME, disp, 128);- std::wstring r = disp[0] ? disp : name;- if (HIWORD((ULONG_PTR)hkl) == 0x0416) r += L" (ABNT2)";- return r;-}--IAudioEndpointVolume* Volume() {- IMMDeviceEnumerator* en = nullptr;- IAudioEndpointVolume* vol = nullptr;- if (SUCCEEDED(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&en)))) {- IMMDevice* dev = nullptr;- if (SUCCEEDED(en->GetDefaultAudioEndpoint(eRender, eConsole, &dev))) {- dev->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, nullptr, (void**)&vol);- dev->Release();- }- en->Release();- }- return vol;-}--std::wstring ClockText() {- SYSTEMTIME st; GetLocalTime(&st);- wchar_t day[16] = {}, mon[16] = {};- const wchar_t* loc = idioma::Locale();- GetDateFormatEx(loc, 0, &st, L"ddd", day, 16, nullptr);- GetDateFormatEx(loc, 0, &st, L"MMM", mon, 16, nullptr);- std::wstring d = day, m = mon;- if (idioma::Pt() && !d.empty() && d.back() != L'.') d += L'.';- if (idioma::Pt() && !m.empty() && m.back() != L'.') m += L'.';- wchar_t buf[64];- if (liquid::Leopard()) {- // Leopard: só o dia da semana e a hora ("Mon 6:45 PM" na captura do 10.5), no formato de hora do usuário- wchar_t tm[32] = {};- GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, TIME_NOSECONDS, &st, nullptr, tm, 32);- std::wstring dd = day;- if (!dd.empty() && dd.back() == L'.') dd.pop_back();- if (!dd.empty()) dd[0] = towupper(dd[0]);- swprintf_s(buf, L"%ls %ls", dd.c_str(), tm);- return buf;- }- // relogio_segundos (issue #38, como "Mostrar segundos" do Mac): 14:05:09- wchar_t hm[16];- if (shell::Setting(L"relogio_segundos", L"0") == L"1") swprintf_s(hm, L"%02d:%02d:%02d", st.wHour, st.wMinute, st.wSecond);- else swprintf_s(hm, L"%02d:%02d", st.wHour, st.wMinute);- if (shell::Setting(L"relogio_curto", L"0") == L"1") swprintf_s(buf, L"%ls", hm);- else if (idioma::En()) swprintf_s(buf, L"%ls %ls %d %ls", d.c_str(), m.c_str(), st.wDay, hm); // Tue Nov 10- else if (idioma::Pt()) swprintf_s(buf, L"%ls %d de %ls %ls", d.c_str(), st.wDay, m.c_str(), hm);- else swprintf_s(buf, L"%ls %ls", idioma::Date(st, idioma::D_WEEKDAY_SHORT).c_str(), hm); // ven. 20 nov., 11月20日(金)- return buf;-}--// ---- ícones de status: HICON → BGRA pré-multiplicado (desenhado sobre preto e sobre branco)-struct IconCache { HICON icon; UINT px; std::vector<BYTE> bgra; };-std::vector<IconCache> g_iconCache;--const std::vector<BYTE>& IconPixels(HICON ic, UINT px) {- for (auto& c : g_iconCache) if (c.icon == ic && c.px == px) return c.bgra;- if (g_iconCache.size() > 64) g_iconCache.clear();- // desenhado 4× maior e reduzido pela média de cada bloco 4×4 (anti-aliasing): em 1080p (17 px) o DrawIconEx- // esticava o ícone de 16/32 px pelo vizinho mais próximo e a borda saía serrilhada- const UINT SS = 4, R = px * SS;- BITMAPINFO bi{}; bi.bmiHeader = { sizeof(BITMAPINFOHEADER), (LONG)R, -(LONG)R, 1, 32, BI_RGB };- void *pb, *pw;- HDC dc = CreateCompatibleDC(nullptr);- HBITMAP b = CreateDIBSection(nullptr, &bi, DIB_RGB_COLORS, &pb, nullptr, 0);- HBITMAP w = CreateDIBSection(nullptr, &bi, DIB_RGB_COLORS, &pw, nullptr, 0);- IconCache c{ ic, px, std::vector<BYTE>(px * px * 4) };- if (!b || !w || !pb || !pw) {- if (b) DeleteObject(b);- if (w) DeleteObject(w);- DeleteDC(dc);- g_iconCache.push_back(std::move(c));- return g_iconCache.back().bgra;- }- memset(pw, 0xFF, R * R * 4);- HGDIOBJ old = SelectObject(dc, b); DrawIconEx(dc, 0, 0, ic, R, R, 0, nullptr, DI_NORMAL);- SelectObject(dc, w); DrawIconEx(dc, 0, 0, ic, R, R, 0, nullptr, DI_NORMAL);- SelectObject(dc, old);- auto* B = (BYTE*)pb; auto* W = (BYTE*)pw;- for (UINT y = 0; y < px; y++)- for (UINT x = 0; x < px; x++) {- UINT sb = 0, sg = 0, sr = 0, sa = 0;- for (UINT dy = 0; dy < SS; dy++)- for (UINT dx = 0; dx < SS; dx++) {- size_t i = ((size_t)(y * SS + dy) * R + (x * SS + dx)) * 4;- int a = 255 - std::clamp((W[i + 1] - B[i + 1]), 0, 255); // alfa = 1 - (branco - preto)- sb += B[i + 0]; sg += B[i + 1]; sr += B[i + 2]; sa += (UINT)a;- }- const UINT n = SS * SS;- size_t o = ((size_t)y * px + x) * 4;- c.bgra[o + 3] = (BYTE)((sa + n / 2) / n);- c.bgra[o + 0] = (BYTE)std::min<UINT>((sb + n / 2) / n, c.bgra[o + 3]);- c.bgra[o + 1] = (BYTE)std::min<UINT>((sg + n / 2) / n, c.bgra[o + 3]);- c.bgra[o + 2] = (BYTE)std::min<UINT>((sr + n / 2) / n, c.bgra[o + 3]);- }- DeleteObject(b); DeleteObject(w); DeleteDC(dc);- g_iconCache.push_back(std::move(c));- return g_iconCache.back().bgra;-}--// ---- desenho-void DrawLogo(ID2D1RenderTarget* rt, ID2D1SolidColorBrush* br, float cx, float cy) {- // logo próprio (não usamos a marca da Apple): quatro quadradinhos arredondados- float s = 5.4f, g = 1.6f;- for (int i = 0; i < 4; i++) {- float x = cx - s - g / 2 + (i % 2) * (s + g), y = cy - s - g / 2 + (i / 2) * (s + g);- rt->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(x, y, x + s, y + s), 1.5f, 1.5f), br);- }-}--void DrawCC(ID2D1RenderTarget* rt, ID2D1SolidColorBrush* br, float cx, float cy) {- // Central de Controle: duas chavinhas- for (int k = 0; k < 2; k++) {- float y = cy - 3.6f + k * 7.2f;- D2D1_ROUNDED_RECT rr{ D2D1::RectF(cx - 7.5f, y - 2.8f, cx + 7.5f, y + 2.8f), 2.8f, 2.8f };- rt->DrawRoundedRectangle(rr, br, 1.2f);- float kx = k == 0 ? cx - 4.7f : cx + 4.7f;- rt->FillEllipse(D2D1::Ellipse({ kx, y }, 2.0f, 2.0f), br);- }-}--// Ajustes > Transparência e Efeitos > "Mostrar fundo da barra de menus" (desligado: como no Tahoe)-// No Tahoe (Liquid Glass) a barra de menus não tem fundo nenhum, como no macOS 26: só o papel de parede atrás.-bool BarBackground() {- if (backdrop::Current().reduce || liquid::Leopard()) return true; // Leopard: a barra translúcida clara sempre tem fundo- if (menubar::Embaixo()) return false; // na linha do Dock: sem faixa atravessando a tela- if (backdrop::Liquid()) return false;- return shell::Setting(L"barra_fundo", L"1") != L"0";-}--void BarGlass(HWND bar) {- if (!bar) return;- // Leopard: o degradê branco translúcido vem do Render. Translúcida (padrão): transparência de verdade, SEM desfoque- // (o 10.5 deixava o papel de parede aparecer nítido através da barra); opaca: acrílico cheio por baixo- const bool leoClear = liquid::Leopard() && shell::Setting(L"barra_translucida", L"1") == L"1";- if (liquid::Leopard() && !leoClear) { ui::Acrylic(bar, 0xFFE6E6E6u); return; }- if (!leoClear)- if (BarBackground()) { ui::Acrylic(bar, ui::Dark() ? 0x40141414u : 0x55F4F4F4u); return; } // vidro bem claro: o papel de parede aparece, como no Mac- // sem fundo: o DWM só respeita o alfa do que a barra desenha (nada de desfoque)- struct ACCENT_POLICY { int state, flags; DWORD gradient; int anim; };- struct WCA_DATA { int attr; PVOID data; SIZE_T size; };- using Fn = BOOL(WINAPI*)(HWND, WCA_DATA*);- static Fn fn = (Fn)GetProcAddress(GetModuleHandleW(L"user32.dll"), "SetWindowCompositionAttribute");- if (!fn) return;- ACCENT_POLICY ap{ 2 /*ACCENT_ENABLE_TRANSPARENTGRADIENT*/, 2, 0x00000000u, 0 };- WCA_DATA d{ 19 /*WCA_ACCENT_POLICY*/, &ap, sizeof(ap) };- fn(bar, &d);-}--// Barra sem fundo (Tahoe): o texto e os ícones seguem a claridade do que está atrás deles, como no Mac-// (branco sobre papel de parede escuro, preto sobre claro), não o tema do sistema. A barra fica sempre-// em cima do papel de parede (a área de trabalho começa abaixo dela): mede o topo da imagem.-float g_topR = 0.5f, g_topG = 0.5f, g_topB = 0.5f; // cor média do topo do papel de parede (vibrancy do Tahoe)-bool WallpaperTopDarkFile(bool fallback);-// a cor do que está atrás da barra: a faixa que a mesa desenhou (muda na hora com o papel de parede); sem a mesa, o-// arquivo do papel de parede-bool WallpaperTopDark(bool fallback) {- float r, g, b;- const bool baixo = menubar::Embaixo();- const int faixa = baixo ? menubar::ReservedBottom(MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)) : menubar::Height();- if (!mesa::TopColor(faixa, r, g, b, baixo)) return WallpaperTopDarkFile(fallback);- g_topR = r; g_topG = g; g_topB = b;- double luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;- static int adapt = -1; // -1 ainda não decidido, 0 texto claro, 1 texto escuro- static double lastLog = -1;- bool dark;- if (liquid::On()) { // histerese 0,40/0,60 (guia, seção 2.1)- if (luma > 0.60) adapt = 1; else if (luma < 0.40) adapt = 0; else if (adapt < 0) adapt = luma >= 0.5 ? 1 : 0;- dark = adapt == 0;- } else dark = luma < 0.72;- if (std::fabs(luma - lastLog) > 0.05) { lastLog = luma; Log(L"barra de menus: atrás dela claridade %.2f -> texto %ls", luma, dark ? L"branco" : L"preto"); }- return dark;-}-// O arquivo do papel de parede numa thread (issue #32): esta conta roda a cada desenho da barra e a cada tique de 1 s,-// e com o Explorador de fundo (o padrão, sem a nossa mesa para dar a cor) lia o Registro e perguntava ao disco pelo-// arquivo toda vez. Com o disco ocupado o GetFileAttributes segurou a interface 11 s (sentinela, 22/11/2026 20:49).-// Agora a interface usa o último resultado e pede uma leitura nova no máximo a cada 4 s.-bool LeTopoDoArquivo(bool fallback, float rgb[3]);-void Render();-bool WallpaperTopDarkFile(bool fallback) {- static std::atomic<bool> rodando{ false };- static DWORD quando = 0;- static int escuro = -1; // -1: ainda sem leitura- DWORD agora = GetTickCount();- if (!rodando && (!quando || agora - quando > 4000)) {- quando = agora;- rodando = true;- std::thread([fallback] {- HRESULT ci = CoInitializeEx(nullptr, COINIT_MULTITHREADED); // WIC- float rgb[3] = { -1, -1, -1 };- bool d = LeTopoDoArquivo(fallback, rgb);- if (SUCCEEDED(ci)) CoUninitialize();- shell::NaInterface([d, r = rgb[0], g = rgb[1], b = rgb[2]] {- rodando = false;- bool mudou = escuro != (d ? 1 : 0);- escuro = d ? 1 : 0;- if (r >= 0 && (r != g_topR || g != g_topG || b != g_topB)) { g_topR = r; g_topG = g; g_topB = b; mudou = true; }- if (mudou) Render();- });- }).detach();- }- return escuro < 0 ? fallback : escuro == 1;-}-// roda numa thread (só uma por vez): rgb sai com a cor média do topo, ou fica como veio se não leu-bool LeTopoDoArquivo(bool fallback, float rgb[3]) {- static std::wstring lastKey;- static bool lastDark = true;- static float lastRGB[3] = { -1, -1, -1 };- struct Sai { float* o; ~Sai() { if (lastRGB[0] >= 0) for (int i = 0; i < 3; i++) o[i] = lastRGB[i]; } } sai{ rgb };- // o papel de parede que a mesa desenha (do registro); sem ele, o do Windows- wchar_t path[MAX_PATH] = {};- DWORD cb = sizeof(path);- if (RegGetValueW(HKEY_CURRENT_USER, L"Control Panel\\Desktop", L"WallPaper", RRF_RT_REG_SZ, nullptr, path, &cb) != ERROR_SUCCESS || !path[0]- || GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES)- SystemParametersInfoW(SPI_GETDESKWALLPAPER, MAX_PATH, path, 0);- WIN32_FILE_ATTRIBUTE_DATA fa{};- if (!path[0] || !GetFileAttributesExW(path, GetFileExInfoStandard, &fa)) {- static bool warned;- if (!warned) { warned = true; Log(L"barra de menus: papel de parede não encontrado (%ls)", path); }- return fallback;- }- std::wstring key = std::wstring(path) + L"|" + std::to_wstring(fa.ftLastWriteTime.dwLowDateTime);- if (key == lastKey) return lastDark;- lastKey = key;- lastDark = fallback;- IWICImagingFactory* wic = nullptr;- HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic));- if (FAILED(hr)) { Log(L"barra de menus: WIC indisponível (0x%08X)", (unsigned)hr); return fallback; }- IWICBitmapDecoder* dec = nullptr; IWICBitmapFrameDecode* fr = nullptr; IWICBitmapScaler* sc = nullptr; IWICFormatConverter* cv = nullptr;- const UINT W = 96, H = 54;- int step = 0;- if (++step, SUCCEEDED(hr = wic->CreateDecoderFromFilename(path, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &dec)) && (++step, SUCCEEDED(hr = dec->GetFrame(0, &fr))) &&- (++step, SUCCEEDED(hr = wic->CreateBitmapScaler(&sc))) && (++step, SUCCEEDED(hr = sc->Initialize(fr, W, H, WICBitmapInterpolationModeFant))) &&- (++step, SUCCEEDED(hr = wic->CreateFormatConverter(&cv))) && (++step, SUCCEEDED(hr = cv->Initialize(sc, GUID_WICPixelFormat32bppBGRA, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeCustom)))) {- std::vector<BYTE> px(W * 3 * 4); // as 3 primeiras linhas (~5% de cima, onde fica a barra)- WICRect top{ 0, 0, (INT)W, 3 };- if (SUCCEEDED(hr = cv->CopyPixels(&top, W * 4, (UINT)px.size(), px.data()))) {- double sum = 0, sr = 0, sg = 0, sb = 0;- for (UINT i = 0; i < W * 3; i++) {- sum += (0.0722 * px[i * 4] + 0.7152 * px[i * 4 + 1] + 0.2126 * px[i * 4 + 2]) / 255.0;- sb += px[i * 4] / 255.0; sg += px[i * 4 + 1] / 255.0; sr += px[i * 4 + 2] / 255.0;- }- double luma = sum / (W * 3);- lastRGB[0] = (float)(sr / (W * 3)); lastRGB[1] = (float)(sg / (W * 3)); lastRGB[2] = (float)(sb / (W * 3));- // Tahoe: adaptação com histerese do vidro do macOS 26 (glassLumaHysteresisRange, guia seção 2.1): acima de- // 0,60 vira texto escuro, abaixo de 0,40 texto claro, entre os dois fica como estava. Sequoia: limiar 0,72.- static int adapt = -1; // -1 ainda não decidido, 0 texto claro, 1 texto escuro- if (liquid::On()) {- if (luma > 0.60) adapt = 1; else if (luma < 0.40) adapt = 0; else if (adapt < 0) adapt = luma >= 0.5 ? 1 : 0;- lastDark = adapt == 0;- } else lastDark = luma < 0.72; // o Mac só usa texto escuro sobre fundo bem claro- Log(L"barra de menus: topo do papel de parede com claridade %.2f -> texto %ls", luma, lastDark ? L"branco" : L"preto");- }- }- else Log(L"barra de menus: não deu para ler o papel de parede (etapa %d, 0x%08X)", step, (unsigned)hr);- if (cv) cv->Release(); if (sc) sc->Release(); if (fr) fr->Release(); if (dec) dec->Release();- wic->Release();- return lastDark;-}--void Render() {- if (!g_bar) return;- HWND bar = Cur();- g_s.hwnd = bar;- RECT rc; GetClientRect(bar, &rc);- float sc = ui::Scale(bar);- auto* rt = ui::Begin(g_s, rc.right, rc.bottom, sc);- if (!rt) return;- float W = rc.right / sc, H = rc.bottom / sc;- bool dark = ui::Dark();- // sem fundo, ou no Tahoe (o vidro da barra é tão leve que o papel de parede aparece quase inteiro):- // a cor do texto e dos ícones segue o papel de parede atrás- const bool bgOn0 = BarBackground();- if (!bgOn0 || liquid::On()) dark = WallpaperTopDark(dark);- const bool leo = liquid::Leopard();- // Leopard: Lucida Grande 14 px no Mac; no Windows, a Lucida Sans Unicode (o mesmo desenho de origem)- static IDWriteTextFormat* tfLeo = ui::FormatFace(L"Lucida Sans Unicode", 14, DWRITE_FONT_WEIGHT_NORMAL);- static IDWriteTextFormat* tfLeoB = ui::FormatFace(L"Lucida Sans Unicode", 14, DWRITE_FONT_WEIGHT_BOLD);- IDWriteTextFormat* tfN = leo ? tfLeo : g_tf;- IDWriteTextFormat* tfB = leo ? tfLeoB : g_tfBold;- if (leo) dark = false; // Leopard: a barra é sempre clara, com texto preto (o 10.5 não tinha modo escuro)- // Menubar Image do macOS 26 (guia, seção 31: catálogos Aqua/DarkAqua): branco 90 % no escuro, preto 85 % no claro- D2D1_COLOR_F fgc = dark ? D2D1::ColorF(1, 1, 1, liquid::On() ? 0.90f : 0.92f) : D2D1::ColorF(0, 0, 0, 0.85f);- // Liquid Glass sem fundo: só branco ou preto, mais firmes. Antes puxava a cor do papel de parede saturada 3×- // (a "vibrancy" do Mac) e em papel de parede azul o texto e os ícones ficavam ciano.- if (liquid::On() && !bgOn0) fgc = dark ? D2D1::ColorF(1, 1, 1, 0.96f) : D2D1::ColorF(0, 0, 0, 0.90f);- ID2D1SolidColorBrush* br = nullptr;- bool liquid = backdrop::Liquid(), bgOn = BarBackground();- D2D1_COLOR_F veil = dark ? D2D1::ColorF(0.06f, 0.06f, 0.07f, 0.18f) : D2D1::ColorF(1, 1, 1, 0.26f);- if (liquid) veil.a = backdrop::Current().tinted ? veil.a : veil.a * 0.35f;- if (!bgOn || leo) veil.a = 0; // sem fundo (Tahoe): só o papel de parede atrás; Leopard: o degradê do Render é o fundo todo- rt->CreateSolidColorBrush(veil, &br);- rt->FillRectangle(D2D1::RectF(0, 0, W, H), br); // tinta leve por cima do acrílico- if (leo) {- // Leopard: a barra de menus translúcida do 10.5 — branco leitoso que deixa o papel de parede passar um pouco,- // um tom mais cinza embaixo, o fio de luz no alto e a linha escura embaixo (a "sombra" da barra)- float px = 1 / sc;- // medido numa captura do 10.5 a 1x: 248 no alto -> 204 embaixo, a linha de baixo quase preta- // Aparência > "Barra de menus translúcida" desligada (o 10.5.2 trouxe a opção): opaca- const float op = shell::Setting(L"barra_translucida", L"1") == L"1" ? 1.f : 1.12f;- // translúcida: ~72 % de branco (o papel de parede passa nítido, como nas capturas do 10.5); opaca: cheia- const float a0 = op > 1 ? 1.f : 0.74f, a1 = op > 1 ? 1.f : 0.70f;- D2D1_GRADIENT_STOP st[2] = { { 0, D2D1::ColorF(248 / 255.f, 248 / 255.f, 248 / 255.f, a0) }, { 1, D2D1::ColorF(214 / 255.f, 214 / 255.f, 214 / 255.f, a1) } };- ID2D1GradientStopCollection* gs = nullptr; ID2D1LinearGradientBrush* lb = nullptr;- if (SUCCEEDED(rt->CreateGradientStopCollection(st, 2, &gs)) &&- SUCCEEDED(rt->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, 0 }, { 0, H }), gs, &lb)))- rt->FillRectangle(D2D1::RectF(0, 0, W, H), lb);- if (lb) lb->Release();- if (gs) gs->Release();- br->SetColor(D2D1::ColorF(1, 1, 1, 0.75f));- rt->FillRectangle(D2D1::RectF(0, 0, W, px), br);- br->SetColor(D2D1::ColorF(0, 0, 0, 0.62f));- rt->FillRectangle(D2D1::RectF(0, H - px, W, H), br);- }- if (liquid && bgOn) { // Liquid Glass: sem degradê branco; só um fio fraco embaixo, como no Tahoe- float px = 1 / sc;- br->SetColor(D2D1::ColorF(1, 1, 1, dark ? 0.08f : 0.18f));- rt->FillRectangle(D2D1::RectF(0, H - px, W, H), br);- }- g_hits.clear();- // Embaixo, o meio da linha é do Dock: o que é da esquerda acaba em limE e o da direita começa em limD- float limE = W, limD = 0;- if (g_vaoD > g_vaoE && bar == g_bar) { limE = g_vaoE / sc - 6; limD = g_vaoD / sc + 6; }- bool litNow = false; // Leopard: o item aceso fica com o texto branco sobre o azul- auto highlight = [&](D2D1_RECT_F r) {- if (leo) { // Leopard: o destaque azul do Aqua de ponta a ponta na altura da barra, sem cantos- litNow = true;- D2D1_GRADIENT_STOP st[2] = { { 0, D2D1::ColorF(0.39f, 0.56f, 0.95f, 1) }, { 1, D2D1::ColorF(0.13f, 0.35f, 0.86f, 1) } };- ID2D1GradientStopCollection* gs = nullptr; ID2D1LinearGradientBrush* lb = nullptr;- if (SUCCEEDED(rt->CreateGradientStopCollection(st, 2, &gs)) &&- SUCCEEDED(rt->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, 0 }, { 0, H }), gs, &lb)))- rt->FillRectangle(D2D1::RectF(r.left, 0, r.right, H - 1 / sc), lb);- if (lb) lb->Release();- if (gs) gs->Release();- return;- }- if (liquid::On()) { // Tahoe (vídeo do macOS 26): o item aberto ganha uma cápsula de vidro clara- br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.24f) : D2D1::ColorF(1, 1, 1, 0.55f));- float rad = (H - 4) / 2;- rt->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(r.left + 1, 2, r.right - 1, H - 2), rad, rad), br);- br->SetColor(D2D1::ColorF(1, 1, 1, dark ? 0.18f : 0.45f)); // o fio de luz da borda- rt->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(r.left + 1.5f, 2.5f, r.right - 1.5f, H - 2.5f), rad - 0.5f, rad - 0.5f), br, 0.8f);- return;- }- br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.20f) : D2D1::ColorF(0, 0, 0, 0.10f));- rt->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(r.left, 2, r.right, H - 2), 4, 4), br);- };- auto add = [&](D2D1_RECT_F r, Kind k, int i) {- litNow = false;- g_hits.push_back({ r, k, i });- bool lit = (k == K_SOUND && (som::IsOpen() || som::HudLit())) // menu Som aberto / aviso de volume do Tahoe- || (k == K_CC && central::IsOpen()) || (k == K_CLOCK && (notificacoes::IsOpen() || (liquid::On() && notificacoes::BannerVisible()))) || (k == K_SPOT && spotlight::IsOpen());- if (lit || ((int)g_hits.size() - 1 == g_open && bar == g_openBar)) highlight(r);- };-- // esquerda (Tahoe, guia seção 35: o menu Apple fica em x 10, com 34 de largura)- float x = liquid::On() ? 10.f : 8.f;- add(D2D1::RectF(x, 0, x + 34, H), K_LOGO, 0);- br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);- if (leo && !litNow) {- // Leopard: a maçã grafite brilhante do 10.5 (a azul era a do Tiger): cinza claro em cima, quase preto embaixo;- // aberta, fica branca- D2D1_GRADIENT_STOP st[3] = { { 0, D2D1::ColorF(0.62f, 0.62f, 0.63f, 1) }, { 0.45f, D2D1::ColorF(0.36f, 0.36f, 0.37f, 1) }, { 1, D2D1::ColorF(0.16f, 0.16f, 0.17f, 1) } };- ID2D1GradientStopCollection* gs = nullptr; ID2D1LinearGradientBrush* lb = nullptr;- bool ok = SUCCEEDED(rt->CreateGradientStopCollection(st, 3, &gs)) &&- SUCCEEDED(rt->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, H / 2 - 7.5f }, { 0, H / 2 + 6.5f }), gs, &lb));- if (!ok || !simbolo::Draw(rt, L"apple.logo", D2D1::RectF(x + 10, H / 2 - 7.5f, x + 24, H / 2 + 6.5f), lb)) {- br->SetColor(D2D1::ColorF(0.30f, 0.30f, 0.31f, 1));- DrawLogo(rt, br, x + 17, H / 2);- }- if (lb) lb->Release();- if (gs) gs->Release();- } else- if (!simbolo::Draw(rt, L"apple.logo", D2D1::RectF(x + 10, H / 2 - 7.5f, x + 24, H / 2 + 6.5f), (br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc), br))) // a maçã do SF Symbols- DrawLogo(rt, br, x + 17, H / 2);- x += 34;- if (float w = ui::TextWidth(tfB, g_appName) + 20; x + w <= limE) {- add(D2D1::RectF(x, 0, x + w, H), K_APP, 0);- br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);- rt->DrawTextW(g_appName.c_str(), (UINT32)g_appName.size(), tfB, D2D1::RectF(x + 10, 0, x + w, H), br);- x += w;- }- float leftEnd = x;-- // direita (da borda para dentro), na ordem do Mac: relógio, Central de Controle, Spotlight, fonte de- // entrada, Wi-Fi, bateria, som, Bluetooth, ícones fixados dos apps e a setinha dos guardados.- // Cada item é o símbolo com 10 pt de cada lado (no Mac fica um a cada ~38 pt).- float r = W - 10;- auto slot = [&](float iconW, Kind k, int i) { // reserva o espaço e devolve a caixa do símbolo- float w = iconW + 2 * PAD;- if (r - w < limD) return D2D1::RectF(-1000, 0, -1000 + iconW, H); // o Dock ocupa o lugar: fica de fora (nem clique)- add(D2D1::RectF(r - w, 0, r, H), k, i);- D2D1_RECT_F box = D2D1::RectF(r - w + PAD, 0, r - PAD, H);- r -= w;- br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);- return box;- };- auto sym = [&](const wchar_t* name, D2D1_RECT_F box, float h) {- return simbolo::Draw(rt, name, D2D1::RectF(box.left, H / 2 - h / 2, box.right, H / 2 + h / 2), br);- };- // Leopard (captura do 10.5): a lupa do Spotlight é o último item, na ponta direita, e o relógio vem antes dela;- // (a Central de Controle continua, à esquerda do relógio: o usuário quer o acesso a ela)- if (leo && shell::Setting(L"barra_spotlight", L"1") == L"1") {- auto bx = slot(15, K_SPOT, 0);- if (!sym(L"magnifyingglass", bx, 15)) rt->DrawTextW(L"", 1, g_tfIcon, bx, br);- }- {- std::wstring t = ClockText();- float w = ui::TextWidth(tfN, t) + 2 * PAD;- if (r - w - (18 + 2 * PAD) < limD) { // embaixo com pouco espaço: só a hora, para a Central de Controle caber- SYSTEMTIME st; GetLocalTime(&st);- wchar_t hm[16]; swprintf_s(hm, L"%02d:%02d", st.wHour, st.wMinute);- t = hm; w = ui::TextWidth(tfN, t) + 2 * PAD;- }- add(D2D1::RectF(r - w, 0, r, H), K_CLOCK, 0);- br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);- rt->DrawTextW(t.c_str(), (UINT32)t.size(), tfN, D2D1::RectF(r - w + PAD, 0, r, H), br);- r -= w;- }- // microfone/câmera em uso (issue #8, todos os temas): como no macOS, uma bolinha de 6 pt no vão entre a Central de- // Controle e a data/hora: laranja = microfone, verde = câmera (a câmera ganha). barra_privacidade=0 tira.- if (shell::Setting(L"barra_privacidade", L"1") != L"0")- if (int pv = ilha::Privacidade()) {- br->SetColor(pv & 2 ? D2D1::ColorF(0.20f, 0.78f, 0.35f) : D2D1::ColorF(1.0f, 0.58f, 0.0f));- rt->FillEllipse(D2D1::Ellipse({ r, H / 2 }, 3, 3), br); // no meio do vão (os dois PAD): nada anda de lugar- }- { auto bx = slot(18, K_CC, 0); if (!sym(L"switch.2", bx, 14)) DrawCC(rt, br, (bx.left + bx.right) / 2, H / 2); }- if (!leo && shell::Setting(L"barra_spotlight", L"1") == L"1") {- auto bx = slot(15, K_SPOT, 0);- if (!sym(L"magnifyingglass", bx, 15)) rt->DrawTextW(L"", 1, g_tfIcon, bx, br);- }- if (shell::Setting(L"barra_teclado", L"1") == L"1") { // fonte de entrada: a sigla num quadradinho (como o "A" do ABC)- std::wstring t = InputBadge(g_st.hkl);- float tw = std::max(15.f, ui::TextWidth(g_tfBadge, t) + 7);- auto bx = slot(tw, K_INPUT, 0);- D2D1_RECT_F k = D2D1::RectF(bx.left, H / 2 - 7.5f, bx.right, H / 2 + 7.5f);- rt->FillRoundedRectangle(D2D1::RoundedRect(k, 3.5f, 3.5f), br);- br->SetColor(dark ? D2D1::ColorF(0.13f, 0.13f, 0.14f) : D2D1::ColorF(0.96f, 0.96f, 0.96f));- rt->DrawTextW(t.c_str(), (UINT32)t.size(), g_tfBadge, D2D1::RectF(k.left, k.top - 0.5f, k.right, k.bottom - 0.5f), br);- }- // como no Mac: só quem tem Wi-Fi; no cabo, o Wi-Fi desconectado não aparece- if (g_st.wlan && (g_st.wifiOn || !g_st.wired) && shell::Setting(L"barra_wifi", L"1") == L"1") {- auto bx = slot(18, K_NET, 0);- if (!sym(g_st.wifiOn ? L"wifi" : L"wifi.slash", bx, 14)) rt->DrawTextW(L"", 1, g_tfIcon, bx, br);- }- if (g_st.batt && shell::Setting(L"barra_bateria", L"1") == L"1") {- const wchar_t* name = g_st.charging ? L"battery.100percent.bolt" : g_st.pct > 87 ? L"battery.100percent" : g_st.pct > 62 ? L"battery.75percent"- : g_st.pct > 37 ? L"battery.50percent" : g_st.pct > 12 ? L"battery.25percent" : L"battery.0percent";- if (liquid::Golden()) {- // macOS 27 (vídeo do MacVince, 2:44): a porcentagem DENTRO do ícone — corpo cheio de 25 × 12 com canto 4,- // o número vazado (e o raio quando carrega) e a ponta à direita- auto bx = slot(29, K_BATT, 0);- float cy = H / 2;- D2D1_RECT_F body = D2D1::RectF(bx.left, cy - 6, bx.left + 25, cy + 6);- rt->FillRoundedRectangle(D2D1::RoundedRect(body, 4, 4), br);- rt->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(body.right + 1, cy - 2.5f, body.right + 2.8f, cy + 2.5f), 1, 1), br);- static IDWriteTextFormat* tfB = ui::Format(9.5f, DWRITE_FONT_WEIGHT_BOLD, false, DWRITE_TEXT_ALIGNMENT_CENTER);- wchar_t num[8]; swprintf_s(num, L"%d", std::clamp(g_st.pct, 0, 100));- br->SetColor(dark ? D2D1::ColorF(0.15f, 0.13f, 0.12f, 0.92f) : D2D1::ColorF(1, 1, 1, 0.95f));- D2D1_RECT_F tr = D2D1::RectF(body.left, body.top - 0.5f, body.right - (g_st.charging ? 6.f : 0.f), body.bottom - 0.5f);- if (tfB) { tfB->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER); rt->DrawTextW(num, (UINT32)wcslen(num), tfB, tr, br); }- if (g_st.charging) { // raio- float bx0 = body.right - 6.5f;- ID2D1PathGeometry* g = nullptr;- if (SUCCEEDED(ui::d2d->CreatePathGeometry(&g))) {- ID2D1GeometrySink* sk = nullptr; g->Open(&sk);- sk->BeginFigure({ bx0 + 2.6f, cy - 4.5f }, D2D1_FIGURE_BEGIN_FILLED);- D2D1_POINT_2F pts[] = { { bx0, cy + 0.6f }, { bx0 + 1.9f, cy + 0.6f }, { bx0 + 1.1f, cy + 4.5f }, { bx0 + 3.8f, cy - 0.8f }, { bx0 + 1.9f, cy - 0.8f } };- sk->AddLines(pts, 5); sk->EndFigure(D2D1_FIGURE_END_CLOSED); sk->Close(); sk->Release();- rt->FillGeometry(g, br);- g->Release();- }- }- br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);- } else {- auto bx = slot(27, K_BATT, 0);- sym(name, bx, 13);- }- }- // Som e Bluetooth: no Mac ficam fora da barra por padrão (Ajustes > Central de Controle liga)- if (g_st.sound && shell::Setting(L"barra_som", L"0") == L"1") {- const wchar_t* name = g_st.muted ? L"speaker.slash.fill" : g_st.phones ? L"headphones" : g_st.vol < 0.01f ? L"speaker.fill"- : g_st.vol < 0.34f ? L"speaker.wave.1.fill" : g_st.vol < 0.67f ? L"speaker.wave.2.fill" : L"speaker.wave.3.fill";- auto bx = slot(g_st.phones ? 16 : 21, K_SOUND, 0);- sym(name, bx, g_st.phones ? 16 : 14);- }- if (g_st.bt && shell::Setting(L"barra_bluetooth", L"0") == L"1") { // o símbolo do Bluetooth do Mac (não está no SF Symbols público)- auto bx = slot(9, K_BT, 0);- float cx = (bx.left + bx.right) / 2, cy = H / 2, hh = 7.2f, ww = 3.9f;- ID2D1PathGeometry* g = nullptr;- if (SUCCEEDED(ui::d2d->CreatePathGeometry(&g))) {- ID2D1GeometrySink* sk = nullptr; g->Open(&sk);- sk->BeginFigure({ cx - ww, cy - hh * 0.48f }, D2D1_FIGURE_BEGIN_HOLLOW);- D2D1_POINT_2F pts[] = { { cx + ww, cy + hh * 0.48f }, { cx, cy + hh }, { cx, cy - hh }, { cx + ww, cy - hh * 0.48f }, { cx - ww, cy + hh * 0.48f } };- sk->AddLines(pts, 5); sk->EndFigure(D2D1_FIGURE_END_OPEN); sk->Close(); sk->Release();- ID2D1StrokeStyle* st = nullptr;- ui::d2d->CreateStrokeStyle(D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_ROUND), nullptr, 0, &st);- rt->DrawGeometry(g, br, 1.5f, st);- if (st) st->Release();- g->Release();- }- }- UINT px = (UINT)std::lround(17 * sc);- for (int i = (int)tray::icons.size() - 1; i >= 0; i--) {- auto& t = tray::icons[i];- if (t.hidden || !t.icon || !IsShown(t) || tray::IsPrivacy(t)) continue; // o do Windows: vira a bolinha- if (r - 37 < (limD > 0 ? limD + 34 : leftEnd + 60)) { g_overflow = true; break; } // sem espaço: some, como no Mac (macOS 27: aparece a »)- auto bx = slot(17, K_TRAY, i);- std::vector<BYTE> mono = IconPixels(t.icon, px);- // como os ícones-modelo do Mac: uma cor só, a mesma do texto da barra (branco no escuro, preto no claro);- // o desenho de dentro (ícone de fundo cheio: Discord, WhatsApp) sai pela transparência, nunca por cinza- // ou pela cor do original, que deixava o ícone azulado/acinzentado em cima do papel de parede.- float lmin = 1, lmax = 0;- for (size_t k = 0; k < mono.size(); k += 4) {- float a = mono[k + 3] / 255.f;- if (a < 0.5f) continue;- float l = std::clamp((0.2126f * mono[k + 2] + 0.7152f * mono[k + 1] + 0.0722f * mono[k]) / 255.f / a, 0.f, 1.f);- lmin = std::min(lmin, l); lmax = std::max(lmax, l);- }- bool detail = lmax - lmin > 0.25f; // tem desenho de dentro (senão é só a silhueta)- BYTE ink = dark ? 255 : 0;- for (size_t k = 0; k < mono.size(); k += 4) {- float a = mono[k + 3] / 255.f;- if (a <= 0.004f) { mono[k] = mono[k + 1] = mono[k + 2] = mono[k + 3] = 0; continue; }- float oa = a;- if (detail) {- float l = std::clamp((0.2126f * mono[k + 2] + 0.7152f * mono[k + 1] + 0.0722f * mono[k]) / 255.f / a, 0.f, 1.f);- float t = std::clamp((l - lmin) / (lmax - lmin), 0.f, 1.f); // 0 = parte mais escura do original- oa = a * (dark ? 0.30f + 0.70f * t : 1.f - 0.70f * t);- }- oa *= dark ? 0.96f : 0.88f;- BYTE c = (BYTE)std::lround(ink * oa);- mono[k] = mono[k + 1] = mono[k + 2] = c;- mono[k + 3] = (BYTE)std::lround(oa * 255);- }- if (ID2D1Bitmap* bmp = ui::Bitmap(rt, px, px, mono)) {- // no pixel inteiro (1:1 com o bitmap): fora da grade o bitmap era reamostrado e borrava/serrilhava- float cxp = (bx.left + bx.right) / 2 * sc, cyp = H / 2 * sc;- float l0 = std::round(cxp - px / 2.f) / sc, t0 = std::round(cyp - px / 2.f) / sc;- rt->DrawBitmap(bmp, D2D1::RectF(l0, t0, l0 + px / sc, t0 + px / sc), 1, D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR);- bmp->Release();- }- }- bool anyHidden = false;- for (auto& t : tray::icons) if (!t.hidden && t.icon && !IsShown(t) && !tray::IsPrivacy(t)) anyHidden = true;- if (liquid::Golden() && (g_overflow || anyHidden)) {- // macOS 27 (vídeo, 2:16): quando os ícones não cabem, uma seta dupla » mostra os escondidos- auto bx = slot(14, K_MORE, 0);- float cx = (bx.left + bx.right) / 2, cy = H / 2;- for (int k = 0; k < 2; k++) {- float ox = cx - 3.5f + k * 5.5f;- rt->DrawLine({ ox - 2.2f, cy - 4.5f }, { ox + 2.2f, cy }, br, 1.5f);- rt->DrawLine({ ox + 2.2f, cy }, { ox - 2.2f, cy + 4.5f }, br, 1.5f);- }- anyHidden = false; // já desenhada- }- g_overflow = false;- // setinha dos ícones guardados: não existe no Mac, desligada por padrão (barra_seta=1 liga); a lista abre- // também no botão direito da Central de Controle- if (anyHidden && shell::Setting(L"barra_seta", L"0") == L"1") { // setinha dos ícones guardados: o chevron do SF Symbols, apontando para onde eles abrem- auto bx = slot(8, K_MORE, 0);- if (!sym(L"chevron.left", bx, 12)) {- float cx = (bx.left + bx.right) / 2, cy = H / 2;- rt->DrawLine({ cx + 2, cy - 5 }, { cx - 2.5f, cy }, br, 1.6f);- rt->DrawLine({ cx - 2.5f, cy }, { cx + 2, cy + 5 }, br, 1.6f);- }- }-- // menus do app (entre o nome e os ícones)- for (int i = 0; i < (int)g_titles.size(); i++) {- float w = ui::TextWidth(tfN, g_titles[i]) + 20;- if (x + w > std::min(r - 8, limE)) break;- add(D2D1::RectF(x, 0, x + w, H), K_MENU, i);- br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);- rt->DrawTextW(g_titles[i].c_str(), (UINT32)g_titles[i].size(), tfN, D2D1::RectF(x + 10, 0, x + w, H), br);- x += w;- }- br->Release();- ui::End(g_s, false);-}--// ---- menus-// Menus próprios, como os do app no Mac, para os apps sem menu Win32 (os itens mandam o atalho do Windows do-// app). Ids: atalhos de g_keyCmds; 0 = separador. No "Janela" os itens vêm antes da lista de janelas.-struct MenuDef { const wchar_t* title; std::vector<int> ids; };-const std::vector<MenuDef>* AppMenus(App* app) {- static const std::vector<MenuDef> browser = {- { L"Arquivo", { 1020, 1001, 5001, 5002, 0, 5003, 5004, 0, 5005, 5006, 5007, 0, 1005 } },- { L"Editar", { 1010, 5070, 0, 1012, 1013, 1014, 1015, 0, 1016 } },- { L"Visualizar", { 5010, 0, 5011, 5012, 5013, 0, 5014, 5015, 5016, 5017, 0, 5018, 5019 } },- { L"Histórico", { 5020, 1040, 1041, 0, 5021, 5022 } },- { L"Favoritos", { 5030, 0, 5031, 5032 } },- { L"Aba", { 5040, 5041 } },- { L"Janela", { 5050, 5051 } },- { L"Ajuda", { 5060 } },- };- static const std::vector<MenuDef> discord = {- { L"Editar", { 1010, 5070, 0, 1012, 1013, 1014, 1015 } },- { L"Visualizar", { 5071, 5072, 0, 5015, 5016, 5017 } },- { L"Janela", {} },- { L"Ajuda", { 5073 } },- };- static const std::vector<MenuDef> whatsapp = {- { L"Arquivo", { 5080, 5081, 0, 1003 } },- { L"Editar", { 1010, 1011, 0, 1012, 1013, 1014, 1015, 0, 1016 } },- { L"Visualizar", { 5015, 5016, 5017 } },- { L"Janela", {} },- { L"Ajuda", {} },- };- static const std::vector<MenuDef> electron = { // Claude e afins: editar e zoom (o padrão do Electron)- { L"Arquivo", { 1001, 0, 1003 } },- { L"Editar", { 1010, 5070, 0, 1012, 1013, 1014, 1015 } },- { L"Visualizar", { 5071, 0, 5015, 5016, 5017 } },- { L"Janela", {} },- { L"Ajuda", {} },- };- // o programa da janela ativa (o App do Chrome casa pelo AUMID e pode vir sem o .exe)- static HWND s_fg; static std::wstring s_path; // a barra pergunta a cada atualização: lido uma vez por janela- std::wstring path = app ? app->exe : L"";- DWORD pid = 0;- if (g_fg && g_fg == s_fg) { if (!s_path.empty()) path = s_path; }- else if (g_fg && GetWindowThreadProcessId(g_fg, &pid) && pid) {- s_fg = g_fg; s_path.clear();- if (HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid)) {- wchar_t buf[MAX_PATH]; DWORD n = MAX_PATH;- if (QueryFullProcessImageNameW(p, 0, buf, &n)) path = s_path = buf;- CloseHandle(p);- }- }- if (path.empty()) return nullptr;- std::wstring n = path.substr(path.find_last_of(L"\\/") + 1);- for (auto& c : n) c = towlower(c);- if (n == L"chrome.exe" || n == L"msedge.exe" || n == L"brave.exe" || n == L"vivaldi.exe") return &browser;- if (n == L"discord.exe" || n == L"discordptb.exe" || n == L"discordcanary.exe") return &discord;- if (n.find(L"whatsapp") != std::wstring::npos) return &whatsapp;- if (n == L"claude.exe") return &electron;- static const std::vector<MenuDef> spotify = {- { L"Arquivo", { 5100, 0, 1003 } },- { L"Editar", { 1010, 1011, 0, 1012, 1013, 1014, 1015, 0, 5108 } },- { L"Visualizar", { 5015, 5016, 5017 } },- { L"Reprodução", { 5101, 5102, 5103, 0, 5104, 5105, 0, 5106, 5107 } },- { L"Janela", {} },- { L"Ajuda", {} },- };- static const std::vector<MenuDef> vscode = {- { L"Arquivo", { 5120, 5121, 0, 1002, 0, 1004, 5122, 0, 5123 } },- { L"Editar", { 1010, 1011, 0, 1012, 1013, 1014, 0, 1016, 5124, 0, 5125 } },- { L"Seleção", { 1015 } },- { L"Visualizar", { 5126, 0, 5127, 5125, 5128, 5129, 0, 5134, 0, 5016, 5017, 5015 } },- { L"Ir", { 5130, 5131 } },- { L"Executar", { 5132, 5133 } },- { L"Janela", {} },- { L"Ajuda", {} },- };- if (n == L"spotify.exe") return &spotify;- if (n == L"code.exe" || n == L"cursor.exe" || n == L"code - insiders.exe") return &vscode;- return nullptr;-}--std::vector<std::wstring> GenericTitles(App* app) {- if (!g_finderActive)- if (auto* defs = AppMenus(app)) {- std::vector<std::wstring> t;- for (auto& d : *defs) t.push_back(Tr(d.title));- return t;- }- if (g_finderActive) return { Tr(L"Arquivo"), Tr(L"Editar"), Tr(L"Visualizar"), Tr(L"Ir"), Tr(L"Janela"), Tr(L"Ajuda") };- return { Tr(L"Arquivo"), Tr(L"Editar"), Tr(L"Janela"), Tr(L"Ajuda") };-}--std::vector<ctxmenu::Item> GenericMenu(const std::wstring& title, App* app) {- std::vector<ctxmenu::Item> pre; // Janela: itens do app antes dos comuns (minimizar, zoom, lista de janelas)- if (auto* defs = g_finderActive ? nullptr : AppMenus(app))- for (auto& d : *defs) {- if (title != Tr(d.title)) continue;- std::vector<ctxmenu::Item> v;- for (int id : d.ids) v.push_back(id ? K(id) : Sep());- if (title != Tr(L"Janela")) {- if (v.empty()) v.push_back(I(Tr(L"Nenhum item"), 0, true));- return v;- }- if (!v.empty()) { pre = v; pre.push_back(Sep()); }- break;- }- if (title == Tr(L"Arquivo")) {- if (g_finderActive) return { K(1001), K(1020), K(1021), Sep(), K(1002), K(1003), Sep(), K(1022), Sep(), K(1023) };- return { K(1001), K(1002), Sep(), K(1003), K(1004), Sep(), K(1005) };- }- if (title == Tr(L"Editar")) return { K(1010), K(1011), Sep(), K(1012), K(1013), K(1014), K(1015), Sep(), K(1016) };- if (title == Tr(L"Visualizar")) return { K(1030), K(1031), K(1032), K(1033), Sep(), K(1034) };- if (title == Tr(L"Ir")) return { K(1040), K(1041), K(1042), Sep(), K(1043), Sep(), I(Tr(L"Recentes"), 1100), I(Tr(L"Documentos"), 1101), I(Tr(L"Mesa"), 1102), I(Tr(L"Downloads"), 1103), I(Tr(L"Início"), 1104), I(Tr(L"Este Computador"), 1105), I(Tr(L"Aplicativos"), 1106) };- if (title == Tr(L"Janela")) {- std::vector<ctxmenu::Item> v{ I(Tr(L"Minimizar"), 1200), I(Tr(L"Zoom"), 1201), Sep(), I(Tr(L"Trazer Tudo para a Frente"), 1202) };- v.insert(v.begin(), pre.begin(), pre.end());- if (app && !app->wins.empty()) {- v.push_back(Sep());- for (int k = 0; k < (int)app->wins.size() && k < 20; k++) {- auto it = I(app->wins[k].title, 3000 + k);- it.checked = app->wins[k].hwnd == g_fg;- v.push_back(it);- }- }- return v;- }- if (title == Tr(L"Ajuda")) return { K(1050) };- return {};-}--std::vector<ctxmenu::Item> LogoMenu() {- std::vector<ctxmenu::Item> recent;- { // Itens Recentes: os atalhos mais novos de shell:Recent- PWSTR p = nullptr;- if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Recent, 0, nullptr, &p))) {- std::wstring dir = p; CoTaskMemFree(p);- std::vector<std::pair<ULONGLONG, std::wstring>> files;- WIN32_FIND_DATAW fd;- HANDLE h = FindFirstFileW((dir + L"\\*.lnk").c_str(), &fd);- if (h != INVALID_HANDLE_VALUE) {- do files.push_back({ ((ULONGLONG)fd.ftLastWriteTime.dwHighDateTime << 32) | fd.ftLastWriteTime.dwLowDateTime, dir + L"\\" + fd.cFileName });- while (FindNextFileW(h, &fd));- FindClose(h);- }- std::sort(files.begin(), files.end(), [](auto& a, auto& b) { return a.first > b.first; });- static std::vector<std::wstring> s_recent;- s_recent.clear();- for (size_t k = 0; k < files.size() && k < 10; k++) {- std::wstring n = files[k].second.substr(files[k].second.find_last_of(L'\\') + 1);- n.resize(n.size() - 4);- s_recent.push_back(files[k].second);- recent.push_back(I(n, 4000 + (int)k));- }- if (recent.empty()) recent.push_back(I(Tr(L"Nenhum item"), 0, true));- }- }- wchar_t user[128] = L""; DWORD n = 128; GetUserNameW(user, &n);- ctxmenu::Item rec = I(Tr(L"Itens Recentes"), 0); rec.sub = recent;- return { I(Tr(L"Sobre Este Mac"), 100), Sep(), I(Tr(L"Ajustes do Sistema…"), 101), I(Tr(L"Microsoft Store…"), 102), Sep(),- rec, Sep(), I(Tr(L"Forçar Encerrar…"), 103), Sep(), I(Tr(L"Repousar"), 104), I(Tr(L"Reiniciar…"), 105), I(Tr(L"Desligar…"), 106), Sep(),- I(Tr(L"Bloquear Tela"), 107), I(Tr(L"Encerrar Sessão de ") + std::wstring(user) + L"…", 108), Sep(), I(Tr(L"Sair do Shell (voltar à barra do Windows)"), 109) };-}--std::vector<ctxmenu::Item> AppMenu(App* a) {- std::wstring n = a ? a->name : g_appName;- return { I(Tr(L"Sobre ") + n, 200), Sep(), K(1051), Sep(), I(Tr(L"Ocultar ") + n, 201), I(Tr(L"Ocultar Outros"), 202), I(Tr(L"Mostrar Tudo"), 203), Sep(), I(Tr(L"Encerrar ") + n, 204) };-}---void Shutdown(UINT how) {- HANDLE tok;- if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &tok)) {- TOKEN_PRIVILEGES tp{ 1 };- LookupPrivilegeValueW(nullptr, SE_SHUTDOWN_NAME, &tp.Privileges[0].Luid);- tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;- AdjustTokenPrivileges(tok, FALSE, &tp, 0, nullptr, nullptr);- CloseHandle(tok);- }- ExitWindowsEx(how, SHTDN_REASON_FLAG_PLANNED);-}--void Open(const wchar_t* what, const wchar_t* args = nullptr) {- if (!wcsncmp(what, L"ms-settings:", 12)) { shell::OpenSettings(what); return; } // o nosso Ajustes do Sistema- shell::Abrir(L"open", what, args, nullptr, SW_SHOWNORMAL);-}--void OpenFinder(const std::wstring& args) {- if (shell::nativo) { shell::AbrirFinder(args); return; }- for (auto& a : apps::list) if (a.finder) { shell::Abrir(L"open", a.launch.c_str(), args.c_str(), nullptr, SW_SHOWNORMAL); return; }-}--void Run(int id, App* app) {- for (auto& k : g_keyCmds) if (k.id == id) { // atalho de teclado para o app ativo- if (g_fg) SetForegroundWindow(g_fg);- Sleep(30);- SendKeys(k.keys);- return;- }- if (id >= 1000 && id < 1100) return;- switch (id) {- case 100: sobre::Show(); break;- case 101: shell::OpenSettings(L""); break;- case 102: Open(L"ms-windows-store:"); break;- case 103: shell::OpenForceQuit(false); break;- case 104: SetSuspendState(FALSE, FALSE, FALSE); break;- // como no Mac: alerta com o ícone do computador, Cancelar | Reiniciar/Desligar (antes era a caixa do Windows). O ícone é- // o mesmo do Sobre Este Mac: o computador em alumínio (modo "este PC", o padrão) ou o Mac Studio- case 105: alertas::Confirm(Tr(L"Tem certeza de que deseja reiniciar o computador agora?"), L"", Tr(L"Reiniciar"), [] { Shutdown(EWX_REBOOT); }, IconePC()); break;- case 106: alertas::Confirm(Tr(L"Tem certeza de que deseja desligar o computador agora?"), L"", Tr(L"Desligar"), [] { Shutdown(EWX_POWEROFF); }, IconePC()); break;- case 107: bloqueio::Lock(); break; // a nossa tela de bloqueio (o LockWorkStation fica desligado pela política enquanto o Shell roda: não fazia nada, issue #8)- case 108: alertas::Confirm(Tr(L"Tem certeza de que deseja encerrar todos os aplicativos e sair agora?"), L"", Tr(L"Encerrar Sessão"), [] { ExitWindowsEx(EWX_LOGOFF, 0); }, IconePC()); break;- case 109: shell::Quit(L"menu do logo"); break;- case 200: if (app && !app->exe.empty()) shell::Abrir(L"properties", app->exe.c_str(), nullptr, nullptr, SW_SHOWNORMAL); break;- case 201: if (app) apps::Hide(*app); break;- case 202: for (auto& a : apps::list) if (&a != app) apps::Hide(a); break;- case 203: for (auto& a : apps::list) for (auto& w : a.wins) if (w.minimized) ShowWindow(w.hwnd, SW_SHOWNOACTIVATE); break;- case 204: if (app) apps::Quit(*app); break;- case 1100: OpenFinder(L"shell:Recent"); break;- case 1101: OpenFinder(L"shell:Personal"); break;- case 1102: OpenFinder(L"shell:Desktop"); break;- case 1103: OpenFinder(L"shell:Downloads"); break;- case 1104: OpenFinder(L"shell:Profile"); break;- case 1105: OpenFinder(L"shell:MyComputerFolder"); break;- case 1106: OpenFinder(L"shell:Common Programs"); break;- case 1200: if (g_fg) ShowWindow(g_fg, SW_MINIMIZE); break;- case 1201: if (g_fg) ShowWindow(g_fg, IsZoomed(g_fg) ? SW_RESTORE : SW_MAXIMIZE); break;- case 1202: if (app) apps::Activate(*app); break;- }- if (id >= 3000 && id < 3100 && app && id - 3000 < (int)app->wins.size()) {- HWND w = app->wins[id - 3000].hwnd;- if (IsIconic(w)) shell::Restaurar(w);- SetForegroundWindow(w);- }-}--int g_closedHit = -1; DWORD g_closedHitAt; // o título cujo menu acabou de fechar (clicar nele de novo só fecha)-void ShowAt(int hit, const std::vector<ctxmenu::Item>& items, std::function<void(int)> done) {- g_open = hit;- g_openBar = Cur();- Render();- float sc = ui::Scale(Cur());- RECT wr; GetWindowRect(Cur(), &wr);- POINT pt{ wr.left + (LONG)std::lround(g_hits[hit].r.left * sc), wr.bottom };- // Tahoe (guia, seção 35): o menu abre 1 pt abaixo da barra e 4 pt à esquerda do título (o texto fica a 10 da caixa)- if (liquid::On()) pt = { wr.left + (LONG)std::lround((g_hits[hit].r.left + 6) * sc), wr.bottom + (LONG)std::lround(sc) };- if (Cur() == g_bar && menubar::Embaixo()) { // na linha do Dock os menus sobem, centrados no item- pt = { wr.left + (LONG)std::lround((g_hits[hit].r.left + g_hits[hit].r.right) / 2 * sc), wr.top - (LONG)std::lround(4 * sc) };- ctxmenu::AboveNext();- }- SetForegroundWindow(g_owner); // o menu fecha se a janela dona não estiver na frente- int id = ctxmenu::ShowItems(g_owner, pt, items);- g_closedHit = hit; g_closedHitAt = GetTickCount();- g_open = -1;- Render();- if (g_fg && IsWindow(g_fg)) SetForegroundWindow(g_fg);- if (id) done(id);-}--void Click(D2D1_POINT_2F p, bool right) {- int hit = -1;- for (int i = 0; i < (int)g_hits.size(); i++)- if (p.x >= g_hits[i].r.left && p.x < g_hits[i].r.right) { hit = i; break; }- if (hit < 0) return;- if (!right && hit == g_closedHit && GetTickCount() - g_closedHitAt < 400) { g_closedHit = -1; return; } // clique no mesmo título: só fechou- g_closedHit = -1;- Hit h = g_hits[hit];- App* app = ActiveApp();- float sc = ui::Scale(Cur());- RECT wr; GetWindowRect(Cur(), &wr);- POINT spt{ wr.left + (LONG)std::lround((h.r.left + h.r.right) / 2 * sc), wr.bottom };- switch (h.kind) {- case K_LOGO: ShowAt(hit, LogoMenu(), [&](int id) {- if (id >= 4000 && id < 4010) { // item recente- PWSTR p = nullptr; SHGetKnownFolderPath(FOLDERID_Recent, 0, nullptr, &p);- std::wstring dir = p; CoTaskMemFree(p);- std::vector<std::pair<ULONGLONG, std::wstring>> files;- WIN32_FIND_DATAW fd; HANDLE fh = FindFirstFileW((dir + L"\\*.lnk").c_str(), &fd);- if (fh != INVALID_HANDLE_VALUE) { do files.push_back({ ((ULONGLONG)fd.ftLastWriteTime.dwHighDateTime << 32) | fd.ftLastWriteTime.dwLowDateTime, dir + L"\\" + fd.cFileName }); while (FindNextFileW(fh, &fd)); FindClose(fh); }- std::sort(files.begin(), files.end(), [](auto& a, auto& b) { return a.first > b.first; });- if (id - 4000 < (int)files.size()) Open(files[id - 4000].second.c_str());- } else Run(id, app);- }); break;- case K_APP: ShowAt(hit, AppMenu(app), [&](int id) { Run(id, app); }); break;- case K_MENU:- if (g_hmenu && IsMenu(g_hmenu)) {- HMENU sub = GetSubMenu(g_hmenu, h.index);- if (!sub) break;- SendMessageTimeoutW(g_fg, WM_INITMENU, (WPARAM)g_hmenu, 0, SMTO_ABORTIFHUNG, 200, nullptr);- SendMessageTimeoutW(g_fg, WM_INITMENUPOPUP, (WPARAM)sub, h.index, SMTO_ABORTIFHUNG, 200, nullptr);- HWND target = g_fg;- ShowAt(hit, FromHmenu(sub, 0), [&](int id) { PostMessageW(target, WM_COMMAND, MAKEWPARAM(id, 0), 0); });- } else ShowAt(hit, GenericMenu(g_titles[h.index], app), [&](int id) { Run(id, app); });- break;- case K_TRAY: tray::Click(h.index, right ? WM_RBUTTONUP : WM_LBUTTONUP, spt); break;- case K_CC:- if (!right) { central::Toggle(); break; }- [[fallthrough]]; // botão direito: a lista dos ícones guardados (a setinha fica desligada, como no Mac)- case K_MORE: { // lista dos ícones guardados: abrir, menu do app, mostrar na barra- std::vector<ctxmenu::Item> items;- std::vector<int> idx;- for (int i = 0; i < (int)tray::icons.size(); i++) {- auto& t = tray::icons[i];- if (t.hidden || !t.icon || tray::IsPrivacy(t)) continue;- std::wstring name = TrayKey(t);- if (name.empty()) name = Tr(L"(sem nome)");- ctxmenu::Item it = I(name, 0);- { // o ícone do app na linha; os de uma cor só (brancos ou pretos) saem na cor do texto do menu- it.img = 32;- it.imgPx = IconPixels(t.icon, it.img);- auto& p = it.imgPx;- bool branco = true, preto = true;- for (size_t k = 0; k + 3 < p.size(); k += 4) {- if (p[k + 3] < 128) continue;- for (int c = 0; c < 3; c++) { branco &= p[k + c] >= p[k + 3] * 0.85f; preto &= p[k + c] <= p[k + 3] * 0.15f; }- }- if (branco || preto) {- const bool claro = ui::Dark() && !liquid::Leopard();- for (size_t k = 0; k + 3 < p.size(); k += 4) p[k] = p[k + 1] = p[k + 2] = claro ? p[k + 3] : 0;- }- }- it.sub = { I(Tr(L"Abrir"), 1000 + i * 4), I(Tr(L"Menu do App"), 1001 + i * 4), Sep(), I(Tr(L"Mostrar na barra de menus"), 1002 + i * 4, false, IsShown(t)) };- items.push_back(it);- }- ShowAt(hit, items, [&](int id) {- int i = (id - 1000) / 4, op = (id - 1000) % 4;- if (i < 0 || i >= (int)tray::icons.size()) return;- if (op == 2) { SetShown(tray::icons[i], !IsShown(tray::icons[i])); return; }- tray::Click(i, op == 1 ? WM_RBUTTONUP : WM_LBUTTONUP, spt);- });- break;- }- case K_SPOT: spotlight::Toggle(); break;- case K_NET: {- std::wstring ssid = g_st.ssid.empty() ? Tr(L"Conectado") : g_st.ssid; // sem a permissão de localização o nome não vem- bool wifi = g_st.wifiOn;- ShowAt(hit, { I(wifi ? L"Wi-Fi: " + ssid : L"Ethernet", 0, true), Sep(), I(Tr(L"Ajustes de Rede…"), 1) }, [](int) { Open(L"ms-settings:network"); });- break;- }- case K_SOUND: { // menu "Som" do Mac (som.cpp): volume, saídas e Ajustes de Som- RECT ir{ wr.left + (LONG)std::lround(h.r.left * sc), wr.top, wr.left + (LONG)std::lround(h.r.right * sc), wr.bottom };- som::Toggle(ir);- break;- }- case K_BT: ShowAt(hit, { I(Tr(L"Bluetooth"), 0, true), Sep(), I(Tr(L"Ajustes de Bluetooth…"), 1) }, [](int) { shell::OpenSettings(L"bluetooth"); }); break;- case K_BATT: {- wchar_t b[64]; swprintf_s(b, Tr(L"Bateria: %d%%"), g_st.pct);- ShowAt(hit, { I(b, 0, true), I(g_st.charging ? Tr(L"Fonte de Energia: Carregador") : Tr(L"Fonte de Energia: Bateria"), 0, true), Sep(), I(Tr(L"Ajustes de Bateria…"), 1) },- [](int) { shell::OpenSettings(L"energia"); });- break;- }- case K_INPUT: { // as fontes de entrada instaladas; a escolhida vai para o app da frente- HKL list[32]; int n = GetKeyboardLayoutList(32, list);- std::vector<ctxmenu::Item> items;- for (int i = 0; i < n; i++) items.push_back(I(InputBadge(list[i]) + L" " + LayoutName(list[i]), 100 + i, false, list[i] == g_st.hkl));- items.push_back(Sep());- items.push_back(I(Tr(L"Abrir Ajustes de Teclado…"), 1));- HWND target = g_fg;- ShowAt(hit, items, [&](int id) {- if (id == 1) { shell::OpenSettings(L"teclado"); return; }- if (id >= 100 && id - 100 < n && target) PostMessageW(target, WM_INPUTLANGCHANGEREQUEST, 0, (LPARAM)list[id - 100]);- RefreshStatus(); Render();- });- break;- } // painel da Central de Controle (central.cpp)- case K_CLOCK: {- if (!right) { notificacoes::Toggle(); break; } // clique: Central de Notificações; botão direito: data e ajustes- SYSTEMTIME st; GetLocalTime(&st);- wchar_t full[128] = {};- GetDateFormatEx(idioma::Locale(), DATE_LONGDATE, &st, nullptr, full, 128, nullptr);- ShowAt(hit, { I(full, 0, true), Sep(), I(Tr(L"Ajustes de Data e Hora…"), 1) }, [](int) { Open(L"ms-settings:dateandtime"); });- break;- }- }-}--// Desenha todas as barras (a principal por último: os itens dela ficam em g_hits de quem chama sem g_cur)-void RenderAll() {- HWND keep = g_cur;- for (HWND b : g_extras) if (IsWindowVisible(b)) { g_cur = b; Render(); }- g_cur = nullptr;- Render();- g_cur = keep;-}--// Redesenha só quando algo visível mudou (antes: a barra inteira a cada segundo)-void RenderIfChanged() {- static std::wstring last;- std::wstring sig = g_appName + L"|" + ClockText() + L"|" + std::to_wstring(ui::Dark()) + L"|" + std::to_wstring(g_titles.size());- for (auto& t : g_titles) sig += t;- wchar_t b[128];- swprintf_s(b, L"|%d%d%d%d%d%d%d|%d|%d|%p|%d", g_st.wlan, g_st.wifiOn, g_st.batt, g_st.charging, g_st.bt, g_st.sound, g_st.muted,- g_st.pct, (int)std::lround(g_st.vol * 3), (void*)g_st.hkl, g_st.phones);- sig += b;- for (auto& t : tray::icons) { swprintf_s(b, L"|%p%d%d", (void*)t.icon, t.hidden, IsShown(t)); sig += b; }- RECT rc; GetClientRect(g_bar, &rc);- sig += std::to_wstring(rc.right) + L"x" + std::to_wstring(rc.bottom);- for (HWND b : g_extras) { GetClientRect(b, &rc); sig += L"|" + std::to_wstring(rc.right) + L"x" + std::to_wstring(IsWindowVisible(b)); }- sig += L"|" + std::to_wstring(g_vaoE) + L"-" + std::to_wstring(g_vaoD);- if (sig == last) return;- last = sig;- RenderAll();-}--const UINT WM_BARDISPLAYS = WM_APP + 41; // monitores mudaram: refaz as barras (fora do WndProc que recebeu o aviso)--// A barra principal no lugar dela: o topo do monitor, ou (barra_embaixo, issue #29) o meio da linha do Dock, com um-// buraco na janela onde o Dock está, para os cliques e o passar do mouse continuarem dele. O Dock muda de largura-// sozinho (app aberto, ampliação): o timer de 1 s chama de novo.-void Assenta() {- if (!g_bar) return;- static bool eraEmbaixo;- static RECT posto;- const bool baixo = menubar::Embaixo();- HMONITOR hm = MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY);- MONITORINFO mi{ sizeof(mi) };- if (!GetMonitorInfoW(hm, &mi)) return;- RECT q = mi.rcMonitor;- const int alt = menubar::HeightOn(hm);- if (baixo) q.top = q.bottom - menubar::ReservedBottom(hm) / 2 - alt / 2;- q.bottom = q.top + alt;- const bool mudou = baixo != eraEmbaixo, moveu = baixo && !EqualRect(&q, &posto);- int e = 0, d = 0;- if (baixo) {- RECT v;- // com o ponteiro em cima, o Dock está ampliado: o vão fica como estava (senão os menus piscavam)- if (dock::Vidro(&v) && v.bottom > q.top && v.top < q.bottom) {- e = std::max<int>(0, v.left - q.left); d = std::min<int>(q.right - q.left, v.right - q.left);- POINT pt; GetCursorPos(&pt);- if (!mudou && !moveu && g_vaoD > g_vaoE && PtInRect(&v, pt)) { e = g_vaoE; d = g_vaoD; }- }- }- if (!mudou && !moveu && e == g_vaoE && d == g_vaoD) return;- eraEmbaixo = baixo; posto = q; g_vaoE = e; g_vaoD = d;- SetWindowPos(g_bar, HWND_TOPMOST, q.left, q.top, q.right - q.left, q.bottom - q.top, SWP_NOACTIVATE);- HRGN rg = nullptr;- if (d > e) {- rg = CreateRectRgn(0, 0, q.right - q.left, q.bottom - q.top);- HRGN furo = CreateRectRgn(e, 0, d, q.bottom - q.top);- CombineRgn(rg, rg, furo, RGN_DIFF);- DeleteObject(furo);- }- SetWindowRgn(g_bar, rg, TRUE); // a janela fica dona da região- if (mudou) {- BarGlass(g_bar);- Log(L"barra de menus: %ls", baixo ? L"embaixo, na linha do Dock" : L"em cima");- menubar::Displays();- return;- }- if (baixo) Log(L"barra de menus: embaixo em %d,%d-%d,%d, o Dock de %d a %d", q.left, q.top, q.right, q.bottom, e, d);- RenderAll();- if (moveu) shell::ApplyWorkArea();-}--LRESULT CALLBACK BarProc(HWND h, UINT m, WPARAM w, LPARAM l) {- switch (m) {- case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(h, &ps); EndPaint(h, &ps); HWND keep = g_cur; g_cur = h; Render(); g_cur = keep; return 0; }- case WM_LBUTTONDOWN: case WM_RBUTTONUP: {- float sc = ui::Scale(h);- HWND keep = g_cur;- g_cur = h; // os menus abrem embaixo da barra clicada (no monitor dela)- Click({ (short)LOWORD(l) / sc, (short)HIWORD(l) / sc }, m == WM_RBUTTONUP);- g_cur = keep;- return 0;- }- case WM_BARDISPLAYS: menubar::Displays(); return 0;- case WM_MOUSEACTIVATE: return MA_NOACTIVATE;+// Barra de menus no topo, como no macOS Sequoia: logo (menu do sistema), nome do app ativo em+// negrito, menus do app; à direita os ícones de status (bandeja), rede, Spotlight, Central de+// Controle e relógio. Ver docs/dock-e-barra-de-menus.md.+#include "shell.h"+#include "../comum/simbolos.h"+static const wchar_t* IconePC() { return shell::Setting(L"sobre_mac", L"pc") == L"macstudio" ? L"pack:macstudio" : L"sym:pc"; }+#include "../menu/context_menu.h"+#include <shellapi.h>+#include <dwmapi.h>+#include <wincodec.h>+#include <shlobj.h>+#include <powrprof.h>+#include <wlanapi.h>+#include <mmdeviceapi.h>+#include <endpointvolume.h>+#include <bluetoothapis.h>+#include <propsys.h>+#pragma comment(lib, "bthprops.lib")+#include <shellscalingapi.h>+#include <iphlpapi.h>+#pragma comment(lib, "iphlpapi.lib")+#include <algorithm>+#include <cmath>+#include <map>+#include <atomic>+#include <mutex>+#include <thread>+#include "../comum/idioma.h"++static void TiqueOcultar(); // ocultar a barra automaticamente (mais abaixo, fora do namespace)+namespace {++const float BAR_PT_SEQUOIA = 26; // altura da barra (telas sem entalhe; um pouco maior que os 24 pt do Mac, para telas grandes)+// Tahoe: 30 pt, medido no macOS 26 (guia macOS26-Theme-Reference, seções 13 e 35: frame.maxY − visibleFrame.maxY)+// Leopard: 22 pt, a barra do Mac OS X 10.5+#define BAR_PT (liquid::On() ? 30.f : liquid::Leopard() ? 22.f : BAR_PT_SEQUOIA)+const float PAD_SEQUOIA = 10; // espaço de cada lado de um ícone de status (Mac: ~10 pt, um item a cada ~38 pt)+// Tahoe (guia, seção 35): cada item da direita = o ícone + ~8 pt de respiro de cada lado (31–42 pt por item)+#define PAD (liquid::On() ? 8.f : PAD_SEQUOIA)++bool g_overflow; // macOS 27: algum ícone da bandeja não coube na barra (mostra a »)+enum Kind { K_LOGO, K_APP, K_MENU, K_TRAY, K_NET, K_SPOT, K_CC, K_CLOCK, K_MORE, K_BATT, K_SOUND, K_BT, K_INPUT, K_SIRI };+struct Hit { D2D1_RECT_F r; Kind kind; int index; };++HWND g_bar, g_owner; // g_bar: a barra do monitor principal+// Uma barra em cada monitor (como no Mac), todas com o mesmo conteúdo. Cada uma tem a sua superfície e os+// seus itens clicáveis; g_cur é a que está sendo desenhada/clicada agora (nullptr = a principal), e g_s/g_hits+// apontam para as dela.+struct BarState { ui::Surface s; std::vector<Hit> hits; };+std::map<HWND, BarState> g_state;+std::vector<HWND> g_extras; // barras dos outros monitores+HWND g_cur, g_openBar;+HWND Cur() { return g_cur ? g_cur : g_bar; }+#define g_s (g_state[Cur()].s)+#define g_hits (g_state[Cur()].hits)+int g_open = -1; // índice em g_hits do item com menu aberto (na barra g_openBar)+int g_vaoE = 0, g_vaoD = 0; // barra embaixo: o trecho do Dock na linha dela (px da janela da barra); 0-0 = em cima+HWND g_fg; // janela do app ativo (fora as nossas)+std::wstring g_appName = L"Finder";+std::vector<std::wstring> g_titles; // menus do app ativo+HMENU g_hmenu; // menu Win32 real do app (se tiver)+bool g_finderActive = true;+IDWriteTextFormat *g_tf, *g_tfBold, *g_tfIcon, *g_tfBadge;++// Como no Mac, a barra mostra pouca coisa: os ícones de bandeja só aparecem se o usuário fixar+// ("Mostrar na barra de menus"); os outros ficam na lista da setinha. Guardados pelo nome (dica).+std::vector<std::wstring> Shown() {+ std::vector<std::wstring> v;+ std::wstring s = shell::Setting(L"barra_icones", L"");+ size_t a = 0, b;+ while ((b = s.find(L'|', a)) != std::wstring::npos) { if (b > a) v.push_back(s.substr(a, b - a)); a = b + 1; }+ if (a < s.size()) v.push_back(s.substr(a));+ return v;+}+// Apps Electron (Discord) põem o ícone sem dica: aparecia "(sem nome)" na lista e não dava para fixar, porque o nome+// vazio some ao ler barra_icones (issue #30). Sem dica vale o nome do programa dono (Discord.exe -> Discord): é estável+// e sai sem ler o disco. Guardado por janela e processo (o número de uma janela fechada pode voltar em outro app).+std::wstring ProgramaDoIcone(HWND h) {+ DWORD pid = 0;+ if (!h || !GetWindowThreadProcessId(h, &pid) || !pid) return L"";+ static std::map<std::pair<HWND, DWORD>, std::wstring> nomes;+ auto chave = std::make_pair(h, pid);+ if (auto it = nomes.find(chave); it != nomes.end()) return it->second;+ std::wstring nome;+ if (HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid)) {+ wchar_t b[MAX_PATH]; DWORD n = MAX_PATH;+ if (QueryFullProcessImageNameW(p, 0, b, &n)) {+ nome = b;+ nome = nome.substr(nome.find_last_of(L'\\') + 1);+ if (nome.size() > 4 && !_wcsicmp(nome.c_str() + nome.size() - 4, L".exe")) nome.resize(nome.size() - 4);+ if (!nome.empty()) nome[0] = towupper(nome[0]);+ }+ CloseHandle(p);+ }+ if (nomes.size() > 256) nomes.clear();+ return nomes[chave] = nome;+}+std::wstring TrayKey(const TrayIcon& t) { // nome estável: a dica até a primeira quebra de linha ou ":"; sem dica, o programa+ std::wstring k = t.tip.substr(0, t.tip.find_first_of(L"\r\n:"));+ while (!k.empty() && k.back() == L' ') k.pop_back();+ return k.empty() ? ProgramaDoIcone(t.hwnd) : k;+}+bool IsShown(const TrayIcon& t) {+ if (shell::Setting(L"barra_icones_todos", L"0") == L"1") return true; // Central de Controle: "Sempre na barra de menus"+ std::wstring k = TrayKey(t);+ for (auto& s : Shown()) if (!_wcsicmp(s.c_str(), k.c_str())) return true;+ return false;+}+void SetShown(const TrayIcon& t, bool on) {+ auto v = Shown();+ std::wstring k = TrayKey(t);+ v.erase(std::remove_if(v.begin(), v.end(), [&](const std::wstring& x) { return !_wcsicmp(x.c_str(), k.c_str()); }), v.end());+ if (on) v.push_back(k);+ std::wstring out;+ for (auto& x : v) { if (!out.empty()) out += L"|"; out += x; }+ shell::SetSetting(L"barra_icones", out);+}++std::wstring Clean(const wchar_t* s, std::wstring* shortcut = nullptr) {+ std::wstring out;+ for (const wchar_t* p = s; *p; p++) {+ if (*p == L'\t') { if (shortcut) *shortcut = p + 1; break; }+ if (*p == L'&') { if (p[1] == L'&') { out += L'&'; p++; } continue; }+ out += *p;+ }+ return out;+}++// ---- teclas para os menus genéricos (apps sem menu Win32): mandadas ao app ativo+void SendKeys(std::initializer_list<WORD> keys) {+ std::vector<INPUT> in;+ for (WORD k : keys) { INPUT i{ INPUT_KEYBOARD }; i.ki.wVk = k; in.push_back(i); }+ for (auto it = std::rbegin(keys); it != std::rend(keys); ++it) { INPUT i{ INPUT_KEYBOARD }; i.ki.wVk = *it; i.ki.dwFlags = KEYEVENTF_KEYUP; in.push_back(i); }+ SendInput((UINT)in.size(), in.data(), sizeof(INPUT));+}++struct KeyCmd { int id; const wchar_t* label; const wchar_t* shortcut; std::initializer_list<WORD> keys; };+// ids 1000+: atalhos de teclado mandados ao app+const KeyCmd g_keyCmds[] = {+ { 1001, L"Nova Janela", L"Ctrl+N", { VK_CONTROL, 'N' } },+ { 1002, L"Abrir…", L"Ctrl+O", { VK_CONTROL, 'O' } },+ { 1003, L"Fechar Janela", L"Ctrl+W", { VK_CONTROL, 'W' } },+ { 1004, L"Salvar", L"Ctrl+S", { VK_CONTROL, 'S' } },+ { 1005, L"Imprimir…", L"Ctrl+P", { VK_CONTROL, 'P' } },+ { 1010, L"Desfazer", L"Ctrl+Z", { VK_CONTROL, 'Z' } },+ { 1011, L"Refazer", L"Ctrl+Y", { VK_CONTROL, 'Y' } },+ { 1012, L"Recortar", L"Ctrl+X", { VK_CONTROL, 'X' } },+ { 1013, L"Copiar", L"Ctrl+C", { VK_CONTROL, 'C' } },+ { 1014, L"Colar", L"Ctrl+V", { VK_CONTROL, 'V' } },+ { 1015, L"Selecionar Tudo", L"Ctrl+A", { VK_CONTROL, 'A' } },+ { 1016, L"Buscar", L"Ctrl+F", { VK_CONTROL, 'F' } },+ { 1020, L"Nova Aba", L"Ctrl+T", { VK_CONTROL, 'T' } },+ { 1021, L"Nova Pasta", L"Ctrl+Shift+N", { VK_CONTROL, VK_SHIFT, 'N' } },+ { 1022, L"Obter Informações", L"Ctrl+I", { VK_CONTROL, 'I' } },+ { 1023, L"Mover para o Lixo", L"Delete", { VK_DELETE } },+ { 1030, L"como Ícones", L"Ctrl+1", { VK_CONTROL, '1' } },+ { 1031, L"como Lista", L"Ctrl+2", { VK_CONTROL, '2' } },+ { 1032, L"como Colunas", L"Ctrl+3", { VK_CONTROL, '3' } },+ { 1033, L"como Galeria", L"Ctrl+4", { VK_CONTROL, '4' } },+ { 1034, L"Mostrar Opções de Visualização", L"Ctrl+J", { VK_CONTROL, 'J' } },+ { 1040, L"Voltar", L"Alt+←", { VK_MENU, VK_LEFT } },+ { 1041, L"Avançar", L"Alt+→", { VK_MENU, VK_RIGHT } },+ { 1042, L"Pasta Superior", L"Ctrl+↑", { VK_CONTROL, VK_UP } },+ { 1043, L"Ir para a Pasta…", L"Ctrl+Shift+G", { VK_CONTROL, VK_SHIFT, 'G' } },+ { 1050, L"Ajuda", L"F1", { VK_F1 } },+ { 1051, L"Ajustes…", L"Ctrl+,", { VK_CONTROL, VK_OEM_COMMA } },+ // menus próprios dos apps sem menu Win32 (AppMenus): os atalhos do Windows de cada um+ { 5001, L"Nova Janela Anônima", L"Ctrl+Shift+N", { VK_CONTROL, VK_SHIFT, 'N' } },+ { 5002, L"Reabrir Aba Fechada", L"Ctrl+Shift+T", { VK_CONTROL, VK_SHIFT, 'T' } },+ { 5003, L"Abrir Arquivo…", L"Ctrl+O", { VK_CONTROL, 'O' } },+ { 5004, L"Abrir Local…", L"Ctrl+L", { VK_CONTROL, 'L' } },+ { 5005, L"Fechar Janela", L"Ctrl+Shift+W", { VK_CONTROL, VK_SHIFT, 'W' } },+ { 5006, L"Fechar Aba", L"Ctrl+W", { VK_CONTROL, 'W' } },+ { 5007, L"Salvar Página Como…", L"Ctrl+S", { VK_CONTROL, 'S' } },+ { 5010, L"Sempre Mostrar a Barra de Favoritos", L"Ctrl+Shift+B", { VK_CONTROL, VK_SHIFT, 'B' } },+ { 5011, L"Parar", L"Esc", { VK_ESCAPE } },+ { 5012, L"Recarregar Esta Página", L"Ctrl+R", { VK_CONTROL, 'R' } },+ { 5013, L"Forçar Recarregamento", L"Ctrl+Shift+R", { VK_CONTROL, VK_SHIFT, 'R' } },+ { 5014, L"Entrar em Tela Cheia", L"F11", { VK_F11 } },+ { 5015, L"Tamanho Real", L"Ctrl+0", { VK_CONTROL, '0' } },+ { 5016, L"Ampliar", L"Ctrl+=", { VK_CONTROL, VK_OEM_PLUS } },+ { 5017, L"Reduzir", L"Ctrl+-", { VK_CONTROL, VK_OEM_MINUS } },+ { 5018, L"Ferramentas do Desenvolvedor", L"Ctrl+Shift+I", { VK_CONTROL, VK_SHIFT, 'I' } },+ { 5019, L"Ver Código-Fonte", L"Ctrl+U", { VK_CONTROL, 'U' } },+ { 5020, L"Página Inicial", L"Alt+Home", { VK_MENU, VK_HOME } },+ { 5021, L"Mostrar Histórico Completo", L"Ctrl+H", { VK_CONTROL, 'H' } },+ { 5022, L"Limpar Dados de Navegação…", L"Ctrl+Shift+Del", { VK_CONTROL, VK_SHIFT, VK_DELETE } },+ { 5030, L"Gerenciador de Favoritos", L"Ctrl+Shift+O", { VK_CONTROL, VK_SHIFT, 'O' } },+ { 5031, L"Adicionar Esta Página aos Favoritos…", L"Ctrl+D", { VK_CONTROL, 'D' } },+ { 5032, L"Adicionar Todas as Abas aos Favoritos…", L"Ctrl+Shift+D", { VK_CONTROL, VK_SHIFT, 'D' } },+ { 5040, L"Selecionar Próxima Aba", L"Ctrl+Tab", { VK_CONTROL, VK_TAB } },+ { 5041, L"Selecionar Aba Anterior", L"Ctrl+Shift+Tab", { VK_CONTROL, VK_SHIFT, VK_TAB } },+ { 5050, L"Downloads", L"Ctrl+J", { VK_CONTROL, 'J' } },+ { 5051, L"Gerenciador de Tarefas", L"Shift+Esc", { VK_SHIFT, VK_ESCAPE } },+ { 5060, L"Central de Ajuda", L"F1", { VK_F1 } },+ { 5070, L"Refazer", L"Ctrl+Shift+Z", { VK_CONTROL, VK_SHIFT, 'Z' } },+ { 5071, L"Recarregar", L"Ctrl+R", { VK_CONTROL, 'R' } },+ { 5072, L"Busca Rápida", L"Ctrl+K", { VK_CONTROL, 'K' } },+ { 5073, L"Atalhos de Teclado", L"Ctrl+/", { VK_CONTROL, VK_DIVIDE } },+ { 5080, L"Nova Conversa", L"Ctrl+N", { VK_CONTROL, 'N' } },+ { 5081, L"Novo Grupo", L"Ctrl+Shift+N", { VK_CONTROL, VK_SHIFT, 'N' } },+ // Spotify+ { 5100, L"Nova Playlist", L"Ctrl+N", { VK_CONTROL, 'N' } },+ { 5101, L"Reproduzir/Pausar", L"Espaço", { VK_SPACE } },+ { 5102, L"Próxima", L"Ctrl+→", { VK_CONTROL, VK_RIGHT } },+ { 5103, L"Anterior", L"Ctrl+←", { VK_CONTROL, VK_LEFT } },+ { 5104, L"Aumentar Volume", L"Ctrl+↑", { VK_CONTROL, VK_UP } },+ { 5105, L"Diminuir Volume", L"Ctrl+↓", { VK_CONTROL, VK_DOWN } },+ { 5106, L"Repetir", L"Ctrl+R", { VK_CONTROL, 'R' } },+ { 5107, L"Aleatório", L"Ctrl+S", { VK_CONTROL, 'S' } },+ { 5108, L"Buscar", L"Ctrl+K", { VK_CONTROL, 'K' } },+ // VS Code+ { 5120, L"Novo Arquivo", L"Ctrl+N", { VK_CONTROL, 'N' } },+ { 5121, L"Nova Janela", L"Ctrl+Shift+N", { VK_CONTROL, VK_SHIFT, 'N' } },+ { 5122, L"Salvar Como…", L"Ctrl+Shift+S", { VK_CONTROL, VK_SHIFT, 'S' } },+ { 5123, L"Fechar Editor", L"Ctrl+W", { VK_CONTROL, 'W' } },+ { 5124, L"Substituir", L"Ctrl+H", { VK_CONTROL, 'H' } },+ { 5125, L"Buscar nos Arquivos", L"Ctrl+Shift+F", { VK_CONTROL, VK_SHIFT, 'F' } },+ { 5126, L"Paleta de Comandos…", L"Ctrl+Shift+P", { VK_CONTROL, VK_SHIFT, 'P' } },+ { 5127, L"Explorador", L"Ctrl+Shift+E", { VK_CONTROL, VK_SHIFT, 'E' } },+ { 5128, L"Controle do Código-Fonte", L"Ctrl+Shift+G", { VK_CONTROL, VK_SHIFT, 'G' } },+ { 5129, L"Extensões", L"Ctrl+Shift+X", { VK_CONTROL, VK_SHIFT, 'X' } },+ { 5130, L"Ir para Arquivo…", L"Ctrl+P", { VK_CONTROL, 'P' } },+ { 5131, L"Ir para Linha…", L"Ctrl+G", { VK_CONTROL, 'G' } },+ { 5132, L"Iniciar Depuração", L"F5", { VK_F5 } },+ { 5133, L"Executar sem Depurar", L"Ctrl+F5", { VK_CONTROL, VK_F5 } },+ { 5134, L"Barra Lateral", L"Ctrl+B", { VK_CONTROL, 'B' } },+};++ctxmenu::Item K(int id) {+ for (auto& k : g_keyCmds) if (k.id == id) { ctxmenu::Item i; i.label = Tr(k.label); i.id = id; i.shortcut = k.shortcut; return i; }+ return {};+}+ctxmenu::Item I(const std::wstring& label, int id, bool disabled = false, bool checked = false) {+ ctxmenu::Item i; i.label = label; i.id = id; i.disabled = disabled; i.checked = checked; return i;+}+ctxmenu::Item Sep() { ctxmenu::Item i; i.separator = true; return i; }++// ---- menu Win32 real do app → itens do nosso menu+std::vector<ctxmenu::Item> FromHmenu(HMENU m, int depth) {+ std::vector<ctxmenu::Item> out;+ int n = GetMenuItemCount(m);+ for (int k = 0; k < n; k++) {+ wchar_t buf[256] = {};+ MENUITEMINFOW mi{ sizeof(mi) };+ mi.fMask = MIIM_STRING | MIIM_FTYPE | MIIM_STATE | MIIM_ID | MIIM_SUBMENU;+ mi.dwTypeData = buf; mi.cch = 255;+ if (!GetMenuItemInfoW(m, k, TRUE, &mi)) continue;+ if (mi.fType & MFT_SEPARATOR) { if (!out.empty() && !out.back().separator) out.push_back(Sep()); continue; }+ if (mi.fType & MFT_OWNERDRAW || !buf[0]) continue;+ ctxmenu::Item it;+ it.label = Clean(buf, &it.shortcut);+ it.id = (int)mi.wID;+ it.disabled = (mi.fState & (MFS_DISABLED | MFS_GRAYED)) != 0;+ it.checked = (mi.fState & MFS_CHECKED) != 0;+ if (mi.hSubMenu) {+ if (g_fg) {+ // alguns apps só preenchem o submenu quando o item dele é destacado (o Ableton deixa "*" nos+ // sets recentes até receber WM_MENUSELECT); depois espera um pouco se ainda for o marcador+ SendMessageTimeoutW(g_fg, WM_MENUSELECT, MAKEWPARAM(k, MF_POPUP | MF_HILITE), (LPARAM)m, SMTO_ABORTIFHUNG, 200, nullptr);+ SendMessageTimeoutW(g_fg, WM_INITMENUPOPUP, (WPARAM)mi.hSubMenu, k, SMTO_ABORTIFHUNG, 200, nullptr);+ for (int t = 0; t < 12; t++) {+ wchar_t first[8] = {};+ GetMenuStringW(mi.hSubMenu, 0, first, 8, MF_BYPOSITION);+ if (wcscmp(first, L"*")) break;+ SendMessageTimeoutW(g_fg, WM_NULL, 0, 0, SMTO_ABORTIFHUNG, 100, nullptr);+ Sleep(15);+ }+ }+ if (depth == 0) it.sub = FromHmenu(mi.hSubMenu, 1);+ else { // nosso menu tem um nível de submenu: os mais fundos entram achatados+ out.push_back(Sep());+ for (auto& c : FromHmenu(mi.hSubMenu, 2)) out.push_back(c);+ out.push_back(Sep());+ continue;+ }+ }+ out.push_back(it);+ }+ while (!out.empty() && out.back().separator) out.pop_back();+ return out;+}++App* ActiveApp() {+ if (g_finderActive || !g_fg) for (auto& a : apps::list) if (a.finder) return &a;+ return g_fg ? apps::OfWindow(g_fg) : nullptr;+}++// ---- estado do sistema para a direita da barra+bool WifiName(std::wstring& ssid) {+ HANDLE h = nullptr; DWORD ver = 0;+ if (WlanOpenHandle(2, nullptr, &ver, &h) != ERROR_SUCCESS) return false;+ bool ok = false;+ PWLAN_INTERFACE_INFO_LIST list = nullptr;+ if (WlanEnumInterfaces(h, nullptr, &list) == ERROR_SUCCESS) {+ for (DWORD i = 0; i < list->dwNumberOfItems && !ok; i++) {+ auto& info = list->InterfaceInfo[i];+ if (info.isState != wlan_interface_state_connected) continue;+ // Conectado é o estado da placa. O nome da rede, desde o Windows 11 24H2, só sai com a permissão de+ // localização ligada (sem ela a consulta falha): antes isso virava "não conectado" (issue #40)+ ok = true;+ PWLAN_CONNECTION_ATTRIBUTES ca = nullptr; DWORD sz = 0;+ if (WlanQueryInterface(h, &info.InterfaceGuid, wlan_intf_opcode_current_connection, nullptr, &sz, (PVOID*)&ca, nullptr) == ERROR_SUCCESS && ca) {+ auto& s = ca->wlanAssociationAttributes.dot11Ssid;+ std::string a((const char*)s.ucSSID, s.uSSIDLength); // o nome vem em UTF-8+ int n = MultiByteToWideChar(CP_UTF8, 0, a.c_str(), (int)a.size(), nullptr, 0);+ ssid.resize(n);+ MultiByteToWideChar(CP_UTF8, 0, a.c_str(), (int)a.size(), ssid.data(), n);+ WlanFreeMemory(ca);+ }+ }+ WlanFreeMemory(list);+ }+ WlanCloseHandle(h, nullptr);+ return ok;+}++// Estado do sistema para os ícones da direita (relido a cada segundo; o Bluetooth a cada 10 s)+struct Status {+ bool wlan = false, wifiOn = false, wired = false;+ bool batt = false, charging = false; int pct = 100;+ bool bt = false;+ bool sound = false, muted = false, phones = false; float vol = 0;+ HKL hkl = nullptr;+ DWORD btAt = 0;+ std::wstring ssid;+} g_st;++bool WifiName(std::wstring& ssid);+std::atomic<bool> g_audioStale{ false }; // a saída padrão mudou: relê o objeto de áudio já++void LerStatus(Status& st) {+ static DWORD wifiAt, audioAt;+ static IAudioEndpointVolume* vol; // o mesmo objeto de áudio entre as leituras (antes: criado e solto a cada segundo)+ DWORD now = GetTickCount();+ // Wi-Fi: existe placa? está conectada? (a cada 5 s)+ if (!wifiAt || now - wifiAt > 5000) {+ wifiAt = now;+ st.wlan = false;+ HANDLE h = nullptr; DWORD ver = 0;+ if (WlanOpenHandle(2, nullptr, &ver, &h) == ERROR_SUCCESS) {+ PWLAN_INTERFACE_INFO_LIST list = nullptr;+ if (WlanEnumInterfaces(h, nullptr, &list) == ERROR_SUCCESS) { st.wlan = list->dwNumberOfItems > 0; WlanFreeMemory(list); }+ WlanCloseHandle(h, nullptr);+ }+ st.ssid.clear();+ st.wifiOn = st.wlan && WifiName(st.ssid);+ // cabo ligado (placa Ethernet com rede)? Aí o Wi-Fi desconectado não aparece na barra+ st.wired = false;+ ULONG sz = 16 * 1024;+ std::vector<BYTE> buf(sz);+ DWORD rc = GetAdaptersInfo((IP_ADAPTER_INFO*)buf.data(), &sz);+ if (rc == ERROR_BUFFER_OVERFLOW) { buf.resize(sz); rc = GetAdaptersInfo((IP_ADAPTER_INFO*)buf.data(), &sz); }+ if (rc == NO_ERROR) // placa Ethernet com gateway = cabo conectado à rede+ for (auto* a = (IP_ADAPTER_INFO*)buf.data(); a; a = a->Next)+ if (a->Type == MIB_IF_TYPE_ETHERNET && strcmp(a->GatewayList.IpAddress.String, "0.0.0.0") && a->GatewayList.IpAddress.String[0]) { st.wired = true; break; }+ }+ // bateria (só em quem tem)+ SYSTEM_POWER_STATUS ps{};+ if (GetSystemPowerStatus(&ps) && !(ps.BatteryFlag & 128) && ps.BatteryFlag != 255 && ps.BatteryLifePercent <= 100) {+ st.batt = true; st.pct = ps.BatteryLifePercent; st.charging = ps.ACLineStatus == 1;+ } else st.batt = false;+ // Bluetooth: tem rádio?+ if (!st.btAt || GetTickCount() - st.btAt > 10000) {+ st.btAt = GetTickCount();+ BLUETOOTH_FIND_RADIO_PARAMS fp{ sizeof(fp) }; HANDLE radio = nullptr;+ HBLUETOOTH_RADIO_FIND f = BluetoothFindFirstRadio(&fp, &radio);+ st.bt = f != nullptr;+ if (radio) CloseHandle(radio);+ if (f) BluetoothFindRadioClose(f);+ }+ // som: volume e mudo a cada segundo (barato, no objeto guardado); a saída padrão e se é um fone a cada 10 s+ bool fresh = false;+ if (g_audioStale.exchange(false)) audioAt = 0;+ if (vol && audioAt && now - audioAt < 10000) {+ BOOL mute = FALSE;+ if (SUCCEEDED(vol->GetMute(&mute)) && SUCCEEDED(vol->GetMasterVolumeLevelScalar(&st.vol))) { st.muted = mute; fresh = true; }+ }+ if (!fresh) {+ audioAt = now;+ if (vol) { vol->Release(); vol = nullptr; }+ st.sound = false;+ IMMDeviceEnumerator* en = nullptr;+ if (SUCCEEDED(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&en)))) {+ IMMDevice* dev = nullptr;+ if (SUCCEEDED(en->GetDefaultAudioEndpoint(eRender, eConsole, &dev))) {+ if (SUCCEEDED(dev->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, nullptr, (void**)&vol))) {+ BOOL mute = FALSE; vol->GetMute(&mute); vol->GetMasterVolumeLevelScalar(&st.vol);+ st.muted = mute; st.sound = true;+ }+ IPropertyStore* ps2 = nullptr;+ st.phones = false;+ if (SUCCEEDED(dev->OpenPropertyStore(STGM_READ, &ps2))) {+ static const PROPERTYKEY formFactor = { { 0x1da5d803, 0xd492, 0x4edd, { 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e } }, 0 };+ PROPVARIANT v; PropVariantInit(&v);+ if (SUCCEEDED(ps2->GetValue(formFactor, &v)) && v.vt == VT_UI4) st.phones = v.ulVal == 3 || v.ulVal == 5; // fone / headset+ PropVariantClear(&v);+ ps2->Release();+ }+ dev->Release();+ }+ en->Release();+ }+ }+}++// Tudo acima pergunta a um serviço do Windows (WLAN, rede, Bluetooth, áudio) e espera a resposta. Na thread da+// interface, com o PC ocupado, o Shell inteiro parava: o WlanOpenHandle levou 3,6 s (pilha de 22/11/2026, 15:14).+// Uma thread só lê; a interface pega a última resposta e redesenha quando chega uma diferente.+const UINT WM_BARSTATUS = WM_APP + 42;+std::mutex g_stMx;+Status g_stLido;++void PedeStatus() {+ static HANDLE pedido = CreateEventW(nullptr, FALSE, FALSE, nullptr);+ static std::once_flag uma;+ std::call_once(uma, [] {+ std::thread([] {+ CoInitializeEx(nullptr, COINIT_MULTITHREADED);+ Status st;+ while (WaitForSingleObject(pedido, INFINITE) == WAIT_OBJECT_0) {+ LerStatus(st);+ bool mudou;+ {+ std::lock_guard<std::mutex> l(g_stMx);+ const Status& a = g_stLido;+ mudou = a.wlan != st.wlan || a.wifiOn != st.wifiOn || a.wired != st.wired || a.batt != st.batt || a.charging != st.charging ||+ a.pct != st.pct || a.bt != st.bt || a.sound != st.sound || a.muted != st.muted || a.phones != st.phones ||+ a.vol != st.vol || a.ssid != st.ssid;+ g_stLido = st;+ }+ if (mudou && g_bar) PostMessageW(g_bar, WM_BARSTATUS, 0, 0);+ }+ }).detach();+ });+ SetEvent(pedido);+}++void PegaStatus() {+ { std::lock_guard<std::mutex> l(g_stMx); g_st = g_stLido; }+ // fonte de entrada (teclado) do app da frente+ HWND fg = GetForegroundWindow();+ g_st.hkl = GetKeyboardLayout(fg ? GetWindowThreadProcessId(fg, nullptr) : 0);+}++void RefreshStatus() {+ PedeStatus();+ PegaStatus();+}++// "A" para o teclado americano (o "ABC" do Mac), senão a sigla do país do layout (BR, PT, ES…)+std::wstring InputBadge(HKL hkl) {+ WORD layout = HIWORD((ULONG_PTR)hkl), lang = LOWORD((ULONG_PTR)hkl);+ if ((layout & 0xF000) == 0xF000) layout = lang; // layout alternativo: usa o idioma+ if (layout == 0x0409) return L"A";+ wchar_t name[LOCALE_NAME_MAX_LENGTH] = {};+ if (LCIDToLocaleName(MAKELCID(layout, SORT_DEFAULT), name, LOCALE_NAME_MAX_LENGTH, 0) ||+ LCIDToLocaleName(MAKELCID(lang, SORT_DEFAULT), name, LOCALE_NAME_MAX_LENGTH, 0)) {+ std::wstring n = name;+ size_t d = n.find(L'-');+ std::wstring c = d != std::wstring::npos ? n.substr(d + 1, 2) : n.substr(0, 2);+ for (auto& ch : c) ch = towupper(ch);+ return c;+ }+ return L"?";+}+std::wstring LayoutName(HKL hkl) {+ wchar_t name[LOCALE_NAME_MAX_LENGTH] = {}, disp[128] = {};+ LCIDToLocaleName(MAKELCID(LOWORD((ULONG_PTR)hkl), SORT_DEFAULT), name, LOCALE_NAME_MAX_LENGTH, 0);+ GetLocaleInfoEx(name, LOCALE_SLOCALIZEDDISPLAYNAME, disp, 128);+ std::wstring r = disp[0] ? disp : name;+ if (HIWORD((ULONG_PTR)hkl) == 0x0416) r += L" (ABNT2)";+ return r;+}++IAudioEndpointVolume* Volume() {+ IMMDeviceEnumerator* en = nullptr;+ IAudioEndpointVolume* vol = nullptr;+ if (SUCCEEDED(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, IID_PPV_ARGS(&en)))) {+ IMMDevice* dev = nullptr;+ if (SUCCEEDED(en->GetDefaultAudioEndpoint(eRender, eConsole, &dev))) {+ dev->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, nullptr, (void**)&vol);+ dev->Release();+ }+ en->Release();+ }+ return vol;+}++std::wstring ClockText() {+ SYSTEMTIME st; GetLocalTime(&st);+ wchar_t day[16] = {}, mon[16] = {};+ const wchar_t* loc = idioma::Locale();+ GetDateFormatEx(loc, 0, &st, L"ddd", day, 16, nullptr);+ GetDateFormatEx(loc, 0, &st, L"MMM", mon, 16, nullptr);+ std::wstring d = day, m = mon;+ if (idioma::Pt() && !d.empty() && d.back() != L'.') d += L'.';+ if (idioma::Pt() && !m.empty() && m.back() != L'.') m += L'.';+ wchar_t buf[64];+ if (liquid::Leopard()) {+ // Leopard: só o dia da semana e a hora ("Mon 6:45 PM" na captura do 10.5), no formato de hora do usuário+ wchar_t tm[32] = {};+ GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, TIME_NOSECONDS, &st, nullptr, tm, 32);+ std::wstring dd = day;+ if (!dd.empty() && dd.back() == L'.') dd.pop_back();+ if (!dd.empty()) dd[0] = towupper(dd[0]);+ swprintf_s(buf, L"%ls %ls", dd.c_str(), tm);+ return buf;+ }+ // relogio_segundos (issue #38, como "Mostrar segundos" do Mac): 14:05:09+ wchar_t hm[16];+ if (shell::Setting(L"relogio_segundos", L"0") == L"1") swprintf_s(hm, L"%02d:%02d:%02d", st.wHour, st.wMinute, st.wSecond);+ else swprintf_s(hm, L"%02d:%02d", st.wHour, st.wMinute);+ if (shell::Setting(L"relogio_curto", L"0") == L"1") swprintf_s(buf, L"%ls", hm);+ else if (idioma::En()) swprintf_s(buf, L"%ls %ls %d %ls", d.c_str(), m.c_str(), st.wDay, hm); // Tue Nov 10+ else if (idioma::Pt()) swprintf_s(buf, L"%ls %d de %ls %ls", d.c_str(), st.wDay, m.c_str(), hm);+ else swprintf_s(buf, L"%ls %ls", idioma::Date(st, idioma::D_WEEKDAY_SHORT).c_str(), hm); // ven. 20 nov., 11月20日(金)+ return buf;+}++// ---- ícones de status: HICON → BGRA pré-multiplicado (desenhado sobre preto e sobre branco)+struct IconCache { HICON icon; UINT px; std::vector<BYTE> bgra; };+std::vector<IconCache> g_iconCache;++const std::vector<BYTE>& IconPixels(HICON ic, UINT px) {+ for (auto& c : g_iconCache) if (c.icon == ic && c.px == px) return c.bgra;+ if (g_iconCache.size() > 64) g_iconCache.clear();+ // desenhado 4× maior e reduzido pela média de cada bloco 4×4 (anti-aliasing): em 1080p (17 px) o DrawIconEx+ // esticava o ícone de 16/32 px pelo vizinho mais próximo e a borda saía serrilhada+ const UINT SS = 4, R = px * SS;+ BITMAPINFO bi{}; bi.bmiHeader = { sizeof(BITMAPINFOHEADER), (LONG)R, -(LONG)R, 1, 32, BI_RGB };+ void *pb, *pw;+ HDC dc = CreateCompatibleDC(nullptr);+ HBITMAP b = CreateDIBSection(nullptr, &bi, DIB_RGB_COLORS, &pb, nullptr, 0);+ HBITMAP w = CreateDIBSection(nullptr, &bi, DIB_RGB_COLORS, &pw, nullptr, 0);+ IconCache c{ ic, px, std::vector<BYTE>(px * px * 4) };+ if (!b || !w || !pb || !pw) {+ if (b) DeleteObject(b);+ if (w) DeleteObject(w);+ DeleteDC(dc);+ g_iconCache.push_back(std::move(c));+ return g_iconCache.back().bgra;+ }+ memset(pw, 0xFF, R * R * 4);+ HGDIOBJ old = SelectObject(dc, b); DrawIconEx(dc, 0, 0, ic, R, R, 0, nullptr, DI_NORMAL);+ SelectObject(dc, w); DrawIconEx(dc, 0, 0, ic, R, R, 0, nullptr, DI_NORMAL);+ SelectObject(dc, old);+ auto* B = (BYTE*)pb; auto* W = (BYTE*)pw;+ for (UINT y = 0; y < px; y++)+ for (UINT x = 0; x < px; x++) {+ UINT sb = 0, sg = 0, sr = 0, sa = 0;+ for (UINT dy = 0; dy < SS; dy++)+ for (UINT dx = 0; dx < SS; dx++) {+ size_t i = ((size_t)(y * SS + dy) * R + (x * SS + dx)) * 4;+ int a = 255 - std::clamp((W[i + 1] - B[i + 1]), 0, 255); // alfa = 1 - (branco - preto)+ sb += B[i + 0]; sg += B[i + 1]; sr += B[i + 2]; sa += (UINT)a;+ }+ const UINT n = SS * SS;+ size_t o = ((size_t)y * px + x) * 4;+ c.bgra[o + 3] = (BYTE)((sa + n / 2) / n);+ c.bgra[o + 0] = (BYTE)std::min<UINT>((sb + n / 2) / n, c.bgra[o + 3]);+ c.bgra[o + 1] = (BYTE)std::min<UINT>((sg + n / 2) / n, c.bgra[o + 3]);+ c.bgra[o + 2] = (BYTE)std::min<UINT>((sr + n / 2) / n, c.bgra[o + 3]);+ }+ DeleteObject(b); DeleteObject(w); DeleteDC(dc);+ g_iconCache.push_back(std::move(c));+ return g_iconCache.back().bgra;+}++// ---- desenho+void DrawLogo(ID2D1RenderTarget* rt, ID2D1SolidColorBrush* br, float cx, float cy) {+ // logo próprio (não usamos a marca da Apple): quatro quadradinhos arredondados+ float s = 5.4f, g = 1.6f;+ for (int i = 0; i < 4; i++) {+ float x = cx - s - g / 2 + (i % 2) * (s + g), y = cy - s - g / 2 + (i / 2) * (s + g);+ rt->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(x, y, x + s, y + s), 1.5f, 1.5f), br);+ }+}++void DrawCC(ID2D1RenderTarget* rt, ID2D1SolidColorBrush* br, float cx, float cy) {+ // Central de Controle: duas chavinhas+ for (int k = 0; k < 2; k++) {+ float y = cy - 3.6f + k * 7.2f;+ D2D1_ROUNDED_RECT rr{ D2D1::RectF(cx - 7.5f, y - 2.8f, cx + 7.5f, y + 2.8f), 2.8f, 2.8f };+ rt->DrawRoundedRectangle(rr, br, 1.2f);+ float kx = k == 0 ? cx - 4.7f : cx + 4.7f;+ rt->FillEllipse(D2D1::Ellipse({ kx, y }, 2.0f, 2.0f), br);+ }+}++// Ajustes > Transparência e Efeitos > "Mostrar fundo da barra de menus" (desligado: como no Tahoe)+// No Tahoe (Liquid Glass) a barra de menus não tem fundo nenhum, como no macOS 26: só o papel de parede atrás.+bool BarBackground() {+ if (backdrop::Current().reduce || liquid::Leopard()) return true; // Leopard: a barra translúcida clara sempre tem fundo+ if (menubar::Embaixo()) return false; // na linha do Dock: sem faixa atravessando a tela+ if (backdrop::Liquid()) return false;+ return shell::Setting(L"barra_fundo", L"1") != L"0";+}++void BarGlass(HWND bar) {+ if (!bar) return;+ // Leopard: o degradê branco translúcido vem do Render. Translúcida (padrão): transparência de verdade, SEM desfoque+ // (o 10.5 deixava o papel de parede aparecer nítido através da barra); opaca: acrílico cheio por baixo+ const bool leoClear = liquid::Leopard() && shell::Setting(L"barra_translucida", L"1") == L"1";+ if (liquid::Leopard() && !leoClear) { ui::Acrylic(bar, 0xFFE6E6E6u); return; }+ if (!leoClear)+ if (BarBackground()) { ui::Acrylic(bar, ui::Dark() ? 0x40141414u : 0x55F4F4F4u); return; } // vidro bem claro: o papel de parede aparece, como no Mac+ // sem fundo: o DWM só respeita o alfa do que a barra desenha (nada de desfoque)+ struct ACCENT_POLICY { int state, flags; DWORD gradient; int anim; };+ struct WCA_DATA { int attr; PVOID data; SIZE_T size; };+ using Fn = BOOL(WINAPI*)(HWND, WCA_DATA*);+ static Fn fn = (Fn)GetProcAddress(GetModuleHandleW(L"user32.dll"), "SetWindowCompositionAttribute");+ if (!fn) return;+ ACCENT_POLICY ap{ 2 /*ACCENT_ENABLE_TRANSPARENTGRADIENT*/, 2, 0x00000000u, 0 };+ WCA_DATA d{ 19 /*WCA_ACCENT_POLICY*/, &ap, sizeof(ap) };+ fn(bar, &d);+}++// Barra sem fundo (Tahoe): o texto e os ícones seguem a claridade do que está atrás deles, como no Mac+// (branco sobre papel de parede escuro, preto sobre claro), não o tema do sistema. A barra fica sempre+// em cima do papel de parede (a área de trabalho começa abaixo dela): mede o topo da imagem.+float g_topR = 0.5f, g_topG = 0.5f, g_topB = 0.5f; // cor média do topo do papel de parede (vibrancy do Tahoe)+bool WallpaperTopDarkFile(bool fallback);+// a cor do que está atrás da barra: a faixa que a mesa desenhou (muda na hora com o papel de parede); sem a mesa, o+// arquivo do papel de parede+bool WallpaperTopDark(bool fallback) {+ float r, g, b;+ const bool baixo = menubar::Embaixo();+ const int faixa = baixo ? menubar::ReservedBottom(MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)) : menubar::Height();+ if (!mesa::TopColor(faixa, r, g, b, baixo)) return WallpaperTopDarkFile(fallback);+ g_topR = r; g_topG = g; g_topB = b;+ double luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;+ static int adapt = -1; // -1 ainda não decidido, 0 texto claro, 1 texto escuro+ static double lastLog = -1;+ bool dark;+ if (liquid::On()) { // histerese 0,40/0,60 (guia, seção 2.1)+ if (luma > 0.60) adapt = 1; else if (luma < 0.40) adapt = 0; else if (adapt < 0) adapt = luma >= 0.5 ? 1 : 0;+ dark = adapt == 0;+ } else dark = luma < 0.72;+ if (std::fabs(luma - lastLog) > 0.05) { lastLog = luma; Log(L"barra de menus: atrás dela claridade %.2f -> texto %ls", luma, dark ? L"branco" : L"preto"); }+ return dark;+}+// O arquivo do papel de parede numa thread (issue #32): esta conta roda a cada desenho da barra e a cada tique de 1 s,+// e com o Explorador de fundo (o padrão, sem a nossa mesa para dar a cor) lia o Registro e perguntava ao disco pelo+// arquivo toda vez. Com o disco ocupado o GetFileAttributes segurou a interface 11 s (sentinela, 22/11/2026 20:49).+// Agora a interface usa o último resultado e pede uma leitura nova no máximo a cada 4 s.+bool LeTopoDoArquivo(bool fallback, float rgb[3]);+void Render();+bool WallpaperTopDarkFile(bool fallback) {+ static std::atomic<bool> rodando{ false };+ static DWORD quando = 0;+ static int escuro = -1; // -1: ainda sem leitura+ DWORD agora = GetTickCount();+ if (!rodando && (!quando || agora - quando > 4000)) {+ quando = agora;+ rodando = true;+ std::thread([fallback] {+ HRESULT ci = CoInitializeEx(nullptr, COINIT_MULTITHREADED); // WIC+ float rgb[3] = { -1, -1, -1 };+ bool d = LeTopoDoArquivo(fallback, rgb);+ if (SUCCEEDED(ci)) CoUninitialize();+ shell::NaInterface([d, r = rgb[0], g = rgb[1], b = rgb[2]] {+ rodando = false;+ bool mudou = escuro != (d ? 1 : 0);+ escuro = d ? 1 : 0;+ if (r >= 0 && (r != g_topR || g != g_topG || b != g_topB)) { g_topR = r; g_topG = g; g_topB = b; mudou = true; }+ if (mudou) Render();+ });+ }).detach();+ }+ return escuro < 0 ? fallback : escuro == 1;+}+// roda numa thread (só uma por vez): rgb sai com a cor média do topo, ou fica como veio se não leu+bool LeTopoDoArquivo(bool fallback, float rgb[3]) {+ static std::wstring lastKey;+ static bool lastDark = true;+ static float lastRGB[3] = { -1, -1, -1 };+ struct Sai { float* o; ~Sai() { if (lastRGB[0] >= 0) for (int i = 0; i < 3; i++) o[i] = lastRGB[i]; } } sai{ rgb };+ // o papel de parede que a mesa desenha (do registro); sem ele, o do Windows+ wchar_t path[MAX_PATH] = {};+ DWORD cb = sizeof(path);+ if (RegGetValueW(HKEY_CURRENT_USER, L"Control Panel\\Desktop", L"WallPaper", RRF_RT_REG_SZ, nullptr, path, &cb) != ERROR_SUCCESS || !path[0]+ || GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES)+ SystemParametersInfoW(SPI_GETDESKWALLPAPER, MAX_PATH, path, 0);+ WIN32_FILE_ATTRIBUTE_DATA fa{};+ if (!path[0] || !GetFileAttributesExW(path, GetFileExInfoStandard, &fa)) {+ static bool warned;+ if (!warned) { warned = true; Log(L"barra de menus: papel de parede não encontrado (%ls)", path); }+ return fallback;+ }+ std::wstring key = std::wstring(path) + L"|" + std::to_wstring(fa.ftLastWriteTime.dwLowDateTime);+ if (key == lastKey) return lastDark;+ lastKey = key;+ lastDark = fallback;+ IWICImagingFactory* wic = nullptr;+ HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic));+ if (FAILED(hr)) { Log(L"barra de menus: WIC indisponível (0x%08X)", (unsigned)hr); return fallback; }+ IWICBitmapDecoder* dec = nullptr; IWICBitmapFrameDecode* fr = nullptr; IWICBitmapScaler* sc = nullptr; IWICFormatConverter* cv = nullptr;+ const UINT W = 96, H = 54;+ int step = 0;+ if (++step, SUCCEEDED(hr = wic->CreateDecoderFromFilename(path, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &dec)) && (++step, SUCCEEDED(hr = dec->GetFrame(0, &fr))) &&+ (++step, SUCCEEDED(hr = wic->CreateBitmapScaler(&sc))) && (++step, SUCCEEDED(hr = sc->Initialize(fr, W, H, WICBitmapInterpolationModeFant))) &&+ (++step, SUCCEEDED(hr = wic->CreateFormatConverter(&cv))) && (++step, SUCCEEDED(hr = cv->Initialize(sc, GUID_WICPixelFormat32bppBGRA, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeCustom)))) {+ std::vector<BYTE> px(W * 3 * 4); // as 3 primeiras linhas (~5% de cima, onde fica a barra)+ WICRect top{ 0, 0, (INT)W, 3 };+ if (SUCCEEDED(hr = cv->CopyPixels(&top, W * 4, (UINT)px.size(), px.data()))) {+ double sum = 0, sr = 0, sg = 0, sb = 0;+ for (UINT i = 0; i < W * 3; i++) {+ sum += (0.0722 * px[i * 4] + 0.7152 * px[i * 4 + 1] + 0.2126 * px[i * 4 + 2]) / 255.0;+ sb += px[i * 4] / 255.0; sg += px[i * 4 + 1] / 255.0; sr += px[i * 4 + 2] / 255.0;+ }+ double luma = sum / (W * 3);+ lastRGB[0] = (float)(sr / (W * 3)); lastRGB[1] = (float)(sg / (W * 3)); lastRGB[2] = (float)(sb / (W * 3));+ // Tahoe: adaptação com histerese do vidro do macOS 26 (glassLumaHysteresisRange, guia seção 2.1): acima de+ // 0,60 vira texto escuro, abaixo de 0,40 texto claro, entre os dois fica como estava. Sequoia: limiar 0,72.+ static int adapt = -1; // -1 ainda não decidido, 0 texto claro, 1 texto escuro+ if (liquid::On()) {+ if (luma > 0.60) adapt = 1; else if (luma < 0.40) adapt = 0; else if (adapt < 0) adapt = luma >= 0.5 ? 1 : 0;+ lastDark = adapt == 0;+ } else lastDark = luma < 0.72; // o Mac só usa texto escuro sobre fundo bem claro+ Log(L"barra de menus: topo do papel de parede com claridade %.2f -> texto %ls", luma, lastDark ? L"branco" : L"preto");+ }+ }+ else Log(L"barra de menus: não deu para ler o papel de parede (etapa %d, 0x%08X)", step, (unsigned)hr);+ if (cv) cv->Release(); if (sc) sc->Release(); if (fr) fr->Release(); if (dec) dec->Release();+ wic->Release();+ return lastDark;+}++void Render() {+ if (!g_bar) return;+ HWND bar = Cur();+ g_s.hwnd = bar;+ RECT rc; GetClientRect(bar, &rc);+ float sc = ui::Scale(bar);+ auto* rt = ui::Begin(g_s, rc.right, rc.bottom, sc);+ if (!rt) return;+ float W = rc.right / sc, H = rc.bottom / sc;+ bool dark = ui::Dark();+ // sem fundo, ou no Tahoe (o vidro da barra é tão leve que o papel de parede aparece quase inteiro):+ // a cor do texto e dos ícones segue o papel de parede atrás+ const bool bgOn0 = BarBackground();+ if (!bgOn0 || liquid::On()) dark = WallpaperTopDark(dark);+ const bool leo = liquid::Leopard();+ // Leopard: Lucida Grande 14 px no Mac; no Windows, a Lucida Sans Unicode (o mesmo desenho de origem)+ static IDWriteTextFormat* tfLeo = ui::FormatFace(L"Lucida Sans Unicode", 14, DWRITE_FONT_WEIGHT_NORMAL);+ static IDWriteTextFormat* tfLeoB = ui::FormatFace(L"Lucida Sans Unicode", 14, DWRITE_FONT_WEIGHT_BOLD);+ IDWriteTextFormat* tfN = leo ? tfLeo : g_tf;+ IDWriteTextFormat* tfB = leo ? tfLeoB : g_tfBold;+ if (leo) dark = false; // Leopard: a barra é sempre clara, com texto preto (o 10.5 não tinha modo escuro)+ // Menubar Image do macOS 26 (guia, seção 31: catálogos Aqua/DarkAqua): branco 90 % no escuro, preto 85 % no claro+ D2D1_COLOR_F fgc = dark ? D2D1::ColorF(1, 1, 1, liquid::On() ? 0.90f : 0.92f) : D2D1::ColorF(0, 0, 0, 0.85f);+ // Liquid Glass sem fundo: só branco ou preto, mais firmes. Antes puxava a cor do papel de parede saturada 3×+ // (a "vibrancy" do Mac) e em papel de parede azul o texto e os ícones ficavam ciano.+ if (liquid::On() && !bgOn0) fgc = dark ? D2D1::ColorF(1, 1, 1, 0.96f) : D2D1::ColorF(0, 0, 0, 0.90f);+ ID2D1SolidColorBrush* br = nullptr;+ bool liquid = backdrop::Liquid(), bgOn = BarBackground();+ D2D1_COLOR_F veil = dark ? D2D1::ColorF(0.06f, 0.06f, 0.07f, 0.18f) : D2D1::ColorF(1, 1, 1, 0.26f);+ if (liquid) veil.a = backdrop::Current().tinted ? veil.a : veil.a * 0.35f;+ if (!bgOn || leo) veil.a = 0; // sem fundo (Tahoe): só o papel de parede atrás; Leopard: o degradê do Render é o fundo todo+ rt->CreateSolidColorBrush(veil, &br);+ rt->FillRectangle(D2D1::RectF(0, 0, W, H), br); // tinta leve por cima do acrílico+ if (leo) {+ // Leopard: a barra de menus translúcida do 10.5 — branco leitoso que deixa o papel de parede passar um pouco,+ // um tom mais cinza embaixo, o fio de luz no alto e a linha escura embaixo (a "sombra" da barra)+ float px = 1 / sc;+ // medido numa captura do 10.5 a 1x: 248 no alto -> 204 embaixo, a linha de baixo quase preta+ // Aparência > "Barra de menus translúcida" desligada (o 10.5.2 trouxe a opção): opaca+ const float op = shell::Setting(L"barra_translucida", L"1") == L"1" ? 1.f : 1.12f;+ // translúcida: ~72 % de branco (o papel de parede passa nítido, como nas capturas do 10.5); opaca: cheia+ const float a0 = op > 1 ? 1.f : 0.74f, a1 = op > 1 ? 1.f : 0.70f;+ D2D1_GRADIENT_STOP st[2] = { { 0, D2D1::ColorF(248 / 255.f, 248 / 255.f, 248 / 255.f, a0) }, { 1, D2D1::ColorF(214 / 255.f, 214 / 255.f, 214 / 255.f, a1) } };+ ID2D1GradientStopCollection* gs = nullptr; ID2D1LinearGradientBrush* lb = nullptr;+ if (SUCCEEDED(rt->CreateGradientStopCollection(st, 2, &gs)) &&+ SUCCEEDED(rt->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, 0 }, { 0, H }), gs, &lb)))+ rt->FillRectangle(D2D1::RectF(0, 0, W, H), lb);+ if (lb) lb->Release();+ if (gs) gs->Release();+ br->SetColor(D2D1::ColorF(1, 1, 1, 0.75f));+ rt->FillRectangle(D2D1::RectF(0, 0, W, px), br);+ br->SetColor(D2D1::ColorF(0, 0, 0, 0.62f));+ rt->FillRectangle(D2D1::RectF(0, H - px, W, H), br);+ }+ if (liquid && bgOn) { // Liquid Glass: sem degradê branco; só um fio fraco embaixo, como no Tahoe+ float px = 1 / sc;+ br->SetColor(D2D1::ColorF(1, 1, 1, dark ? 0.08f : 0.18f));+ rt->FillRectangle(D2D1::RectF(0, H - px, W, H), br);+ }+ g_hits.clear();+ // Embaixo, o meio da linha é do Dock: o que é da esquerda acaba em limE e o da direita começa em limD+ float limE = W, limD = 0;+ if (g_vaoD > g_vaoE && bar == g_bar) { limE = g_vaoE / sc - 6; limD = g_vaoD / sc + 6; }+ bool litNow = false; // Leopard: o item aceso fica com o texto branco sobre o azul+ auto highlight = [&](D2D1_RECT_F r) {+ if (leo) { // Leopard: o destaque azul do Aqua de ponta a ponta na altura da barra, sem cantos+ litNow = true;+ D2D1_GRADIENT_STOP st[2] = { { 0, D2D1::ColorF(0.39f, 0.56f, 0.95f, 1) }, { 1, D2D1::ColorF(0.13f, 0.35f, 0.86f, 1) } };+ ID2D1GradientStopCollection* gs = nullptr; ID2D1LinearGradientBrush* lb = nullptr;+ if (SUCCEEDED(rt->CreateGradientStopCollection(st, 2, &gs)) &&+ SUCCEEDED(rt->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, 0 }, { 0, H }), gs, &lb)))+ rt->FillRectangle(D2D1::RectF(r.left, 0, r.right, H - 1 / sc), lb);+ if (lb) lb->Release();+ if (gs) gs->Release();+ return;+ }+ if (liquid::On()) { // Tahoe (vídeo do macOS 26): o item aberto ganha uma cápsula de vidro clara+ br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.24f) : D2D1::ColorF(1, 1, 1, 0.55f));+ float rad = (H - 4) / 2;+ rt->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(r.left + 1, 2, r.right - 1, H - 2), rad, rad), br);+ br->SetColor(D2D1::ColorF(1, 1, 1, dark ? 0.18f : 0.45f)); // o fio de luz da borda+ rt->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(r.left + 1.5f, 2.5f, r.right - 1.5f, H - 2.5f), rad - 0.5f, rad - 0.5f), br, 0.8f);+ return;+ }+ br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.20f) : D2D1::ColorF(0, 0, 0, 0.10f));+ rt->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(r.left, 2, r.right, H - 2), 4, 4), br);+ };+ auto add = [&](D2D1_RECT_F r, Kind k, int i) {+ litNow = false;+ g_hits.push_back({ r, k, i });+ bool lit = (k == K_SOUND && (som::IsOpen() || som::HudLit())) // menu Som aberto / aviso de volume do Tahoe+ || (k == K_CC && central::IsOpen()) || (k == K_CLOCK && (notificacoes::IsOpen() || (liquid::On() && notificacoes::BannerVisible()))) || (k == K_SPOT && spotlight::IsOpen()) || (k == K_SIRI && siri::Aberta());+ if (lit || ((int)g_hits.size() - 1 == g_open && bar == g_openBar)) highlight(r);+ };++ // esquerda (Tahoe, guia seção 35: o menu Apple fica em x 10, com 34 de largura)+ float x = liquid::On() ? 10.f : 8.f;+ add(D2D1::RectF(x, 0, x + 34, H), K_LOGO, 0);+ br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);+ if (leo && !litNow) {+ // Leopard: a maçã grafite brilhante do 10.5 (a azul era a do Tiger): cinza claro em cima, quase preto embaixo;+ // aberta, fica branca+ D2D1_GRADIENT_STOP st[3] = { { 0, D2D1::ColorF(0.62f, 0.62f, 0.63f, 1) }, { 0.45f, D2D1::ColorF(0.36f, 0.36f, 0.37f, 1) }, { 1, D2D1::ColorF(0.16f, 0.16f, 0.17f, 1) } };+ ID2D1GradientStopCollection* gs = nullptr; ID2D1LinearGradientBrush* lb = nullptr;+ bool ok = SUCCEEDED(rt->CreateGradientStopCollection(st, 3, &gs)) &&+ SUCCEEDED(rt->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, H / 2 - 7.5f }, { 0, H / 2 + 6.5f }), gs, &lb));+ if (!ok || !simbolo::Draw(rt, L"apple.logo", D2D1::RectF(x + 10, H / 2 - 7.5f, x + 24, H / 2 + 6.5f), lb)) {+ br->SetColor(D2D1::ColorF(0.30f, 0.30f, 0.31f, 1));+ DrawLogo(rt, br, x + 17, H / 2);+ }+ if (lb) lb->Release();+ if (gs) gs->Release();+ } else+ if (!simbolo::Draw(rt, L"apple.logo", D2D1::RectF(x + 10, H / 2 - 7.5f, x + 24, H / 2 + 6.5f), (br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc), br))) // a maçã do SF Symbols+ DrawLogo(rt, br, x + 17, H / 2);+ x += 34;+ if (float w = ui::TextWidth(tfB, g_appName) + 20; x + w <= limE) {+ add(D2D1::RectF(x, 0, x + w, H), K_APP, 0);+ br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);+ rt->DrawTextW(g_appName.c_str(), (UINT32)g_appName.size(), tfB, D2D1::RectF(x + 10, 0, x + w, H), br);+ x += w;+ }+ float leftEnd = x;++ // direita (da borda para dentro), na ordem do Mac: relógio, Central de Controle, Spotlight, fonte de+ // entrada, Wi-Fi, bateria, som, Bluetooth, ícones fixados dos apps e a setinha dos guardados.+ // Cada item é o símbolo com 10 pt de cada lado (no Mac fica um a cada ~38 pt).+ float r = W - 10;+ auto slot = [&](float iconW, Kind k, int i) { // reserva o espaço e devolve a caixa do símbolo+ float w = iconW + 2 * PAD;+ if (r - w < limD) return D2D1::RectF(-1000, 0, -1000 + iconW, H); // o Dock ocupa o lugar: fica de fora (nem clique)+ add(D2D1::RectF(r - w, 0, r, H), k, i);+ D2D1_RECT_F box = D2D1::RectF(r - w + PAD, 0, r - PAD, H);+ r -= w;+ br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);+ return box;+ };+ auto sym = [&](const wchar_t* name, D2D1_RECT_F box, float h) {+ return simbolo::Draw(rt, name, D2D1::RectF(box.left, H / 2 - h / 2, box.right, H / 2 + h / 2), br);+ };+ // Leopard (captura do 10.5): a lupa do Spotlight é o último item, na ponta direita, e o relógio vem antes dela;+ // (a Central de Controle continua, à esquerda do relógio: o usuário quer o acesso a ela)+ if (leo && shell::Setting(L"barra_spotlight", L"1") == L"1") {+ auto bx = slot(15, K_SPOT, 0);+ if (!sym(L"magnifyingglass", bx, 15)) rt->DrawTextW(L"", 1, g_tfIcon, bx, br);+ }+ {+ std::wstring t = ClockText();+ float w = ui::TextWidth(tfN, t) + 2 * PAD;+ if (r - w - (18 + 2 * PAD) < limD) { // embaixo com pouco espaço: só a hora, para a Central de Controle caber+ SYSTEMTIME st; GetLocalTime(&st);+ wchar_t hm[16]; swprintf_s(hm, L"%02d:%02d", st.wHour, st.wMinute);+ t = hm; w = ui::TextWidth(tfN, t) + 2 * PAD;+ }+ add(D2D1::RectF(r - w, 0, r, H), K_CLOCK, 0);+ br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);+ rt->DrawTextW(t.c_str(), (UINT32)t.size(), tfN, D2D1::RectF(r - w + PAD, 0, r, H), br);+ r -= w;+ }+ // microfone/câmera em uso (issue #8, todos os temas): como no macOS, uma bolinha de 6 pt no vão entre a Central de+ // Controle e a data/hora: laranja = microfone, verde = câmera (a câmera ganha). barra_privacidade=0 tira.+ if (shell::Setting(L"barra_privacidade", L"1") != L"0")+ if (int pv = ilha::Privacidade()) {+ br->SetColor(pv & 2 ? D2D1::ColorF(0.20f, 0.78f, 0.35f) : D2D1::ColorF(1.0f, 0.58f, 0.0f));+ rt->FillEllipse(D2D1::Ellipse({ r, H / 2 }, 3, 3), br); // no meio do vão (os dois PAD): nada anda de lugar+ }+ // a Siri entre o relógio e a Central de Controle, como no macOS (só com um serviço escolhido; barra_siri=0 tira)+ if (siri::Pronta() && shell::Setting(L"barra_siri", L"1") != L"0") {+ auto bx = slot(16, K_SIRI, 0);+ float cx = (bx.left + bx.right) / 2, r = 7.f;+ D2D1_GRADIENT_STOP gs[3] = { { 0, D2D1::ColorF(0.98f, 0.36f, 0.62f) }, { 0.5f, D2D1::ColorF(0.62f, 0.38f, 1.f) }, { 1, D2D1::ColorF(0.25f, 0.62f, 1.f) } };+ ID2D1GradientStopCollection* gsc = nullptr; ID2D1LinearGradientBrush* lg = nullptr;+ if (SUCCEEDED(rt->CreateGradientStopCollection(gs, 3, &gsc)) &&+ SUCCEEDED(rt->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ cx - r, H / 2 - r }, { cx + r, H / 2 + r }), gsc, &lg)))+ rt->FillEllipse(D2D1::Ellipse({ cx, H / 2 }, r, r), lg);+ if (lg) lg->Release();+ if (gsc) gsc->Release();+ }+ { auto bx = slot(18, K_CC, 0); if (!sym(L"switch.2", bx, 14)) DrawCC(rt, br, (bx.left + bx.right) / 2, H / 2); }+ if (!leo && shell::Setting(L"barra_spotlight", L"1") == L"1") {+ auto bx = slot(15, K_SPOT, 0);+ if (!sym(L"magnifyingglass", bx, 15)) rt->DrawTextW(L"", 1, g_tfIcon, bx, br);+ }+ if (shell::Setting(L"barra_teclado", L"1") == L"1") { // fonte de entrada: a sigla num quadradinho (como o "A" do ABC)+ std::wstring t = InputBadge(g_st.hkl);+ float tw = std::max(15.f, ui::TextWidth(g_tfBadge, t) + 7);+ auto bx = slot(tw, K_INPUT, 0);+ D2D1_RECT_F k = D2D1::RectF(bx.left, H / 2 - 7.5f, bx.right, H / 2 + 7.5f);+ rt->FillRoundedRectangle(D2D1::RoundedRect(k, 3.5f, 3.5f), br);+ br->SetColor(dark ? D2D1::ColorF(0.13f, 0.13f, 0.14f) : D2D1::ColorF(0.96f, 0.96f, 0.96f));+ rt->DrawTextW(t.c_str(), (UINT32)t.size(), g_tfBadge, D2D1::RectF(k.left, k.top - 0.5f, k.right, k.bottom - 0.5f), br);+ }+ // como no Mac: só quem tem Wi-Fi; no cabo, o Wi-Fi desconectado não aparece+ if (g_st.wlan && (g_st.wifiOn || !g_st.wired) && shell::Setting(L"barra_wifi", L"1") == L"1") {+ auto bx = slot(18, K_NET, 0);+ if (!sym(g_st.wifiOn ? L"wifi" : L"wifi.slash", bx, 14)) rt->DrawTextW(L"", 1, g_tfIcon, bx, br);+ }+ if (g_st.batt && shell::Setting(L"barra_bateria", L"1") == L"1") {+ const wchar_t* name = g_st.charging ? L"battery.100percent.bolt" : g_st.pct > 87 ? L"battery.100percent" : g_st.pct > 62 ? L"battery.75percent"+ : g_st.pct > 37 ? L"battery.50percent" : g_st.pct > 12 ? L"battery.25percent" : L"battery.0percent";+ if (liquid::Golden()) {+ // macOS 27 (vídeo do MacVince, 2:44): a porcentagem DENTRO do ícone — corpo cheio de 25 × 12 com canto 4,+ // o número vazado (e o raio quando carrega) e a ponta à direita+ auto bx = slot(29, K_BATT, 0);+ float cy = H / 2;+ D2D1_RECT_F body = D2D1::RectF(bx.left, cy - 6, bx.left + 25, cy + 6);+ rt->FillRoundedRectangle(D2D1::RoundedRect(body, 4, 4), br);+ rt->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(body.right + 1, cy - 2.5f, body.right + 2.8f, cy + 2.5f), 1, 1), br);+ static IDWriteTextFormat* tfB = ui::Format(9.5f, DWRITE_FONT_WEIGHT_BOLD, false, DWRITE_TEXT_ALIGNMENT_CENTER);+ wchar_t num[8]; swprintf_s(num, L"%d", std::clamp(g_st.pct, 0, 100));+ br->SetColor(dark ? D2D1::ColorF(0.15f, 0.13f, 0.12f, 0.92f) : D2D1::ColorF(1, 1, 1, 0.95f));+ D2D1_RECT_F tr = D2D1::RectF(body.left, body.top - 0.5f, body.right - (g_st.charging ? 6.f : 0.f), body.bottom - 0.5f);+ if (tfB) { tfB->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER); rt->DrawTextW(num, (UINT32)wcslen(num), tfB, tr, br); }+ if (g_st.charging) { // raio+ float bx0 = body.right - 6.5f;+ ID2D1PathGeometry* g = nullptr;+ if (SUCCEEDED(ui::d2d->CreatePathGeometry(&g))) {+ ID2D1GeometrySink* sk = nullptr; g->Open(&sk);+ sk->BeginFigure({ bx0 + 2.6f, cy - 4.5f }, D2D1_FIGURE_BEGIN_FILLED);+ D2D1_POINT_2F pts[] = { { bx0, cy + 0.6f }, { bx0 + 1.9f, cy + 0.6f }, { bx0 + 1.1f, cy + 4.5f }, { bx0 + 3.8f, cy - 0.8f }, { bx0 + 1.9f, cy - 0.8f } };+ sk->AddLines(pts, 5); sk->EndFigure(D2D1_FIGURE_END_CLOSED); sk->Close(); sk->Release();+ rt->FillGeometry(g, br);+ g->Release();+ }+ }+ br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);+ } else {+ auto bx = slot(27, K_BATT, 0);+ sym(name, bx, 13);+ }+ }+ // Som e Bluetooth: no Mac ficam fora da barra por padrão (Ajustes > Central de Controle liga)+ if (g_st.sound && shell::Setting(L"barra_som", L"0") == L"1") {+ const wchar_t* name = g_st.muted ? L"speaker.slash.fill" : g_st.phones ? L"headphones" : g_st.vol < 0.01f ? L"speaker.fill"+ : g_st.vol < 0.34f ? L"speaker.wave.1.fill" : g_st.vol < 0.67f ? L"speaker.wave.2.fill" : L"speaker.wave.3.fill";+ auto bx = slot(g_st.phones ? 16 : 21, K_SOUND, 0);+ sym(name, bx, g_st.phones ? 16 : 14);+ }+ if (g_st.bt && shell::Setting(L"barra_bluetooth", L"0") == L"1") { // o símbolo do Bluetooth do Mac (não está no SF Symbols público)+ auto bx = slot(9, K_BT, 0);+ float cx = (bx.left + bx.right) / 2, cy = H / 2, hh = 7.2f, ww = 3.9f;+ ID2D1PathGeometry* g = nullptr;+ if (SUCCEEDED(ui::d2d->CreatePathGeometry(&g))) {+ ID2D1GeometrySink* sk = nullptr; g->Open(&sk);+ sk->BeginFigure({ cx - ww, cy - hh * 0.48f }, D2D1_FIGURE_BEGIN_HOLLOW);+ D2D1_POINT_2F pts[] = { { cx + ww, cy + hh * 0.48f }, { cx, cy + hh }, { cx, cy - hh }, { cx + ww, cy - hh * 0.48f }, { cx - ww, cy + hh * 0.48f } };+ sk->AddLines(pts, 5); sk->EndFigure(D2D1_FIGURE_END_OPEN); sk->Close(); sk->Release();+ ID2D1StrokeStyle* st = nullptr;+ ui::d2d->CreateStrokeStyle(D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_ROUND), nullptr, 0, &st);+ rt->DrawGeometry(g, br, 1.5f, st);+ if (st) st->Release();+ g->Release();+ }+ }+ UINT px = (UINT)std::lround(17 * sc);+ for (int i = (int)tray::icons.size() - 1; i >= 0; i--) {+ auto& t = tray::icons[i];+ if (t.hidden || !t.icon || !IsShown(t) || tray::IsPrivacy(t)) continue; // o do Windows: vira a bolinha+ if (r - 37 < (limD > 0 ? limD + 34 : leftEnd + 60)) { g_overflow = true; break; } // sem espaço: some, como no Mac (macOS 27: aparece a »)+ auto bx = slot(17, K_TRAY, i);+ std::vector<BYTE> mono = IconPixels(t.icon, px);+ // como os ícones-modelo do Mac: uma cor só, a mesma do texto da barra (branco no escuro, preto no claro);+ // o desenho de dentro (ícone de fundo cheio: Discord, WhatsApp) sai pela transparência, nunca por cinza+ // ou pela cor do original, que deixava o ícone azulado/acinzentado em cima do papel de parede.+ float lmin = 1, lmax = 0;+ for (size_t k = 0; k < mono.size(); k += 4) {+ float a = mono[k + 3] / 255.f;+ if (a < 0.5f) continue;+ float l = std::clamp((0.2126f * mono[k + 2] + 0.7152f * mono[k + 1] + 0.0722f * mono[k]) / 255.f / a, 0.f, 1.f);+ lmin = std::min(lmin, l); lmax = std::max(lmax, l);+ }+ bool detail = lmax - lmin > 0.25f; // tem desenho de dentro (senão é só a silhueta)+ BYTE ink = dark ? 255 : 0;+ for (size_t k = 0; k < mono.size(); k += 4) {+ float a = mono[k + 3] / 255.f;+ if (a <= 0.004f) { mono[k] = mono[k + 1] = mono[k + 2] = mono[k + 3] = 0; continue; }+ float oa = a;+ if (detail) {+ float l = std::clamp((0.2126f * mono[k + 2] + 0.7152f * mono[k + 1] + 0.0722f * mono[k]) / 255.f / a, 0.f, 1.f);+ float t = std::clamp((l - lmin) / (lmax - lmin), 0.f, 1.f); // 0 = parte mais escura do original+ oa = a * (dark ? 0.30f + 0.70f * t : 1.f - 0.70f * t);+ }+ oa *= dark ? 0.96f : 0.88f;+ BYTE c = (BYTE)std::lround(ink * oa);+ mono[k] = mono[k + 1] = mono[k + 2] = c;+ mono[k + 3] = (BYTE)std::lround(oa * 255);+ }+ if (ID2D1Bitmap* bmp = ui::Bitmap(rt, px, px, mono)) {+ // no pixel inteiro (1:1 com o bitmap): fora da grade o bitmap era reamostrado e borrava/serrilhava+ float cxp = (bx.left + bx.right) / 2 * sc, cyp = H / 2 * sc;+ float l0 = std::round(cxp - px / 2.f) / sc, t0 = std::round(cyp - px / 2.f) / sc;+ rt->DrawBitmap(bmp, D2D1::RectF(l0, t0, l0 + px / sc, t0 + px / sc), 1, D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR);+ bmp->Release();+ }+ }+ bool anyHidden = false;+ for (auto& t : tray::icons) if (!t.hidden && t.icon && !IsShown(t) && !tray::IsPrivacy(t)) anyHidden = true;+ if (liquid::Golden() && (g_overflow || anyHidden)) {+ // macOS 27 (vídeo, 2:16): quando os ícones não cabem, uma seta dupla » mostra os escondidos+ auto bx = slot(14, K_MORE, 0);+ float cx = (bx.left + bx.right) / 2, cy = H / 2;+ for (int k = 0; k < 2; k++) {+ float ox = cx - 3.5f + k * 5.5f;+ rt->DrawLine({ ox - 2.2f, cy - 4.5f }, { ox + 2.2f, cy }, br, 1.5f);+ rt->DrawLine({ ox + 2.2f, cy }, { ox - 2.2f, cy + 4.5f }, br, 1.5f);+ }+ anyHidden = false; // já desenhada+ }+ g_overflow = false;+ // setinha dos ícones guardados: não existe no Mac, desligada por padrão (barra_seta=1 liga); a lista abre+ // também no botão direito da Central de Controle+ if (anyHidden && shell::Setting(L"barra_seta", L"0") == L"1") { // setinha dos ícones guardados: o chevron do SF Symbols, apontando para onde eles abrem+ auto bx = slot(8, K_MORE, 0);+ if (!sym(L"chevron.left", bx, 12)) {+ float cx = (bx.left + bx.right) / 2, cy = H / 2;+ rt->DrawLine({ cx + 2, cy - 5 }, { cx - 2.5f, cy }, br, 1.6f);+ rt->DrawLine({ cx - 2.5f, cy }, { cx + 2, cy + 5 }, br, 1.6f);+ }+ }++ // menus do app (entre o nome e os ícones)+ for (int i = 0; i < (int)g_titles.size(); i++) {+ float w = ui::TextWidth(tfN, g_titles[i]) + 20;+ if (x + w > std::min(r - 8, limE)) break;+ add(D2D1::RectF(x, 0, x + w, H), K_MENU, i);+ br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);+ rt->DrawTextW(g_titles[i].c_str(), (UINT32)g_titles[i].size(), tfN, D2D1::RectF(x + 10, 0, x + w, H), br);+ x += w;+ }+ br->Release();+ ui::End(g_s, false);+}++// ---- menus+// Menus próprios, como os do app no Mac, para os apps sem menu Win32 (os itens mandam o atalho do Windows do+// app). Ids: atalhos de g_keyCmds; 0 = separador. No "Janela" os itens vêm antes da lista de janelas.+struct MenuDef { const wchar_t* title; std::vector<int> ids; };+const std::vector<MenuDef>* AppMenus(App* app) {+ static const std::vector<MenuDef> browser = {+ { L"Arquivo", { 1020, 1001, 5001, 5002, 0, 5003, 5004, 0, 5005, 5006, 5007, 0, 1005 } },+ { L"Editar", { 1010, 5070, 0, 1012, 1013, 1014, 1015, 0, 1016 } },+ { L"Visualizar", { 5010, 0, 5011, 5012, 5013, 0, 5014, 5015, 5016, 5017, 0, 5018, 5019 } },+ { L"Histórico", { 5020, 1040, 1041, 0, 5021, 5022 } },+ { L"Favoritos", { 5030, 0, 5031, 5032 } },+ { L"Aba", { 5040, 5041 } },+ { L"Janela", { 5050, 5051 } },+ { L"Ajuda", { 5060 } },+ };+ static const std::vector<MenuDef> discord = {+ { L"Editar", { 1010, 5070, 0, 1012, 1013, 1014, 1015 } },+ { L"Visualizar", { 5071, 5072, 0, 5015, 5016, 5017 } },+ { L"Janela", {} },+ { L"Ajuda", { 5073 } },+ };+ static const std::vector<MenuDef> whatsapp = {+ { L"Arquivo", { 5080, 5081, 0, 1003 } },+ { L"Editar", { 1010, 1011, 0, 1012, 1013, 1014, 1015, 0, 1016 } },+ { L"Visualizar", { 5015, 5016, 5017 } },+ { L"Janela", {} },+ { L"Ajuda", {} },+ };+ static const std::vector<MenuDef> electron = { // Claude e afins: editar e zoom (o padrão do Electron)+ { L"Arquivo", { 1001, 0, 1003 } },+ { L"Editar", { 1010, 5070, 0, 1012, 1013, 1014, 1015 } },+ { L"Visualizar", { 5071, 0, 5015, 5016, 5017 } },+ { L"Janela", {} },+ { L"Ajuda", {} },+ };+ // o programa da janela ativa (o App do Chrome casa pelo AUMID e pode vir sem o .exe)+ static HWND s_fg; static std::wstring s_path; // a barra pergunta a cada atualização: lido uma vez por janela+ std::wstring path = app ? app->exe : L"";+ DWORD pid = 0;+ if (g_fg && g_fg == s_fg) { if (!s_path.empty()) path = s_path; }+ else if (g_fg && GetWindowThreadProcessId(g_fg, &pid) && pid) {+ s_fg = g_fg; s_path.clear();+ if (HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid)) {+ wchar_t buf[MAX_PATH]; DWORD n = MAX_PATH;+ if (QueryFullProcessImageNameW(p, 0, buf, &n)) path = s_path = buf;+ CloseHandle(p);+ }+ }+ if (path.empty()) return nullptr;+ std::wstring n = path.substr(path.find_last_of(L"\\/") + 1);+ for (auto& c : n) c = towlower(c);+ if (n == L"chrome.exe" || n == L"msedge.exe" || n == L"brave.exe" || n == L"vivaldi.exe") return &browser;+ if (n == L"discord.exe" || n == L"discordptb.exe" || n == L"discordcanary.exe") return &discord;+ if (n.find(L"whatsapp") != std::wstring::npos) return &whatsapp;+ if (n == L"claude.exe") return &electron;+ static const std::vector<MenuDef> spotify = {+ { L"Arquivo", { 5100, 0, 1003 } },+ { L"Editar", { 1010, 1011, 0, 1012, 1013, 1014, 1015, 0, 5108 } },+ { L"Visualizar", { 5015, 5016, 5017 } },+ { L"Reprodução", { 5101, 5102, 5103, 0, 5104, 5105, 0, 5106, 5107 } },+ { L"Janela", {} },+ { L"Ajuda", {} },+ };+ static const std::vector<MenuDef> vscode = {+ { L"Arquivo", { 5120, 5121, 0, 1002, 0, 1004, 5122, 0, 5123 } },+ { L"Editar", { 1010, 1011, 0, 1012, 1013, 1014, 0, 1016, 5124, 0, 5125 } },+ { L"Seleção", { 1015 } },+ { L"Visualizar", { 5126, 0, 5127, 5125, 5128, 5129, 0, 5134, 0, 5016, 5017, 5015 } },+ { L"Ir", { 5130, 5131 } },+ { L"Executar", { 5132, 5133 } },+ { L"Janela", {} },+ { L"Ajuda", {} },+ };+ if (n == L"spotify.exe") return &spotify;+ if (n == L"code.exe" || n == L"cursor.exe" || n == L"code - insiders.exe") return &vscode;+ return nullptr;+}++std::vector<std::wstring> GenericTitles(App* app) {+ if (!g_finderActive)+ if (auto* defs = AppMenus(app)) {+ std::vector<std::wstring> t;+ for (auto& d : *defs) t.push_back(Tr(d.title));+ return t;+ }+ if (g_finderActive) return { Tr(L"Arquivo"), Tr(L"Editar"), Tr(L"Visualizar"), Tr(L"Ir"), Tr(L"Janela"), Tr(L"Ajuda") };+ return { Tr(L"Arquivo"), Tr(L"Editar"), Tr(L"Janela"), Tr(L"Ajuda") };+}++std::vector<ctxmenu::Item> GenericMenu(const std::wstring& title, App* app) {+ std::vector<ctxmenu::Item> pre; // Janela: itens do app antes dos comuns (minimizar, zoom, lista de janelas)+ if (auto* defs = g_finderActive ? nullptr : AppMenus(app))+ for (auto& d : *defs) {+ if (title != Tr(d.title)) continue;+ std::vector<ctxmenu::Item> v;+ for (int id : d.ids) v.push_back(id ? K(id) : Sep());+ if (title != Tr(L"Janela")) {+ if (v.empty()) v.push_back(I(Tr(L"Nenhum item"), 0, true));+ return v;+ }+ if (!v.empty()) { pre = v; pre.push_back(Sep()); }+ break;+ }+ if (title == Tr(L"Arquivo")) {+ if (g_finderActive) return { K(1001), K(1020), K(1021), Sep(), K(1002), K(1003), Sep(), K(1022), Sep(), K(1023) };+ return { K(1001), K(1002), Sep(), K(1003), K(1004), Sep(), K(1005) };+ }+ if (title == Tr(L"Editar")) return { K(1010), K(1011), Sep(), K(1012), K(1013), K(1014), K(1015), Sep(), K(1016) };+ if (title == Tr(L"Visualizar")) return { K(1030), K(1031), K(1032), K(1033), Sep(), K(1034) };+ if (title == Tr(L"Ir")) return { K(1040), K(1041), K(1042), Sep(), K(1043), Sep(), I(Tr(L"Recentes"), 1100), I(Tr(L"Documentos"), 1101), I(Tr(L"Mesa"), 1102), I(Tr(L"Downloads"), 1103), I(Tr(L"Início"), 1104), I(Tr(L"Este Computador"), 1105), I(Tr(L"Aplicativos"), 1106) };+ if (title == Tr(L"Janela")) {+ std::vector<ctxmenu::Item> v{ I(Tr(L"Minimizar"), 1200), I(Tr(L"Zoom"), 1201), Sep(), I(Tr(L"Trazer Tudo para a Frente"), 1202) };+ v.insert(v.begin(), pre.begin(), pre.end());+ if (app && !app->wins.empty()) {+ v.push_back(Sep());+ for (int k = 0; k < (int)app->wins.size() && k < 20; k++) {+ auto it = I(app->wins[k].title, 3000 + k);+ it.checked = app->wins[k].hwnd == g_fg;+ v.push_back(it);+ }+ }+ return v;+ }+ if (title == Tr(L"Ajuda")) return { K(1050) };+ return {};+}++std::vector<ctxmenu::Item> LogoMenu() {+ std::vector<ctxmenu::Item> recent;+ { // Itens Recentes: os atalhos mais novos de shell:Recent+ PWSTR p = nullptr;+ if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Recent, 0, nullptr, &p))) {+ std::wstring dir = p; CoTaskMemFree(p);+ std::vector<std::pair<ULONGLONG, std::wstring>> files;+ WIN32_FIND_DATAW fd;+ HANDLE h = FindFirstFileW((dir + L"\\*.lnk").c_str(), &fd);+ if (h != INVALID_HANDLE_VALUE) {+ do files.push_back({ ((ULONGLONG)fd.ftLastWriteTime.dwHighDateTime << 32) | fd.ftLastWriteTime.dwLowDateTime, dir + L"\\" + fd.cFileName });+ while (FindNextFileW(h, &fd));+ FindClose(h);+ }+ std::sort(files.begin(), files.end(), [](auto& a, auto& b) { return a.first > b.first; });+ static std::vector<std::wstring> s_recent;+ s_recent.clear();+ for (size_t k = 0; k < files.size() && k < 10; k++) {+ std::wstring n = files[k].second.substr(files[k].second.find_last_of(L'\\') + 1);+ n.resize(n.size() - 4);+ s_recent.push_back(files[k].second);+ recent.push_back(I(n, 4000 + (int)k));+ }+ if (recent.empty()) recent.push_back(I(Tr(L"Nenhum item"), 0, true));+ }+ }+ wchar_t user[128] = L""; DWORD n = 128; GetUserNameW(user, &n);+ ctxmenu::Item rec = I(Tr(L"Itens Recentes"), 0); rec.sub = recent;+ return { I(Tr(L"Sobre Este Mac"), 100), Sep(), I(Tr(L"Ajustes do Sistema…"), 101), I(Tr(L"Microsoft Store…"), 102), Sep(),+ rec, Sep(), I(Tr(L"Forçar Encerrar…"), 103), Sep(), I(Tr(L"Repousar"), 104), I(Tr(L"Reiniciar…"), 105), I(Tr(L"Desligar…"), 106), Sep(),+ I(Tr(L"Bloquear Tela"), 107), I(Tr(L"Encerrar Sessão de ") + std::wstring(user) + L"…", 108), Sep(), I(Tr(L"Sair do Shell (voltar à barra do Windows)"), 109) };+}++std::vector<ctxmenu::Item> AppMenu(App* a) {+ std::wstring n = a ? a->name : g_appName;+ return { I(Tr(L"Sobre ") + n, 200), Sep(), K(1051), Sep(), I(Tr(L"Ocultar ") + n, 201), I(Tr(L"Ocultar Outros"), 202), I(Tr(L"Mostrar Tudo"), 203), Sep(), I(Tr(L"Encerrar ") + n, 204) };+}+++void Shutdown(UINT how) {+ HANDLE tok;+ if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &tok)) {+ TOKEN_PRIVILEGES tp{ 1 };+ LookupPrivilegeValueW(nullptr, SE_SHUTDOWN_NAME, &tp.Privileges[0].Luid);+ tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;+ AdjustTokenPrivileges(tok, FALSE, &tp, 0, nullptr, nullptr);+ CloseHandle(tok);+ }+ ExitWindowsEx(how, SHTDN_REASON_FLAG_PLANNED);+}++void Open(const wchar_t* what, const wchar_t* args = nullptr) {+ if (!wcsncmp(what, L"ms-settings:", 12)) { shell::OpenSettings(what); return; } // o nosso Ajustes do Sistema+ shell::Abrir(L"open", what, args, nullptr, SW_SHOWNORMAL);+}++void OpenFinder(const std::wstring& args) {+ if (shell::nativo) { shell::AbrirFinder(args); return; }+ for (auto& a : apps::list) if (a.finder) { shell::Abrir(L"open", a.launch.c_str(), args.c_str(), nullptr, SW_SHOWNORMAL); return; }+}++void Run(int id, App* app) {+ for (auto& k : g_keyCmds) if (k.id == id) { // atalho de teclado para o app ativo+ if (g_fg) SetForegroundWindow(g_fg);+ Sleep(30);+ SendKeys(k.keys);+ return;+ }+ if (id >= 1000 && id < 1100) return;+ switch (id) {+ case 100: sobre::Show(); break;+ case 101: shell::OpenSettings(L""); break;+ case 102: Open(L"ms-windows-store:"); break;+ case 103: shell::OpenForceQuit(false); break;+ case 104: SetSuspendState(FALSE, FALSE, FALSE); break;+ // como no Mac: alerta com o ícone do computador, Cancelar | Reiniciar/Desligar (antes era a caixa do Windows). O ícone é+ // o mesmo do Sobre Este Mac: o computador em alumínio (modo "este PC", o padrão) ou o Mac Studio+ case 105: alertas::Confirm(Tr(L"Tem certeza de que deseja reiniciar o computador agora?"), L"", Tr(L"Reiniciar"), [] { Shutdown(EWX_REBOOT); }, IconePC()); break;+ case 106: alertas::Confirm(Tr(L"Tem certeza de que deseja desligar o computador agora?"), L"", Tr(L"Desligar"), [] { Shutdown(EWX_POWEROFF); }, IconePC()); break;+ case 107: bloqueio::Lock(); break; // a nossa tela de bloqueio (o LockWorkStation fica desligado pela política enquanto o Shell roda: não fazia nada, issue #8)+ case 108: alertas::Confirm(Tr(L"Tem certeza de que deseja encerrar todos os aplicativos e sair agora?"), L"", Tr(L"Encerrar Sessão"), [] { ExitWindowsEx(EWX_LOGOFF, 0); }, IconePC()); break;+ case 109: shell::Quit(L"menu do logo"); break;+ case 200: if (app && !app->exe.empty()) shell::Abrir(L"properties", app->exe.c_str(), nullptr, nullptr, SW_SHOWNORMAL); break;+ case 201: if (app) apps::Hide(*app); break;+ case 202: for (auto& a : apps::list) if (&a != app) apps::Hide(a); break;+ case 203: for (auto& a : apps::list) for (auto& w : a.wins) if (w.minimized) ShowWindow(w.hwnd, SW_SHOWNOACTIVATE); break;+ case 204: if (app) apps::Quit(*app); break;+ case 1100: OpenFinder(L"shell:Recent"); break;+ case 1101: OpenFinder(L"shell:Personal"); break;+ case 1102: OpenFinder(L"shell:Desktop"); break;+ case 1103: OpenFinder(L"shell:Downloads"); break;+ case 1104: OpenFinder(L"shell:Profile"); break;+ case 1105: OpenFinder(L"shell:MyComputerFolder"); break;+ case 1106: OpenFinder(L"shell:Common Programs"); break;+ case 1200: if (g_fg) ShowWindow(g_fg, SW_MINIMIZE); break;+ case 1201: if (g_fg) ShowWindow(g_fg, IsZoomed(g_fg) ? SW_RESTORE : SW_MAXIMIZE); break;+ case 1202: if (app) apps::Activate(*app); break;+ }+ if (id >= 3000 && id < 3100 && app && id - 3000 < (int)app->wins.size()) {+ HWND w = app->wins[id - 3000].hwnd;+ if (IsIconic(w)) shell::Restaurar(w);+ SetForegroundWindow(w);+ }+}++int g_closedHit = -1; DWORD g_closedHitAt; // o título cujo menu acabou de fechar (clicar nele de novo só fecha)+void ShowAt(int hit, const std::vector<ctxmenu::Item>& items, std::function<void(int)> done) {+ g_open = hit;+ g_openBar = Cur();+ Render();+ float sc = ui::Scale(Cur());+ RECT wr; GetWindowRect(Cur(), &wr);+ POINT pt{ wr.left + (LONG)std::lround(g_hits[hit].r.left * sc), wr.bottom };+ // Tahoe (guia, seção 35): o menu abre 1 pt abaixo da barra e 4 pt à esquerda do título (o texto fica a 10 da caixa)+ if (liquid::On()) pt = { wr.left + (LONG)std::lround((g_hits[hit].r.left + 6) * sc), wr.bottom + (LONG)std::lround(sc) };+ if (Cur() == g_bar && menubar::Embaixo()) { // na linha do Dock os menus sobem, centrados no item+ pt = { wr.left + (LONG)std::lround((g_hits[hit].r.left + g_hits[hit].r.right) / 2 * sc), wr.top - (LONG)std::lround(4 * sc) };+ ctxmenu::AboveNext();+ }+ SetForegroundWindow(g_owner); // o menu fecha se a janela dona não estiver na frente+ int id = ctxmenu::ShowItems(g_owner, pt, items);+ g_closedHit = hit; g_closedHitAt = GetTickCount();+ g_open = -1;+ Render();+ if (g_fg && IsWindow(g_fg)) SetForegroundWindow(g_fg);+ if (id) done(id);+}++void Click(D2D1_POINT_2F p, bool right) {+ int hit = -1;+ for (int i = 0; i < (int)g_hits.size(); i++)+ if (p.x >= g_hits[i].r.left && p.x < g_hits[i].r.right) { hit = i; break; }+ if (hit < 0) return;+ if (!right && hit == g_closedHit && GetTickCount() - g_closedHitAt < 400) { g_closedHit = -1; return; } // clique no mesmo título: só fechou+ g_closedHit = -1;+ Hit h = g_hits[hit];+ App* app = ActiveApp();+ float sc = ui::Scale(Cur());+ RECT wr; GetWindowRect(Cur(), &wr);+ POINT spt{ wr.left + (LONG)std::lround((h.r.left + h.r.right) / 2 * sc), wr.bottom };+ switch (h.kind) {+ case K_LOGO: ShowAt(hit, LogoMenu(), [&](int id) {+ if (id >= 4000 && id < 4010) { // item recente+ PWSTR p = nullptr; SHGetKnownFolderPath(FOLDERID_Recent, 0, nullptr, &p);+ std::wstring dir = p; CoTaskMemFree(p);+ std::vector<std::pair<ULONGLONG, std::wstring>> files;+ WIN32_FIND_DATAW fd; HANDLE fh = FindFirstFileW((dir + L"\\*.lnk").c_str(), &fd);+ if (fh != INVALID_HANDLE_VALUE) { do files.push_back({ ((ULONGLONG)fd.ftLastWriteTime.dwHighDateTime << 32) | fd.ftLastWriteTime.dwLowDateTime, dir + L"\\" + fd.cFileName }); while (FindNextFileW(fh, &fd)); FindClose(fh); }+ std::sort(files.begin(), files.end(), [](auto& a, auto& b) { return a.first > b.first; });+ if (id - 4000 < (int)files.size()) Open(files[id - 4000].second.c_str());+ } else Run(id, app);+ }); break;+ case K_APP: ShowAt(hit, AppMenu(app), [&](int id) { Run(id, app); }); break;+ case K_MENU:+ if (g_hmenu && IsMenu(g_hmenu)) {+ HMENU sub = GetSubMenu(g_hmenu, h.index);+ if (!sub) break;+ SendMessageTimeoutW(g_fg, WM_INITMENU, (WPARAM)g_hmenu, 0, SMTO_ABORTIFHUNG, 200, nullptr);+ SendMessageTimeoutW(g_fg, WM_INITMENUPOPUP, (WPARAM)sub, h.index, SMTO_ABORTIFHUNG, 200, nullptr);+ HWND target = g_fg;+ ShowAt(hit, FromHmenu(sub, 0), [&](int id) { PostMessageW(target, WM_COMMAND, MAKEWPARAM(id, 0), 0); });+ } else ShowAt(hit, GenericMenu(g_titles[h.index], app), [&](int id) { Run(id, app); });+ break;+ case K_TRAY: tray::Click(h.index, right ? WM_RBUTTONUP : WM_LBUTTONUP, spt); break;+ case K_CC:+ if (!right) { central::Toggle(); break; }+ [[fallthrough]]; // botão direito: a lista dos ícones guardados (a setinha fica desligada, como no Mac)+ case K_MORE: { // lista dos ícones guardados: abrir, menu do app, mostrar na barra+ std::vector<ctxmenu::Item> items;+ std::vector<int> idx;+ for (int i = 0; i < (int)tray::icons.size(); i++) {+ auto& t = tray::icons[i];+ if (t.hidden || !t.icon || tray::IsPrivacy(t)) continue;+ std::wstring name = TrayKey(t);+ if (name.empty()) name = Tr(L"(sem nome)");+ ctxmenu::Item it = I(name, 0);+ { // o ícone do app na linha; os de uma cor só (brancos ou pretos) saem na cor do texto do menu+ it.img = 32;+ it.imgPx = IconPixels(t.icon, it.img);+ auto& p = it.imgPx;+ bool branco = true, preto = true;+ for (size_t k = 0; k + 3 < p.size(); k += 4) {+ if (p[k + 3] < 128) continue;+ for (int c = 0; c < 3; c++) { branco &= p[k + c] >= p[k + 3] * 0.85f; preto &= p[k + c] <= p[k + 3] * 0.15f; }+ }+ if (branco || preto) {+ const bool claro = ui::Dark() && !liquid::Leopard();+ for (size_t k = 0; k + 3 < p.size(); k += 4) p[k] = p[k + 1] = p[k + 2] = claro ? p[k + 3] : 0;+ }+ }+ it.sub = { I(Tr(L"Abrir"), 1000 + i * 4), I(Tr(L"Menu do App"), 1001 + i * 4), Sep(), I(Tr(L"Mostrar na barra de menus"), 1002 + i * 4, false, IsShown(t)) };+ items.push_back(it);+ }+ ShowAt(hit, items, [&](int id) {+ int i = (id - 1000) / 4, op = (id - 1000) % 4;+ if (i < 0 || i >= (int)tray::icons.size()) return;+ if (op == 2) { SetShown(tray::icons[i], !IsShown(tray::icons[i])); return; }+ tray::Click(i, op == 1 ? WM_RBUTTONUP : WM_LBUTTONUP, spt);+ });+ break;+ }+ case K_SPOT: spotlight::Toggle(); break;+ case K_SIRI: siri::Abrir(); break;+ case K_NET: {+ std::wstring ssid = g_st.ssid.empty() ? Tr(L"Conectado") : g_st.ssid; // sem a permissão de localização o nome não vem+ bool wifi = g_st.wifiOn;+ ShowAt(hit, { I(wifi ? L"Wi-Fi: " + ssid : L"Ethernet", 0, true), Sep(), I(Tr(L"Ajustes de Rede…"), 1) }, [](int) { Open(L"ms-settings:network"); });+ break;+ }+ case K_SOUND: { // menu "Som" do Mac (som.cpp): volume, saídas e Ajustes de Som+ RECT ir{ wr.left + (LONG)std::lround(h.r.left * sc), wr.top, wr.left + (LONG)std::lround(h.r.right * sc), wr.bottom };+ som::Toggle(ir);+ break;+ }+ case K_BT: ShowAt(hit, { I(Tr(L"Bluetooth"), 0, true), Sep(), I(Tr(L"Ajustes de Bluetooth…"), 1) }, [](int) { shell::OpenSettings(L"bluetooth"); }); break;+ case K_BATT: {+ wchar_t b[64]; swprintf_s(b, Tr(L"Bateria: %d%%"), g_st.pct);+ ShowAt(hit, { I(b, 0, true), I(g_st.charging ? Tr(L"Fonte de Energia: Carregador") : Tr(L"Fonte de Energia: Bateria"), 0, true), Sep(), I(Tr(L"Ajustes de Bateria…"), 1) },+ [](int) { shell::OpenSettings(L"energia"); });+ break;+ }+ case K_INPUT: { // as fontes de entrada instaladas; a escolhida vai para o app da frente+ HKL list[32]; int n = GetKeyboardLayoutList(32, list);+ std::vector<ctxmenu::Item> items;+ for (int i = 0; i < n; i++) items.push_back(I(InputBadge(list[i]) + L" " + LayoutName(list[i]), 100 + i, false, list[i] == g_st.hkl));+ items.push_back(Sep());+ items.push_back(I(Tr(L"Abrir Ajustes de Teclado…"), 1));+ HWND target = g_fg;+ ShowAt(hit, items, [&](int id) {+ if (id == 1) { shell::OpenSettings(L"teclado"); return; }+ if (id >= 100 && id - 100 < n && target) PostMessageW(target, WM_INPUTLANGCHANGEREQUEST, 0, (LPARAM)list[id - 100]);+ RefreshStatus(); Render();+ });+ break;+ } // painel da Central de Controle (central.cpp)+ case K_CLOCK: {+ if (!right) { notificacoes::Toggle(); break; } // clique: Central de Notificações; botão direito: data e ajustes+ SYSTEMTIME st; GetLocalTime(&st);+ wchar_t full[128] = {};+ GetDateFormatEx(idioma::Locale(), DATE_LONGDATE, &st, nullptr, full, 128, nullptr);+ ShowAt(hit, { I(full, 0, true), Sep(), I(Tr(L"Ajustes de Data e Hora…"), 1) }, [](int) { Open(L"ms-settings:dateandtime"); });+ break;+ }+ }+}++// Desenha todas as barras (a principal por último: os itens dela ficam em g_hits de quem chama sem g_cur)+void RenderAll() {+ HWND keep = g_cur;+ for (HWND b : g_extras) if (IsWindowVisible(b)) { g_cur = b; Render(); }+ g_cur = nullptr;+ Render();+ g_cur = keep;+}++// Redesenha só quando algo visível mudou (antes: a barra inteira a cada segundo)+void RenderIfChanged() {+ static std::wstring last;+ std::wstring sig = g_appName + L"|" + ClockText() + L"|" + std::to_wstring(ui::Dark()) + L"|" + std::to_wstring(g_titles.size());+ for (auto& t : g_titles) sig += t;+ wchar_t b[128];+ swprintf_s(b, L"|%d%d%d%d%d%d%d|%d|%d|%p|%d", g_st.wlan, g_st.wifiOn, g_st.batt, g_st.charging, g_st.bt, g_st.sound, g_st.muted,+ g_st.pct, (int)std::lround(g_st.vol * 3), (void*)g_st.hkl, g_st.phones);+ sig += b;+ for (auto& t : tray::icons) { swprintf_s(b, L"|%p%d%d", (void*)t.icon, t.hidden, IsShown(t)); sig += b; }+ RECT rc; GetClientRect(g_bar, &rc);+ sig += std::to_wstring(rc.right) + L"x" + std::to_wstring(rc.bottom);+ for (HWND b : g_extras) { GetClientRect(b, &rc); sig += L"|" + std::to_wstring(rc.right) + L"x" + std::to_wstring(IsWindowVisible(b)); }+ sig += L"|" + std::to_wstring(g_vaoE) + L"-" + std::to_wstring(g_vaoD);+ if (sig == last) return;+ last = sig;+ RenderAll();+}++const UINT WM_BARDISPLAYS = WM_APP + 41; // monitores mudaram: refaz as barras (fora do WndProc que recebeu o aviso)++// A barra principal no lugar dela: o topo do monitor, ou (barra_embaixo, issue #29) o meio da linha do Dock, com um+// buraco na janela onde o Dock está, para os cliques e o passar do mouse continuarem dele. O Dock muda de largura+// sozinho (app aberto, ampliação): o timer de 1 s chama de novo.+void Assenta() {+ if (!g_bar) return;+ static bool eraEmbaixo;+ static RECT posto;+ const bool baixo = menubar::Embaixo();+ HMONITOR hm = MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY);+ MONITORINFO mi{ sizeof(mi) };+ if (!GetMonitorInfoW(hm, &mi)) return;+ RECT q = mi.rcMonitor;+ const int alt = menubar::HeightOn(hm);+ if (baixo) q.top = q.bottom - menubar::ReservedBottom(hm) / 2 - alt / 2;+ q.bottom = q.top + alt;+ const bool mudou = baixo != eraEmbaixo, moveu = baixo && !EqualRect(&q, &posto);+ int e = 0, d = 0;+ if (baixo) {+ RECT v;+ // com o ponteiro em cima, o Dock está ampliado: o vão fica como estava (senão os menus piscavam)+ if (dock::Vidro(&v) && v.bottom > q.top && v.top < q.bottom) {+ e = std::max<int>(0, v.left - q.left); d = std::min<int>(q.right - q.left, v.right - q.left);+ POINT pt; GetCursorPos(&pt);+ if (!mudou && !moveu && g_vaoD > g_vaoE && PtInRect(&v, pt)) { e = g_vaoE; d = g_vaoD; }+ }+ }+ if (!mudou && !moveu && e == g_vaoE && d == g_vaoD) return;+ eraEmbaixo = baixo; posto = q; g_vaoE = e; g_vaoD = d;+ SetWindowPos(g_bar, HWND_TOPMOST, q.left, q.top, q.right - q.left, q.bottom - q.top, SWP_NOACTIVATE);+ HRGN rg = nullptr;+ if (d > e) {+ rg = CreateRectRgn(0, 0, q.right - q.left, q.bottom - q.top);+ HRGN furo = CreateRectRgn(e, 0, d, q.bottom - q.top);+ CombineRgn(rg, rg, furo, RGN_DIFF);+ DeleteObject(furo);+ }+ SetWindowRgn(g_bar, rg, TRUE); // a janela fica dona da região+ if (mudou) {+ BarGlass(g_bar);+ Log(L"barra de menus: %ls", baixo ? L"embaixo, na linha do Dock" : L"em cima");+ menubar::Displays();+ return;+ }+ if (baixo) Log(L"barra de menus: embaixo em %d,%d-%d,%d, o Dock de %d a %d", q.left, q.top, q.right, q.bottom, e, d);+ RenderAll();+ if (moveu) shell::ApplyWorkArea();+}++LRESULT CALLBACK BarProc(HWND h, UINT m, WPARAM w, LPARAM l) {+ switch (m) {+ case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(h, &ps); EndPaint(h, &ps); HWND keep = g_cur; g_cur = h; Render(); g_cur = keep; return 0; }+ case WM_LBUTTONDOWN: case WM_RBUTTONUP: {+ float sc = ui::Scale(h);+ HWND keep = g_cur;+ g_cur = h; // os menus abrem embaixo da barra clicada (no monitor dela)+ Click({ (short)LOWORD(l) / sc, (short)HIWORD(l) / sc }, m == WM_RBUTTONUP);+ g_cur = keep;+ return 0;+ }+ case WM_BARDISPLAYS: menubar::Displays(); return 0;+ case WM_MOUSEACTIVATE: return MA_NOACTIVATE;case WM_TIMER:if (w == 2) { TiqueOcultar(); return 0; }RefreshStatus(); Assenta(); menubar::Update();@@ -1518,50 +1531,50 @@ LRESULT CALLBACK BarProc(HWND h, UINT m, WPARAM w, LPARAM l) {SYSTEMTIME agora; GetLocalTime(&agora);SetTimer(h, 1, 1000 - agora.wMilliseconds + 15, nullptr);}- return 0;- case WM_BARSTATUS: PegaStatus(); menubar::Update(); return 0;- case WM_SETTINGCHANGE: // Windows trocou entre claro e escuro- if (l && !lstrcmpiW((LPCWSTR)l, L"ImmersiveColorSet")) { menubar::ApplyTheme(); dock::ApplyTheme(); }- break;- case WM_DPICHANGED: case WM_DISPLAYCHANGE:- // todas as barras recebem o aviso: só a principal refaz (depois, fora deste WndProc)- PostMessageW(g_bar, WM_BARDISPLAYS, 0, 0);- return 0;- }- return DefWindowProcW(h, m, w, l);-}--} // namespace--HWND menubar::Hwnd() { return g_bar; }-void menubar::SoundChanged(bool device) {- if (!g_bar) return;- if (device) g_audioStale = true;- RefreshStatus();- if (g_open < 0) RenderAll();-}-bool menubar::SoundIcon(RECT* out) {- if (!g_bar || !IsWindowVisible(Cur())) return false;- for (auto& h : g_hits)- if (h.kind == K_SOUND) {- float sc = ui::Scale(Cur());- RECT wr; GetWindowRect(Cur(), &wr);- *out = { wr.left + (LONG)std::lround(h.r.left * sc), wr.top, wr.left + (LONG)std::lround(h.r.right * sc), wr.bottom };- return true;- }- return false;-}-void menubar::ApplyTheme() {- if (!g_bar) return;- { // tema trocado (Sequoia 26 pt / Tahoe 30 pt): a barra muda de altura- static float lastPt = 0;- if (lastPt && lastPt != BAR_PT) menubar::Displays();- lastPt = BAR_PT;- }- BarGlass(g_bar);- InvalidateRect(g_bar, nullptr, FALSE);- for (HWND b : g_extras) { BarGlass(b); InvalidateRect(b, nullptr, FALSE); }-}+ return 0;+ case WM_BARSTATUS: PegaStatus(); menubar::Update(); return 0;+ case WM_SETTINGCHANGE: // Windows trocou entre claro e escuro+ if (l && !lstrcmpiW((LPCWSTR)l, L"ImmersiveColorSet")) { menubar::ApplyTheme(); dock::ApplyTheme(); }+ break;+ case WM_DPICHANGED: case WM_DISPLAYCHANGE:+ // todas as barras recebem o aviso: só a principal refaz (depois, fora deste WndProc)+ PostMessageW(g_bar, WM_BARDISPLAYS, 0, 0);+ return 0;+ }+ return DefWindowProcW(h, m, w, l);+}++} // namespace++HWND menubar::Hwnd() { return g_bar; }+void menubar::SoundChanged(bool device) {+ if (!g_bar) return;+ if (device) g_audioStale = true;+ RefreshStatus();+ if (g_open < 0) RenderAll();+}+bool menubar::SoundIcon(RECT* out) {+ if (!g_bar || !IsWindowVisible(Cur())) return false;+ for (auto& h : g_hits)+ if (h.kind == K_SOUND) {+ float sc = ui::Scale(Cur());+ RECT wr; GetWindowRect(Cur(), &wr);+ *out = { wr.left + (LONG)std::lround(h.r.left * sc), wr.top, wr.left + (LONG)std::lround(h.r.right * sc), wr.bottom };+ return true;+ }+ return false;+}+void menubar::ApplyTheme() {+ if (!g_bar) return;+ { // tema trocado (Sequoia 26 pt / Tahoe 30 pt): a barra muda de altura+ static float lastPt = 0;+ if (lastPt && lastPt != BAR_PT) menubar::Displays();+ lastPt = BAR_PT;+ }+ BarGlass(g_bar);+ InvalidateRect(g_bar, nullptr, FALSE);+ for (HWND b : g_extras) { BarGlass(b); InvalidateRect(b, nullptr, FALSE); }+}static bool g_fsOn;static HMONITOR g_fsMon;// Ocultar e mostrar automaticamente (barra_ocultar=1, Ajustes > Central de Controle, como no Mac; issue #40): a barra não@@ -1608,185 +1621,185 @@ static void TiqueOcultar() {if (perto) { fora = 0; return; }if (!fora) fora = agora;if (agora - fora >= 400) { fora = 0; Revela(false); }-}-void menubar::SetFullscreen(bool on, HMONITOR mon) {- if (!g_bar) return;- g_fsOn = on; g_fsMon = mon;- std::vector<HWND> all{ g_bar };- all.insert(all.end(), g_extras.begin(), g_extras.end());- auto alheias = shell::AlheiasNoTopo(); // as "sempre por cima" de outros apps (issue #33) voltam por cima no fim- struct Fim { std::vector<HWND>& a; ~Fim() { shell::DevolveAlheias(a); } } fim{ alheias };- for (HWND b : all) {- bool hide = (on && (!mon || MonitorFromWindow(b, MONITOR_DEFAULTTONEAREST) == mon)) || (Ocultar() && !g_revelada); // só a barra do monitor em tela cheia- if (hide == !IsWindowVisible(b)) continue;- ShowWindow(b, hide ? SW_HIDE : SW_SHOWNOACTIVATE);- if (!hide) SetWindowPos(b, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);- }-}-int menubar::Height() { return g_bar ? (int)std::lround(BAR_PT * ui::Scale(g_bar)) : (int)std::lround(BAR_PT * GetDpiForSystem() / 96.f); }-int menubar::HeightOn(HMONITOR mon) {- UINT dx = 96, dy = 96;- if (FAILED(GetDpiForMonitor(mon, MDT_EFFECTIVE_DPI, &dx, &dy))) dx = GetDpiForSystem();- return (int)std::lround(BAR_PT * dx / 96.f);-}--static bool AllMonitors() { return shell::Setting(L"barra_todos_monitores", L"1") != L"0"; }-// O que a barra ocupa no topo do monitor (área de trabalho, Dock lateral): 0 nos secundários sem barra-int menubar::ReservedOn(HMONITOR mon) {- MONITORINFO mi{ sizeof(mi) };- bool prim = GetMonitorInfoW(mon, &mi) && (mi.dwFlags & MONITORINFOF_PRIMARY);- if (menubar::Embaixo()) return 0; // o topo de todos os monitores volta para as janelas- if (Ocultar()) return 0; // ocultar automaticamente: o topo é das janelas, a barra aparece por cima- if (prim) return Height();- return AllMonitors() ? HeightOn(mon) : 0;-}-bool menubar::Embaixo() {- if (shell::Setting(L"barra_embaixo", L"0") != L"1" || liquid::Leopard()) return false;- if (!dock::Hwnd() || dock::Posicao() != 0) return false;- HMONITOR prim = MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY);- if (dock::MonitorHandle() != prim) return false;- // Dock largo demais (muitos apps ou janelas minimizadas, tela de notebook): sem lugar dos lados para a maçã, o- // nome do app e o relógio, a barra ficava por trás do Dock (issue #29, foto de um ThinkPad). Aí ela volta para- // cima até o Dock encolher. Folga de 30 pt entre entrar e sair, para não ficar pulando.- static bool cabia = true;- RECT v; MONITORINFO mi{ sizeof(mi) };- POINT pt; GetCursorPos(&pt);- if (dock::Vidro(&v) && !PtInRect(&v, pt) && GetMonitorInfoW(prim, &mi)) { // ampliado pelo ponteiro: não conta- float sc = GetDpiForWindow(dock::Hwnd()) / 96.f;- float esq = (v.left - mi.rcMonitor.left) / sc, dir = (mi.rcMonitor.right - v.right) / sc;- float precisa = cabia ? 150.f : 180.f; // maçã + nome do app à esquerda; relógio e Central à direita- cabia = esq >= precisa && dir >= precisa;- }- return cabia;-}-int menubar::ReservedBottom(HMONITOR mon) {- if (!menubar::Embaixo() || mon != MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)) return 0;- return std::max(dock::ReservedHeight(), HeightOn(mon)); // com o Dock oculto sobra a altura da barra-}-int menubar::TopInset() { return menubar::Embaixo() ? 0 : Height(); }--// Uma barra em cada monitor (como no Mac): a principal no monitor principal e uma igual em cada um dos outros.-void menubar::Displays() {- if (!g_bar) return;- struct Mon { HMONITOR hm; RECT r; };- std::vector<Mon> others;- Mon prim{};- std::pair<std::vector<Mon>*, Mon*> ctx{ &others, &prim };- EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hm, HDC, LPRECT, LPARAM p) -> BOOL {- MONITORINFO mi{ sizeof(mi) };- if (!GetMonitorInfoW(hm, &mi)) return TRUE;- auto* v = (std::pair<std::vector<Mon>*, Mon*>*)p;- if (mi.dwFlags & MONITORINFOF_PRIMARY) *v->second = { hm, mi.rcMonitor };- else v->first->push_back({ hm, mi.rcMonitor });- return TRUE;- }, (LPARAM)&ctx);- if (!prim.hm) { prim.hm = MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY); MONITORINFO mi{ sizeof(mi) }; GetMonitorInfoW(prim.hm, &mi); prim.r = mi.rcMonitor; }- // "Mostrar a barra de menus em todos os monitores" desligado (barra_todos_monitores=0): só a do principal- const bool baixo = menubar::Embaixo();- if (!AllMonitors() || baixo) others.clear();- Assenta();- if (!baixo) { auto alheias = shell::AlheiasNoTopo(); SetWindowPos(g_bar, HWND_TOPMOST, prim.r.left, prim.r.top, prim.r.right - prim.r.left, HeightOn(prim.hm), SWP_NOACTIVATE); shell::DevolveAlheias(alheias); }- // sobrando (monitor desligado): fecha- while (g_extras.size() > others.size()) {- HWND b = g_extras.back();- g_extras.pop_back();- apps::ours.erase(std::remove(apps::ours.begin(), apps::ours.end(), b), apps::ours.end());- if (g_cur == b) g_cur = nullptr;- if (g_openBar == b) g_openBar = nullptr;- DestroyWindow(b);- g_state.erase(b);- }- // faltando (monitor novo): cria- while (g_extras.size() < others.size()) {- HWND b = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, L"ShellBarraDeMenus", L"Barra de menus", WS_POPUP,- 0, 0, 100, 20, nullptr, nullptr, (HINSTANCE)GetWindowLongPtrW(g_bar, GWLP_HINSTANCE), nullptr);- if (!b) break;- g_extras.push_back(b);- apps::ours.push_back(b);- g_state[b].s.hwnd = b;- DWORD corner = 1;- DwmSetWindowAttribute(b, 33, &corner, sizeof(corner));- BarGlass(b);- }- for (size_t i = 0; i < g_extras.size(); i++) {- const RECT& r = others[i].r;- bool hide = Escondida(g_extras[i], others[i].hm);- SetWindowPos(g_extras[i], HWND_TOPMOST, r.left, r.top, r.right - r.left, HeightOn(others[i].hm),- SWP_NOACTIVATE | (hide ? SWP_HIDEWINDOW : SWP_SHOWWINDOW));- }- if (Ocultar()) { g_revelada = false; if (IsWindowVisible(g_bar)) ShowWindow(g_bar, SW_HIDE); for (HWND b : g_extras) ShowWindow(b, SW_HIDE); SetTimer(g_bar, 2, 50, nullptr); }- else {- KillTimer(g_bar, 2);- g_revelada = false;- if (!IsWindowVisible(g_bar) && !Escondida(g_bar, prim.hm)) ShowWindow(g_bar, SW_SHOWNOACTIVATE);- }- static size_t lastN = (size_t)-1;- if (lastN != g_extras.size()) { lastN = g_extras.size(); Log(L"barra de menus: %zu monitor(es) a mais", lastN); }- RenderAll();- shell::ApplyWorkArea();-}--bool menubar::Create(HINSTANCE hi) {- WNDCLASSW wc{}; wc.lpfnWndProc = BarProc; wc.hInstance = hi; wc.lpszClassName = L"ShellBarraDeMenus";- wc.hCursor = LoadCursorW(nullptr, IDC_ARROW);- RegisterClassW(&wc);- WNDCLASSW oc{}; oc.lpfnWndProc = DefWindowProcW; oc.hInstance = hi; oc.lpszClassName = L"ShellDonoDosMenus";- RegisterClassW(&oc);- g_owner = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_LAYERED, oc.lpszClassName, L"", WS_POPUP | WS_VISIBLE, -32000, -32000, 1, 1, nullptr, nullptr, hi, nullptr);- SetLayeredWindowAttributes(g_owner, 0, 0, LWA_ALPHA);- g_bar = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, wc.lpszClassName, L"Barra de menus", WS_POPUP,- 0, 0, GetSystemMetrics(SM_CXSCREEN), menubar::Height(), nullptr, nullptr, hi, nullptr);- if (!g_bar) return false;- apps::ours.push_back(g_bar);- apps::ours.push_back(g_owner);- g_s.hwnd = g_bar;- DWORD corner = 1; // sem cantos arredondados- DwmSetWindowAttribute(g_bar, 33, &corner, sizeof(corner));- BarGlass(g_bar);- g_tf = ui::Format(13.5f, DWRITE_FONT_WEIGHT_MEDIUM); // o Mac desenha a barra com vibrância: as letras parecem mais cheias- g_tfBold = ui::Format(13.5f, DWRITE_FONT_WEIGHT_BOLD);- g_tfBadge = ui::Format(10, DWRITE_FONT_WEIGHT_NORMAL, false, DWRITE_TEXT_ALIGNMENT_CENTER); // sem negrito (issue #8)- if (g_tfBadge) g_tfBadge->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);- g_tfIcon = ui::Format(14, DWRITE_FONT_WEIGHT_NORMAL, true, DWRITE_TEXT_ALIGNMENT_CENTER);- RefreshStatus();- ShowWindow(g_bar, SW_SHOWNOACTIVATE);- SetTimer(g_bar, 1, 1000, nullptr);- Update();- Displays(); // uma barra igual em cada um dos outros monitores- return true;-}--void menubar::Update() {- HWND fg = GetForegroundWindow();- if (fg && !apps::IsShellWindow(fg)) {- HWND root = GetAncestor(fg, GA_ROOTOWNER);- if (root) fg = root;- wchar_t cls[64] = {}; GetClassNameW(fg, cls, 64);- bool desktop = mesa::IsDeskClass(cls) || !wcscmp(cls, L"Shell_TrayWnd");- if (desktop) { g_finderActive = true; g_fg = nullptr; }- else if (fg != g_fg) {- g_fg = fg;- App* a = apps::OfWindow(fg);- g_finderActive = a && a->finder;- }- }- App* a = ActiveApp();- g_appName = a ? a->name : L"Finder";- if (wchar_t cls[32] = {}; g_fg && GetClassNameW(g_fg, cls, 32) && !wcscmp(cls, L"AjustesJanela")) g_appName = TrPick(L"Ajustes do Sistema", L"System Settings");- g_hmenu = (g_fg && !g_finderActive) ? GetMenu(g_fg) : nullptr;- if (!g_hmenu && g_fg && !g_finderActive) g_hmenu = (HMENU)GetPropW(g_fg, L"MacJanelaMenu"); // tirada da janela pela MacJanela.dll- g_titles.clear();- if (g_hmenu && IsMenu(g_hmenu)) {- int n = GetMenuItemCount(g_hmenu);- for (int k = 0; k < n; k++) {- wchar_t buf[128] = {};- GetMenuStringW(g_hmenu, k, buf, 127, MF_BYPOSITION);- if (buf[0]) g_titles.push_back(Clean(buf));- else g_titles.push_back(L"?");- }- } else {- g_hmenu = nullptr;- g_titles = GenericTitles(a);- }- if (g_open < 0) RenderIfChanged();-}+}+void menubar::SetFullscreen(bool on, HMONITOR mon) {+ if (!g_bar) return;+ g_fsOn = on; g_fsMon = mon;+ std::vector<HWND> all{ g_bar };+ all.insert(all.end(), g_extras.begin(), g_extras.end());+ auto alheias = shell::AlheiasNoTopo(); // as "sempre por cima" de outros apps (issue #33) voltam por cima no fim+ struct Fim { std::vector<HWND>& a; ~Fim() { shell::DevolveAlheias(a); } } fim{ alheias };+ for (HWND b : all) {+ bool hide = (on && (!mon || MonitorFromWindow(b, MONITOR_DEFAULTTONEAREST) == mon)) || (Ocultar() && !g_revelada); // só a barra do monitor em tela cheia+ if (hide == !IsWindowVisible(b)) continue;+ ShowWindow(b, hide ? SW_HIDE : SW_SHOWNOACTIVATE);+ if (!hide) SetWindowPos(b, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);+ }+}+int menubar::Height() { return g_bar ? (int)std::lround(BAR_PT * ui::Scale(g_bar)) : (int)std::lround(BAR_PT * GetDpiForSystem() / 96.f); }+int menubar::HeightOn(HMONITOR mon) {+ UINT dx = 96, dy = 96;+ if (FAILED(GetDpiForMonitor(mon, MDT_EFFECTIVE_DPI, &dx, &dy))) dx = GetDpiForSystem();+ return (int)std::lround(BAR_PT * dx / 96.f);+}++static bool AllMonitors() { return shell::Setting(L"barra_todos_monitores", L"1") != L"0"; }+// O que a barra ocupa no topo do monitor (área de trabalho, Dock lateral): 0 nos secundários sem barra+int menubar::ReservedOn(HMONITOR mon) {+ MONITORINFO mi{ sizeof(mi) };+ bool prim = GetMonitorInfoW(mon, &mi) && (mi.dwFlags & MONITORINFOF_PRIMARY);+ if (menubar::Embaixo()) return 0; // o topo de todos os monitores volta para as janelas+ if (Ocultar()) return 0; // ocultar automaticamente: o topo é das janelas, a barra aparece por cima+ if (prim) return Height();+ return AllMonitors() ? HeightOn(mon) : 0;+}+bool menubar::Embaixo() {+ if (shell::Setting(L"barra_embaixo", L"0") != L"1" || liquid::Leopard()) return false;+ if (!dock::Hwnd() || dock::Posicao() != 0) return false;+ HMONITOR prim = MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY);+ if (dock::MonitorHandle() != prim) return false;+ // Dock largo demais (muitos apps ou janelas minimizadas, tela de notebook): sem lugar dos lados para a maçã, o+ // nome do app e o relógio, a barra ficava por trás do Dock (issue #29, foto de um ThinkPad). Aí ela volta para+ // cima até o Dock encolher. Folga de 30 pt entre entrar e sair, para não ficar pulando.+ static bool cabia = true;+ RECT v; MONITORINFO mi{ sizeof(mi) };+ POINT pt; GetCursorPos(&pt);+ if (dock::Vidro(&v) && !PtInRect(&v, pt) && GetMonitorInfoW(prim, &mi)) { // ampliado pelo ponteiro: não conta+ float sc = GetDpiForWindow(dock::Hwnd()) / 96.f;+ float esq = (v.left - mi.rcMonitor.left) / sc, dir = (mi.rcMonitor.right - v.right) / sc;+ float precisa = cabia ? 150.f : 180.f; // maçã + nome do app à esquerda; relógio e Central à direita+ cabia = esq >= precisa && dir >= precisa;+ }+ return cabia;+}+int menubar::ReservedBottom(HMONITOR mon) {+ if (!menubar::Embaixo() || mon != MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)) return 0;+ return std::max(dock::ReservedHeight(), HeightOn(mon)); // com o Dock oculto sobra a altura da barra+}+int menubar::TopInset() { return menubar::Embaixo() ? 0 : Height(); }++// Uma barra em cada monitor (como no Mac): a principal no monitor principal e uma igual em cada um dos outros.+void menubar::Displays() {+ if (!g_bar) return;+ struct Mon { HMONITOR hm; RECT r; };+ std::vector<Mon> others;+ Mon prim{};+ std::pair<std::vector<Mon>*, Mon*> ctx{ &others, &prim };+ EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hm, HDC, LPRECT, LPARAM p) -> BOOL {+ MONITORINFO mi{ sizeof(mi) };+ if (!GetMonitorInfoW(hm, &mi)) return TRUE;+ auto* v = (std::pair<std::vector<Mon>*, Mon*>*)p;+ if (mi.dwFlags & MONITORINFOF_PRIMARY) *v->second = { hm, mi.rcMonitor };+ else v->first->push_back({ hm, mi.rcMonitor });+ return TRUE;+ }, (LPARAM)&ctx);+ if (!prim.hm) { prim.hm = MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY); MONITORINFO mi{ sizeof(mi) }; GetMonitorInfoW(prim.hm, &mi); prim.r = mi.rcMonitor; }+ // "Mostrar a barra de menus em todos os monitores" desligado (barra_todos_monitores=0): só a do principal+ const bool baixo = menubar::Embaixo();+ if (!AllMonitors() || baixo) others.clear();+ Assenta();+ if (!baixo) { auto alheias = shell::AlheiasNoTopo(); SetWindowPos(g_bar, HWND_TOPMOST, prim.r.left, prim.r.top, prim.r.right - prim.r.left, HeightOn(prim.hm), SWP_NOACTIVATE); shell::DevolveAlheias(alheias); }+ // sobrando (monitor desligado): fecha+ while (g_extras.size() > others.size()) {+ HWND b = g_extras.back();+ g_extras.pop_back();+ apps::ours.erase(std::remove(apps::ours.begin(), apps::ours.end(), b), apps::ours.end());+ if (g_cur == b) g_cur = nullptr;+ if (g_openBar == b) g_openBar = nullptr;+ DestroyWindow(b);+ g_state.erase(b);+ }+ // faltando (monitor novo): cria+ while (g_extras.size() < others.size()) {+ HWND b = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, L"ShellBarraDeMenus", L"Barra de menus", WS_POPUP,+ 0, 0, 100, 20, nullptr, nullptr, (HINSTANCE)GetWindowLongPtrW(g_bar, GWLP_HINSTANCE), nullptr);+ if (!b) break;+ g_extras.push_back(b);+ apps::ours.push_back(b);+ g_state[b].s.hwnd = b;+ DWORD corner = 1;+ DwmSetWindowAttribute(b, 33, &corner, sizeof(corner));+ BarGlass(b);+ }+ for (size_t i = 0; i < g_extras.size(); i++) {+ const RECT& r = others[i].r;+ bool hide = Escondida(g_extras[i], others[i].hm);+ SetWindowPos(g_extras[i], HWND_TOPMOST, r.left, r.top, r.right - r.left, HeightOn(others[i].hm),+ SWP_NOACTIVATE | (hide ? SWP_HIDEWINDOW : SWP_SHOWWINDOW));+ }+ if (Ocultar()) { g_revelada = false; if (IsWindowVisible(g_bar)) ShowWindow(g_bar, SW_HIDE); for (HWND b : g_extras) ShowWindow(b, SW_HIDE); SetTimer(g_bar, 2, 50, nullptr); }+ else {+ KillTimer(g_bar, 2);+ g_revelada = false;+ if (!IsWindowVisible(g_bar) && !Escondida(g_bar, prim.hm)) ShowWindow(g_bar, SW_SHOWNOACTIVATE);+ }+ static size_t lastN = (size_t)-1;+ if (lastN != g_extras.size()) { lastN = g_extras.size(); Log(L"barra de menus: %zu monitor(es) a mais", lastN); }+ RenderAll();+ shell::ApplyWorkArea();+}++bool menubar::Create(HINSTANCE hi) {+ WNDCLASSW wc{}; wc.lpfnWndProc = BarProc; wc.hInstance = hi; wc.lpszClassName = L"ShellBarraDeMenus";+ wc.hCursor = LoadCursorW(nullptr, IDC_ARROW);+ RegisterClassW(&wc);+ WNDCLASSW oc{}; oc.lpfnWndProc = DefWindowProcW; oc.hInstance = hi; oc.lpszClassName = L"ShellDonoDosMenus";+ RegisterClassW(&oc);+ g_owner = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_LAYERED, oc.lpszClassName, L"", WS_POPUP | WS_VISIBLE, -32000, -32000, 1, 1, nullptr, nullptr, hi, nullptr);+ SetLayeredWindowAttributes(g_owner, 0, 0, LWA_ALPHA);+ g_bar = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, wc.lpszClassName, L"Barra de menus", WS_POPUP,+ 0, 0, GetSystemMetrics(SM_CXSCREEN), menubar::Height(), nullptr, nullptr, hi, nullptr);+ if (!g_bar) return false;+ apps::ours.push_back(g_bar);+ apps::ours.push_back(g_owner);+ g_s.hwnd = g_bar;+ DWORD corner = 1; // sem cantos arredondados+ DwmSetWindowAttribute(g_bar, 33, &corner, sizeof(corner));+ BarGlass(g_bar);+ g_tf = ui::Format(13.5f, DWRITE_FONT_WEIGHT_MEDIUM); // o Mac desenha a barra com vibrância: as letras parecem mais cheias+ g_tfBold = ui::Format(13.5f, DWRITE_FONT_WEIGHT_BOLD);+ g_tfBadge = ui::Format(10, DWRITE_FONT_WEIGHT_NORMAL, false, DWRITE_TEXT_ALIGNMENT_CENTER); // sem negrito (issue #8)+ if (g_tfBadge) g_tfBadge->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);+ g_tfIcon = ui::Format(14, DWRITE_FONT_WEIGHT_NORMAL, true, DWRITE_TEXT_ALIGNMENT_CENTER);+ RefreshStatus();+ ShowWindow(g_bar, SW_SHOWNOACTIVATE);+ SetTimer(g_bar, 1, 1000, nullptr);+ Update();+ Displays(); // uma barra igual em cada um dos outros monitores+ return true;+}++void menubar::Update() {+ HWND fg = GetForegroundWindow();+ if (fg && !apps::IsShellWindow(fg)) {+ HWND root = GetAncestor(fg, GA_ROOTOWNER);+ if (root) fg = root;+ wchar_t cls[64] = {}; GetClassNameW(fg, cls, 64);+ bool desktop = mesa::IsDeskClass(cls) || !wcscmp(cls, L"Shell_TrayWnd");+ if (desktop) { g_finderActive = true; g_fg = nullptr; }+ else if (fg != g_fg) {+ g_fg = fg;+ App* a = apps::OfWindow(fg);+ g_finderActive = a && a->finder;+ }+ }+ App* a = ActiveApp();+ g_appName = a ? a->name : L"Finder";+ if (wchar_t cls[32] = {}; g_fg && GetClassNameW(g_fg, cls, 32) && !wcscmp(cls, L"AjustesJanela")) g_appName = TrPick(L"Ajustes do Sistema", L"System Settings");+ g_hmenu = (g_fg && !g_finderActive) ? GetMenu(g_fg) : nullptr;+ if (!g_hmenu && g_fg && !g_finderActive) g_hmenu = (HMENU)GetPropW(g_fg, L"MacJanelaMenu"); // tirada da janela pela MacJanela.dll+ g_titles.clear();+ if (g_hmenu && IsMenu(g_hmenu)) {+ int n = GetMenuItemCount(g_hmenu);+ for (int k = 0; k < n; k++) {+ wchar_t buf[128] = {};+ GetMenuStringW(g_hmenu, k, buf, 127, MF_BYPOSITION);+ if (buf[0]) g_titles.push_back(Clean(buf));+ else g_titles.push_back(L"?");+ }+ } else {+ g_hmenu = nullptr;+ g_titles = GenericTitles(a);+ }+ if (g_open < 0) RenderIfChanged();+}diff --git a/src/shell/shell.h b/src/shell/shell.hindex 231d4e0..c1e80cb 100644--- a/src/shell/shell.h+++ b/src/shell/shell.h@@ -1,735 +1,737 @@-// Shell no estilo do macOS Sequoia: barra de menus (topo), Dock (embaixo) e bandeja.-// Ver docs/dock-e-barra-de-menus.md e docs/estudo-bandeja.md.-#pragma once-#include "../comum/nomes.h"-#include "../comum/abrircom.h" // áudio abre no Música (Finder, mesa, Spotlight, pilha)-#define NOMINMAX-#include <windows.h>-#include <d2d1_1.h>-#include <dwrite.h>-#include <string>-#include <vector>-#include <functional>-#include <atomic>-#include "../comum/idioma.h"-#include <cstdio>--struct IDXGISwapChain1;-struct IDCompositionTarget;-struct IDCompositionVisual;-struct IDCompositionDevice;-struct IDCompositionSurface;-struct IDCompositionAnimation;-struct ID3D11Device;--void Log(const wchar_t* fmt, ...);--// ---- ui.cpp: Direct2D em DIB de 32 bits (alfa preservado), acrílico, fontes, desenhos comuns.-// ---- anim.cpp: tempo de alta precisão e as curvas do macOS (para todas as animações do Shell)-namespace anim {-double Now(); // ms, QueryPerformanceCounter-double Tick(); // ms na base do GetTickCount, com fração (sem degraus)-float Bezier(float t, float x1, float y1, float x2, float y2);-float Ease(float t); // curva padrão do Core Animation (0.25, 0.1, 0.25, 1)-float EaseInOut(float t); // (0.42, 0, 0.58, 1)-float EaseOut(float t); // (0, 0, 0.58, 1)-float Spring(float tSec, float response = 0.55f, float damping = 0.825f); // mola do SwiftUI, de 0 a 1-float SpringDuration(float response, float damping);-// A mola dos painéis do Shell (Spotlight, Central de Controle, menus de status, alertas...), a mesma em-// todos: abrindo, aparece na curva do Mac em 180 ms e cresce de 96% a 100% numa mola ágil (passa um-// tiquinho e assenta, ~0,5 s); fechando, o caminho de volta em 150 ms, acelerando.-struct Panel { float fade = 1, scale = 1; bool done = true; };-Panel PanelIn(double msSinceOpen);-Panel PanelOut(double msSinceClose);-Panel CCIn(double msSinceOpen); // Central de Controle do Tahoe (medida no macOS 26)-// Ajustes > Acessibilidade > Reduzir movimento (reduzir_movimento=1), lido em LoadSettings: o que move ou escala-// vira corte seco ou fade curto (guia macOS26-Theme-Reference, seção 62); fades de saída continuam-extern bool reduceMotion;-Panel CCOut(double msSinceClose);-const double PANEL_OUT_MS = 150;-}--namespace ui {-extern ID2D1Factory* d2d;-extern IDWriteFactory* dw;-extern std::wstring family; // SF Pro Text / Inter / Segoe UI-extern std::wstring iconFamily; // Segoe Fluent Icons / MDL2-bool Init();-bool Dark(); // tema escuro (ajuste "tema" ou o do Windows)-float Scale(HWND h); // DPI / 96--// Superfície: desenhe em DIPs entre Begin e End.-struct Surface {- HWND hwnd = nullptr;- HDC mem = nullptr;- HBITMAP dib = nullptr;- void* bits = nullptr;- int w = 0, h = 0;- ID2D1DCRenderTarget* rt = nullptr;- float scale = 1;-};-ID2D1RenderTarget* Begin(Surface& s, int w, int h, float scale);-// layered = UpdateLayeredWindow (alfa por pixel, partes vazias deixam o clique passar);-// senão BitBlt sobre o acrílico da janela.-void End(Surface& s, bool layered, POINT screenPos = { 0, 0 });-void Free(Surface& s);--// Superfície na GPU (Direct2D + DirectComposition, alfa pré-multiplicado): para o que anima.-// A janela precisa de WS_EX_NOREDIRECTIONBITMAP. Bitmaps criados com o contexto de Gpu() valem-// para todas as superfícies (o dispositivo é um só).-struct GpuSurface {- HWND hwnd = nullptr;- IDXGISwapChain1* swap = nullptr;- IDCompositionTarget* target = nullptr;- IDCompositionVisual* visual = nullptr;- ID2D1Bitmap1* back = nullptr;- int w = 0, h = 0;-};-ID2D1DeviceContext* Gpu(); // contexto compartilhado (criado na primeira vez)-ID2D1DeviceContext* GpuBegin(GpuSurface& s, int w, int h, float scale); // já limpo e com BeginDraw-void GpuEnd(GpuSurface& s); // EndDraw + Present (sem esperar a tela)-void GpuFree(GpuSurface& s);-void GpuSoltarEscondida(GpuSurface& s); // painel de tela cheia: solta os buffers depois de 2 min escondido (pinte antes de mostrar)-// Desloca o conteúdo dentro da janela (px): a janela pode encolher/crescer sem recriar a imagem.-void GpuOffset(GpuSurface& s, float x, float y);-void GpuScale(GpuSurface& s, float scale, float cx, float cy); // escala o desenho em volta de (cx, cy) px (animação dos painéis)-void GpuMotion(GpuSurface& s, float scale, float cx, float cy, float opacity); // escala e opacidade (a mola dos painéis)-// Desliza o conteúdo (px) de (fromX, fromY) até (toX, toY) em `ms`, com ease-out, pelo próprio compositor.-void GpuSlide(GpuSurface& s, float fromX, float fromY, float toX, float toY, float ms);-// Quadros no ritmo do monitor: enquanto `on`, manda `msg` para `hwnd` a cada atualização da tela.-void FrameClock(HWND hwnd, UINT msg, bool on);-void FrameAck(HWND hwnd, UINT msg); // no começo do tratamento do quadro: o próximo só vem depois deste (sem fila)-// Compositor (DirectComposition) do dispositivo de Gpu(): para animações que o DWM faz sozinho.-IDCompositionDevice* Comp();-ID3D11Device* D3D(); // o dispositivo D3D11 de Gpu()-// Superfície do compositor desenhada uma vez com Direct2D (pixels, 96 dpi). nullptr se falhar.-IDCompositionSurface* CompSurface(int w, int h, const std::function<void(ID2D1DeviceContext*)>& draw);-// Curva suave pelos pontos (igualmente espaçados em `durSec`): Hermite com inclinações de Catmull-Rom.-IDCompositionAnimation* CompCurve(const std::vector<float>& v, float durSec);--void Acrylic(HWND h, DWORD tintABGR); // desfoque atrás da janela (SetWindowCompositionAttribute)-IDWriteTextFormat* Format(float size, DWRITE_FONT_WEIGHT w, bool icons = false,- DWRITE_TEXT_ALIGNMENT a = DWRITE_TEXT_ALIGNMENT_LEADING);-IDWriteTextFormat* FormatFace(const wchar_t* face, float size, DWRITE_FONT_WEIGHT w); // família escolhida (Leopard: Lucida)-float TextWidth(IDWriteTextFormat* tf, const std::wstring& s);-ID2D1Bitmap* Bitmap(ID2D1RenderTarget* rt, UINT w, UINT h, const std::vector<BYTE>& bgra);-// Tahoe: Aparência > "Estilo de ícones e widgets" (estilo_icones): padrao | escuro | transparente | tingido.-// Devolve o estilo atual (só com o Liquid Glass; senão "padrao") e aplica nos pixels BGRA pré-multiplicados.-std::wstring IconStyle();-std::wstring IconStyleKey(); // estilo + cor de destaque (para os caches: trocar a cor refaz os ícones Tingidos)-D2D1_COLOR_F Accent(); // Ajustes > Aparência > Cor de destaque (destaque=), "multicor" = azul-void StyleIcon(UINT w, UINT h, std::vector<BYTE>& bgra, const std::wstring& style);--// Pixels BGRA pré-multiplicados de um item do shell (exe, atalho, pasta, shell:AppsFolder\...).-bool ShellImage(const std::wstring& parsingName, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra, bool iconOnly);-// o mesmo pelos bytes do PIDL: itens cujo nome não volta a virar item (tarefas do Painel de Controle)-bool ShellImageId(const std::vector<BYTE>& idList, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra);-// arquivo como no Finder do Mac: miniatura de verdade (foto, vídeo, PDF); sem ela, a folha do Mac com o tipo-// (comum\docicone.h). Pastas e programas: o ícone do Windows (o ícone do próprio app)-bool FileImage(const std::wstring& path, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra);-void TrimToSquare(UINT& w, UINT& h, std::vector<BYTE>& bgra);-void Downscale(UINT& w, UINT& h, std::vector<BYTE>& bgra, UINT maxSide); // reduz (média por área) se passar de maxSide-bool LoadPng(const std::wstring& path, UINT& w, UINT& h, std::vector<BYTE>& bgra); // BGRA pré-multiplicado-// foto inteira (JPG, PNG, WebP, HEIC...) pelo WIC, girada pelo EXIF e reduzida até maxSide (o Quick Look)-bool LoadPhoto(const std::wstring& path, UINT maxSide, UINT& w, UINT& h, std::vector<BYTE>& bgra);-std::wstring PackIcon(const std::wstring& name); // "icones\sequoia\<nome>.png" se existir, senão ""--void DrawFolder(ID2D1RenderTarget* rt, D2D1_RECT_F box, wchar_t glyph); // pasta azul do Arquivos-void DrawTrash(ID2D1RenderTarget* rt, D2D1_RECT_F box, bool full); // lixeira de tela-}--// ---- apps.cpp: apps do Dock (fixos + abertos), janelas, ícones, abrir/ativar/encerrar.-struct AppWin { HWND hwnd; std::wstring title; bool minimized; };-struct App {- std::wstring id; // "aumid:..." ou caminho do .exe em minúsculas- std::wstring launch; // .lnk, .exe ou shell:AppsFolder\AUMID- std::wstring name;- std::wstring exe; // .exe de destino em minúsculas (casa janelas sem AUMID com o atalho fixo)- bool pinned = false;- bool finder = false; // o Arquivos (sempre o primeiro)- bool recent = false; // fechado há pouco (seção de recentes)- std::vector<AppWin> wins;- UINT iw = 0, ih = 0;- std::vector<BYTE> icon; // BGRA pré-multiplicado- bool mac = false; // ícone do pacote do Sequoia (já tem a margem do Mac: desenha no tamanho cheio)- DWORD launchedAt = 0; // pulando enquanto abre- DWORD attentionAt = 0; // pediu atenção (janela piscando)- DWORD lastActive = 0;-};-namespace apps {-extern std::vector<App> list; // ordem do Dock: Arquivos, fixos, abertos/recentes-extern std::vector<std::wstring> recent; // ids dos últimos apps fechados (até 3)-void Load(const std::wstring& finderExe);-void Save();-void Relabel(); // nomes dos nossos apps no idioma escolhido (Ajustes > Geral > Idioma)-bool Refresh(); // relê as janelas; true se algo mudou-std::wstring IdOfWindow(HWND h);-App* FindById(const std::wstring& id);-App* OfWindow(HWND h);-void EnsureIcon(App& a, int px);-void Launch(App& a, const std::wstring& args = L"");-// Apps Chromium/Electron: abre com a opção que mantém a miniatura viva no Mission Control.-// false se o alvo não for um deles (quem chamou abre do jeito normal).-bool LaunchNoOcclusion(const std::wstring& target, const std::wstring& args = L"", const std::wstring& exeHint = L"");-// App empacotado ("shell:AppsFolder\<AUMID com !>": Segurança do Windows, ChatGPT, apps da Loja) pelo ativador-// do Windows. Sem o Explorador, abrir pelo item do shell dá "Classe não registrada". false = não é empacotado-// ou não abriu (quem chamou tenta o jeito comum).-bool ActivatePackaged(const std::wstring& target, const std::wstring& args = L"");-void Activate(App& a); // traz todas as janelas para frente-void Hide(App& a); // Ocultar do Mac: as janelas somem (sem gênio, sem ir para o Dock); clicar no ícone traz de volta+// Shell no estilo do macOS Sequoia: barra de menus (topo), Dock (embaixo) e bandeja.+// Ver docs/dock-e-barra-de-menus.md e docs/estudo-bandeja.md.+#pragma once+#include "../comum/nomes.h"+#include "../comum/abrircom.h" // áudio abre no Música (Finder, mesa, Spotlight, pilha)+#define NOMINMAX+#include <windows.h>+#include <d2d1_1.h>+#include <dwrite.h>+#include <string>+#include <vector>+#include <functional>+#include <atomic>+#include "../comum/idioma.h"+#include <cstdio>++struct IDXGISwapChain1;+struct IDCompositionTarget;+struct IDCompositionVisual;+struct IDCompositionDevice;+struct IDCompositionSurface;+struct IDCompositionAnimation;+struct ID3D11Device;++void Log(const wchar_t* fmt, ...);++// ---- ui.cpp: Direct2D em DIB de 32 bits (alfa preservado), acrílico, fontes, desenhos comuns.+// ---- anim.cpp: tempo de alta precisão e as curvas do macOS (para todas as animações do Shell)+namespace anim {+double Now(); // ms, QueryPerformanceCounter+double Tick(); // ms na base do GetTickCount, com fração (sem degraus)+float Bezier(float t, float x1, float y1, float x2, float y2);+float Ease(float t); // curva padrão do Core Animation (0.25, 0.1, 0.25, 1)+float EaseInOut(float t); // (0.42, 0, 0.58, 1)+float EaseOut(float t); // (0, 0, 0.58, 1)+float Spring(float tSec, float response = 0.55f, float damping = 0.825f); // mola do SwiftUI, de 0 a 1+float SpringDuration(float response, float damping);+// A mola dos painéis do Shell (Spotlight, Central de Controle, menus de status, alertas...), a mesma em+// todos: abrindo, aparece na curva do Mac em 180 ms e cresce de 96% a 100% numa mola ágil (passa um+// tiquinho e assenta, ~0,5 s); fechando, o caminho de volta em 150 ms, acelerando.+struct Panel { float fade = 1, scale = 1; bool done = true; };+Panel PanelIn(double msSinceOpen);+Panel PanelOut(double msSinceClose);+Panel CCIn(double msSinceOpen); // Central de Controle do Tahoe (medida no macOS 26)+// Ajustes > Acessibilidade > Reduzir movimento (reduzir_movimento=1), lido em LoadSettings: o que move ou escala+// vira corte seco ou fade curto (guia macOS26-Theme-Reference, seção 62); fades de saída continuam+extern bool reduceMotion;+Panel CCOut(double msSinceClose);+const double PANEL_OUT_MS = 150;+}++namespace ui {+extern ID2D1Factory* d2d;+extern IDWriteFactory* dw;+extern std::wstring family; // SF Pro Text / Inter / Segoe UI+extern std::wstring iconFamily; // Segoe Fluent Icons / MDL2+bool Init();+bool Dark(); // tema escuro (ajuste "tema" ou o do Windows)+float Scale(HWND h); // DPI / 96++// Superfície: desenhe em DIPs entre Begin e End.+struct Surface {+ HWND hwnd = nullptr;+ HDC mem = nullptr;+ HBITMAP dib = nullptr;+ void* bits = nullptr;+ int w = 0, h = 0;+ ID2D1DCRenderTarget* rt = nullptr;+ float scale = 1;+};+ID2D1RenderTarget* Begin(Surface& s, int w, int h, float scale);+// layered = UpdateLayeredWindow (alfa por pixel, partes vazias deixam o clique passar);+// senão BitBlt sobre o acrílico da janela.+void End(Surface& s, bool layered, POINT screenPos = { 0, 0 });+void Free(Surface& s);++// Superfície na GPU (Direct2D + DirectComposition, alfa pré-multiplicado): para o que anima.+// A janela precisa de WS_EX_NOREDIRECTIONBITMAP. Bitmaps criados com o contexto de Gpu() valem+// para todas as superfícies (o dispositivo é um só).+struct GpuSurface {+ HWND hwnd = nullptr;+ IDXGISwapChain1* swap = nullptr;+ IDCompositionTarget* target = nullptr;+ IDCompositionVisual* visual = nullptr;+ ID2D1Bitmap1* back = nullptr;+ int w = 0, h = 0;+};+ID2D1DeviceContext* Gpu(); // contexto compartilhado (criado na primeira vez)+ID2D1DeviceContext* GpuBegin(GpuSurface& s, int w, int h, float scale); // já limpo e com BeginDraw+void GpuEnd(GpuSurface& s); // EndDraw + Present (sem esperar a tela)+void GpuFree(GpuSurface& s);+void GpuSoltarEscondida(GpuSurface& s); // painel de tela cheia: solta os buffers depois de 2 min escondido (pinte antes de mostrar)+// Desloca o conteúdo dentro da janela (px): a janela pode encolher/crescer sem recriar a imagem.+void GpuOffset(GpuSurface& s, float x, float y);+void GpuScale(GpuSurface& s, float scale, float cx, float cy); // escala o desenho em volta de (cx, cy) px (animação dos painéis)+void GpuMotion(GpuSurface& s, float scale, float cx, float cy, float opacity); // escala e opacidade (a mola dos painéis)+// Desliza o conteúdo (px) de (fromX, fromY) até (toX, toY) em `ms`, com ease-out, pelo próprio compositor.+void GpuSlide(GpuSurface& s, float fromX, float fromY, float toX, float toY, float ms);+// Quadros no ritmo do monitor: enquanto `on`, manda `msg` para `hwnd` a cada atualização da tela.+void FrameClock(HWND hwnd, UINT msg, bool on);+void FrameAck(HWND hwnd, UINT msg); // no começo do tratamento do quadro: o próximo só vem depois deste (sem fila)+// Compositor (DirectComposition) do dispositivo de Gpu(): para animações que o DWM faz sozinho.+IDCompositionDevice* Comp();+ID3D11Device* D3D(); // o dispositivo D3D11 de Gpu()+// Superfície do compositor desenhada uma vez com Direct2D (pixels, 96 dpi). nullptr se falhar.+IDCompositionSurface* CompSurface(int w, int h, const std::function<void(ID2D1DeviceContext*)>& draw);+// Curva suave pelos pontos (igualmente espaçados em `durSec`): Hermite com inclinações de Catmull-Rom.+IDCompositionAnimation* CompCurve(const std::vector<float>& v, float durSec);++void Acrylic(HWND h, DWORD tintABGR); // desfoque atrás da janela (SetWindowCompositionAttribute)+IDWriteTextFormat* Format(float size, DWRITE_FONT_WEIGHT w, bool icons = false,+ DWRITE_TEXT_ALIGNMENT a = DWRITE_TEXT_ALIGNMENT_LEADING);+IDWriteTextFormat* FormatFace(const wchar_t* face, float size, DWRITE_FONT_WEIGHT w); // família escolhida (Leopard: Lucida)+float TextWidth(IDWriteTextFormat* tf, const std::wstring& s);+ID2D1Bitmap* Bitmap(ID2D1RenderTarget* rt, UINT w, UINT h, const std::vector<BYTE>& bgra);+// Tahoe: Aparência > "Estilo de ícones e widgets" (estilo_icones): padrao | escuro | transparente | tingido.+// Devolve o estilo atual (só com o Liquid Glass; senão "padrao") e aplica nos pixels BGRA pré-multiplicados.+std::wstring IconStyle();+std::wstring IconStyleKey(); // estilo + cor de destaque (para os caches: trocar a cor refaz os ícones Tingidos)+D2D1_COLOR_F Accent(); // Ajustes > Aparência > Cor de destaque (destaque=), "multicor" = azul+void StyleIcon(UINT w, UINT h, std::vector<BYTE>& bgra, const std::wstring& style);++// Pixels BGRA pré-multiplicados de um item do shell (exe, atalho, pasta, shell:AppsFolder\...).+bool ShellImage(const std::wstring& parsingName, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra, bool iconOnly);+// o mesmo pelos bytes do PIDL: itens cujo nome não volta a virar item (tarefas do Painel de Controle)+bool ShellImageId(const std::vector<BYTE>& idList, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra);+// arquivo como no Finder do Mac: miniatura de verdade (foto, vídeo, PDF); sem ela, a folha do Mac com o tipo+// (comum\docicone.h). Pastas e programas: o ícone do Windows (o ícone do próprio app)+bool FileImage(const std::wstring& path, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra);+void TrimToSquare(UINT& w, UINT& h, std::vector<BYTE>& bgra);+void Downscale(UINT& w, UINT& h, std::vector<BYTE>& bgra, UINT maxSide); // reduz (média por área) se passar de maxSide+bool LoadPng(const std::wstring& path, UINT& w, UINT& h, std::vector<BYTE>& bgra); // BGRA pré-multiplicado+// foto inteira (JPG, PNG, WebP, HEIC...) pelo WIC, girada pelo EXIF e reduzida até maxSide (o Quick Look)+bool LoadPhoto(const std::wstring& path, UINT maxSide, UINT& w, UINT& h, std::vector<BYTE>& bgra);+std::wstring PackIcon(const std::wstring& name); // "icones\sequoia\<nome>.png" se existir, senão ""++void DrawFolder(ID2D1RenderTarget* rt, D2D1_RECT_F box, wchar_t glyph); // pasta azul do Arquivos+void DrawTrash(ID2D1RenderTarget* rt, D2D1_RECT_F box, bool full); // lixeira de tela+}++// ---- apps.cpp: apps do Dock (fixos + abertos), janelas, ícones, abrir/ativar/encerrar.+struct AppWin { HWND hwnd; std::wstring title; bool minimized; };+struct App {+ std::wstring id; // "aumid:..." ou caminho do .exe em minúsculas+ std::wstring launch; // .lnk, .exe ou shell:AppsFolder\AUMID+ std::wstring name;+ std::wstring exe; // .exe de destino em minúsculas (casa janelas sem AUMID com o atalho fixo)+ bool pinned = false;+ bool finder = false; // o Arquivos (sempre o primeiro)+ bool recent = false; // fechado há pouco (seção de recentes)+ std::vector<AppWin> wins;+ UINT iw = 0, ih = 0;+ std::vector<BYTE> icon; // BGRA pré-multiplicado+ bool mac = false; // ícone do pacote do Sequoia (já tem a margem do Mac: desenha no tamanho cheio)+ DWORD launchedAt = 0; // pulando enquanto abre+ DWORD attentionAt = 0; // pediu atenção (janela piscando)+ DWORD lastActive = 0;+};+namespace apps {+extern std::vector<App> list; // ordem do Dock: Arquivos, fixos, abertos/recentes+extern std::vector<std::wstring> recent; // ids dos últimos apps fechados (até 3)+void Load(const std::wstring& finderExe);+void Save();+void Relabel(); // nomes dos nossos apps no idioma escolhido (Ajustes > Geral > Idioma)+bool Refresh(); // relê as janelas; true se algo mudou+std::wstring IdOfWindow(HWND h);+App* FindById(const std::wstring& id);+App* OfWindow(HWND h);+void EnsureIcon(App& a, int px);+void Launch(App& a, const std::wstring& args = L"");+// Apps Chromium/Electron: abre com a opção que mantém a miniatura viva no Mission Control.+// false se o alvo não for um deles (quem chamou abre do jeito normal).+bool LaunchNoOcclusion(const std::wstring& target, const std::wstring& args = L"", const std::wstring& exeHint = L"");+// App empacotado ("shell:AppsFolder\<AUMID com !>": Segurança do Windows, ChatGPT, apps da Loja) pelo ativador+// do Windows. Sem o Explorador, abrir pelo item do shell dá "Classe não registrada". false = não é empacotado+// ou não abriu (quem chamou tenta o jeito comum).+bool ActivatePackaged(const std::wstring& target, const std::wstring& args = L"");+void Activate(App& a); // traz todas as janelas para frente+void Hide(App& a); // Ocultar do Mac: as janelas somem (sem gênio, sem ir para o Dock); clicar no ícone traz de voltabool IsHidden(HWND h);-bool OcultaComGenio(HWND h); // a janela da frente que o clique no ícone do Dock está ocultando (vai pelo gênio) // janela oculta pelo Ocultar (minimizada por baixo, mas não aparece no Dock)-void Quit(App& a);-void SetPinned(App& a, bool pin);-// programa ou atalho (.lnk, .exe, .url, .appref-ms) solto no Dock: fica fixo antes do app de índice `at` (-1 = no fim-// dos fixos). Já no Dock: só fixa. false = não é programa-bool PinPath(const std::wstring& path, int at);-bool IsProgramFile(const std::wstring& path);-void Move(int from, int to);-void ForgetRecent(const std::wstring& id); // tira um app da seção de recentes-bool OpenAtLogin(const App& a);-void SetOpenAtLogin(const App& a, bool on);-void ShowInFinder(const App& a);-bool IsAppWindow(HWND h); // janela que apareceria na barra de tarefas (regras do Alt+Tab)-bool IsShellWindow(HWND h); // nossas janelas (não entram no Dock nem na barra)-bool LoneOwned(HWND h); // janela com dona escondida (aviso sozinho de um app): conta como janela do app-std::wstring PackIconByName(const std::wstring& name, const std::wstring& exe = L""); // ícone do pacote do Sequoia-// Ícone próprio do app (Dock/Launchpad > Alterar Ícone…), em %APPDATA%\Shell\icones-dock: <exe>.png e <nome>.png-std::wstring CustomIconDir(); // com a barra no fim-std::wstring CustomIcon(const std::wstring& name, const std::wstring& exe); // o PNG escolhido, ou ""-bool HasCustomIcon(const std::wstring& name, const std::wstring& exe);-void ChooseIcon(const std::wstring& name, const std::wstring& exe); // janela de Abrir (outra thread); avisa "ShellIconeMudou"-void RestoreIcon(const std::wstring& name, const std::wstring& exe); // apaga o ícone próprio; avisa "ShellIconeMudou"-void ReloadIcons(); // Dock, Alt+Tab e Launchpad relêem os ícones (thread da interface)-extern std::vector<HWND> ours;-}--// ---- tray.cpp: Shell_TrayWnd próprio (ícones de status dos apps).-struct TrayIcon {- HWND hwnd = nullptr;- UINT uid = 0;- GUID guid{};- UINT callback = 0;- UINT version = 0;- HICON icon = nullptr;- std::wstring tip;- bool hidden = false;-};-namespace tray {-extern std::vector<TrayIcon> icons;-// modo nativo: os ícones chegam pela barra do Windows (MacBarra.dll, ITrayUI::HandleCopyData, na thread da-// barra); true = era da bandeja (res = resposta ao app)-bool DoExplorer(COPYDATASTRUCT* cd, LRESULT* res);-void Start(std::function<void()> changed);-void Stop();-void SemAvisoAoSair(); // reinício: o Shell novo avisa ao abrir; avisar também ao sair confundia o Lively-void Click(int index, UINT button, POINT screenPt); // WM_LBUTTONUP / WM_RBUTTONUP-void Keepalive(); // mantém o nosso Shell_TrayWnd na frente-// O ícone "<app> está usando o microfone/a câmera" do próprio Windows (guid 7820AE82-...): não vai para a barra de-// menus (lá fica a bolinha laranja/verde, como no Mac) e é o sinal de uso; 1 microfone, 2 câmera (pelo texto)-bool IsPrivacy(const TrayIcon& t);-int PrivacyBits();-}--// ---- menubar.cpp / dock.cpp-namespace menubar {-bool Create(HINSTANCE hi);-void Update(); // app ativo mudou, relógio, ícones-HWND Hwnd();-int Height(); // px-void SetFullscreen(bool on, HMONITOR mon = nullptr); // app em tela cheia na frente: some (só no monitor dele; nullptr = todos)-int HeightOn(HMONITOR mon); // px da barra naquele monitor (cada monitor tem a sua barra)-int ReservedOn(HMONITOR mon); // px que a barra ocupa no topo daquele monitor (0: secundário sem barra, barra_todos_monitores=0, ou barra embaixo)-bool Embaixo(); // barra_embaixo: a barra está na linha do Dock (Dock embaixo no monitor principal, fora do Leopard)-int ReservedBottom(HMONITOR mon); // px que a linha do Dock ocupa embaixo com a barra nela (0 = barra em cima)-int TopInset(); // px da barra no topo do monitor principal (0 com ela embaixo): de onde descem os painéis-void Displays(); // monitores mudaram: uma barra em cada-void ApplyTheme(); // claro/escuro mudou-void SoundChanged(bool device); // volume/mudo (ou, com device, a saída padrão) mudou, ou o menu Som abriu/fechou: redesenha-bool SoundIcon(RECT* screen); // onde está o ícone de som (tela); false se não está na barra-}-namespace som { // menu "Som" do ícone da barra e o aviso de volume das teclas (som.cpp)-bool Create(HINSTANCE hi);-void Toggle(RECT iconScreen);-bool IsOpen();-bool HudLit(); // aviso do Tahoe na tela: o ícone da barra fica destacado-void Key(UINT vk, bool fine); // VK_VOLUME_UP/DOWN/MUTE (fine: Shift+Alt, quartos de passo)-}-namespace menus { // menus do Windows (#32768) de todos os programas no visual do Mac (menus.cpp)-void Start();-void Stop();-}-namespace dialogs { // janela de Abrir/Salvar trocada pelo Finder por fora (dialogs.cpp)-void Start();-void Stop();-std::wstring LastSaved(); // caminho escolhido no último Salvar (até 20 s atrás), para a confirmação de substituir-}-namespace janelas { // barra de título do Mac nas janelas dos outros programas (janelas.cpp + MacJanela.dll)-void Start();-void Stop(); // devolve o visual do Windows e tira os ganchos (reiniciando: só tira os ganchos)-void Foreground(HWND h);-void ManterAoReiniciar(); // o próximo Stop é um reinício: as janelas ficam com a barra (o Shell novo assume)-}-namespace barras { // barra de título do Mac por fora, sem nada dentro dos outros programas (modo nativo; barras.cpp)-void Start();-void Stop();-}-namespace sombras { // sombra do Mac nas janelas que a MacJanela.dll não trata (sombras.cpp)-void Start();-void Stop();-}-namespace central { // Central de Controle: painel embaixo do ícone da barra de menus (central.cpp)-bool Create(HINSTANCE hi);-void BrilhoPasso(int dir); // teclas de brilho (F14/F15): -1/+1 de 16 passos, DDC/CI ou WMI, aviso na Ilha-void Toggle();-bool IsOpen();-}-namespace missioncontrol { // Win+Tab: todas as janelas e as Mesas (missioncontrol.cpp)-bool Create(HINSTANCE hi);-void Warm(); // prepara o fundo (papel de parede) antes da primeira abertura-void Toggle();-// Exposé do app (Ctrl+↓ no Mac; aqui Ctrl+Win+↓, "Mostrar Todas as Janelas" no Dock, Cantos Ativos): só as-// janelas do app `appId` (apps::App::id), espalhadas, sem a faixa de Mesas. De novo com o mesmo app: fecha.-void ToggleApp(const std::wstring& appId, const std::wstring& appName);-bool IsOpen();-}-namespace encaixe { // encaixe.cpp: arrastar a janela até a borda = metade/quarto/preencher, com a prévia do Mac-void Start();-void Stop(); // o encaixe do Windows volta como estava-void Half(HWND h, bool right); // Win+← / Win+→-}-namespace memoria { // memoria.cpp: pressão de memória, soneca de apps (App Nap) e memória descartável, como no Mac-void Start();-void Stop(); // acorda todos os apps em soneca (devolve o estado de antes)-int Level(); // 0 normal, 1 alta, 2 crítica-bool Napping(DWORD pid);-}-namespace limites { // limites.cpp: janelas voltam para dentro da área (não cruzam a barra de menus nem o Dock)-void Start();-void Stop();-void Maximizada(HWND h); // a janela da frente mudou de lugar: maximizada por cima da barra/do Dock volta para a área-}-namespace pastas { // pastas.cpp: janela de pasta do Explorador (Chrome "Mostrar na pasta", explorer /select) vira o Finder-void Start();-void Stop();-}-namespace indice { // índice de arquivos próprio (indice.cpp): pasta do usuário e outros discos, salvo em indice.db-struct Hit { std::wstring path, name; bool dir; int score; };-void Start();-bool Ready();-size_t Count();-// foldedQuery: minúsculas sem acento; para logo se cancelled() der true-void Search(const std::wstring& foldedQuery, size_t max, const std::function<bool()>& cancelled, std::vector<Hit>& out);-}-namespace atualizacao { // aviso de versão nova no GitHub (atualizacao.cpp)-void Start(HWND msgWnd); // thread: confere 90 s depois e a cada 6 h; avisa msgWnd-bool Handle(UINT m); // na MsgProc: mostra a notificação (uma vez por versão); true = era a mensagem-void Avisar(const std::wstring& title, const std::wstring& body); // notificação do WacOS (vira o banner do Mac)-}-namespace migrar { // troca de nome Sequoia → WacOS (migrar.cpp)-bool TrocarPeloNovo(); // rodando como SequoiaShell.exe com o WacOSShell.exe ao lado: abre o novo (true = sair)-void Registro(); // caminhos do nome velho no registro e a tarefa do login-}-namespace alertas { // confirmações de excluir do Explorer no alerta do Mac (alertas.cpp)-bool Create(HINSTANCE hi);-void Stop();-// alerta do Mac para uma pergunta do próprio Shell; onYes roda se a resposta for o botão azul-// icon: "" = Lixeira, "pack:<nome>" = icones\sequoia\<nome>.png, senão o caminho de um programa-void Confirm(const std::wstring& title, const std::wstring& info, const std::wstring& yes, std::function<void()> onYes, const std::wstring& icon = L"");-}-namespace progresso { // janela de progresso do Windows (copiar, mover, apagar...) trocada pela do Finder (progresso.cpp)-bool Create(HINSTANCE hi);-void Stop();-bool Owns(HWND h); // janela do Windows que tiramos da tela (não entra no Dock)-}-namespace spotlight { // Win+Espaço / lupa da barra de menus: busca de apps, ajustes e arquivos (spotlight.cpp)-bool Create(HINSTANCE hi);-void Toggle();-bool IsOpen();-void OpenMode(int mode); // Tahoe: abre direto num modo (1 Aplicativos = o "Apps" do Dock, 2 Arquivos, 3 Ações); de novo fecha-void Rescan(); // relê a lista de apps (um programa foi instalado ou removido)-void ClickedDesktop(); // clique na mesa (gancho do revelar.cpp, outra thread): aberto, fecha-}-namespace dashboard { // Dashboard do Leopard (dashboard.cpp): Win+F12 / ShellAbrirPainel 16-bool Create(HINSTANCE hi);-void Toggle();-bool IsOpen();-}-namespace espacos { // Spaces do Leopard (espacos.cpp): Win+F8 / ShellAbrirPainel 17-bool Create(HINSTANCE hi);-void Toggle();-bool IsOpen();-}-namespace tempo { // a "viagem no tempo" do Time Machine do Leopard (tempo.cpp): app Time Machine / ShellAbrirPainel 18-bool Create(HINSTANCE hi);-void Enter();-bool IsOpen();-}-namespace sobre { // "Sobre Este Mac" do menu da Apple (sobre.cpp)-bool Create(HINSTANCE hi);-void Show();-}-namespace genio { // efeito gênio ao minimizar e ao restaurar pelo Dock (genio.cpp)-void Create(HINSTANCE hi);-void Stop();-bool Busy(HWND h); // a janela está no meio do gênio (o Dock ainda não mostra)-int Phase(HWND h); // 0 parada, 1 minimizando (indo para o Dock), 2 restaurando (saindo dele)-bool Restore(HWND h, RECT fromSlot);-bool OnMinRect(HWND h, RECT* out); // HSHELL_GETMINRECT: começa o gênio antes da janela sumir-void Pause(DWORD ms); // Win+D: minimiza tudo de uma vez, sem o gênio (pesado em várias janelas)-}-namespace seletor { // Alt+Tab: o seletor de apps do Mac (seletor.cpp)-bool Create(HINSTANCE hi);-bool IsActive();-void Step(int dir); // Tab (+1) / Shift+Tab (-1) com o Alt seguro-void Key(UINT vk); // Q, H, Esc, setas enquanto aberto-void Release(); // soltou o Alt: troca para o escolhido-void IconsChanged(); // o pacote de ícones mudou (tema): solta os ícones guardados-}-namespace revelar { // clique no vazio da área de trabalho mostra a mesa, como no Mac (revelar.cpp)-void Start();-void Stop();-void Pausar(bool p); // modo jogo: sem o gancho global do mouse-void Foreground(HWND h);-bool Owns(HWND h); // janela minimizada por "mostrar a mesa" (não vai para o Dock)-}-namespace mesas { // áreas de trabalho virtuais pela interface interna do Explorer (mesas.cpp); false = use os atalhos-bool Switch(int index);-bool Create();-bool Remove(int index);-bool MoveWindow(HWND h, int index); // leva a janela (de qualquer programa) para outra mesa-}-namespace widgets { // widgets da mesa: Relógio Mundial, Tempo, Relógio, Calendário, Nascer do Sol (widgets.cpp)-void Create(HINSTANCE hi);-std::vector<RECT> Areas(); // onde estão (tela): os ícones da mesa não ficam embaixo deles-void EditMenu(POINT pt); // "Editar Widgets…": ligar/desligar cada widget (também sem nenhum na tela)-void SettingsChanged(); // widget.<id>.on mudou no ajustes.txt (Ajustes > Personalizar a Mesa)-}-namespace mesa { // mesa própria (papel de parede + ícones) e o modo sem explorer.exe (mesa.cpp, docs/sem-explorer.md)-void Start(HINSTANCE hi, HWND msgWnd); // ajuste explorer=0: fecha o Explorador e assume a mesa-void Stop(bool restartExplorer); // false: caiu/fim da sessão (o vigia abre o Explorador)-void Pulse(); // laço principal: a interface andou (o vigia lê; ver mesa.cpp)-void NoExplorerOnExit(); // reiniciando o Shell: ao sair, o Explorador não é aberto (o Shell novo vem já)-void SettingsChanged(); // ajustes.txt mudou (explorer=0/1)-// cor média do papel de parede que a mesa está mostrando, na faixa atrás da barra de menus (0..1); false sem mesa-bool TopColor(int barPx, float& r, float& g, float& b, bool baixo = false);-// a imagem do papel de parede do monitor principal como a mesa desenhou (BGRA, opaca) e onde fica na tela. key muda-// quando o papel de parede é refeito: com key igual ao que se passou, não copia nada e devolve true-bool Papel(void*& key, int& w, int& h, RECT& tela, std::vector<BYTE>& px);-bool Standalone(); // sem Explorador agora (qualquer thread)-void WallpaperNow(const std::wstring& path); // o Ajustes escolheu este papel de parede: mostra já-void DepoisDoJogo(); // modo jogo acabou: refaz a mesa se a tela mudou durante o jogo-// App antigo da Loja (UWP: Segurança do Windows...) não abre sem o Explorador (a janela dele vem de uma peça-// que vive no explorer.exe). Abre o Explorador escondido, abre o app de novo e, sem nenhum desses apps-// aberto por 15 s, volta ao modo sem Explorador. Qualquer thread.-void NeedExplorer(const std::wstring& aumid);-bool IsDeskClass(const wchar_t* cls); // Progman, WorkerW ou a nossa SequoiaMesa-bool IsDeskWindow(HWND h);-bool IconAt(POINT screen); // há um ícone da nossa mesa embaixo do ponto-void WinKey(UINT vk); // Win+E / Win+R / Win+D sem o Explorador-bool Watchdog(const wchar_t* cmdLine); // WacOSShell.exe --mesa-vigia <pid>-bool IsWindowsShell(); // HKCU Winlogon Shell aponta para o WacOSShell-void RunStartupApps(); // shell do Windows: Run e pastas Inicializar (uma vez por sessão)-}-namespace notificacoes { // Central de Notificações: clique na data/hora da barra de menus (notificacoes.cpp)-bool Create(HINSTANCE hi);-void Toggle();-bool IsOpen();-bool BannerVisible(); // um banner está na tela (Tahoe: o relógio da barra ganha a pílula de destaque)-void IconsChanged(); // ícone próprio do Dock mudou (apps::ReloadIcons): relê os ícones das notificações-void Stop(); // ao sair: o banner do Windows volta a aparecer (o Shell troca pelo banner do Mac; ajuste "banners_mac")-// Widgets da coluna, embaixo das notificações. Sem chamar, vêm Calendário e Relógio próprios.-// w × h em pt (pequeno 164 × 164, médio 344 × 164); paint desenha em DIPs com a origem no canto do widget-// (o vidro e a borda já vêm desenhados); click roda depois que o painel fecha.-struct Widget {- float w, h;- std::function<void(ID2D1DeviceContext* dc, float w, float h, bool dark)> paint;- std::function<void()> click;-};-void SetWidgets(std::vector<Widget> list, std::function<void()> onEdit); // onEdit: "Editar Widgets…"-struct Brief { std::wstring aumid, app; long long time; }; // notificação do Windows (só o necessário para o badge)-std::vector<Brief> Recentes(); // as notificações da Central agora (qualquer thread)-}-namespace ilha { // Ilha Dinâmica (ilha.cpp): notch/pílula preta no topo (música, timer, avisos, Estante...); ajuste ilha=1, ilha_estilo-bool Create(HINSTANCE hi);-void Reload(); // ajustes mudaram (ilha, ilha_estilo, ilha_notificacoes, ilha_volume, ilha_passar)-void SetFullscreen(bool locked); // a janela da frente mudou: confere tela cheia no monitor principal (jogo, vídeo, app) e some na hora-bool On();-// notificação nova: true = a ilha mostrou (o banner do canto não aparece). icon desenha o ícone do app em r (DIP)-bool Notificacao(const std::wstring& app, const std::wstring& title, const std::wstring& body,- std::function<void(ID2D1DeviceContext*, ID2D1SolidColorBrush*, D2D1_RECT_F)> icon, std::function<void()> click);-bool Volume(float level, bool mute); // teclas de volume: true = a ilha mostrou (sem o aviso de volume)+bool OcultaComGenio(HWND h); // a janela da frente que o clique no ícone do Dock está ocultando (vai pelo gênio) // janela oculta pelo Ocultar (minimizada por baixo, mas não aparece no Dock)+void Quit(App& a);+void SetPinned(App& a, bool pin);+// programa ou atalho (.lnk, .exe, .url, .appref-ms) solto no Dock: fica fixo antes do app de índice `at` (-1 = no fim+// dos fixos). Já no Dock: só fixa. false = não é programa+bool PinPath(const std::wstring& path, int at);+bool IsProgramFile(const std::wstring& path);+void Move(int from, int to);+void ForgetRecent(const std::wstring& id); // tira um app da seção de recentes+bool OpenAtLogin(const App& a);+void SetOpenAtLogin(const App& a, bool on);+void ShowInFinder(const App& a);+bool IsAppWindow(HWND h); // janela que apareceria na barra de tarefas (regras do Alt+Tab)+bool IsShellWindow(HWND h); // nossas janelas (não entram no Dock nem na barra)+bool LoneOwned(HWND h); // janela com dona escondida (aviso sozinho de um app): conta como janela do app+std::wstring PackIconByName(const std::wstring& name, const std::wstring& exe = L""); // ícone do pacote do Sequoia+// Ícone próprio do app (Dock/Launchpad > Alterar Ícone…), em %APPDATA%\Shell\icones-dock: <exe>.png e <nome>.png+std::wstring CustomIconDir(); // com a barra no fim+std::wstring CustomIcon(const std::wstring& name, const std::wstring& exe); // o PNG escolhido, ou ""+bool HasCustomIcon(const std::wstring& name, const std::wstring& exe);+void ChooseIcon(const std::wstring& name, const std::wstring& exe); // janela de Abrir (outra thread); avisa "ShellIconeMudou"+void RestoreIcon(const std::wstring& name, const std::wstring& exe); // apaga o ícone próprio; avisa "ShellIconeMudou"+void ReloadIcons(); // Dock, Alt+Tab e Launchpad relêem os ícones (thread da interface)+extern std::vector<HWND> ours;+}++// ---- tray.cpp: Shell_TrayWnd próprio (ícones de status dos apps).+struct TrayIcon {+ HWND hwnd = nullptr;+ UINT uid = 0;+ GUID guid{};+ UINT callback = 0;+ UINT version = 0;+ HICON icon = nullptr;+ std::wstring tip;+ bool hidden = false;+};+namespace tray {+extern std::vector<TrayIcon> icons;+// modo nativo: os ícones chegam pela barra do Windows (MacBarra.dll, ITrayUI::HandleCopyData, na thread da+// barra); true = era da bandeja (res = resposta ao app)+bool DoExplorer(COPYDATASTRUCT* cd, LRESULT* res);+void Start(std::function<void()> changed);+void Stop();+void SemAvisoAoSair(); // reinício: o Shell novo avisa ao abrir; avisar também ao sair confundia o Lively+void Click(int index, UINT button, POINT screenPt); // WM_LBUTTONUP / WM_RBUTTONUP+void Keepalive(); // mantém o nosso Shell_TrayWnd na frente+// O ícone "<app> está usando o microfone/a câmera" do próprio Windows (guid 7820AE82-...): não vai para a barra de+// menus (lá fica a bolinha laranja/verde, como no Mac) e é o sinal de uso; 1 microfone, 2 câmera (pelo texto)+bool IsPrivacy(const TrayIcon& t);+int PrivacyBits();+}++// ---- menubar.cpp / dock.cpp+namespace menubar {+bool Create(HINSTANCE hi);+void Update(); // app ativo mudou, relógio, ícones+HWND Hwnd();+int Height(); // px+void SetFullscreen(bool on, HMONITOR mon = nullptr); // app em tela cheia na frente: some (só no monitor dele; nullptr = todos)+int HeightOn(HMONITOR mon); // px da barra naquele monitor (cada monitor tem a sua barra)+int ReservedOn(HMONITOR mon); // px que a barra ocupa no topo daquele monitor (0: secundário sem barra, barra_todos_monitores=0, ou barra embaixo)+bool Embaixo(); // barra_embaixo: a barra está na linha do Dock (Dock embaixo no monitor principal, fora do Leopard)+int ReservedBottom(HMONITOR mon); // px que a linha do Dock ocupa embaixo com a barra nela (0 = barra em cima)+int TopInset(); // px da barra no topo do monitor principal (0 com ela embaixo): de onde descem os painéis+void Displays(); // monitores mudaram: uma barra em cada+void ApplyTheme(); // claro/escuro mudou+void SoundChanged(bool device); // volume/mudo (ou, com device, a saída padrão) mudou, ou o menu Som abriu/fechou: redesenha+bool SoundIcon(RECT* screen); // onde está o ícone de som (tela); false se não está na barra+}+namespace som { // menu "Som" do ícone da barra e o aviso de volume das teclas (som.cpp)+bool Create(HINSTANCE hi);+void Toggle(RECT iconScreen);+bool IsOpen();+bool HudLit(); // aviso do Tahoe na tela: o ícone da barra fica destacado+void Key(UINT vk, bool fine); // VK_VOLUME_UP/DOWN/MUTE (fine: Shift+Alt, quartos de passo)+}+namespace menus { // menus do Windows (#32768) de todos os programas no visual do Mac (menus.cpp)+void Start();+void Stop();+}+namespace dialogs { // janela de Abrir/Salvar trocada pelo Finder por fora (dialogs.cpp)+void Start();+void Stop();+std::wstring LastSaved(); // caminho escolhido no último Salvar (até 20 s atrás), para a confirmação de substituir+}+namespace janelas { // barra de título do Mac nas janelas dos outros programas (janelas.cpp + MacJanela.dll)+void Start();+void Stop(); // devolve o visual do Windows e tira os ganchos (reiniciando: só tira os ganchos)+void Foreground(HWND h);+void ManterAoReiniciar(); // o próximo Stop é um reinício: as janelas ficam com a barra (o Shell novo assume)+}+namespace barras { // barra de título do Mac por fora, sem nada dentro dos outros programas (modo nativo; barras.cpp)+void Start();+void Stop();+}+namespace sombras { // sombra do Mac nas janelas que a MacJanela.dll não trata (sombras.cpp)+void Start();+void Stop();+}+namespace central { // Central de Controle: painel embaixo do ícone da barra de menus (central.cpp)+bool Create(HINSTANCE hi);+void BrilhoPasso(int dir); // teclas de brilho (F14/F15): -1/+1 de 16 passos, DDC/CI ou WMI, aviso na Ilha+void Toggle();+bool IsOpen();+}+namespace missioncontrol { // Win+Tab: todas as janelas e as Mesas (missioncontrol.cpp)+bool Create(HINSTANCE hi);+void Warm(); // prepara o fundo (papel de parede) antes da primeira abertura+void Toggle();+// Exposé do app (Ctrl+↓ no Mac; aqui Ctrl+Win+↓, "Mostrar Todas as Janelas" no Dock, Cantos Ativos): só as+// janelas do app `appId` (apps::App::id), espalhadas, sem a faixa de Mesas. De novo com o mesmo app: fecha.+void ToggleApp(const std::wstring& appId, const std::wstring& appName);+bool IsOpen();+}+namespace encaixe { // encaixe.cpp: arrastar a janela até a borda = metade/quarto/preencher, com a prévia do Mac+void Start();+void Stop(); // o encaixe do Windows volta como estava+void Half(HWND h, bool right); // Win+← / Win+→+}+namespace memoria { // memoria.cpp: pressão de memória, soneca de apps (App Nap) e memória descartável, como no Mac+void Start();+void Stop(); // acorda todos os apps em soneca (devolve o estado de antes)+int Level(); // 0 normal, 1 alta, 2 crítica+bool Napping(DWORD pid);+}+namespace limites { // limites.cpp: janelas voltam para dentro da área (não cruzam a barra de menus nem o Dock)+void Start();+void Stop();+void Maximizada(HWND h); // a janela da frente mudou de lugar: maximizada por cima da barra/do Dock volta para a área+}+namespace pastas { // pastas.cpp: janela de pasta do Explorador (Chrome "Mostrar na pasta", explorer /select) vira o Finder+void Start();+void Stop();+}+namespace indice { // índice de arquivos próprio (indice.cpp): pasta do usuário e outros discos, salvo em indice.db+struct Hit { std::wstring path, name; bool dir; int score; };+void Start();+bool Ready();+size_t Count();+// foldedQuery: minúsculas sem acento; para logo se cancelled() der true+void Search(const std::wstring& foldedQuery, size_t max, const std::function<bool()>& cancelled, std::vector<Hit>& out);+}+namespace atualizacao { // aviso de versão nova no GitHub (atualizacao.cpp)+void Start(HWND msgWnd); // thread: confere 90 s depois e a cada 6 h; avisa msgWnd+bool Handle(UINT m); // na MsgProc: mostra a notificação (uma vez por versão); true = era a mensagem+void Avisar(const std::wstring& title, const std::wstring& body); // notificação do WacOS (vira o banner do Mac)+}+namespace migrar { // troca de nome Sequoia → WacOS (migrar.cpp)+bool TrocarPeloNovo(); // rodando como SequoiaShell.exe com o WacOSShell.exe ao lado: abre o novo (true = sair)+void Registro(); // caminhos do nome velho no registro e a tarefa do login+}+namespace alertas { // confirmações de excluir do Explorer no alerta do Mac (alertas.cpp)+bool Create(HINSTANCE hi);+void Stop();+// alerta do Mac para uma pergunta do próprio Shell; onYes roda se a resposta for o botão azul+// icon: "" = Lixeira, "pack:<nome>" = icones\sequoia\<nome>.png, senão o caminho de um programa+void Confirm(const std::wstring& title, const std::wstring& info, const std::wstring& yes, std::function<void()> onYes, const std::wstring& icon = L"");+}+namespace progresso { // janela de progresso do Windows (copiar, mover, apagar...) trocada pela do Finder (progresso.cpp)+bool Create(HINSTANCE hi);+void Stop();+bool Owns(HWND h); // janela do Windows que tiramos da tela (não entra no Dock)+}+namespace spotlight { // Win+Espaço / lupa da barra de menus: busca de apps, ajustes e arquivos (spotlight.cpp)+bool Create(HINSTANCE hi);+void Toggle();+bool IsOpen();+void OpenMode(int mode); // Tahoe: abre direto num modo (1 Aplicativos = o "Apps" do Dock, 2 Arquivos, 3 Ações); de novo fecha+void Rescan(); // relê a lista de apps (um programa foi instalado ou removido)+void ClickedDesktop(); // clique na mesa (gancho do revelar.cpp, outra thread): aberto, fecha+}+namespace dashboard { // Dashboard do Leopard (dashboard.cpp): Win+F12 / ShellAbrirPainel 16+bool Create(HINSTANCE hi);+void Toggle();+bool IsOpen();+}+namespace espacos { // Spaces do Leopard (espacos.cpp): Win+F8 / ShellAbrirPainel 17+bool Create(HINSTANCE hi);+void Toggle();+bool IsOpen();+}+namespace tempo { // a "viagem no tempo" do Time Machine do Leopard (tempo.cpp): app Time Machine / ShellAbrirPainel 18+bool Create(HINSTANCE hi);+void Enter();+bool IsOpen();+}+namespace sobre { // "Sobre Este Mac" do menu da Apple (sobre.cpp)+bool Create(HINSTANCE hi);+void Show();+}+namespace genio { // efeito gênio ao minimizar e ao restaurar pelo Dock (genio.cpp)+void Create(HINSTANCE hi);+void Stop();+bool Busy(HWND h); // a janela está no meio do gênio (o Dock ainda não mostra)+int Phase(HWND h); // 0 parada, 1 minimizando (indo para o Dock), 2 restaurando (saindo dele)+bool Restore(HWND h, RECT fromSlot);+bool OnMinRect(HWND h, RECT* out); // HSHELL_GETMINRECT: começa o gênio antes da janela sumir+void Pause(DWORD ms); // Win+D: minimiza tudo de uma vez, sem o gênio (pesado em várias janelas)+}+namespace seletor { // Alt+Tab: o seletor de apps do Mac (seletor.cpp)+bool Create(HINSTANCE hi);+bool IsActive();+void Step(int dir); // Tab (+1) / Shift+Tab (-1) com o Alt seguro+void Key(UINT vk); // Q, H, Esc, setas enquanto aberto+void Release(); // soltou o Alt: troca para o escolhido+void IconsChanged(); // o pacote de ícones mudou (tema): solta os ícones guardados+}+namespace revelar { // clique no vazio da área de trabalho mostra a mesa, como no Mac (revelar.cpp)+void Start();+void Stop();+void Pausar(bool p); // modo jogo: sem o gancho global do mouse+void Foreground(HWND h);+bool Owns(HWND h); // janela minimizada por "mostrar a mesa" (não vai para o Dock)+}+namespace mesas { // áreas de trabalho virtuais pela interface interna do Explorer (mesas.cpp); false = use os atalhos+bool Switch(int index);+bool Create();+bool Remove(int index);+bool MoveWindow(HWND h, int index); // leva a janela (de qualquer programa) para outra mesa+}+namespace widgets { // widgets da mesa: Relógio Mundial, Tempo, Relógio, Calendário, Nascer do Sol (widgets.cpp)+void Create(HINSTANCE hi);+std::vector<RECT> Areas(); // onde estão (tela): os ícones da mesa não ficam embaixo deles+void EditMenu(POINT pt); // "Editar Widgets…": ligar/desligar cada widget (também sem nenhum na tela)+void SettingsChanged(); // widget.<id>.on mudou no ajustes.txt (Ajustes > Personalizar a Mesa)+}+namespace mesa { // mesa própria (papel de parede + ícones) e o modo sem explorer.exe (mesa.cpp, docs/sem-explorer.md)+void Start(HINSTANCE hi, HWND msgWnd); // ajuste explorer=0: fecha o Explorador e assume a mesa+void Stop(bool restartExplorer); // false: caiu/fim da sessão (o vigia abre o Explorador)+void Pulse(); // laço principal: a interface andou (o vigia lê; ver mesa.cpp)+void NoExplorerOnExit(); // reiniciando o Shell: ao sair, o Explorador não é aberto (o Shell novo vem já)+void SettingsChanged(); // ajustes.txt mudou (explorer=0/1)+// cor média do papel de parede que a mesa está mostrando, na faixa atrás da barra de menus (0..1); false sem mesa+bool TopColor(int barPx, float& r, float& g, float& b, bool baixo = false);+// a imagem do papel de parede do monitor principal como a mesa desenhou (BGRA, opaca) e onde fica na tela. key muda+// quando o papel de parede é refeito: com key igual ao que se passou, não copia nada e devolve true+bool Papel(void*& key, int& w, int& h, RECT& tela, std::vector<BYTE>& px);+bool Standalone(); // sem Explorador agora (qualquer thread)+void WallpaperNow(const std::wstring& path); // o Ajustes escolheu este papel de parede: mostra já+void DepoisDoJogo(); // modo jogo acabou: refaz a mesa se a tela mudou durante o jogo+// App antigo da Loja (UWP: Segurança do Windows...) não abre sem o Explorador (a janela dele vem de uma peça+// que vive no explorer.exe). Abre o Explorador escondido, abre o app de novo e, sem nenhum desses apps+// aberto por 15 s, volta ao modo sem Explorador. Qualquer thread.+void NeedExplorer(const std::wstring& aumid);+bool IsDeskClass(const wchar_t* cls); // Progman, WorkerW ou a nossa SequoiaMesa+bool IsDeskWindow(HWND h);+bool IconAt(POINT screen); // há um ícone da nossa mesa embaixo do ponto+void WinKey(UINT vk); // Win+E / Win+R / Win+D sem o Explorador+bool Watchdog(const wchar_t* cmdLine); // WacOSShell.exe --mesa-vigia <pid>+bool IsWindowsShell(); // HKCU Winlogon Shell aponta para o WacOSShell+void RunStartupApps(); // shell do Windows: Run e pastas Inicializar (uma vez por sessão)+}+namespace notificacoes { // Central de Notificações: clique na data/hora da barra de menus (notificacoes.cpp)+bool Create(HINSTANCE hi);+void Toggle();+bool IsOpen();+bool BannerVisible(); // um banner está na tela (Tahoe: o relógio da barra ganha a pílula de destaque)+void IconsChanged(); // ícone próprio do Dock mudou (apps::ReloadIcons): relê os ícones das notificações+void Stop(); // ao sair: o banner do Windows volta a aparecer (o Shell troca pelo banner do Mac; ajuste "banners_mac")+// Widgets da coluna, embaixo das notificações. Sem chamar, vêm Calendário e Relógio próprios.+// w × h em pt (pequeno 164 × 164, médio 344 × 164); paint desenha em DIPs com a origem no canto do widget+// (o vidro e a borda já vêm desenhados); click roda depois que o painel fecha.+struct Widget {+ float w, h;+ std::function<void(ID2D1DeviceContext* dc, float w, float h, bool dark)> paint;+ std::function<void()> click;+};+void SetWidgets(std::vector<Widget> list, std::function<void()> onEdit); // onEdit: "Editar Widgets…"+struct Brief { std::wstring aumid, app; long long time; }; // notificação do Windows (só o necessário para o badge)+std::vector<Brief> Recentes(); // as notificações da Central agora (qualquer thread)+}+namespace ilha { // Ilha Dinâmica (ilha.cpp): notch/pílula preta no topo (música, timer, avisos, Estante...); ajuste ilha=1, ilha_estilo+bool Create(HINSTANCE hi);+void Reload(); // ajustes mudaram (ilha, ilha_estilo, ilha_notificacoes, ilha_volume, ilha_passar)+void SetFullscreen(bool locked); // a janela da frente mudou: confere tela cheia no monitor principal (jogo, vídeo, app) e some na hora+bool On();+// notificação nova: true = a ilha mostrou (o banner do canto não aparece). icon desenha o ícone do app em r (DIP)+bool Notificacao(const std::wstring& app, const std::wstring& title, const std::wstring& body,+ std::function<void(ID2D1DeviceContext*, ID2D1SolidColorBrush*, D2D1_RECT_F)> icon, std::function<void()> click);+bool Volume(float level, bool mute); // teclas de volume: true = a ilha mostrou (sem o aviso de volume)void BotaoMouse(bool down, POINT pt); // gancho do mouse: botão esquerdo apertado/solto (arrastar arquivo até a Ilha desligada)void Brilho(int pct); // o brilho da tela mudou (qualquer thread): aviso de brilho, como o de volume-void CapsLock(); // a tecla Caps Lock foi apertada (gancho de teclado do main.cpp)-void PrivacidadeMudou(); // a bandeja mudou: relê o ícone de privacidade do Windows (tray::PrivacyBits)-void Captura(bool copiada); // a Captura de Tela terminou: aviso rápido "Captura feita" / "Captura copiada"-int Privacidade(); // 1 microfone, 2 câmera em uso (bits); a 1ª chamada liga a vigia; mudou = menubar::Update()-}+void CapsLock(); // a tecla Caps Lock foi apertada (gancho de teclado do main.cpp)+void PrivacidadeMudou(); // a bandeja mudou: relê o ícone de privacidade do Windows (tray::PrivacyBits)+void Captura(bool copiada); // a Captura de Tela terminou: aviso rápido "Captura feita" / "Captura copiada"+int Privacidade(); // 1 microfone, 2 câmera em uso (bits); a 1ª chamada liga a vigia; mudou = menubar::Update()+}namespace siri { // siri.cpp: a Siri com a chave do usuário (issue #39); provedores e chave em src/comum/siri.hbool Pronta(); // um serviço escolhido nos Ajustes (e a chave, se ele pede)-void Perguntar(const std::wstring& q); // abre o painel da Siri e faz a pergunta (numa thread)+void Perguntar(const std::wstring& q, bool teste = false);+void Abrir(bool teste = false); // o ícone da barra de menus: o painel com o campo para digitar (de novo: fecha)+bool Aberta(); // abre o painel da Siri e faz a pergunta (numa thread)}namespace brilho { // brilho.cpp: vigia o brilho da tela do notebook (WMI) e mostra na Ilhavoid Start();}-namespace palco { // Organizador Visual / Stage Manager (palco.cpp): ajuste organizador=1-bool On();-void Sync(); // liga/desliga conforme o ajuste-void Toggle(); // Central de Controle-void Stop(); // Shell saindo: devolve as janelas-}-namespace quicklook { // Quick Look (quicklook.cpp): painel só com a prévia de um arquivo (espaço abre e fecha)-void Toggle(const std::wstring& path, bool activate = true);-void Close();-bool IsOpen();-std::wstring Path();-}-namespace pilhas { // Pilhas do Dock (pilhas.cpp): Downloads em Leque, Grade ou Lista, como no Mac-void Show(POINT anchorScreen); // anchor: centro de cima do ícone-void ShowApps(POINT anchorScreen); // Leopard: a pasta Aplicativos da Dock como Pilha em Grade-void Menu(POINT anchorScreen); // botão direito: ordenar, ver como, exibir como (pasta/pilha), abrir a pasta-bool IsOpen();-std::vector<std::wstring> Recentes(int max); // os primeiros arquivos de Downloads na ordem escolhida (a pilha no Dock)-}-namespace verde { // menu do botão verde (verde.cpp): encaixar a janela (metades, quartos, preencher)-void Show(HWND target, POINT screenPt);-}-namespace atalhos { // itens do app no menu do Dock: tarefas ("Nova janela") e recentes (atalhos.cpp)-struct Item { std::wstring title, path, args, dir; bool recent = false; };-std::vector<Item> Tasks(const std::wstring& exePath);-std::vector<Item> Recent(const std::wstring& aumid, const std::wstring& exePath, int max = 8);-std::wstring AumidOf(HWND h);-void Run(const Item& it);-// o que o app está tocando (controles de mídia do Windows), como no menu do Spotify no Dock do Mac-struct Media { bool has = false, playing = false, canNext = false, canPrev = false; std::wstring title, artist; };-Media MediaOf(const std::wstring& exePath, const std::wstring& aumid);-void MediaCommand(const std::wstring& exePath, const std::wstring& aumid, int cmd); // 0 tocar/pausar, 1 próxima, 2 anterior-}-namespace cantos { // Cantos Ativos (cantos.cpp): canto_se/sd/ie/id = nada|mission|mesa|launchpad|notificacoes|central|spotlight|bloquear|tela|nota-void Start();-bool NotaRapida(); // o canto inferior direito é o da Nota Rápida-void Pausar(bool p); // modo jogo: sem ler o ponteiro-}-namespace notarapida { // canto inferior direito da tela abre a Nota Rápida (notarapida.cpp); `canto_nota_rapida=0` desliga-void Create(HINSTANCE hi);-}--namespace bloqueio { // tela de bloqueio do Sequoia (bloqueio.cpp); `bloqueio=0` em ajustes.txt usa a do Windows-void Create(HINSTANCE hi);-void Lock(); // Win+L, menu da Apple → Bloquear Tela-bool Active(); // travada agora (o gancho do teclado barra Alt+Tab, Win...)-void Fallback(); // o Shell vai sair/caiu: se travada, bloqueia o Windows de verdade-void Stop(); // Shell saindo: apaga a política do Win+L, dispensa o vigia-bool Watchdog(const wchar_t* cmdLine); // Shell.exe --vigia <pid>: true = era o vigia (sair)-bool RenderPng(const wchar_t* cmdLine); // Shell.exe --bloqueio-png ...: imagem de teste (sair)-int Preview(HINSTANCE hi); // Shell.exe --testar-bloqueio: a tela por ~3,5 s, sem senha-int SetPasswordUi(HINSTANCE hi); // Shell.exe --senha-bloqueio: senha própria da tela (só o resumo é gravado)-}-namespace boot { // tela de inicialização do Mac depois do login (boot.cpp); ajuste boot=0 desliga-void Show(HINSTANCE hi); // começo do WinMain: só aparece se o login foi há pouco-void Progress(float p); // 0..1: partes do Shell já criadas-void Done(); // Shell pronto: a tela espera o Explorador/apps de inicialização e esmaece-int Preview(HINSTANCE hi); // Shell.exe --testar-boot: só a tela, ~6 s-}-namespace launchpad {-bool Create(HINSTANCE hi);-void Warm(); // prepara o fundo desfocado antes da primeira abertura-void Toggle();-bool IsOpen();-int Category(const std::wstring& appName); // categoria do app (1..CategoryCount()-1; 0 = todos)-int CategoryCount();-const wchar_t* CategoryName(int k);-void Rescan(); // relê a lista de apps (um programa foi instalado ou removido)-void IconsChanged(); // um ícone próprio mudou: relê a lista e os ícones (sem reaproveitar os guardados)-// Fora do Launchpad e do painel Apps: tirado à mão (launchpad_ocultos) ou ferramenta do Windows com-// launchpad_sem_sistema=1 (Painel de Controle, Mapa de Caracteres, Ferramentas do Windows...)-bool Escondido(const std::wstring& name, const std::wstring& parsing);-bool AppDoSistema(const std::wstring& name, const std::wstring& parsing);-void Ocultar(const std::wstring& name); // acrescenta a launchpad_ocultos-}-namespace instalados { // vigia o Menu Iniciar e os apps da Store e avisa o Spotlight e o Launchpad (instalados.cpp)-void Start();-}-namespace dock {-bool Create(HINSTANCE hi);-void Update(); // apps mudaram-HWND Hwnd();-HWND Fundo(); // o vidro, a janela mais de baixo do Dock-bool Vidro(RECT* screen); // retângulo do vidro do Dock na tela (todos os temas, também o Leopard); false = fora da tela-int ReservedHeight(); // px reservados na borda do Dock (área de trabalho): embaixo ou do lado (Posicao)-int Posicao(); // 0 embaixo, 1 esquerda, 2 direita (dock_posicao; o Leopard fica sempre embaixo)-HMONITOR MonitorHandle(); // o monitor do Dock (ajuste dock_monitor; vazio = o principal)-void Raise(); // traz o Dock para cima (ex.: por cima do Launchpad)-void OpenAppsStack(); // Leopard: a pasta Aplicativos como Pilha em Grade-void OpenDownloadsStack(); // a pilha Downloads (testes: ShellAbrirPainel 15)-void ReloadSettings(); // o Ajustes do Sistema mudou tamanho, ampliação...-void ApplyTheme(); // claro/escuro mudou-void IconsChanged(); // o pacote de ícones mudou (tema Sequoia/Tahoe): solta os ícones guardados-void SetFullscreen(bool on); // app em tela cheia na frente: some+namespace palco { // Organizador Visual / Stage Manager (palco.cpp): ajuste organizador=1+bool On();+void Sync(); // liga/desliga conforme o ajuste+void Toggle(); // Central de Controle+void Stop(); // Shell saindo: devolve as janelas+}+namespace quicklook { // Quick Look (quicklook.cpp): painel só com a prévia de um arquivo (espaço abre e fecha)+void Toggle(const std::wstring& path, bool activate = true);+void Close();+bool IsOpen();+std::wstring Path();+}+namespace pilhas { // Pilhas do Dock (pilhas.cpp): Downloads em Leque, Grade ou Lista, como no Mac+void Show(POINT anchorScreen); // anchor: centro de cima do ícone+void ShowApps(POINT anchorScreen); // Leopard: a pasta Aplicativos da Dock como Pilha em Grade+void Menu(POINT anchorScreen); // botão direito: ordenar, ver como, exibir como (pasta/pilha), abrir a pasta+bool IsOpen();+std::vector<std::wstring> Recentes(int max); // os primeiros arquivos de Downloads na ordem escolhida (a pilha no Dock)+}+namespace verde { // menu do botão verde (verde.cpp): encaixar a janela (metades, quartos, preencher)+void Show(HWND target, POINT screenPt);+}+namespace atalhos { // itens do app no menu do Dock: tarefas ("Nova janela") e recentes (atalhos.cpp)+struct Item { std::wstring title, path, args, dir; bool recent = false; };+std::vector<Item> Tasks(const std::wstring& exePath);+std::vector<Item> Recent(const std::wstring& aumid, const std::wstring& exePath, int max = 8);+std::wstring AumidOf(HWND h);+void Run(const Item& it);+// o que o app está tocando (controles de mídia do Windows), como no menu do Spotify no Dock do Mac+struct Media { bool has = false, playing = false, canNext = false, canPrev = false; std::wstring title, artist; };+Media MediaOf(const std::wstring& exePath, const std::wstring& aumid);+void MediaCommand(const std::wstring& exePath, const std::wstring& aumid, int cmd); // 0 tocar/pausar, 1 próxima, 2 anterior+}+namespace cantos { // Cantos Ativos (cantos.cpp): canto_se/sd/ie/id = nada|mission|mesa|launchpad|notificacoes|central|spotlight|bloquear|tela|nota+void Start();+bool NotaRapida(); // o canto inferior direito é o da Nota Rápida+void Pausar(bool p); // modo jogo: sem ler o ponteiro+}+namespace notarapida { // canto inferior direito da tela abre a Nota Rápida (notarapida.cpp); `canto_nota_rapida=0` desliga+void Create(HINSTANCE hi);+}++namespace bloqueio { // tela de bloqueio do Sequoia (bloqueio.cpp); `bloqueio=0` em ajustes.txt usa a do Windows+void Create(HINSTANCE hi);+void Lock(); // Win+L, menu da Apple → Bloquear Tela+bool Active(); // travada agora (o gancho do teclado barra Alt+Tab, Win...)+void Fallback(); // o Shell vai sair/caiu: se travada, bloqueia o Windows de verdade+void Stop(); // Shell saindo: apaga a política do Win+L, dispensa o vigia+bool Watchdog(const wchar_t* cmdLine); // Shell.exe --vigia <pid>: true = era o vigia (sair)+bool RenderPng(const wchar_t* cmdLine); // Shell.exe --bloqueio-png ...: imagem de teste (sair)+int Preview(HINSTANCE hi); // Shell.exe --testar-bloqueio: a tela por ~3,5 s, sem senha+int SetPasswordUi(HINSTANCE hi); // Shell.exe --senha-bloqueio: senha própria da tela (só o resumo é gravado)+}+namespace boot { // tela de inicialização do Mac depois do login (boot.cpp); ajuste boot=0 desliga+void Show(HINSTANCE hi); // começo do WinMain: só aparece se o login foi há pouco+void Progress(float p); // 0..1: partes do Shell já criadas+void Done(); // Shell pronto: a tela espera o Explorador/apps de inicialização e esmaece+int Preview(HINSTANCE hi); // Shell.exe --testar-boot: só a tela, ~6 s+}+namespace launchpad {+bool Create(HINSTANCE hi);+void Warm(); // prepara o fundo desfocado antes da primeira abertura+void Toggle();+bool IsOpen();+int Category(const std::wstring& appName); // categoria do app (1..CategoryCount()-1; 0 = todos)+int CategoryCount();+const wchar_t* CategoryName(int k);+void Rescan(); // relê a lista de apps (um programa foi instalado ou removido)+void IconsChanged(); // um ícone próprio mudou: relê a lista e os ícones (sem reaproveitar os guardados)+// Fora do Launchpad e do painel Apps: tirado à mão (launchpad_ocultos) ou ferramenta do Windows com+// launchpad_sem_sistema=1 (Painel de Controle, Mapa de Caracteres, Ferramentas do Windows...)+bool Escondido(const std::wstring& name, const std::wstring& parsing);+bool AppDoSistema(const std::wstring& name, const std::wstring& parsing);+void Ocultar(const std::wstring& name); // acrescenta a launchpad_ocultos+}+namespace instalados { // vigia o Menu Iniciar e os apps da Store e avisa o Spotlight e o Launchpad (instalados.cpp)+void Start();+}+namespace dock {+bool Create(HINSTANCE hi);+void Update(); // apps mudaram+HWND Hwnd();+HWND Fundo(); // o vidro, a janela mais de baixo do Dock+bool Vidro(RECT* screen); // retângulo do vidro do Dock na tela (todos os temas, também o Leopard); false = fora da tela+int ReservedHeight(); // px reservados na borda do Dock (área de trabalho): embaixo ou do lado (Posicao)+int Posicao(); // 0 embaixo, 1 esquerda, 2 direita (dock_posicao; o Leopard fica sempre embaixo)+HMONITOR MonitorHandle(); // o monitor do Dock (ajuste dock_monitor; vazio = o principal)+void Raise(); // traz o Dock para cima (ex.: por cima do Launchpad)+void OpenAppsStack(); // Leopard: a pasta Aplicativos como Pilha em Grade+void OpenDownloadsStack(); // a pilha Downloads (testes: ShellAbrirPainel 15)+void ReloadSettings(); // o Ajustes do Sistema mudou tamanho, ampliação...+void ApplyTheme(); // claro/escuro mudou+void IconsChanged(); // o pacote de ícones mudou (tema Sequoia/Tahoe): solta os ícones guardados+void SetFullscreen(bool on); // app em tela cheia na frente: someRECT MinimizeTarget(HWND h = nullptr);-RECT AppIconTarget(HWND h); // tela: o ícone do app dono da janela (vazio se não está no Dock) // tela: onde a janela minimizada vai parar (h: no ícone do app com dock_minimizar_no_icone)-void BadgesChanged(); // chegou ou saiu notificação: redesenha os badges vermelhos-}--namespace backdrop { // vidro desfocado com recorte arredondado suave (backdrop.cpp)-bool Attach(HWND h); // janela criada com WS_EX_NOREDIRECTIONBITMAP-void Detach(HWND h); // a janela vai ser destruída: solta o vidro dela-void Restart(); // refaz o vidro real do zero (Ajustes: "Reiniciar o Liquid Glass")-void Set(HWND h, float w, float hgt, float radius, D2D1_COLOR_F tint); // px-void Fade(HWND h, float opacity, float scale, float cx, float cy); // animação: opacidade e escala em volta de (cx, cy) px-// Conteúdo desenhado DENTRO do vidro (mesma árvore da Composição): vidro e desenho chegam à tela no mesmo-// quadro. Numa janela à parte (swap chain), a borda do vidro ficava um quadro atrás do desenho quando o-// painel mudava de tamanho. Coordenadas em DIP (scale = DPI/96); o contexto é do dispositivo de ui::Gpu()-// (bitmaps de lá valem). Recortado, esmaecido e escalado junto com o vidro. nullptr: desenhe do jeito antigo.-ID2D1DeviceContext* ContentBegin(HWND h, int wpx, int hpx, float scale);-void ContentEnd(HWND h);-// avisa (PostMessage(to, msg)) quando o que foi desenhado no vidro já chegou à tela (commit do compositor);-// quem mostra a janela depois disso não aparece com o vidro da última vez-void AfterCommit(HWND to, UINT msg);-// Transparência e Efeitos (Ajustes do Sistema): Liquid Glass, reduzir transparência, tinta do vidro-struct Style {- bool liquid = false; // liquid_glass: vidro líquido do macOS Tahoe- bool golden = false; // golden_gate (com liquid_glass): tema macOS 27 Golden Gate- bool leopard = false; // leopard (sem liquid_glass): tema Mac OS X Leopard (o Sequoia com o Aqua de 2007)- bool tinted = false; // liquid_estilo: "nitido" ou "tingido"- float refraction = 0.6f; // liquid_refracao 0..1: força da lente nas bordas- bool reduce = false; // reduzir_transparencia- float tintK = 0.5f; // vidro_tinta 0..1 (0,5 = a tinta original de cada janela); no vidro real, também o desfoque- bool real = false; // vidro_real: Liquid Glass com refração de verdade (captura da tela por baixo)-};-struct Piece { // px, nas coordenadas da janela- D2D1_RECT_F r; float radius;- // gosma (comum/vidro.h): a peça é a cápsula `cap` unida aos círculos `circ` (o Spotlight soltando os círculos)- bool goo = false; D2D1_RECT_F cap{}; float capR = 0; std::vector<D2D1_ELLIPSE> circ; unsigned broken = 0;-};-// várias peças de vidro soltas numa janela só (módulos da Central): cada uma com a lente dela e a tinta;-// o contorno fica por conta de quem desenha por cima-void SetPieces(HWND h, float w, float hgt, const std::vector<Piece>& pieces, D2D1_COLOR_F tint, float minFrost = 0); // minFrost: desfoque mínimo (DIP)-bool Real(); // vidro real ativo (senão, o fosco)-void CaptureVisible(bool show); // Captura de Tela do projeto: mostrar as peças só durante a foto-const Style& Current();-bool Liquid(); // Liquid Glass ligado (e transparência não reduzida)-void Reload(); // lê os ajustes e reaplica em todos os vidros-float AdjustAlpha(float a); // opacidade da tinta conforme os ajustes-D2D1_COLOR_F AdjustTint(D2D1_COLOR_F c);-}-namespace liquid { // tema macOS Tahoe nos painéis do Shell (liquid.cpp): detalhes D2D por cima do vidro-bool On(); // Tema = macOS Tahoe (liquid_glass), mesmo com a transparência reduzida-bool Golden(); // Tema = macOS Golden Gate (liquid_glass + golden_gate): o Tahoe com o que mudou no macOS 27-bool Leopard(); // Tema = Mac OS X Leopard (leopard=1, sem liquid_glass): barra de menus clara com a maçã grafite, Dock em prateleira-// contorno especular; spec = força do brilho dos cantos (0 em repouso, 1 com o ponteiro em cima), lx/ly = de onde vem a-// luz (0..1 dentro da peça, a posição do ponteiro; < 0 = canto de cima à esquerda)-void Rim(ID2D1DeviceContext* dc, D2D1_RECT_F r, float rad, bool dark, float strength = 1, float spec = 1, float lx = -1, float ly = -1);-void Tile(ID2D1DeviceContext* dc, D2D1_RECT_F r, float rad, bool dark, float fill = 1); // bloco/cápsula de vidro-}--// ---- main.cpp-namespace shell {-// Modo nativo (barra-nativa\MacBarra.dll): o Shell é a barra de tarefas do próprio Windows, rodando numa-// thread dentro do explorer.exe (trocado pelo TrayUI Component). Nada de processo próprio: sem esconder a-// barra do Windows (ela é nossa), sem Shell_TrayWnd falsa, sem mesa própria, sem ganchos com DLL nos outros-// programas, sem TerminateProcess/filtro de falhas (o processo é o explorer).-extern bool nativo;-// Modo "Só Dock e barra de menus" (ajuste modo=dock; Ajustes > Geral): só a barra de menus (com Central de Controle,-// Notificações e Spotlight), o Dock (com Launchpad, gênio e Mission Control). O resto fica com o Windows: a área de-// trabalho e os ícones dele, o Explorador nas pastas, o Alt+Tab, a tecla Windows, a captura de tela e as barras de-// título dos outros apps. Lido na partida do Shell (trocar o modo reinicia o Shell).-bool SoDock();-// Tira a janela de minimizada. Numa janela de administrador o ShowWindow de fora e recusado pelo Windows (o explorer-// nao e administrador); o pedido pelo menu de sistema dela (WM_SYSCOMMAND) passa.-inline void Restaurar(HWND h) { ShowWindow(h, SW_RESTORE); if (IsIconic(h)) PostMessageW(h, WM_SYSCOMMAND, SC_RESTORE, 0); }-// Libera o SetForegroundWindow: o processo que mandou a última entrada pode trocar a janela da frente. Era só Alt-// apertado e solto, mas Alt sozinho, ao soltar, liga a barra de menus do app da frente (o Firefox abria com a barra-// Arquivo/Editar/Exibir à mostra, igual ao F10; issue #8). Uma tecla sem função (vkE8) no meio desfaz isso. Marcadas-// como nossas: o gancho do teclado do Shell deixa passar.+RECT AppIconTarget(HWND h); // tela: o ícone do app dono da janela (vazio se não está no Dock) // tela: onde a janela minimizada vai parar (h: no ícone do app com dock_minimizar_no_icone)+void BadgesChanged(); // chegou ou saiu notificação: redesenha os badges vermelhos+}++namespace backdrop { // vidro desfocado com recorte arredondado suave (backdrop.cpp)+bool Attach(HWND h); // janela criada com WS_EX_NOREDIRECTIONBITMAP+void Detach(HWND h); // a janela vai ser destruída: solta o vidro dela+void Restart(); // refaz o vidro real do zero (Ajustes: "Reiniciar o Liquid Glass")+void Set(HWND h, float w, float hgt, float radius, D2D1_COLOR_F tint); // px+void Fade(HWND h, float opacity, float scale, float cx, float cy); // animação: opacidade e escala em volta de (cx, cy) px+// Conteúdo desenhado DENTRO do vidro (mesma árvore da Composição): vidro e desenho chegam à tela no mesmo+// quadro. Numa janela à parte (swap chain), a borda do vidro ficava um quadro atrás do desenho quando o+// painel mudava de tamanho. Coordenadas em DIP (scale = DPI/96); o contexto é do dispositivo de ui::Gpu()+// (bitmaps de lá valem). Recortado, esmaecido e escalado junto com o vidro. nullptr: desenhe do jeito antigo.+ID2D1DeviceContext* ContentBegin(HWND h, int wpx, int hpx, float scale);+void ContentEnd(HWND h);+// avisa (PostMessage(to, msg)) quando o que foi desenhado no vidro já chegou à tela (commit do compositor);+// quem mostra a janela depois disso não aparece com o vidro da última vez+void AfterCommit(HWND to, UINT msg);+// Transparência e Efeitos (Ajustes do Sistema): Liquid Glass, reduzir transparência, tinta do vidro+struct Style {+ bool liquid = false; // liquid_glass: vidro líquido do macOS Tahoe+ bool golden = false; // golden_gate (com liquid_glass): tema macOS 27 Golden Gate+ bool leopard = false; // leopard (sem liquid_glass): tema Mac OS X Leopard (o Sequoia com o Aqua de 2007)+ bool tinted = false; // liquid_estilo: "nitido" ou "tingido"+ float refraction = 0.6f; // liquid_refracao 0..1: força da lente nas bordas+ bool reduce = false; // reduzir_transparencia+ float tintK = 0.5f; // vidro_tinta 0..1 (0,5 = a tinta original de cada janela); no vidro real, também o desfoque+ bool real = false; // vidro_real: Liquid Glass com refração de verdade (captura da tela por baixo)+};+struct Piece { // px, nas coordenadas da janela+ D2D1_RECT_F r; float radius;+ // gosma (comum/vidro.h): a peça é a cápsula `cap` unida aos círculos `circ` (o Spotlight soltando os círculos)+ bool goo = false; D2D1_RECT_F cap{}; float capR = 0; std::vector<D2D1_ELLIPSE> circ; unsigned broken = 0;+};+// várias peças de vidro soltas numa janela só (módulos da Central): cada uma com a lente dela e a tinta;+// o contorno fica por conta de quem desenha por cima+void SetPieces(HWND h, float w, float hgt, const std::vector<Piece>& pieces, D2D1_COLOR_F tint, float minFrost = 0); // minFrost: desfoque mínimo (DIP)+bool Real(); // vidro real ativo (senão, o fosco)+void CaptureVisible(bool show); // Captura de Tela do projeto: mostrar as peças só durante a foto+const Style& Current();+bool Liquid(); // Liquid Glass ligado (e transparência não reduzida)+void Reload(); // lê os ajustes e reaplica em todos os vidros+float AdjustAlpha(float a); // opacidade da tinta conforme os ajustes+D2D1_COLOR_F AdjustTint(D2D1_COLOR_F c);+}+namespace liquid { // tema macOS Tahoe nos painéis do Shell (liquid.cpp): detalhes D2D por cima do vidro+bool On(); // Tema = macOS Tahoe (liquid_glass), mesmo com a transparência reduzida+bool Golden(); // Tema = macOS Golden Gate (liquid_glass + golden_gate): o Tahoe com o que mudou no macOS 27+bool Leopard(); // Tema = Mac OS X Leopard (leopard=1, sem liquid_glass): barra de menus clara com a maçã grafite, Dock em prateleira+// contorno especular; spec = força do brilho dos cantos (0 em repouso, 1 com o ponteiro em cima), lx/ly = de onde vem a+// luz (0..1 dentro da peça, a posição do ponteiro; < 0 = canto de cima à esquerda)+void Rim(ID2D1DeviceContext* dc, D2D1_RECT_F r, float rad, bool dark, float strength = 1, float spec = 1, float lx = -1, float ly = -1);+void Tile(ID2D1DeviceContext* dc, D2D1_RECT_F r, float rad, bool dark, float fill = 1); // bloco/cápsula de vidro+}++// ---- main.cpp+namespace shell {+// Modo nativo (barra-nativa\MacBarra.dll): o Shell é a barra de tarefas do próprio Windows, rodando numa+// thread dentro do explorer.exe (trocado pelo TrayUI Component). Nada de processo próprio: sem esconder a+// barra do Windows (ela é nossa), sem Shell_TrayWnd falsa, sem mesa própria, sem ganchos com DLL nos outros+// programas, sem TerminateProcess/filtro de falhas (o processo é o explorer).+extern bool nativo;+// Modo "Só Dock e barra de menus" (ajuste modo=dock; Ajustes > Geral): só a barra de menus (com Central de Controle,+// Notificações e Spotlight), o Dock (com Launchpad, gênio e Mission Control). O resto fica com o Windows: a área de+// trabalho e os ícones dele, o Explorador nas pastas, o Alt+Tab, a tecla Windows, a captura de tela e as barras de+// título dos outros apps. Lido na partida do Shell (trocar o modo reinicia o Shell).+bool SoDock();+// Tira a janela de minimizada. Numa janela de administrador o ShowWindow de fora e recusado pelo Windows (o explorer+// nao e administrador); o pedido pelo menu de sistema dela (WM_SYSCOMMAND) passa.+inline void Restaurar(HWND h) { ShowWindow(h, SW_RESTORE); if (IsIconic(h)) PostMessageW(h, WM_SYSCOMMAND, SC_RESTORE, 0); }+// Libera o SetForegroundWindow: o processo que mandou a última entrada pode trocar a janela da frente. Era só Alt+// apertado e solto, mas Alt sozinho, ao soltar, liga a barra de menus do app da frente (o Firefox abria com a barra+// Arquivo/Editar/Exibir à mostra, igual ao F10; issue #8). Uma tecla sem função (vkE8) no meio desfaz isso. Marcadas+// como nossas: o gancho do teclado do Shell deixa passar.// Janelas "sempre por cima" de outros programas que estão acima de todas as nossas visíveis (uma ilha dinâmica de outro// app, um widget flutuante). Ao subir o Dock, a barra de menus ou a camada do revelar, elas iam para baixo da barra e// sumiam (issue #33: a ilha do Vibrance sumia ao clicar na mesa). Pega antes de subir as nossas; DevolveAlheias as põe// de volta por cima, na mesma ordem.std::vector<HWND> AlheiasNoTopo();void DevolveAlheias(const std::vector<HWND>& v);-inline void LiberaFrente() {- const ULONG_PTR M = 0x53484C4C;- keybd_event(VK_MENU, 0, 0, M); keybd_event(0xE8, 0, 0, M); keybd_event(0xE8, 0, KEYEVENTF_KEYUP, M); keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, M);-}-int RodarNativo(HINSTANCE dll, const std::wstring& dirBin, const std::wstring& logPath);-// abre o Finder com estes argumentos: no nativo, no Finder de dentro do explorer (MacFinder.dll); senão o WacOSFinder.exe-void AbrirFinder(const std::wstring& args);-// abre o Finder com estes argumentos: no nativo, no Finder de dentro do explorer (MacFinder.dll); senão o WacOSFinder.exe-void AbrirFinder(const std::wstring& args);-DWORD SemProprio(); // WINEVENT_SKIPOWNPROCESS fora do modo nativo (no nativo, o processo é o explorer)-void ThreadDeGancho(); // a thread atual segura um gancho global de mouse/teclado: prioridade alta e fora do EcoQoS-bool Nossa(HWND h); // janela do próprio Shell (no nativo: só as criadas pelo Shell, não as do explorer)-extern HINSTANCE inst;-extern std::wstring dir; // pasta do Shell.exe-void Quit(const wchar_t* why); // sai do shell e devolve a barra do Windows-void ApplyWorkArea();-std::wstring Setting(const wchar_t* key, const wchar_t* def);-void SetSetting(const wchar_t* key, const std::wstring& value);-RECT WorkAreaFor(HMONITOR mon); // a área de trabalho que o Shell reserva (barra de menus em cima, Dock embaixo), px-bool NaoIncomodar(HMONITOR mon); // app em tela cheia nesse monitor (nullptr = qualquer um) ou Windows em "não incomodar"-void Sound(const wchar_t* name);-bool OpenCalculator(const std::wstring& target); // alvo é a Calculadora do Windows: abre a nossa (Calculadora.exe)-void OpenForceQuit(bool memory); // Forçar Encerrar (Ctrl+Alt+Esc, menu da Apple); memory = "ficou sem memória"-void OpenMonitor(); // Monitor de Atividade (Ctrl+Shift+Esc, menu da Apple) // toca sons\mac\<name>.wav (sons do Mac), sem esperar-void OpenSettings(const std::wstring& page); // abre o Ajustes do Sistema (Ajustes.exe) na página // grava em %APPDATA%\Shell\ajustes.txt-// ShellExecute numa thread (com o disco ocupado ele segurou a interface 3,2 s; issue #32). Os textos são copiados na hora.-void Abrir(const wchar_t* verb, const wchar_t* file, const wchar_t* args = nullptr, const wchar_t* dir = nullptr, int show = SW_SHOWNORMAL);-// roda `f` na thread da interface (pela janela de mensagens): o resultado de um trabalho feito numa thread-void NaInterface(std::function<void()> f);-}--namespace sentinela { // sentinela.cpp: registra no shell.log onde a thread da interface ficou parada (1 s ou mais)-void Start(HWND alvo);-extern std::atomic<UINT> ultimaMsg; // o laço principal anota a mensagem que vai tratar-extern std::atomic<HWND> ultimaJanela;-}--namespace ampliar { // animação do "ampliar" do Mac nas janelas de outros apps (ampliar.cpp; pedida pela MacJanela.dll)-// Foto da janela no retângulo `from` (tela) animando até `to`. true = a foto já está na tela (a DLL esconde a janela)-bool Start(HWND h, RECT from, RECT to, int flags, COLORREF bar); // flags: 1 barra padrão (botões e título na foto), 2 janela de plug-in-void SecondPhoto(HWND h); // a janela já mudou de tamanho (escondida): foto nova entra por cima, ainda em movimento-void Shown(HWND h); // a janela de verdade reapareceu: as fotos somem-bool Fechar(HWND h, LPARAM bar = 0); // a janela vai sumir: foto dela encolhendo e sumindo, como no Mac (bar: a nossa barra, da DLL)-}-namespace abrir { // janela nova aparecendo como no Mac (abrir.cpp; pedida pela WacOSWindow.dll)-void Open(HWND h, HWND bar = nullptr); // a janela (e a nossa barra, se tiver) escondida e já pintada: anima e manda mostrar-}-namespace foto {-// Foto (BGRA pré-multiplicado, opaca) da parte `src` da janela `h` (coordenadas da miniatura do DWM);-// `corner` > 0: raio (px) dos cantos arredondados. Funciona com a janela minimizada.-bool Window(HWND h, const RECT& src, float corner, std::vector<BYTE>& bgra, UINT& w, UINT& hh);-// Várias janelas de uma vez, na placa de vídeo (Windows.Graphics.Capture), direto em superfícies do-// compositor (dispositivo de ui::Comp()). surf == nullptr na que falhar. Espera até `timeoutMs`.-struct Gpu { IDCompositionSurface* surf = nullptr; UINT w = 0, h = 0; };-std::vector<Gpu> Windows(const std::vector<HWND>& hs, const std::vector<RECT>& srcs, int timeoutMs = 150);-// Capturas que ficam abertas (guardam o último quadro de cada janela): Grab tira as fotos na hora.-struct Live;-Live* Start(const std::vector<HWND>& hs, const std::vector<RECT>& srcs);-std::vector<Gpu> Grab(Live* live, int timeoutMs = 150);-void Stop(Live* live);-}--namespace ponteiro { // ponteiro.cpp: sacudir o mouse faz o ponteiro crescer (como no Mac)-void Start();-void Stop();-// tema Mac OS X Leopard: liga o cursor do Mac OS X (guardando o esquema de antes) ou devolve o de antes-void TemaLeopard(bool on);-void Pausar(bool p); // modo jogo: sem Raw Input do mouse enquanto o jogo roda-}-namespace jogo { // Modo Jogo (jogo.cpp): jogo na frente → desliga o que mais pesa; ajuste modo_jogo, lista %APPDATA%\Shell\jogos.txt-void Start();-void Reload(); // ajustes mudaram-void Foreground(HWND h); // a janela da frente mudou-bool Ativo();-// gancho de EVENT_OBJECT_LOCATIONCHANGE que sai durante o modo jogo (cada movimento do cursor chegava ao Shell)-void GanchoPosicao(WINEVENTPROC fn, DWORD flags);-void SoltarPosicao(WINEVENTPROC fn);-}--namespace leve { // Modo leve (leve.cpp): PC fraco ou na bateria → sem vidro real, fosco mais barato, animações a ~60 quadros/s-void Start(); // vigia tomada/bateria-bool Atualizar(); // relê modo_leve, a bateria e o PC; true = mudou (quem chama recarrega o vidro)-bool Ativo(); // pode ser lido de qualquer thread-}+inline void LiberaFrente() {+ const ULONG_PTR M = 0x53484C4C;+ keybd_event(VK_MENU, 0, 0, M); keybd_event(0xE8, 0, 0, M); keybd_event(0xE8, 0, KEYEVENTF_KEYUP, M); keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, M);+}+int RodarNativo(HINSTANCE dll, const std::wstring& dirBin, const std::wstring& logPath);+// abre o Finder com estes argumentos: no nativo, no Finder de dentro do explorer (MacFinder.dll); senão o WacOSFinder.exe+void AbrirFinder(const std::wstring& args);+// abre o Finder com estes argumentos: no nativo, no Finder de dentro do explorer (MacFinder.dll); senão o WacOSFinder.exe+void AbrirFinder(const std::wstring& args);+DWORD SemProprio(); // WINEVENT_SKIPOWNPROCESS fora do modo nativo (no nativo, o processo é o explorer)+void ThreadDeGancho(); // a thread atual segura um gancho global de mouse/teclado: prioridade alta e fora do EcoQoS+bool Nossa(HWND h); // janela do próprio Shell (no nativo: só as criadas pelo Shell, não as do explorer)+extern HINSTANCE inst;+extern std::wstring dir; // pasta do Shell.exe+void Quit(const wchar_t* why); // sai do shell e devolve a barra do Windows+void ApplyWorkArea();+std::wstring Setting(const wchar_t* key, const wchar_t* def);+void SetSetting(const wchar_t* key, const std::wstring& value);+RECT WorkAreaFor(HMONITOR mon); // a área de trabalho que o Shell reserva (barra de menus em cima, Dock embaixo), px+bool NaoIncomodar(HMONITOR mon); // app em tela cheia nesse monitor (nullptr = qualquer um) ou Windows em "não incomodar"+void Sound(const wchar_t* name);+bool OpenCalculator(const std::wstring& target); // alvo é a Calculadora do Windows: abre a nossa (Calculadora.exe)+void OpenForceQuit(bool memory); // Forçar Encerrar (Ctrl+Alt+Esc, menu da Apple); memory = "ficou sem memória"+void OpenMonitor(); // Monitor de Atividade (Ctrl+Shift+Esc, menu da Apple) // toca sons\mac\<name>.wav (sons do Mac), sem esperar+void OpenSettings(const std::wstring& page); // abre o Ajustes do Sistema (Ajustes.exe) na página // grava em %APPDATA%\Shell\ajustes.txt+// ShellExecute numa thread (com o disco ocupado ele segurou a interface 3,2 s; issue #32). Os textos são copiados na hora.+void Abrir(const wchar_t* verb, const wchar_t* file, const wchar_t* args = nullptr, const wchar_t* dir = nullptr, int show = SW_SHOWNORMAL);+// roda `f` na thread da interface (pela janela de mensagens): o resultado de um trabalho feito numa thread+void NaInterface(std::function<void()> f);+}++namespace sentinela { // sentinela.cpp: registra no shell.log onde a thread da interface ficou parada (1 s ou mais)+void Start(HWND alvo);+extern std::atomic<UINT> ultimaMsg; // o laço principal anota a mensagem que vai tratar+extern std::atomic<HWND> ultimaJanela;+}++namespace ampliar { // animação do "ampliar" do Mac nas janelas de outros apps (ampliar.cpp; pedida pela MacJanela.dll)+// Foto da janela no retângulo `from` (tela) animando até `to`. true = a foto já está na tela (a DLL esconde a janela)+bool Start(HWND h, RECT from, RECT to, int flags, COLORREF bar); // flags: 1 barra padrão (botões e título na foto), 2 janela de plug-in+void SecondPhoto(HWND h); // a janela já mudou de tamanho (escondida): foto nova entra por cima, ainda em movimento+void Shown(HWND h); // a janela de verdade reapareceu: as fotos somem+bool Fechar(HWND h, LPARAM bar = 0); // a janela vai sumir: foto dela encolhendo e sumindo, como no Mac (bar: a nossa barra, da DLL)+}+namespace abrir { // janela nova aparecendo como no Mac (abrir.cpp; pedida pela WacOSWindow.dll)+void Open(HWND h, HWND bar = nullptr); // a janela (e a nossa barra, se tiver) escondida e já pintada: anima e manda mostrar+}+namespace foto {+// Foto (BGRA pré-multiplicado, opaca) da parte `src` da janela `h` (coordenadas da miniatura do DWM);+// `corner` > 0: raio (px) dos cantos arredondados. Funciona com a janela minimizada.+bool Window(HWND h, const RECT& src, float corner, std::vector<BYTE>& bgra, UINT& w, UINT& hh);+// Várias janelas de uma vez, na placa de vídeo (Windows.Graphics.Capture), direto em superfícies do+// compositor (dispositivo de ui::Comp()). surf == nullptr na que falhar. Espera até `timeoutMs`.+struct Gpu { IDCompositionSurface* surf = nullptr; UINT w = 0, h = 0; };+std::vector<Gpu> Windows(const std::vector<HWND>& hs, const std::vector<RECT>& srcs, int timeoutMs = 150);+// Capturas que ficam abertas (guardam o último quadro de cada janela): Grab tira as fotos na hora.+struct Live;+Live* Start(const std::vector<HWND>& hs, const std::vector<RECT>& srcs);+std::vector<Gpu> Grab(Live* live, int timeoutMs = 150);+void Stop(Live* live);+}++namespace ponteiro { // ponteiro.cpp: sacudir o mouse faz o ponteiro crescer (como no Mac)+void Start();+void Stop();+// tema Mac OS X Leopard: liga o cursor do Mac OS X (guardando o esquema de antes) ou devolve o de antes+void TemaLeopard(bool on);+void Pausar(bool p); // modo jogo: sem Raw Input do mouse enquanto o jogo roda+}+namespace jogo { // Modo Jogo (jogo.cpp): jogo na frente → desliga o que mais pesa; ajuste modo_jogo, lista %APPDATA%\Shell\jogos.txt+void Start();+void Reload(); // ajustes mudaram+void Foreground(HWND h); // a janela da frente mudou+bool Ativo();+// gancho de EVENT_OBJECT_LOCATIONCHANGE que sai durante o modo jogo (cada movimento do cursor chegava ao Shell)+void GanchoPosicao(WINEVENTPROC fn, DWORD flags);+void SoltarPosicao(WINEVENTPROC fn);+}++namespace leve { // Modo leve (leve.cpp): PC fraco ou na bateria → sem vidro real, fosco mais barato, animações a ~60 quadros/s+void Start(); // vigia tomada/bateria+bool Atualizar(); // relê modo_leve, a bateria e o PC; true = mudou (quem chama recarrega o vidro)+bool Ativo(); // pode ser lido de qualquer thread+}diff --git a/src/shell/siri.cpp b/src/shell/siri.cppindex e6b2a05..05cdcb7 100644--- a/src/shell/siri.cpp+++ b/src/shell/siri.cpp@@ -1,518 +1,634 @@-// Siri (issue #39, 23/11/2026): pergunta pelo Spotlight ("Perguntar à Siri") e a resposta num painel de vidro no alto-// da tela, como a Siri do macOS. Não há servidor do WacOS: a pergunta vai direto do PC para o serviço que o usuário-// escolheu nos Ajustes (Gemini, Groq, OpenAI ou o Ollama local), com a chave dele (src/comum/siri.h).-// A chamada roda numa thread (WinHTTP, até 60 s); cada pergunta tem um número, e a resposta de uma pergunta antiga-// (painel fechado ou outra pergunta feita) é descartada. Esc ou clicar fora fecha; Ctrl+C copia a resposta.-#include "shell.h"-#include "../comum/siri.h"-#include "../comum/simbolos.h"-#include "../comum/idioma.h"-#include <dwmapi.h>-#include <windowsx.h>-#include <thread>-#include <atomic>-#include <algorithm>-#include <cmath>--namespace {--const UINT WM_SIRI_FIM = WM_APP + 70, WM_SIRI_FRAME = WM_APP + 71;-const UINT_PTR T_PONTOS = 1;-const float W = 560, PAD = 20, ORB = 30, R = 22;-const float M = 28; // folga em volta do painel para o brilho (os cliques nela atravessam: WM_NCHITTEST)--HWND g_wnd, g_back;-ui::GpuSurface g_s;-bool g_glass, g_inGlass, g_open;-std::wstring g_q, g_a;-bool g_busy, g_erro;-std::atomic<int> g_num{ 0 };-int g_pontos;-float g_scroll, g_contentH, g_viewH;-double g_openAt, g_answerAt, g_closeAt;-bool g_closing;-ID2D1StrokeStyle* g_round;-IDWriteTextFormat *g_tfQ, *g_tfA;--// ---------------------------------------------------------------- a pergunta (thread)-std::wstring Limpa(std::wstring t) { // os modelos insistem em Markdown: tira o que fica feio em texto puro- for (const wchar_t* m : { L"**", L"__", L"`" }) for (size_t i; (i = t.find(m)) != std::wstring::npos;) t.erase(i, wcslen(m));- std::wstring o; bool ini = true;- for (size_t i = 0; i < t.size(); i++) {- if (ini) { // "# Título" e "* item" no começo da linha- while (i < t.size() && t[i] == L'#') i++;- if (i + 1 < t.size() && (t[i] == L'*' || t[i] == L'-') && t[i + 1] == L' ') { o += L"• "; i += 2; }- while (i < t.size() && t[i] == L' ' && !o.empty() && o.back() == L'\n') i++;- }- if (i >= t.size()) break;- o += t[i];- ini = t[i] == L'\n';- }- while (!o.empty() && iswspace(o.back())) o.pop_back();- size_t s = 0; while (s < o.size() && iswspace(o[s])) s++;- return o.substr(s);-}--// o modelo não existe mais (ou nunca existiu) para esta conta: os serviços dizem isso de jeitos diferentes-bool ModeloSumiu(DWORD status, const std::wstring& msg) {- if (status != 400 && status != 404) return false;- std::wstring l = msg; for (auto& c : l) c = (wchar_t)towlower(c);- for (const wchar_t* w : { L"no longer available", L"not found", L"does not exist", L"not supported", L"decommissioned", L"deprecated",- L"invalid model", L"unknown model", L"model_not_found", L"is not a valid model" })- if (l.find(w) != std::wstring::npos) return true;- return false;-}--std::wstring PerguntaCli(const siri::Provedor& pv, const std::wstring& q, bool& erro) {- const std::wstring instr = L"Answer briefly and clearly, in the same language as the question, in plain text without Markdown. "- L"Do not run commands or edit files. Question: ";- DWORD codigo = 0; bool tempo = false;- wchar_t tmp[MAX_PATH]; GetTempPathW(MAX_PATH, tmp);- std::wstring ultima = std::wstring(tmp) + L"WacOS-Siri\\ultima.txt";- DeleteFileW(ultima.c_str());- std::wstring r = siri::RodaCli(pv.caminho, instr + q, codigo, tempo);- Log(L"siri: %ls -> código %lu, %zu caracteres%ls", pv.nome, codigo, r.size(), tempo ? L" (passou do tempo)" : L"");- if (tempo) return Tr(L"O app demorou demais para responder.");- if (codigo == 9009 || codigo == ERROR_FILE_NOT_FOUND) // o cmd não achou o comando- return std::wstring(Tr(L"Não achei o app neste PC. Instale e entre na sua conta nele:")) + L" " + pv.site;- // o Codex grava a última mensagem num arquivo (a saída tem o resto da conversa)- HANDLE h = CreateFileW(ultima.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);- if (h != INVALID_HANDLE_VALUE) {- DWORD sz = GetFileSize(h, nullptr), n = 0;- std::string b(sz < (1u << 20) ? sz : 0, 0);- if (!b.empty() && ReadFile(h, b.data(), sz, &n, nullptr)) r = siri::Wide(b);- CloseHandle(h);- DeleteFileW(ultima.c_str());- }- if (codigo != 0 || r.empty()) {- std::wstring t = Limpa(r);- if (t.size() > 400) t = t.substr(t.size() - 400);- return std::wstring(Tr(L"O app não respondeu. Ele está instalado e com a conta entrada?")) + (t.empty() ? L"" : L"\n\n" + t);- }- erro = false;- return Limpa(r);-}--std::wstring Pergunta(const std::wstring& q, bool& erro) {- erro = true;- const auto& provs = siri::Provedores();- int p = std::clamp(_wtoi(shell::Setting(L"siri_provedor", L"0").c_str()), 0, (int)provs.size() - 1);- if (p == 0) return Tr(L"Escolha um serviço para a Siri em Ajustes do Sistema > Apple Intelligence e Siri.");- const auto& pv = provs[p];- if (pv.fmt == siri::F_CLI) return PerguntaCli(pv, q, erro);- std::wstring modelo = shell::Setting(L"siri_modelo", pv.modelos.empty() ? L"" : pv.modelos[0]);- std::wstring chave = pv.precisaChave ? siri::LeChave(p) : L"";- if (pv.precisaChave && chave.empty()) return Tr(L"Falta a chave da API. Cole a chave em Ajustes do Sistema > Apple Intelligence e Siri.");- if (modelo.empty()) { // LM Studio e afins: o modelo carregado- std::wstring e; auto l = siri::ListaModelos(p, e);- if (!l.empty()) modelo = l[0];- }- const std::wstring sistema = L"You are Siri inside WacOS, a macOS-style desktop for Windows. Answer briefly and clearly, "- L"in the same language as the question. Use plain text, without Markdown.";- std::wstring cab = siri::Cabecalhos(pv, chave);- SecureZeroMemory(chave.data(), chave.size() * sizeof(wchar_t));- siri::Resposta r;- for (int tentativa = 0; tentativa < 3; tentativa++) {- std::string body;- std::wstring caminho = pv.caminho;- if (pv.fmt == siri::F_GEMINI) {- size_t m = caminho.find(L"{m}"); if (m != std::wstring::npos) caminho.replace(m, 3, modelo);- body = "{\"systemInstruction\":{\"parts\":[{\"text\":" + siri::JStr(sistema) + "}]},\"contents\":[{\"role\":\"user\",\"parts\":[{\"text\":" + siri::JStr(q) + "}]}]}";- } else if (pv.fmt == siri::F_ANTHROPIC) {- body = "{\"model\":" + siri::JStr(modelo) + ",\"max_tokens\":1024,\"system\":" + siri::JStr(sistema) +- ",\"messages\":[{\"role\":\"user\",\"content\":" + siri::JStr(q) + "}]}";- } else { // OpenAI e compatíveis (Groq, OpenRouter, Mistral, DeepSeek, xAI, LM Studio) e Ollama- body = "{\"model\":" + siri::JStr(modelo) + ",\"messages\":[{\"role\":\"system\",\"content\":" + siri::JStr(sistema) + "},{\"role\":\"user\",\"content\":" + siri::JStr(q) + "}]" +- (pv.fmt == siri::F_OLLAMA ? ",\"stream\":false}" : "}");- }- r = siri::Http(pv, L"POST", caminho, cab, body);- Log(L"siri: %ls %ls -> %lu (%zu bytes, erro %lu)", pv.nome, modelo.c_str(), r.status, r.corpo.size(), r.falha);- if (r.falha || tentativa >= 2) break;- if (r.status == 503 || r.status == 500 || r.status == 529) { // sobrecarregado: de novo; depois, outro modelo da lista (só nesta pergunta)- if (!tentativa) { Sleep(1500); continue; }- std::wstring e; auto lista = siri::ListaModelos(p, e);- std::wstring alt;- // o reserva: estável (sem preview/omni/exp), de preferência da mesma família (Flash no Gemini)- for (auto& m : lista) {- if (m == modelo || m.find(L"lite") != std::wstring::npos || m.find(L"preview") != std::wstring::npos ||- m.find(L"omni") != std::wstring::npos || m.find(L"exp") != std::wstring::npos || m.find(L"latest") != std::wstring::npos) continue;- bool familia = pv.fmt != siri::F_GEMINI || m.find(L"flash") != std::wstring::npos;- if (familia) { alt = m; break; }- if (alt.empty()) alt = m;- }- if (!alt.empty()) { Log(L"siri: %ls sobrecarregado; tentando %ls", modelo.c_str(), alt.c_str()); modelo = alt; continue; }- break;- }- // cota zerada deste modelo (o plano grátis não inclui todos): tenta o preferido da lista, que costuma estar no plano- std::wstring msgErro = siri::ErroDoServico(r.corpo), lm = msgErro;- for (auto& c : lm) c = (wchar_t)towlower(c);- bool semCota = r.status == 429 && lm.find(L"quota") != std::wstring::npos;- if (semCota) {- std::wstring e; auto lista = siri::ListaModelos(p, e);- if (!lista.empty() && lista[0] != modelo) {- Log(L"siri: sem cota em %ls; tentando %ls", modelo.c_str(), lista[0].c_str());- modelo = lista[0];- shell::SetSetting(L"siri_modelo", modelo.c_str());- continue;- }- }- if (!ModeloSumiu(r.status, msgErro)) { if (r.status >= 400) Log(L"siri: erro do serviço: %ls", siri::ErroDoServico(r.corpo).substr(0, 200).c_str()); break; }- // o modelo saiu do ar: pega a lista atual do serviço, guarda o preferido dela e pergunta de novo- std::wstring e; auto lista = siri::ListaModelos(p, e);- if (lista.empty() || lista[0] == modelo) { Log(L"siri: o modelo saiu do ar, mas a lista não trouxe outro (%ls)", e.empty() ? L"vazia" : e.c_str()); break; }- Log(L"siri: %ls não existe mais; agora %ls", modelo.c_str(), lista[0].c_str());- modelo = lista[0];- shell::SetSetting(L"siri_modelo", modelo.c_str());- std::wstring junta; for (auto& m : lista) junta += (junta.empty() ? L"" : L"|") + m;- shell::SetSetting((L"siri_modelos_" + std::to_wstring(p)).c_str(), junta.c_str());- }- SecureZeroMemory(cab.data(), cab.size() * sizeof(wchar_t)); // a chave ia no cabeçalho- if (r.falha) {- if (pv.porta != 443) return std::wstring(Tr(L"Não deu para falar com o app neste PC. Ele está aberto?")) + L" (" + pv.nome + L")";- return Tr(L"Não deu para falar com o serviço. Confira a internet.");- }- std::wstring t;- if (r.status >= 200 && r.status < 300) {- bool ok = pv.fmt == siri::F_GEMINI ? siri::JLe(r.corpo, "text", r.corpo.find("\"candidates\""), t)- : pv.fmt == siri::F_ANTHROPIC ? siri::JLe(r.corpo, "text", r.corpo.find("\"content\""), t)- : siri::JLe(r.corpo, "content", r.corpo.find("\"message\""), t);- if (ok && !t.empty()) { erro = false; return Limpa(t); }- return Tr(L"O serviço respondeu sem texto.");- }- t = siri::ErroDoServico(r.corpo);- if (r.status == 429) {- std::wstring l = t; for (auto& c : l) c = (wchar_t)towlower(c);- if (l.find(L"quota") != std::wstring::npos || l.find(L"rate") != std::wstring::npos)- return std::wstring(Tr(L"Acabou a cota deste modelo no seu plano (o grátis tem limite por minuto e por dia). Espere um pouco ou escolha outro modelo em Ajustes do Sistema > Apple Intelligence e Siri.")) + L" (" + modelo + L")";- }- // as mensagens dos serviços podem ter várias linhas e links: só a primeira frase- if (size_t nlPos = t.find(L'\n'); nlPos != std::wstring::npos) t = t.substr(0, nlPos);- if (t.size() > 240) t = t.substr(0, 237) + L"...";- if (!t.empty()) return (r.status == 401 || r.status == 403 ? std::wstring(Tr(L"Chave recusada pelo serviço.")) + L" " : std::wstring()) + t;- return std::wstring(Tr(L"O serviço recusou a pergunta")) + L" (" + std::to_wstring(r.status) + L").";-}--// ---------------------------------------------------------------- painel-float Sc() { return g_wnd ? ui::Scale(g_wnd) : 1.f; }--float AlturaTexto(const std::wstring& t, IDWriteTextFormat* f, float w) {- IDWriteTextLayout* l = nullptr; float h = 0;- if (f && SUCCEEDED(ui::dw->CreateTextLayout(t.c_str(), (UINT32)t.size(), f, w, 10000, &l))) { DWRITE_TEXT_METRICS m{}; l->GetMetrics(&m); h = m.height; l->Release(); }- return h;-}--// ---- o brilho da Siri: uma luz colorida que corre pela borda do painel e se espalha para fora, como a do Apple-// Intelligence. A cor de cada ponto da borda depende da posição nela e do tempo (as cores andam em volta); por baixo, três-// traços largos e fracos fazem o brilho; por cima, o fio forte. Enquanto pensa: inteiro e "respirando"; quando a resposta-// chega, apaga em 0,9 s.-D2D1_COLOR_F CorDaVolta(float u) { // u em [0,1): rosa, roxo, azul, ciano, laranja e de volta ao rosa- static const D2D1_COLOR_F c[] = { { 1.f, 0.33f, 0.62f, 1 }, { 0.68f, 0.36f, 1.f, 1 }, { 0.26f, 0.52f, 1.f, 1 },- { 0.30f, 0.86f, 1.f, 1 }, { 1.f, 0.64f, 0.30f, 1 } };- const int n = 5;- u = u - std::floor(u);- float f = u * n; int a = (int)f % n, b = (a + 1) % n; float k = f - std::floor(f);- k = k * k * (3 - 2 * k); // suave entre as cores- return { c[a].r + (c[b].r - c[a].r) * k, c[a].g + (c[b].g - c[a].g) * k, c[a].b + (c[b].b - c[a].b) * k, 1 };-}-// ponto da borda do retângulo arredondado em u (0..1, sentido horário a partir do meio de cima)-D2D1_POINT_2F PontoDaBorda(const D2D1_RECT_F& r, float rad, float u) {- float w = r.right - r.left, h = r.bottom - r.top, arco = 1.5707963f * rad;- float retoX = w - 2 * rad, retoY = h - 2 * rad, total = 2 * retoX + 2 * retoY + 4 * arco;- float d = (u - std::floor(u)) * total;- auto canto = [&](float cx, float cy, float a0, float t) { float a = a0 + t / rad; return D2D1_POINT_2F{ cx + std::cos(a) * rad, cy + std::sin(a) * rad }; };- float x0 = r.left + w / 2;- // do meio de cima para a direita- float seg = retoX / 2; if (d < seg) return { x0 + d, r.top }; d -= seg;- if (d < arco) return canto(r.right - rad, r.top + rad, -1.5707963f, d); d -= arco;- if (d < retoY) return { r.right, r.top + rad + d }; d -= retoY;- if (d < arco) return canto(r.right - rad, r.bottom - rad, 0, d); d -= arco;- if (d < retoX) return { r.right - rad - d, r.bottom }; d -= retoX;- if (d < arco) return canto(r.left + rad, r.bottom - rad, 1.5707963f, d); d -= arco;- if (d < retoY) return { r.left, r.bottom - rad - d }; d -= retoY;- if (d < arco) return canto(r.left + rad, r.top + rad, 3.1415926f, d); d -= arco;- return { r.left + rad + std::min(d, retoX / 2), r.top };-}-void Brilho(ID2D1DeviceContext* dc, const D2D1_RECT_F& box, float rad, double tMs, float forca) {- if (forca <= 0.01f) return;- ID2D1SolidColorBrush* br = nullptr;- dc->CreateSolidColorBrush(D2D1::ColorF(1, 1, 1), &br);- if (!br) return;- const int N = 180;- float gira = (float)(tMs / 2600.0); // as cores dão uma volta a cada 2,6 s- struct Camada { float largura, alfa; } camadas[] = { { 22, 0.06f }, { 13, 0.10f }, { 7, 0.18f }, { 2.6f, 0.95f } };- std::vector<D2D1_POINT_2F> pts(N + 1);- for (int k = 0; k <= N; k++) pts[k] = PontoDaBorda(box, rad, (float)k / N);- for (auto& cm : camadas) {- for (int k = 0; k < N; k++) {- float u = (float)k / N;- D2D1_COLOR_F c = CorDaVolta(u * 2 + gira); // duas voltas de cor pela borda inteira- // um trecho mais claro corre pela borda (a "onda" de luz)- float onda = 0.55f + 0.45f * std::cos(6.2831853f * (u - gira * 0.7f));- c.a = cm.alfa * forca * (cm.largura > 3 ? onda : 0.75f + 0.25f * onda);- br->SetColor(c);- dc->DrawLine(pts[k], pts[k + 1], br, cm.largura, g_round);- }- }- br->Release();-}--void Orbe(ID2D1DeviceContext* dc, D2D1_POINT_2F c, float r, double t) {- // a bolinha da Siri: as cores giram enquanto pensa (e devagar depois), com um brilho que pulsa- D2D1_GRADIENT_STOP gs[4] = { { 0, D2D1::ColorF(0.98f, 0.36f, 0.62f) }, { 0.35f, D2D1::ColorF(0.62f, 0.38f, 1.f) },- { 0.7f, D2D1::ColorF(0.25f, 0.62f, 1.f) }, { 1, D2D1::ColorF(1.f, 0.62f, 0.32f) } };- ID2D1GradientStopCollection* sc = nullptr;- if (FAILED(dc->CreateGradientStopCollection(gs, 4, &sc))) return;- float a = (float)(t / (g_busy ? 700.0 : 2400.0));- float pulso = g_busy ? 1.f + 0.07f * (float)std::sin(t / 260.0) : 1.f;- float rr = r * pulso;- ID2D1SolidColorBrush* br = nullptr;- dc->CreateSolidColorBrush(D2D1::ColorF(0.62f, 0.38f, 1.f, g_busy ? 0.22f : 0.12f), &br);- if (br) { dc->FillEllipse(D2D1::Ellipse(c, rr + 5, rr + 5), br); } // halo- D2D1_POINT_2F p0{ c.x + std::cos(a) * rr, c.y + std::sin(a) * rr }, p1{ c.x - std::cos(a) * rr, c.y - std::sin(a) * rr };- ID2D1LinearGradientBrush* lg = nullptr;- if (SUCCEEDED(dc->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties(p0, p1), sc, &lg))) {- dc->FillEllipse(D2D1::Ellipse(c, rr, rr), lg);- lg->Release();- }- sc->Release();- if (br) { // reflexo em cima, como uma bolha de vidro- br->SetColor(D2D1::ColorF(1, 1, 1, 0.38f));- dc->FillEllipse(D2D1::Ellipse({ c.x - rr * 0.25f, c.y - rr * 0.38f }, rr * 0.45f, rr * 0.25f), br);- br->SetColor(D2D1::ColorF(1, 1, 1, 0.35f));- dc->DrawEllipse(D2D1::Ellipse(c, rr - 0.5f, rr - 0.5f), br, 1);- br->Release();- }-}--// quanto do brilho aparece agora (1 pensando, apagando em 0,9 s depois da resposta)-float ForcaBrilho(double now) {- if (g_busy) return 0.85f + 0.15f * (float)std::sin(now / 420.0);- float k = (float)((now - g_answerAt) / 900.0);- return k >= 1 ? 0.f : (1 - k) * (1 - k);-}-bool Animando(double now) {- return g_closing || g_busy || !anim::PanelIn(now - g_openAt).done || now - g_answerAt < 950;-}--void Paint() {- if ((!g_open && !g_closing) || !g_wnd) return;- double now = anim::Now();- float sc = Sc();- bool dark = ui::Dark();- float textW = W - PAD * 2 - ORB - 14;- std::wstring a = g_busy ? std::wstring(Tr(L"Pensando")) + std::wstring((size_t)(g_pontos % 3 + 1), L'.') : g_a;- float qh = AlturaTexto(g_q, g_tfQ, textW), ah = AlturaTexto(a, g_tfA, textW);- g_contentH = PAD + qh + 8 + ah + PAD;- HMONITOR hm = MonitorFromWindow(g_wnd, MONITOR_DEFAULTTONEAREST);- MONITORINFO mi{ sizeof(mi) }; GetMonitorInfoW(hm, &mi);- float maxH = (mi.rcWork.bottom - mi.rcWork.top) / sc * 0.6f;- float H = std::clamp(g_contentH, ORB + PAD * 2, maxH);- g_viewH = H;- g_scroll = std::clamp(g_scroll, 0.f, std::max(0.f, g_contentH - H));- int wpx = (int)std::lround((W + 2 * M) * sc), hpx = (int)std::lround((H + 2 * M) * sc);- RECT wr; GetWindowRect(g_wnd, &wr);- if (wr.bottom - wr.top != hpx || wr.right - wr.left != wpx) {- SetWindowPos(g_wnd, nullptr, 0, 0, wpx, hpx, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);- if (g_back) SetWindowPos(g_back, g_wnd, wr.left, wr.top, wpx, hpx, SWP_NOACTIVATE);- }- float mpx = M * sc;- if (g_glass) backdrop::SetPieces(g_back, (float)wpx, (float)hpx, { { D2D1::RectF(mpx, mpx, wpx - mpx, hpx - mpx), R * sc } },- dark ? D2D1::ColorF(0.13f, 0.13f, 0.14f, 0.55f) : D2D1::ColorF(0.96f, 0.96f, 0.97f, 0.50f), 24.f);- ID2D1DeviceContext* dc = g_glass ? backdrop::ContentBegin(g_back, wpx, hpx, sc) : nullptr;- g_inGlass = dc != nullptr;- if (!dc) dc = ui::GpuBegin(g_s, wpx, hpx, sc);- if (!dc) return;- D2D1_MATRIX_3X2_F base; dc->GetTransform(&base);- dc->SetTransform(D2D1::Matrix3x2F::Translation(M, M) * base); // o painel começa na folga- ID2D1SolidColorBrush* br = nullptr;- dc->CreateSolidColorBrush(D2D1::ColorF(1, 1, 1), &br);- if (br) {- D2D1_RECT_F box = D2D1::RectF(0, 0, W, H);- Brilho(dc, D2D1::RectF(-1, -1, W + 1, H + 1), R + 1, now - g_openAt, ForcaBrilho(now));- if (!g_glass) { br->SetColor(dark ? D2D1::ColorF(0.16f, 0.16f, 0.17f, 0.95f) : D2D1::ColorF(0.96f, 0.96f, 0.97f, 0.95f)); dc->FillRoundedRectangle(D2D1::RoundedRect(box, R, R), br); }- if (liquid::On()) liquid::Rim(dc, box, R, dark);- else { br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.14f) : D2D1::ColorF(0, 0, 0, 0.12f)); dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(0.5f, 0.5f, W - 0.5f, H - 0.5f), R, R), br, 1); }- Orbe(dc, { PAD + ORB / 2, PAD + ORB / 2 }, ORB / 2, now - g_openAt);- float x = PAD + ORB + 14;- dc->PushAxisAlignedClip(D2D1::RectF(x - 2, 8, W - PAD + 2, H - 8), D2D1_ANTIALIAS_MODE_ALIASED);- float y = PAD - g_scroll;- br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.55f) : D2D1::ColorF(0, 0, 0, 0.5f));- dc->DrawTextW(g_q.c_str(), (UINT32)g_q.size(), g_tfQ, D2D1::RectF(x, y, x + textW, y + qh + 4), br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT);- y += qh + 8;- // a resposta entra subindo um pouco e aparecendo (0,35 s)- float k = g_busy ? 1.f : std::clamp((float)((now - g_answerAt) / 350.0), 0.f, 1.f);- float e = 1 - (1 - k) * (1 - k) * (1 - k);- D2D1_COLOR_F tc = g_erro ? D2D1::ColorF(1.f, 0.42f, 0.38f) : dark ? D2D1::ColorF(1, 1, 1, 0.95f) : D2D1::ColorF(0, 0, 0, 0.88f);- tc.a *= g_busy ? 0.6f + 0.25f * (float)std::sin(now / 300.0) : e;- br->SetColor(tc);- float dy = (1 - e) * 8;- dc->DrawTextW(a.c_str(), (UINT32)a.size(), g_tfA, D2D1::RectF(x, y + dy, x + textW, y + dy + ah + 4), br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT); // emoji colorido- dc->PopAxisAlignedClip();- if (g_contentH > H) { // barrinha de rolagem fina- float bh = std::max(24.f, H * H / g_contentH), by = 6 + (H - 12 - bh) * (g_scroll / (g_contentH - H));- br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.3f) : D2D1::ColorF(0, 0, 0, 0.25f));- dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(W - 8, by, W - 4, by + bh), 2, 2), br);- }- br->Release();- }- dc->SetTransform(base);- if (g_inGlass) backdrop::ContentEnd(g_back); else ui::GpuEnd(g_s);-}--// a mola de abrir (crescendo do meio) e a de fechar: escala e opacidade pelo compositor-void Movimento() {- double now = anim::Now();- anim::Panel mo = g_closing ? anim::PanelOut(now - g_closeAt) : anim::PanelIn(now - g_openAt);- RECT wr; GetWindowRect(g_wnd, &wr);- float cx = (wr.right - wr.left) / 2.f, cy = (wr.bottom - wr.top) / 2.f;- if (g_inGlass) backdrop::Fade(g_back, mo.fade, mo.scale, cx, cy);- else { ui::GpuMotion(g_s, mo.scale, cx, cy, mo.fade); if (g_back) backdrop::Fade(g_back, mo.fade, mo.scale, cx, cy); }-}--void Esconde() {- Log(L"siri: painel escondido");- g_closing = false;- ui::FrameClock(g_wnd, WM_SIRI_FRAME, false);- ShowWindow(g_wnd, SW_HIDE);- if (g_back) ShowWindow(g_back, SW_HIDE);-}--void Fecha() {- if (!g_open) return;- g_open = false; g_busy = false;- g_num++; // a resposta que ainda vem é descartada- KillTimer(g_wnd, T_PONTOS);- if (anim::reduceMotion) { Esconde(); return; }- g_closing = true; g_closeAt = anim::Now();- ui::FrameClock(g_wnd, WM_SIRI_FRAME, true);-}--void Copia() {- if (g_busy || g_a.empty() || !OpenClipboard(g_wnd)) return;- EmptyClipboard();- size_t n = (g_a.size() + 1) * sizeof(wchar_t);- if (HGLOBAL g = GlobalAlloc(GMEM_MOVEABLE, n)) { memcpy(GlobalLock(g), g_a.c_str(), n); GlobalUnlock(g); SetClipboardData(CF_UNICODETEXT, g); }- CloseClipboard();-}--LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {- switch (m) {- case WM_SIRI_FIM: {- std::wstring* r = (std::wstring*)l;- if ((int)w == g_num && g_open) {- g_erro = r->size() > 1 && (*r)[0] == L'\x1';- g_a = g_erro ? r->substr(1) : *r;- g_busy = false; g_scroll = 0;- g_answerAt = anim::Now();- KillTimer(h, T_PONTOS);- Paint(); // o brilho apaga e a resposta entra: os quadros continuam (WM_SIRI_FRAME)- }- delete r;- return 0;- }- case WM_SIRI_FRAME: {- ui::FrameAck(h, WM_SIRI_FRAME);- double now = anim::Now();- if (g_closing) {- Movimento();- if (anim::PanelOut(now - g_closeAt).done) Esconde();- return 0;- }- Paint(); Movimento();- if (!Animando(now)) ui::FrameClock(h, WM_SIRI_FRAME, false);- return 0;- }- case WM_NCHITTEST: { // só o painel pega o clique; a folga do brilho deixa passar- POINT pt{ GET_X_LPARAM(l), GET_Y_LPARAM(l) };- RECT wr; GetWindowRect(h, &wr);- float sc = Sc(); int mpx = (int)std::lround(M * sc);- return pt.x >= wr.left + mpx && pt.x < wr.right - mpx && pt.y >= wr.top + mpx && pt.y < wr.bottom - mpx ? HTCLIENT : HTTRANSPARENT;- }- case WM_TIMER: if (w == T_PONTOS) { g_pontos++; if (!Animando(anim::Now())) Paint(); } return 0;- case WM_MOUSEWHEEL: g_scroll -= GET_WHEEL_DELTA_WPARAM(w) / 120.f * 48; Paint(); return 0;- case WM_KEYDOWN:- if (w == VK_ESCAPE) Fecha();- else if (w == 'C' && GetKeyState(VK_CONTROL) < 0) Copia();- else if (w == VK_DOWN) { g_scroll += 40; Paint(); }- else if (w == VK_UP) { g_scroll -= 40; Paint(); }- return 0;- case WM_ACTIVATE:- if (LOWORD(w) == WA_INACTIVE && g_open) {- wchar_t c[64] = {}; if (l) GetClassNameW((HWND)l, c, 64);- Log(L"siri: perdeu a frente para %ls; fecha", c[0] ? c : L"(nenhuma)");- Fecha();- }- return 0;- case WM_CLOSE: Fecha(); return 0;- }- return DefWindowProcW(h, m, w, l);-}-LRESULT CALLBACK BackProc(HWND h, UINT m, WPARAM w, LPARAM l) {- if (m == WM_MOUSEACTIVATE) return MA_NOACTIVATE;- if (m == WM_NCHITTEST) return HTTRANSPARENT;- return DefWindowProcW(h, m, w, l);-}--bool Ready() {- if (g_wnd && IsWindow(g_wnd)) return true;- HINSTANCE hi = shell::inst;- WNDCLASSW wc{}; wc.lpfnWndProc = Proc; wc.hInstance = hi; wc.lpszClassName = L"ShellSiri"; wc.hCursor = LoadCursorW(nullptr, IDC_ARROW);- RegisterClassW(&wc);- WNDCLASSW bc{}; bc.lpfnWndProc = BackProc; bc.hInstance = hi; bc.lpszClassName = L"ShellSiriFundo";- RegisterClassW(&bc);- g_wnd = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP, wc.lpszClassName, L"Siri", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);- g_back = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP, bc.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);- if (!g_wnd || !g_back) { Log(L"siri: janela não criada (%lu)", GetLastError()); return false; }- g_glass = backdrop::Attach(g_back);- if (!g_glass) { DestroyWindow(g_back); g_back = nullptr; }- apps::ours.push_back(g_wnd); if (g_back) apps::ours.push_back(g_back);- g_s.hwnd = g_wnd;- g_tfQ = ui::Format(12.5f, DWRITE_FONT_WEIGHT_NORMAL);- g_tfA = ui::Format(15, DWRITE_FONT_WEIGHT_NORMAL);- for (auto* f : { g_tfQ, g_tfA }) if (f) f->SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);- D2D1_STROKE_STYLE_PROPERTIES sp = D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_ROUND);- ui::d2d->CreateStrokeStyle(sp, nullptr, 0, &g_round);- return true;-}--} // namespace--bool siri::Pronta() {- const auto& provs = siri::Provedores();- int p = _wtoi(shell::Setting(L"siri_provedor", L"0").c_str());- if (p <= 0 || p >= (int)provs.size()) return false;- return !provs[p].precisaChave || GetFileAttributesW(siri::ArquivoChave(p).c_str()) != INVALID_FILE_ATTRIBUTES;-}--void siri::Perguntar(const std::wstring& q) {- if (q.empty() || !Ready()) return;- g_q = q; g_a.clear(); g_busy = true; g_erro = false; g_scroll = 0; g_pontos = 0;- int num = ++g_num;- // no alto do monitor do ponteiro, centralizado (onde a Siri do Mac aparece... e onde o Spotlight estava)- POINT pt; GetCursorPos(&pt);- HMONITOR hm = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);- MONITORINFO mi{ sizeof(mi) }; GetMonitorInfoW(hm, &mi);- float sc = ui::Scale(g_wnd);- int wpx = (int)std::lround((W + 2 * M) * sc), hpx = (int)std::lround((ORB + PAD * 2 + 2 * M) * sc);- int x = (mi.rcWork.left + mi.rcWork.right - wpx) / 2, y = mi.rcWork.top + (mi.rcWork.bottom - mi.rcWork.top) / 6 - (int)std::lround(M * sc);- SetWindowPos(g_wnd, HWND_TOPMOST, x, y, wpx, hpx, SWP_NOACTIVATE);- if (g_back) SetWindowPos(g_back, g_wnd, x, y, wpx, hpx, SWP_NOACTIVATE);- g_open = true; g_closing = false; g_openAt = anim::Now(); g_answerAt = 0;- if (g_glass) backdrop::Fade(g_back, 0, 0.94f, wpx / 2.f, hpx / 2.f); // nasce invisível e um pouco menor: a mola leva até o tamanho- else ui::GpuMotion(g_s, 0.94f, wpx / 2.f, hpx / 2.f, 0);- Paint();- if (g_back) ShowWindow(g_back, SW_SHOWNOACTIVATE);- ShowWindow(g_wnd, SW_SHOW);- shell::LiberaFrente();- SetForegroundWindow(g_wnd); SetFocus(g_wnd);- SetTimer(g_wnd, T_PONTOS, 420, nullptr);- ui::FrameClock(g_wnd, WM_SIRI_FRAME, true); // a mola de abrir, o brilho e a bolinha enquanto pensa- HWND to = g_wnd;- std::thread([q, num, to] {- CoInitializeEx(nullptr, COINIT_MULTITHREADED);- bool erro = false;- std::wstring r = Pergunta(q, erro);- PostMessageW(to, WM_SIRI_FIM, (WPARAM)num, (LPARAM)new std::wstring((erro ? L"\x1" : L"") + r));- CoUninitialize();- }).detach();-}+// Siri (issue #39, 23/11/2026): pergunta pelo Spotlight ("Perguntar à Siri") e a resposta num painel de vidro no alto+// da tela, como a Siri do macOS. Não há servidor do WacOS: a pergunta vai direto do PC para o serviço que o usuário+// escolheu nos Ajustes (Gemini, Groq, OpenAI ou o Ollama local), com a chave dele (src/comum/siri.h).+// A chamada roda numa thread (WinHTTP, até 60 s); cada pergunta tem um número, e a resposta de uma pergunta antiga+// (painel fechado ou outra pergunta feita) é descartada. Esc ou clicar fora fecha; Ctrl+C copia a resposta.+#include "shell.h"+#include "../comum/siri.h"+#include "../comum/simbolos.h"+#include "../comum/idioma.h"+#include <dwmapi.h>+#include <windowsx.h>+#include <thread>+#include <atomic>+#include <algorithm>+#include <cmath>++namespace {++const UINT WM_SIRI_FIM = WM_APP + 70, WM_SIRI_FRAME = WM_APP + 71;+const UINT_PTR T_PONTOS = 1;+const float W = 560, PAD = 20, ORB = 30, R = 22;+const float M = 28; // folga em volta do painel para o brilho (os cliques nela atravessam: WM_NCHITTEST)++HWND g_wnd, g_back;+ui::GpuSurface g_s;+bool g_glass, g_inGlass, g_open;+std::wstring g_q, g_a;+bool g_busy, g_erro;+std::atomic<int> g_num{ 0 };+int g_pontos;+float g_scroll, g_contentH, g_viewH;+double g_openAt, g_answerAt, g_closeAt;+bool g_closing;+bool g_teste;+// campo de digitar (aberta pelo ícone da barra, ou digitando depois de uma resposta): g_texto é o que foi digitado+bool g_entrada;+std::wstring g_texto;+const UINT_PTR T_CURSOR = 2;+bool g_cursorOn = true; // 'SIRT' (teste com um jogo na frente): não pega a frente, não fecha ao perder a frente, some em 8 s+ID2D1StrokeStyle* g_round;+IDWriteTextFormat *g_tfQ, *g_tfA;++// ---------------------------------------------------------------- a pergunta (thread)+std::wstring Limpa(std::wstring t) { // os modelos insistem em Markdown: tira o que fica feio em texto puro+ for (const wchar_t* m : { L"**", L"__", L"`" }) for (size_t i; (i = t.find(m)) != std::wstring::npos;) t.erase(i, wcslen(m));+ std::wstring o; bool ini = true;+ for (size_t i = 0; i < t.size(); i++) {+ if (ini) { // "# Título" e "* item" no começo da linha+ while (i < t.size() && t[i] == L'#') i++;+ if (i + 1 < t.size() && (t[i] == L'*' || t[i] == L'-') && t[i + 1] == L' ') { o += L"• "; i += 2; }+ while (i < t.size() && t[i] == L' ' && !o.empty() && o.back() == L'\n') i++;+ }+ if (i >= t.size()) break;+ o += t[i];+ ini = t[i] == L'\n';+ }+ while (!o.empty() && iswspace(o.back())) o.pop_back();+ size_t s = 0; while (s < o.size() && iswspace(o[s])) s++;+ return o.substr(s);+}++// o modelo não existe mais (ou nunca existiu) para esta conta: os serviços dizem isso de jeitos diferentes+bool ModeloSumiu(DWORD status, const std::wstring& msg) {+ if (status != 400 && status != 404) return false;+ std::wstring l = msg; for (auto& c : l) c = (wchar_t)towlower(c);+ for (const wchar_t* w : { L"no longer available", L"not found", L"does not exist", L"not supported", L"decommissioned", L"deprecated",+ L"invalid model", L"unknown model", L"model_not_found", L"is not a valid model" })+ if (l.find(w) != std::wstring::npos) return true;+ return false;+}++// outro modelo da lista para esta pergunta: estável (sem preview/omni/exp/latest/lite), da mesma família (Flash no Gemini)+std::wstring Reserva(const std::vector<std::wstring>& lista, const std::wstring& atual, bool gemini) {+ std::wstring alt;+ for (auto& m : lista) {+ if (m == atual || m.find(L"lite") != std::wstring::npos || m.find(L"preview") != std::wstring::npos ||+ m.find(L"omni") != std::wstring::npos || m.find(L"exp") != std::wstring::npos || m.find(L"latest") != std::wstring::npos) continue;+ if (!gemini || m.find(L"flash") != std::wstring::npos) return m;+ if (alt.empty()) alt = m;+ }+ return alt;+}++std::wstring PerguntaCli(const siri::Provedor& pv, const std::wstring& q, bool& erro) {+ const std::wstring instr = L"Answer briefly and clearly, in the same language as the question, in plain text without Markdown. "+ L"Do not run commands or edit files. Question: ";+ DWORD codigo = 0; bool tempo = false;+ wchar_t tmp[MAX_PATH]; GetTempPathW(MAX_PATH, tmp);+ std::wstring ultima = std::wstring(tmp) + L"WacOS-Siri\\ultima.txt";+ DeleteFileW(ultima.c_str());+ std::wstring r = siri::RodaCli(pv.caminho, instr + q, codigo, tempo);+ Log(L"siri: %ls -> código %lu, %zu caracteres%ls", pv.nome, codigo, r.size(), tempo ? L" (passou do tempo)" : L"");+ if (tempo) return Tr(L"O app demorou demais para responder.");+ if (codigo == 9009 || codigo == ERROR_FILE_NOT_FOUND) // o cmd não achou o comando+ return std::wstring(Tr(L"Não achei o app neste PC. Instale e entre na sua conta nele:")) + L" " + pv.site;+ // o Codex grava a última mensagem num arquivo (a saída tem o resto da conversa)+ HANDLE h = CreateFileW(ultima.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);+ if (h != INVALID_HANDLE_VALUE) {+ DWORD sz = GetFileSize(h, nullptr), n = 0;+ std::string b(sz < (1u << 20) ? sz : 0, 0);+ if (!b.empty() && ReadFile(h, b.data(), sz, &n, nullptr)) r = siri::Wide(b);+ CloseHandle(h);+ DeleteFileW(ultima.c_str());+ }+ if (codigo != 0 || r.empty()) {+ std::wstring t = Limpa(r);+ if (t.size() > 400) t = t.substr(t.size() - 400);+ return std::wstring(Tr(L"O app não respondeu. Ele está instalado e com a conta entrada?")) + (t.empty() ? L"" : L"\n\n" + t);+ }+ erro = false;+ return Limpa(r);+}++std::wstring Pergunta(const std::wstring& q, bool& erro) {+ erro = true;+ const auto& provs = siri::Provedores();+ int p = std::clamp(_wtoi(shell::Setting(L"siri_provedor", L"0").c_str()), 0, (int)provs.size() - 1);+ if (p == 0) return Tr(L"Escolha um serviço para a Siri em Ajustes do Sistema > Apple Intelligence e Siri.");+ const auto& pv = provs[p];+ if (pv.fmt == siri::F_CLI) return PerguntaCli(pv, q, erro);+ std::wstring modelo = shell::Setting(L"siri_modelo", pv.modelos.empty() ? L"" : pv.modelos[0]);+ std::wstring chave = pv.precisaChave ? siri::LeChave(p) : L"";+ if (pv.precisaChave && chave.empty()) return Tr(L"Falta a chave da API. Cole a chave em Ajustes do Sistema > Apple Intelligence e Siri.");+ if (modelo.empty()) { // LM Studio e afins: o modelo carregado+ std::wstring e; auto l = siri::ListaModelos(p, e);+ if (!l.empty()) modelo = l[0];+ }+ const std::wstring sistema = L"You are Siri inside WacOS, a macOS-style desktop for Windows. Answer briefly and clearly, "+ L"in the same language as the question. Use plain text, without Markdown.";+ std::wstring cab = siri::Cabecalhos(pv, chave);+ SecureZeroMemory(chave.data(), chave.size() * sizeof(wchar_t));+ siri::Resposta r;+ for (int tentativa = 0; tentativa < 3; tentativa++) {+ std::string body;+ std::wstring caminho = pv.caminho;+ if (pv.fmt == siri::F_GEMINI) {+ size_t m = caminho.find(L"{m}"); if (m != std::wstring::npos) caminho.replace(m, 3, modelo);+ body = "{\"systemInstruction\":{\"parts\":[{\"text\":" + siri::JStr(sistema) + "}]},\"contents\":[{\"role\":\"user\",\"parts\":[{\"text\":" + siri::JStr(q) + "}]}]}";+ } else if (pv.fmt == siri::F_ANTHROPIC) {+ body = "{\"model\":" + siri::JStr(modelo) + ",\"max_tokens\":1024,\"system\":" + siri::JStr(sistema) ++ ",\"messages\":[{\"role\":\"user\",\"content\":" + siri::JStr(q) + "}]}";+ } else { // OpenAI e compatíveis (Groq, OpenRouter, Mistral, DeepSeek, xAI, LM Studio) e Ollama+ body = "{\"model\":" + siri::JStr(modelo) + ",\"messages\":[{\"role\":\"system\",\"content\":" + siri::JStr(sistema) + "},{\"role\":\"user\",\"content\":" + siri::JStr(q) + "}]" ++ (pv.fmt == siri::F_OLLAMA ? ",\"stream\":false}" : "}");+ }+ r = siri::Http(pv, L"POST", caminho, cab, body);+ Log(L"siri: %ls %ls -> %lu (%zu bytes, erro %lu)", pv.nome, modelo.c_str(), r.status, r.corpo.size(), r.falha);+ if (r.falha || tentativa >= 2) break;+ if (r.status == 503 || r.status == 500 || r.status == 529) { // sobrecarregado: de novo; depois, outro modelo da lista (só nesta pergunta)+ if (!tentativa) { Sleep(1500); continue; }+ std::wstring e; auto lista = siri::ListaModelos(p, e);+ std::wstring alt;+ alt = Reserva(lista, modelo, pv.fmt == siri::F_GEMINI);+ if (!alt.empty()) { Log(L"siri: %ls sobrecarregado; tentando %ls", modelo.c_str(), alt.c_str()); modelo = alt; continue; }+ break;+ }+ // cota zerada deste modelo (o plano grátis não inclui todos): tenta o preferido da lista, que costuma estar no plano+ std::wstring msgErro = siri::ErroDoServico(r.corpo), lm = msgErro;+ for (auto& c : lm) c = (wchar_t)towlower(c);+ bool semCota = r.status == 429 && lm.find(L"quota") != std::wstring::npos;+ if (semCota) {+ std::wstring e; auto lista = siri::ListaModelos(p, e);+ std::wstring outro = !lista.empty() && lista[0] != modelo ? lista[0] : Reserva(lista, modelo, pv.fmt == siri::F_GEMINI);+ if (!outro.empty()) {+ Log(L"siri: sem cota em %ls; tentando %ls", modelo.c_str(), outro.c_str());+ modelo = outro;+ continue; // só nesta pergunta: a cota volta amanhã, e o escolhido nos Ajustes fica+ }+ }+ if (!ModeloSumiu(r.status, msgErro)) { if (r.status >= 400) Log(L"siri: erro do serviço: %ls", siri::ErroDoServico(r.corpo).substr(0, 200).c_str()); break; }+ // o modelo saiu do ar: pega a lista atual do serviço, guarda o preferido dela e pergunta de novo+ std::wstring e; auto lista = siri::ListaModelos(p, e);+ if (lista.empty() || lista[0] == modelo) { Log(L"siri: o modelo saiu do ar, mas a lista não trouxe outro (%ls)", e.empty() ? L"vazia" : e.c_str()); break; }+ Log(L"siri: %ls não existe mais; agora %ls", modelo.c_str(), lista[0].c_str());+ modelo = lista[0];+ shell::SetSetting(L"siri_modelo", modelo.c_str());+ std::wstring junta; for (auto& m : lista) junta += (junta.empty() ? L"" : L"|") + m;+ shell::SetSetting((L"siri_modelos_" + std::to_wstring(p)).c_str(), junta.c_str());+ }+ SecureZeroMemory(cab.data(), cab.size() * sizeof(wchar_t)); // a chave ia no cabeçalho+ if (r.falha) {+ if (pv.porta != 443) return std::wstring(Tr(L"Não deu para falar com o app neste PC. Ele está aberto?")) + L" (" + pv.nome + L")";+ return Tr(L"Não deu para falar com o serviço. Confira a internet.");+ }+ std::wstring t;+ if (r.status >= 200 && r.status < 300) {+ bool ok = pv.fmt == siri::F_GEMINI ? siri::JLe(r.corpo, "text", r.corpo.find("\"candidates\""), t)+ : pv.fmt == siri::F_ANTHROPIC ? siri::JLe(r.corpo, "text", r.corpo.find("\"content\""), t)+ : siri::JLe(r.corpo, "content", r.corpo.find("\"message\""), t);+ if (ok && !t.empty()) { erro = false; return Limpa(t); }+ return Tr(L"O serviço respondeu sem texto.");+ }+ t = siri::ErroDoServico(r.corpo);+ if (r.status == 429) {+ std::wstring l = t; for (auto& c : l) c = (wchar_t)towlower(c);+ if (l.find(L"quota") != std::wstring::npos || l.find(L"rate") != std::wstring::npos)+ return std::wstring(Tr(L"Acabou a cota deste modelo no seu plano (o grátis tem limite por minuto e por dia). Espere um pouco ou escolha outro modelo em Ajustes do Sistema > Apple Intelligence e Siri.")) + L" (" + modelo + L")";+ }+ // as mensagens dos serviços podem ter várias linhas e links: só a primeira frase+ if (size_t nlPos = t.find(L'\n'); nlPos != std::wstring::npos) t = t.substr(0, nlPos);+ if (t.size() > 240) t = t.substr(0, 237) + L"...";+ if (!t.empty()) return (r.status == 401 || r.status == 403 ? std::wstring(Tr(L"Chave recusada pelo serviço.")) + L" " : std::wstring()) + t;+ return std::wstring(Tr(L"O serviço recusou a pergunta")) + L" (" + std::to_wstring(r.status) + L").";+}++// ---------------------------------------------------------------- painel+float Sc() { return g_wnd ? ui::Scale(g_wnd) : 1.f; }++float AlturaTexto(const std::wstring& t, IDWriteTextFormat* f, float w) {+ IDWriteTextLayout* l = nullptr; float h = 0;+ if (f && SUCCEEDED(ui::dw->CreateTextLayout(t.c_str(), (UINT32)t.size(), f, w, 10000, &l))) { DWRITE_TEXT_METRICS m{}; l->GetMetrics(&m); h = m.height; l->Release(); }+ return h;+}++// ---- o brilho da Siri: uma luz colorida que corre pela borda do painel e se espalha para fora, como a do Apple+// Intelligence. A cor de cada ponto da borda depende da posição nela e do tempo (as cores andam em volta); por baixo, três+// traços largos e fracos fazem o brilho; por cima, o fio forte. Enquanto pensa: inteiro e "respirando"; quando a resposta+// chega, apaga em 0,9 s.+D2D1_COLOR_F CorDaVolta(float u) { // u em [0,1): rosa, roxo, azul, ciano, laranja e de volta ao rosa+ static const D2D1_COLOR_F c[] = { { 1.f, 0.33f, 0.62f, 1 }, { 0.68f, 0.36f, 1.f, 1 }, { 0.26f, 0.52f, 1.f, 1 },+ { 0.30f, 0.86f, 1.f, 1 }, { 1.f, 0.64f, 0.30f, 1 } };+ const int n = 5;+ u = u - std::floor(u);+ float f = u * n; int a = (int)f % n, b = (a + 1) % n; float k = f - std::floor(f);+ k = k * k * (3 - 2 * k); // suave entre as cores+ return { c[a].r + (c[b].r - c[a].r) * k, c[a].g + (c[b].g - c[a].g) * k, c[a].b + (c[b].b - c[a].b) * k, 1 };+}+// ponto da borda do retângulo arredondado em u (0..1, sentido horário a partir do meio de cima)+D2D1_POINT_2F PontoDaBorda(const D2D1_RECT_F& r, float rad, float u) {+ float w = r.right - r.left, h = r.bottom - r.top, arco = 1.5707963f * rad;+ float retoX = w - 2 * rad, retoY = h - 2 * rad, total = 2 * retoX + 2 * retoY + 4 * arco;+ float d = (u - std::floor(u)) * total;+ auto canto = [&](float cx, float cy, float a0, float t) { float a = a0 + t / rad; return D2D1_POINT_2F{ cx + std::cos(a) * rad, cy + std::sin(a) * rad }; };+ float x0 = r.left + w / 2;+ // do meio de cima para a direita+ float seg = retoX / 2; if (d < seg) return { x0 + d, r.top }; d -= seg;+ if (d < arco) return canto(r.right - rad, r.top + rad, -1.5707963f, d); d -= arco;+ if (d < retoY) return { r.right, r.top + rad + d }; d -= retoY;+ if (d < arco) return canto(r.right - rad, r.bottom - rad, 0, d); d -= arco;+ if (d < retoX) return { r.right - rad - d, r.bottom }; d -= retoX;+ if (d < arco) return canto(r.left + rad, r.bottom - rad, 1.5707963f, d); d -= arco;+ if (d < retoY) return { r.left, r.bottom - rad - d }; d -= retoY;+ if (d < arco) return canto(r.left + rad, r.top + rad, 3.1415926f, d); d -= arco;+ return { r.left + rad + std::min(d, retoX / 2), r.top };+}+void Brilho(ID2D1DeviceContext* dc, const D2D1_RECT_F& box, float rad, double tMs, float forca) {+ if (forca <= 0.01f) return;+ ID2D1SolidColorBrush* br = nullptr;+ dc->CreateSolidColorBrush(D2D1::ColorF(1, 1, 1), &br);+ if (!br) return;+ const int N = 240;+ float gira = (float)(tMs / 2600.0); // as cores dão uma volta a cada 2,6 s+ struct Camada { float largura, alfa; } camadas[] = { { 22, 0.06f }, { 13, 0.10f }, { 7, 0.18f }, { 2.6f, 0.95f } };+ ID2D1Factory* fab = nullptr; dc->GetFactory(&fab);+ static ID2D1Factory* fabDoTraco = nullptr;+ if (fab && fab != fabDoTraco) {+ if (g_round) { g_round->Release(); g_round = nullptr; }+ D2D1_STROKE_STYLE_PROPERTIES sp = D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_ROUND);+ fab->CreateStrokeStyle(sp, nullptr, 0, &g_round);+ fabDoTraco = fab;+ }+ if (fab) fab->Release();+ std::vector<D2D1_POINT_2F> pts(N + 1);+ for (int k = 0; k <= N; k++) pts[k] = PontoDaBorda(box, rad, (float)k / N);+ for (auto& cm : camadas) {+ for (int k = 0; k < N; k++) {+ float u = (float)k / N;+ D2D1_COLOR_F c = CorDaVolta(u * 2 + gira); // duas voltas de cor pela borda inteira+ // um trecho mais claro corre pela borda (a "onda" de luz)+ float onda = 0.55f + 0.45f * std::cos(6.2831853f * (u - gira * 0.7f));+ c.a = cm.alfa * forca * (cm.largura > 3 ? onda : 0.75f + 0.25f * onda);+ br->SetColor(c);+ // pontas retas nas camadas translúcidas (as redondas se sobrepunham e faziam "contas" na borda); redondas no fio+ dc->DrawLine(pts[k], pts[k + 1], br, cm.largura, cm.largura > 3 ? nullptr : g_round);+ }+ }+ br->Release();+}++void Orbe(ID2D1DeviceContext* dc, D2D1_POINT_2F c, float r, double t) {+ // a bolinha da Siri: as cores giram enquanto pensa (e devagar depois), com um brilho que pulsa+ D2D1_GRADIENT_STOP gs[4] = { { 0, D2D1::ColorF(0.98f, 0.36f, 0.62f) }, { 0.35f, D2D1::ColorF(0.62f, 0.38f, 1.f) },+ { 0.7f, D2D1::ColorF(0.25f, 0.62f, 1.f) }, { 1, D2D1::ColorF(1.f, 0.62f, 0.32f) } };+ ID2D1GradientStopCollection* sc = nullptr;+ if (FAILED(dc->CreateGradientStopCollection(gs, 4, &sc))) return;+ float a = (float)(t / (g_busy ? 700.0 : 2400.0));+ float pulso = g_busy ? 1.f + 0.07f * (float)std::sin(t / 260.0) : 1.f;+ float rr = r * pulso;+ ID2D1SolidColorBrush* br = nullptr;+ dc->CreateSolidColorBrush(D2D1::ColorF(0.62f, 0.38f, 1.f, g_busy ? 0.22f : 0.12f), &br);+ if (br) { dc->FillEllipse(D2D1::Ellipse(c, rr + 5, rr + 5), br); } // halo+ D2D1_POINT_2F p0{ c.x + std::cos(a) * rr, c.y + std::sin(a) * rr }, p1{ c.x - std::cos(a) * rr, c.y - std::sin(a) * rr };+ ID2D1LinearGradientBrush* lg = nullptr;+ if (SUCCEEDED(dc->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties(p0, p1), sc, &lg))) {+ dc->FillEllipse(D2D1::Ellipse(c, rr, rr), lg);+ lg->Release();+ }+ sc->Release();+ if (br) { // reflexo em cima, como uma bolha de vidro+ br->SetColor(D2D1::ColorF(1, 1, 1, 0.38f));+ dc->FillEllipse(D2D1::Ellipse({ c.x - rr * 0.25f, c.y - rr * 0.38f }, rr * 0.45f, rr * 0.25f), br);+ br->SetColor(D2D1::ColorF(1, 1, 1, 0.35f));+ dc->DrawEllipse(D2D1::Ellipse(c, rr - 0.5f, rr - 0.5f), br, 1);+ br->Release();+ }+}++// quanto do brilho aparece agora (1 pensando, apagando em 0,9 s depois da resposta)+float ForcaBrilho(double now) {+ if (g_entrada) return 0;+ if (g_busy) return 0.85f + 0.15f * (float)std::sin(now / 420.0);+ float k = (float)((now - g_answerAt) / 900.0);+ return k >= 1 ? 0.f : (1 - k) * (1 - k);+}+bool Animando(double now) {+ return g_closing || g_busy || !anim::PanelIn(now - g_openAt).done || now - g_answerAt < 950;+}++void Paint() {+ if ((!g_open && !g_closing) || !g_wnd) return;+ double now = anim::Now();+ float sc = Sc();+ bool dark = ui::Dark();+ float textW = W - PAD * 2 - ORB - 14;+ std::wstring a = g_busy ? std::wstring(Tr(L"Pensando")) + std::wstring((size_t)(g_pontos % 3 + 1), L'.') : g_a;+ float qh = AlturaTexto(g_q, g_tfQ, textW), ah = AlturaTexto(a, g_tfA, textW);+ g_contentH = PAD + qh + 8 + ah + PAD;+ if (g_entrada) { // só o campo: uma linha (ou mais, se o texto quebrar)+ qh = 0; ah = std::max(AlturaTexto(g_texto.empty() ? L"M" : g_texto, g_tfA, textW), 20.f);+ g_contentH = std::max(ORB + PAD * 2, PAD + ah + PAD + 4);+ }+ HMONITOR hm = MonitorFromWindow(g_wnd, MONITOR_DEFAULTTONEAREST);+ MONITORINFO mi{ sizeof(mi) }; GetMonitorInfoW(hm, &mi);+ float maxH = (mi.rcWork.bottom - mi.rcWork.top) / sc * 0.6f;+ float H = std::clamp(g_contentH, ORB + PAD * 2, maxH);+ g_viewH = H;+ g_scroll = std::clamp(g_scroll, 0.f, std::max(0.f, g_contentH - H));+ int wpx = (int)std::lround((W + 2 * M) * sc), hpx = (int)std::lround((H + 2 * M) * sc);+ RECT wr; GetWindowRect(g_wnd, &wr);+ if (wr.bottom - wr.top != hpx || wr.right - wr.left != wpx) {+ SetWindowPos(g_wnd, nullptr, 0, 0, wpx, hpx, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);+ if (g_back) SetWindowPos(g_back, g_wnd, wr.left, wr.top, wpx, hpx, SWP_NOACTIVATE);+ }+ float mpx = M * sc;+ if (g_glass) backdrop::SetPieces(g_back, (float)wpx, (float)hpx, { { D2D1::RectF(mpx, mpx, wpx - mpx, hpx - mpx), R * sc } },+ dark ? D2D1::ColorF(0.13f, 0.13f, 0.14f, 0.55f) : D2D1::ColorF(0.96f, 0.96f, 0.97f, 0.50f), 24.f);+ ID2D1DeviceContext* dc = g_glass ? backdrop::ContentBegin(g_back, wpx, hpx, sc) : nullptr;+ g_inGlass = dc != nullptr;+ if (!dc) dc = ui::GpuBegin(g_s, wpx, hpx, sc);+ if (!dc) return;+ D2D1_MATRIX_3X2_F base; dc->GetTransform(&base);+ dc->SetTransform(D2D1::Matrix3x2F::Translation(M, M) * base); // o painel começa na folga+ ID2D1SolidColorBrush* br = nullptr;+ dc->CreateSolidColorBrush(D2D1::ColorF(1, 1, 1), &br);+ if (br) {+ D2D1_RECT_F box = D2D1::RectF(0, 0, W, H);+ if (!g_inGlass) Brilho(dc, D2D1::RectF(-1, -1, W + 1, H + 1), R + 1, now - g_openAt, ForcaBrilho(now));+ if (!g_glass) { br->SetColor(dark ? D2D1::ColorF(0.16f, 0.16f, 0.17f, 0.95f) : D2D1::ColorF(0.96f, 0.96f, 0.97f, 0.95f)); dc->FillRoundedRectangle(D2D1::RoundedRect(box, R, R), br); }+ if (liquid::On()) liquid::Rim(dc, box, R, dark);+ else { br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.14f) : D2D1::ColorF(0, 0, 0, 0.12f)); dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(0.5f, 0.5f, W - 0.5f, H - 0.5f), R, R), br, 1); }+ Orbe(dc, { PAD + ORB / 2, PAD + ORB / 2 }, ORB / 2, now - g_openAt);+ float x = PAD + ORB + 14;+ if (g_entrada) { // o campo: o texto digitado (ou o convite em cinza) e o cursor piscando+ float y0 = (H - ah) / 2;+ bool vazio = g_texto.empty();+ const std::wstring& t = vazio ? std::wstring(Tr(L"Pergunte à Siri…")) : g_texto;+ br->SetColor(vazio ? (dark ? D2D1::ColorF(1, 1, 1, 0.38f) : D2D1::ColorF(0, 0, 0, 0.35f)) : (dark ? D2D1::ColorF(1, 1, 1, 0.95f) : D2D1::ColorF(0, 0, 0, 0.88f)));+ dc->DrawTextW(t.c_str(), (UINT32)t.size(), g_tfA, D2D1::RectF(x, y0, x + textW, y0 + ah + 4), br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT);+ if (g_cursorOn) { // o cursor no fim do texto+ IDWriteTextLayout* lay = nullptr; float cx = x, cy = y0, ch = 18;+ if (!vazio && SUCCEEDED(ui::dw->CreateTextLayout(g_texto.c_str(), (UINT32)g_texto.size(), g_tfA, textW, 10000, &lay))) {+ DWRITE_HIT_TEST_METRICS hm{}; FLOAT px = 0, py = 0;+ lay->HitTestTextPosition((UINT32)g_texto.size() - 1, TRUE, &px, &py, &hm);+ cx = x + px; cy = y0 + py; ch = hm.height; lay->Release();+ }+ br->SetColor(D2D1::ColorF(0.40f, 0.52f, 1.f));+ dc->FillRectangle(D2D1::RectF(cx + 1, cy + 1, cx + 3, cy + ch - 1), br);+ }+ br->Release();+ dc->SetTransform(base);+ if (g_inGlass) {+ backdrop::ContentEnd(g_back);+ if (ID2D1DeviceContext* gd = ui::GpuBegin(g_s, wpx, hpx, sc)) ui::GpuEnd(g_s); // sem brilho enquanto digita+ } else ui::GpuEnd(g_s);+ return;+ }+ dc->PushAxisAlignedClip(D2D1::RectF(x - 2, 8, W - PAD + 2, H - 8), D2D1_ANTIALIAS_MODE_ALIASED);+ float y = PAD - g_scroll;+ br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.55f) : D2D1::ColorF(0, 0, 0, 0.5f));+ dc->DrawTextW(g_q.c_str(), (UINT32)g_q.size(), g_tfQ, D2D1::RectF(x, y, x + textW, y + qh + 4), br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT);+ y += qh + 8;+ // a resposta entra subindo um pouco e aparecendo (0,35 s)+ float k = g_busy ? 1.f : std::clamp((float)((now - g_answerAt) / 350.0), 0.f, 1.f);+ float e = 1 - (1 - k) * (1 - k) * (1 - k);+ D2D1_COLOR_F tc = g_erro ? D2D1::ColorF(1.f, 0.42f, 0.38f) : dark ? D2D1::ColorF(1, 1, 1, 0.95f) : D2D1::ColorF(0, 0, 0, 0.88f);+ tc.a *= g_busy ? 0.6f + 0.25f * (float)std::sin(now / 300.0) : e;+ br->SetColor(tc);+ float dy = (1 - e) * 8;+ dc->DrawTextW(a.c_str(), (UINT32)a.size(), g_tfA, D2D1::RectF(x, y + dy, x + textW, y + dy + ah + 4), br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT); // emoji colorido+ dc->PopAxisAlignedClip();+ if (g_contentH > H) { // barrinha de rolagem fina+ float bh = std::max(24.f, H * H / g_contentH), by = 6 + (H - 12 - bh) * (g_scroll / (g_contentH - H));+ br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.3f) : D2D1::ColorF(0, 0, 0, 0.25f));+ dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(W - 8, by, W - 4, by + bh), 2, 2), br);+ }+ br->Release();+ }+ dc->SetTransform(base);+ if (g_inGlass) {+ backdrop::ContentEnd(g_back);+ // o desenho dentro do vidro é recortado no formato do painel: o brilho, que passa para fora, vai na janela da frente+ // (transparente, do tamanho da folga)+ if (ID2D1DeviceContext* gd = ui::GpuBegin(g_s, wpx, hpx, sc)) {+ D2D1_MATRIX_3X2_F b2; gd->GetTransform(&b2);+ gd->SetTransform(D2D1::Matrix3x2F::Translation(M, M) * b2);+ Brilho(gd, D2D1::RectF(-1, -1, W + 1, H + 1), R + 1, now - g_openAt, ForcaBrilho(now));+ gd->SetTransform(b2);+ ui::GpuEnd(g_s);+ }+ } else ui::GpuEnd(g_s);+}++// a mola de abrir (crescendo do meio) e a de fechar: escala e opacidade pelo compositor+void Movimento() {+ double now = anim::Now();+ anim::Panel mo = g_closing ? anim::PanelOut(now - g_closeAt) : anim::PanelIn(now - g_openAt);+ RECT wr; GetWindowRect(g_wnd, &wr);+ float cx = (wr.right - wr.left) / 2.f, cy = (wr.bottom - wr.top) / 2.f;+ ui::GpuMotion(g_s, mo.scale, cx, cy, mo.fade); // o brilho (ou tudo, sem vidro)+ if (g_back) backdrop::Fade(g_back, mo.fade, mo.scale, cx, cy);+}++void Esconde() {+ Log(L"siri: painel escondido");+ g_closing = false;+ ui::FrameClock(g_wnd, WM_SIRI_FRAME, false);+ ShowWindow(g_wnd, SW_HIDE);+ if (g_back) ShowWindow(g_back, SW_HIDE);+}++void Fecha() {+ if (!g_open) return;+ g_open = false; g_busy = false;+ g_num++; // a resposta que ainda vem é descartada+ KillTimer(g_wnd, T_PONTOS);+ if (anim::reduceMotion) { Esconde(); return; }+ g_closing = true; g_closeAt = anim::Now();+ ui::FrameClock(g_wnd, WM_SIRI_FRAME, true);+}++void Copia() {+ if (g_busy || g_a.empty() || !OpenClipboard(g_wnd)) return;+ EmptyClipboard();+ size_t n = (g_a.size() + 1) * sizeof(wchar_t);+ if (HGLOBAL g = GlobalAlloc(GMEM_MOVEABLE, n)) { memcpy(GlobalLock(g), g_a.c_str(), n); GlobalUnlock(g); SetClipboardData(CF_UNICODETEXT, g); }+ CloseClipboard();+}++LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {+ switch (m) {+ case WM_SIRI_FIM: {+ std::wstring* r = (std::wstring*)l;+ if ((int)w == g_num && g_open) {+ g_erro = r->size() > 1 && (*r)[0] == L'\x1';+ g_a = g_erro ? r->substr(1) : *r;+ g_busy = false; g_scroll = 0;+ g_answerAt = anim::Now();+ KillTimer(h, T_PONTOS);+ Paint(); // o brilho apaga e a resposta entra: os quadros continuam (WM_SIRI_FRAME)+ }+ delete r;+ return 0;+ }+ case WM_SIRI_FRAME: {+ ui::FrameAck(h, WM_SIRI_FRAME);+ double now = anim::Now();+ if (g_closing) {+ Movimento();+ if (anim::PanelOut(now - g_closeAt).done) Esconde();+ return 0;+ }+ Paint(); Movimento();+ if (!Animando(now)) ui::FrameClock(h, WM_SIRI_FRAME, false);+ return 0;+ }+ case WM_NCHITTEST: { // só o painel pega o clique; a folga do brilho deixa passar+ POINT pt{ GET_X_LPARAM(l), GET_Y_LPARAM(l) };+ RECT wr; GetWindowRect(h, &wr);+ float sc = Sc(); int mpx = (int)std::lround(M * sc);+ return pt.x >= wr.left + mpx && pt.x < wr.right - mpx && pt.y >= wr.top + mpx && pt.y < wr.bottom - mpx ? HTCLIENT : HTTRANSPARENT;+ }+ case WM_TIMER: if (w == 9) { KillTimer(h, 9); Fecha(); return 0; }+ if (w == T_CURSOR) { g_cursorOn = !g_cursorOn; if (g_entrada) Paint(); else KillTimer(h, T_CURSOR); return 0; }+ if (w == T_PONTOS) { g_pontos++; if (!Animando(anim::Now())) Paint(); } return 0;+ case WM_MOUSEWHEEL: g_scroll -= GET_WHEEL_DELTA_WPARAM(w) / 120.f * 48; Paint(); return 0;+ case WM_CHAR:+ { static int n; if (n++ < 3) Log(L"siri: tecla %u (aberta %d, pensando %d, campo %d)", (unsigned)w, g_open, g_busy, g_entrada); }+ if (!g_open || g_busy) return 0;+ if (w == 13) { // Enter: pergunta+ if (g_entrada && !g_texto.empty()) { std::wstring q = g_texto; siri::Perguntar(q, g_teste); }+ return 0;+ }+ if (w == 8) { if (g_entrada && !g_texto.empty()) { g_texto.pop_back(); g_cursorOn = true; Paint(); } return 0; }+ if (w >= 32 && w != 127 && !(GetKeyState(VK_CONTROL) < 0 && GetKeyState(VK_MENU) >= 0)) {+ if (!g_entrada) { g_entrada = true; g_texto.clear(); g_q.clear(); g_a.clear(); g_scroll = 0; } // digitou depois da resposta: outra pergunta+ if (g_texto.size() < 2000) g_texto += (wchar_t)w;+ g_cursorOn = true; SetTimer(h, T_CURSOR, 530, nullptr);+ Paint();+ }+ return 0;+ case WM_KEYDOWN:+ if (w == 'V' && GetKeyState(VK_CONTROL) < 0 && !g_busy && OpenClipboard(h)) { // colar no campo+ if (HANDLE cb = GetClipboardData(CF_UNICODETEXT)) {+ if (auto* p = (const wchar_t*)GlobalLock(cb)) {+ std::wstring t = p; GlobalUnlock(cb);+ for (auto& c : t) if (c == L'\r' || c == L'\n' || c == L'\t') c = L' ';+ if (!g_entrada) { g_entrada = true; g_texto.clear(); g_q.clear(); g_a.clear(); }+ g_texto += t.substr(0, 2000 - std::min<size_t>(2000, g_texto.size()));+ }+ }+ CloseClipboard();+ Paint();+ return 0;+ }+ if (w == VK_ESCAPE) Fecha();+ else if (w == 'C' && GetKeyState(VK_CONTROL) < 0) Copia();+ else if (w == VK_DOWN) { g_scroll += 40; Paint(); }+ else if (w == VK_UP) { g_scroll -= 40; Paint(); }+ return 0;+ case WM_ACTIVATE:+ if (LOWORD(w) == WA_INACTIVE && g_open && !g_teste) {+ wchar_t c[64] = {}; if (l) GetClassNameW((HWND)l, c, 64);+ Log(L"siri: perdeu a frente para %ls; fecha", c[0] ? c : L"(nenhuma)");+ Fecha();+ }+ return 0;+ case WM_CLOSE: Fecha(); return 0;+ }+ return DefWindowProcW(h, m, w, l);+}+LRESULT CALLBACK BackProc(HWND h, UINT m, WPARAM w, LPARAM l) {+ if (m == WM_MOUSEACTIVATE) return MA_NOACTIVATE;+ if (m == WM_NCHITTEST) return HTTRANSPARENT;+ return DefWindowProcW(h, m, w, l);+}++bool Ready() {+ if (g_wnd && IsWindow(g_wnd)) return true;+ HINSTANCE hi = shell::inst;+ WNDCLASSW wc{}; wc.lpfnWndProc = Proc; wc.hInstance = hi; wc.lpszClassName = L"ShellSiri"; wc.hCursor = LoadCursorW(nullptr, IDC_ARROW);+ RegisterClassW(&wc);+ WNDCLASSW bc{}; bc.lpfnWndProc = BackProc; bc.hInstance = hi; bc.lpszClassName = L"ShellSiriFundo";+ RegisterClassW(&bc);+ g_wnd = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP, wc.lpszClassName, L"Siri", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);+ g_back = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP, bc.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);+ if (!g_wnd || !g_back) { Log(L"siri: janela não criada (%lu)", GetLastError()); return false; }+ g_glass = backdrop::Attach(g_back);+ if (!g_glass) { DestroyWindow(g_back); g_back = nullptr; }+ apps::ours.push_back(g_wnd); if (g_back) apps::ours.push_back(g_back);+ g_s.hwnd = g_wnd;+ g_tfQ = ui::Format(12.5f, DWRITE_FONT_WEIGHT_NORMAL);+ g_tfA = ui::Format(15, DWRITE_FONT_WEIGHT_NORMAL);+ for (auto* f : { g_tfQ, g_tfA }) if (f) f->SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);+ return true;+}++} // namespace++bool siri::Pronta() {+ const auto& provs = siri::Provedores();+ int p = _wtoi(shell::Setting(L"siri_provedor", L"0").c_str());+ if (p <= 0 || p >= (int)provs.size()) return false;+ return !provs[p].precisaChave || GetFileAttributesW(siri::ArquivoChave(p).c_str()) != INVALID_FILE_ATTRIBUTES;+}++// mostra o painel (a mola de abrir); já aberto, fica onde está e só muda o conteúdo+static void MostraPainel(bool teste) {+ if (g_open && IsWindowVisible(g_wnd)) {+ Paint();+ ui::FrameClock(g_wnd, WM_SIRI_FRAME, true);+ return;+ }+ // no alto do monitor do ponteiro, centralizado (onde a Siri do Mac aparece... e onde o Spotlight estava)+ POINT pt; GetCursorPos(&pt);+ HMONITOR hm = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);+ MONITORINFO mi{ sizeof(mi) }; GetMonitorInfoW(hm, &mi);+ float sc = ui::Scale(g_wnd);+ int wpx = (int)std::lround((W + 2 * M) * sc), hpx = (int)std::lround((ORB + PAD * 2 + 2 * M) * sc);+ int x = (mi.rcWork.left + mi.rcWork.right - wpx) / 2, y = mi.rcWork.top + (mi.rcWork.bottom - mi.rcWork.top) / 6 - (int)std::lround(M * sc);+ SetWindowPos(g_wnd, HWND_TOPMOST, x, y, wpx, hpx, SWP_NOACTIVATE);+ if (g_back) SetWindowPos(g_back, g_wnd, x, y, wpx, hpx, SWP_NOACTIVATE);+ g_open = true; g_closing = false; g_openAt = anim::Now(); g_answerAt = 0;+ if (g_glass) backdrop::Fade(g_back, 0, 0.94f, wpx / 2.f, hpx / 2.f); // nasce invisível e um pouco menor: a mola leva até o tamanho+ ui::GpuMotion(g_s, 0.94f, wpx / 2.f, hpx / 2.f, 0);+ Paint();+ if (g_back) ShowWindow(g_back, SW_SHOWNOACTIVATE);+ ShowWindow(g_wnd, teste ? SW_SHOWNOACTIVATE : SW_SHOW);+ if (teste) SetTimer(g_wnd, 9, 8000, nullptr);+ else { shell::LiberaFrente(); SetForegroundWindow(g_wnd); SetFocus(g_wnd); }+ ui::FrameClock(g_wnd, WM_SIRI_FRAME, true); // a mola de abrir, o brilho e a bolinha enquanto pensa+}++void siri::Abrir(bool teste) { // o ícone da barra: o painel com o campo para digitar+ if (!Ready()) return;+ if (g_open && g_entrada) { Fecha(); return; } // clicar de novo fecha+ g_teste = teste;+ g_entrada = true; g_texto.clear(); g_q.clear(); g_a.clear(); g_busy = false; g_erro = false; g_scroll = 0;+ g_num++;+ g_cursorOn = true;+ MostraPainel(teste);+ SetTimer(g_wnd, T_CURSOR, 530, nullptr);+}++bool siri::Aberta() { return g_open; }++void siri::Perguntar(const std::wstring& q, bool teste) {+ if (q.empty() || !Ready()) return;+ g_teste = teste;+ g_entrada = false; g_texto.clear();+ KillTimer(g_wnd, T_CURSOR);+ g_q = q; g_a.clear(); g_busy = true; g_erro = false; g_scroll = 0; g_pontos = 0;+ g_answerAt = 0;+ int num = ++g_num;+ MostraPainel(teste);+ SetTimer(g_wnd, T_PONTOS, 420, nullptr);+ HWND to = g_wnd;+ std::thread([q, num, to] {+ CoInitializeEx(nullptr, COINIT_MULTITHREADED);+ bool erro = false;+ std::wstring r = Pergunta(q, erro);+ PostMessageW(to, WM_SIRI_FIM, (WPARAM)num, (LPARAM)new std::wstring((erro ? L"\x1" : L"") + r));+ CoUninitialize();+ }).detach();+}