A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
Reddit feedback: smart-hide Dock, smoother genie, Calendar/Weather/Clock fixes, cleaner window corners
Eternity070628e27beb52eb18
diff --git a/docs/registro-mudancas.txt b/docs/registro-mudancas.txtindex c6efda2..4adafbc 100644--- a/docs/registro-mudancas.txt+++ b/docs/registro-mudancas.txt@@ -600,4 +600,23 @@ Compilado (tudo), instalado, Shell e reserva do Finder reiniciados às 23:07 sem[2026-11-20 09:05 PC] BUG ANTIGO nos tools\musica-registrar.ps1 e quicktime-registrar.ps1 (chamados pelo instalar.ps1): New-Item -Force em HKCU\Software\RegisteredApplications e em HKCU\Software\Classes\<ext>\OpenWithProgids RECRIA a chave e apagava tudo dela: os outros apps registrados no Windows (Aplicativos padrão) e o "Abrir com" de outros apps para .mp3/.mp4 etc. (por isso o backup de hoje já não tinha "Música (Sequoia)": o QuickTime, registrado depois, apagou). Agora só cria a chave se não existir. Testado: RegisteredApplications 26 -> 26, PackagedApps 20 -> 20, um valor sentinela em .mp3\OpenWithProgids ficou. Neste PC: RegisteredApplications devolvida do backup de hoje (C:\Users\Public\wacos-teste-bkp, 24 apps + WacOS Music + WacOS QuickTime Player; o teste dos scripts velhos tinha apagado tudo de novo). O OpenWithProgids de .mp3/.mp4 e cia em HKCU não tinha backup: ficou só com os do WacOS (os outros apps continuam no HKLM/no próprio pacote). O instalador novo (WacOSSetup) nunca teve esse problema (RegCreateKeyEx não apaga nada).[2026-11-20 09:05 PC] Também: atualizar (instalar.ps1 -Atualizar e WacOSSetup) registra de novo o Música/QuickTime que já estavam registrados por aquela instalação, para os nomes em inglês chegarem a quem atualiza. Neste PC os dois registradores rodaram (apontando para o repositório, como antes): nomes agora em inglês.-[2026-11-20 09:10 PC] TESTE do "Atualizar Agora" antigo (tools\atualizar-github.ps1 da instalação, como num PC com build-14): achou o build-15, baixou 172 MB, SHA-256 confere, rodou o instalar.ps1 -Atualizar do pacote, fechou e reabriu o WacOS (Finder e Captura de Tela, que estavam abertos, voltaram). Depois: bin\versao.txt = build-15, ajustes.txt igual ao de antes, RegisteredApplications 26/20 intactos, Abrir com deste PC sem mudança (aponta para o repositório, então não foi registrado de novo). Achado: o instalar.ps1 não copiava o WacOSSetup.exe para a instalação (quem atualiza pelo botão antigo ficava sem ele; o Atualizar Agora novo cai no script). Corrigido em instalador\instalar.ps1 (vale a partir da próxima versão publicada).+[2026-11-20 09:10 PC] TESTE do "Atualizar Agora" antigo (tools\atualizar-github.ps1 da instalação, como num PC com build-14): achou o build-15, baixou 172 MB, SHA-256 confere, rodou o instalar.ps1 -Atualizar do pacote, fechou e reabriu o WacOS (Finder e Captura de Tela, que estavam abertos, voltaram). Depois: bin\versao.txt = build-15, ajustes.txt igual ao de antes, RegisteredApplications 26/20 intactos, Abrir com deste PC sem mudança (aponta para o repositório, então não foi registrado de novo). Achado: o instalar.ps1 não copiava o WacOSSetup.exe para a instalação (quem atualiza pelo botão antigo ficava sem ele; o Atualizar Agora novo cai no script). Corrigido em instalador\instalar.ps1 (vale a partir da próxima versão publicada).++[2026-11-20 11:40] Dock: ocultação inteligente (pedido no Reddit). ajustes ocultar=inteligente: o Dock fica à mostra e só esconde quando uma janela de app (ou diálogo dela) encosta na área dele; o mouse na borda de baixo mostra, como na ocultação comum. Ajustes > Mesa e Dock: "Ocultar o Dock" virou lista (Nunca / Automaticamente / Quando uma janela encostar nele); menu do fundo do Dock ganhou "Ocultação Inteligente" e agora grava a escolha no ajustes.txt. Desempenho: com ocultação ligada e o Dock parado, o Dock não redesenha mais a cada quadro (antes o relógio de quadros ficava ligado o tempo todo); só olha mouse e janelas a cada 100 ms (medido: 0,065% da CPU do PC parado com ocultar=1). Testado no Shell instalado; ajuste do usuário devolvido (ocultar=0, antes ausente = 0).++[2026-11-20 12:10] Pedidos de um usuário do Reddit (modo apps + barras, sem o Shell):+ - Calendário: no tema macOS 27, esconder a lateral sumia com o botão dela (não voltava); agora o botão fica na barra, depois dos três botões.+ - Calendário: a semana começa no dia da região do Windows (segunda na Europa); botão direito nos nomes dos dias troca (Domingo/Segunda) e liga/desliga feriados. Gravado no calendario.txt (S semana / S feriados).+ - Calendário: calendário "Feriados" (só leitura) com os feriados do país da região do Windows, da Nager.Date (date.nager.at, sem chave); cada ano baixado fica em %APPDATA%\Shelleriados.txt. Eventos de id negativo, não vão para o calendario.txt.+ - Tempo: o botão da lateral não fazia nada; agora esconde e mostra (nos dois visuais). Botão direito numa cidade: "Usar como Meu Local" (grava tempoCidade/Lat/Lon nos Ajustes, pelo Shell ou direto no arquivo sem ele) e "Apagar" (também o Meu Local, se houver outra cidade). Sem tempoCidade, a cidade padrão é a do fuso do Windows (src\comum\cidade_padrao.h; Brasília continua Campinas), no app e no widget.+ - Relógio: "Outra Cidade…" no + do Relógio Mundial procura qualquer cidade (geocodificação do Open-Meteo) e converte o fuso IANA para o do Windows pelo icu.dll do Windows (linhas C no relogio.txt, índices 1000+ no W). Sem o Shell, o próprio app toca os alarmes enquanto estiver aberto (antes ninguém tocava).+ - Barras de título (WacOSWindow.dll): nos apps do Windows os três botões 4 pt mais para dentro (LightsLayout/WinAppInset); apps do WacOS, Leopard e barras próprias como antes.+ - app2d.h: SetAppSetting (grava ajuste pelo Shell, ou no ajustes.txt sem ele).+ Testado no PC: lateral do Calendário e do Tempo (cliques mandados para as janelas), feriados do BR, semana na segunda (calendario.txt de teste apagado; o usuário não tinha esse arquivo), ICU (Europe/Warsaw -> Central European Standard Time), foto da barra do Mapa de Caracteres. Não testado: alarme tocando sem o Shell, "Outra Cidade…" pela interface, menu "Usar como Meu Local".++[2026-11-20 12:15] Gênio menos serrilhado (Reddit: "pixelated"): o compositor encolhia a foto inteira da janela até ~5% com filtro de 2x2 pixels (pulava linhas e colunas). Agora src\shell\genio.cpp sobe níveis de detalhe (a foto e metades com média 2x2, até 6) e cada nível tem as suas faixas; a de cima some (opacidade animada pelo DWM) quando a escala dela cai de 0,65 para 0,5. Faixas do nível 0 com ~3 px (até 240; antes ~5 px até 120, degraus visíveis em janelas altas); 32 pontos de curva (antes 24). Medido: janela 1101x621 preparo 25,6 -> 34,4 ms, 414 faixas em 6 níveis. Não deu para ver o resultado por foto (a captura GDI não pega a camada do compositor).++[2026-11-20 12:17] Gênio, 2ª etapa (o usuário ainda via partes pixeladas): borda SOFT no compositor (antes HARD: o contorno do funil saía em escadinha, sem suavizar) e cada faixa desce 2 linhas por baixo da seguinte e fica por cima dela, para a borda suave não abrir fresta. Rodou sem erro (449 faixas em 6 níveis, preparo 26 ms).+[2026-11-20 12:21] Gênio, 3ª etapa (ainda pixelado): os níveis de detalhe agora reduzem só a largura (o funil estreita a janela muito antes de achatá-la; reduzir as duas direções esticava linhas em blocos numa janela fina e alta). A troca de nível segue só a escala horizontal; nível 0 com até 200 faixas (~3 px), os outros com a metade. Medido: 700 faixas em 6 níveis, preparo 38,9 ms (janela 1101x621).+[2026-11-20 12:26] Barras de título (WacOSWindow.dll): "cantinhos" claros sobrando nos cantos das janelas no tema claro (Tahoe e Leopard). O recorte vinha do CreateRoundRectRgn, que não é simétrico (sai ~1 px a mais à direita e embaixo) e cujos degraus passavam do arco suavizado da moldura. Agora RoundRgn (macjanela.cpp) monta o recorte linha a linha: só entra pixel com o centro a 0,5 px ou mais para dentro do arco de raio CornerRadius, a mesma geometria da moldura. Vale também para o modo "leve". Conferido no tema escuro (cantos limpos); o tema claro do Windows não foi ligado no PC para testar.+[2026-11-20 12:34] Barras de título: em janelas de tamanho fixo (diálogos), o recorte pega a janela inteira, mas a barra do Mac ia só da área do app; sobrava a borda do Windows lisa dos lados e em cima da barra (bem visível no metal do Leopard). BarRect agora vai até o recorte (Insets) nos lados e no topo. Também: a camada ShellAbrir (animação de abrir) fica visível sem animação rodando; não bloqueou cliques no uso de hoje, mas fica para olhar se aparecer de novo.diff --git a/src/ajustes/paginas.cpp b/src/ajustes/paginas.cppindex 38b9eeb..a59e38a 100644--- a/src/ajustes/paginas.cpp+++ b/src/ajustes/paginas.cpp@@ -1458,7 +1458,10 @@ Page MesaDock() {[monDev] { std::wstring v = Setting(L"dock_monitor", L""); for (int i = 0; i < (int)monDev.size(); i++) if (!_wcsicmp(v.c_str(), monDev[i].c_str())) return i; return 0; },[monDev](int i) { SetSetting(L"dock_monitor", monDev[std::clamp(i, 0, (int)monDev.size() - 1)]); });monRow.enabled = monDev.size() > 1;- Row hide = Toggle(L"Ocultar e mostrar o Dock automaticamente", flag(L"ocultar", L"0"), setFlag(L"ocultar"));+ // Inteligente: só esconde quando uma janela encosta no Dock (pedido de um usuário no Reddit)+ Row hide = Popup(L"Ocultar o Dock", { L"Nunca", L"Automaticamente", L"Quando uma janela encostar nele" },+ [] { std::wstring v = Setting(L"ocultar", L"0"); return v == L"1" ? 1 : v == L"inteligente" ? 2 : 0; },+ [](int i) { SetSetting(L"ocultar", i == 1 ? L"1" : i == 2 ? L"inteligente" : L"0"); });Row anim = Toggle(L"Animar aplicativos ao abrir", flag(L"animar_abertura", L"1"), setFlag(L"animar_abertura"));Row ind = Toggle(L"Mostrar indicadores de aplicativos abertos", flag(L"indicadores", L"1"), setFlag(L"indicadores"));Row dl = Toggle(L"Mostrar a pasta Downloads no Dock", flag(L"dock_downloads", L"1"), setFlag(L"dock_downloads"));diff --git a/src/calendario/main.cpp b/src/calendario/main.cppindex b5ebbb1..92e401d 100644--- a/src/calendario/main.cpp+++ b/src/calendario/main.cpp@@ -6,6 +6,10 @@#include "../comum/app2d.h"#include <shobjidl.h>#include <map>+#include <set>+#include <thread>+#include <winhttp.h>+#pragma comment(lib, "winhttp.lib")using namespace app2d;@@ -43,10 +47,25 @@ D2D1_COLOR_F EvColor(int i) {}const wchar_t* COLOR_NAMES[] = { L"Azul", L"Vermelho", L"Laranja", L"Verde", L"Roxo", L"Amarelo", L"Marrom" };+// Feriados nacionais (pedido no Reddit): o calendário "Feriados", só de leitura, com os feriados do país da região do+// Windows, da Nager.Date (date.nager.at, sem chave). Os eventos têm id negativo e não vão para o calendario.txt;+// cada ano baixado fica em feriados.txt (não baixa de novo). Desliga no quadradinho da lateral.+const int HOL_CAL = -5;+const UINT WM_HOLIDAYS = WM_APP + 6;+bool g_holOn = true;+std::wstring g_holCC; // país (ISO de 2 letras)+std::set<int> g_holYears; // anos já carregados ou pedidos+int g_holNextId = -1000;+int g_firstDow = 0; // primeiro dia da semana (WeekStart, mais abaixo): 0 = domingo, 1 = segunda+bool g_firstDowSet = false; // escolhido pelo usuário (senão vale a região do Windows)+void Save() {std::vector<std::wstring> out{ L"# Calendário do WacOS (E = evento: id, início, fim em minutos desde 1970, dia inteiro, título, cor, notas)" };- for (auto& c : g_cals) out.push_back(L"C\t" + std::to_wstring(c.id) + L"\t" + Esc(c.name) + L"\t" + std::to_wstring(c.color) + L"\t" + (c.on ? L"1" : L"0"));- for (auto& e : g_ev) out.push_back(L"E\t" + std::to_wstring(e.id) + L"\t" + std::to_wstring(e.start) + L"\t" + std::to_wstring(e.end) + L"\t" + (e.allDay ? L"1" : L"0") + L"\t" ++ if (Cal* hc = FindCal(HOL_CAL)) g_holOn = hc->on;+ out.push_back(L"S\tsemana\t" + std::to_wstring(g_firstDowSet ? g_firstDow : -1));+ out.push_back(L"S\tferiados\t" + std::wstring(g_holOn ? L"1" : L"0"));+ for (auto& c : g_cals) if (c.id != HOL_CAL) out.push_back(L"C\t" + std::to_wstring(c.id) + L"\t" + Esc(c.name) + L"\t" + std::to_wstring(c.color) + L"\t" + (c.on ? L"1" : L"0"));+ for (auto& e : g_ev) if (e.id >= 0) out.push_back(L"E\t" + std::to_wstring(e.id) + L"\t" + std::to_wstring(e.start) + L"\t" + std::to_wstring(e.end) + L"\t" + (e.allDay ? L"1" : L"0") + L"\t" +Esc(e.title) + L"\t" + std::to_wstring(e.color) + L"\t" + Esc(e.notes) + L"\t" + std::to_wstring(e.cal));WriteLines(g_file, out);}@@ -59,8 +78,16 @@ void Load() {if (f.size() > 8) e.cal = _wtoi(f[8].c_str());g_ev.push_back(e);} else if (f.size() >= 5 && f[0] == L"C") g_cals.push_back({ _wtoi(f[1].c_str()), Unesc(f[2]), _wtoi(f[3].c_str()), f[4] == L"1" });+ else if (f.size() >= 3 && f[0] == L"S" && f[1] == L"semana") { int v = _wtoi(f[2].c_str()); if (v == 0 || v == 1) { g_firstDow = v; g_firstDowSet = true; } }+ else if (f.size() >= 3 && f[0] == L"S" && f[1] == L"feriados") g_holOn = f[2] != L"0";}if (g_cals.empty()) g_cals = { { 1, Tr(L"Pessoal"), 0, true }, { 2, Tr(L"Trabalho"), 2, true }, { 3, Tr(L"Família"), 3, true } };+ if (!g_firstDowSet) { // a região do Windows: LOCALE_IFIRSTDAYOFWEEK 0 = segunda ... 6 = domingo+ wchar_t b[4] = {};+ if (GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_IFIRSTDAYOFWEEK, b, 4)) g_firstDow = (_wtoi(b) + 1) % 7 == 1 ? 1 : 0;+ }+ { wchar_t cc[8] = {}; if (GetUserDefaultGeoName(cc, 8) && wcslen(cc) == 2) g_holCC = cc; }+ if (!g_holCC.empty()) g_cals.push_back({ HOL_CAL, Tr(L"Feriados"), 1, g_holOn });for (auto& e : g_ev) g_nextId = std::max(g_nextId, e.id + 1);for (auto& c : g_cals) g_nextId = std::max(g_nextId, c.id + 1);}@@ -80,7 +107,104 @@ std::vector<RemItem> Reminders() {long long AddDays(long long day, int n) { SYSTEMTIME s = FromMin(day); s.wHour = 12; long long m = ToMin(s) + n * 24LL * 60; return DayStart(m); }long long MonthStart(long long m) { SYSTEMTIME s = FromMin(m); s.wDay = 1; s.wHour = s.wMinute = 0; return ToMin(s); }long long AddMonths(long long m, int n) { SYSTEMTIME s = FromMin(MonthStart(m)); int mo = s.wMonth - 1 + n; s.wYear = (WORD)(s.wYear + (mo >= 0 ? mo / 12 : (mo - 11) / 12)); s.wMonth = (WORD)(((mo % 12) + 12) % 12 + 1); return ToMin(s); }-long long WeekStart(long long m) { long long d = DayStart(m); return AddDays(d, -(int)FromMin(d).wDayOfWeek); } // domingo+// primeiro dia da semana: 0 = domingo, 1 = segunda. Padrão: o da região do Windows (como o Mac, que segue a+// região); o usuário troca com o botão direito nos nomes dos dias (pedido no Reddit); g_firstDow fica lá em cima+long long WeekStart(long long m) { long long d = DayStart(m); return AddDays(d, -(((int)FromMin(d).wDayOfWeek - g_firstDow + 7) % 7)); }+int DowAt(int col) { return (col + g_firstDow) % 7; } // coluna 0..6 -> dia da semana++// ---- feriados+struct HolDay { int y, m, d; std::wstring name; };+void AddHoliday(const HolDay& hd) {+ SYSTEMTIME st{}; st.wYear = (WORD)hd.y; st.wMonth = (WORD)hd.m; st.wDay = (WORD)hd.d;+ long long day = ToMin(st);+ for (auto& e : g_ev) if (e.cal == HOL_CAL && e.start == day && e.title == hd.name) return;+ g_ev.push_back({ g_holNextId--, day, AddDays(day, 1), true, hd.name, 1, L"", HOL_CAL });+}+std::wstring HolFile() { return DataPath(L"feriados.txt"); }+void LoadHolidayCache() { // H país ano aaaammdd nome+ for (auto& line : ReadLines(HolFile())) {+ auto f = Split(line);+ if (f.size() < 5 || f[0] != L"H" || f[1] != g_holCC) continue;+ int y = _wtoi(f[2].c_str()), v = _wtoi(f[3].c_str());+ g_holYears.insert(y);+ if (v > 0) AddHoliday({ v / 10000, v / 100 % 100, v % 100, Unesc(f[4]) });+ }+}+std::wstring JsonStr(const std::string& j, size_t& p, const char* key) { // o próximo "key":"valor" a partir de p+ std::string k = std::string("\"") + key + "\":\"";+ size_t a = j.find(k, p);+ if (a == std::string::npos) return L"";+ a += k.size();+ std::wstring out;+ size_t i = a;+ for (; i < j.size() && j[i] != '"'; i++) {+ if (j[i] == '\\' && i + 1 < j.size()) {+ char c = j[++i];+ if (c == 'u' && i + 4 < j.size()) { out += (wchar_t)strtol(j.substr(i + 1, 4).c_str(), nullptr, 16); i += 4; }+ else out += (wchar_t)(c == 'n' ? L' ' : c);+ continue;+ }+ // UTF-8: junta os bytes do caractere+ unsigned char c = (unsigned char)j[i];+ int n = c < 0x80 ? 1 : c < 0xE0 ? 2 : c < 0xF0 ? 3 : 4;+ wchar_t w[4] = {}; int got = MultiByteToWideChar(CP_UTF8, 0, j.data() + i, std::min<int>(n, (int)(j.size() - i)), w, 4);+ out.append(w, got > 0 ? got : 0);+ i += n - 1;+ }+ p = i;+ return out;+}+void RequestHolidays(int year) {+ if (g_holCC.empty() || !g_holOn || year < 1970 || g_holYears.count(year)) return;+ g_holYears.insert(year);+ std::wstring cc = g_holCC; HWND h = wnd;+ std::thread([year, cc, h] {+ std::string body;+ HINTERNET ses = WinHttpOpen(L"WacOS-Calendar/1.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);+ if (ses) {+ WinHttpSetTimeouts(ses, 5000, 5000, 8000, 8000);+ HINTERNET con = WinHttpConnect(ses, L"date.nager.at", INTERNET_DEFAULT_HTTPS_PORT, 0);+ std::wstring path = L"/api/v3/PublicHolidays/" + std::to_wstring(year) + L"/" + cc;+ HINTERNET req = con ? WinHttpOpenRequest(con, L"GET", path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : nullptr;+ if (req && WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) && WinHttpReceiveResponse(req, nullptr)) {+ DWORD status = 0, sz = sizeof(status), avail = 0;+ WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, nullptr, &status, &sz, nullptr);+ while (WinHttpQueryDataAvailable(req, &avail) && avail && body.size() < 256 * 1024) {+ std::string chunk(avail, '\0'); DWORD got = 0;+ if (!WinHttpReadData(req, chunk.data(), avail, &got) || !got) break;+ body.append(chunk.data(), got);+ }+ if (status != 200) body.clear();+ }+ if (req) WinHttpCloseHandle(req);+ if (con) WinHttpCloseHandle(con);+ WinHttpCloseHandle(ses);+ }+ auto* list = new std::vector<HolDay>;+ size_t p = 0;+ for (;;) {+ std::wstring d = JsonStr(body, p, "date");+ if (d.size() < 10) break;+ std::wstring n = JsonStr(body, p, "localName");+ list->push_back({ _wtoi(d.substr(0, 4).c_str()), _wtoi(d.substr(5, 2).c_str()), _wtoi(d.substr(8, 2).c_str()), n });+ }+ bool ok = !body.empty();+ if (!PostMessageW(h, WM_HOLIDAYS, (WPARAM)(ok ? year : -year), (LPARAM)list)) delete list;+ }).detach();+}+void HolidaysArrived(int year, std::vector<HolDay>* list) {+ if (year < 0) { g_holYears.erase(-year); delete list; return; } // sem rede: tenta de novo depois+ auto lines = ReadLines(HolFile());+ if (lines.empty()) lines.push_back(L"# Feriados baixados pelo Calendário do WacOS (Nager.Date): H, país, ano, aaaammdd, nome");+ lines.push_back(L"H\t" + g_holCC + L"\t" + std::to_wstring(year) + L"\t0\t"); // ano baixado (mesmo sem feriados)+ for (auto& hd : *list) {+ wchar_t v[16]; swprintf_s(v, L"%04d%02d%02d", hd.y, hd.m, hd.d);+ lines.push_back(L"H\t" + g_holCC + L"\t" + std::to_wstring(year) + L"\t" + v + L"\t" + Esc(hd.name));+ AddHoliday(hd);+ }+ WriteLines(HolFile(), lines);+ delete list;+}bool OnDay(const Ev& e, long long day) { long long next = AddDays(day, 1); return e.start < next && (e.end > day || (e.end <= e.start && e.start >= day)); }@@ -120,7 +244,8 @@ void PaintMonth(D2D1_SIZE_F sz, bool dark, D2D1_COLOR_F text, D2D1_COLOR_F gray,long long ms = MonthStart(g_anchor), first = WeekStart(ms);SYSTEMTIME am = FromMin(ms);float top = TB + WEEKHEAD, cw = sz.width / 7, rows = 6, ch = (sz.height - top) / rows;- for (int d = 0; d < 7; d++) Text(WeekdayShort(d), g_tfHeadDay, D2D1::RectF(d * cw, TB, (d + 1) * cw - 8, TB + WEEKHEAD), gray);+ for (int d = 0; d < 7; d++) Text(WeekdayShort(DowAt(d)), g_tfHeadDay, D2D1::RectF(d * cw, TB, (d + 1) * cw - 8, TB + WEEKHEAD), gray);+ g_hits.push_back({ 13, 0, 0, D2D1::RectF(0, TB, 7 * cw, TB + WEEKHEAD) }); // botão direito: começar a semana em...long long today = DayStart(NowMin());D2D1_COLOR_F line = dark ? Rgb(255, 255, 255, 0.10f) : Rgb(0, 0, 0, 0.10f);for (int i = 0; i < 42; i++) {@@ -255,9 +380,9 @@ void PaintYear(D2D1_SIZE_F sz, bool dark, D2D1_COLOR_F text, D2D1_COLOR_F gray)if (g_tfHeadDay) {}SYSTEMTIME s1{}; s1.wYear = a.wYear; s1.wMonth = (WORD)(m + 1); s1.wDay = 1;long long first = ToMin(s1), next = AddMonths(first, 1);- int wd = FromMin(first).wDayOfWeek, days = (int)((DayStart(next + 12 * 60) - first + 12 * 60) / (24 * 60));+ int wd = ((int)FromMin(first).wDayOfWeek - g_firstDow + 7) % 7, days = (int)((DayStart(next + 12 * 60) - first + 12 * 60) / (24 * 60));float cw = (mw - 20) / 7, ch = std::min((mh - 50) / 6, cw);- for (int d = 0; d < 7; d++) Text(std::wstring(1, WeekdayShort(d)[0]), g_tfYearDay, D2D1::RectF(x0 + d * cw, y0 + 26, x0 + (d + 1) * cw, y0 + 42), gray);+ for (int d = 0; d < 7; d++) Text(std::wstring(1, WeekdayShort(DowAt(d))[0]), g_tfYearDay, D2D1::RectF(x0 + d * cw, y0 + 26, x0 + (d + 1) * cw, y0 + 42), gray);for (int d = 1; d <= days; d++) {int idx = wd + d - 1;D2D1_RECT_F c = D2D1::RectF(x0 + (idx % 7) * cw, y0 + 44 + (idx / 7) * ch, x0 + (idx % 7 + 1) * cw, y0 + 44 + (idx / 7 + 1) * ch);@@ -293,7 +418,7 @@ void MiniMonth(float x0, float bottom, bool dark, D2D1_COLOR_F text, D2D1_COLOR_g_hits.push_back({ 10, -1, 0, pv }); g_hits.push_back({ 10, 1, 0, nx });for (int d = 0; d < 7; d++) {float cx = x0 + 26.5f + d * 28;- Text(std::wstring(1, WeekdayShort(d)[0]), g_tfMiniW, D2D1::RectF(cx - 12, bottom - 167.5f, cx + 12, bottom - 147.5f), soft);+ Text(std::wstring(1, WeekdayShort(DowAt(d))[0]), g_tfMiniW, D2D1::RectF(cx - 12, bottom - 167.5f, cx + 12, bottom - 147.5f), soft);}long long today = DayStart(NowMin());for (int i = 0; i < 42; i++) {@@ -367,6 +492,13 @@ void PaintGolden() {// barra: "+" redondo, Dia/Semana/Mês/Ano, buscafloat cl = X0, cr = sz.width;float plusL = g_side ? cl + 6 : 84;+ if (!g_side) { // lateral escondida: o botão dela vem para a barra, logo depois dos três botões (senão não voltava)+ D2D1_RECT_F sb = D2D1::RectF(84, 7.5f, 121, 44.5f);+ GlassButton(sb, dark);+ IconSidebar({ (sb.left + sb.right) / 2, 26 }, text);+ g_hits.push_back({ 5, 0, 0, sb }); BarButton(sb);+ plusL = sb.right + 8;+ }D2D1_RECT_F plus = D2D1::RectF(plusL, 7.5f, plusL + 37, 44.5f);GlassButton(plus, dark);br->SetColor(text);@@ -407,6 +539,7 @@ void PaintGolden() {}void Paint() {+ if (g_holOn) { int y = FromMin(g_anchor).wYear; RequestHolidays(y); if (FromMin(g_anchor).wMonth == 12) RequestHolidays(y + 1); } // o ano à vistaif (!BeginPaint()) return;g_hits.clear();barButtons.clear();@@ -479,7 +612,7 @@ void Rename(int id) {void NewEvent(long long day, long long at, bool allDay) {Ev e{ g_nextId++, allDay ? day : at, allDay ? AddDays(day, 1) : at + 60, allDay, Tr(L"Novo Evento"), 0, L"" };- for (auto& c : g_cals) if (c.on) { e.cal = c.id; e.color = c.color; break; } // no primeiro calendário à vista+ for (auto& c : g_cals) if (c.on && c.id != HOL_CAL) { e.cal = c.id; e.color = c.color; break; } // no primeiro calendário à vistag_ev.push_back(e);g_selEv = e.id; g_selDay = day;Save();@@ -579,6 +712,7 @@ LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {case WM_CTLCOLOREDIT: return FieldColors((HDC)w, Dark() ? RGB(30, 30, 30) : RGB(255, 255, 255));case WM_FIELDLOST: if (field.h && GetFocus() != field.h) FieldEnd(0); return 0;case WM_TIMER: InvalidateRect(h, nullptr, FALSE); return 0; // a linha da hora atual e os lembretes+ case WM_HOLIDAYS: HolidaysArrived((int)w, (std::vector<HolDay>*)l); InvalidateRect(h, nullptr, FALSE); return 0;case WM_MOUSEWHEEL: {if (field.h) FieldEnd(0);float d = GET_WHEEL_DELTA_WPARAM(w) / 120.f;@@ -605,7 +739,8 @@ LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {}for (auto& ht : g_hits) if (ht.kind == 6 && In(ht.r, x, y)) {Cal& c = g_cals[ht.ev];- if (!right) { c.on = !c.on; Save(); InvalidateRect(h, nullptr, FALSE); return 0; }+ if (!right) { c.on = !c.on; Save(); if (c.id == HOL_CAL && c.on) RequestHolidays(FromMin(g_anchor).wYear); InvalidateRect(h, nullptr, FALSE); return 0; }+ if (c.id == HOL_CAL) return 0; // feriados: só ligar e desligarHMENU mm = CreatePopupMenu(), col = CreatePopupMenu();for (int i = 0; i < 7; i++) AppendMenuW(col, MF_STRING | (c.color == i ? MF_CHECKED : 0), 10 + i, Tr(COLOR_NAMES[i]));AppendMenuW(mm, MF_STRING, 1, Tr(L"Renomear"));@@ -631,6 +766,21 @@ LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {for (auto& ht : g_hits) if (ht.kind == 3 && In(ht.r, x, y)) { Nav(ht.ev); return 0; }for (auto& ht : g_hits) if (ht.kind == 9 && In(ht.r, x, y)) { NewEvent(g_selDay, g_selDay + 9 * 60, g_view == V_MONTH); return 0; }for (auto& ht : g_hits) if (ht.kind == 10 && In(ht.r, x, y)) { g_selDay = AddMonths(MonthStart(g_selDay), ht.ev); InvalidateRect(h, nullptr, FALSE); return 0; }+ for (auto& ht : g_hits) if (ht.kind == 13 && right && In(ht.r, x, y)) { // nomes dos dias: começar a semana em...+ HMENU mm = CreatePopupMenu();+ AppendMenuW(mm, MF_STRING | (g_firstDow == 0 ? MF_CHECKED : 0), 1, Tr(L"Começar a Semana no Domingo"));+ AppendMenuW(mm, MF_STRING | (g_firstDow == 1 ? MF_CHECKED : 0), 2, Tr(L"Começar a Semana na Segunda-feira"));+ if (!g_holCC.empty()) {+ AppendMenuW(mm, MF_SEPARATOR, 0, nullptr);+ AppendMenuW(mm, MF_STRING | (g_holOn ? MF_CHECKED : 0), 3, Tr(L"Mostrar Feriados"));+ }+ int k = TrackPopupMenu(mm, TPM_RETURNCMD | TPM_RIGHTBUTTON, scr.x, scr.y, 0, h, nullptr);+ DestroyMenu(mm);+ if (k == 1 || k == 2) { g_firstDow = k - 1; g_firstDowSet = true; Save(); }+ if (k == 3) { if (Cal* hc = FindCal(HOL_CAL)) { hc->on = !hc->on; Save(); if (hc->on) RequestHolidays(FromMin(g_anchor).wYear); } }+ InvalidateRect(h, nullptr, FALSE);+ return 0;+ }for (auto& ht : g_hits) if (ht.kind == 11 && In(ht.r, x, y)) { g_anchor = g_selDay = ht.day; InvalidateRect(h, nullptr, FALSE); return 0; }for (auto& ht : g_hits) if (ht.kind == 12 && In(ht.r, x, y)) { // busca: digita e Enter vai ao próximo evento com o textoD2D1_RECT_F fr = D2D1::RectF(ht.r.left - 200, ht.r.top + 8, ht.r.left - 8, ht.r.bottom - 8);@@ -654,6 +804,7 @@ LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {auto& ht = g_hits[i];if (ht.kind != 1 || !In(ht.r, x, y)) continue;g_selEv = ht.ev; g_selDay = ht.day;+ if (ht.ev < 0) { g_selEv = -1; InvalidateRect(h, nullptr, FALSE); return 0; } // feriado: só de leituraif (right) { InvalidateRect(h, nullptr, FALSE); EvMenu(ht.ev, scr); return 0; }if (dbl) { Rename(ht.ev); return 0; }InvalidateRect(h, nullptr, FALSE);@@ -729,6 +880,7 @@ int WINAPI wWinMain(HINSTANCE hi, HINSTANCE, PWSTR, int show) {if (semaforo::Aqua()) { TB = 112; SIDE = 218.5f; }if (!CreateMain(hi, L"CalendarioJanela", Tr(L"Calendário"), Proc, semaforo::Aqua() ? 1137 : 1100, semaforo::Aqua() ? 760 : 760)) return 1;SetTimer(wnd, 1, 30000, nullptr);+ LoadHolidayCache();ShowWindow(wnd, show);return Run();}diff --git a/src/clima/main.cpp b/src/clima/main.cppindex 45e1dbb..d475434 100644--- a/src/clima/main.cpp+++ b/src/clima/main.cpp@@ -1,9 +1,11 @@// Clima (Weather do Mac): à esquerda as cidades (a primeira é a dos Ajustes, a mesma do widget); à direita, sobre// um fundo da cor do céu, a cidade, a temperatura grande, a condição, máx./mín., a previsão por hora (24 h), a de// 10 dias (com a barra de mín.–máx.) e os quadros de sensação, umidade, vento e sol. Dados do Open-Meteo (sem chave).-// "+" procura uma cidade pelo nome (geocodificação do Open-Meteo); botão direito numa cidade remove.+// "+" procura uma cidade pelo nome (geocodificação do Open-Meteo); botão direito numa cidade: tornar "Meu Local"+// (vai para os Ajustes, o mesmo do widget) ou apagar (o "Meu Local" também, se houver outra para ficar no lugar).// Cidades em %APPDATA%\Shell\clima.txt.#include "../comum/app2d.h"+#include "../comum/cidade_padrao.h"#include <winhttp.h>#include <map>#include <mutex>@@ -14,7 +16,8 @@ using namespace app2d;namespace {-const float SB = 230;+const float SB_W = 230;+bool g_side = true; // barra lateral das cidades (o botão dela esconde e mostra; antes não havia como)const UINT WM_DATA = WM_APP + 5, WM_FIELDLOST = WM_APP + 77;struct Hour { double t; float temp; int code; bool day; };@@ -137,9 +140,16 @@ std::wstring Setting(const wchar_t* key, const wchar_t* def) {for (auto& l : ReadLines(DataPath(L"ajustes.txt"))) { size_t e = l.find(L'='); if (e != std::wstring::npos && l.substr(0, e) == key) return l.substr(e + 1); }return def;}+// "Meu Local" vai para os Ajustes (tempoCidade/Lat/Lon), o mesmo do widget da mesa+void SetMyPlace(const Place& p) {+ SetAppSetting(L"tempoCidade", p.name);+ SetAppSetting(L"tempoLat", p.lat);+ SetAppSetting(L"tempoLon", p.lon);+}void Load() {g_places.clear();- g_places.push_back({ Setting(L"tempoCidade", L"Campinas"), Setting(L"tempoLat", L"-22.9056"), Setting(L"tempoLon", L"-47.0608") });+ cidade::Padrao def; // sem cidade nos Ajustes: a do fuso do Windows (antes era sempre Campinas)+ g_places.push_back({ Setting(L"tempoCidade", def.nome.c_str()), Setting(L"tempoLat", def.lat.c_str()), Setting(L"tempoLon", def.lon.c_str()) });for (auto& l : ReadLines(g_file)) { auto f = Split(l); if (f.size() >= 4 && f[0] == L"C") g_places.push_back({ Unesc(f[1]), f[2], f[3] }); }}@@ -238,17 +248,23 @@ void PaintGoldenWx() {g_hits.clear();D2D1_SIZE_F sz = Size();D2D1_COLOR_F white = Rgb(255, 255, 255), dim = Rgb(255, 255, 255, 0.72f);- const float SBG = 270;+ const float SBG = g_side ? 270.f : 0.f;Place pl; bool have = g_sel >= 0 && g_sel < (int)g_places.size();if (have) { std::lock_guard<std::mutex> l(g_mx); pl = g_places[g_sel]; }Wx sky = have && pl.wx.ok ? pl.wx : Wx{};if (!have || !pl.wx.ok) { sky.day = true; sky.code = 1; }SkyFill(D2D1::RectF(0, 0, sz.width, sz.height), sky, 0);- // ---- lateral+ // ---- lateral (escondida: o botão dela fica na barra, logo depois dos três botões da janela)+ if (!g_side) {+ D2D1_RECT_F tb = D2D1::RectF(84, 8, 120, 44);+ Fill(tb, Rgb(255, 255, 255, 0.16f), 18); IconSidebar({ 102, 26 }, white); BarButton(tb);+ g_hits.push_back({ 3, 0, tb });+ } else {SkyFill(D2D1::RectF(0, 0, SBG, sz.height), sky, 0.28f);Fill(D2D1::RectF(SBG - 0.5f, 0, SBG, sz.height), Rgb(0, 0, 0, 0.18f));D2D1_RECT_F tb = D2D1::RectF(244 - 18, 8, 244 + 18, 44);Fill(tb, Rgb(255, 255, 255, 0.16f), 18); IconSidebar({ 244, 26 }, white); BarButton(tb);+ g_hits.push_back({ 3, 0, tb });D2D1_RECT_F sr = D2D1::RectF(9, 63, 262, 97);Fill(sr, Rgb(255, 255, 255, 0.16f), 17);br->SetColor(Rgb(255, 255, 255, 0.22f)); rt->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(sr.left + 0.25f, sr.top + 0.25f, sr.right - 0.25f, sr.bottom - 0.25f), 16.75f, 16.75f), br, 0.5f);@@ -271,9 +287,11 @@ void PaintGoldenWx() {y += 76;}if (!g_status.empty()) Text(g_status, g_tfSmall, D2D1::RectF(12, sz.height - 30, SBG - 10, sz.height - 8), dim);+ } // g_side// "+" no conteúdo- D2D1_RECT_F add = D2D1::RectF(297 - 18, 8, 297 + 18, 44);- Fill(add, Rgb(255, 255, 255, 0.16f), 18); IconPlus({ 297, 26 }, white);+ float addX = g_side ? 297.f : 146.f;+ D2D1_RECT_F add = D2D1::RectF(addX - 18, 8, addX + 18, 44);+ Fill(add, Rgb(255, 255, 255, 0.16f), 18); IconPlus({ addX, 26 }, white);g_hits.push_back({ 2, 0, add }); BarButton(add);if (!have) return;float X0 = SBG, cx = (SBG + sz.width) / 2;@@ -411,8 +429,13 @@ void Paint() {D2D1_SIZE_F sz = Size();D2D1_COLOR_F text = dark ? Rgb(245, 245, 247) : Rgb(29, 29, 31), gray = dark ? Rgb(152, 152, 157) : Rgb(134, 134, 139), white = Rgb(255, 255, 255), dim = Rgb(255, 255, 255, 0.7f);rt->Clear(dark ? Rgb(30, 30, 30) : Rgb(242, 242, 245));+ const float SB = g_side ? SB_W : 0.f;+ D2D1_RECT_F tog = D2D1::RectF(10, 10, 38, 38); // mostrar/esconder a lateral+ auto toggle = [&](D2D1_COLOR_F c) { wchar_t sg[2] = { 0xE700, 0 }; Text(sg, g_tfIcon, tog, c); g_hits.push_back({ 3, 0, tog }); };// ---- cidades+ if (g_side) {Fill(D2D1::RectF(0, 0, SB, sz.height), dark ? Rgb(40, 40, 42) : Rgb(236, 236, 240));+ toggle(text);D2D1_RECT_F add = D2D1::RectF(SB - 40, 10, SB - 10, 38);wchar_t p[2] = { 0xE710, 0 }; Text(p, g_tfIcon, add, text);g_hits.push_back({ 2, 0, add });@@ -442,11 +465,12 @@ void Paint() {y += 78;}if (!g_status.empty()) Text(g_status, g_tfSmall, D2D1::RectF(12, sz.height - 30, SB - 10, sz.height - 8), gray);+ } // g_side// ---- cidade escolhida- if (g_sel < 0 || g_sel >= (int)g_places.size()) { EndPaint(); return; }+ if (g_sel < 0 || g_sel >= (int)g_places.size()) { if (!g_side) toggle(text); EndPaint(); return; }Place pl; { std::lock_guard<std::mutex> l(g_mx); pl = g_places[g_sel]; }D2D1_RECT_F main = D2D1::RectF(SB, 0, sz.width, sz.height);- if (!pl.wx.ok) { Text(pl.loading ? Tr(L"Carregando…") : Tr(L"Sem conexão com o serviço do tempo."), g_tfCond, main, gray); EndPaint(); return; }+ if (!pl.wx.ok) { Text(pl.loading ? Tr(L"Carregando…") : Tr(L"Sem conexão com o serviço do tempo."), g_tfCond, main, gray); if (!g_side) toggle(text); EndPaint(); return; }const Wx& w = pl.wx;{D2D1_COLOR_F a, b; Sky(w, a, b);@@ -457,6 +481,7 @@ void Paint() {if (lg) { rt->FillRectangle(main, lg); lg->Release(); }if (st) st->Release();}+ if (!g_side) toggle(white);float cx = (SB + sz.width) / 2, W = sz.width - SB;Text(g_sel == 0 ? std::wstring(Tr(L"Meu Local")) : pl.name, g_tfCity, D2D1::RectF(SB, 24, sz.width, 62), white);if (g_sel == 0) Text(pl.name, g_tfSmallC, D2D1::RectF(SB, 58, sz.width, 76), dim);@@ -562,17 +587,27 @@ LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {if (field.h) FieldEnd(0);float s = Sc(), x = GET_X_LPARAM(l) / s, y = GET_Y_LPARAM(l) / s;for (auto& ht : g_hits) if (In(ht.r, x, y)) {+ if (ht.kind == 3) { g_side = !g_side; InvalidateRect(h, nullptr, FALSE); return 0; }if (ht.kind == 2) {- D2D1_RECT_F fr = BAR > 0 ? D2D1::RectF(38, 71, 256, 89) : D2D1::RectF(12, 12, SB - 46, 36);+ if (!g_side) { g_side = true; Paint(); } // a busca fica na lateral+ D2D1_RECT_F fr = BAR > 0 ? D2D1::RectF(38, 71, 256, 89) : D2D1::RectF(12, 12, SB_W - 46, 36);FieldOpen(fr, L"", 13, false, [](const std::wstring& t, int key) { if (key == VK_RETURN) Search(t); });return 0;}if (ht.kind == 1) {- if (m == WM_RBUTTONUP && ht.arg > 0) {+ if (m == WM_RBUTTONUP) {POINT scr{ GET_X_LPARAM(l), GET_Y_LPARAM(l) }; ClientToScreen(h, &scr);- HMENU mm = CreatePopupMenu(); AppendMenuW(mm, MF_STRING, 1, Tr(L"Apagar"));- if (TrackPopupMenu(mm, TPM_RETURNCMD | TPM_RIGHTBUTTON, scr.x, scr.y, 0, h, nullptr) == 1) { g_places.erase(g_places.begin() + ht.arg); g_sel = 0; Save(); }+ HMENU mm = CreatePopupMenu();+ if (ht.arg > 0) AppendMenuW(mm, MF_STRING, 2, Tr(L"Usar como Meu Local"));+ AppendMenuW(mm, MF_STRING | (g_places.size() > 1 ? 0 : MF_GRAYED), 1, Tr(L"Apagar"));+ int k = TrackPopupMenu(mm, TPM_RETURNCMD | TPM_RIGHTBUTTON, scr.x, scr.y, 0, h, nullptr);DestroyMenu(mm);+ if (k == 2) { std::lock_guard<std::mutex> lk(g_mx); std::swap(g_places[0], g_places[ht.arg]); SetMyPlace(g_places[0]); g_sel = 0; Save(); }+ else if (k == 1 && g_places.size() > 1) {+ { std::lock_guard<std::mutex> lk(g_mx); g_places.erase(g_places.begin() + ht.arg); }+ if (ht.arg == 0) SetMyPlace(g_places[0]); // o "Meu Local" saiu: a próxima cidade fica no lugar+ g_sel = 0; Save();+ }} else g_sel = ht.arg;InvalidateRect(h, nullptr, FALSE);}diff --git a/src/comum/app2d.h b/src/comum/app2d.hindex 844b5b7..c7ad4de 100644--- a/src/comum/app2d.h+++ b/src/comum/app2d.h@@ -486,6 +486,27 @@ inline D2D1_COLOR_F SidebarColor() {return Tinted(Dark() ? D2D1::ColorF(40 / 255.f, 40 / 255.f, 42 / 255.f) : D2D1::ColorF(242 / 255.f, 242 / 255.f, 245 / 255.f));}+// Grava um ajuste no %APPDATA%\Shell\ajustes.txt (o mesmo dos Ajustes do Sistema). Com o Shell aberto, a mudança vai+// para ele (WM_COPYDATA 'SJST'): ele grava no arquivo dele e recarrega; sem o Shell (modo só apps), grava aqui.+inline void SetAppSetting(const wchar_t* key, const std::wstring& v) {+ HWND sh = FindWindowExW(HWND_MESSAGE, nullptr, L"ShellMensagens", nullptr);+ if (!sh) sh = FindWindowW(L"ShellMensagens", nullptr);+ std::wstring kv = std::wstring(key) + L"=" + v;+ if (sh) {+ COPYDATASTRUCT cd{ 0x534A5354, (DWORD)((kv.size() + 1) * sizeof(wchar_t)), (void*)kv.c_str() };+ DWORD_PTR r = 0;+ if (SendMessageTimeoutW(sh, WM_COPYDATA, (WPARAM)wnd, (LPARAM)&cd, SMTO_ABORTIFHUNG, 500, &r) && r) return;+ }+ std::wstring path = DataPath(L"ajustes.txt"), want = std::wstring(key) + L"=";+ auto lines = ReadLines(path);+ bool done = false;+ for (auto& l : lines) if (l.rfind(want, 0) == 0) { l = kv; done = true; }+ if (!done) lines.push_back(kv);+ WriteLines(path, lines);+ static UINT msg = RegisterWindowMessageW(L"ShellAjustesMudaram");+ if (sh) PostMessageW(sh, msg, 0, 0);+}+inline int Run() {if (!FotoPath().empty() && wnd) SetTimer(nullptr, 0, 1800, FotoTick); // teste: espera carregar e salva a fotoMSG m;diff --git a/src/comum/cidade_padrao.h b/src/comum/cidade_padrao.hnew file mode 100644index 0000000..1b252d8--- /dev/null+++ b/src/comum/cidade_padrao.h@@ -0,0 +1,75 @@+#pragma once+// Cidade padrão do Tempo (app Clima e widget da mesa) quando o ajustes.txt não tem tempoCidade: a do fuso horário+// do Windows. Antes era sempre Campinas, e quem é de fora do Brasil abria o Tempo no Brasil (Reddit, 20/11/2026).+// Fuso sem cidade na tabela: Londres (UTC).+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <windows.h>+#include <string>++namespace cidade {++struct Padrao {+ std::wstring nome = L"London", lat = L"51.5072", lon = L"-0.1276";+ Padrao() {+ static const struct { const wchar_t *tz, *nome, *lat, *lon; } T[] = {+ { L"E. South America Standard Time", L"Campinas", L"-22.9056", L"-47.0608" },+ { L"SA Eastern Standard Time", L"Fortaleza", L"-3.7319", L"-38.5267" },+ { L"Bahia Standard Time", L"Salvador", L"-12.9777", L"-38.5016" },+ { L"Tocantins Standard Time", L"Palmas", L"-10.1844", L"-48.3336" },+ { L"SA Western Standard Time", L"Manaus", L"-3.1190", L"-60.0217" },+ { L"Central Brazilian Standard Time", L"Cuiabá", L"-15.6014", L"-56.0979" },+ { L"Argentina Standard Time", L"Buenos Aires", L"-34.6037", L"-58.3816" },+ { L"Pacific SA Standard Time", L"Santiago", L"-33.4489", L"-70.6693" },+ { L"SA Pacific Standard Time", L"Bogotá", L"4.7110", L"-74.0721" },+ { L"Venezuela Standard Time", L"Caracas", L"10.4806", L"-66.9036" },+ { L"Central Standard Time (Mexico)", L"Ciudad de México", L"19.4326", L"-99.1332" },+ { L"Eastern Standard Time", L"New York", L"40.7128", L"-74.0060" },+ { L"Central Standard Time", L"Chicago", L"41.8781", L"-87.6298" },+ { L"Mountain Standard Time", L"Denver", L"39.7392", L"-104.9903" },+ { L"US Mountain Standard Time", L"Phoenix", L"33.4484", L"-112.0740" },+ { L"Pacific Standard Time", L"Los Angeles", L"34.0522", L"-118.2437" },+ { L"Alaskan Standard Time", L"Anchorage", L"61.2181", L"-149.9003" },+ { L"Hawaiian Standard Time", L"Honolulu", L"21.3069", L"-157.8583" },+ { L"Atlantic Standard Time", L"Halifax", L"44.6488", L"-63.5752" },+ { L"GMT Standard Time", L"London", L"51.5072", L"-0.1276" },+ { L"Greenwich Standard Time", L"Reykjavík", L"64.1466", L"-21.9426" },+ { L"W. Europe Standard Time", L"Berlin", L"52.5200", L"13.4050" },+ { L"Romance Standard Time", L"Paris", L"48.8566", L"2.3522" },+ { L"Central Europe Standard Time", L"Budapest", L"47.4979", L"19.0402" },+ { L"Central European Standard Time", L"Warszawa", L"52.2297", L"21.0122" },+ { L"GTB Standard Time", L"Athens", L"37.9838", L"23.7275" },+ { L"FLE Standard Time", L"Kyiv", L"50.4501", L"30.5234" },+ { L"E. Europe Standard Time", L"Chișinău", L"47.0105", L"28.8638" },+ { L"Turkey Standard Time", L"İstanbul", L"41.0082", L"28.9784" },+ { L"Russian Standard Time", L"Moscow", L"55.7558", L"37.6173" },+ { L"Israel Standard Time", L"Jerusalem", L"31.7683", L"35.2137" },+ { L"Egypt Standard Time", L"Cairo", L"30.0444", L"31.2357" },+ { L"South Africa Standard Time", L"Johannesburg", L"-26.2041", L"28.0473" },+ { L"W. Central Africa Standard Time", L"Lagos", L"6.5244", L"3.3792" },+ { L"E. Africa Standard Time", L"Nairobi", L"-1.2921", L"36.8219" },+ { L"Arab Standard Time", L"Riyadh", L"24.7136", L"46.6753" },+ { L"Arabian Standard Time", L"Dubai", L"25.2048", L"55.2708" },+ { L"Iran Standard Time", L"Tehran", L"35.6892", L"51.3890" },+ { L"Pakistan Standard Time", L"Karachi", L"24.8607", L"67.0011" },+ { L"India Standard Time", L"Mumbai", L"19.0760", L"72.8777" },+ { L"Bangladesh Standard Time", L"Dhaka", L"23.8103", L"90.4125" },+ { L"SE Asia Standard Time", L"Bangkok", L"13.7563", L"100.5018" },+ { L"Singapore Standard Time", L"Singapore", L"1.3521", L"103.8198" },+ { L"China Standard Time", L"Beijing", L"39.9042", L"116.4074" },+ { L"Taipei Standard Time", L"Taipei", L"25.0330", L"121.5654" },+ { L"Korea Standard Time", L"Seoul", L"37.5665", L"126.9780" },+ { L"Tokyo Standard Time", L"Tokyo", L"35.6762", L"139.6503" },+ { L"W. Australia Standard Time", L"Perth", L"-31.9505", L"115.8605" },+ { L"AUS Eastern Standard Time", L"Sydney", L"-33.8688", L"151.2093" },+ { L"E. Australia Standard Time", L"Brisbane", L"-27.4698", L"153.0251" },+ { L"New Zealand Standard Time", L"Auckland", L"-36.8485", L"174.7633" },+ };+ DYNAMIC_TIME_ZONE_INFORMATION d{};+ if (GetDynamicTimeZoneInformation(&d) == TIME_ZONE_ID_INVALID) return;+ for (auto& t : T) if (!wcscmp(d.TimeZoneKeyName, t.tz)) { nome = t.nome; lat = t.lat; lon = t.lon; return; }+ }+};++} // namespace cidadediff --git a/src/comum/idioma_en.inc b/src/comum/idioma_en.incindex 5a5c0a4..6f9c4c0 100644--- a/src/comum/idioma_en.inc+++ b/src/comum/idioma_en.inc@@ -77,6 +77,16 @@{ L"Encerrar", L"Quit" },{ L"Ativar Ocultação", L"Turn Hiding On" },{ L"Ativar Ampliação", L"Turn Magnification On" },+{ L"Ocultação Inteligente", L"Smart Hiding" },+{ L"Ocultar o Dock", L"Hide the Dock" },+{ L"Quando uma janela encostar nele", L"When a window touches it (smart hide)" },+{ L"Feriados", L"Holidays" },+{ L"Começar a Semana no Domingo", L"Start Week on Sunday" },+{ L"Começar a Semana na Segunda-feira", L"Start Week on Monday" },+{ L"Mostrar Feriados", L"Show Holidays" },+{ L"Usar como Meu Local", L"Use as My Location" },+{ L"Outra Cidade…", L"Other City…" },+{ L"Automaticamente", L"Automatically" },{ L"Aparência Automática", L"Automatic Appearance" },{ L"Aparência Clara", L"Light Appearance" },{ L"Aparência Escura", L"Dark Appearance" },diff --git a/src/janelas/macjanela.cpp b/src/janelas/macjanela.cppindex 21aafdc..c6fd65b 100644--- a/src/janelas/macjanela.cpp+++ b/src/janelas/macjanela.cpp@@ -159,16 +159,74 @@ RECT FrameRect(HWND h) {bool TemaTahoe(bool force = false); // mais abaixo: tema Tahoe ligado no ajustes.txt do Shellint CornerRadius(HWND h); // mais abaixo: o canto da janela (px)++// Recorte arredondado [x0, x1) × [y0, y1) com raio r (px), simétrico e sempre por dentro do arco que a moldura+// suavizada (UpdateCorners) desenha: um pixel só entra se o centro dele fica a 0,5 px ou mais para dentro do arco.+// O CreateRoundRectRgn do Windows não é simétrico (sai ~1 px a mais à direita e embaixo): os degraus dele+// passavam do arco suavizado e sobravam "cantinhos" claros nas janelas no tema claro (20/11/2026).+HRGN RoundRgn(int x0, int y0, int x1, int y1, int r) {+ int w = x1 - x0, h = y1 - y0;+ r = std::max(0, std::min(r, std::min(w, h) / 2));+ std::vector<RECT> rows;+ auto inset = [&](int y) { // quantos pixels ficam de fora no começo da linha y (0 = topo)+ int yy = y < r ? y : h - 1 - y;+ if (yy >= r) return 0;+ float dy = r - (yy + 0.5f), lim = r - 0.5f;+ float in2 = lim * lim - dy * dy;+ if (in2 < 0) return -1; // linha inteira fora do arco+ return (int)std::ceil(r - std::sqrt(in2) - 0.5f);+ };+ for (int y = 0; y < h; y++) {+ int k = inset(y);+ if (k < 0 || 2 * k >= w) continue;+ if (y >= r && y < h - r) { rows.push_back({ x0, y0 + y, x1, y0 + h - r }); y = h - r - 1; continue; } // o meio de uma vez+ rows.push_back({ x0 + k, y0 + y, x1 - k, y0 + y + 1 });+ }+ std::vector<char> buf(sizeof(RGNDATAHEADER) + rows.size() * sizeof(RECT));+ auto* rd = (RGNDATA*)buf.data();+ rd->rdh = { sizeof(RGNDATAHEADER), RDH_RECTANGLES, (DWORD)rows.size(), (DWORD)(rows.size() * sizeof(RECT)), { x0, y0, x1, y1 } };+ memcpy(rd->Buffer, rows.data(), rows.size() * sizeof(RECT));+ return ExtCreateRegion(nullptr, (DWORD)buf.size(), rd);+}bool OwnApp(); // mais abaixo: um dos apps do WacOSconst float PATCH_L = 80, PATCH_R = 3 * 46 + 6; // pt: botões do Mac / os três botões do app (46 pt cada no Windows)+// Apps do Windows (barra de título padrão, mais alta que a do Mac): os botões 4 pt mais para dentro; na medida do+// Mac eles pareciam colados na borda (Reddit, 20/11/2026). Os apps do WacOS, barras próprias e o Leopard ficam como estão.+float WinAppInset(Info* in) {+ return in->custom || in->tool || OwnApp() || UnifiedBar(in->owner) || leopard::On() ? 0.f : 4.f;+}++// posição dos três botões (pt): centro do 1º, passo entre centros e raio; o desenho e o clique usam esta+void LightsLayout(Info* in, float& lx0, float& lpitch, float& lr) {+ lx0 = in->tool ? 14.f : 19.f; lpitch = in->tool ? 20.f : 23.f; lr = in->tool ? 6.f : 7.f;+ // Tahoe (guia macOS26-Theme-Reference, seção 9.1, medido): só título = 14×14 com o 1º em x 9 (centro 16),+ // 23 entre eles; painel utilitário = 10×10 em x 8 (centro 13), 17 entre eles+ if (TemaTahoe()) { lx0 = in->tool ? 13.f : 16.f; lpitch = in->tool ? 17.f : 23.f; lr = in->tool ? 5.f : 7.f; }+ if (int u = UnifiedBar(in->owner)) { lx0 = u > 40 ? 26.f : 16.f; lpitch = 23; lr = 7; } // macOS 27: com barra de ferramentas 26, 49, 72; só título 16, 39, 62+ if (leopard::On() && !in->tool && !UnifiedBar(in->owner)) { lx0 = 14.5f; lpitch = 21; lr = 7; } // Leopard (medido: 14 px, 21 entre centros)+ lx0 += WinAppInset(in);+}++void Insets(Info* in, int& l, int& t, int& rr, int& b);RECT BarRect(Info* in) {if (int u = UnifiedBar(in->owner)) { // a faixa de cima da área do appPOINT c{ 0, 0 }; ClientToScreen(in->owner, &c);RECT cr; GetClientRect(in->owner, &cr);return { c.x, c.y, c.x + cr.right, c.y + (int)std::lround(u * Scale(in->owner)) };}- if (!in->custom) return CaptionRect(in->owner);+ if (!in->custom) {+ RECT r = CaptionRect(in->owner);+ // tamanho fixo (diálogos): o recorte pega a janela inteira, com a borda do Windows dos lados da barra; a barra+ // vai até o recorte, senão sobrava uma faixa lisa ao lado dela (bem visível no metal do Leopard, 20/11/2026)+ if (in->rgn.cx && !IsZoomed(in->owner)) {+ int l, t, rr, b; Insets(in, l, t, rr, b);+ RECT wr; GetWindowRect(in->owner, &wr);+ r.left = std::min(r.left, wr.left + l); r.right = std::max(r.right, wr.right - rr);+ r.top = std::min(r.top, wr.top + t); // e de cima, rente ao recorte (a linha de 1 px do topo também)+ }+ return r;+ }RECT f = FrameRect(in->owner);float sc = Scale(in->owner);int h = in->barH ? in->barH : (int)(32 * sc);@@ -235,12 +293,8 @@ void Paint(Info* in) {static const D2D1_COLOR_F on_c[3] = { D2D1::ColorF(1.0f, 0.373f, 0.341f), D2D1::ColorF(0.996f, 0.737f, 0.18f), D2D1::ColorF(0.157f, 0.784f, 0.251f) }; const D2D1_COLOR_F* on = semaforo::Pick(on_c, semaforo::FILL);LONG st = in->style;bool can[3] = { true, (st & WS_MINIMIZEBOX) != 0, (st & WS_MAXIMIZEBOX) != 0 };- float lx0 = in->tool ? 14.f : 19.f, lpitch = in->tool ? 20.f : 23.f, lr = in->tool ? 6.f : 7.f;- // Tahoe (guia macOS26-Theme-Reference, seção 9.1, medido): só título = 14×14 com o 1º em x 9 (centro 16),- // 23 entre eles; painel utilitário = 10×10 em x 8 (centro 13), 17 entre eles- if (TemaTahoe()) { lx0 = in->tool ? 13.f : 16.f; lpitch = in->tool ? 17.f : 23.f; lr = in->tool ? 5.f : 7.f; }- if (int u = UnifiedBar(in->owner)) { lx0 = u > 40 ? 26.f : 16.f; lpitch = 23; lr = 7; } // macOS 27: com barra de ferramentas 26, 49, 72; só título 16, 39, 62- if (leopard::On() && !in->tool && !UnifiedBar(in->owner)) { lx0 = 14.5f; lpitch = 21; lr = 7; } // Leopard (medido: 14 px, 21 entre centros)+ float lx0, lpitch, lr;+ LightsLayout(in, lx0, lpitch, lr);for (int k = 0; k < 3; k++) {D2D1_POINT_2F c{ lx0 + k * lpitch, H / 2 };bool lit = (in->active || in->hoverLights) && can[k];@@ -306,10 +360,8 @@ int HitLight(Info* in, POINT clientPt) {RECT r = BarRect(in);float H = (r.bottom - r.top) / sc;float x = clientPt.x / sc, y = clientPt.y / sc;- float lx0 = in->tool ? 14.f : 19.f, lpitch = in->tool ? 20.f : 23.f;- if (TemaTahoe()) { lx0 = in->tool ? 13.f : 16.f; lpitch = in->tool ? 17.f : 23.f; } // mesmas posições do desenho- if (int u = UnifiedBar(in->owner)) { lx0 = u > 40 ? 26.f : 16.f; lpitch = 23; }- if (leopard::On() && !in->tool && !UnifiedBar(in->owner)) { lx0 = 14.5f; lpitch = 21; } // mesmas posições do desenho+ float lx0, lpitch, lr;+ LightsLayout(in, lx0, lpitch, lr); // mesmas posições do desenhofor (int k = 0; k < 3; k++) if (std::fabs(x - (lx0 + k * lpitch)) <= 9 && std::fabs(y - H / 2) <= 8) return k;return -1;}@@ -589,8 +641,8 @@ void ApplyRegion(Info* in) {if (sz.cx == in->rgn.cx && sz.cy == in->rgn.cy) return;int l, t, rr, b;Insets(in, l, t, rr, b);- // um pouco mais fechado que o arco: a borda suavizada (UpdateCorners) cobre o que sobra- int R = CornerRadius(h) * 2 + 2;+ // por dentro do arco: a borda suavizada (UpdateCorners) cobre o que sobra+ int R = CornerRadius(h);in->rgn = sz;// a borda fina e o arredondamento do Windows seriam desenhados no tamanho antigo, em volta do recorteCOLORREF none = 0xFFFFFFFE; // DWMWA_COLOR_NONE@@ -601,7 +653,7 @@ void ApplyRegion(Info* in) {// bordas invisíveis), um retângulo escuro de bordas retas em volta de diálogosDWMNCRENDERINGPOLICY off = DWMNCRP_DISABLED;DwmSetWindowAttribute(h, DWMWA_NCRENDERING_POLICY, &off, sizeof(off));- SetWindowRgn(h, CreateRoundRectRgn(l, t, sz.cx - rr + 1, sz.cy - b + 1, R, R), TRUE);+ SetWindowRgn(h, RoundRgn(l, t, sz.cx - rr, sz.cy - b, R), TRUE);PaintNC(in);}@@ -829,7 +881,7 @@ LRESULT CALLBACK OverlayProc(HWND h, UINT m, WPARAM w, LPARAM l) {RECT r = BarRect(in);p.x -= r.left; p.y -= r.top;float sc = Scale(in->owner);- if (p.x / sc < (in->custom ? PATCH_L : UnifiedBar(in->owner) > 40 ? 84 : 72)) return HTCLIENT;+ if (p.x / sc < (in->custom ? PATCH_L : (UnifiedBar(in->owner) > 40 ? 84 : 72) + WinAppInset(in))) return HTCLIENT;if (in->custom && p.x / sc > (r.right - r.left) / sc - PATCH_R) return HTCLIENT; // os três botões; o resto deixa o clique passar para a barra (arrastar)return HTTRANSPARENT;}@@ -1458,8 +1510,8 @@ void CantoLeve(HWND h) {}int W = wr.right - wr.left, H = wr.bottom - wr.top;if (W - 2 * b < 200 || H - b < 120) return;- int r = CornerRadius(h), d = r * 2 + 2;- HRGN g = CreateRoundRectRgn(b, 0, W - b + 1, H - b + 1, d, d);+ int r = CornerRadius(h);+ HRGN g = RoundRgn(b, 0, W - b, H - b, r);if (g && !SetWindowRgn(h, g, TRUE)) DeleteObject(g);SetPropW(h, PROP_CANTO, (HANDLE)(INT_PTR)r);}diff --git a/src/relogio/main.cpp b/src/relogio/main.cppindex fec676a..a501bba 100644--- a/src/relogio/main.cpp+++ b/src/relogio/main.cpp@@ -1,19 +1,24 @@// Relógio (Clock do Mac): Relógio Mundial, Alarmes, Cronômetro e Timer, nas abas do alto (Ctrl+1..4).// - Mundial: cidades (fusos do Windows), hora, "Hoje/Amanhã" e a diferença; + adiciona, botão direito remove.// - Alarmes: hora grande, nome, dias e o interruptor; + cria, clique edita a hora, botão direito apaga/renomeia.-// Quem toca é o Shell (banner do Mac + som), mesmo com o app fechado: %APPDATA%\Shell\alarmes.txt.+// Quem toca é o Shell (banner do Mac + som), mesmo com o app fechado: %APPDATA%\Shell\relogio.txt. Sem o Shell+// (modo só apps), o próprio app toca enquanto estiver aberto.+// - "Outra Cidade…" no +: qualquer cidade pelo nome (Open-Meteo), com o fuso convertido pelo ICU do Windows.// - Cronômetro: Iniciar/Parar, Volta/Zerar e a lista de voltas (a melhor em verde, a pior em vermelho).// - Timer: escolher minutos (atalhos e − / +), Iniciar/Pausar/Cancelar; ao acabar toca e a janela vem para frente.#include "../comum/app2d.h"#include <mmsystem.h>+#include <thread>+#include <winhttp.h>#pragma comment(lib, "winmm.lib")+#pragma comment(lib, "winhttp.lib")using namespace app2d;namespace {float TB = 56; // macOS 27: 52 (barra unificada)-const UINT WM_FIELDLOST = WM_APP + 77;+const UINT WM_FIELDLOST = WM_APP + 77, WM_CITYFOUND = WM_APP + 8;int g_tab = 0; // 0 mundial, 1 alarmes, 2 cronômetro, 3 timerIDWriteTextFormat *g_tfSeg, *g_tfBig, *g_tfBigR, *g_tfHuge, *g_tfRow, *g_tfSub, *g_tfBtn, *g_tfIcon, *g_tfMono;@@ -32,12 +37,18 @@ const City CITIES[] = {{ L"Cairo", L"Egypt Standard Time" }, { L"Nairóbi", L"E. Africa Standard Time" }, { L"UTC", L"UTC" },};const int NCITIES = (int)(sizeof(CITIES) / sizeof(CITIES[0]));-std::vector<int> g_world; // índices em CITIES+// cidades que o usuário procurou pelo nome (Outra Cidade…): no g_world como 1000 + índice aqui+struct Custom { std::wstring name, tz; };+std::vector<Custom> g_custom;+const int CUSTOM0 = 1000;+std::vector<int> g_world; // índices em CITIES (ou CUSTOM0 + índice em g_custom)+const wchar_t* CityTz(int i) { return i >= CUSTOM0 ? g_custom[i - CUSTOM0].tz.c_str() : CITIES[i].tz; }+std::wstring CityName(int i) { return i >= CUSTOM0 ? g_custom[i - CUSTOM0].name : std::wstring(Tr(CITIES[i].name)); }bool CityTime(int i, SYSTEMTIME& out) {DYNAMIC_TIME_ZONE_INFORMATION d{};for (DWORD k = 0; EnumDynamicTimeZoneInformation(k, &d) == ERROR_SUCCESS; k++)- if (!wcscmp(d.TimeZoneKeyName, CITIES[i].tz)) {+ if (!wcscmp(d.TimeZoneKeyName, CityTz(i))) {SYSTEMTIME utc; GetSystemTime(&utc);return SystemTimeToTzSpecificLocalTimeEx(&d, &utc, &out) != FALSE;}@@ -51,17 +62,20 @@ int g_nextId = 1;std::wstring g_file;void Save() {- std::vector<std::wstring> out{ L"# Relógio do WacOS: W = cidade do Relógio Mundial, A = alarme (id, hora, minuto, ligado, nome, dias)" };+ std::vector<std::wstring> out{ L"# Relógio do WacOS: W = cidade do Relógio Mundial, C = cidade própria (nome, fuso do Windows), A = alarme (id, hora, minuto, ligado, nome, dias)" };+ for (auto& c : g_custom) out.push_back(L"C\t" + Esc(c.name) + L"\t" + c.tz);for (int i : g_world) out.push_back(L"W\t" + std::to_wstring(i));for (auto& a : g_alarms) out.push_back(L"A\t" + std::to_wstring(a.id) + L"\t" + std::to_wstring(a.hh) + L"\t" + std::to_wstring(a.mm) + L"\t" + (a.on ? L"1" : L"0") + L"\t" + Esc(a.label) + L"\t" + std::to_wstring(a.days));WriteLines(g_file, out);}void Load() {- g_world.clear(); g_alarms.clear();+ g_world.clear(); g_alarms.clear(); g_custom.clear();bool any = false;- for (auto& l : ReadLines(g_file)) {+ auto lines = ReadLines(g_file);+ for (auto& l : lines) { auto f = Split(l); if (f.size() >= 3 && f[0] == L"C") g_custom.push_back({ Unesc(f[1]), f[2] }); }+ for (auto& l : lines) {auto f = Split(l);- if (f.size() >= 2 && f[0] == L"W") { int i = _wtoi(f[1].c_str()); if (i >= 0 && i < NCITIES) g_world.push_back(i); any = true; }+ if (f.size() >= 2 && f[0] == L"W") { int i = _wtoi(f[1].c_str()); if ((i >= 0 && i < NCITIES) || (i >= CUSTOM0 && i - CUSTOM0 < (int)g_custom.size())) g_world.push_back(i); any = true; }else if (f.size() >= 7 && f[0] == L"A") g_alarms.push_back({ _wtoi(f[1].c_str()), _wtoi(f[2].c_str()), _wtoi(f[3].c_str()), f[4] == L"1", Unesc(f[5]), _wtoi(f[6].c_str()) });}if (!any && g_world.empty()) g_world = { 0, 5, 25, 17 }; // São Paulo, Londres, Nova York, Tóquio@@ -202,7 +216,7 @@ void PaintWorldGolden(D2D1_SIZE_F sz, bool dark) {Circle({ x, y }, 4.2f, Rgb(255, 255, 255, 0.9f), true);Circle({ x, y }, 3.2f, Rgb(255, 149, 0), true);wchar_t hm[24]; swprintf_s(hm, L"%d:%02d", t.wHour, t.wMinute);- Text(Tr(CITIES[i].name), g_tfCityB, D2D1::RectF(x + 7, y - 9, x + 160, y + 5), Rgb(255, 255, 255));+ Text(CityName(i), g_tfCityB, D2D1::RectF(x + 7, y - 9, x + 160, y + 5), Rgb(255, 255, 255));Text(hm, g_tfCityT, D2D1::RectF(x + 7, y + 4, x + 160, y + 15), Rgb(255, 255, 255, 0.85f));}// cartões com o relógio analógico@@ -233,7 +247,7 @@ void PaintWorldGolden(D2D1_SIZE_F sz, bool dark) {rt->DrawLine({ c.x - (float)sin(ss) * 8, c.y + (float)cos(ss) * 8 }, { c.x + (float)sin(ss) * 46, c.y - (float)cos(ss) * 46 }, br, 1);Circle(c, 3, Rgb(255, 149, 0), true);Circle(c, 1.4f, day ? Rgb(255, 255, 255) : Rgb(0, 0, 0), true);- wchar_t nm[96]; swprintf_s(nm, L"%ls, %d:%02d", Tr(CITIES[i].name), t.wHour, t.wMinute);+ wchar_t nm[96]; swprintf_s(nm, L"%ls, %d:%02d", CityName(i).c_str(), t.wHour, t.wMinute);Text(nm, g_tfCard, D2D1::RectF(x0 + 6, cy0 + 136, x0 + 164, cy0 + 154), dark ? Rgb(245, 245, 247) : Rgb(29, 29, 31));FILETIME a, b2; SystemTimeToFileTime(&here, &a); SystemTimeToFileTime(&t, &b2);long long diffMin = ((long long)(((ULONGLONG)b2.dwHighDateTime << 32 | b2.dwLowDateTime) - ((ULONGLONG)a.dwHighDateTime << 32 | a.dwLowDateTime))) / 600000000LL;@@ -346,7 +360,7 @@ void Paint() {else swprintf_s(off, L", %+lld h", dh / 2);D2D1_RECT_F row = D2D1::RectF(X, y, W, y + 74);Text(day + off, g_tfSub, D2D1::RectF(X, y + 10, W - 200, y + 30), gray);- Text(Tr(CITIES[i].name), g_tfRow, D2D1::RectF(X, y + 30, W - 200, y + 60), text);+ Text(CityName(i), g_tfRow, D2D1::RectF(X, y + 30, W - 200, y + 60), text);wchar_t hm[16]; swprintf_s(hm, L"%d:%02d", t.wHour, t.wMinute);Text(hm, g_tfBigR, D2D1::RectF(W - 220, y, W, y + 74), text);Fill(D2D1::RectF(X, y + 74, W, y + 75), line);@@ -426,7 +440,32 @@ void Paint() {EndPaint();}+// Sem o Shell (modo só apps) ninguém tocava os alarmes: o app toca enquanto estiver aberto+void CheckAlarms() {+ SYSTEMTIME t; GetLocalTime(&t);+ static int last = -1;+ int now = t.wHour * 60 + t.wMinute;+ if (now == last) return;+ bool first = last < 0;+ last = now;+ if (first) return; // ao abrir não toca o minuto que já está correndo+ if (FindWindowExW(HWND_MESSAGE, nullptr, L"ShellMensagens", nullptr) || FindWindowW(L"ShellMensagens", nullptr)) return; // o Shell toca+ bool changed = false;+ for (auto& a : g_alarms) {+ if (!a.on || a.hh != t.wHour || a.mm != t.wMinute) continue;+ if (a.days && !(a.days & (1 << t.wDayOfWeek))) continue;+ if (!a.days) { a.on = false; changed = true; } // uma vez só: desliga (como no Mac)+ PlaySoundW(L"SystemExclamation", nullptr, SND_ALIAS | SND_ASYNC);+ FLASHWINFO fw{ sizeof(fw), wnd, FLASHW_ALL | FLASHW_TIMERNOFG, 6, 0 }; FlashWindowEx(&fw);+ wchar_t msg[160]; swprintf_s(msg, L"%ls\n%d:%02d", a.label.empty() ? Tr(L"Alarme") : a.label.c_str(), a.hh, a.mm);+ if (changed) Save();+ MessageBoxW(wnd, msg, Tr(L"Relógio"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST);+ }+ if (changed) { Save(); InvalidateRect(wnd, nullptr, FALSE); }+}+void Tick() {+ CheckAlarms();if (g_tmRun && !g_tmPaused && TmLeft() == 0) { // timer acaboug_tmRun = false;PlaySoundW(L"SystemExclamation", nullptr, SND_ALIAS | SND_ASYNC);@@ -438,12 +477,81 @@ void Tick() {if (g_swRun || (g_tmRun && !g_tmPaused) || ++n % 20 == 0) InvalidateRect(wnd, nullptr, FALSE);}+// Fuso IANA ("Europe/Warsaw", o que o Open-Meteo devolve) -> nome do fuso no Windows ("Central European Standard+// Time"), pelo ICU que vem no Windows 10 1903+ (icu.dll)+std::wstring WindowsTz(const std::wstring& iana) {+ typedef int (*GetWinId)(const wchar_t*, int, wchar_t*, int, int*);+ static HMODULE icu = LoadLibraryExW(L"icu.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);+ static GetWinId f = icu ? (GetWinId)GetProcAddress(icu, "ucal_getWindowsTimeZoneID") : nullptr;+ if (!f) return L"";+ wchar_t out[128] = {}; int st = 0;+ int n = f(iana.c_str(), (int)iana.size(), out, 127, &st);+ return st > 0 || n <= 0 ? L"" : std::wstring(out, n);+}+std::string Utf8Of(const std::wstring& w) { int n = WideCharToMultiByte(CP_UTF8, 0, w.data(), (int)w.size(), nullptr, 0, nullptr, nullptr); std::string s(n, '\0'); WideCharToMultiByte(CP_UTF8, 0, w.data(), (int)w.size(), s.data(), n, nullptr, nullptr); return s; }+std::wstring WideOf(const std::string& s) { int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0); std::wstring w(n, L'\0'); MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), w.data(), n); return w; }+std::string JsonField(const std::string& j, const char* key) {+ std::string k = std::string("\"") + key + "\":\"";+ size_t p = j.find(k); if (p == std::string::npos) return "";+ p += k.size(); size_t e = j.find('"', p);+ return e == std::string::npos ? "" : j.substr(p, e - p);+}+void FindCity(const std::wstring& q) {+ if (q.empty()) return;+ HWND h = wnd;+ std::thread([q, h] {+ std::string u = Utf8Of(q), enc;+ for (unsigned char c : u) { if (isalnum(c) || c == '-' || c == '.') enc += (char)c; else { char b[4]; sprintf_s(b, "%%%02X", c); enc += b; } }+ std::wstring path = L"/v1/search?count=1&language=" + std::wstring(idioma::En() ? L"en" : L"pt") + L"&name=" + WideOf(enc);+ std::string body;+ HINTERNET ses = WinHttpOpen(L"WacOS-Clock/1.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);+ if (ses) {+ WinHttpSetTimeouts(ses, 5000, 5000, 8000, 8000);+ HINTERNET con = WinHttpConnect(ses, L"geocoding-api.open-meteo.com", INTERNET_DEFAULT_HTTPS_PORT, 0);+ HINTERNET req = con ? WinHttpOpenRequest(con, L"GET", path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : nullptr;+ if (req && WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) && WinHttpReceiveResponse(req, nullptr)) {+ DWORD avail = 0;+ while (WinHttpQueryDataAvailable(req, &avail) && avail && body.size() < 64 * 1024) {+ std::string chunk(avail, '\0'); DWORD got = 0;+ if (!WinHttpReadData(req, chunk.data(), avail, &got) || !got) break;+ body.append(chunk.data(), got);+ }+ }+ if (req) WinHttpCloseHandle(req);+ if (con) WinHttpCloseHandle(con);+ WinHttpCloseHandle(ses);+ }+ auto* c = new Custom;+ if (body.find("\"results\"") != std::string::npos) { c->name = WideOf(JsonField(body, "name")); c->tz = WideOf(JsonField(body, "timezone")); }+ if (!PostMessageW(h, WM_CITYFOUND, 0, (LPARAM)c)) delete c;+ }).detach();+}+void CityFound(Custom* c) {+ std::wstring tz = c->tz.empty() ? L"" : WindowsTz(c->tz);+ if (c->name.empty() || tz.empty()) MessageBoxW(wnd, Tr(L"Cidade não encontrada."), Tr(L"Relógio"), MB_OK | MB_ICONINFORMATION);+ else {+ int idx = -1;+ for (int k = 0; k < (int)g_custom.size(); k++) if (g_custom[k].name == c->name && g_custom[k].tz == tz) idx = k;+ if (idx < 0) { g_custom.push_back({ c->name, tz }); idx = (int)g_custom.size() - 1; }+ if (std::find(g_world.begin(), g_world.end(), CUSTOM0 + idx) == g_world.end()) g_world.push_back(CUSTOM0 + idx);+ Save();+ }+ delete c;+ InvalidateRect(wnd, nullptr, FALSE);+}void AddCity(POINT scr) {HMENU m = CreatePopupMenu();+ AppendMenuW(m, MF_STRING, 9999, Tr(L"Outra Cidade…"));+ AppendMenuW(m, MF_SEPARATOR, 0, nullptr);for (int i = 0; i < NCITIES; i++) AppendMenuW(m, MF_STRING | (std::find(g_world.begin(), g_world.end(), i) != g_world.end() ? MF_CHECKED : 0), i + 1, Tr(CITIES[i].name));int c = TrackPopupMenu(m, TPM_RETURNCMD, scr.x, scr.y, 0, wnd, nullptr);DestroyMenu(m);- if (c > 0 && std::find(g_world.begin(), g_world.end(), c - 1) == g_world.end()) { g_world.push_back(c - 1); Save(); }+ if (c == 9999) { // digita o nome; Enter procura+ D2D1_SIZE_F sz = Size();+ FieldOpen(D2D1::RectF(sz.width - 300, TB + 12, sz.width - 24, TB + 36), L"", 14, false, [](const std::wstring& t, int key) { if (key == VK_RETURN) FindCity(t); });+ return;+ }+ if (c > 0 && c <= NCITIES && std::find(g_world.begin(), g_world.end(), c - 1) == g_world.end()) { g_world.push_back(c - 1); Save(); }}// hora do alarme digitada ("7:30", "0730", "19h")@@ -507,6 +615,7 @@ LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {case WM_CTLCOLOREDIT: return FieldColors((HDC)w, Dark() ? RGB(30, 30, 30) : RGB(255, 255, 255));case WM_FIELDLOST: if (field.h && GetFocus() != field.h) FieldEnd(0); return 0;case WM_TIMER: Tick(); return 0;+ case WM_CITYFOUND: CityFound((Custom*)l); return 0;case WM_LBUTTONDOWN: case WM_RBUTTONUP: {if (field.h) FieldEnd(0);float s = Sc(), x = GET_X_LPARAM(l) / s, y = GET_Y_LPARAM(l) / s;diff --git a/src/shell/apps.cpp b/src/shell/apps.cppindex 614d74e..57fe37f 100644--- a/src/shell/apps.cpp+++ b/src/shell/apps.cpp@@ -221,6 +221,8 @@ static bool IsTaskbarWindow(HWND h) {return GetWindowTextLengthW(h) > 0 || lone; // aviso sem título (Ableton): vale também}+bool apps::IsAppWindow(HWND h) { return IsTaskbarWindow(h); }+App* apps::OfWindow(HWND h) {std::wstring id = IdOfWindow(h);if (App* a = FindById(id)) return a;diff --git a/src/shell/dock.cpp b/src/shell/dock.cppindex 79cde78..8160d45 100644--- a/src/shell/dock.cpp+++ b/src/shell/dock.cpp@@ -26,6 +26,9 @@ float g_resizeTile;float g_large = 128; // tamanho máximo na ampliaçãobool g_magnify = false;bool g_autohide = false;+bool g_smart = false; // ocultação inteligente: só esconde quando uma janela encosta no Dock+bool g_covered = false; // alguma janela por cima da área do Dock agora+DWORD g_coverAt = 0;// Proporções medidas no vídeo do Sequoia (ícone de 80 px): os ícones encostam uns nos outros// (o espaço é a margem do próprio desenho), o fundo é o ícone + ~9% embaixo (onde fica o ponto),// ~4% dos lados e fica a ~10% da borda da tela; o separador ocupa meio ícone.@@ -103,6 +106,7 @@ ui::GpuSurface g_gi; // ícones: GPU (DirectComposition), quadros no rRECT g_win{}; // janela dos ícones dentro da faixa de baixo da tela (px)D2D1_RECT_F g_lastBg{};const UINT WM_DOCKFRAME = WM_APP + 40;+const UINT_PTR TIMER_HIDECHECK = 7101; // ocultação parada: olha o mouse e as janelas sem redesenharstd::vector<Item> g_items;std::map<std::wstring, ID2D1Bitmap*> g_bmps;ID2D1RenderTarget* g_bmpRt;@@ -510,6 +514,41 @@ float BounceOffset(const App& a) {return 0;}+// Ocultação inteligente: alguma janela de app (não minimizada, nesta mesa) cobre a área do Dock à mostra?+// Como a "ocultação inteligente" dos docks do Windows: janela maximizada ou arrastada até embaixo esconde o Dock.+bool WindowOverDock() {+ float sc = Sc();+ RECT mon = Monitor();+ RECT dk{ mon.left + (LONG)(g_bg.left * sc), mon.bottom - (LONG)std::lround((g_tile + PAD_TOP + PAD_BOTTOM + MARGIN) * sc),+ mon.left + (LONG)(g_bg.right * sc), mon.bottom };+ if (dk.right <= dk.left) return false;+ struct C { RECT dk; bool hit; } c{ dk, false };+ EnumWindows([](HWND h, LPARAM p) -> BOOL {+ auto* c = (C*)p;+ if (!IsWindowVisible(h) || IsIconic(h) || apps::IsShellWindow(h) || shell::Nossa(h)) return TRUE;+ LONG_PTR ex = GetWindowLongPtrW(h, GWL_EXSTYLE);+ bool app = apps::IsAppWindow(h);+ // diálogo de um app (janela com dona) também conta; menus, dicas e camadas transparentes não+ if (!app && (!GetWindow(h, GW_OWNER) || (ex & (WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_TRANSPARENT)))) return TRUE;+ if (!app) { DWORD cl = 0; DwmGetWindowAttribute(h, DWMWA_CLOAKED, &cl, sizeof(cl)); if (cl) return TRUE; }+ RECT r; if (FAILED(DwmGetWindowAttribute(h, DWMWA_EXTENDED_FRAME_BOUNDS, &r, sizeof(r)))) GetWindowRect(h, &r);+ RECT x; if (IntersectRect(&x, &r, &c->dk)) { c->hit = true; return FALSE; }+ return TRUE;+ }, (LPARAM)&c);+ return c.hit;+}++// Esconder agora? Sempre (ocultação comum) ou só com janela por cima (inteligente); o mouse na borda de baixo mostra.+bool WantHidden() {+ POINT c; GetCursorPos(&c);+ RECT mon = Monitor();+ float sc = Sc();+ bool nearEdge = c.x >= mon.left && c.x < mon.right &&+ (c.y >= mon.bottom - 2 || (g_reveal > 0.5f && c.y >= mon.bottom - (LONG)((g_bg.bottom - g_bg.top + 30) * sc)));+ if (g_smart && GetTickCount() - g_coverAt >= 100) { g_coverAt = GetTickCount(); g_covered = WindowOverDock(); }+ return (!g_smart || g_covered) && !nearEdge && g_press < 0;+}+bool Animating() {for (auto& a : apps::list) if ((a.launchedAt && GetTickCount() - a.launchedAt < 8000) || (a.attentionAt && GetTickCount() - a.attentionAt < 1800)) return true;for (auto& [id, t] : g_nudge) if (GetTickCount() - t < 640) return true;@@ -1185,7 +1224,8 @@ void BackgroundMenu() {SetForegroundWindow(g_owner);c.y -= 120;std::wstring tema = shell::Setting(L"tema", L"auto");- int id = ctxmenu::ShowItems(g_owner, c, { MI(Tr(L"Ativar Ocultação"), 1, g_autohide), MI(Tr(L"Ativar Ampliação"), 2, g_magnify), MSep(),+ int id = ctxmenu::ShowItems(g_owner, c, { MI(Tr(L"Ativar Ocultação"), 1, g_autohide && !g_smart), MI(Tr(L"Ocultação Inteligente"), 7, g_smart),+ MI(Tr(L"Ativar Ampliação"), 2, g_magnify), MSep(),MI(Tr(L"Aparência Automática"), 4, tema != L"claro" && tema != L"escuro"),MI(Tr(L"Aparência Clara"), 5, tema == L"claro"), MI(Tr(L"Aparência Escura"), 6, tema == L"escuro"), MSep(),MI(Tr(L"Ajustes do Dock…"), 3) });@@ -1195,7 +1235,12 @@ void BackgroundMenu() {menubar::ApplyTheme();return;}- if (id == 1) { g_autohide = !g_autohide; g_hidden = g_autohide; shell::ApplyWorkArea(); ui::FrameClock(g_icons, WM_DOCKFRAME, true); }+ if (id == 1 || id == 7) {+ bool smart = id == 7 ? !g_smart : false, on = id == 7 ? smart : !(g_autohide && !g_smart);+ shell::SetSetting(L"ocultar", !on ? L"0" : smart ? L"inteligente" : L"1");+ g_autohide = on; g_smart = smart; g_covered = false; g_coverAt = 0; g_hidden = false;+ shell::ApplyWorkArea(); ui::FrameClock(g_icons, WM_DOCKFRAME, true);+ }if (id == 2) g_magnify = !g_magnify;if (id == 3) shell::OpenSettings(L"dock");Paint();@@ -1430,7 +1475,14 @@ LRESULT CALLBACK IconsProc(HWND h, UINT m, WPARAM w, LPARAM l) {Paint();return 0;}- case WM_DOCKSTACK: Paint(); return 0; // as imagens da pilha de Downloads chegaram+ case WM_DOCKSTACK: Paint(); return 0;+ case WM_TIMER:+ if (w == TIMER_HIDECHECK) {+ if (!g_autohide) { KillTimer(h, TIMER_HIDECHECK); return 0; }+ if (WantHidden() != g_hidden) { KillTimer(h, TIMER_HIDECHECK); ui::FrameClock(g_icons, WM_DOCKFRAME, true); }+ return 0;+ }+ break; // as imagens da pilha de Downloads chegaramcase WM_DOCKFRAME: {double now = anim::Now();float dt = g_lastFrame ? (float)std::clamp((now - g_lastFrame) / 1000.0, 0.0, 0.05) : 0.016f;@@ -1440,16 +1492,19 @@ LRESULT CALLBACK IconsProc(HWND h, UINT m, WPARAM w, LPARAM l) {g_magAmt += (magTarget - g_magAmt) * (1 - std::exp(-dt / 0.05f));if (std::fabs(magTarget - g_magAmt) < 0.002f) g_magAmt = magTarget;if (g_autohide) { // aparece com o mouse na borda de baixo- POINT c; GetCursorPos(&c);- RECT mon = Monitor();- bool nearEdge = c.y >= mon.bottom - 2 || (g_reveal > 0.5f && c.y >= mon.bottom - (LONG)((g_bg.bottom - g_bg.top + 30) * sc));- g_hidden = !nearEdge && g_press < 0;+ g_hidden = WantHidden();g_reveal = std::clamp(g_reveal + (g_hidden ? -dt : dt) / 0.32f, 0.f, 1.f); // 0,32 s, com a curva do Mac} else g_reveal = 1;for (auto& it : g_items) if (it.kind == I_MINWIN && it.leaving && SlotFactor(it) <= 0.001f) { BuildItems(); break; } // o espaço fechou: sai da listabool anim = Animating();Paint();if (!anim && !g_autohide) ui::FrameClock(g_icons, WM_DOCKFRAME, false);+ // ocultação parada (toda escondida ou toda à mostra): sem quadro a cada atualização da tela, só uma+ // olhada a cada 100 ms no mouse e nas janelas (antes o Dock se redesenhava sem parar, pesado em GPU fraca)+ else if (!anim && g_autohide && g_reveal == (g_hidden ? 0.f : 1.f)) {+ ui::FrameClock(g_icons, WM_DOCKFRAME, false);+ SetTimer(g_icons, TIMER_HIDECHECK, 100, nullptr);+ }}return 0;}@@ -1477,7 +1532,9 @@ static void ReadSettings() {g_tile = (float)_wtof(shell::Setting(L"tamanho", L"48").c_str());g_large = (float)_wtof(shell::Setting(L"ampliacao_tamanho", L"128").c_str());g_magnify = shell::Setting(L"ampliacao", L"0") == L"1";- g_autohide = shell::Setting(L"ocultar", L"0") == L"1";+ std::wstring oc = shell::Setting(L"ocultar", L"0"); // 0, 1 (sempre) ou inteligente+ g_autohide = oc == L"1" || oc == L"inteligente";+ g_smart = oc == L"inteligente";g_tile = g_tileWant = std::clamp(g_tile, 16.f, 128.f);g_large = std::clamp(g_large, g_tile, 256.f);FitTile();@@ -1502,10 +1559,10 @@ void dock::IconsChanged() {}void dock::ReloadSettings() {- bool hide = g_autohide;+ bool hide = g_autohide, smart = g_smart;ReadSettings();if (!g_icons) return;- if (hide != g_autohide) { g_hidden = g_autohide; ui::FrameClock(g_icons, WM_DOCKFRAME, true); }+ if (hide != g_autohide || smart != g_smart) { g_hidden = false; g_covered = false; g_coverAt = 0; ui::FrameClock(g_icons, WM_DOCKFRAME, true); }g_win = {}; g_lastBg = {};BuildItems(); // a pasta Downloads pode ter entrado ou saídoPaint();diff --git a/src/shell/genio.cpp b/src/shell/genio.cppindex 008d4a1..4fcca43 100644--- a/src/shell/genio.cpp+++ b/src/shell/genio.cpp@@ -108,12 +108,21 @@ ID3D11DeviceContext* g_ctx;IDCompositionDesktopDevice* g_dev;IDCompositionTarget* g_target;IDCompositionVisual2* g_root;-IDCompositionSurface* g_surf;+// Níveis de detalhe: a foto inteira e cópias com metade, um quarto... da LARGURA (a altura fica), cada uma a+// média de 2 pixels vizinhos da anterior. Só na largura porque o funil estreita a janela muito antes de achatá-la:+// reduzir as duas direções juntas trazia, numa janela fina mas ainda alta, linhas esticadas em blocos. Na altura,+// as faixas finas (cada uma com poucas linhas) já fazem a média. O compositor só filtra 2×2 pixels: encolhendo a foto inteira até ~5% ele pulava linhas e+// colunas e o gênio ficava serrilhado e "pixelado" (Reddit, 20/11/2026). Cada nível tem as suas faixas (o de baixo,+// menor, com menos) e a de cima some quando a sua escala passa de ~0,6 para 0,5, mostrando a de baixo.+const int MAX_LEVELS = 6;+IDCompositionSurface* g_surf[MAX_LEVELS];+IDCompositionVisual2* g_level[MAX_LEVELS]; // um grupo por nível; o nível 0 (a foto inteira) por cima+int g_levels;IDCompositionEffectGroup* g_fx;HWND g_wnd, g_cap; // a camada do compositor e a janela da fotoHTHUMBNAIL g_capTh;bool g_ok, g_tried, g_active;-struct Strip { IDCompositionVisual2* v = nullptr; IDCompositionScaleTransform* sc = nullptr; };+struct Strip { IDCompositionVisual2* v = nullptr; IDCompositionScaleTransform* sc = nullptr; IDCompositionEffectGroup* fx = nullptr; int level = 0; };std::vector<Strip> g_strips;const UINT_PTR T_BACK = 1, T_END = 2, T_SETTLE = 3;@@ -143,7 +152,9 @@ bool Init(HINSTANCE hi) {g_dev->CreateEffectGroup(&g_fx);if (g_fx) g_root->SetEffect(g_fx);g_root->SetBitmapInterpolationMode(DCOMPOSITION_BITMAP_INTERPOLATION_MODE_LINEAR);- g_root->SetBorderMode(DCOMPOSITION_BORDER_MODE_HARD); // faixas encostadas sem fresta entre elas+ // borda suave: o contorno do funil sai suavizado, não em escadinha. Para não aparecer fresta entre as faixas,+ // cada uma desce 2 linhas por baixo da seguinte e fica por cima dela (Start)+ g_root->SetBorderMode(DCOMPOSITION_BORDER_MODE_SOFT);g_target->SetRoot(g_root);g_dev->Commit();g_ok = true;@@ -178,11 +189,16 @@ void HideCap() {void Clear() {for (auto& s : g_strips) {- if (s.v) { g_root->RemoveVisual(s.v); s.v->Release(); }+ if (s.v) { if (g_level[s.level]) g_level[s.level]->RemoveVisual(s.v); s.v->Release(); }if (s.sc) s.sc->Release();+ if (s.fx) s.fx->Release();}g_strips.clear();- if (g_surf) { g_surf->Release(); g_surf = nullptr; }+ for (int k = 0; k < MAX_LEVELS; k++) {+ if (g_level[k]) { g_root->RemoveVisual(g_level[k]); g_level[k]->Release(); g_level[k] = nullptr; }+ if (g_surf[k]) { g_surf[k]->Release(); g_surf[k] = nullptr; }+ }+ g_levels = 0;g_dev->Commit();HideCap();}@@ -274,14 +290,29 @@ bool Snap(HWND h, bool show, std::vector<uint32_t>& px, int& w, int& hh) {return true;}-bool Upload(const std::vector<uint32_t>& px, int w, int hh) {- if (FAILED(g_dev->CreateSurface(w, hh, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_ALPHA_MODE_PREMULTIPLIED, &g_surf))) return false;+bool Upload(const std::vector<uint32_t>& px, int w, int hh, IDCompositionSurface** out) {+ if (FAILED(g_dev->CreateSurface(w, hh, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_ALPHA_MODE_PREMULTIPLIED, out))) return false;ID3D11Texture2D* tex = nullptr; POINT off{};- if (FAILED(g_surf->BeginDraw(nullptr, IID_PPV_ARGS(&tex), &off))) return false;+ if (FAILED((*out)->BeginDraw(nullptr, IID_PPV_ARGS(&tex), &off))) return false;D3D11_BOX box{ (UINT)off.x, (UINT)off.y, 0, (UINT)(off.x + w), (UINT)(off.y + hh), 1 };g_ctx->UpdateSubresource(tex, 0, &box, px.data(), w * 4, 0);tex->Release();- return SUCCEEDED(g_surf->EndDraw());+ return SUCCEEDED((*out)->EndDraw());+}++// metade da largura: cada pixel é a média dos 2 vizinhos (cores pré-multiplicadas: a média vale para o alfa também)+void Half(const std::vector<uint32_t>& in, int w, int h, std::vector<uint32_t>& out, int& ow, int& oh) {+ ow = std::max(1, (w + 1) / 2); oh = h;+ out.assign((size_t)ow * oh, 0);+ for (int y = 0; y < oh; y++) {+ const uint32_t* row = &in[(size_t)y * w];+ uint32_t* dst = &out[(size_t)y * ow];+ for (int x = 0; x < ow; x++) {+ uint32_t a = row[2 * x], b = row[std::min(2 * x + 1, w - 1)];+ // média byte a byte sem separar os canais+ dst[x] = (a | b) - (((a ^ b) & 0xFEFEFEFEu) >> 1);+ }+ }}// true: o compositor está animando (o motor antigo não roda)@@ -291,40 +322,77 @@ bool Start(HWND h) {std::vector<uint32_t> px; int sw = 0, sh = 0;if (!Snap(h, !g_a.restore, px, sw, sh)) { Log(L"gênio (compositor): sem foto da janela; motor antigo"); return false; }double tSnap = anim::Now() - t0;- if (!Upload(px, sw, sh)) { Log(L"gênio (compositor): superfície falhou; motor antigo"); Clear(); return false; }+ // os níveis: a foto inteira e as metades, até ~16 px ou MAX_LEVELS+ std::vector<uint32_t> lv = std::move(px); int lw = sw, lh = sh;+ int dims[MAX_LEVELS][2]{};+ for (g_levels = 0; g_levels < MAX_LEVELS; g_levels++) {+ if (!Upload(lv, lw, lh, &g_surf[g_levels])) break;+ dims[g_levels][0] = lw; dims[g_levels][1] = lh;+ if (lw < 24) { g_levels++; break; }+ std::vector<uint32_t> nx; int nw, nh; Half(lv, lw, lh, nx, nw, nh);+ lv = std::move(nx); lw = nw; lh = nh;+ }+ if (!g_levels) { Log(L"gênio (compositor): superfície falhou; motor antigo"); Clear(); return false; }+ // grupos de cada nível: o de baixo (o menor) primeiro, cada um por cima do anterior+ for (int k = g_levels - 1; k >= 0; k--) {+ if (FAILED(g_dev->CreateVisual(&g_level[k]))) { Clear(); return false; }+ g_root->AddVisual(g_level[k], TRUE, k + 1 < g_levels ? g_level[k + 1] : nullptr);+ }SetWindowPos(g_wnd, HWND_TOPMOST, g_ovRect.left, g_ovRect.top, g_ovRect.right - g_ovRect.left, g_ovRect.bottom - g_ovRect.top, SWP_NOACTIVATE);const float D = DURATION;- const int K = 24, n = g_a.n;- for (int i = 0; i < n; i++) {- float v0 = (float)i / n, v1 = (float)(i + 1) / n;- float top = v0 * sh, bot = v1 * sh; // as linhas da foto desta faixa- Strip s;- if (FAILED(g_dev->CreateVisual(&s.v))) { Clear(); return false; }- s.v->SetContent(g_surf);- s.v->SetClip(D2D_RECT_F{ 0.f, top, (float)sw, bot });- std::vector<float> ox(K), oy(K), sx(K), sy(K);- for (int k = 0; k < K; k++) {- float t = (float)k / (K - 1);- float pp = g_a.restore ? 1 - anim::Ease(t) : anim::Ease(t);- float L, R, ya, yb; StripAt(pp, v0, v1, L, R, ya, yb);- sx[k] = std::max(0.f, (R - L) / sw);- sy[k] = std::max(0.f, (yb - ya) / (bot - top));- ox[k] = L - g_ovRect.left;- oy[k] = ya - g_ovRect.top - top * sy[k]; // a linha `top` da foto cai em ya- }- g_dev->CreateScaleTransform(&s.sc);- IDCompositionAnimation *ax = Curve(ox, D), *ay = Curve(oy, D), *asx = Curve(sx, D), *asy = Curve(sy, D);- if (ax) { s.v->SetOffsetX(ax); ax->Release(); }- if (ay) { s.v->SetOffsetY(ay); ay->Release(); }- if (s.sc) {- s.sc->SetCenterX(0.f); s.sc->SetCenterY(0.f);- if (asx) { s.sc->SetScaleX(asx); asx->Release(); }- if (asy) { s.sc->SetScaleY(asy); asy->Release(); }- s.v->SetTransform(s.sc);+ const int K = 32;+ // faixas finas (~3 px de janela) no nível 0: a curva do funil sem degraus; cada nível menor tem a metade+ const int n0 = std::clamp((int)((g_a.win.bottom - g_a.win.top) / 3), 24, 200);+ int total = 0;+ for (int lvl = 0; lvl < g_levels; lvl++) {+ const int n = lvl == 0 ? n0 : std::max(12, n0 / 2); // os níveis estreitos aparecem com a janela já fina+ IDCompositionVisual2* prev = nullptr; // cada faixa entra por baixo da anterior (a de cima cobre a emenda)+ const float lw2 = (float)dims[lvl][0], lh2 = (float)dims[lvl][1];+ const float mult = (float)(1 << lvl); // escala da foto inteira -> escala deste nível+ for (int i = 0; i < n; i++) {+ float v0 = (float)i / n, v1 = (float)(i + 1) / n;+ float top = v0 * lh2, bot = v1 * lh2; // as linhas da foto (deste nível) desta faixa+ Strip st; st.level = lvl;+ if (FAILED(g_dev->CreateVisual(&st.v))) { Clear(); return false; }+ st.v->SetContent(g_surf[lvl]);+ st.v->SetClip(D2D_RECT_F{ 0.f, top, lw2, i + 1 < n ? std::min(lh2, bot + 2.f) : bot }); // 2 linhas por baixo da seguinte+ std::vector<float> ox(K), oy(K), sx(K), sy(K), op(K);+ bool fades = false;+ for (int k = 0; k < K; k++) {+ float t = (float)k / (K - 1);+ float pp = g_a.restore ? 1 - anim::Ease(t) : anim::Ease(t);+ float L, R, ya, yb; StripAt(pp, v0, v1, L, R, ya, yb);+ sx[k] = std::max(0.f, (R - L) / lw2);+ sy[k] = std::max(0.f, (yb - ya) / (bot - top));+ ox[k] = L - g_ovRect.left;+ oy[k] = ya - g_ovRect.top - top * sy[k]; // a linha `top` da foto cai em ya+ // escala deste nível na tela: abaixo de ~0,5 o filtro do compositor pula pixels; o nível menor assume+ float m = sx[k]; // os níveis só reduzem a largura+ op[k] = lvl + 1 < g_levels ? Smooth(0.5f, 0.65f, m) : 1.f;+ if (op[k] < 0.999f) fades = true;+ (void)mult;+ }+ g_dev->CreateScaleTransform(&st.sc);+ IDCompositionAnimation *ax = Curve(ox, D), *ay = Curve(oy, D), *asx = Curve(sx, D), *asy = Curve(sy, D);+ if (ax) { st.v->SetOffsetX(ax); ax->Release(); }+ if (ay) { st.v->SetOffsetY(ay); ay->Release(); }+ if (st.sc) {+ st.sc->SetCenterX(0.f); st.sc->SetCenterY(0.f);+ if (asx) { st.sc->SetScaleX(asx); asx->Release(); }+ if (asy) { st.sc->SetScaleY(asy); asy->Release(); }+ st.v->SetTransform(st.sc);+ }+ if (fades && SUCCEEDED(g_dev->CreateEffectGroup(&st.fx)) && st.fx) {+ if (IDCompositionAnimation* ao = Curve(op, D)) { st.fx->SetOpacity(ao); ao->Release(); }+ st.v->SetEffect(st.fx);+ }+ g_level[lvl]->AddVisual(st.v, FALSE, prev);+ prev = st.v;+ g_strips.push_back(st);+ total++;}- g_root->AddVisual(s.v, TRUE, nullptr);- g_strips.push_back(s);}+ const int n = total;if (g_fx) { // some de leve ao entrar no Dock (igual ao motor antigo)std::vector<float> op(K);for (int k = 0; k < K; k++) {@@ -342,7 +410,7 @@ bool Start(HWND h) {UINT ms = (UINT)std::lround(D * 1000);if (g_a.restore) SetTimer(g_wnd, T_BACK, (UINT)(ms * 0.4f), nullptr);SetTimer(g_wnd, T_END, ms + 20, nullptr);- Log(L"gênio (compositor): %d faixas, foto %dx%d em %.1f ms, preparo %.1f ms; o resto é com o DWM", n, sw, sh, tSnap, anim::Now() - t0);+ Log(L"gênio (compositor): %d faixas em %d níveis, foto %dx%d em %.1f ms, preparo %.1f ms; o resto é com o DWM", n, g_levels, sw, sh, tSnap, anim::Now() - t0);dock::Update();return true;}diff --git a/src/shell/shell.h b/src/shell/shell.hindex 8d20d9b..1f5bf7c 100644--- a/src/shell/shell.h+++ b/src/shell/shell.h@@ -181,6 +181,7 @@ void ForgetRecent(const std::wstring& id); // tira um app da seção de recentebool 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 appstd::wstring PackIconByName(const std::wstring& name, const std::wstring& exe = L""); // ícone do pacote do Sequoiadiff --git a/src/shell/widgets.cpp b/src/shell/widgets.cppindex b840e36..2fa6a2a 100644--- a/src/shell/widgets.cpp+++ b/src/shell/widgets.cpp@@ -1,1043 +1,1045 @@-// Widgets da mesa, como no macOS Sequoia: Relógio Mundial, Tempo, Relógio, Calendário e Nascer do Sol.-// Ficam logo acima da área de trabalho (abaixo de todas as janelas), arrastáveis; posições em ajustes.txt.-// Medidas da referência (Sequoia, 0,72 px por pt): pequeno 170 × 170 pt, médio 364 × 170 pt, 16 pt entre-// eles, canto de 21 pt. Claro: as cores de cada widget (Tempo em degradê do céu, Calendário branco, Relógio-// Mundial preto, Relógio em vidro). Escuro: todos em vidro desfocado da mesa, com texto e símbolos brancos.-// O tempo vem do Open-Meteo (sem chave), a cada 15 min, para a cidade em ajustes.txt (padrão: Campinas - SP);-// a última resposta fica em %APPDATA%\Shell\tempo.json para aparecer já ao ligar.-#include "shell.h"-#include "../menu/context_menu.h"-#include <dwmapi.h>-#include <shellapi.h>-#include <shlobj.h>-#include <winhttp.h>-#include <algorithm>-#include <cmath>-#include <ctime>-#include <map>-#include <mutex>-#include <thread>-#include <atomic>-#include "../comum/idioma.h"-#pragma comment(lib, "winhttp.lib")--namespace {--const float SMALL = 170, MEDIUM = 356, GAP = 16, RADIUS_SEQ = 21, MARGIN = 16;-inline float WidgetRadius() { return liquid::On() ? 26.f : RADIUS_SEQ; } // Tahoe: mais redondos-const UINT WM_WX_READY = WM_APP + 60;-const float PI = 3.14159265f;--enum Kind { K_WORLD, K_WEATHER, K_CLOCK, K_CALENDAR, K_SUN };-struct Widget {- Kind kind; const wchar_t* id; const wchar_t* name; float w, h;- HWND wnd = nullptr, back = nullptr;- bool glass = false, on = true;- int rc = -1, row = -1; // casa na grade (rc: coluna da borda direita, contando da direita)- ui::GpuSurface s;-};-std::vector<Widget> g_w;-HWND g_menuOwner; // dono invisível do menu de contexto (o menu precisa de um dono em primeiro plano)-HWND g_ghost; // sombra da casa de destino ao arrastar-HWND g_timer; // janela que recebe os relógios e a chegada do tempo-bool g_dark, g_placing;-int g_lastMinute = -1;--// arrastar-Widget* g_drag; POINT g_dragStart, g_winStart; bool g_dragging;--// ---------------------------------------------------------------- tempo (Open-Meteo)-struct Hour { double t; float temp; int code; bool day; };-struct Weather {- bool ok = false;- float temp = 0; int code = 0; bool day = true;- float hi = 0, lo = 0;- double sunrise[2]{}, sunset[2]{};- int utcOffset = -3 * 3600;- std::vector<Hour> hours;-};-std::mutex g_mx;-Weather g_wx;-std::atomic<bool> g_fetching{ false };--std::wstring City() { return shell::Setting(L"tempoCidade", L"Campinas"); }--std::string Section(const std::string& j, const char* key) {- size_t p = j.find(std::string("\"") + key + "\":{");- if (p == std::string::npos) return "";- p = j.find('{', p);- int depth = 0;- for (size_t i = p; i < j.size(); i++) {- if (j[i] == '{') depth++;- else if (j[i] == '}' && --depth == 0) return j.substr(p, i - p + 1);- }- return "";-}-double Number(const std::string& s, const char* key) {- size_t p = s.find(std::string("\"") + key + "\":");- if (p == std::string::npos) return NAN;- p += strlen(key) + 3;- while (p < s.size() && s[p] == ' ') p++;- if (s.compare(p, 4, "null") == 0) return NAN;- return strtod(s.c_str() + p, nullptr);-}-std::vector<double> Array(const std::string& s, const char* key) {- std::vector<double> v;- size_t p = s.find(std::string("\"") + key + "\":[");- if (p == std::string::npos) return v;- p = s.find('[', p) + 1;- while (p < s.size() && s[p] != ']') {- while (p < s.size() && (s[p] == ' ' || s[p] == ',')) p++;- if (s[p] == ']') break;- if (s.compare(p, 4, "null") == 0) { v.push_back(NAN); p += 4; continue; }- char* e = nullptr;- v.push_back(strtod(s.c_str() + p, &e));- if (e == s.c_str() + p) break;- p = e - s.c_str();- }- return v;-}--bool Parse(const std::string& j, Weather& w) {- std::string cur = Section(j, "current"), hr = Section(j, "hourly"), dl = Section(j, "daily");- if (cur.empty() || hr.empty() || dl.empty()) return false;- double off = Number(j, "utc_offset_seconds");- if (!std::isnan(off)) w.utcOffset = (int)off;- w.temp = (float)Number(cur, "temperature_2m");- w.code = (int)Number(cur, "weather_code");- w.day = Number(cur, "is_day") > 0.5;- auto t = Array(hr, "time"), tp = Array(hr, "temperature_2m"), c = Array(hr, "weather_code"), d = Array(hr, "is_day");- w.hours.clear();- for (size_t i = 0; i < t.size() && i < tp.size() && i < c.size() && i < d.size(); i++)- w.hours.push_back({ t[i], (float)tp[i], (int)c[i], d[i] > 0.5 });- auto mx = Array(dl, "temperature_2m_max"), mn = Array(dl, "temperature_2m_min"), sr = Array(dl, "sunrise"), ss = Array(dl, "sunset");- if (mx.empty() || mn.empty() || sr.size() < 2 || ss.size() < 2 || std::isnan(w.temp)) return false;- w.hi = (float)mx[0]; w.lo = (float)mn[0];- for (int i = 0; i < 2; i++) { w.sunrise[i] = sr[i]; w.sunset[i] = ss[i]; }- w.ok = true;- return true;-}--std::wstring CachePath() {- PWSTR p = nullptr; std::wstring f;- if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) { f = std::wstring(p) + L"\\Shell\\tempo.json"; CoTaskMemFree(p); }- return f;-}--std::string HttpGet(const wchar_t* host, const std::wstring& path) {- std::string body;- HINTERNET ses = WinHttpOpen(L"ShellProprio/1.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);- if (!ses) return body;- WinHttpSetTimeouts(ses, 5000, 5000, 8000, 8000);- HINTERNET con = WinHttpConnect(ses, host, INTERNET_DEFAULT_HTTPS_PORT, 0);- HINTERNET req = con ? WinHttpOpenRequest(con, L"GET", path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : nullptr;- if (req && WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) && WinHttpReceiveResponse(req, nullptr)) {- DWORD status = 0, sz = sizeof(status);- WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, nullptr, &status, &sz, nullptr);- DWORD avail = 0;- while (WinHttpQueryDataAvailable(req, &avail) && avail && body.size() < 256 * 1024) {- std::string chunk(avail, '\0'); DWORD got = 0;- if (!WinHttpReadData(req, chunk.data(), avail, &got) || !got) break;- body.append(chunk.data(), got);- }- if (status != 200) body.clear();- }- if (req) WinHttpCloseHandle(req);- if (con) WinHttpCloseHandle(con);- WinHttpCloseHandle(ses);- return body;-}--void Fetch() {- if (g_fetching.exchange(true)) return;- std::wstring lat = shell::Setting(L"tempoLat", L"-22.9056"), lon = shell::Setting(L"tempoLon", L"-47.0608");- std::thread([lat, lon] {- std::wstring path = L"/v1/forecast?latitude=" + lat + L"&longitude=" + lon +- L"¤t=temperature_2m,weather_code,is_day&hourly=temperature_2m,weather_code,is_day"- L"&daily=temperature_2m_max,temperature_2m_min,sunrise,sunset&timezone=auto&forecast_days=3&timeformat=unixtime";- std::string body = HttpGet(L"api.open-meteo.com", path);- Weather w;- if (!body.empty() && Parse(body, w)) {- { std::lock_guard<std::mutex> lk(g_mx); g_wx = w; }- FILE* fp = nullptr;- if (!_wfopen_s(&fp, CachePath().c_str(), L"wb") && fp) { fwrite(body.data(), 1, body.size(), fp); fclose(fp); }- Log(L"widgets: tempo atualizado (%.1f°, código %d)", w.temp, w.code);- PostMessageW(g_timer, WM_WX_READY, 0, 0);- } else Log(L"widgets: não deu para buscar o tempo (%zu bytes)", body.size());- g_fetching = false;- }).detach();-}--void LoadCache() {- FILE* fp = nullptr;- if (_wfopen_s(&fp, CachePath().c_str(), L"rb") || !fp) return;- std::string body; char buf[8192]; size_t n;- while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) body.append(buf, n);- fclose(fp);- Weather w;- if (Parse(body, w)) { std::lock_guard<std::mutex> lk(g_mx); g_wx = w; }-}--enum Icon { I_SUN, I_MOON, I_PARTLY, I_PARTLY_NIGHT, I_CLOUD, I_FOG, I_DRIZZLE, I_RAIN, I_SNOW, I_THUNDER };-Icon IconOf(int code, bool day) {- if (code == 0) return day ? I_SUN : I_MOON;- if (code <= 2) return day ? I_PARTLY : I_PARTLY_NIGHT;- if (code == 3) return I_CLOUD;- if (code == 45 || code == 48) return I_FOG;- if (code >= 51 && code <= 57) return I_DRIZZLE;- if ((code >= 61 && code <= 67) || (code >= 80 && code <= 82)) return I_RAIN;- if ((code >= 71 && code <= 77) || code == 85 || code == 86) return I_SNOW;- if (code >= 95) return I_THUNDER;- return I_CLOUD;-}-const wchar_t* ConditionOf(int code, bool day) {- if (code == 0) return day ? Tr(L"Ensolarado") : Tr(L"Céu Limpo");- if (code == 1) return day ? Tr(L"Predom. Ensolarado") : Tr(L"Predom. Limpo");- if (code == 2) return Tr(L"Parcialmente Nublado");- if (code == 3) return Tr(L"Nublado");- if (code == 45 || code == 48) return Tr(L"Neblina");- if (code >= 51 && code <= 57) return Tr(L"Garoa");- if (code == 65 || code == 82) return Tr(L"Chuva Forte");- if (code == 66 || code == 67) return Tr(L"Chuva Congelada");- if ((code >= 61 && code <= 63) || code == 80 || code == 81) return Tr(L"Chuva");- if ((code >= 71 && code <= 77) || code == 85 || code == 86) return Tr(L"Neve");- if (code >= 95) return Tr(L"Tempestades");- return Tr(L"Nublado");-}--// hora local da cidade do tempo, a partir de um instante unix-int LocalMinuteOfDay(double t, int off) { long long s = (long long)t + off; s %= 86400; if (s < 0) s += 86400; return (int)(s / 60); }-std::wstring HourMin(double t, int off) { int m = LocalMinuteOfDay(t, off); wchar_t b[16]; swprintf_s(b, L"%02d:%02d", m / 60, m % 60); return b; }--// ---------------------------------------------------------------- desenho-D2D1_COLOR_F C(float r, float g, float b, float a = 1) { return D2D1::ColorF(r, g, b, a); }-const D2D1_COLOR_F WHITE = { 1, 1, 1, 1 }, ORANGE = { 1, 0.584f, 0, 1 }, RED = { 1, 0.231f, 0.188f, 1 };--void Txt(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, const std::wstring& s, float size, DWRITE_FONT_WEIGHT wgt,- DWRITE_TEXT_ALIGNMENT al, D2D1_RECT_F r, D2D1_COLOR_F c, bool display = false) {- IDWriteTextFormat* tf = nullptr;- if (FAILED(ui::dw->CreateTextFormat(display ? L"SF Pro Display" : ui::family.c_str(), nullptr, wgt, DWRITE_FONT_STYLE_NORMAL,- DWRITE_FONT_STRETCH_NORMAL, size, L"pt-br", &tf)) || !tf) return;- tf->SetTextAlignment(al);- tf->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);- tf->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);- br->SetColor(c);- dc->DrawText(s.c_str(), (UINT32)s.size(), tf, r, br, D2D1_DRAW_TEXT_OPTIONS_NONE);- tf->Release();-}-float Width(const std::wstring& s, float size, DWRITE_FONT_WEIGHT wgt, bool display = false) {- IDWriteTextFormat* tf = nullptr;- if (FAILED(ui::dw->CreateTextFormat(display ? L"SF Pro Display" : ui::family.c_str(), nullptr, wgt, DWRITE_FONT_STYLE_NORMAL,- DWRITE_FONT_STRETCH_NORMAL, size, L"pt-br", &tf)) || !tf) return 0;- float w = ui::TextWidth(tf, s);- tf->Release();- return w;-}--ID2D1StrokeStyle* RoundCaps(ID2D1DeviceContext* dc) {- ID2D1Factory* f = nullptr; dc->GetFactory(&f);- ID2D1StrokeStyle* st = nullptr;- if (f) { f->CreateStrokeStyle(D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND), nullptr, 0, &st); f->Release(); }- return st;-}--ID2D1Geometry* Combine(ID2D1Factory* f, ID2D1Geometry* a, ID2D1Geometry* b, D2D1_COMBINE_MODE mode) {- ID2D1PathGeometry* p = nullptr;- if (a && b && SUCCEEDED(f->CreatePathGeometry(&p))) {- ID2D1GeometrySink* s = nullptr;- if (SUCCEEDED(p->Open(&s))) { a->CombineWithGeometry(b, mode, nullptr, s); s->Close(); s->Release(); }- }- if (a) a->Release();- if (b) b->Release();- return p;-}-ID2D1Geometry* Circle(ID2D1Factory* f, float x, float y, float r) {- ID2D1EllipseGeometry* e = nullptr; f->CreateEllipseGeometry(D2D1::Ellipse({ x, y }, r, r), &e); return e;-}-// nuvem do SF Symbols: três bolhas sobre uma base arredondada (s = tamanho do símbolo)-ID2D1Geometry* Cloud(ID2D1Factory* f, float cx, float cy, float s) {- ID2D1RoundedRectangleGeometry* rr = nullptr;- f->CreateRoundedRectangleGeometry(D2D1::RoundedRect(D2D1::RectF(cx - 0.40f * s, cy + 0.02f * s, cx + 0.44f * s, cy + 0.25f * s), 0.115f * s, 0.115f * s), &rr);- ID2D1Geometry* g = Combine(f, Circle(f, cx - 0.19f * s, cy + 0.05f * s, 0.20f * s), Circle(f, cx + 0.04f * s, cy - 0.06f * s, 0.27f * s), D2D1_COMBINE_MODE_UNION);- g = Combine(f, g, Circle(f, cx + 0.26f * s, cy + 0.08f * s, 0.17f * s), D2D1_COMBINE_MODE_UNION);- return Combine(f, g, rr, D2D1_COMBINE_MODE_UNION);-}-ID2D1Geometry* Moon(ID2D1Factory* f, float cx, float cy, float s) {- return Combine(f, Circle(f, cx, cy, 0.32f * s), Circle(f, cx + 0.19f * s, cy - 0.13f * s, 0.27f * s), D2D1_COMBINE_MODE_EXCLUDE);-}--void Sun(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, ID2D1StrokeStyle* st, float cx, float cy, float s, D2D1_COLOR_F c) {- br->SetColor(c);- dc->FillEllipse(D2D1::Ellipse({ cx, cy }, 0.2f * s, 0.2f * s), br);- for (int i = 0; i < 8; i++) {- float a = i * PI / 4, dx = std::sin(a), dy = -std::cos(a);- dc->DrawLine({ cx + dx * 0.31f * s, cy + dy * 0.31f * s }, { cx + dx * 0.44f * s, cy + dy * 0.44f * s }, br, 0.075f * s, st);- }-}--// símbolos do tempo no estilo multicolorido do SF Symbols (mono: tudo branco, para o vidro do modo escuro)-void DrawIcon(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, Icon ic, float cx, float cy, float s, bool mono) {- ID2D1Factory* f = nullptr; dc->GetFactory(&f);- if (!f) return;- ID2D1StrokeStyle* st = RoundCaps(dc);- D2D1_COLOR_F yellow = mono ? WHITE : C(1, 0.84f, 0.04f), drop = mono ? WHITE : C(0.39f, 0.78f, 1), cloud = WHITE;- auto fill = [&](ID2D1Geometry* g, D2D1_COLOR_F c) { if (g) { br->SetColor(c); dc->FillGeometry(g, br); g->Release(); } };- float ccy = cy - 0.12f * s; // nuvem mais alta quando tem algo caindo embaixo- switch (ic) {- case I_SUN: Sun(dc, br, st, cx, cy, s, yellow); break;- case I_MOON: fill(Moon(f, cx, cy, s), WHITE); break;- case I_PARTLY:- Sun(dc, br, st, cx - 0.14f * s, cy - 0.14f * s, 0.78f * s, yellow);- fill(Cloud(f, cx + 0.08f * s, cy + 0.06f * s, 0.82f * s), cloud);- break;- case I_PARTLY_NIGHT:- fill(Moon(f, cx - 0.14f * s, cy - 0.16f * s, 0.72f * s), WHITE);- fill(Cloud(f, cx + 0.08f * s, cy + 0.06f * s, 0.82f * s), cloud);- break;- case I_CLOUD: fill(Cloud(f, cx, cy, s), cloud); break;- case I_FOG:- fill(Cloud(f, cx, cy - 0.1f * s, 0.88f * s), cloud);- br->SetColor(C(1, 1, 1, mono ? 1 : 0.85f));- dc->DrawLine({ cx - 0.36f * s, cy + 0.28f * s }, { cx + 0.36f * s, cy + 0.28f * s }, br, 0.07f * s, st);- dc->DrawLine({ cx - 0.26f * s, cy + 0.40f * s }, { cx + 0.30f * s, cy + 0.40f * s }, br, 0.07f * s, st);- break;- case I_DRIZZLE: case I_RAIN: case I_SNOW: case I_THUNDER: {- fill(Cloud(f, cx, ccy, 0.92f * s), cloud);- br->SetColor(ic == I_SNOW ? WHITE : drop);- if (ic == I_THUNDER) {- ID2D1PathGeometry* p = nullptr;- if (SUCCEEDED(f->CreatePathGeometry(&p))) {- ID2D1GeometrySink* sk = nullptr; p->Open(&sk);- D2D1_POINT_2F pts[] = { { cx + 0.02f * s, cy + 0.12f * s }, { cx - 0.12f * s, cy + 0.33f * s }, { cx - 0.01f * s, cy + 0.33f * s },- { cx - 0.06f * s, cy + 0.50f * s }, { cx + 0.12f * s, cy + 0.26f * s }, { cx + 0.01f * s, cy + 0.26f * s } };- sk->BeginFigure(pts[0], D2D1_FIGURE_BEGIN_FILLED); sk->AddLines(pts + 1, 5); sk->EndFigure(D2D1_FIGURE_END_CLOSED);- sk->Close(); sk->Release();- br->SetColor(yellow); dc->FillGeometry(p, br); p->Release();- }- break;- }- for (int i = -1; i <= 1; i++) {- float x = cx + i * 0.19f * s, y = cy + 0.22f * s;- if (ic == I_RAIN) dc->DrawLine({ x + 0.04f * s, y }, { x - 0.04f * s, y + 0.2f * s }, br, 0.075f * s, st);- else if (ic == I_DRIZZLE) { dc->FillEllipse(D2D1::Ellipse({ x, y + 0.06f * s }, 0.045f * s, 0.045f * s), br); dc->FillEllipse(D2D1::Ellipse({ x - 0.04f * s, y + 0.2f * s }, 0.045f * s, 0.045f * s), br); }- else dc->FillEllipse(D2D1::Ellipse({ x, y + 0.12f * s + (i == 0 ? 0.06f * s : 0) }, 0.06f * s, 0.06f * s), br);- }- break;- }- }- if (st) st->Release();- f->Release();-}--ID2D1LinearGradientBrush* Gradient(ID2D1DeviceContext* dc, float y0, float y1, D2D1_COLOR_F a, D2D1_COLOR_F b) {- D2D1_GRADIENT_STOP stops[] = { { 0, a }, { 1, b } };- ID2D1GradientStopCollection* sc = nullptr; ID2D1LinearGradientBrush* lb = nullptr;- dc->CreateGradientStopCollection(stops, 2, &sc);- if (sc) { dc->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, y0 }, { 0, y1 }), sc, &lb); sc->Release(); }- return lb;-}-// céu do app Tempo: azul de dia, noite escura, cinza com nuvem ou chuva-void Sky(ID2D1DeviceContext* dc, float w, float h, int code, bool day) {- D2D1_COLOR_F a, b;- bool rain = code >= 51, cloudy = code == 3 || code == 45 || code == 48;- if (day) {- if (rain) { a = C(0.29f, 0.35f, 0.43f); b = C(0.45f, 0.51f, 0.59f); }- else if (cloudy) { a = C(0.40f, 0.49f, 0.60f); b = C(0.58f, 0.66f, 0.75f); }- else { a = C(0.16f, 0.40f, 0.74f); b = C(0.36f, 0.60f, 0.88f); }- } else {- if (rain || cloudy) { a = C(0.12f, 0.14f, 0.19f); b = C(0.24f, 0.27f, 0.33f); }- else { a = C(0.03f, 0.06f, 0.16f); b = C(0.12f, 0.19f, 0.35f); }- }- if (auto* lb = Gradient(dc, 0, h, a, b)) { dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(0, 0, w, h), WidgetRadius(), WidgetRadius()), lb); lb->Release(); }-}--// mostrador analógico (relógio e relógio mundial)-// Tahoe, "Estilo de ícones e widgets" Transparente ou Tingido (macOS 26): o widget vira vidro claro e tudo por cima-// fica branco — os mostradores também (anel translúcido, ponteiros e números brancos)-bool g_vidroWidgets;-void Face(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, ID2D1StrokeStyle* st, float cx, float cy, float R,- D2D1_COLOR_F face, D2D1_COLOR_F ink, float numSize, bool ticks, const SYSTEMTIME& t) {- if (g_vidroWidgets) { face = C(1, 1, 1, 0.14f); ink = WHITE; }- br->SetColor(face);- dc->FillEllipse(D2D1::Ellipse({ cx, cy }, R, R), br);- if (ticks) {- D2D1_COLOR_F tc = ink; tc.a *= 0.35f; br->SetColor(tc);- for (int i = 0; i < 60; i++) {- if (i % 5 == 0) continue;- float a = i * PI / 30, dx = std::sin(a), dy = -std::cos(a);- dc->DrawLine({ cx + dx * R * 0.93f, cy + dy * R * 0.93f }, { cx + dx * R * 0.97f, cy + dy * R * 0.97f }, br, std::max(0.8f, R * 0.012f));- }- }- float nr = R * (ticks ? 0.79f : 0.74f);- for (int i = 1; i <= 12; i++) {- float a = i * PI / 6, x = cx + std::sin(a) * nr, y = cy - std::cos(a) * nr;- Txt(dc, br, std::to_wstring(i), numSize, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER,- D2D1::RectF(x - numSize, y - numSize * 0.75f, x + numSize, y + numSize * 0.75f), ink);- }- float sec = t.wSecond + t.wMilliseconds / 1000.f;- float mn = t.wMinute + sec / 60, hr = (t.wHour % 12) + mn / 60;- auto hand = [&](float frac, float from, float to, float width) {- float a = frac * 2 * PI, dx = std::sin(a), dy = -std::cos(a);- dc->DrawLine({ cx + dx * from, cy + dy * from }, { cx + dx * to, cy + dy * to }, br, width, st);- };- br->SetColor(ink);- hand(hr / 12, 0, R * 0.14f, std::max(1.2f, R * 0.028f));- hand(hr / 12, R * 0.14f, R * 0.50f, R * 0.075f);- hand(mn / 60, 0, R * 0.14f, std::max(1.2f, R * 0.028f));- hand(mn / 60, R * 0.14f, R * 0.84f, R * 0.075f);- dc->FillEllipse(D2D1::Ellipse({ cx, cy }, R * 0.06f, R * 0.06f), br);- br->SetColor(ORANGE);- hand(sec / 60, -R * 0.16f, R * 0.90f, std::max(1.f, R * 0.018f));- dc->FillEllipse(D2D1::Ellipse({ cx, cy }, R * 0.045f, R * 0.045f), br);- br->SetColor(face);- dc->FillEllipse(D2D1::Ellipse({ cx, cy }, R * 0.017f, R * 0.017f), br);-}--// ---------------------------------------------------------------- relógio mundial-struct CityTz { std::wstring name, tz; };-std::vector<CityTz> Cities() {- // ajustes.txt: relogioCidades=Cupertino|Pacific Standard Time;Tóquio|Tokyo Standard Time;...- std::wstring s = shell::Setting(L"relogioCidades",- L"Cupertino|Pacific Standard Time;Tóquio|Tokyo Standard Time;Sydney|AUS Eastern Standard Time;Paris|Romance Standard Time");- std::vector<CityTz> v;- size_t p = 0;- while (p < s.size() && v.size() < 4) {- size_t e = s.find(L';', p); if (e == std::wstring::npos) e = s.size();- std::wstring item = s.substr(p, e - p);- size_t bar = item.find(L'|');- if (bar != std::wstring::npos) v.push_back({ item.substr(0, bar), item.substr(bar + 1) });- p = e + 1;- }- return v;-}-bool TimeIn(const std::wstring& key, const SYSTEMTIME& utc, SYSTEMTIME& out) {- static std::map<std::wstring, DYNAMIC_TIME_ZONE_INFORMATION> cache;- auto it = cache.find(key);- if (it == cache.end()) {- DYNAMIC_TIME_ZONE_INFORMATION d{};- for (DWORD i = 0; EnumDynamicTimeZoneInformation(i, &d) == ERROR_SUCCESS; i++)- if (!_wcsicmp(d.TimeZoneKeyName, key.c_str())) { it = cache.emplace(key, d).first; break; }- if (it == cache.end()) return false;- }- return SystemTimeToTzSpecificLocalTimeEx(&it->second, &utc, &out) != FALSE;-}-long long Minutes(const SYSTEMTIME& t) { FILETIME f; SystemTimeToFileTime(&t, &f); return (long long)(((ULONGLONG)f.dwHighDateTime << 32 | f.dwLowDateTime) / 600000000ULL); }--void PaintWorld(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, ID2D1StrokeStyle* st, float w, float h, bool dark) {- if (!dark) { br->SetColor(C(0.11f, 0.11f, 0.118f)); dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(0, 0, w, h), WidgetRadius(), WidgetRadius()), br); }- SYSTEMTIME utc, local; GetSystemTime(&utc); GetLocalTime(&local);- long long lm = Minutes(local);- auto cities = Cities();- float col = w / 4;- for (size_t i = 0; i < cities.size(); i++) {- SYSTEMTIME t;- if (!TimeIn(cities[i].tz, utc, t)) continue;- t.wMilliseconds = local.wMilliseconds;- float cx = col * (i + 0.5f);- bool night = t.wHour < 6 || t.wHour >= 18;- D2D1_COLOR_F face, ink;- if (dark) { face = night ? C(0, 0, 0, 0.30f) : C(1, 1, 1, 0.88f); ink = night ? WHITE : C(0, 0, 0); }- else { face = night ? C(0.23f, 0.23f, 0.24f) : WHITE; ink = night ? WHITE : C(0, 0, 0); }- Face(dc, br, st, cx, 60, 33, face, ink, 8.5f, false, t);- Txt(dc, br, Tr(cities[i].name), 12.5f, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(cx - col / 2, 99, cx + col / 2, 117), WHITE);- long long diff = Minutes(t) - lm; // em minutos- int dayDiff = (int)((t.wYear * 10000 + t.wMonth * 100 + t.wDay) > (local.wYear * 10000 + local.wMonth * 100 + local.wDay)) -- (int)((t.wYear * 10000 + t.wMonth * 100 + t.wDay) < (local.wYear * 10000 + local.wMonth * 100 + local.wDay));- D2D1_COLOR_F sub = C(1, 1, 1, 0.55f);- Txt(dc, br, dayDiff > 0 ? Tr(L"Amanhã") : dayDiff < 0 ? Tr(L"Ontem") : Tr(L"Hoje"), 10, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_TEXT_ALIGNMENT_CENTER,- D2D1::RectF(cx - col / 2, 117, cx + col / 2, 132), sub);- long long ad = diff < 0 ? -diff : diff;- wchar_t b[24];- if (ad % 60) swprintf_s(b, L"%ls%lld:%02lld H", diff < 0 ? L"−" : L"+", ad / 60, ad % 60);- else swprintf_s(b, L"%ls%lld H", diff < 0 ? L"−" : L"+", ad / 60);- Txt(dc, br, b, 10, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(cx - col / 2, 131, cx + col / 2, 146), sub);- }-}--// ---------------------------------------------------------------- tempo-void PaintWeather(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, float w, float h, bool dark) {- Weather wx; { std::lock_guard<std::mutex> lk(g_mx); wx = g_wx; }- if (!dark) Sky(dc, w, h, wx.ok ? wx.code : 0, wx.ok ? wx.day : true);- std::wstring city = City();- Txt(dc, br, city, 15, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING, D2D1::RectF(17, 12, 250, 32), WHITE);- { // seta de localização (location.fill)- float x = 17 + Width(city, 15, DWRITE_FONT_WEIGHT_SEMI_BOLD) + 5, y = 22;- ID2D1Factory* f = nullptr; dc->GetFactory(&f);- ID2D1PathGeometry* p = nullptr;- if (f && SUCCEEDED(f->CreatePathGeometry(&p))) {- ID2D1GeometrySink* sk = nullptr; p->Open(&sk);- D2D1_POINT_2F pts[] = { { x + 9, y - 5 }, { x + 5, y + 5 }, { x + 4, y + 1 }, { x, y } };- sk->BeginFigure(pts[0], D2D1_FIGURE_BEGIN_FILLED); sk->AddLines(pts + 1, 3); sk->EndFigure(D2D1_FIGURE_END_CLOSED);- sk->Close(); sk->Release();- br->SetColor(WHITE); dc->FillGeometry(p, br); p->Release();- }- if (f) f->Release();- }- wchar_t b[64];- if (wx.ok) swprintf_s(b, L"%ld°", lround(wx.temp)); else wcscpy_s(b, L"--°");- Txt(dc, br, b, 44, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING, D2D1::RectF(14, 32, 200, 86), WHITE, true);- if (!wx.ok) {- Txt(dc, br, Tr(L"Buscando o tempo…"), 13, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(0, 110, w, 140), C(1, 1, 1, 0.7f));- return;- }- DrawIcon(dc, br, IconOf(wx.code, wx.day), w - 26, 24, 22, dark);- Txt(dc, br, ConditionOf(wx.code, wx.day), 13, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_TRAILING, D2D1::RectF(120, 38, w - 17, 56), WHITE);- swprintf_s(b, Tr(L"Máx.: %ld° Mín.: %ld°"), lround(wx.hi), lround(wx.lo));- Txt(dc, br, b, 13, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_TRAILING, D2D1::RectF(120, 57, w - 17, 75), WHITE);- // próximas 6 horas- double now = (double)time(nullptr);- size_t first = 0;- while (first < wx.hours.size() && wx.hours[first].t <= now) first++;- float pitch = (w - 34) / 6;- for (int i = 0; i < 6 && first + i < wx.hours.size(); i++) {- auto& hr = wx.hours[first + i];- float cx = 17 + pitch * (i + 0.5f);- swprintf_s(b, L"%dh", LocalMinuteOfDay(hr.t, wx.utcOffset) / 60);- Txt(dc, br, b, 11, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(cx - 30, 92, cx + 30, 108), C(1, 1, 1, 0.75f));- DrawIcon(dc, br, IconOf(hr.code, hr.day), cx, 125, 21, dark);- swprintf_s(b, L"%ld°", lround(hr.temp));- Txt(dc, br, b, 13, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(cx - 30, 144, cx + 30, 162), WHITE);- }-}--// ---------------------------------------------------------------- relógio-void PaintClock(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, ID2D1StrokeStyle* st, float w, float h, bool dark) {- SYSTEMTIME t; GetLocalTime(&t);- Face(dc, br, st, w / 2, h / 2, 75, dark ? C(0.07f, 0.07f, 0.08f, 0.92f) : WHITE, dark ? WHITE : C(0, 0, 0), 20, true, t);-}--// ---------------------------------------------------------------- calendário-void PaintCalendar(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, float w, float h, bool dark) {- if (!dark) { br->SetColor(WHITE); dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(0, 0, w, h), WidgetRadius(), WidgetRadius()), br); }- static const wchar_t* months[] = { L"JANEIRO", L"FEVEREIRO", L"MARÇO", L"ABRIL", L"MAIO", L"JUNHO", L"JULHO", L"AGOSTO", L"SETEMBRO", L"OUTUBRO", L"NOVEMBRO", L"DEZEMBRO" };- SYSTEMTIME t; GetLocalTime(&t);- Txt(dc, br, Tr(months[t.wMonth - 1]), 11, DWRITE_FONT_WEIGHT_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING, D2D1::RectF(16, 16, w, 33), RED);- SYSTEMTIME f = t; f.wDay = 1; f.wHour = 12; FILETIME ft; SystemTimeToFileTime(&f, &ft); FileTimeToSystemTime(&ft, &f);- int startDow = f.wDayOfWeek;- static const int dim[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };- int days = dim[t.wMonth - 1] + (t.wMonth == 2 && ((t.wYear % 4 == 0 && t.wYear % 100) || t.wYear % 400 == 0));- int rows = (startDow + days + 6) / 7;- D2D1_COLOR_F ink = dark ? WHITE : C(0, 0, 0), weekend = dark ? C(1, 1, 1, 0.45f) : C(0, 0, 0, 0.40f);- const wchar_t* heads = idioma::En() ? L"SMTWTFS" : L"DSTQQSS";- float pitchX = 21.2f, x0 = 21, top = 44, pitchY = rows > 5 ? 17 : 19.8f;- for (int c = 0; c < 7; c++) {- wchar_t s[2] = { heads[c], 0 };- Txt(dc, br, s, 10, DWRITE_FONT_WEIGHT_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(x0 + c * pitchX - 10, top - 8, x0 + c * pitchX + 10, top + 8),- dark ? C(1, 1, 1, 0.55f) : C(0, 0, 0, 0.45f));- }- for (int d = 1; d <= days; d++) {- int cell = startDow + d - 1, c = cell % 7, r = cell / 7;- float cx = x0 + c * pitchX, cy = top + 20 + r * pitchY;- bool today = d == t.wDay;- if (today) { br->SetColor(RED); dc->FillEllipse(D2D1::Ellipse({ cx, cy }, 9, 9), br); }- Txt(dc, br, std::to_wstring(d), 11, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(cx - 11, cy - 8, cx + 11, cy + 8),- today ? WHITE : (c == 0 || c == 6) ? weekend : ink);- }-}--// ---------------------------------------------------------------- nascer e pôr do sol-void PaintSun(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, ID2D1StrokeStyle* st, float w, float h, bool dark) {- Weather wx; { std::lock_guard<std::mutex> lk(g_mx); wx = g_wx; }- if (!dark) Sky(dc, w, h, 0, wx.ok ? wx.day : true);- double now = (double)time(nullptr);- bool toSunset = false; double ev = 0, other = 0;- if (wx.ok) {- if (now < wx.sunrise[0]) { ev = wx.sunrise[0]; other = wx.sunset[0]; }- else if (now < wx.sunset[0]) { toSunset = true; ev = wx.sunset[0]; other = wx.sunrise[1]; }- else { ev = wx.sunrise[1]; other = wx.sunset[1]; }- }- // cabeçalho- float hx = 16;- Sun(dc, br, st, hx + 6, 22, 13, WHITE);- Txt(dc, br, toSunset ? Tr(L"PÔR DO SOL") : Tr(L"NASCER DO SOL"), 11, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING,- D2D1::RectF(hx + 16, 14, w, 30), C(1, 1, 1, 0.92f));- Txt(dc, br, wx.ok ? HourMin(ev, wx.utcOffset) : L"--:--", 30, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING,- D2D1::RectF(hx - 1, 32, w, 68), WHITE, true);- // curva do dia: meia-noite embaixo, meio-dia em cima; a linha do horizonte passa no nascer do sol- float cy = 104, A = 18;- auto yOf = [&](float u) { return cy + A * std::cos(2 * PI * u); };- float horizon = wx.ok ? yOf(LocalMinuteOfDay(wx.sunrise[0], wx.utcOffset) / 1440.f) : cy;- br->SetColor(C(1, 1, 1, 0.35f));- dc->DrawLine({ 0, horizon }, { w, horizon }, br, 1);- ID2D1Factory* f = nullptr; dc->GetFactory(&f);- for (int pass = 0; pass < 2 && f; pass++) { // abaixo do horizonte apagada, acima clara- ID2D1PathGeometry* p = nullptr;- if (FAILED(f->CreatePathGeometry(&p))) break;- ID2D1GeometrySink* sk = nullptr; p->Open(&sk);- sk->BeginFigure({ 0, yOf(0) }, D2D1_FIGURE_BEGIN_HOLLOW);- for (int i = 1; i <= 96; i++) sk->AddLine({ w * i / 96.f, yOf(i / 96.f) });- sk->EndFigure(D2D1_FIGURE_END_OPEN); sk->Close(); sk->Release();- D2D1_RECT_F clip = pass == 0 ? D2D1::RectF(0, horizon, w, h) : D2D1::RectF(0, 0, w, horizon);- dc->PushAxisAlignedClip(clip, D2D1_ANTIALIAS_MODE_ALIASED);- br->SetColor(C(1, 1, 1, pass == 0 ? 0.30f : 0.85f));- dc->DrawGeometry(p, br, 2, st);- dc->PopAxisAlignedClip();- p->Release();- }- if (f) f->Release();- if (wx.ok) {- float u = LocalMinuteOfDay(now, wx.utcOffset) / 1440.f, x = w * u, y = yOf(u);- br->SetColor(C(1, 1, 1, 0.25f)); dc->FillEllipse(D2D1::Ellipse({ x, y }, 8, 8), br);- br->SetColor(WHITE); dc->FillEllipse(D2D1::Ellipse({ x, y }, 5, 5), br);- std::wstring bottom = std::wstring(toSunset ? Tr(L"Nascer do sol: ") : Tr(L"Pôr do sol: ")) + HourMin(other, wx.utcOffset);- Txt(dc, br, bottom, 11, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_TEXT_ALIGNMENT_LEADING, D2D1::RectF(hx, 138, w, 156), C(1, 1, 1, 0.85f));- }-}--// ---------------------------------------------------------------- janelas-void Paint(Widget& wd) {- if (!wd.on || !wd.wnd) return;- float sc = ui::Scale(wd.wnd);- int wpx = (int)std::lround(wd.w * sc), hpx = (int)std::lround(wd.h * sc);- auto* dc = ui::GpuBegin(wd.s, wpx, hpx, sc);- if (!dc) return;- ID2D1SolidColorBrush* br = nullptr;- dc->CreateSolidColorBrush(WHITE, &br);- ID2D1StrokeStyle* st = RoundCaps(dc);- std::wstring est = ui::IconStyle(); // Tahoe/Golden Gate: Aparência > Estilo de ícones e widgets (Escuro "Auto" incluído)- g_vidroWidgets = est == L"transparente" || est == L"tingido";- bool dark = g_dark || g_vidroWidgets; // vidro: o conteúdo em branco, como no modo escuro- if (br) {- switch (wd.kind) {- case K_WORLD: PaintWorld(dc, br, st, wd.w, wd.h, dark); break;- case K_WEATHER: PaintWeather(dc, br, wd.w, wd.h, dark); break;- case K_CLOCK: PaintClock(dc, br, st, wd.w, wd.h, dark); break;- case K_CALENDAR: PaintCalendar(dc, br, wd.w, wd.h, dark); break;- case K_SUN: PaintSun(dc, br, st, wd.w, wd.h, dark); break;- }- if (liquid::On()) liquid::Rim(dc, D2D1::RectF(0, 0, wd.w, wd.h), WidgetRadius(), dark, 0.9f); // Tahoe: contorno especular- else if (dark) { // borda clarinha do vidro- br->SetColor(C(1, 1, 1, 0.10f));- dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(0.5f, 0.5f, wd.w - 0.5f, wd.h - 0.5f), WidgetRadius() - 0.5f, WidgetRadius() - 0.5f), br, 1);- }- br->Release();- }- if (st) st->Release();- ui::GpuEnd(wd.s);- D2D1_COLOR_F tint = dark ? C(0.10f, 0.10f, 0.11f, 0.38f)- : wd.kind == K_CLOCK ? C(0.96f, 0.95f, 1.0f, 0.30f) : C(1, 1, 1, 0);- if (g_vidroWidgets) { // vidro claro (Transparente) ou na cor de destaque (Tingido), o papel de parede aparece- if (est == L"tingido") { D2D1_COLOR_F a = ui::Accent(); tint = C(a.r, a.g, a.b, 0.42f); }- else tint = C(1, 1, 1, g_dark ? 0.12f : 0.22f);- }- if (wd.glass) backdrop::Set(wd.back, (float)wpx, (float)hpx, WidgetRadius() * sc, tint);-}--void PaintAll() { for (auto& w : g_w) Paint(w); }--// a janela mais alta da área de trabalho (Progman / WorkerW): os widgets ficam logo acima dela-HWND DesktopTop() {- for (HWND w = GetTopWindow(nullptr); w; w = GetWindow(w, GW_HWNDNEXT)) {- wchar_t c[32] = {}; GetClassNameW(w, c, 32);- if (mesa::IsDeskClass(c) && IsWindowVisible(w)) return w;- }- return nullptr;-}-bool IsOurs(HWND h) { if (h && h == g_ghost) return true; for (auto& w : g_w) if (w.wnd == h || w.back == h) return true; return false; }--void PlaceAtDesktop(Widget& wd) {- HWND desk = DesktopTop();- HWND above = desk ? GetWindow(desk, GW_HWNDPREV) : nullptr;- while (above && IsOurs(above)) above = GetWindow(above, GW_HWNDPREV); // acima dos outros widgets também- g_placing = true;- SetWindowPos(wd.wnd, above ? above : HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);- SetWindowPos(wd.back, wd.wnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);- g_placing = false;-}-// alguém (o Explorer, "mostrar a mesa") pôs a mesa por cima dos widgets?-bool BelowDesktop(const Widget& wd) {- for (HWND w = GetTopWindow(nullptr); w; w = GetWindow(w, GW_HWNDNEXT)) {- if (w == wd.wnd) return false;- wchar_t c[32] = {}; GetClassNameW(w, c, 32);- if (mesa::IsDeskClass(c) && IsWindowVisible(w)) return true;- }- return false;-}--// ---------------------------------------------------------------- grade-// Como no Mac: os widgets se encaixam em casas de 170 pt com 16 pt entre elas, contadas a partir do canto-// superior direito da tela (o médio ocupa duas casas). Arrastando, uma sombra mostra a casa livre mais perto-// e desliza até ela; ao soltar, o widget vai para a casa com a mola do sistema.-const float PITCH = SMALL + GAP;-const float SPRING_RESPONSE = 0.40f, SPRING_DAMPING = 0.86f;-const UINT WM_WG_FRAME = WM_APP + 61;--struct Grid { float left, top, right, bottom, sc; };-Grid GridNow(HWND h) {- MONITORINFO mi{ sizeof(mi) };- GetMonitorInfoW(MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY), &mi);- float sc = ui::Scale(h);- RECT r = shell::WorkAreaFor(MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)); // a do Shell (issue #1)- return { r.left / sc, r.top / sc, r.right / sc, r.bottom / sc, sc };-}-int Cols(const Widget& w) { return w.w > SMALL + 1 ? 2 : 1; }-int MaxRc(const Grid& g, const Widget& w) { return std::max(0, (int)std::floor((g.right - g.left - 2 * MARGIN - w.w) / PITCH)); }-int MaxRow(const Grid& g, const Widget& w) { return std::max(0, (int)std::floor((g.bottom - g.top - 2 * MARGIN - w.h) / PITCH)); }-POINT CellPx(const Grid& g, const Widget& w, int rc, int row) { // rc: casa da borda direita do widget, contando da direita- float x = g.right - MARGIN - w.w - rc * PITCH, y = g.top + MARGIN + row * PITCH;- return { (LONG)std::lround(x * g.sc), (LONG)std::lround(y * g.sc) };-}-bool Overlaps(const Widget& w, int rc, int row) {- int a0 = rc, a1 = rc + Cols(w) - 1;- for (auto& o : g_w) {- if (&o == &w || !o.on || o.rc < 0 || o.row != row) continue;- int b0 = o.rc, b1 = o.rc + Cols(o) - 1;- if (a0 <= b1 && b0 <= a1) return true;- }- return false;-}-// a casa livre mais perto de px (canto superior esquerdo do widget, em px)-void Nearest(const Grid& g, const Widget& w, POINT px, int& rc, int& row) {- double best = 1e300; rc = 0; row = 0;- for (int r = 0; r <= MaxRow(g, w); r++)- for (int c = 0; c <= MaxRc(g, w); c++) {- if (Overlaps(w, c, r)) continue;- POINT p = CellPx(g, w, c, r);- double dx = p.x - px.x, dy = p.y - px.y, d = dx * dx + dy * dy;- if (d < best) { best = d; rc = c; row = r; }- }-}-void DefaultCell(const Widget& wd, int& rc, int& row) {- switch (wd.kind) {- case K_WEATHER: rc = 0; row = 0; break;- case K_WORLD: rc = 2; row = 0; break;- case K_CLOCK: rc = 1; row = 1; break;- case K_CALENDAR: rc = 0; row = 1; break;- case K_SUN: rc = 2; row = 1; break;- }-}--void MoveWin(Widget& w, int x, int y) {- g_placing = true;- HDWP d = BeginDeferWindowPos(2);- if (d) d = DeferWindowPos(d, w.back, nullptr, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);- if (d) d = DeferWindowPos(d, w.wnd, nullptr, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);- if (d) EndDeferWindowPos(d);- g_placing = false;-}--// animações de encaixe-struct Move { Widget* w; POINT from, to; double t0; };-std::vector<Move> g_moves;-// sombra da casa de destino enquanto arrasta-ui::Surface g_ghostS;-double g_gx, g_gy, g_lastFrame; POINT g_ghostTo; int g_targetRc = -1, g_targetRow = -1;--void Animate(bool on) { ui::FrameClock(g_timer, WM_WG_FRAME, on); g_lastFrame = anim::Now(); }--void AnimateTo(Widget& w, POINT to) {- RECT r; GetWindowRect(w.wnd, &r);- g_moves.erase(std::remove_if(g_moves.begin(), g_moves.end(), [&](const Move& m) { return m.w == &w; }), g_moves.end());- if (r.left == to.x && r.top == to.y) return;- g_moves.push_back({ &w, { r.left, r.top }, to, anim::Now() });- Animate(true);-}--void PaintGhost(const Widget& w) {- float sc = ui::Scale(w.wnd);- int wpx = (int)std::lround(w.w * sc), hpx = (int)std::lround(w.h * sc);- auto* rt = ui::Begin(g_ghostS, wpx, hpx, sc);- if (!rt) return;- rt->Clear(D2D1::ColorF(0, 0, 0, 0));- ID2D1SolidColorBrush* br = nullptr;- rt->CreateSolidColorBrush(C(1, 1, 1, g_dark ? 0.10f : 0.22f), &br);- if (br) {- auto rr = D2D1::RoundedRect(D2D1::RectF(1, 1, w.w - 1, w.h - 1), WidgetRadius() - 1, WidgetRadius() - 1);- rt->FillRoundedRectangle(rr, br);- br->SetColor(C(1, 1, 1, g_dark ? 0.30f : 0.55f));- rt->DrawRoundedRectangle(rr, br, 1.5f);- br->Release();- }- ui::End(g_ghostS, true, { (LONG)g_gx, (LONG)g_gy });-}--void Frame() {- double now = anim::Now();- static float dur = anim::SpringDuration(SPRING_RESPONSE, SPRING_DAMPING);- for (size_t i = 0; i < g_moves.size();) {- auto& m = g_moves[i];- float t = (float)((now - m.t0) / 1000.0);- if (t >= dur) { MoveWin(*m.w, m.to.x, m.to.y); g_moves.erase(g_moves.begin() + i); continue; }- float p = anim::Spring(t, SPRING_RESPONSE, SPRING_DAMPING);- MoveWin(*m.w, (int)std::lround(m.from.x + (m.to.x - m.from.x) * p), (int)std::lround(m.from.y + (m.to.y - m.from.y) * p));- i++;- }- if (g_ghost && IsWindowVisible(g_ghost)) { // a sombra segue a casa de destino, suave (sem degrau)- double dt = std::min(50.0, now - g_lastFrame), k = 1 - std::exp(-dt / 55.0);- g_gx += (g_ghostTo.x - g_gx) * k; g_gy += (g_ghostTo.y - g_gy) * k;- SetWindowPos(g_ghost, nullptr, (int)std::lround(g_gx), (int)std::lround(g_gy), 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);- if (!g_dragging && std::fabs(g_ghostTo.x - g_gx) < 0.5 && std::fabs(g_ghostTo.y - g_gy) < 0.5 && g_moves.empty()) ShowWindow(g_ghost, SW_HIDE);- }- g_lastFrame = now;- if (g_moves.empty() && !g_dragging && !(g_ghost && IsWindowVisible(g_ghost))) Animate(false);-}--void SaveCell(const Widget& w) {- wchar_t b[32]; swprintf_s(b, L"g:%d,%d", w.rc, w.row);- shell::SetSetting((std::wstring(L"widget.") + w.id).c_str(), b);-}--void Position(Widget& wd, bool reset, bool animate = false) {- Grid g = GridNow(wd.wnd);- int rc = -1, row = -1, a, b;- std::wstring saved = reset ? L"" : shell::Setting((std::wstring(L"widget.") + wd.id).c_str(), L"");- wd.rc = -1;- if (!saved.empty() && swscanf_s(saved.c_str(), L"g:%d,%d", &a, &b) == 2) { rc = a; row = b; }- else if (!saved.empty() && swscanf_s(saved.c_str(), L"%d,%d", &a, &b) == 2) Nearest(g, wd, { a, b }, rc, row); // posição antiga, em px- else DefaultCell(wd, rc, row);- rc = std::clamp(rc, 0, MaxRc(g, wd)); row = std::clamp(row, 0, MaxRow(g, wd));- if (Overlaps(wd, rc, row)) Nearest(g, wd, CellPx(g, wd, rc, row), rc, row);- wd.rc = rc; wd.row = row;- POINT p = CellPx(g, wd, rc, row);- int wpx = (int)std::lround(wd.w * g.sc), hpx = (int)std::lround(wd.h * g.sc);- g_placing = true;- UINT fl = SWP_NOZORDER | SWP_NOACTIVATE | (animate ? SWP_NOMOVE : 0);- SetWindowPos(wd.back, nullptr, p.x, p.y, wpx, hpx, fl);- SetWindowPos(wd.wnd, nullptr, p.x, p.y, wpx, hpx, fl);- g_placing = false;- if (animate) AnimateTo(wd, p);-}--void Show(Widget& wd, bool on) {- wd.on = on;- if (!on) wd.rc = -1; // a casa fica livre- if (on) {- Position(wd, false);- ShowWindow(wd.back, SW_SHOWNOACTIVATE);- ShowWindow(wd.wnd, SW_SHOWNOACTIVATE);- PlaceAtDesktop(wd);- Paint(wd);- } else {- ShowWindow(wd.wnd, SW_HIDE);- ShowWindow(wd.back, SW_HIDE);- }-}--Widget* Of(HWND h) { for (auto& w : g_w) if (w.wnd == h || w.back == h) return &w; return nullptr; }--void Click(Widget& wd) {- const wchar_t* target = nullptr;- std::wstring url;- switch (wd.kind) {- case K_WEATHER: case K_SUN: {- url = L"https://www.google.com/search?q=tempo+" + City();- for (auto& c : url) if (c == L' ') c = L'+';- target = url.c_str(); break;- }- case K_CLOCK: case K_WORLD: target = L"ms-clock:"; break;- case K_CALENDAR: target = L"outlookcal:"; break;- }- if (target) ShellExecuteW(nullptr, L"open", target, nullptr, nullptr, SW_SHOWNORMAL);-}--void Menu(Widget* wd, POINT pt) { // wd nulo: "Editar Widgets…" da mesa (só ligar/desligar e organizar)- std::vector<ctxmenu::Item> items;- for (size_t i = 0; i < g_w.size(); i++) {- ctxmenu::Item it; it.label = Tr(g_w[i].name); it.id = 10 + (int)i; it.checked = g_w[i].on; items.push_back(it);- }- ctxmenu::Item sep; sep.separator = true; items.push_back(sep);- if (wd) { ctxmenu::Item rm; rm.label = Tr(L"Remover Widget"); rm.id = 1; items.push_back(rm); }- ctxmenu::Item reset; reset.label = Tr(L"Organizar Widgets"); reset.id = 2; items.push_back(reset);- HWND fg = GetForegroundWindow();- DWORD ft = fg ? GetWindowThreadProcessId(fg, nullptr) : 0, me = GetCurrentThreadId();- bool att = ft && ft != me && AttachThreadInput(me, ft, TRUE);- SetForegroundWindow(g_menuOwner);- if (att) AttachThreadInput(me, ft, FALSE);- int id = ctxmenu::ShowItems(g_menuOwner, pt, items);- if (id == 1 && wd) { Show(*wd, false); shell::SetSetting((std::wstring(L"widget.") + wd->id + L".on").c_str(), L"0"); }- else if (id == 2) {- for (auto& w : g_w) w.rc = -1;- for (auto& w : g_w) { shell::SetSetting((std::wstring(L"widget.") + w.id).c_str(), L""); if (w.on) Position(w, true, true); }- } else if (id >= 10 && id < 10 + (int)g_w.size()) {- Widget& t = g_w[id - 10];- Show(t, !t.on);- shell::SetSetting((std::wstring(L"widget.") + t.id + L".on").c_str(), t.on ? L"1" : L"0");- }-}--LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM wp, LPARAM lp) {- Widget* wd = Of(h);- switch (m) {- case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(h, &ps); EndPaint(h, &ps); if (wd && wd->wnd == h) Paint(*wd); return 0; }- case WM_MOUSEACTIVATE: return MA_NOACTIVATE;- case WM_WINDOWPOSCHANGING: { // só nós mexemos na ordem: ficam sempre logo acima da mesa- auto* p = (WINDOWPOS*)lp;- if (!g_placing) p->flags |= SWP_NOZORDER;- break;- }- case WM_LBUTTONDOWN:- if (wd) { g_drag = wd; GetCursorPos(&g_dragStart); RECT r; GetWindowRect(wd->wnd, &r); g_winStart = { r.left, r.top }; g_dragging = false; SetCapture(h); }- return 0;- case WM_MOUSEMOVE:- if (g_drag && GetCapture() == h) {- POINT c; GetCursorPos(&c);- int dx = c.x - g_dragStart.x, dy = c.y - g_dragStart.y;- // só vira arrastar depois de ~8 px: com 3 px um clique com a mão tremendo mudava o widget de casa- // e gravava o lugar novo (os widgets "pulavam" para o meio da tela, 17/11/2026)- int lim = std::max(8, GetSystemMetrics(SM_CXDRAG) * 2);- if (!g_dragging && (abs(dx) > lim || abs(dy) > lim)) { // começou a arrastar: por cima dos outros, sombra na casa atual- g_dragging = true;- g_moves.erase(std::remove_if(g_moves.begin(), g_moves.end(), [&](const Move& mv) { return mv.w == g_drag; }), g_moves.end());- PlaceAtDesktop(*g_drag);- Grid g = GridNow(g_drag->wnd);- g_targetRc = g_drag->rc; g_targetRow = g_drag->row;- g_drag->rc = -1; // a casa dele fica livre enquanto arrasta- if (g_targetRc < 0) Nearest(g, *g_drag, g_winStart, g_targetRc, g_targetRow);- g_ghostTo = CellPx(g, *g_drag, g_targetRc, g_targetRow);- g_gx = g_ghostTo.x; g_gy = g_ghostTo.y;- PaintGhost(*g_drag);- g_placing = true;- SetWindowPos(g_ghost, g_drag->back, (int)g_gx, (int)g_gy, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW);- g_placing = false;- Animate(true);- }- if (g_dragging) {- POINT p{ g_winStart.x + dx, g_winStart.y + dy };- MoveWin(*g_drag, p.x, p.y);- Grid g = GridNow(g_drag->wnd);- Nearest(g, *g_drag, p, g_targetRc, g_targetRow);- g_ghostTo = CellPx(g, *g_drag, g_targetRc, g_targetRow);- }- }- return 0;- case WM_LBUTTONUP: case WM_CAPTURECHANGED:- if (g_drag && (m == WM_CAPTURECHANGED || GetCapture() == h)) {- Widget* d = g_drag; g_drag = nullptr;- bool dragged = g_dragging; g_dragging = false;- if (m == WM_LBUTTONUP) ReleaseCapture();- if (dragged) { // encaixa na casa com a mola- d->rc = g_targetRc; d->row = g_targetRow;- SaveCell(*d);- AnimateTo(*d, CellPx(GridNow(d->wnd), *d, d->rc, d->row));- Animate(true);- } else if (m == WM_LBUTTONUP) Click(*d);- }- return 0;- case WM_RBUTTONUP:- if (wd) { POINT c; GetCursorPos(&c); Menu(wd, c); }- return 0;- }- return DefWindowProcW(h, m, wp, lp);-}--const UINT WM_WG_DESK = WM_APP + 62;-// a mesa veio para a frente (Win+D, "mostrar a área de trabalho", clique na mesa): os widgets sobem na hora-// (antes só na conferência de 3 s: no Win+D eles demoravam a aparecer)-void CALLBACK OnForeground(HWINEVENTHOOK, DWORD, HWND h, LONG obj, LONG, DWORD, DWORD) {- if (obj != OBJID_WINDOW || !h) return;- wchar_t c[32] = {}; GetClassNameW(h, c, 32);- if (mesa::IsDeskClass(c)) PostMessageW(g_timer, WM_WG_DESK, 0, 0);-}--LRESULT CALLBACK TimerProc(HWND h, UINT m, WPARAM wp, LPARAM lp) {- if (m == WM_WG_FRAME) { Frame(); return 0; }- if (m == WM_WG_DESK) { if (!g_drag) for (auto& w : g_w) if (w.on && BelowDesktop(w)) { for (auto& x : g_w) if (x.on) PlaceAtDesktop(x); break; } return 0; }- if (m == WM_WX_READY) { for (auto& w : g_w) if (w.kind == K_WEATHER || w.kind == K_SUN) Paint(w); return 0; }- if (m == WM_TIMER && wp == 1) {- SYSTEMTIME t; GetLocalTime(&t);- SetTimer(h, 1, 1000 - t.wMilliseconds + 5, nullptr); // na virada do segundo- bool dark = ui::Dark();- bool all = dark != g_dark || t.wMinute != g_lastMinute;- g_dark = dark; g_lastMinute = t.wMinute;- static int tick;- bool checkZ = true; // ordem das janelas: todo segundo, só pelo primeiro widget ligado (barato: para no primeiro achado)- ++tick;- { // área de trabalho mudou (a barra de menus reservou a faixa de cima depois que os widgets nasceram, ou o- // Dock mudou): reposiciona. O Shell muda a área sem avisar todo mundo, então o WM_SETTINGCHANGE não chegava- // e os widgets ficavam por cima da barra de menus (17/11/2026)- static RECT lastWork{};- RECT work = shell::WorkAreaFor(MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)); // a do Shell (issue #1)- if (!EqualRect(&work, &lastWork) && !g_drag && g_moves.empty()) {- bool first = lastWork.right == 0;- lastWork = work;- (void)first; // também na primeira: os widgets podem ter nascido com a área antiga (sem a barra)- for (auto& w : g_w) if (w.on) { Position(w, false); Paint(w); }- }- }- bool below = false;- if (checkZ) for (auto& w : g_w) if (w.on) { below = BelowDesktop(w); break; }- for (auto& w : g_w) {- if (!w.on) continue;- if (below) PlaceAtDesktop(w);- if (all || w.kind == K_CLOCK || w.kind == K_WORLD) Paint(w);- }- return 0;- }- if (m == WM_TIMER && wp == 2) { Fetch(); return 0; }- if (m == WM_DISPLAYCHANGE || (m == WM_SETTINGCHANGE && wp == SPI_SETWORKAREA)) {- for (auto& w : g_w) if (w.on) { Position(w, false); Paint(w); }- return 0;- }- return DefWindowProcW(h, m, wp, lp);-}--LRESULT CALLBACK BackProc(HWND h, UINT m, WPARAM w, LPARAM l) {- if (m == WM_MOUSEACTIVATE) return MA_NOACTIVATE;- if (m == WM_WINDOWPOSCHANGING && !g_placing) ((WINDOWPOS*)l)->flags |= SWP_NOZORDER;- return DefWindowProcW(h, m, w, l);-}--} // namespace--// "Editar Widgets…" (menu da mesa e da Central): a lista dos widgets para ligar ou desligar, mesmo sem nenhum na-// tela (antes só dava pelo menu de um widget: removidos todos, não havia como trazer de volta)-void widgets::EditMenu(POINT pt) { if (!g_w.empty()) Menu(nullptr, pt); }--void widgets::Create(HINSTANCE hi) {- WNDCLASSW bc{}; bc.lpfnWndProc = BackProc; bc.hInstance = hi; bc.lpszClassName = L"ShellWidgetFundo";- RegisterClassW(&bc);- WNDCLASSW wc{}; wc.lpfnWndProc = Proc; wc.hInstance = hi; wc.lpszClassName = L"ShellWidget"; wc.hCursor = LoadCursorW(nullptr, IDC_ARROW);- RegisterClassW(&wc);- WNDCLASSW tc{}; tc.lpfnWndProc = TimerProc; tc.hInstance = hi; tc.lpszClassName = L"ShellWidgetsRelogio";- RegisterClassW(&tc);- g_timer = CreateWindowExW(WS_EX_TOOLWINDOW, tc.lpszClassName, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, hi, nullptr); // recebe WM_DISPLAYCHANGE- WNDCLASSW gc{}; gc.lpfnWndProc = BackProc; gc.hInstance = hi; gc.lpszClassName = L"ShellWidgetSombra";- RegisterClassW(&gc);- g_ghost = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_LAYERED | WS_EX_TRANSPARENT, gc.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);- g_ghostS.hwnd = g_ghost;- g_menuOwner = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_LAYERED, tc.lpszClassName, L"", WS_POPUP | WS_VISIBLE, -32000, -32000, 1, 1, nullptr, nullptr, hi, nullptr);- SetLayeredWindowAttributes(g_menuOwner, 0, 0, LWA_ALPHA);- apps::ours.push_back(g_menuOwner);- apps::ours.push_back(g_ghost);-- g_w = { { K_WEATHER, L"tempo", L"Tempo", MEDIUM, SMALL },- { K_CLOCK, L"relogio", L"Relógio", SMALL, SMALL },- { K_CALENDAR, L"calendario", L"Calendário", SMALL, SMALL },- { K_WORLD, L"mundial", L"Relógio Mundial", MEDIUM, SMALL },- { K_SUN, L"sol", L"Nascer do Sol", SMALL, SMALL } };- g_w.reserve(g_w.size());- g_dark = ui::Dark();- LoadCache();- for (auto& wd : g_w) {- wd.back = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP, bc.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);- if (!wd.back) continue;- wd.glass = backdrop::Attach(wd.back);- if (!wd.glass) {- DestroyWindow(wd.back);- wd.back = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, bc.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);- DWORD corner = 2; DwmSetWindowAttribute(wd.back, 33, &corner, sizeof(corner));- ui::Acrylic(wd.back, g_dark ? 0x60201E1Eu : 0x30F6F6F6u);- } else { DWORD corner = 1; DwmSetWindowAttribute(wd.back, 33, &corner, sizeof(corner)); }- COLORREF none = 0xFFFFFFFE;- DwmSetWindowAttribute(wd.back, 34, &none, sizeof(none));- BOOL off = TRUE; DwmSetWindowAttribute(wd.back, DWMWA_TRANSITIONS_FORCEDISABLED, &off, sizeof(off));- wd.wnd = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP, wc.lpszClassName, wd.name, WS_POPUP, 0, 0, 10, 10, wd.back, nullptr, hi, nullptr);- if (!wd.wnd) continue;- DwmSetWindowAttribute(wd.wnd, DWMWA_TRANSITIONS_FORCEDISABLED, &off, sizeof(off));- apps::ours.push_back(wd.wnd);- apps::ours.push_back(wd.back);- wd.s.hwnd = wd.wnd;- Show(wd, shell::Setting((std::wstring(L"widget.") + wd.id + L".on").c_str(), L"1") != L"0");- }- SetTimer(g_timer, 1, 1000, nullptr);- SetTimer(g_timer, 2, 15 * 60 * 1000, nullptr);- SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr, OnForeground, 0, 0, WINEVENT_OUTOFCONTEXT);- Fetch();- Log(L"widgets: %zu na mesa (tempo de %ls)", g_w.size(), City().c_str());-}--std::vector<RECT> widgets::Areas() {- std::vector<RECT> r;- for (auto& w : g_w) if (w.on && w.wnd && IsWindowVisible(w.wnd)) { RECT x; GetWindowRect(w.wnd, &x); r.push_back(x); }- return r;-}+// Widgets da mesa, como no macOS Sequoia: Relógio Mundial, Tempo, Relógio, Calendário e Nascer do Sol.+// Ficam logo acima da área de trabalho (abaixo de todas as janelas), arrastáveis; posições em ajustes.txt.+// Medidas da referência (Sequoia, 0,72 px por pt): pequeno 170 × 170 pt, médio 364 × 170 pt, 16 pt entre+// eles, canto de 21 pt. Claro: as cores de cada widget (Tempo em degradê do céu, Calendário branco, Relógio+// Mundial preto, Relógio em vidro). Escuro: todos em vidro desfocado da mesa, com texto e símbolos brancos.+// O tempo vem do Open-Meteo (sem chave), a cada 15 min, para a cidade em ajustes.txt (padrão: a do fuso do Windows, comum/cidade_padrao.h);+// a última resposta fica em %APPDATA%\Shell\tempo.json para aparecer já ao ligar.+#include "shell.h"+#include "../comum/cidade_padrao.h"+#include "../menu/context_menu.h"+#include <dwmapi.h>+#include <shellapi.h>+#include <shlobj.h>+#include <winhttp.h>+#include <algorithm>+#include <cmath>+#include <ctime>+#include <map>+#include <mutex>+#include <thread>+#include <atomic>+#include "../comum/idioma.h"+#pragma comment(lib, "winhttp.lib")++namespace {++const float SMALL = 170, MEDIUM = 356, GAP = 16, RADIUS_SEQ = 21, MARGIN = 16;+inline float WidgetRadius() { return liquid::On() ? 26.f : RADIUS_SEQ; } // Tahoe: mais redondos+const UINT WM_WX_READY = WM_APP + 60;+const float PI = 3.14159265f;++enum Kind { K_WORLD, K_WEATHER, K_CLOCK, K_CALENDAR, K_SUN };+struct Widget {+ Kind kind; const wchar_t* id; const wchar_t* name; float w, h;+ HWND wnd = nullptr, back = nullptr;+ bool glass = false, on = true;+ int rc = -1, row = -1; // casa na grade (rc: coluna da borda direita, contando da direita)+ ui::GpuSurface s;+};+std::vector<Widget> g_w;+HWND g_menuOwner; // dono invisível do menu de contexto (o menu precisa de um dono em primeiro plano)+HWND g_ghost; // sombra da casa de destino ao arrastar+HWND g_timer; // janela que recebe os relógios e a chegada do tempo+bool g_dark, g_placing;+int g_lastMinute = -1;++// arrastar+Widget* g_drag; POINT g_dragStart, g_winStart; bool g_dragging;++// ---------------------------------------------------------------- tempo (Open-Meteo)+struct Hour { double t; float temp; int code; bool day; };+struct Weather {+ bool ok = false;+ float temp = 0; int code = 0; bool day = true;+ float hi = 0, lo = 0;+ double sunrise[2]{}, sunset[2]{};+ int utcOffset = -3 * 3600;+ std::vector<Hour> hours;+};+std::mutex g_mx;+Weather g_wx;+std::atomic<bool> g_fetching{ false };++std::wstring City() { static cidade::Padrao def; return shell::Setting(L"tempoCidade", def.nome.c_str()); } // sem cidade: a do fuso do Windows++std::string Section(const std::string& j, const char* key) {+ size_t p = j.find(std::string("\"") + key + "\":{");+ if (p == std::string::npos) return "";+ p = j.find('{', p);+ int depth = 0;+ for (size_t i = p; i < j.size(); i++) {+ if (j[i] == '{') depth++;+ else if (j[i] == '}' && --depth == 0) return j.substr(p, i - p + 1);+ }+ return "";+}+double Number(const std::string& s, const char* key) {+ size_t p = s.find(std::string("\"") + key + "\":");+ if (p == std::string::npos) return NAN;+ p += strlen(key) + 3;+ while (p < s.size() && s[p] == ' ') p++;+ if (s.compare(p, 4, "null") == 0) return NAN;+ return strtod(s.c_str() + p, nullptr);+}+std::vector<double> Array(const std::string& s, const char* key) {+ std::vector<double> v;+ size_t p = s.find(std::string("\"") + key + "\":[");+ if (p == std::string::npos) return v;+ p = s.find('[', p) + 1;+ while (p < s.size() && s[p] != ']') {+ while (p < s.size() && (s[p] == ' ' || s[p] == ',')) p++;+ if (s[p] == ']') break;+ if (s.compare(p, 4, "null") == 0) { v.push_back(NAN); p += 4; continue; }+ char* e = nullptr;+ v.push_back(strtod(s.c_str() + p, &e));+ if (e == s.c_str() + p) break;+ p = e - s.c_str();+ }+ return v;+}++bool Parse(const std::string& j, Weather& w) {+ std::string cur = Section(j, "current"), hr = Section(j, "hourly"), dl = Section(j, "daily");+ if (cur.empty() || hr.empty() || dl.empty()) return false;+ double off = Number(j, "utc_offset_seconds");+ if (!std::isnan(off)) w.utcOffset = (int)off;+ w.temp = (float)Number(cur, "temperature_2m");+ w.code = (int)Number(cur, "weather_code");+ w.day = Number(cur, "is_day") > 0.5;+ auto t = Array(hr, "time"), tp = Array(hr, "temperature_2m"), c = Array(hr, "weather_code"), d = Array(hr, "is_day");+ w.hours.clear();+ for (size_t i = 0; i < t.size() && i < tp.size() && i < c.size() && i < d.size(); i++)+ w.hours.push_back({ t[i], (float)tp[i], (int)c[i], d[i] > 0.5 });+ auto mx = Array(dl, "temperature_2m_max"), mn = Array(dl, "temperature_2m_min"), sr = Array(dl, "sunrise"), ss = Array(dl, "sunset");+ if (mx.empty() || mn.empty() || sr.size() < 2 || ss.size() < 2 || std::isnan(w.temp)) return false;+ w.hi = (float)mx[0]; w.lo = (float)mn[0];+ for (int i = 0; i < 2; i++) { w.sunrise[i] = sr[i]; w.sunset[i] = ss[i]; }+ w.ok = true;+ return true;+}++std::wstring CachePath() {+ PWSTR p = nullptr; std::wstring f;+ if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) { f = std::wstring(p) + L"\\Shell\\tempo.json"; CoTaskMemFree(p); }+ return f;+}++std::string HttpGet(const wchar_t* host, const std::wstring& path) {+ std::string body;+ HINTERNET ses = WinHttpOpen(L"ShellProprio/1.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);+ if (!ses) return body;+ WinHttpSetTimeouts(ses, 5000, 5000, 8000, 8000);+ HINTERNET con = WinHttpConnect(ses, host, INTERNET_DEFAULT_HTTPS_PORT, 0);+ HINTERNET req = con ? WinHttpOpenRequest(con, L"GET", path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : nullptr;+ if (req && WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) && WinHttpReceiveResponse(req, nullptr)) {+ DWORD status = 0, sz = sizeof(status);+ WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, nullptr, &status, &sz, nullptr);+ DWORD avail = 0;+ while (WinHttpQueryDataAvailable(req, &avail) && avail && body.size() < 256 * 1024) {+ std::string chunk(avail, '\0'); DWORD got = 0;+ if (!WinHttpReadData(req, chunk.data(), avail, &got) || !got) break;+ body.append(chunk.data(), got);+ }+ if (status != 200) body.clear();+ }+ if (req) WinHttpCloseHandle(req);+ if (con) WinHttpCloseHandle(con);+ WinHttpCloseHandle(ses);+ return body;+}++void Fetch() {+ if (g_fetching.exchange(true)) return;+ static cidade::Padrao def;+ std::wstring lat = shell::Setting(L"tempoLat", def.lat.c_str()), lon = shell::Setting(L"tempoLon", def.lon.c_str());+ std::thread([lat, lon] {+ std::wstring path = L"/v1/forecast?latitude=" + lat + L"&longitude=" + lon ++ L"¤t=temperature_2m,weather_code,is_day&hourly=temperature_2m,weather_code,is_day"+ L"&daily=temperature_2m_max,temperature_2m_min,sunrise,sunset&timezone=auto&forecast_days=3&timeformat=unixtime";+ std::string body = HttpGet(L"api.open-meteo.com", path);+ Weather w;+ if (!body.empty() && Parse(body, w)) {+ { std::lock_guard<std::mutex> lk(g_mx); g_wx = w; }+ FILE* fp = nullptr;+ if (!_wfopen_s(&fp, CachePath().c_str(), L"wb") && fp) { fwrite(body.data(), 1, body.size(), fp); fclose(fp); }+ Log(L"widgets: tempo atualizado (%.1f°, código %d)", w.temp, w.code);+ PostMessageW(g_timer, WM_WX_READY, 0, 0);+ } else Log(L"widgets: não deu para buscar o tempo (%zu bytes)", body.size());+ g_fetching = false;+ }).detach();+}++void LoadCache() {+ FILE* fp = nullptr;+ if (_wfopen_s(&fp, CachePath().c_str(), L"rb") || !fp) return;+ std::string body; char buf[8192]; size_t n;+ while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) body.append(buf, n);+ fclose(fp);+ Weather w;+ if (Parse(body, w)) { std::lock_guard<std::mutex> lk(g_mx); g_wx = w; }+}++enum Icon { I_SUN, I_MOON, I_PARTLY, I_PARTLY_NIGHT, I_CLOUD, I_FOG, I_DRIZZLE, I_RAIN, I_SNOW, I_THUNDER };+Icon IconOf(int code, bool day) {+ if (code == 0) return day ? I_SUN : I_MOON;+ if (code <= 2) return day ? I_PARTLY : I_PARTLY_NIGHT;+ if (code == 3) return I_CLOUD;+ if (code == 45 || code == 48) return I_FOG;+ if (code >= 51 && code <= 57) return I_DRIZZLE;+ if ((code >= 61 && code <= 67) || (code >= 80 && code <= 82)) return I_RAIN;+ if ((code >= 71 && code <= 77) || code == 85 || code == 86) return I_SNOW;+ if (code >= 95) return I_THUNDER;+ return I_CLOUD;+}+const wchar_t* ConditionOf(int code, bool day) {+ if (code == 0) return day ? Tr(L"Ensolarado") : Tr(L"Céu Limpo");+ if (code == 1) return day ? Tr(L"Predom. Ensolarado") : Tr(L"Predom. Limpo");+ if (code == 2) return Tr(L"Parcialmente Nublado");+ if (code == 3) return Tr(L"Nublado");+ if (code == 45 || code == 48) return Tr(L"Neblina");+ if (code >= 51 && code <= 57) return Tr(L"Garoa");+ if (code == 65 || code == 82) return Tr(L"Chuva Forte");+ if (code == 66 || code == 67) return Tr(L"Chuva Congelada");+ if ((code >= 61 && code <= 63) || code == 80 || code == 81) return Tr(L"Chuva");+ if ((code >= 71 && code <= 77) || code == 85 || code == 86) return Tr(L"Neve");+ if (code >= 95) return Tr(L"Tempestades");+ return Tr(L"Nublado");+}++// hora local da cidade do tempo, a partir de um instante unix+int LocalMinuteOfDay(double t, int off) { long long s = (long long)t + off; s %= 86400; if (s < 0) s += 86400; return (int)(s / 60); }+std::wstring HourMin(double t, int off) { int m = LocalMinuteOfDay(t, off); wchar_t b[16]; swprintf_s(b, L"%02d:%02d", m / 60, m % 60); return b; }++// ---------------------------------------------------------------- desenho+D2D1_COLOR_F C(float r, float g, float b, float a = 1) { return D2D1::ColorF(r, g, b, a); }+const D2D1_COLOR_F WHITE = { 1, 1, 1, 1 }, ORANGE = { 1, 0.584f, 0, 1 }, RED = { 1, 0.231f, 0.188f, 1 };++void Txt(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, const std::wstring& s, float size, DWRITE_FONT_WEIGHT wgt,+ DWRITE_TEXT_ALIGNMENT al, D2D1_RECT_F r, D2D1_COLOR_F c, bool display = false) {+ IDWriteTextFormat* tf = nullptr;+ if (FAILED(ui::dw->CreateTextFormat(display ? L"SF Pro Display" : ui::family.c_str(), nullptr, wgt, DWRITE_FONT_STYLE_NORMAL,+ DWRITE_FONT_STRETCH_NORMAL, size, L"pt-br", &tf)) || !tf) return;+ tf->SetTextAlignment(al);+ tf->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);+ tf->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);+ br->SetColor(c);+ dc->DrawText(s.c_str(), (UINT32)s.size(), tf, r, br, D2D1_DRAW_TEXT_OPTIONS_NONE);+ tf->Release();+}+float Width(const std::wstring& s, float size, DWRITE_FONT_WEIGHT wgt, bool display = false) {+ IDWriteTextFormat* tf = nullptr;+ if (FAILED(ui::dw->CreateTextFormat(display ? L"SF Pro Display" : ui::family.c_str(), nullptr, wgt, DWRITE_FONT_STYLE_NORMAL,+ DWRITE_FONT_STRETCH_NORMAL, size, L"pt-br", &tf)) || !tf) return 0;+ float w = ui::TextWidth(tf, s);+ tf->Release();+ return w;+}++ID2D1StrokeStyle* RoundCaps(ID2D1DeviceContext* dc) {+ ID2D1Factory* f = nullptr; dc->GetFactory(&f);+ ID2D1StrokeStyle* st = nullptr;+ if (f) { f->CreateStrokeStyle(D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND), nullptr, 0, &st); f->Release(); }+ return st;+}++ID2D1Geometry* Combine(ID2D1Factory* f, ID2D1Geometry* a, ID2D1Geometry* b, D2D1_COMBINE_MODE mode) {+ ID2D1PathGeometry* p = nullptr;+ if (a && b && SUCCEEDED(f->CreatePathGeometry(&p))) {+ ID2D1GeometrySink* s = nullptr;+ if (SUCCEEDED(p->Open(&s))) { a->CombineWithGeometry(b, mode, nullptr, s); s->Close(); s->Release(); }+ }+ if (a) a->Release();+ if (b) b->Release();+ return p;+}+ID2D1Geometry* Circle(ID2D1Factory* f, float x, float y, float r) {+ ID2D1EllipseGeometry* e = nullptr; f->CreateEllipseGeometry(D2D1::Ellipse({ x, y }, r, r), &e); return e;+}+// nuvem do SF Symbols: três bolhas sobre uma base arredondada (s = tamanho do símbolo)+ID2D1Geometry* Cloud(ID2D1Factory* f, float cx, float cy, float s) {+ ID2D1RoundedRectangleGeometry* rr = nullptr;+ f->CreateRoundedRectangleGeometry(D2D1::RoundedRect(D2D1::RectF(cx - 0.40f * s, cy + 0.02f * s, cx + 0.44f * s, cy + 0.25f * s), 0.115f * s, 0.115f * s), &rr);+ ID2D1Geometry* g = Combine(f, Circle(f, cx - 0.19f * s, cy + 0.05f * s, 0.20f * s), Circle(f, cx + 0.04f * s, cy - 0.06f * s, 0.27f * s), D2D1_COMBINE_MODE_UNION);+ g = Combine(f, g, Circle(f, cx + 0.26f * s, cy + 0.08f * s, 0.17f * s), D2D1_COMBINE_MODE_UNION);+ return Combine(f, g, rr, D2D1_COMBINE_MODE_UNION);+}+ID2D1Geometry* Moon(ID2D1Factory* f, float cx, float cy, float s) {+ return Combine(f, Circle(f, cx, cy, 0.32f * s), Circle(f, cx + 0.19f * s, cy - 0.13f * s, 0.27f * s), D2D1_COMBINE_MODE_EXCLUDE);+}++void Sun(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, ID2D1StrokeStyle* st, float cx, float cy, float s, D2D1_COLOR_F c) {+ br->SetColor(c);+ dc->FillEllipse(D2D1::Ellipse({ cx, cy }, 0.2f * s, 0.2f * s), br);+ for (int i = 0; i < 8; i++) {+ float a = i * PI / 4, dx = std::sin(a), dy = -std::cos(a);+ dc->DrawLine({ cx + dx * 0.31f * s, cy + dy * 0.31f * s }, { cx + dx * 0.44f * s, cy + dy * 0.44f * s }, br, 0.075f * s, st);+ }+}++// símbolos do tempo no estilo multicolorido do SF Symbols (mono: tudo branco, para o vidro do modo escuro)+void DrawIcon(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, Icon ic, float cx, float cy, float s, bool mono) {+ ID2D1Factory* f = nullptr; dc->GetFactory(&f);+ if (!f) return;+ ID2D1StrokeStyle* st = RoundCaps(dc);+ D2D1_COLOR_F yellow = mono ? WHITE : C(1, 0.84f, 0.04f), drop = mono ? WHITE : C(0.39f, 0.78f, 1), cloud = WHITE;+ auto fill = [&](ID2D1Geometry* g, D2D1_COLOR_F c) { if (g) { br->SetColor(c); dc->FillGeometry(g, br); g->Release(); } };+ float ccy = cy - 0.12f * s; // nuvem mais alta quando tem algo caindo embaixo+ switch (ic) {+ case I_SUN: Sun(dc, br, st, cx, cy, s, yellow); break;+ case I_MOON: fill(Moon(f, cx, cy, s), WHITE); break;+ case I_PARTLY:+ Sun(dc, br, st, cx - 0.14f * s, cy - 0.14f * s, 0.78f * s, yellow);+ fill(Cloud(f, cx + 0.08f * s, cy + 0.06f * s, 0.82f * s), cloud);+ break;+ case I_PARTLY_NIGHT:+ fill(Moon(f, cx - 0.14f * s, cy - 0.16f * s, 0.72f * s), WHITE);+ fill(Cloud(f, cx + 0.08f * s, cy + 0.06f * s, 0.82f * s), cloud);+ break;+ case I_CLOUD: fill(Cloud(f, cx, cy, s), cloud); break;+ case I_FOG:+ fill(Cloud(f, cx, cy - 0.1f * s, 0.88f * s), cloud);+ br->SetColor(C(1, 1, 1, mono ? 1 : 0.85f));+ dc->DrawLine({ cx - 0.36f * s, cy + 0.28f * s }, { cx + 0.36f * s, cy + 0.28f * s }, br, 0.07f * s, st);+ dc->DrawLine({ cx - 0.26f * s, cy + 0.40f * s }, { cx + 0.30f * s, cy + 0.40f * s }, br, 0.07f * s, st);+ break;+ case I_DRIZZLE: case I_RAIN: case I_SNOW: case I_THUNDER: {+ fill(Cloud(f, cx, ccy, 0.92f * s), cloud);+ br->SetColor(ic == I_SNOW ? WHITE : drop);+ if (ic == I_THUNDER) {+ ID2D1PathGeometry* p = nullptr;+ if (SUCCEEDED(f->CreatePathGeometry(&p))) {+ ID2D1GeometrySink* sk = nullptr; p->Open(&sk);+ D2D1_POINT_2F pts[] = { { cx + 0.02f * s, cy + 0.12f * s }, { cx - 0.12f * s, cy + 0.33f * s }, { cx - 0.01f * s, cy + 0.33f * s },+ { cx - 0.06f * s, cy + 0.50f * s }, { cx + 0.12f * s, cy + 0.26f * s }, { cx + 0.01f * s, cy + 0.26f * s } };+ sk->BeginFigure(pts[0], D2D1_FIGURE_BEGIN_FILLED); sk->AddLines(pts + 1, 5); sk->EndFigure(D2D1_FIGURE_END_CLOSED);+ sk->Close(); sk->Release();+ br->SetColor(yellow); dc->FillGeometry(p, br); p->Release();+ }+ break;+ }+ for (int i = -1; i <= 1; i++) {+ float x = cx + i * 0.19f * s, y = cy + 0.22f * s;+ if (ic == I_RAIN) dc->DrawLine({ x + 0.04f * s, y }, { x - 0.04f * s, y + 0.2f * s }, br, 0.075f * s, st);+ else if (ic == I_DRIZZLE) { dc->FillEllipse(D2D1::Ellipse({ x, y + 0.06f * s }, 0.045f * s, 0.045f * s), br); dc->FillEllipse(D2D1::Ellipse({ x - 0.04f * s, y + 0.2f * s }, 0.045f * s, 0.045f * s), br); }+ else dc->FillEllipse(D2D1::Ellipse({ x, y + 0.12f * s + (i == 0 ? 0.06f * s : 0) }, 0.06f * s, 0.06f * s), br);+ }+ break;+ }+ }+ if (st) st->Release();+ f->Release();+}++ID2D1LinearGradientBrush* Gradient(ID2D1DeviceContext* dc, float y0, float y1, D2D1_COLOR_F a, D2D1_COLOR_F b) {+ D2D1_GRADIENT_STOP stops[] = { { 0, a }, { 1, b } };+ ID2D1GradientStopCollection* sc = nullptr; ID2D1LinearGradientBrush* lb = nullptr;+ dc->CreateGradientStopCollection(stops, 2, &sc);+ if (sc) { dc->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, y0 }, { 0, y1 }), sc, &lb); sc->Release(); }+ return lb;+}+// céu do app Tempo: azul de dia, noite escura, cinza com nuvem ou chuva+void Sky(ID2D1DeviceContext* dc, float w, float h, int code, bool day) {+ D2D1_COLOR_F a, b;+ bool rain = code >= 51, cloudy = code == 3 || code == 45 || code == 48;+ if (day) {+ if (rain) { a = C(0.29f, 0.35f, 0.43f); b = C(0.45f, 0.51f, 0.59f); }+ else if (cloudy) { a = C(0.40f, 0.49f, 0.60f); b = C(0.58f, 0.66f, 0.75f); }+ else { a = C(0.16f, 0.40f, 0.74f); b = C(0.36f, 0.60f, 0.88f); }+ } else {+ if (rain || cloudy) { a = C(0.12f, 0.14f, 0.19f); b = C(0.24f, 0.27f, 0.33f); }+ else { a = C(0.03f, 0.06f, 0.16f); b = C(0.12f, 0.19f, 0.35f); }+ }+ if (auto* lb = Gradient(dc, 0, h, a, b)) { dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(0, 0, w, h), WidgetRadius(), WidgetRadius()), lb); lb->Release(); }+}++// mostrador analógico (relógio e relógio mundial)+// Tahoe, "Estilo de ícones e widgets" Transparente ou Tingido (macOS 26): o widget vira vidro claro e tudo por cima+// fica branco — os mostradores também (anel translúcido, ponteiros e números brancos)+bool g_vidroWidgets;+void Face(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, ID2D1StrokeStyle* st, float cx, float cy, float R,+ D2D1_COLOR_F face, D2D1_COLOR_F ink, float numSize, bool ticks, const SYSTEMTIME& t) {+ if (g_vidroWidgets) { face = C(1, 1, 1, 0.14f); ink = WHITE; }+ br->SetColor(face);+ dc->FillEllipse(D2D1::Ellipse({ cx, cy }, R, R), br);+ if (ticks) {+ D2D1_COLOR_F tc = ink; tc.a *= 0.35f; br->SetColor(tc);+ for (int i = 0; i < 60; i++) {+ if (i % 5 == 0) continue;+ float a = i * PI / 30, dx = std::sin(a), dy = -std::cos(a);+ dc->DrawLine({ cx + dx * R * 0.93f, cy + dy * R * 0.93f }, { cx + dx * R * 0.97f, cy + dy * R * 0.97f }, br, std::max(0.8f, R * 0.012f));+ }+ }+ float nr = R * (ticks ? 0.79f : 0.74f);+ for (int i = 1; i <= 12; i++) {+ float a = i * PI / 6, x = cx + std::sin(a) * nr, y = cy - std::cos(a) * nr;+ Txt(dc, br, std::to_wstring(i), numSize, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER,+ D2D1::RectF(x - numSize, y - numSize * 0.75f, x + numSize, y + numSize * 0.75f), ink);+ }+ float sec = t.wSecond + t.wMilliseconds / 1000.f;+ float mn = t.wMinute + sec / 60, hr = (t.wHour % 12) + mn / 60;+ auto hand = [&](float frac, float from, float to, float width) {+ float a = frac * 2 * PI, dx = std::sin(a), dy = -std::cos(a);+ dc->DrawLine({ cx + dx * from, cy + dy * from }, { cx + dx * to, cy + dy * to }, br, width, st);+ };+ br->SetColor(ink);+ hand(hr / 12, 0, R * 0.14f, std::max(1.2f, R * 0.028f));+ hand(hr / 12, R * 0.14f, R * 0.50f, R * 0.075f);+ hand(mn / 60, 0, R * 0.14f, std::max(1.2f, R * 0.028f));+ hand(mn / 60, R * 0.14f, R * 0.84f, R * 0.075f);+ dc->FillEllipse(D2D1::Ellipse({ cx, cy }, R * 0.06f, R * 0.06f), br);+ br->SetColor(ORANGE);+ hand(sec / 60, -R * 0.16f, R * 0.90f, std::max(1.f, R * 0.018f));+ dc->FillEllipse(D2D1::Ellipse({ cx, cy }, R * 0.045f, R * 0.045f), br);+ br->SetColor(face);+ dc->FillEllipse(D2D1::Ellipse({ cx, cy }, R * 0.017f, R * 0.017f), br);+}++// ---------------------------------------------------------------- relógio mundial+struct CityTz { std::wstring name, tz; };+std::vector<CityTz> Cities() {+ // ajustes.txt: relogioCidades=Cupertino|Pacific Standard Time;Tóquio|Tokyo Standard Time;...+ std::wstring s = shell::Setting(L"relogioCidades",+ L"Cupertino|Pacific Standard Time;Tóquio|Tokyo Standard Time;Sydney|AUS Eastern Standard Time;Paris|Romance Standard Time");+ std::vector<CityTz> v;+ size_t p = 0;+ while (p < s.size() && v.size() < 4) {+ size_t e = s.find(L';', p); if (e == std::wstring::npos) e = s.size();+ std::wstring item = s.substr(p, e - p);+ size_t bar = item.find(L'|');+ if (bar != std::wstring::npos) v.push_back({ item.substr(0, bar), item.substr(bar + 1) });+ p = e + 1;+ }+ return v;+}+bool TimeIn(const std::wstring& key, const SYSTEMTIME& utc, SYSTEMTIME& out) {+ static std::map<std::wstring, DYNAMIC_TIME_ZONE_INFORMATION> cache;+ auto it = cache.find(key);+ if (it == cache.end()) {+ DYNAMIC_TIME_ZONE_INFORMATION d{};+ for (DWORD i = 0; EnumDynamicTimeZoneInformation(i, &d) == ERROR_SUCCESS; i++)+ if (!_wcsicmp(d.TimeZoneKeyName, key.c_str())) { it = cache.emplace(key, d).first; break; }+ if (it == cache.end()) return false;+ }+ return SystemTimeToTzSpecificLocalTimeEx(&it->second, &utc, &out) != FALSE;+}+long long Minutes(const SYSTEMTIME& t) { FILETIME f; SystemTimeToFileTime(&t, &f); return (long long)(((ULONGLONG)f.dwHighDateTime << 32 | f.dwLowDateTime) / 600000000ULL); }++void PaintWorld(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, ID2D1StrokeStyle* st, float w, float h, bool dark) {+ if (!dark) { br->SetColor(C(0.11f, 0.11f, 0.118f)); dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(0, 0, w, h), WidgetRadius(), WidgetRadius()), br); }+ SYSTEMTIME utc, local; GetSystemTime(&utc); GetLocalTime(&local);+ long long lm = Minutes(local);+ auto cities = Cities();+ float col = w / 4;+ for (size_t i = 0; i < cities.size(); i++) {+ SYSTEMTIME t;+ if (!TimeIn(cities[i].tz, utc, t)) continue;+ t.wMilliseconds = local.wMilliseconds;+ float cx = col * (i + 0.5f);+ bool night = t.wHour < 6 || t.wHour >= 18;+ D2D1_COLOR_F face, ink;+ if (dark) { face = night ? C(0, 0, 0, 0.30f) : C(1, 1, 1, 0.88f); ink = night ? WHITE : C(0, 0, 0); }+ else { face = night ? C(0.23f, 0.23f, 0.24f) : WHITE; ink = night ? WHITE : C(0, 0, 0); }+ Face(dc, br, st, cx, 60, 33, face, ink, 8.5f, false, t);+ Txt(dc, br, Tr(cities[i].name), 12.5f, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(cx - col / 2, 99, cx + col / 2, 117), WHITE);+ long long diff = Minutes(t) - lm; // em minutos+ int dayDiff = (int)((t.wYear * 10000 + t.wMonth * 100 + t.wDay) > (local.wYear * 10000 + local.wMonth * 100 + local.wDay)) -+ (int)((t.wYear * 10000 + t.wMonth * 100 + t.wDay) < (local.wYear * 10000 + local.wMonth * 100 + local.wDay));+ D2D1_COLOR_F sub = C(1, 1, 1, 0.55f);+ Txt(dc, br, dayDiff > 0 ? Tr(L"Amanhã") : dayDiff < 0 ? Tr(L"Ontem") : Tr(L"Hoje"), 10, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_TEXT_ALIGNMENT_CENTER,+ D2D1::RectF(cx - col / 2, 117, cx + col / 2, 132), sub);+ long long ad = diff < 0 ? -diff : diff;+ wchar_t b[24];+ if (ad % 60) swprintf_s(b, L"%ls%lld:%02lld H", diff < 0 ? L"−" : L"+", ad / 60, ad % 60);+ else swprintf_s(b, L"%ls%lld H", diff < 0 ? L"−" : L"+", ad / 60);+ Txt(dc, br, b, 10, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(cx - col / 2, 131, cx + col / 2, 146), sub);+ }+}++// ---------------------------------------------------------------- tempo+void PaintWeather(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, float w, float h, bool dark) {+ Weather wx; { std::lock_guard<std::mutex> lk(g_mx); wx = g_wx; }+ if (!dark) Sky(dc, w, h, wx.ok ? wx.code : 0, wx.ok ? wx.day : true);+ std::wstring city = City();+ Txt(dc, br, city, 15, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING, D2D1::RectF(17, 12, 250, 32), WHITE);+ { // seta de localização (location.fill)+ float x = 17 + Width(city, 15, DWRITE_FONT_WEIGHT_SEMI_BOLD) + 5, y = 22;+ ID2D1Factory* f = nullptr; dc->GetFactory(&f);+ ID2D1PathGeometry* p = nullptr;+ if (f && SUCCEEDED(f->CreatePathGeometry(&p))) {+ ID2D1GeometrySink* sk = nullptr; p->Open(&sk);+ D2D1_POINT_2F pts[] = { { x + 9, y - 5 }, { x + 5, y + 5 }, { x + 4, y + 1 }, { x, y } };+ sk->BeginFigure(pts[0], D2D1_FIGURE_BEGIN_FILLED); sk->AddLines(pts + 1, 3); sk->EndFigure(D2D1_FIGURE_END_CLOSED);+ sk->Close(); sk->Release();+ br->SetColor(WHITE); dc->FillGeometry(p, br); p->Release();+ }+ if (f) f->Release();+ }+ wchar_t b[64];+ if (wx.ok) swprintf_s(b, L"%ld°", lround(wx.temp)); else wcscpy_s(b, L"--°");+ Txt(dc, br, b, 44, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING, D2D1::RectF(14, 32, 200, 86), WHITE, true);+ if (!wx.ok) {+ Txt(dc, br, Tr(L"Buscando o tempo…"), 13, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(0, 110, w, 140), C(1, 1, 1, 0.7f));+ return;+ }+ DrawIcon(dc, br, IconOf(wx.code, wx.day), w - 26, 24, 22, dark);+ Txt(dc, br, ConditionOf(wx.code, wx.day), 13, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_TRAILING, D2D1::RectF(120, 38, w - 17, 56), WHITE);+ swprintf_s(b, Tr(L"Máx.: %ld° Mín.: %ld°"), lround(wx.hi), lround(wx.lo));+ Txt(dc, br, b, 13, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_TRAILING, D2D1::RectF(120, 57, w - 17, 75), WHITE);+ // próximas 6 horas+ double now = (double)time(nullptr);+ size_t first = 0;+ while (first < wx.hours.size() && wx.hours[first].t <= now) first++;+ float pitch = (w - 34) / 6;+ for (int i = 0; i < 6 && first + i < wx.hours.size(); i++) {+ auto& hr = wx.hours[first + i];+ float cx = 17 + pitch * (i + 0.5f);+ swprintf_s(b, L"%dh", LocalMinuteOfDay(hr.t, wx.utcOffset) / 60);+ Txt(dc, br, b, 11, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(cx - 30, 92, cx + 30, 108), C(1, 1, 1, 0.75f));+ DrawIcon(dc, br, IconOf(hr.code, hr.day), cx, 125, 21, dark);+ swprintf_s(b, L"%ld°", lround(hr.temp));+ Txt(dc, br, b, 13, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(cx - 30, 144, cx + 30, 162), WHITE);+ }+}++// ---------------------------------------------------------------- relógio+void PaintClock(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, ID2D1StrokeStyle* st, float w, float h, bool dark) {+ SYSTEMTIME t; GetLocalTime(&t);+ Face(dc, br, st, w / 2, h / 2, 75, dark ? C(0.07f, 0.07f, 0.08f, 0.92f) : WHITE, dark ? WHITE : C(0, 0, 0), 20, true, t);+}++// ---------------------------------------------------------------- calendário+void PaintCalendar(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, float w, float h, bool dark) {+ if (!dark) { br->SetColor(WHITE); dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(0, 0, w, h), WidgetRadius(), WidgetRadius()), br); }+ static const wchar_t* months[] = { L"JANEIRO", L"FEVEREIRO", L"MARÇO", L"ABRIL", L"MAIO", L"JUNHO", L"JULHO", L"AGOSTO", L"SETEMBRO", L"OUTUBRO", L"NOVEMBRO", L"DEZEMBRO" };+ SYSTEMTIME t; GetLocalTime(&t);+ Txt(dc, br, Tr(months[t.wMonth - 1]), 11, DWRITE_FONT_WEIGHT_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING, D2D1::RectF(16, 16, w, 33), RED);+ SYSTEMTIME f = t; f.wDay = 1; f.wHour = 12; FILETIME ft; SystemTimeToFileTime(&f, &ft); FileTimeToSystemTime(&ft, &f);+ int startDow = f.wDayOfWeek;+ static const int dim[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };+ int days = dim[t.wMonth - 1] + (t.wMonth == 2 && ((t.wYear % 4 == 0 && t.wYear % 100) || t.wYear % 400 == 0));+ int rows = (startDow + days + 6) / 7;+ D2D1_COLOR_F ink = dark ? WHITE : C(0, 0, 0), weekend = dark ? C(1, 1, 1, 0.45f) : C(0, 0, 0, 0.40f);+ const wchar_t* heads = idioma::En() ? L"SMTWTFS" : L"DSTQQSS";+ float pitchX = 21.2f, x0 = 21, top = 44, pitchY = rows > 5 ? 17 : 19.8f;+ for (int c = 0; c < 7; c++) {+ wchar_t s[2] = { heads[c], 0 };+ Txt(dc, br, s, 10, DWRITE_FONT_WEIGHT_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(x0 + c * pitchX - 10, top - 8, x0 + c * pitchX + 10, top + 8),+ dark ? C(1, 1, 1, 0.55f) : C(0, 0, 0, 0.45f));+ }+ for (int d = 1; d <= days; d++) {+ int cell = startDow + d - 1, c = cell % 7, r = cell / 7;+ float cx = x0 + c * pitchX, cy = top + 20 + r * pitchY;+ bool today = d == t.wDay;+ if (today) { br->SetColor(RED); dc->FillEllipse(D2D1::Ellipse({ cx, cy }, 9, 9), br); }+ Txt(dc, br, std::to_wstring(d), 11, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_CENTER, D2D1::RectF(cx - 11, cy - 8, cx + 11, cy + 8),+ today ? WHITE : (c == 0 || c == 6) ? weekend : ink);+ }+}++// ---------------------------------------------------------------- nascer e pôr do sol+void PaintSun(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, ID2D1StrokeStyle* st, float w, float h, bool dark) {+ Weather wx; { std::lock_guard<std::mutex> lk(g_mx); wx = g_wx; }+ if (!dark) Sky(dc, w, h, 0, wx.ok ? wx.day : true);+ double now = (double)time(nullptr);+ bool toSunset = false; double ev = 0, other = 0;+ if (wx.ok) {+ if (now < wx.sunrise[0]) { ev = wx.sunrise[0]; other = wx.sunset[0]; }+ else if (now < wx.sunset[0]) { toSunset = true; ev = wx.sunset[0]; other = wx.sunrise[1]; }+ else { ev = wx.sunrise[1]; other = wx.sunset[1]; }+ }+ // cabeçalho+ float hx = 16;+ Sun(dc, br, st, hx + 6, 22, 13, WHITE);+ Txt(dc, br, toSunset ? Tr(L"PÔR DO SOL") : Tr(L"NASCER DO SOL"), 11, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING,+ D2D1::RectF(hx + 16, 14, w, 30), C(1, 1, 1, 0.92f));+ Txt(dc, br, wx.ok ? HourMin(ev, wx.utcOffset) : L"--:--", 30, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_TEXT_ALIGNMENT_LEADING,+ D2D1::RectF(hx - 1, 32, w, 68), WHITE, true);+ // curva do dia: meia-noite embaixo, meio-dia em cima; a linha do horizonte passa no nascer do sol+ float cy = 104, A = 18;+ auto yOf = [&](float u) { return cy + A * std::cos(2 * PI * u); };+ float horizon = wx.ok ? yOf(LocalMinuteOfDay(wx.sunrise[0], wx.utcOffset) / 1440.f) : cy;+ br->SetColor(C(1, 1, 1, 0.35f));+ dc->DrawLine({ 0, horizon }, { w, horizon }, br, 1);+ ID2D1Factory* f = nullptr; dc->GetFactory(&f);+ for (int pass = 0; pass < 2 && f; pass++) { // abaixo do horizonte apagada, acima clara+ ID2D1PathGeometry* p = nullptr;+ if (FAILED(f->CreatePathGeometry(&p))) break;+ ID2D1GeometrySink* sk = nullptr; p->Open(&sk);+ sk->BeginFigure({ 0, yOf(0) }, D2D1_FIGURE_BEGIN_HOLLOW);+ for (int i = 1; i <= 96; i++) sk->AddLine({ w * i / 96.f, yOf(i / 96.f) });+ sk->EndFigure(D2D1_FIGURE_END_OPEN); sk->Close(); sk->Release();+ D2D1_RECT_F clip = pass == 0 ? D2D1::RectF(0, horizon, w, h) : D2D1::RectF(0, 0, w, horizon);+ dc->PushAxisAlignedClip(clip, D2D1_ANTIALIAS_MODE_ALIASED);+ br->SetColor(C(1, 1, 1, pass == 0 ? 0.30f : 0.85f));+ dc->DrawGeometry(p, br, 2, st);+ dc->PopAxisAlignedClip();+ p->Release();+ }+ if (f) f->Release();+ if (wx.ok) {+ float u = LocalMinuteOfDay(now, wx.utcOffset) / 1440.f, x = w * u, y = yOf(u);+ br->SetColor(C(1, 1, 1, 0.25f)); dc->FillEllipse(D2D1::Ellipse({ x, y }, 8, 8), br);+ br->SetColor(WHITE); dc->FillEllipse(D2D1::Ellipse({ x, y }, 5, 5), br);+ std::wstring bottom = std::wstring(toSunset ? Tr(L"Nascer do sol: ") : Tr(L"Pôr do sol: ")) + HourMin(other, wx.utcOffset);+ Txt(dc, br, bottom, 11, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_TEXT_ALIGNMENT_LEADING, D2D1::RectF(hx, 138, w, 156), C(1, 1, 1, 0.85f));+ }+}++// ---------------------------------------------------------------- janelas+void Paint(Widget& wd) {+ if (!wd.on || !wd.wnd) return;+ float sc = ui::Scale(wd.wnd);+ int wpx = (int)std::lround(wd.w * sc), hpx = (int)std::lround(wd.h * sc);+ auto* dc = ui::GpuBegin(wd.s, wpx, hpx, sc);+ if (!dc) return;+ ID2D1SolidColorBrush* br = nullptr;+ dc->CreateSolidColorBrush(WHITE, &br);+ ID2D1StrokeStyle* st = RoundCaps(dc);+ std::wstring est = ui::IconStyle(); // Tahoe/Golden Gate: Aparência > Estilo de ícones e widgets (Escuro "Auto" incluído)+ g_vidroWidgets = est == L"transparente" || est == L"tingido";+ bool dark = g_dark || g_vidroWidgets; // vidro: o conteúdo em branco, como no modo escuro+ if (br) {+ switch (wd.kind) {+ case K_WORLD: PaintWorld(dc, br, st, wd.w, wd.h, dark); break;+ case K_WEATHER: PaintWeather(dc, br, wd.w, wd.h, dark); break;+ case K_CLOCK: PaintClock(dc, br, st, wd.w, wd.h, dark); break;+ case K_CALENDAR: PaintCalendar(dc, br, wd.w, wd.h, dark); break;+ case K_SUN: PaintSun(dc, br, st, wd.w, wd.h, dark); break;+ }+ if (liquid::On()) liquid::Rim(dc, D2D1::RectF(0, 0, wd.w, wd.h), WidgetRadius(), dark, 0.9f); // Tahoe: contorno especular+ else if (dark) { // borda clarinha do vidro+ br->SetColor(C(1, 1, 1, 0.10f));+ dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(0.5f, 0.5f, wd.w - 0.5f, wd.h - 0.5f), WidgetRadius() - 0.5f, WidgetRadius() - 0.5f), br, 1);+ }+ br->Release();+ }+ if (st) st->Release();+ ui::GpuEnd(wd.s);+ D2D1_COLOR_F tint = dark ? C(0.10f, 0.10f, 0.11f, 0.38f)+ : wd.kind == K_CLOCK ? C(0.96f, 0.95f, 1.0f, 0.30f) : C(1, 1, 1, 0);+ if (g_vidroWidgets) { // vidro claro (Transparente) ou na cor de destaque (Tingido), o papel de parede aparece+ if (est == L"tingido") { D2D1_COLOR_F a = ui::Accent(); tint = C(a.r, a.g, a.b, 0.42f); }+ else tint = C(1, 1, 1, g_dark ? 0.12f : 0.22f);+ }+ if (wd.glass) backdrop::Set(wd.back, (float)wpx, (float)hpx, WidgetRadius() * sc, tint);+}++void PaintAll() { for (auto& w : g_w) Paint(w); }++// a janela mais alta da área de trabalho (Progman / WorkerW): os widgets ficam logo acima dela+HWND DesktopTop() {+ for (HWND w = GetTopWindow(nullptr); w; w = GetWindow(w, GW_HWNDNEXT)) {+ wchar_t c[32] = {}; GetClassNameW(w, c, 32);+ if (mesa::IsDeskClass(c) && IsWindowVisible(w)) return w;+ }+ return nullptr;+}+bool IsOurs(HWND h) { if (h && h == g_ghost) return true; for (auto& w : g_w) if (w.wnd == h || w.back == h) return true; return false; }++void PlaceAtDesktop(Widget& wd) {+ HWND desk = DesktopTop();+ HWND above = desk ? GetWindow(desk, GW_HWNDPREV) : nullptr;+ while (above && IsOurs(above)) above = GetWindow(above, GW_HWNDPREV); // acima dos outros widgets também+ g_placing = true;+ SetWindowPos(wd.wnd, above ? above : HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);+ SetWindowPos(wd.back, wd.wnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);+ g_placing = false;+}+// alguém (o Explorer, "mostrar a mesa") pôs a mesa por cima dos widgets?+bool BelowDesktop(const Widget& wd) {+ for (HWND w = GetTopWindow(nullptr); w; w = GetWindow(w, GW_HWNDNEXT)) {+ if (w == wd.wnd) return false;+ wchar_t c[32] = {}; GetClassNameW(w, c, 32);+ if (mesa::IsDeskClass(c) && IsWindowVisible(w)) return true;+ }+ return false;+}++// ---------------------------------------------------------------- grade+// Como no Mac: os widgets se encaixam em casas de 170 pt com 16 pt entre elas, contadas a partir do canto+// superior direito da tela (o médio ocupa duas casas). Arrastando, uma sombra mostra a casa livre mais perto+// e desliza até ela; ao soltar, o widget vai para a casa com a mola do sistema.+const float PITCH = SMALL + GAP;+const float SPRING_RESPONSE = 0.40f, SPRING_DAMPING = 0.86f;+const UINT WM_WG_FRAME = WM_APP + 61;++struct Grid { float left, top, right, bottom, sc; };+Grid GridNow(HWND h) {+ MONITORINFO mi{ sizeof(mi) };+ GetMonitorInfoW(MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY), &mi);+ float sc = ui::Scale(h);+ RECT r = shell::WorkAreaFor(MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)); // a do Shell (issue #1)+ return { r.left / sc, r.top / sc, r.right / sc, r.bottom / sc, sc };+}+int Cols(const Widget& w) { return w.w > SMALL + 1 ? 2 : 1; }+int MaxRc(const Grid& g, const Widget& w) { return std::max(0, (int)std::floor((g.right - g.left - 2 * MARGIN - w.w) / PITCH)); }+int MaxRow(const Grid& g, const Widget& w) { return std::max(0, (int)std::floor((g.bottom - g.top - 2 * MARGIN - w.h) / PITCH)); }+POINT CellPx(const Grid& g, const Widget& w, int rc, int row) { // rc: casa da borda direita do widget, contando da direita+ float x = g.right - MARGIN - w.w - rc * PITCH, y = g.top + MARGIN + row * PITCH;+ return { (LONG)std::lround(x * g.sc), (LONG)std::lround(y * g.sc) };+}+bool Overlaps(const Widget& w, int rc, int row) {+ int a0 = rc, a1 = rc + Cols(w) - 1;+ for (auto& o : g_w) {+ if (&o == &w || !o.on || o.rc < 0 || o.row != row) continue;+ int b0 = o.rc, b1 = o.rc + Cols(o) - 1;+ if (a0 <= b1 && b0 <= a1) return true;+ }+ return false;+}+// a casa livre mais perto de px (canto superior esquerdo do widget, em px)+void Nearest(const Grid& g, const Widget& w, POINT px, int& rc, int& row) {+ double best = 1e300; rc = 0; row = 0;+ for (int r = 0; r <= MaxRow(g, w); r++)+ for (int c = 0; c <= MaxRc(g, w); c++) {+ if (Overlaps(w, c, r)) continue;+ POINT p = CellPx(g, w, c, r);+ double dx = p.x - px.x, dy = p.y - px.y, d = dx * dx + dy * dy;+ if (d < best) { best = d; rc = c; row = r; }+ }+}+void DefaultCell(const Widget& wd, int& rc, int& row) {+ switch (wd.kind) {+ case K_WEATHER: rc = 0; row = 0; break;+ case K_WORLD: rc = 2; row = 0; break;+ case K_CLOCK: rc = 1; row = 1; break;+ case K_CALENDAR: rc = 0; row = 1; break;+ case K_SUN: rc = 2; row = 1; break;+ }+}++void MoveWin(Widget& w, int x, int y) {+ g_placing = true;+ HDWP d = BeginDeferWindowPos(2);+ if (d) d = DeferWindowPos(d, w.back, nullptr, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);+ if (d) d = DeferWindowPos(d, w.wnd, nullptr, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);+ if (d) EndDeferWindowPos(d);+ g_placing = false;+}++// animações de encaixe+struct Move { Widget* w; POINT from, to; double t0; };+std::vector<Move> g_moves;+// sombra da casa de destino enquanto arrasta+ui::Surface g_ghostS;+double g_gx, g_gy, g_lastFrame; POINT g_ghostTo; int g_targetRc = -1, g_targetRow = -1;++void Animate(bool on) { ui::FrameClock(g_timer, WM_WG_FRAME, on); g_lastFrame = anim::Now(); }++void AnimateTo(Widget& w, POINT to) {+ RECT r; GetWindowRect(w.wnd, &r);+ g_moves.erase(std::remove_if(g_moves.begin(), g_moves.end(), [&](const Move& m) { return m.w == &w; }), g_moves.end());+ if (r.left == to.x && r.top == to.y) return;+ g_moves.push_back({ &w, { r.left, r.top }, to, anim::Now() });+ Animate(true);+}++void PaintGhost(const Widget& w) {+ float sc = ui::Scale(w.wnd);+ int wpx = (int)std::lround(w.w * sc), hpx = (int)std::lround(w.h * sc);+ auto* rt = ui::Begin(g_ghostS, wpx, hpx, sc);+ if (!rt) return;+ rt->Clear(D2D1::ColorF(0, 0, 0, 0));+ ID2D1SolidColorBrush* br = nullptr;+ rt->CreateSolidColorBrush(C(1, 1, 1, g_dark ? 0.10f : 0.22f), &br);+ if (br) {+ auto rr = D2D1::RoundedRect(D2D1::RectF(1, 1, w.w - 1, w.h - 1), WidgetRadius() - 1, WidgetRadius() - 1);+ rt->FillRoundedRectangle(rr, br);+ br->SetColor(C(1, 1, 1, g_dark ? 0.30f : 0.55f));+ rt->DrawRoundedRectangle(rr, br, 1.5f);+ br->Release();+ }+ ui::End(g_ghostS, true, { (LONG)g_gx, (LONG)g_gy });+}++void Frame() {+ double now = anim::Now();+ static float dur = anim::SpringDuration(SPRING_RESPONSE, SPRING_DAMPING);+ for (size_t i = 0; i < g_moves.size();) {+ auto& m = g_moves[i];+ float t = (float)((now - m.t0) / 1000.0);+ if (t >= dur) { MoveWin(*m.w, m.to.x, m.to.y); g_moves.erase(g_moves.begin() + i); continue; }+ float p = anim::Spring(t, SPRING_RESPONSE, SPRING_DAMPING);+ MoveWin(*m.w, (int)std::lround(m.from.x + (m.to.x - m.from.x) * p), (int)std::lround(m.from.y + (m.to.y - m.from.y) * p));+ i++;+ }+ if (g_ghost && IsWindowVisible(g_ghost)) { // a sombra segue a casa de destino, suave (sem degrau)+ double dt = std::min(50.0, now - g_lastFrame), k = 1 - std::exp(-dt / 55.0);+ g_gx += (g_ghostTo.x - g_gx) * k; g_gy += (g_ghostTo.y - g_gy) * k;+ SetWindowPos(g_ghost, nullptr, (int)std::lround(g_gx), (int)std::lround(g_gy), 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);+ if (!g_dragging && std::fabs(g_ghostTo.x - g_gx) < 0.5 && std::fabs(g_ghostTo.y - g_gy) < 0.5 && g_moves.empty()) ShowWindow(g_ghost, SW_HIDE);+ }+ g_lastFrame = now;+ if (g_moves.empty() && !g_dragging && !(g_ghost && IsWindowVisible(g_ghost))) Animate(false);+}++void SaveCell(const Widget& w) {+ wchar_t b[32]; swprintf_s(b, L"g:%d,%d", w.rc, w.row);+ shell::SetSetting((std::wstring(L"widget.") + w.id).c_str(), b);+}++void Position(Widget& wd, bool reset, bool animate = false) {+ Grid g = GridNow(wd.wnd);+ int rc = -1, row = -1, a, b;+ std::wstring saved = reset ? L"" : shell::Setting((std::wstring(L"widget.") + wd.id).c_str(), L"");+ wd.rc = -1;+ if (!saved.empty() && swscanf_s(saved.c_str(), L"g:%d,%d", &a, &b) == 2) { rc = a; row = b; }+ else if (!saved.empty() && swscanf_s(saved.c_str(), L"%d,%d", &a, &b) == 2) Nearest(g, wd, { a, b }, rc, row); // posição antiga, em px+ else DefaultCell(wd, rc, row);+ rc = std::clamp(rc, 0, MaxRc(g, wd)); row = std::clamp(row, 0, MaxRow(g, wd));+ if (Overlaps(wd, rc, row)) Nearest(g, wd, CellPx(g, wd, rc, row), rc, row);+ wd.rc = rc; wd.row = row;+ POINT p = CellPx(g, wd, rc, row);+ int wpx = (int)std::lround(wd.w * g.sc), hpx = (int)std::lround(wd.h * g.sc);+ g_placing = true;+ UINT fl = SWP_NOZORDER | SWP_NOACTIVATE | (animate ? SWP_NOMOVE : 0);+ SetWindowPos(wd.back, nullptr, p.x, p.y, wpx, hpx, fl);+ SetWindowPos(wd.wnd, nullptr, p.x, p.y, wpx, hpx, fl);+ g_placing = false;+ if (animate) AnimateTo(wd, p);+}++void Show(Widget& wd, bool on) {+ wd.on = on;+ if (!on) wd.rc = -1; // a casa fica livre+ if (on) {+ Position(wd, false);+ ShowWindow(wd.back, SW_SHOWNOACTIVATE);+ ShowWindow(wd.wnd, SW_SHOWNOACTIVATE);+ PlaceAtDesktop(wd);+ Paint(wd);+ } else {+ ShowWindow(wd.wnd, SW_HIDE);+ ShowWindow(wd.back, SW_HIDE);+ }+}++Widget* Of(HWND h) { for (auto& w : g_w) if (w.wnd == h || w.back == h) return &w; return nullptr; }++void Click(Widget& wd) {+ const wchar_t* target = nullptr;+ std::wstring url;+ switch (wd.kind) {+ case K_WEATHER: case K_SUN: {+ url = L"https://www.google.com/search?q=tempo+" + City();+ for (auto& c : url) if (c == L' ') c = L'+';+ target = url.c_str(); break;+ }+ case K_CLOCK: case K_WORLD: target = L"ms-clock:"; break;+ case K_CALENDAR: target = L"outlookcal:"; break;+ }+ if (target) ShellExecuteW(nullptr, L"open", target, nullptr, nullptr, SW_SHOWNORMAL);+}++void Menu(Widget* wd, POINT pt) { // wd nulo: "Editar Widgets…" da mesa (só ligar/desligar e organizar)+ std::vector<ctxmenu::Item> items;+ for (size_t i = 0; i < g_w.size(); i++) {+ ctxmenu::Item it; it.label = Tr(g_w[i].name); it.id = 10 + (int)i; it.checked = g_w[i].on; items.push_back(it);+ }+ ctxmenu::Item sep; sep.separator = true; items.push_back(sep);+ if (wd) { ctxmenu::Item rm; rm.label = Tr(L"Remover Widget"); rm.id = 1; items.push_back(rm); }+ ctxmenu::Item reset; reset.label = Tr(L"Organizar Widgets"); reset.id = 2; items.push_back(reset);+ HWND fg = GetForegroundWindow();+ DWORD ft = fg ? GetWindowThreadProcessId(fg, nullptr) : 0, me = GetCurrentThreadId();+ bool att = ft && ft != me && AttachThreadInput(me, ft, TRUE);+ SetForegroundWindow(g_menuOwner);+ if (att) AttachThreadInput(me, ft, FALSE);+ int id = ctxmenu::ShowItems(g_menuOwner, pt, items);+ if (id == 1 && wd) { Show(*wd, false); shell::SetSetting((std::wstring(L"widget.") + wd->id + L".on").c_str(), L"0"); }+ else if (id == 2) {+ for (auto& w : g_w) w.rc = -1;+ for (auto& w : g_w) { shell::SetSetting((std::wstring(L"widget.") + w.id).c_str(), L""); if (w.on) Position(w, true, true); }+ } else if (id >= 10 && id < 10 + (int)g_w.size()) {+ Widget& t = g_w[id - 10];+ Show(t, !t.on);+ shell::SetSetting((std::wstring(L"widget.") + t.id + L".on").c_str(), t.on ? L"1" : L"0");+ }+}++LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM wp, LPARAM lp) {+ Widget* wd = Of(h);+ switch (m) {+ case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(h, &ps); EndPaint(h, &ps); if (wd && wd->wnd == h) Paint(*wd); return 0; }+ case WM_MOUSEACTIVATE: return MA_NOACTIVATE;+ case WM_WINDOWPOSCHANGING: { // só nós mexemos na ordem: ficam sempre logo acima da mesa+ auto* p = (WINDOWPOS*)lp;+ if (!g_placing) p->flags |= SWP_NOZORDER;+ break;+ }+ case WM_LBUTTONDOWN:+ if (wd) { g_drag = wd; GetCursorPos(&g_dragStart); RECT r; GetWindowRect(wd->wnd, &r); g_winStart = { r.left, r.top }; g_dragging = false; SetCapture(h); }+ return 0;+ case WM_MOUSEMOVE:+ if (g_drag && GetCapture() == h) {+ POINT c; GetCursorPos(&c);+ int dx = c.x - g_dragStart.x, dy = c.y - g_dragStart.y;+ // só vira arrastar depois de ~8 px: com 3 px um clique com a mão tremendo mudava o widget de casa+ // e gravava o lugar novo (os widgets "pulavam" para o meio da tela, 17/11/2026)+ int lim = std::max(8, GetSystemMetrics(SM_CXDRAG) * 2);+ if (!g_dragging && (abs(dx) > lim || abs(dy) > lim)) { // começou a arrastar: por cima dos outros, sombra na casa atual+ g_dragging = true;+ g_moves.erase(std::remove_if(g_moves.begin(), g_moves.end(), [&](const Move& mv) { return mv.w == g_drag; }), g_moves.end());+ PlaceAtDesktop(*g_drag);+ Grid g = GridNow(g_drag->wnd);+ g_targetRc = g_drag->rc; g_targetRow = g_drag->row;+ g_drag->rc = -1; // a casa dele fica livre enquanto arrasta+ if (g_targetRc < 0) Nearest(g, *g_drag, g_winStart, g_targetRc, g_targetRow);+ g_ghostTo = CellPx(g, *g_drag, g_targetRc, g_targetRow);+ g_gx = g_ghostTo.x; g_gy = g_ghostTo.y;+ PaintGhost(*g_drag);+ g_placing = true;+ SetWindowPos(g_ghost, g_drag->back, (int)g_gx, (int)g_gy, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW);+ g_placing = false;+ Animate(true);+ }+ if (g_dragging) {+ POINT p{ g_winStart.x + dx, g_winStart.y + dy };+ MoveWin(*g_drag, p.x, p.y);+ Grid g = GridNow(g_drag->wnd);+ Nearest(g, *g_drag, p, g_targetRc, g_targetRow);+ g_ghostTo = CellPx(g, *g_drag, g_targetRc, g_targetRow);+ }+ }+ return 0;+ case WM_LBUTTONUP: case WM_CAPTURECHANGED:+ if (g_drag && (m == WM_CAPTURECHANGED || GetCapture() == h)) {+ Widget* d = g_drag; g_drag = nullptr;+ bool dragged = g_dragging; g_dragging = false;+ if (m == WM_LBUTTONUP) ReleaseCapture();+ if (dragged) { // encaixa na casa com a mola+ d->rc = g_targetRc; d->row = g_targetRow;+ SaveCell(*d);+ AnimateTo(*d, CellPx(GridNow(d->wnd), *d, d->rc, d->row));+ Animate(true);+ } else if (m == WM_LBUTTONUP) Click(*d);+ }+ return 0;+ case WM_RBUTTONUP:+ if (wd) { POINT c; GetCursorPos(&c); Menu(wd, c); }+ return 0;+ }+ return DefWindowProcW(h, m, wp, lp);+}++const UINT WM_WG_DESK = WM_APP + 62;+// a mesa veio para a frente (Win+D, "mostrar a área de trabalho", clique na mesa): os widgets sobem na hora+// (antes só na conferência de 3 s: no Win+D eles demoravam a aparecer)+void CALLBACK OnForeground(HWINEVENTHOOK, DWORD, HWND h, LONG obj, LONG, DWORD, DWORD) {+ if (obj != OBJID_WINDOW || !h) return;+ wchar_t c[32] = {}; GetClassNameW(h, c, 32);+ if (mesa::IsDeskClass(c)) PostMessageW(g_timer, WM_WG_DESK, 0, 0);+}++LRESULT CALLBACK TimerProc(HWND h, UINT m, WPARAM wp, LPARAM lp) {+ if (m == WM_WG_FRAME) { Frame(); return 0; }+ if (m == WM_WG_DESK) { if (!g_drag) for (auto& w : g_w) if (w.on && BelowDesktop(w)) { for (auto& x : g_w) if (x.on) PlaceAtDesktop(x); break; } return 0; }+ if (m == WM_WX_READY) { for (auto& w : g_w) if (w.kind == K_WEATHER || w.kind == K_SUN) Paint(w); return 0; }+ if (m == WM_TIMER && wp == 1) {+ SYSTEMTIME t; GetLocalTime(&t);+ SetTimer(h, 1, 1000 - t.wMilliseconds + 5, nullptr); // na virada do segundo+ bool dark = ui::Dark();+ bool all = dark != g_dark || t.wMinute != g_lastMinute;+ g_dark = dark; g_lastMinute = t.wMinute;+ static int tick;+ bool checkZ = true; // ordem das janelas: todo segundo, só pelo primeiro widget ligado (barato: para no primeiro achado)+ ++tick;+ { // área de trabalho mudou (a barra de menus reservou a faixa de cima depois que os widgets nasceram, ou o+ // Dock mudou): reposiciona. O Shell muda a área sem avisar todo mundo, então o WM_SETTINGCHANGE não chegava+ // e os widgets ficavam por cima da barra de menus (17/11/2026)+ static RECT lastWork{};+ RECT work = shell::WorkAreaFor(MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)); // a do Shell (issue #1)+ if (!EqualRect(&work, &lastWork) && !g_drag && g_moves.empty()) {+ bool first = lastWork.right == 0;+ lastWork = work;+ (void)first; // também na primeira: os widgets podem ter nascido com a área antiga (sem a barra)+ for (auto& w : g_w) if (w.on) { Position(w, false); Paint(w); }+ }+ }+ bool below = false;+ if (checkZ) for (auto& w : g_w) if (w.on) { below = BelowDesktop(w); break; }+ for (auto& w : g_w) {+ if (!w.on) continue;+ if (below) PlaceAtDesktop(w);+ if (all || w.kind == K_CLOCK || w.kind == K_WORLD) Paint(w);+ }+ return 0;+ }+ if (m == WM_TIMER && wp == 2) { Fetch(); return 0; }+ if (m == WM_DISPLAYCHANGE || (m == WM_SETTINGCHANGE && wp == SPI_SETWORKAREA)) {+ for (auto& w : g_w) if (w.on) { Position(w, false); Paint(w); }+ return 0;+ }+ return DefWindowProcW(h, m, wp, lp);+}++LRESULT CALLBACK BackProc(HWND h, UINT m, WPARAM w, LPARAM l) {+ if (m == WM_MOUSEACTIVATE) return MA_NOACTIVATE;+ if (m == WM_WINDOWPOSCHANGING && !g_placing) ((WINDOWPOS*)l)->flags |= SWP_NOZORDER;+ return DefWindowProcW(h, m, w, l);+}++} // namespace++// "Editar Widgets…" (menu da mesa e da Central): a lista dos widgets para ligar ou desligar, mesmo sem nenhum na+// tela (antes só dava pelo menu de um widget: removidos todos, não havia como trazer de volta)+void widgets::EditMenu(POINT pt) { if (!g_w.empty()) Menu(nullptr, pt); }++void widgets::Create(HINSTANCE hi) {+ WNDCLASSW bc{}; bc.lpfnWndProc = BackProc; bc.hInstance = hi; bc.lpszClassName = L"ShellWidgetFundo";+ RegisterClassW(&bc);+ WNDCLASSW wc{}; wc.lpfnWndProc = Proc; wc.hInstance = hi; wc.lpszClassName = L"ShellWidget"; wc.hCursor = LoadCursorW(nullptr, IDC_ARROW);+ RegisterClassW(&wc);+ WNDCLASSW tc{}; tc.lpfnWndProc = TimerProc; tc.hInstance = hi; tc.lpszClassName = L"ShellWidgetsRelogio";+ RegisterClassW(&tc);+ g_timer = CreateWindowExW(WS_EX_TOOLWINDOW, tc.lpszClassName, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, hi, nullptr); // recebe WM_DISPLAYCHANGE+ WNDCLASSW gc{}; gc.lpfnWndProc = BackProc; gc.hInstance = hi; gc.lpszClassName = L"ShellWidgetSombra";+ RegisterClassW(&gc);+ g_ghost = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_LAYERED | WS_EX_TRANSPARENT, gc.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);+ g_ghostS.hwnd = g_ghost;+ g_menuOwner = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_LAYERED, tc.lpszClassName, L"", WS_POPUP | WS_VISIBLE, -32000, -32000, 1, 1, nullptr, nullptr, hi, nullptr);+ SetLayeredWindowAttributes(g_menuOwner, 0, 0, LWA_ALPHA);+ apps::ours.push_back(g_menuOwner);+ apps::ours.push_back(g_ghost);++ g_w = { { K_WEATHER, L"tempo", L"Tempo", MEDIUM, SMALL },+ { K_CLOCK, L"relogio", L"Relógio", SMALL, SMALL },+ { K_CALENDAR, L"calendario", L"Calendário", SMALL, SMALL },+ { K_WORLD, L"mundial", L"Relógio Mundial", MEDIUM, SMALL },+ { K_SUN, L"sol", L"Nascer do Sol", SMALL, SMALL } };+ g_w.reserve(g_w.size());+ g_dark = ui::Dark();+ LoadCache();+ for (auto& wd : g_w) {+ wd.back = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP, bc.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);+ if (!wd.back) continue;+ wd.glass = backdrop::Attach(wd.back);+ if (!wd.glass) {+ DestroyWindow(wd.back);+ wd.back = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, bc.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);+ DWORD corner = 2; DwmSetWindowAttribute(wd.back, 33, &corner, sizeof(corner));+ ui::Acrylic(wd.back, g_dark ? 0x60201E1Eu : 0x30F6F6F6u);+ } else { DWORD corner = 1; DwmSetWindowAttribute(wd.back, 33, &corner, sizeof(corner)); }+ COLORREF none = 0xFFFFFFFE;+ DwmSetWindowAttribute(wd.back, 34, &none, sizeof(none));+ BOOL off = TRUE; DwmSetWindowAttribute(wd.back, DWMWA_TRANSITIONS_FORCEDISABLED, &off, sizeof(off));+ wd.wnd = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP, wc.lpszClassName, wd.name, WS_POPUP, 0, 0, 10, 10, wd.back, nullptr, hi, nullptr);+ if (!wd.wnd) continue;+ DwmSetWindowAttribute(wd.wnd, DWMWA_TRANSITIONS_FORCEDISABLED, &off, sizeof(off));+ apps::ours.push_back(wd.wnd);+ apps::ours.push_back(wd.back);+ wd.s.hwnd = wd.wnd;+ Show(wd, shell::Setting((std::wstring(L"widget.") + wd.id + L".on").c_str(), L"1") != L"0");+ }+ SetTimer(g_timer, 1, 1000, nullptr);+ SetTimer(g_timer, 2, 15 * 60 * 1000, nullptr);+ SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr, OnForeground, 0, 0, WINEVENT_OUTOFCONTEXT);+ Fetch();+ Log(L"widgets: %zu na mesa (tempo de %ls)", g_w.size(), City().c_str());+}++std::vector<RECT> widgets::Areas() {+ std::vector<RECT> r;+ for (auto& w : g_w) if (w.on && w.wnd && IsWindowVisible(w.wnd)) { RECT x; GetWindowRect(w.wnd, &x); r.push_back(x); }+ return r;+}