A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
Shell stalls: system status, theme lookup and helper launches no longer block the UI thread
Eternity070628fe634cd8330c
diff --git a/docs/registro-mudancas.txt b/docs/registro-mudancas.txtindex 7567bdb..7684ead 100644--- a/docs/registro-mudancas.txt+++ b/docs/registro-mudancas.txt@@ -1173,3 +1173,20 @@ Compilado (tudo), instalado, Shell e reserva do Finder reiniciados às 23:07 sem- desfeitos bf271c0 e a8704a8 (remendos do Wobbly Windows): não resolviam e mexiam na barra de todos os apps.Conferido: compilado, instalado (hashes iguais), 600 medidas em 5 min: maior resposta 5 ms, nenhum reinício. NÃO conferido: sob disco saturado, arrastando de verdade, menu do Dock clicado, e por que o vidro sumiu da tela do usuário com o GIMP aberto.DESFAZER: reverter o commit.++[2026-11-22 16:10, hora do PC] Travamentos, causas com pilha e medida.+ Shell (instalado às 15:36): as paradas tinham arquivo e linha, nenhuma no conserto do GIMP:+ - menubar.cpp RefreshStatus: WlanOpenHandle na interface (3,6 s). O estado da barra (Wi-Fi, rede, Bluetooth, som) é lido numa thread (PedeStatus/PegaStatus, WM_BARSTATUS).+ - ui.cpp ui::Dark: lia o Registro a cada peça de vidro de cada quadro (1,1 s). Lê só quando a chave muda (RegNotifyChangeKeyValue).+ - main.cpp EnsureReserve: CreateProcess do Finder reserva na interface (2,9 s). Vai numa thread; a Captura residente também.+ Mesma classe de espera, achadas lendo o código (sem pilha): central.cpp ReadFast numa thread; limites::Maximizada com SWP_ASYNCWINDOWPOS.+ Conferido: 9 min com o disco com fila >= 5 em 65 % das medidas: 0 paradas acima de 400 ms, maior resposta 62 ms (antes: 3,6 s e 4,4 s).+ NÃO conferido na tela: ícones da barra ao trocar Wi-Fi/fone, tema claro/escuro ao vivo, Central de Controle, issue #24 com o movimento assíncrono.+ Apps travando: nas pilhas tiradas não era a WacOSWindow.dll.+ - Claude parado 11,7 s em FlushFileBuffers (grava a própria lista de atalhos na thread da interface), sem frame nosso; NVIDIA Overlay, sem a DLL, parado 4 s; leitura de controle de 4 KB acima de 0,5 s 7 vezes.+ - C: (XPG SPECTRIX S40G) saturado com 34-105 MB/s de gravação; folgado grava 521 MB/s e já marca 75 C. Estrangulamento por calor ou cache é provável, não provado.+ - Na janela ruim (14:45-15:51) a maior parte dos 4 GB que sobraram gravados era deste projeto: builds em 3 cópias, 4 worktrees (227 MB de docs cada), zips de ensaio, pack do git.+ - Pista falsa descartada: NVDisplay.Container conta ~17 MB de "escrita" a cada processo que abre a GPU, mas o disco não sobe (é pipe).+ - Para trabalhar sem travar o PC: uma build por vez, sem worktree novo à toa, ensaio de pacote só quando for publicar.+ Atenção ao publicar: desde o push de 15:37 (e06bee0) o main público tem os commits da barra própria ligada por padrão. A build-28 precisa tirá-los, se ela continuar de fora.+ DESFAZER: reverter o commit.diff --git a/src/shell/central.cpp b/src/shell/central.cppindex 4e3286c..21d3336 100644--- a/src/shell/central.cpp+++ b/src/shell/central.cpp@@ -574,7 +574,8 @@ void BrightWorker() {g_brightBusy = false;}-void ReadFast() { // leituras rápidas: ao abrir e a cada atualização+std::atomic<int> g_fastPedidos{ 0 };+void ReadFastAgora() { // só na thread do ReadFast: WLAN e áudio esperam serviços do Windows (já levou 3,6 s)std::wstring ssid = Ssid();float vol = 0; BOOL mute = FALSE;if (IAudioEndpointVolume* v = Endpoint()) { v->GetMasterVolumeLevelScalar(&vol); v->GetMute(&mute); v->Release(); }@@ -583,6 +584,19 @@ void ReadFast() { // leituras rápidas: ao abrir e a cada atualizaçãostd::lock_guard<std::mutex> l(g_mx);g_st.ssid = ssid; g_st.volume = vol; g_st.mute = mute != FALSE; g_st.focus = focus; g_st.airdrop = air;}+void ReadFast() { // leituras rápidas: ao abrir e a cada atualização; fora da interface, uma de cada vez+ if (g_fastPedidos.fetch_add(1) > 0) return; // já há uma lendo: ela lê de novo no fim+ std::thread([] {+ HRESULT ci = CoInitializeEx(nullptr, COINIT_MULTITHREADED);+ for (;;) {+ int n = g_fastPedidos.load();+ ReadFastAgora();+ if (g_wnd) PostMessageW(g_wnd, WM_CC_UPDATE, 0, 0);+ if (g_fastPedidos.fetch_sub(n) == n) break;+ }+ if (SUCCEEDED(ci)) CoUninitialize();+ }).detach();+}// Wi-Fi/Bluetooth ligados ou não (Windows.Devices.Radios), numa thread própriavoid LoadRadios() {diff --git a/src/shell/limites.cpp b/src/shell/limites.cppindex 3ee4fb7..d4b2fe2 100644--- a/src/shell/limites.cpp+++ b/src/shell/limites.cpp@@ -189,7 +189,12 @@ void limites::Maximizada(HWND h) {if (fb.top >= wa.top - 1 && fb.bottom <= wa.bottom + 1) return; // dentro da área: nada a fazerif (feitas.size() > 64) feitas.clear();if (antes.size() > 64) antes.clear();+ // a correção vai sem esperar o app (SWP_ASYNCWINDOWPOS): esperando, um app ocupado prendia o Shell inteiro. Enquanto+ // ela não chega, os avisos que já estavam na fila mostram o lugar de antes: isso não é o app insistindo.+ static std::map<HWND, DWORD> quando;+ if (quando.size() > 64) quando.clear();auto& a = antes[h];+ if (a.second > 0 && EqualRect(&a.first, &wr) && GetTickCount() - quando[h] < 300) return;if (a.second >= 3 || (a.second > 0 && EqualRect(&a.first, &wr))) {feitas.insert(h);wchar_t c[64] = {}; GetClassNameW(h, c, 64);@@ -197,9 +202,10 @@ void limites::Maximizada(HWND h) {return;}a.first = wr; a.second++;+ quando[h] = GetTickCount();int dl = fb.left - wr.left, dt = fb.top - wr.top, dr = wr.right - fb.right, db = wr.bottom - fb.bottom;SetWindowPos(h, nullptr, wa.left - dl, wa.top - dt, (wa.right - wa.left) + dl + dr, (wa.bottom - wa.top) + dt + db,- SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER);+ SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_ASYNCWINDOWPOS);wchar_t c[64] = {}; GetClassNameW(h, c, 64);Log(L"limites: maximizada '%ls' por cima da barra/do Dock: volta para a área de trabalho", c);}diff --git a/src/shell/main.cpp b/src/shell/main.cppindex f53da86..6efe9da 100644--- a/src/shell/main.cpp+++ b/src/shell/main.cpp@@ -578,10 +578,12 @@ static void EnsureScreenshot() {std::wstring cmd = L"\"" + shell::dir + L"\\" EXE_SCREENSHOT L"\" /residente";STARTUPINFOW si{ sizeof(si) };PROCESS_INFORMATION pi{};- 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");- }+ 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@@ -618,10 +620,13 @@ static void EnsureReserve() {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, nullptr, &si, &pi)) {- CloseHandle(pi.hProcess); CloseHandle(pi.hThread);- Log(L"Finder reserva preparado");- }+ // 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 dediff --git a/src/shell/menubar.cpp b/src/shell/menubar.cppindex 838d188..3cc94d8 100644--- a/src/shell/menubar.cpp+++ b/src/shell/menubar.cpp@@ -22,6 +22,9 @@ static const wchar_t* IconePC() { return shell::Setting(L"sobre_mac", L"pc") ==#include <algorithm>#include <cmath>#include <map>+#include <atomic>+#include <mutex>+#include <thread>#include "../comum/idioma.h"namespace {@@ -290,89 +293,131 @@ struct Status {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);-bool g_audioStale; // a saída padrão mudou: relê o objeto de áudio já+std::atomic<bool> g_audioStale{ false }; // a saída padrão mudou: relê o objeto de áudio já-void RefreshStatus() {+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;- g_st.wlan = false;+ 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) { g_st.wlan = list->dwNumberOfItems > 0; WlanFreeMemory(list); }+ if (WlanEnumInterfaces(h, nullptr, &list) == ERROR_SUCCESS) { st.wlan = list->dwNumberOfItems > 0; WlanFreeMemory(list); }WlanCloseHandle(h, nullptr);}- std::wstring ssid;- g_st.wifiOn = g_st.wlan && WifiName(ssid);+ 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- g_st.wired = false;+ 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 à redefor (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]) { g_st.wired = true; break; }+ 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) {- g_st.batt = true; g_st.pct = ps.BatteryLifePercent; g_st.charging = ps.ACLineStatus == 1;- } else g_st.batt = false;+ st.batt = true; st.pct = ps.BatteryLifePercent; st.charging = ps.ACLineStatus == 1;+ } else st.batt = false;// Bluetooth: tem rádio?- if (!g_st.btAt || GetTickCount() - g_st.btAt > 10000) {- g_st.btAt = GetTickCount();+ 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);- g_st.bt = f != nullptr;+ 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 sbool fresh = false;- if (g_audioStale) { g_audioStale = false; audioAt = 0; }+ if (g_audioStale.exchange(false)) audioAt = 0;if (vol && audioAt && now - audioAt < 10000) {BOOL mute = FALSE;- if (SUCCEEDED(vol->GetMute(&mute)) && SUCCEEDED(vol->GetMasterVolumeLevelScalar(&g_st.vol))) { g_st.muted = mute; fresh = true; }+ 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; }- g_st.sound = false;+ 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(&g_st.vol);- g_st.muted = mute; g_st.sound = true;+ BOOL mute = FALSE; vol->GetMute(&mute); vol->GetMasterVolumeLevelScalar(&st.vol);+ st.muted = mute; st.sound = true;}- IPropertyStore* st = nullptr;- g_st.phones = false;- if (SUCCEEDED(dev->OpenPropertyStore(STGM_READ, &st))) {+ 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(st->GetValue(formFactor, &v)) && v.vt == VT_UI4) g_st.phones = v.ulVal == 3 || v.ulVal == 5; // fone / headset+ if (SUCCEEDED(ps2->GetValue(formFactor, &v)) && v.vt == VT_UI4) st.phones = v.ulVal == 3 || v.ulVal == 5; // fone / headsetPropVariantClear(&v);- st->Release();+ 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 frenteHWND 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);@@ -1237,8 +1282,8 @@ void Click(D2D1_POINT_2F p, bool right) {}case K_SPOT: spotlight::Toggle(); break;case K_NET: {- std::wstring ssid;- bool wifi = WifiName(ssid);+ std::wstring ssid = g_st.ssid;+ 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;}@@ -1321,7 +1366,8 @@ LRESULT CALLBACK BarProc(HWND h, UINT m, WPARAM w, LPARAM l) {}case WM_BARDISPLAYS: menubar::Displays(); return 0;case WM_MOUSEACTIVATE: return MA_NOACTIVATE;- case WM_TIMER: RefreshStatus(); menubar::Update(); return 0;+ case WM_TIMER: RefreshStatus(); menubar::Update(); return 0;+ case WM_BARSTATUS: PegaStatus(); menubar::Update(); return 0;case WM_SETTINGCHANGE: // Windows trocou entre claro e escuroif (l && !lstrcmpiW((LPCWSTR)l, L"ImmersiveColorSet")) { menubar::ApplyTheme(); dock::ApplyTheme(); }break;diff --git a/src/shell/ui.cpp b/src/shell/ui.cppindex cef1676..49a3921 100644--- a/src/shell/ui.cpp+++ b/src/shell/ui.cpp@@ -10,6 +10,7 @@#include <dcomp.h>#include <dwmapi.h>#include <atomic>+#include <mutex>#include <thread>#include <algorithm>#include <cmath>@@ -37,14 +38,37 @@ bool ui::Init() {return true;}+// Dark() roda a cada peça de vidro de cada quadro (~300 vezes por segundo). Lendo o Registro toda vez, a interface+// parava quando ele demorava (RegOpenKeyEx: 1,1 s, pilha de 22/11/2026, 15:14). O Windows avisa quando a chave muda+// (o aviso já está lá quando o RegSetValue volta): só então lê de novo.+static bool TemaDoWindowsEscuro() {+ static std::mutex mx;+ static HKEY k;+ static HANDLE mudou;+ static std::atomic<bool> escuro{ false }, pronto{ false };+ if (pronto && (!mudou || WaitForSingleObject(mudou, 0) != WAIT_OBJECT_0)) return escuro;+ std::lock_guard<std::mutex> l(mx);+ if (!k) {+ if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",+ 0, KEY_QUERY_VALUE | KEY_NOTIFY, &k) == ERROR_SUCCESS)+ mudou = CreateEventW(nullptr, FALSE, FALSE, nullptr);+ else k = nullptr;+ }+ if (k) {+ if (mudou) RegNotifyChangeKeyValue(k, FALSE, REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_THREAD_AGNOSTIC, mudou, TRUE);+ DWORD v = 1, cb = sizeof(v);+ RegGetValueW(k, nullptr, L"AppsUseLightTheme", RRF_RT_REG_DWORD, nullptr, &v, &cb);+ escuro = v == 0;+ }+ pronto = true;+ return escuro;+}+bool ui::Dark() { // ajuste "tema": auto (segue o Windows), claro ou escurostd::wstring t = shell::Setting(L"tema", L"auto");if (t == L"claro") return false;if (t == L"escuro") return true;- DWORD v = 1, cb = sizeof(v);- RegGetValueW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",- L"AppsUseLightTheme", RRF_RT_REG_DWORD, nullptr, &v, &cb);- return v == 0;+ return TemaDoWindowsEscuro();}float ui::Scale(HWND h) { return GetDpiForWindow(h) / 96.f; }