Skip to content

armgit / WacOS

Public Imported from GitHub
0

A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.

Rust

Siri: real dictation, Apple Intelligence icon, fluid animation, Win+S; #37 fixes; AI Writing Tools in Notes

Eternity07062843ef0a833509
diff --git a/docs/registro-mudancas.txt b/docs/registro-mudancas.txt
index 359b700..451f233 100644
--- a/docs/registro-mudancas.txt
+++ b/docs/registro-mudancas.txt
@@ -1713,3 +1713,31 @@ Compilado (tudo), instalado, Shell e reserva do Finder reiniciados às 23:07 sem
Compilado e instalado. Visto: a propriedade do caminho existe nos itens de Aplicativos dos jogos do PC. NÃO visto: abrir um
jogo pelo Launchpad (não abro programas do usuário), o Dock inteligente na tela.
DESFAZER: reverter o commit.
+[2026-11-23 19:50] Siri, voz, área de trabalho, issue #37 e Ferramentas de Escrita com IA nas Notas:
+ - src/shell/voz.cpp (novo), siri.cpp, spotlight.cpp: o microfone da Siri e do Spotlight dita de verdade
+ (Windows.Media.SpeechRecognition). Sem o "Reconhecimento de fala online" ligado, avisa e abre a página do Windows.
+ - siri.cpp: animação fluida. O brilho da borda é um anel desfocado na GPU (Gaussian blur), não mais 4x240 traços.
+ O ícone e o brilho ficam na camada da frente; o vidro e o texto só redesenham quando mudam. O vidro (SetPieces)
+ não é refeito a cada quadro. A mola de abrir/fechar é do compositor (ui::GpuMotionAnim, backdrop::FadeAnim):
+ a thread da interface ocupada (o gênio do Dock) não faz mais o painel pular quadros. Medição no log ao esconder.
+ - siri.cpp: abre alinhada ao Spotlight (mesmo monitor, centro, topo e largura do campo: spotlight::Lugar e
+ LarguraCampo). Atalho novo: Win+S abre a Siri (main.cpp, WM_APP_SIRI), só com um serviço escolhido.
+ - menubar.cpp: o ícone da Siri na barra é o símbolo apple.intelligence monocromático, na cor da barra (como no
+ macOS). O ponto de privacidade não deixa mais a cor laranja/verde para os ícones seguintes.
+ - mesa.cpp: o ajuste explorer vazio vale "fundo" (o padrão do instalador). Quem perdeu a linha do ajustes.txt
+ ficava com a área de trabalho do Explorador e o menu de clique direito do Windows.
+ - main.cpp (issue #37): com a barra do Windows em "ocultar automaticamente", o Explorador devolvia a área de
+ trabalho para a tela inteira ~6 vezes por segundo, e as janelas maximizadas eram reencaixadas a cada vez
+ (as travadas). O ocultar automático fica desligado enquanto o Shell roda e volta ao sair
+ (barra_windows_ocultar_antes). Teclas de mídia (tocar/pausar, próxima, anterior, parar) vão para a sessão de
+ mídia atual do Windows (atalhos::MediaCommand sem app).
+ - src/comum/siri.h (siri::Gera), src/notas/editor.cpp (AiTake, AiReplace), src/notas/main.cpp: Ferramentas de
+ Escrita com IA nas Notas, com o serviço e a chave da Siri. Revisar, Reescrever, Amigável, Profissional, Conciso,
+ Resumo, Pontos-chave, Lista, Tabela e "Pedir à IA…". Agem na seleção ou na nota inteira; Ctrl+Z desfaz. As
+ transformações sem IA ficam num submenu. Traduções nos 11 idiomas.
+ Compilado e instalado. Visto: o brilho e o texto em fotos; 942 quadros em 8 s (antes 76/s, irregular); a briga da
+ área de trabalho reproduzida com o ocultar automático e sumida com a correção (o ajuste da barra e o
+ ajustes.txt devolvidos, hash conferido); a posição da Siri (painel 520 de largura, centro 1720, topo 432, igual
+ ao campo do Spotlight). NÃO visto: ditado falando de verdade (o reconhecimento online está desligado neste PC),
+ as teclas de mídia apertadas (sem teclas simuladas), as Ferramentas de Escrita com IA na tela, o Win+S.
+ DESFAZER: reverter o commit.
diff --git a/src/ajustes/main.cpp b/src/ajustes/main.cpp
index ef51e35..668fd40 100644
--- a/src/ajustes/main.cpp
+++ b/src/ajustes/main.cpp
@@ -367,9 +367,14 @@ void aj::Tile(Ctx& c, D2D1_RECT_F r, wchar_t glyph, UINT32 color, const std::wst
D2D1_COLOR_F top = Rgb(color), bot = Rgb(color);
top.r = std::min(1.f, top.r * 1.08f + 0.05f); top.g = std::min(1.f, top.g * 1.08f + 0.05f); top.b = std::min(1.f, top.b * 1.08f + 0.05f);
D2D1_GRADIENT_STOP gs[2] = { { 0, top }, { 1, bot } };
- c.dc->CreateGradientStopCollection(gs, 2, &stops);
+ // o ícone do Apple Intelligence e da Siri: o degradê dele (amarelo, laranja, rosa, roxo e azul), na diagonal
+ D2D1_GRADIENT_STOP ai[5] = { { 0, D2D1::ColorF(1.f, 0.78f, 0.25f) }, { 0.3f, D2D1::ColorF(1.f, 0.50f, 0.20f) }, { 0.55f, D2D1::ColorF(1.f, 0.30f, 0.50f) },
+ { 0.78f, D2D1::ColorF(0.70f, 0.38f, 1.f) }, { 1, D2D1::ColorF(0.22f, 0.52f, 1.f) } };
+ bool appleAI = symbol == L"apple.intelligence";
+ c.dc->CreateGradientStopCollection(appleAI ? ai : gs, appleAI ? 5 : 2, &stops);
ID2D1LinearGradientBrush* lg = nullptr;
- if (stops) c.dc->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, r.top }, { 0, r.bottom }), stops, &lg);
+ if (stops) c.dc->CreateLinearGradientBrush(appleAI ? D2D1::LinearGradientBrushProperties({ r.left, r.top }, { r.right, r.bottom })
+ : D2D1::LinearGradientBrushProperties({ 0, r.top }, { 0, r.bottom }), stops, &lg);
auto rr = D2D1::RoundedRect(r, w * 0.24f, w * 0.24f);
if (lg) c.dc->FillRoundedRectangle(rr, lg); else { c.br->SetColor(Rgb(color)); c.dc->FillRoundedRectangle(rr, c.br); }
if (lg) lg->Release();
diff --git a/src/ajustes/paginas.cpp b/src/ajustes/paginas.cpp
index 8ee91d5..20e6576 100644
--- a/src/ajustes/paginas.cpp
+++ b/src/ajustes/paginas.cpp
@@ -1483,21 +1483,21 @@ Page TransparenciaEfeitos() {
[](bool v) { SetSetting(L"barra_fundo", v ? L"1" : L"0"); },
L"Desligado, a barra fica sem fundo, só com o papel de parede atrás (como no Tahoe).");
bar.enabled = !reduce && !liquid; // no Tahoe a barra nunca tem fundo, como no macOS 26
- // no Tahoe: a barra pode ter o vidro do Dock (barra_vidro; o Shell confere a cada segundo)
- Row barGlass = Toggle(L"Barra de menus de vidro (Liquid Glass)", [] { return Setting(L"barra_vidro", L"0") == L"1"; },
- [](bool v) { SetSetting(L"barra_vidro", v ? L"1" : L"0"); },
- L"O vidro do Dock atrás da barra de menus: as letras ficam legíveis em qualquer papel de parede.");
- barGlass.enabled = !reduce && liquid;
- // menus (de contexto, da barra de menus e os do Windows) com o vidro do Dock em vez do vidro tingido (menu_vidro)
- Row menuGlass = Toggle(L"Menus de vidro (Liquid Glass)", [] { return Setting(L"menu_vidro", L"0") == L"1"; },
- [](bool v) { SetSetting(L"menu_vidro", v ? L"1" : L"0"); },
- L"Os menus (clique direito, barra de menus e Dock) ficam com o vidro claro do Dock, com refração na borda.");
- menuGlass.enabled = !reduce && liquid;
+ // no Tahoe: a barra pode ter o vidro do Dock (barra_vidro; o Shell confere a cada segundo)
+ Row barGlass = Toggle(L"Barra de menus de vidro (Liquid Glass)", [] { return Setting(L"barra_vidro", L"0") == L"1"; },
+ [](bool v) { SetSetting(L"barra_vidro", v ? L"1" : L"0"); },
+ L"O vidro do Dock atrás da barra de menus: as letras ficam legíveis em qualquer papel de parede.");
+ barGlass.enabled = !reduce && liquid;
+ // menus (de contexto, da barra de menus e os do Windows) com o vidro do Dock em vez do vidro tingido (menu_vidro)
+ Row menuGlass = Toggle(L"Menus de vidro (Liquid Glass)", [] { return Setting(L"menu_vidro", L"0") == L"1"; },
+ [](bool v) { SetSetting(L"menu_vidro", v ? L"1" : L"0"); },
+ L"Os menus (clique direito, barra de menus e Dock) ficam com o vidro claro do Dock, com refração na borda.");
+ menuGlass.enabled = !reduce && liquid;
// macOS 26: "Permitir tingir janelas com o papel de parede" (a barra lateral dos apps pega a cor dele)
Row wtint = Toggle(L"Permitir tingir janelas com o papel de parede", [] { return Setting(L"tingir_janelas", L"1") != L"0"; },
[](bool v) { SetSetting(L"tingir_janelas", v ? L"1" : L"0"); },
L"A barra lateral dos apps (Lembretes, Calendário, Contatos, Fotos, Música) ganha um pouco da cor do papel de parede. Vale ao abrir o app de novo.");
- p.groups.push_back(G({ red, tint, bar, barGlass, menuGlass, wtint }, L"Transparência"));
+ p.groups.push_back(G({ red, tint, bar, barGlass, menuGlass, wtint }, L"Transparência"));
Row genie = Toggle(L"Efeito gênio ao minimizar", [] { return Setting(L"genio", L"1") == L"1"; },
[](bool v) { SetSetting(L"genio", v ? L"1" : L"0"); });
@@ -1648,13 +1648,13 @@ Page CentralControle() {
[] { return Setting(L"barra_icones_todos", L"0") == L"1" ? 2 : Setting(L"barra_seta", L"0") == L"1" ? 1 : 0; },
[](int i) { SetSetting(L"barra_icones_todos", i == 2 ? L"1" : L"0"); SetSetting(L"barra_seta", i == 1 ? L"1" : L"0"); });
tray.icon = 0xE71D; tray.iconColor = C_GRAY;
- // o vidro da barra também aqui, à vista (antes só em Aparência > Transparência e Efeitos); o mesmo barra_vidro
- Row barGlass = Toggle(L"Barra de menus de vidro (Liquid Glass)", [] { return Setting(L"barra_vidro", L"0") == L"1"; },
- [](bool v) { SetSetting(L"barra_vidro", v ? L"1" : L"0"); },
- L"O vidro do Dock atrás da barra de menus: as letras ficam legíveis em qualquer papel de parede.");
- barGlass.icon = 0xE790; barGlass.iconColor = C_BLUE;
- barGlass.enabled = Setting(L"liquid_glass", L"0") == L"1" && Setting(L"reduzir_transparencia", L"0") != L"1" && Setting(L"leopard", L"0") != L"1";
- p.groups.push_back(G({ tray, barGlass }, L"Barra de Menus", L"Ícones que os aplicativos põem na área de notificação do Windows."));
+ // o vidro da barra também aqui, à vista (antes só em Aparência > Transparência e Efeitos); o mesmo barra_vidro
+ Row barGlass = Toggle(L"Barra de menus de vidro (Liquid Glass)", [] { return Setting(L"barra_vidro", L"0") == L"1"; },
+ [](bool v) { SetSetting(L"barra_vidro", v ? L"1" : L"0"); },
+ L"O vidro do Dock atrás da barra de menus: as letras ficam legíveis em qualquer papel de parede.");
+ barGlass.icon = 0xE790; barGlass.iconColor = C_BLUE;
+ barGlass.enabled = Setting(L"liquid_glass", L"0") == L"1" && Setting(L"reduzir_transparencia", L"0") != L"1" && Setting(L"leopard", L"0") != L"1";
+ p.groups.push_back(G({ tray, barGlass }, L"Barra de Menus", L"Ícones que os aplicativos põem na área de notificação do Windows."));
Row clock = Popup(L"Relógio", { L"Dia, data e hora", L"Só a hora" }, [] { return Setting(L"relogio_curto", L"0") == L"1" ? 1 : 0; },
[](int i) { SetSetting(L"relogio_curto", i == 1 ? L"1" : L"0"); });
clock.icon = 0xE787; clock.iconColor = C_GRAY;
@@ -2622,7 +2622,7 @@ std::wstring SymbolFor(const std::wstring& label) {
static const std::map<std::wstring, std::wstring> m = {
{ L"Wi‑Fi", L"wifi" }, { L"Rede", L"globe" }, { L"Energia", L"bolt.fill" }, { L"Bateria", L"battery.100percent" },
{ L"Geral", L"gearshape.fill" }, { L"Experimental", L"sparkles" }, { L"Acessibilidade", L"accessibility" }, { L"Aparência", L"circle.lefthalf.filled" },
- { L"Apple Intelligence e Siri", L"apple.intelligence" }, { L"Assistente e Fala", L"apple.intelligence" }, { L"Central de Controle", L"switch.2" },
+ { L"Apple Intelligence e Siri", L"apple.intelligence" }, { L"Siri", L"apple.intelligence" }, { L"Assistente e Fala", L"apple.intelligence" }, { L"Central de Controle", L"switch.2" },
{ L"Ilha Dinâmica", L"menubar.dock.rectangle" }, { L"Mostrar o uso do microfone e da câmera", L"microphone.fill" },
{ L"Mesa e Dock", L"dock.rectangle" }, { L"Telas", L"sun.max.fill" }, { L"Protetor de Tela", L"photo.on.rectangle.angled" },
{ L"Spotlight", L"magnifyingglass" }, { L"Imagem de Fundo", L"camera.macro" }, { L"Notificações", L"bell.badge.fill" },
diff --git a/src/comum/idioma_de.inc b/src/comum/idioma_de.inc
index 7c14c09..6464fd7 100644
--- a/src/comum/idioma_de.inc
+++ b/src/comum/idioma_de.inc
@@ -1706,3 +1706,32 @@
{ L"Recursos que ainda estão em teste. Podem mudar ou ter falhas: ligue para experimentar e conte o que achou no GitHub do WacOS.", L"Funktionen, die noch getestet werden. Sie können sich ändern oder Fehler haben: Schalte sie zum Ausprobieren ein und sag uns auf GitHub, was du denkst." },
{ L"Barra de título do Mac em todos os apps", L"Mac-Titelleiste in allen Apps" },
{ L"Os programas do Windows ganham a barra de título e os três botões do Mac. Ao mudar, o WacOS reinicia (os apps continuam abertos).", L"Windows-Programme bekommen die Titelleiste und die drei Tasten des Mac. Beim Ändern startet WacOS neu (deine Apps bleiben offen)." },
+{ L"Ouvindo…", L"Hört zu …" },
+{ L"O reconhecimento de fala do Windows não está disponível neste idioma.", L"Die Windows-Spracherkennung ist in dieser Sprache nicht verfügbar." },
+{ L"Para ditar, ligue o \"Reconhecimento de fala online\" em Configurações do Windows > Privacidade > Fala.", L"Zum Diktieren schalte „Online-Spracherkennung“ in den Windows-Einstellungen > Datenschutz > Spracherkennung ein." },
+{ L"O Windows não deixou usar o microfone. Libere em Configurações > Privacidade > Microfone.", L"Windows hat das Mikrofon nicht freigegeben. Erlaube es unter Einstellungen > Datenschutz > Mikrofon." },
+{ L"Não deu para ouvir agora. Confira se há um microfone ligado.", L"Zuhören ist gerade nicht möglich. Prüfe, ob ein Mikrofon angeschlossen ist." },
+{ L"Ex.: organize em tópicos, traduza para o inglês…", L"Z. B.: in Themen gliedern, ins Englische übersetzen …" },
+{ L"Ferramentas de Escrita", L"Schreibtools" },
+{ L"Escreva algo na nota (ou selecione um trecho) antes de usar as Ferramentas de Escrita.", L"Schreib etwas in die Notiz (oder wähle Text aus), bevor du die Schreibtools nutzt." },
+{ L"Escolha um serviço de IA em Ajustes do Sistema > Apple Intelligence e Siri.", L"Wähle einen KI-Dienst in Systemeinstellungen > Apple Intelligence & Siri." },
+{ L"O serviço recusou o pedido:", L"Der Dienst hat die Anfrage abgelehnt:" },
+{ L"A nota mudou enquanto a IA escrevia. Tente de novo.", L"Die Notiz hat sich geändert, während die KI schrieb. Versuch es noch einmal." },
+{ L"Pedir à IA", L"KI fragen" },
+{ L"Descreva o que fazer com o texto selecionado (ou com a nota inteira).", L"Beschreibe, was mit dem ausgewählten Text (oder der ganzen Notiz) passieren soll." },
+{ L"Enviar", L"Senden" },
+{ L"Escrevendo…", L"Schreibt …" },
+{ L"Reescrever", L"Umschreiben" },
+{ L"Amigável", L"Freundlich" },
+{ L"Profissional", L"Professionell" },
+{ L"Conciso", L"Prägnant" },
+{ L"Resumo", L"Zusammenfassung" },
+{ L"Pontos-chave", L"Kernpunkte" },
+{ L"Tabela", L"Tabelle" },
+{ L"Pedir à IA…", L"KI fragen …" },
+{ L"No computador, sem IA", L"Auf dem Computer, ohne KI" },
+{ L"Revisando…", L"Korrigiert …" },
+{ L"Reescrevendo…", L"Schreibt um …" },
+{ L"Resumindo…", L"Fasst zusammen …" },
+{ L"Organizando…", L"Ordnet …" },
+{ L"Usar IA: escolha um serviço em Ajustes do Sistema > Apple Intelligence e Siri", L"KI nutzen: Wähle einen Dienst in Systemeinstellungen > Apple Intelligence & Siri" },
diff --git a/src/comum/idioma_en.inc b/src/comum/idioma_en.inc
index 18b5241..b399249 100644
--- a/src/comum/idioma_en.inc
+++ b/src/comum/idioma_en.inc
@@ -1706,3 +1706,32 @@
{ L"Recursos que ainda estão em teste. Podem mudar ou ter falhas: ligue para experimentar e conte o que achou no GitHub do WacOS.", L"Features still being tested. They may change or have bugs: turn them on to try them and share what you think on WacOS's GitHub." },
{ L"Barra de título do Mac em todos os apps", L"Mac title bar in all apps" },
{ L"Os programas do Windows ganham a barra de título e os três botões do Mac. Ao mudar, o WacOS reinicia (os apps continuam abertos).", L"Windows programs get the Mac title bar and its three buttons. Changing this restarts WacOS (your apps stay open)." },
+{ L"Ouvindo…", L"Listening…" },
+{ L"O reconhecimento de fala do Windows não está disponível neste idioma.", L"Windows speech recognition isn't available in this language." },
+{ L"Para ditar, ligue o \"Reconhecimento de fala online\" em Configurações do Windows > Privacidade > Fala.", L"To dictate, turn on \"Online speech recognition\" in Windows Settings > Privacy > Speech." },
+{ L"O Windows não deixou usar o microfone. Libere em Configurações > Privacidade > Microfone.", L"Windows didn't allow the microphone. Allow it in Settings > Privacy > Microphone." },
+{ L"Não deu para ouvir agora. Confira se há um microfone ligado.", L"Couldn't listen right now. Check that a microphone is connected." },
+{ L"Ex.: organize em tópicos, traduza para o inglês…", L"E.g.: organize into topics, translate to English…" },
+{ L"Ferramentas de Escrita", L"Writing Tools" },
+{ L"Escreva algo na nota (ou selecione um trecho) antes de usar as Ferramentas de Escrita.", L"Write something in the note (or select some text) before using Writing Tools." },
+{ L"Escolha um serviço de IA em Ajustes do Sistema > Apple Intelligence e Siri.", L"Choose an AI service in System Settings > Apple Intelligence & Siri." },
+{ L"O serviço recusou o pedido:", L"The service refused the request:" },
+{ L"A nota mudou enquanto a IA escrevia. Tente de novo.", L"The note changed while the AI was writing. Try again." },
+{ L"Pedir à IA", L"Ask AI" },
+{ L"Descreva o que fazer com o texto selecionado (ou com a nota inteira).", L"Describe what to do with the selected text (or the whole note)." },
+{ L"Enviar", L"Send" },
+{ L"Escrevendo…", L"Writing…" },
+{ L"Reescrever", L"Rewrite" },
+{ L"Amigável", L"Friendly" },
+{ L"Profissional", L"Professional" },
+{ L"Conciso", L"Concise" },
+{ L"Resumo", L"Summary" },
+{ L"Pontos-chave", L"Key Points" },
+{ L"Tabela", L"Table" },
+{ L"Pedir à IA…", L"Ask AI…" },
+{ L"No computador, sem IA", L"On this computer, without AI" },
+{ L"Revisando…", L"Proofreading…" },
+{ L"Reescrevendo…", L"Rewriting…" },
+{ L"Resumindo…", L"Summarizing…" },
+{ L"Organizando…", L"Organizing…" },
+{ L"Usar IA: escolha um serviço em Ajustes do Sistema > Apple Intelligence e Siri", L"Use AI: choose a service in System Settings > Apple Intelligence & Siri" },
diff --git a/src/comum/idioma_es.inc b/src/comum/idioma_es.inc
index 4f8942e..e8d54ac 100644
--- a/src/comum/idioma_es.inc
+++ b/src/comum/idioma_es.inc
@@ -1706,3 +1706,32 @@
{ L"Recursos que ainda estão em teste. Podem mudar ou ter falhas: ligue para experimentar e conte o que achou no GitHub do WacOS.", L"Funciones que aún están en prueba. Pueden cambiar o tener fallos: actívalas para probarlas y cuéntanos qué te parecen en el GitHub de WacOS." },
{ L"Barra de título do Mac em todos os apps", L"Barra de título del Mac en todas las apps" },
{ L"Os programas do Windows ganham a barra de título e os três botões do Mac. Ao mudar, o WacOS reinicia (os apps continuam abertos).", L"Los programas de Windows reciben la barra de título y los tres botones del Mac. Al cambiarlo, WacOS se reinicia (tus apps siguen abiertas)." },
+{ L"Ouvindo…", L"Escuchando…" },
+{ L"O reconhecimento de fala do Windows não está disponível neste idioma.", L"El reconocimiento de voz de Windows no está disponible en este idioma." },
+{ L"Para ditar, ligue o \"Reconhecimento de fala online\" em Configurações do Windows > Privacidade > Fala.", L"Para dictar, activa \"Reconocimiento de voz en línea\" en Configuración de Windows > Privacidad > Voz." },
+{ L"O Windows não deixou usar o microfone. Libere em Configurações > Privacidade > Microfone.", L"Windows no permitió usar el micrófono. Permítelo en Configuración > Privacidad > Micrófono." },
+{ L"Não deu para ouvir agora. Confira se há um microfone ligado.", L"No se pudo escuchar ahora. Comprueba que haya un micrófono conectado." },
+{ L"Ex.: organize em tópicos, traduza para o inglês…", L"Ej.: organiza en temas, traduce al inglés…" },
+{ L"Ferramentas de Escrita", L"Herramientas de Escritura" },
+{ L"Escreva algo na nota (ou selecione um trecho) antes de usar as Ferramentas de Escrita.", L"Escribe algo en la nota (o selecciona un fragmento) antes de usar las Herramientas de Escritura." },
+{ L"Escolha um serviço de IA em Ajustes do Sistema > Apple Intelligence e Siri.", L"Elige un servicio de IA en Ajustes del Sistema > Apple Intelligence y Siri." },
+{ L"O serviço recusou o pedido:", L"El servicio rechazó la solicitud:" },
+{ L"A nota mudou enquanto a IA escrevia. Tente de novo.", L"La nota cambió mientras la IA escribía. Inténtalo de nuevo." },
+{ L"Pedir à IA", L"Pedir a la IA" },
+{ L"Descreva o que fazer com o texto selecionado (ou com a nota inteira).", L"Describe qué hacer con el texto seleccionado (o con toda la nota)." },
+{ L"Enviar", L"Enviar" },
+{ L"Escrevendo…", L"Escribiendo…" },
+{ L"Reescrever", L"Reescribir" },
+{ L"Amigável", L"Amistoso" },
+{ L"Profissional", L"Profesional" },
+{ L"Conciso", L"Conciso" },
+{ L"Resumo", L"Resumen" },
+{ L"Pontos-chave", L"Puntos clave" },
+{ L"Tabela", L"Tabla" },
+{ L"Pedir à IA…", L"Pedir a la IA…" },
+{ L"No computador, sem IA", L"En el ordenador, sin IA" },
+{ L"Revisando…", L"Revisando…" },
+{ L"Reescrevendo…", L"Reescribiendo…" },
+{ L"Resumindo…", L"Resumiendo…" },
+{ L"Organizando…", L"Organizando…" },
+{ L"Usar IA: escolha um serviço em Ajustes do Sistema > Apple Intelligence e Siri", L"Usar IA: elige un servicio en Ajustes del Sistema > Apple Intelligence y Siri" },
diff --git a/src/comum/idioma_fr.inc b/src/comum/idioma_fr.inc
index 7978eaa..79bfc47 100644
--- a/src/comum/idioma_fr.inc
+++ b/src/comum/idioma_fr.inc
@@ -1706,3 +1706,32 @@
{ L"Recursos que ainda estão em teste. Podem mudar ou ter falhas: ligue para experimentar e conte o que achou no GitHub do WacOS.", L"Fonctions encore en test. Elles peuvent changer ou avoir des bugs : activez-les pour essayer et donnez votre avis sur le GitHub de WacOS." },
{ L"Barra de título do Mac em todos os apps", L"Barre de titre du Mac dans toutes les apps" },
{ L"Os programas do Windows ganham a barra de título e os três botões do Mac. Ao mudar, o WacOS reinicia (os apps continuam abertos).", L"Les programmes Windows reçoivent la barre de titre et les trois boutons du Mac. Changer ce réglage redémarre WacOS (vos apps restent ouvertes)." },
+{ L"Ouvindo…", L"Écoute…" },
+{ L"O reconhecimento de fala do Windows não está disponível neste idioma.", L"La reconnaissance vocale de Windows n'est pas disponible dans cette langue." },
+{ L"Para ditar, ligue o \"Reconhecimento de fala online\" em Configurações do Windows > Privacidade > Fala.", L"Pour dicter, activez « Reconnaissance vocale en ligne » dans Paramètres Windows > Confidentialité > Voix." },
+{ L"O Windows não deixou usar o microfone. Libere em Configurações > Privacidade > Microfone.", L"Windows n'a pas autorisé le micro. Autorisez-le dans Paramètres > Confidentialité > Microphone." },
+{ L"Não deu para ouvir agora. Confira se há um microfone ligado.", L"Impossible d'écouter pour le moment. Vérifiez qu'un micro est branché." },
+{ L"Ex.: organize em tópicos, traduza para o inglês…", L"Ex. : organise en thèmes, traduis en anglais…" },
+{ L"Ferramentas de Escrita", L"Outils d’écriture" },
+{ L"Escreva algo na nota (ou selecione um trecho) antes de usar as Ferramentas de Escrita.", L"Écrivez quelque chose dans la note (ou sélectionnez un passage) avant d’utiliser les Outils d’écriture." },
+{ L"Escolha um serviço de IA em Ajustes do Sistema > Apple Intelligence e Siri.", L"Choisissez un service d’IA dans Réglages Système > Apple Intelligence et Siri." },
+{ L"O serviço recusou o pedido:", L"Le service a refusé la demande :" },
+{ L"A nota mudou enquanto a IA escrevia. Tente de novo.", L"La note a changé pendant que l’IA écrivait. Réessayez." },
+{ L"Pedir à IA", L"Demander à l’IA" },
+{ L"Descreva o que fazer com o texto selecionado (ou com a nota inteira).", L"Décrivez quoi faire avec le texte sélectionné (ou toute la note)." },
+{ L"Enviar", L"Envoyer" },
+{ L"Escrevendo…", L"Rédaction…" },
+{ L"Reescrever", L"Réécrire" },
+{ L"Amigável", L"Amical" },
+{ L"Profissional", L"Professionnel" },
+{ L"Conciso", L"Concis" },
+{ L"Resumo", L"Résumé" },
+{ L"Pontos-chave", L"Points clés" },
+{ L"Tabela", L"Tableau" },
+{ L"Pedir à IA…", L"Demander à l’IA…" },
+{ L"No computador, sem IA", L"Sur l’ordinateur, sans IA" },
+{ L"Revisando…", L"Relecture…" },
+{ L"Reescrevendo…", L"Réécriture…" },
+{ L"Resumindo…", L"Résumé en cours…" },
+{ L"Organizando…", L"Organisation…" },
+{ L"Usar IA: escolha um serviço em Ajustes do Sistema > Apple Intelligence e Siri", L"Utiliser l’IA : choisissez un service dans Réglages Système > Apple Intelligence et Siri" },
diff --git a/src/comum/idioma_it.inc b/src/comum/idioma_it.inc
index 403d2c8..be2c996 100644
--- a/src/comum/idioma_it.inc
+++ b/src/comum/idioma_it.inc
@@ -1706,3 +1706,32 @@
{ L"Recursos que ainda estão em teste. Podem mudar ou ter falhas: ligue para experimentar e conte o que achou no GitHub do WacOS.", L"Funzioni ancora in prova. Possono cambiare o avere difetti: attivale per provarle e dicci cosa ne pensi sul GitHub di WacOS." },
{ L"Barra de título do Mac em todos os apps", L"Barra del titolo del Mac in tutte le app" },
{ L"Os programas do Windows ganham a barra de título e os três botões do Mac. Ao mudar, o WacOS reinicia (os apps continuam abertos).", L"I programmi di Windows ottengono la barra del titolo e i tre pulsanti del Mac. Cambiando, WacOS si riavvia (le app restano aperte)." },
+{ L"Ouvindo…", L"In ascolto…" },
+{ L"O reconhecimento de fala do Windows não está disponível neste idioma.", L"Il riconoscimento vocale di Windows non è disponibile in questa lingua." },
+{ L"Para ditar, ligue o \"Reconhecimento de fala online\" em Configurações do Windows > Privacidade > Fala.", L"Per dettare, attiva \"Riconoscimento vocale online\" in Impostazioni di Windows > Privacy > Voce." },
+{ L"O Windows não deixou usar o microfone. Libere em Configurações > Privacidade > Microfone.", L"Windows non ha consentito il microfono. Consentilo in Impostazioni > Privacy > Microfono." },
+{ L"Não deu para ouvir agora. Confira se há um microfone ligado.", L"Impossibile ascoltare ora. Controlla che ci sia un microfono collegato." },
+{ L"Ex.: organize em tópicos, traduza para o inglês…", L"Es.: organizza per argomenti, traduci in inglese…" },
+{ L"Ferramentas de Escrita", L"Strumenti di scrittura" },
+{ L"Escreva algo na nota (ou selecione um trecho) antes de usar as Ferramentas de Escrita.", L"Scrivi qualcosa nella nota (o seleziona un testo) prima di usare gli Strumenti di scrittura." },
+{ L"Escolha um serviço de IA em Ajustes do Sistema > Apple Intelligence e Siri.", L"Scegli un servizio di IA in Impostazioni di Sistema > Apple Intelligence e Siri." },
+{ L"O serviço recusou o pedido:", L"Il servizio ha rifiutato la richiesta:" },
+{ L"A nota mudou enquanto a IA escrevia. Tente de novo.", L"La nota è cambiata mentre l’IA scriveva. Riprova." },
+{ L"Pedir à IA", L"Chiedi all’IA" },
+{ L"Descreva o que fazer com o texto selecionado (ou com a nota inteira).", L"Descrivi cosa fare con il testo selezionato (o con tutta la nota)." },
+{ L"Enviar", L"Invia" },
+{ L"Escrevendo…", L"Scrittura…" },
+{ L"Reescrever", L"Riscrivi" },
+{ L"Amigável", L"Amichevole" },
+{ L"Profissional", L"Professionale" },
+{ L"Conciso", L"Conciso" },
+{ L"Resumo", L"Riepilogo" },
+{ L"Pontos-chave", L"Punti chiave" },
+{ L"Tabela", L"Tabella" },
+{ L"Pedir à IA…", L"Chiedi all’IA…" },
+{ L"No computador, sem IA", L"Sul computer, senza IA" },
+{ L"Revisando…", L"Revisione…" },
+{ L"Reescrevendo…", L"Riscrittura…" },
+{ L"Resumindo…", L"Riepilogo in corso…" },
+{ L"Organizando…", L"Organizzazione…" },
+{ L"Usar IA: escolha um serviço em Ajustes do Sistema > Apple Intelligence e Siri", L"Usa l’IA: scegli un servizio in Impostazioni di Sistema > Apple Intelligence e Siri" },
diff --git a/src/comum/idioma_ja.inc b/src/comum/idioma_ja.inc
index 52156eb..0311410 100644
--- a/src/comum/idioma_ja.inc
+++ b/src/comum/idioma_ja.inc
@@ -1706,3 +1706,32 @@
{ L"Recursos que ainda estão em teste. Podem mudar ou ter falhas: ligue para experimentar e conte o que achou no GitHub do WacOS.", L"テスト中の機能です。変更されたり不具合があったりする場合があります。オンにして試し、WacOS の GitHub で感想を教えてください。" },
{ L"Barra de título do Mac em todos os apps", L"すべてのアプリに Mac のタイトルバー" },
{ L"Os programas do Windows ganham a barra de título e os três botões do Mac. Ao mudar, o WacOS reinicia (os apps continuam abertos).", L"Windows のプログラムに Mac のタイトルバーと 3 つのボタンが付きます。変更すると WacOS が再起動します (アプリは開いたままです)。" },
+{ L"Ouvindo…", L"聞き取り中…" },
+{ L"O reconhecimento de fala do Windows não está disponível neste idioma.", L"この言語では Windows の音声認識を使えません。" },
+{ L"Para ditar, ligue o \"Reconhecimento de fala online\" em Configurações do Windows > Privacidade > Fala.", L"音声入力するには、Windows の設定 > プライバシー > 音声認識 で「オンライン音声認識」をオンにしてください。" },
+{ L"O Windows não deixou usar o microfone. Libere em Configurações > Privacidade > Microfone.", L"Windows がマイクの使用を許可しませんでした。設定 > プライバシー > マイク で許可してください。" },
+{ L"Não deu para ouvir agora. Confira se há um microfone ligado.", L"今は聞き取れません。マイクが接続されているか確認してください。" },
+{ L"Ex.: organize em tópicos, traduza para o inglês…", L"例:トピックごとに整理、英語に翻訳…" },
+{ L"Ferramentas de Escrita", L"作文ツール" },
+{ L"Escreva algo na nota (ou selecione um trecho) antes de usar as Ferramentas de Escrita.", L"作文ツールを使う前に、メモに何か書く(または範囲を選択する)してください。" },
+{ L"Escolha um serviço de IA em Ajustes do Sistema > Apple Intelligence e Siri.", L"システム設定 > Apple Intelligence と Siri で AI サービスを選んでください。" },
+{ L"O serviço recusou o pedido:", L"サービスがリクエストを拒否しました:" },
+{ L"A nota mudou enquanto a IA escrevia. Tente de novo.", L"AI の作成中にメモが変更されました。もう一度お試しください。" },
+{ L"Pedir à IA", L"AI に頼む" },
+{ L"Descreva o que fazer com o texto selecionado (ou com a nota inteira).", L"選択したテキスト(またはメモ全体)をどうするか書いてください。" },
+{ L"Enviar", L"送信" },
+{ L"Escrevendo…", L"作成中…" },
+{ L"Reescrever", L"書き直す" },
+{ L"Amigável", L"フレンドリー" },
+{ L"Profissional", L"プロフェッショナル" },
+{ L"Conciso", L"簡潔" },
+{ L"Resumo", L"要約" },
+{ L"Pontos-chave", L"要点" },
+{ L"Tabela", L"表" },
+{ L"Pedir à IA…", L"AI に頼む…" },
+{ L"No computador, sem IA", L"このコンピュータで(AI なし)" },
+{ L"Revisando…", L"校正中…" },
+{ L"Reescrevendo…", L"書き直し中…" },
+{ L"Resumindo…", L"要約中…" },
+{ L"Organizando…", L"整理中…" },
+{ L"Usar IA: escolha um serviço em Ajustes do Sistema > Apple Intelligence e Siri", L"AI を使う:システム設定 > Apple Intelligence と Siri でサービスを選択" },
diff --git a/src/comum/idioma_ko.inc b/src/comum/idioma_ko.inc
index 08520ad..d1cd646 100644
--- a/src/comum/idioma_ko.inc
+++ b/src/comum/idioma_ko.inc
@@ -1706,3 +1706,32 @@
{ L"Recursos que ainda estão em teste. Podem mudar ou ter falhas: ligue para experimentar e conte o que achou no GitHub do WacOS.", L"아직 테스트 중인 기능입니다. 바뀌거나 문제가 있을 수 있습니다. 켜서 사용해 보고 WacOS GitHub에 의견을 남겨 주세요." },
{ L"Barra de título do Mac em todos os apps", L"모든 앱에 Mac 제목 막대" },
{ L"Os programas do Windows ganham a barra de título e os três botões do Mac. Ao mudar, o WacOS reinicia (os apps continuam abertos).", L"Windows 프로그램에 Mac의 제목 막대와 세 버튼이 생깁니다. 바꾸면 WacOS가 다시 시작됩니다(앱은 열린 채로 유지됩니다)." },
+{ L"Ouvindo…", L"듣는 중…" },
+{ L"O reconhecimento de fala do Windows não está disponível neste idioma.", L"이 언어에서는 Windows 음성 인식을 사용할 수 없습니다." },
+{ L"Para ditar, ligue o \"Reconhecimento de fala online\" em Configurações do Windows > Privacidade > Fala.", L"받아쓰려면 Windows 설정 > 개인 정보 > 음성에서 \"온라인 음성 인식\"을 켜세요." },
+{ L"O Windows não deixou usar o microfone. Libere em Configurações > Privacidade > Microfone.", L"Windows가 마이크 사용을 허용하지 않았습니다. 설정 > 개인 정보 > 마이크에서 허용하세요." },
+{ L"Não deu para ouvir agora. Confira se há um microfone ligado.", L"지금은 들을 수 없습니다. 마이크가 연결되어 있는지 확인하세요." },
+{ L"Ex.: organize em tópicos, traduza para o inglês…", L"예: 주제별로 정리, 영어로 번역…" },
+{ L"Ferramentas de Escrita", L"글쓰기 도구" },
+{ L"Escreva algo na nota (ou selecione um trecho) antes de usar as Ferramentas de Escrita.", L"글쓰기 도구를 사용하기 전에 메모에 내용을 쓰거나 텍스트를 선택하세요." },
+{ L"Escolha um serviço de IA em Ajustes do Sistema > Apple Intelligence e Siri.", L"시스템 설정 > Apple Intelligence 및 Siri에서 AI 서비스를 선택하세요." },
+{ L"O serviço recusou o pedido:", L"서비스가 요청을 거부했습니다:" },
+{ L"A nota mudou enquanto a IA escrevia. Tente de novo.", L"AI가 작성하는 동안 메모가 변경되었습니다. 다시 시도하세요." },
+{ L"Pedir à IA", L"AI에게 요청" },
+{ L"Descreva o que fazer com o texto selecionado (ou com a nota inteira).", L"선택한 텍스트(또는 메모 전체)로 무엇을 할지 설명하세요." },
+{ L"Enviar", L"보내기" },
+{ L"Escrevendo…", L"작성 중…" },
+{ L"Reescrever", L"다시 쓰기" },
+{ L"Amigável", L"친근하게" },
+{ L"Profissional", L"전문적으로" },
+{ L"Conciso", L"간결하게" },
+{ L"Resumo", L"요약" },
+{ L"Pontos-chave", L"핵심 사항" },
+{ L"Tabela", L"표" },
+{ L"Pedir à IA…", L"AI에게 요청…" },
+{ L"No computador, sem IA", L"이 컴퓨터에서, AI 없이" },
+{ L"Revisando…", L"교정 중…" },
+{ L"Reescrevendo…", L"다시 쓰는 중…" },
+{ L"Resumindo…", L"요약 중…" },
+{ L"Organizando…", L"정리 중…" },
+{ L"Usar IA: escolha um serviço em Ajustes do Sistema > Apple Intelligence e Siri", L"AI 사용: 시스템 설정 > Apple Intelligence 및 Siri에서 서비스를 선택" },
diff --git a/src/comum/idioma_pl.inc b/src/comum/idioma_pl.inc
index b109b4b..44a4c9c 100644
--- a/src/comum/idioma_pl.inc
+++ b/src/comum/idioma_pl.inc
@@ -1706,3 +1706,32 @@
{ L"Recursos que ainda estão em teste. Podem mudar ou ter falhas: ligue para experimentar e conte o que achou no GitHub do WacOS.", L"Funkcje wciąż testowane. Mogą się zmienić lub mieć błędy: włącz je, aby wypróbować, i podziel się opinią na GitHubie WacOS." },
{ L"Barra de título do Mac em todos os apps", L"Pasek tytułu Maca we wszystkich aplikacjach" },
{ L"Os programas do Windows ganham a barra de título e os três botões do Mac. Ao mudar, o WacOS reinicia (os apps continuam abertos).", L"Programy Windows dostają pasek tytułu i trzy przyciski Maca. Zmiana uruchamia WacOS ponownie (aplikacje zostają otwarte)." },
+{ L"Ouvindo…", L"Słucham…" },
+{ L"O reconhecimento de fala do Windows não está disponível neste idioma.", L"Rozpoznawanie mowy Windows nie jest dostępne w tym języku." },
+{ L"Para ditar, ligue o \"Reconhecimento de fala online\" em Configurações do Windows > Privacidade > Fala.", L"Aby dyktować, włącz \"Rozpoznawanie mowy online\" w Ustawieniach Windows > Prywatność > Mowa." },
+{ L"O Windows não deixou usar o microfone. Libere em Configurações > Privacidade > Microfone.", L"Windows nie zezwolił na mikrofon. Zezwól w Ustawieniach > Prywatność > Mikrofon." },
+{ L"Não deu para ouvir agora. Confira se há um microfone ligado.", L"Nie można teraz słuchać. Sprawdź, czy mikrofon jest podłączony." },
+{ L"Ex.: organize em tópicos, traduza para o inglês…", L"Np.: uporządkuj w tematy, przetłumacz na angielski…" },
+{ L"Ferramentas de Escrita", L"Narzędzia pisania" },
+{ L"Escreva algo na nota (ou selecione um trecho) antes de usar as Ferramentas de Escrita.", L"Napisz coś w notatce (lub zaznacz fragment) przed użyciem Narzędzi pisania." },
+{ L"Escolha um serviço de IA em Ajustes do Sistema > Apple Intelligence e Siri.", L"Wybierz usługę AI w Ustawieniach systemowych > Apple Intelligence i Siri." },
+{ L"O serviço recusou o pedido:", L"Usługa odrzuciła prośbę:" },
+{ L"A nota mudou enquanto a IA escrevia. Tente de novo.", L"Notatka zmieniła się, gdy AI pisała. Spróbuj ponownie." },
+{ L"Pedir à IA", L"Poproś AI" },
+{ L"Descreva o que fazer com o texto selecionado (ou com a nota inteira).", L"Opisz, co zrobić z zaznaczonym tekstem (lub całą notatką)." },
+{ L"Enviar", L"Wyślij" },
+{ L"Escrevendo…", L"Pisanie…" },
+{ L"Reescrever", L"Przepisz" },
+{ L"Amigável", L"Przyjaźnie" },
+{ L"Profissional", L"Profesjonalnie" },
+{ L"Conciso", L"Zwięźle" },
+{ L"Resumo", L"Podsumowanie" },
+{ L"Pontos-chave", L"Kluczowe punkty" },
+{ L"Tabela", L"Tabela" },
+{ L"Pedir à IA…", L"Poproś AI…" },
+{ L"No computador, sem IA", L"Na komputerze, bez AI" },
+{ L"Revisando…", L"Korekta…" },
+{ L"Reescrevendo…", L"Przepisywanie…" },
+{ L"Resumindo…", L"Podsumowywanie…" },
+{ L"Organizando…", L"Porządkowanie…" },
+{ L"Usar IA: escolha um serviço em Ajustes do Sistema > Apple Intelligence e Siri", L"Użyj AI: wybierz usługę w Ustawieniach systemowych > Apple Intelligence i Siri" },
diff --git a/src/comum/idioma_ru.inc b/src/comum/idioma_ru.inc
index 09eb454..b0ddf55 100644
--- a/src/comum/idioma_ru.inc
+++ b/src/comum/idioma_ru.inc
@@ -1706,3 +1706,32 @@
{ L"Recursos que ainda estão em teste. Podem mudar ou ter falhas: ligue para experimentar e conte o que achou no GitHub do WacOS.", L"Функции, которые ещё тестируются. Они могут измениться или работать с ошибками: включите, чтобы попробовать, и расскажите о впечатлениях на GitHub WacOS." },
{ L"Barra de título do Mac em todos os apps", L"Заголовок Mac во всех приложениях" },
{ L"Os programas do Windows ganham a barra de título e os três botões do Mac. Ao mudar, o WacOS reinicia (os apps continuam abertos).", L"Программы Windows получают заголовок окна и три кнопки Mac. При изменении WacOS перезапускается (приложения остаются открытыми)." },
+{ L"Ouvindo…", L"Слушаю…" },
+{ L"O reconhecimento de fala do Windows não está disponível neste idioma.", L"Распознавание речи Windows недоступно на этом языке." },
+{ L"Para ditar, ligue o \"Reconhecimento de fala online\" em Configurações do Windows > Privacidade > Fala.", L"Чтобы диктовать, включите «Распознавание речи в Интернете» в Параметрах Windows > Конфиденциальность > Речь." },
+{ L"O Windows não deixou usar o microfone. Libere em Configurações > Privacidade > Microfone.", L"Windows не разрешил использовать микрофон. Разрешите в Параметрах > Конфиденциальность > Микрофон." },
+{ L"Não deu para ouvir agora. Confira se há um microfone ligado.", L"Сейчас не удаётся слушать. Проверьте, подключён ли микрофон." },
+{ L"Ex.: organize em tópicos, traduza para o inglês…", L"Напр.: разбей на темы, переведи на английский…" },
+{ L"Ferramentas de Escrita", L"Инструменты письма" },
+{ L"Escreva algo na nota (ou selecione um trecho) antes de usar as Ferramentas de Escrita.", L"Напишите что-нибудь в заметке (или выделите фрагмент), прежде чем использовать Инструменты письма." },
+{ L"Escolha um serviço de IA em Ajustes do Sistema > Apple Intelligence e Siri.", L"Выберите сервис ИИ в Системных настройках > Apple Intelligence и Siri." },
+{ L"O serviço recusou o pedido:", L"Сервис отклонил запрос:" },
+{ L"A nota mudou enquanto a IA escrevia. Tente de novo.", L"Заметка изменилась, пока ИИ писал. Попробуйте ещё раз." },
+{ L"Pedir à IA", L"Спросить ИИ" },
+{ L"Descreva o que fazer com o texto selecionado (ou com a nota inteira).", L"Опишите, что сделать с выделенным текстом (или всей заметкой)." },
+{ L"Enviar", L"Отправить" },
+{ L"Escrevendo…", L"Пишет…" },
+{ L"Reescrever", L"Переписать" },
+{ L"Amigável", L"Дружелюбно" },
+{ L"Profissional", L"Профессионально" },
+{ L"Conciso", L"Кратко" },
+{ L"Resumo", L"Сводка" },
+{ L"Pontos-chave", L"Ключевые пункты" },
+{ L"Tabela", L"Таблица" },
+{ L"Pedir à IA…", L"Спросить ИИ…" },
+{ L"No computador, sem IA", L"На компьютере, без ИИ" },
+{ L"Revisando…", L"Проверка…" },
+{ L"Reescrevendo…", L"Переписывание…" },
+{ L"Resumindo…", L"Сводка…" },
+{ L"Organizando…", L"Упорядочивание…" },
+{ L"Usar IA: escolha um serviço em Ajustes do Sistema > Apple Intelligence e Siri", L"Использовать ИИ: выберите сервис в Системных настройках > Apple Intelligence и Siri" },
diff --git a/src/comum/idioma_tr.inc b/src/comum/idioma_tr.inc
index d38fa2e..842c284 100644
--- a/src/comum/idioma_tr.inc
+++ b/src/comum/idioma_tr.inc
@@ -1706,3 +1706,32 @@
{ L"Recursos que ainda estão em teste. Podem mudar ou ter falhas: ligue para experimentar e conte o que achou no GitHub do WacOS.", L"Hâlâ test edilen özellikler. Değişebilir veya hata içerebilir: denemek için açın ve düşüncelerinizi WacOS'un GitHub sayfasında paylaşın." },
{ L"Barra de título do Mac em todos os apps", L"Tüm uygulamalarda Mac başlık çubuğu" },
{ L"Os programas do Windows ganham a barra de título e os três botões do Mac. Ao mudar, o WacOS reinicia (os apps continuam abertos).", L"Windows programları Mac başlık çubuğunu ve üç düğmesini alır. Değiştirmek WacOS’u yeniden başlatır (uygulamalarınız açık kalır)." },
+{ L"Ouvindo…", L"Dinleniyor…" },
+{ L"O reconhecimento de fala do Windows não está disponível neste idioma.", L"Windows konuşma tanıma bu dilde kullanılamıyor." },
+{ L"Para ditar, ligue o \"Reconhecimento de fala online\" em Configurações do Windows > Privacidade > Fala.", L"Dikte etmek için Windows Ayarları > Gizlilik > Konuşma bölümünde \"Çevrimiçi konuşma tanıma\"yı açın." },
+{ L"O Windows não deixou usar o microfone. Libere em Configurações > Privacidade > Microfone.", L"Windows mikrofona izin vermedi. Ayarlar > Gizlilik > Mikrofon'dan izin verin." },
+{ L"Não deu para ouvir agora. Confira se há um microfone ligado.", L"Şu anda dinlenemiyor. Bir mikrofonun bağlı olduğunu kontrol edin." },
+{ L"Ex.: organize em tópicos, traduza para o inglês…", L"Örn.: konulara ayır, İngilizceye çevir…" },
+{ L"Ferramentas de Escrita", L"Yazma Araçları" },
+{ L"Escreva algo na nota (ou selecione um trecho) antes de usar as Ferramentas de Escrita.", L"Yazma Araçlarını kullanmadan önce notta bir şey yazın (veya bir bölüm seçin)." },
+{ L"Escolha um serviço de IA em Ajustes do Sistema > Apple Intelligence e Siri.", L"Sistem Ayarları > Apple Intelligence ve Siri’den bir yapay zekâ hizmeti seçin." },
+{ L"O serviço recusou o pedido:", L"Hizmet isteği reddetti:" },
+{ L"A nota mudou enquanto a IA escrevia. Tente de novo.", L"Yapay zekâ yazarken not değişti. Yeniden deneyin." },
+{ L"Pedir à IA", L"Yapay Zekâya Sor" },
+{ L"Descreva o que fazer com o texto selecionado (ou com a nota inteira).", L"Seçili metinle (veya notun tamamıyla) ne yapılacağını yazın." },
+{ L"Enviar", L"Gönder" },
+{ L"Escrevendo…", L"Yazılıyor…" },
+{ L"Reescrever", L"Yeniden Yaz" },
+{ L"Amigável", L"Samimi" },
+{ L"Profissional", L"Profesyonel" },
+{ L"Conciso", L"Kısa" },
+{ L"Resumo", L"Özet" },
+{ L"Pontos-chave", L"Ana Noktalar" },
+{ L"Tabela", L"Tablo" },
+{ L"Pedir à IA…", L"Yapay Zekâya Sor…" },
+{ L"No computador, sem IA", L"Bilgisayarda, yapay zekâsız" },
+{ L"Revisando…", L"Düzeltiliyor…" },
+{ L"Reescrevendo…", L"Yeniden yazılıyor…" },
+{ L"Resumindo…", L"Özetleniyor…" },
+{ L"Organizando…", L"Düzenleniyor…" },
+{ L"Usar IA: escolha um serviço em Ajustes do Sistema > Apple Intelligence e Siri", L"Yapay zekâ kullan: Sistem Ayarları > Apple Intelligence ve Siri’den bir hizmet seçin" },
diff --git a/src/comum/idioma_zh.inc b/src/comum/idioma_zh.inc
index 7f224e8..dc24e74 100644
--- a/src/comum/idioma_zh.inc
+++ b/src/comum/idioma_zh.inc
@@ -1706,3 +1706,32 @@
{ L"Recursos que ainda estão em teste. Podem mudar ou ter falhas: ligue para experimentar e conte o que achou no GitHub do WacOS.", L"仍在测试中的功能。它们可能会变化或有问题:打开即可试用,并在 WacOS 的 GitHub 上告诉我们你的看法。" },
{ L"Barra de título do Mac em todos os apps", L"所有应用使用 Mac 标题栏" },
{ L"Os programas do Windows ganham a barra de título e os três botões do Mac. Ao mudar, o WacOS reinicia (os apps continuam abertos).", L"Windows 程序会获得 Mac 的标题栏和三个按钮。更改后 WacOS 会重新启动(你的应用保持打开)。" },
+{ L"Ouvindo…", L"正在聆听…" },
+{ L"O reconhecimento de fala do Windows não está disponível neste idioma.", L"此语言无法使用 Windows 语音识别。" },
+{ L"Para ditar, ligue o \"Reconhecimento de fala online\" em Configurações do Windows > Privacidade > Fala.", L"要听写,请在 Windows 设置 > 隐私 > 语音 中打开\"联机语音识别\"。" },
+{ L"O Windows não deixou usar o microfone. Libere em Configurações > Privacidade > Microfone.", L"Windows 未允许使用麦克风。请在设置 > 隐私 > 麦克风 中允许。" },
+{ L"Não deu para ouvir agora. Confira se há um microfone ligado.", L"现在无法聆听。请检查是否连接了麦克风。" },
+{ L"Ex.: organize em tópicos, traduza para o inglês…", L"例如:按主题整理、翻译成英文…" },
+{ L"Ferramentas de Escrita", L"写作工具" },
+{ L"Escreva algo na nota (ou selecione um trecho) antes de usar as Ferramentas de Escrita.", L"使用写作工具前,请先在备忘录中写点内容(或选择一段文字)。" },
+{ L"Escolha um serviço de IA em Ajustes do Sistema > Apple Intelligence e Siri.", L"请在系统设置 > Apple 智能与 Siri 中选择一个 AI 服务。" },
+{ L"O serviço recusou o pedido:", L"服务拒绝了请求:" },
+{ L"A nota mudou enquanto a IA escrevia. Tente de novo.", L"AI 写作期间备忘录已更改,请重试。" },
+{ L"Pedir à IA", L"询问 AI" },
+{ L"Descreva o que fazer com o texto selecionado (ou com a nota inteira).", L"描述要对所选文字(或整篇备忘录)做什么。" },
+{ L"Enviar", L"发送" },
+{ L"Escrevendo…", L"正在写作…" },
+{ L"Reescrever", L"重写" },
+{ L"Amigável", L"友好" },
+{ L"Profissional", L"专业" },
+{ L"Conciso", L"简洁" },
+{ L"Resumo", L"摘要" },
+{ L"Pontos-chave", L"要点" },
+{ L"Tabela", L"表格" },
+{ L"Pedir à IA…", L"询问 AI…" },
+{ L"No computador, sem IA", L"在本机,不用 AI" },
+{ L"Revisando…", L"正在校对…" },
+{ L"Reescrevendo…", L"正在重写…" },
+{ L"Resumindo…", L"正在总结…" },
+{ L"Organizando…", L"正在整理…" },
+{ L"Usar IA: escolha um serviço em Ajustes do Sistema > Apple Intelligence e Siri", L"使用 AI:在系统设置 > Apple 智能与 Siri 中选择服务" },
diff --git a/src/comum/siri.h b/src/comum/siri.h
index c908bad..98b113c 100644
--- a/src/comum/siri.h
+++ b/src/comum/siri.h
@@ -326,4 +326,82 @@ inline std::wstring RodaCli(const std::wstring& comando, const std::wstring& per
return Wide(saida);
}
+// ---------------------------------------------------------------- um pedido de texto (Ferramentas de Escrita das Notas)
+// O serviço e o modelo escolhidos para a Siri (siri_provedor, siri_modelo), com a chave dela. Uma tentativa a mais se o
+// serviço estiver sobrecarregado, e o preferido da lista se o modelo saiu do ar ou ficou sem cota.
+// erro: 0 ok, 1 sem serviço escolhido, 2 sem chave, 3 sem conexão, 4 o serviço recusou (msg: a mensagem dele),
+// 5 o app local (CLI) não respondeu.
+struct Gerado { std::wstring texto, msg; int erro = 0; };
+inline Gerado Gera(int p, std::wstring modelo, const std::wstring& sistema, const std::wstring& pedido) {
+ Gerado g;
+ const auto& provs = Provedores();
+ if (p <= 0 || p >= (int)provs.size()) { g.erro = 1; return g; }
+ const auto& pv = provs[p];
+ if (pv.fmt == F_CLI) {
+ DWORD codigo = 0; bool tempo = false;
+ wchar_t tmp[MAX_PATH]; GetTempPathW(MAX_PATH, tmp);
+ std::wstring ultima = std::wstring(tmp) + L"WacOS-Siri\\ultima.txt";
+ DeleteFileW(ultima.c_str());
+ std::wstring r = RodaCli(pv.caminho, sistema + L"\n\nDo not run commands or edit files.\n\n" + pedido, codigo, tempo);
+ HANDLE h = CreateFileW(ultima.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
+ if (h != INVALID_HANDLE_VALUE) { // o Codex grava só a última mensagem num arquivo
+ DWORD sz = GetFileSize(h, nullptr), n = 0;
+ std::string b(sz < (1u << 20) ? sz : 0, 0);
+ if (!b.empty() && ReadFile(h, b.data(), sz, &n, nullptr)) r = Wide(b);
+ CloseHandle(h);
+ DeleteFileW(ultima.c_str());
+ }
+ if (tempo || codigo != 0 || r.empty()) { g.erro = 5; g.msg = pv.nome; return g; }
+ g.texto = r;
+ return g;
+ }
+ std::wstring chave = pv.precisaChave ? LeChave(p) : L"";
+ if (pv.precisaChave && chave.empty()) { g.erro = 2; return g; }
+ if (modelo.empty() && !pv.modelos.empty()) modelo = pv.modelos[0];
+ if (modelo.empty()) { std::wstring e; auto l = ListaModelos(p, e); if (!l.empty()) modelo = l[0]; }
+ std::wstring cab = Cabecalhos(pv, chave);
+ SecureZeroMemory(chave.data(), chave.size() * sizeof(wchar_t));
+ Resposta r;
+ for (int tentativa = 0; tentativa < 3; tentativa++) {
+ std::string body;
+ std::wstring caminho = pv.caminho;
+ if (pv.fmt == F_GEMINI) {
+ size_t m = caminho.find(L"{m}"); if (m != std::wstring::npos) caminho.replace(m, 3, modelo);
+ body = "{\"systemInstruction\":{\"parts\":[{\"text\":" + JStr(sistema) + "}]},\"contents\":[{\"role\":\"user\",\"parts\":[{\"text\":" + JStr(pedido) + "}]}]}";
+ } else if (pv.fmt == F_ANTHROPIC) {
+ body = "{\"model\":" + JStr(modelo) + ",\"max_tokens\":4096,\"system\":" + JStr(sistema) +
+ ",\"messages\":[{\"role\":\"user\",\"content\":" + JStr(pedido) + "}]}";
+ } else {
+ body = "{\"model\":" + JStr(modelo) + ",\"messages\":[{\"role\":\"system\",\"content\":" + JStr(sistema) + "},{\"role\":\"user\",\"content\":" + JStr(pedido) + "}]" +
+ (pv.fmt == F_OLLAMA ? ",\"stream\":false}" : "}");
+ }
+ r = Http(pv, L"POST", caminho, cab, body, 120000);
+ if (r.falha || tentativa >= 2) break;
+ if (r.status == 503 || r.status == 500 || r.status == 529) { Sleep(1500); continue; }
+ std::wstring m = ErroDoServico(r.corpo); for (auto& c : m) c = (wchar_t)towlower(c);
+ bool trocar = (r.status == 429 && m.find(L"quota") != std::wstring::npos) ||
+ ((r.status == 400 || r.status == 404) && (m.find(L"not found") != std::wstring::npos || m.find(L"no longer") != std::wstring::npos ||
+ m.find(L"does not exist") != std::wstring::npos || m.find(L"model") != std::wstring::npos));
+ if (!trocar) break;
+ std::wstring e; auto lista = ListaModelos(p, e);
+ if (lista.empty() || lista[0] == modelo) break;
+ modelo = lista[0]; // só neste pedido
+ }
+ SecureZeroMemory(cab.data(), cab.size() * sizeof(wchar_t));
+ if (r.falha) { g.erro = 3; return g; }
+ if (r.status >= 200 && r.status < 300) {
+ std::wstring t;
+ bool ok = pv.fmt == F_GEMINI ? JLe(r.corpo, "text", r.corpo.find("\"candidates\""), t)
+ : pv.fmt == F_ANTHROPIC ? JLe(r.corpo, "text", r.corpo.find("\"content\""), t)
+ : JLe(r.corpo, "content", r.corpo.find("\"message\""), t);
+ if (ok && !t.empty()) { g.texto = t; return g; }
+ }
+ g.erro = 4;
+ g.msg = ErroDoServico(r.corpo);
+ if (size_t q = g.msg.find(L'\n'); q != std::wstring::npos) g.msg = g.msg.substr(0, q);
+ if (g.msg.size() > 240) g.msg = g.msg.substr(0, 237) + L"...";
+ if (g.msg.empty()) g.msg = L"HTTP " + std::to_wstring(r.status);
+ return g;
+}
+
} // namespace siri
diff --git a/src/notas/editor.cpp b/src/notas/editor.cpp
index 32afd09..407b492 100644
--- a/src/notas/editor.cpp
+++ b/src/notas/editor.cpp
@@ -1,847 +1,847 @@
-// Notas: o editor de texto rico. Cada parágrafo vira um IDWriteTextLayout (estilo, negrito/itálico/
-// sublinhado/tachado, realces, variáveis e resultados das Notas Matemáticas); cursor amarelo, seleção,
-// listas (marcadores, traços, números, verificação com bolinhas), seções recolhíveis nos títulos,
-// desfazer/refazer e área de transferência com formatação (formato próprio + texto puro).
-#include "notas.h"
-#include <cwctype>
-#include <algorithm>
-#include <cmath>
-#include "../comum/simbolos.h"
-#include "../comum/semaforo.h" // tema Leopard: o papel amarelo pautado das Notas do 10.5
-#include <wincodec.h>
-#include <shellapi.h>
-#include <map>
-// Tabelas, anexos e Ferramentas de Escrita (botões da barra do macOS 26/27):
-// - tabela: cada linha é um parágrafo K_ROW com as células separadas por TAB; o layout usa uma parada de tabulação por
-// coluna (largura da tabela / colunas), sem quebra de linha, e a grade é desenhada por cima. Tab/Shift+Tab andam de
-// célula em célula, Enter abre uma linha nova e Enter numa linha vazia no fim sai da tabela.
-// - anexo: parágrafo K_FILE sem texto, com o arquivo em `src` (copiado para Notas\anexos). Imagens aparecem na nota
-// (WIC -> bitmap do Direct2D, até 400 pt de altura); outros arquivos viram um cartão; clique duplo abre no programa
-// padrão. O cursor fica à esquerda do anexo; Backspace/Delete apagam o anexo inteiro.
-// - Ferramentas de Escrita: transformações locais, sem IA (revisar espaços/pontuação/maiúsculas, lista, tabela, caixa).
-
-using editor::Pos;
-
-namespace {
-
-Note* N;
-Pos caret, anchor;
-bool focused, blinkOn = true;
-float scrollY, desiredX = -1;
-D2D1_RECT_F area{};
-std::wstring family = L"Segoe UI", monoFamily = L"Consolas";
-bool dark;
-std::wstring query;
-uint8_t typing; bool typingSet;
-bool wantReveal;
-int hoverChevron = -1;
-int clickMode; // 1 caractere, 2 palavra, 3 parágrafo (arrastar estende nessa unidade)
-Pos clickA, clickB;
-
+// Notas: o editor de texto rico. Cada parágrafo vira um IDWriteTextLayout (estilo, negrito/itálico/
+// sublinhado/tachado, realces, variáveis e resultados das Notas Matemáticas); cursor amarelo, seleção,
+// listas (marcadores, traços, números, verificação com bolinhas), seções recolhíveis nos títulos,
+// desfazer/refazer e área de transferência com formatação (formato próprio + texto puro).
+#include "notas.h"
+#include <cwctype>
+#include <algorithm>
+#include <cmath>
+#include "../comum/simbolos.h"
+#include "../comum/semaforo.h" // tema Leopard: o papel amarelo pautado das Notas do 10.5
+#include <wincodec.h>
+#include <shellapi.h>
+#include <map>
+// Tabelas, anexos e Ferramentas de Escrita (botões da barra do macOS 26/27):
+// - tabela: cada linha é um parágrafo K_ROW com as células separadas por TAB; o layout usa uma parada de tabulação por
+// coluna (largura da tabela / colunas), sem quebra de linha, e a grade é desenhada por cima. Tab/Shift+Tab andam de
+// célula em célula, Enter abre uma linha nova e Enter numa linha vazia no fim sai da tabela.
+// - anexo: parágrafo K_FILE sem texto, com o arquivo em `src` (copiado para Notas\anexos). Imagens aparecem na nota
+// (WIC -> bitmap do Direct2D, até 400 pt de altura); outros arquivos viram um cartão; clique duplo abre no programa
+// padrão. O cursor fica à esquerda do anexo; Backspace/Delete apagam o anexo inteiro.
+// - Ferramentas de Escrita: transformações locais, sem IA (revisar espaços/pontuação/maiúsculas, lista, tabela, caixa).
+
+using editor::Pos;
+
+namespace {
+
+Note* N;
+Pos caret, anchor;
+bool focused, blinkOn = true;
+float scrollY, desiredX = -1;
+D2D1_RECT_F area{};
+std::wstring family = L"Segoe UI", monoFamily = L"Consolas";
+bool dark;
+std::wstring query;
+uint8_t typing; bool typingSet;
+bool wantReveal;
+int hoverChevron = -1;
+int clickMode; // 1 caractere, 2 palavra, 3 parágrafo (arrastar estende nessa unidade)
+Pos clickA, clickB;
+
struct PL { IDWriteTextLayout* tl = nullptr; float x = 0, y = 0, h = 0, w = 0, base = 0; bool hidden = false; int number = 0, resultAt = -1;
float pad = 0; // linha de tabela: folga em cima e embaixo do texto
int cols = 0; float colW = 0, tableW = 0; // linha de tabela
- float imgW = 0, imgH = 0; }; // anexo: tamanho na nota
-std::vector<PL> pl;
-bool dirtyLayout = true;
-float layoutW = -1;
-float contentH;
-std::vector<MathLine> math;
-ID2D1DeviceContext* lastDc;
-ID2D1SolidColorBrush *brAccent, *brHi[HI_COUNT + 1];
-IDWriteTextFormat* fmt[5];
-
-const float MARGIN = 24, INDENT = 26, TOP_PAD = 34, CELL_PAD = 8, ROW_PAD = 7;
-
-// medidas de cada estilo (tamanho, altura da linha, espaço depois)
-struct StyleM { float size, line, after; DWRITE_FONT_WEIGHT w; };
-const StyleM SM[5] = {
- { 24, 30, 6, DWRITE_FONT_WEIGHT_BOLD }, // Título
- { 18, 23, 4, DWRITE_FONT_WEIGHT_BOLD }, // Cabeçalho
- { 14, 18, 3, DWRITE_FONT_WEIGHT_BOLD }, // Subcabeçalho
- { 13, 17.5f, 0, DWRITE_FONT_WEIGHT_NORMAL }, // Corpo
- { 12, 16.5f, 0, DWRITE_FONT_WEIGHT_NORMAL }, // Monoespaçado
-};
-
-D2D1_COLOR_F TextColor() { return dark ? D2D1::ColorF(1, 1, 1, 0.88f) : D2D1::ColorF(0.11f, 0.11f, 0.12f); }
-D2D1_COLOR_F Text2() { return dark ? D2D1::ColorF(1, 1, 1, 0.45f) : D2D1::ColorF(0, 0, 0, 0.45f); }
-
-// realces do Sequoia: roxo, rosa, laranja, menta, azul (texto na cor, fundo claro da mesma cor)
-D2D1_COLOR_F HiText(int h) {
- static const D2D1_COLOR_F L[HI_COUNT] = { D2D1::ColorF(0.55f, 0.27f, 0.85f), D2D1::ColorF(0.86f, 0.18f, 0.45f), D2D1::ColorF(0.85f, 0.42f, 0.0f), D2D1::ColorF(0.0f, 0.55f, 0.48f), D2D1::ColorF(0.0f, 0.45f, 0.90f) };
- static const D2D1_COLOR_F D[HI_COUNT] = { D2D1::ColorF(0.80f, 0.62f, 1.0f), D2D1::ColorF(1.0f, 0.50f, 0.68f), D2D1::ColorF(1.0f, 0.68f, 0.35f), D2D1::ColorF(0.40f, 0.90f, 0.80f), D2D1::ColorF(0.45f, 0.72f, 1.0f) };
- return dark ? D[h - 1] : L[h - 1];
-}
-D2D1_COLOR_F HiBack(int h) {
- static const D2D1_COLOR_F c[HI_COUNT] = { D2D1::ColorF(0.69f, 0.42f, 0.98f), D2D1::ColorF(1.0f, 0.30f, 0.55f), D2D1::ColorF(1.0f, 0.58f, 0.15f), D2D1::ColorF(0.20f, 0.82f, 0.72f), D2D1::ColorF(0.25f, 0.60f, 1.0f) };
- D2D1_COLOR_F k = c[h - 1]; k.a = dark ? 0.30f : 0.22f; return k;
-}
-
-bool Less(Pos a, Pos b) { return a.p < b.p || (a.p == b.p && a.o < b.o); }
-bool Same(Pos a, Pos b) { return a.p == b.p && a.o == b.o; }
-Pos SelStart() { return Less(caret, anchor) ? caret : anchor; }
-Pos SelEnd() { return Less(caret, anchor) ? anchor : caret; }
-bool HasSel() { return !Same(caret, anchor); }
-Para& P(int i) { return N->paras[i]; }
-int Count() { return N ? (int)N->paras.size() : 0; }
-int Level(const Para& p) { return p.kind == K_TEXT && p.style <= S_SUBHEADING ? p.style : 99; }
-bool IsRow(int i) { return i >= 0 && i < Count() && P(i).kind == K_ROW; }
-bool IsFile(int i) { return i >= 0 && i < Count() && P(i).kind == K_FILE; }
-int Tabs(const std::wstring& s) { return (int)std::count(s.begin(), s.end(), L'\t'); }
-int TableCols(int i) { // colunas do bloco de linhas que contém i (a linha mais larga manda)
- int a = i, b = i, n = 1;
- while (IsRow(a - 1)) a--;
- while (IsRow(b + 1)) b++;
- for (int k = a; k <= b; k++) n = std::max(n, Tabs(P(k).text) + 1);
- return n;
-}
-float After(int i) { return IsFile(i) ? 10.f : IsRow(i) ? (IsRow(i + 1) ? 0.f : 10.f) : SM[P(i).style].after; }
-bool IsImageFile(const std::wstring& path) {
- std::wstring e = path.substr(path.find_last_of(L'.') + 1);
- for (auto& c : e) c = towlower(c);
- return e == L"png" || e == L"jpg" || e == L"jpeg" || e == L"gif" || e == L"bmp" || e == L"tif" || e == L"tiff" || e == L"webp" || e == L"heic" || e == L"ico";
-}
-// nome mostrado: sem o prefixo único que o AddAttachment põe ("1dd7...-foto.png" -> "foto.png")
-std::wstring ShownName(const std::wstring& path) {
- std::wstring n = path.substr(path.find_last_of(L"\\/") + 1);
- size_t d = n.find(L'-');
- if (d != std::wstring::npos && d >= 8 && n.find_first_not_of(L"0123456789abcdef") == d) n = n.substr(d + 1);
- return n;
-}
-
-// imagens dos anexos (por contexto do Direct2D; nullptr guardado = não é imagem ou não abriu)
-std::map<std::wstring, ID2D1Bitmap*> imgs;
-IWICImagingFactory* wic;
-void ReleaseImages() { for (auto& k : imgs) if (k.second) k.second->Release(); imgs.clear(); }
-ID2D1Bitmap* Img(ID2D1DeviceContext* dc, const std::wstring& path) {
- auto it = imgs.find(path);
- if (it != imgs.end()) return it->second;
- ID2D1Bitmap* bmp = nullptr;
- if (IsImageFile(path)) {
- if (!wic) CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic));
- IWICBitmapDecoder* dec = nullptr; IWICBitmapFrameDecode* fr = nullptr; IWICFormatConverter* cv = nullptr;
- if (wic && SUCCEEDED(wic->CreateDecoderFromFilename(path.c_str(), nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &dec)) &&
- SUCCEEDED(dec->GetFrame(0, &fr)) && SUCCEEDED(wic->CreateFormatConverter(&cv)) &&
- SUCCEEDED(cv->Initialize(fr, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeMedianCut)))
- dc->CreateBitmapFromWicBitmap(cv, nullptr, &bmp);
- if (cv) cv->Release(); if (fr) fr->Release(); if (dec) dec->Release();
- }
- imgs[path] = bmp;
- return bmp;
-}
-
-void ReleaseLayouts() { for (auto& l : pl) if (l.tl) l.tl->Release(); pl.clear(); dirtyLayout = true; }
-void ReleaseBrushes() {
- ReleaseImages();
- if (brAccent) brAccent->Release(); brAccent = nullptr;
- for (auto& b : brHi) { if (b) b->Release(); b = nullptr; }
-}
-
-void Clamp() {
- if (!N) return;
- auto fix = [](Pos& q) { q.p = std::clamp(q.p, 0, Count() - 1); q.o = std::clamp(q.o, 0, (int)P(q.p).text.size()); };
- fix(caret); fix(anchor);
-}
-
-// ---------------------------------------------------------------------------
-// layout
-void ComputeHidden() {
- int hideLevel = -1; // escondendo até achar um título de nível <= hideLevel
- for (int i = 0; i < Count(); i++) {
- int lv = Level(P(i));
- if (hideLevel >= 0) {
- if (lv <= hideLevel) hideLevel = -1;
- else { pl[i].hidden = true; continue; }
- }
- pl[i].hidden = false;
- if (P(i).collapsed && lv < 99) hideLevel = lv;
- }
-}
-
-void BuildLayouts(ID2D1DeviceContext* dc, float width) {
- if (dc != lastDc) { ReleaseBrushes(); ReleaseLayouts(); lastDc = dc; }
- if (!brAccent) {
- dc->CreateSolidColorBrush(AccentText(), &brAccent);
- for (int h = 1; h <= HI_COUNT; h++) dc->CreateSolidColorBrush(HiText(h), &brHi[h]);
- }
- if (!dirtyLayout && width == layoutW && (int)pl.size() == Count()) return;
- for (auto& l : pl) if (l.tl) l.tl->Release();
- pl.assign(Count(), PL{});
- layoutW = width;
- dirtyLayout = false;
- math = EvalMath(N->paras);
- int counters[10] = {};
- float y = TOP_PAD;
- for (int i = 0; i < Count(); i++) {
- Para& p = P(i);
- PL& l = pl[i];
- // numeração das listas numeradas
- if (p.list == L_NONE) std::fill(std::begin(counters), std::end(counters), 0);
- else {
- for (int k = p.indent + 1; k < 10; k++) counters[k] = 0;
- if (p.list == L_NUMBER) l.number = ++counters[std::min<int>(p.indent, 9)];
- else counters[std::min<int>(p.indent, 9)] = 0;
- }
- float base = MARGIN + p.indent * INDENT;
- if (p.kind == K_FILE) { // anexo: imagem na largura possível (até 400 de altura) ou cartão de 52
- l.x = l.base = base; l.w = std::max(40.f, width - base - MARGIN);
- gfx::dw->CreateTextLayout(L"", 0, fmt[S_BODY], l.w, 10000, &l.tl);
- if (l.tl) l.tl->SetLineSpacing(DWRITE_LINE_SPACING_METHOD_UNIFORM, SM[S_BODY].line, SM[S_BODY].line * 0.8f);
- if (ID2D1Bitmap* b = Img(dc, p.src)) {
- D2D1_SIZE_U px = b->GetPixelSize();
- // desenhos do Notas são gravados em 2x; o resto, 1 pixel = 1 pt
- float k = ShownName(p.src).rfind(L"desenho-", 0) == 0 || p.src.find(L"\\desenho-") != std::wstring::npos ? 0.5f : 1.f;
- float w = std::min(l.w, std::max(1.f, px.width * k)), h = w * px.height / std::max(1u, px.width);
- if (h > 400) { w *= 400 / h; h = 400; }
- l.imgW = w; l.imgH = h;
- } else { l.imgW = std::min(l.w, 320.f); l.imgH = 52; }
- l.h = l.imgH; l.y = y; y += l.h + After(i);
- continue;
- }
- if (p.kind == K_ROW) { // linha de tabela: uma parada de tabulação por coluna, sem quebra
- l.cols = TableCols(i); l.base = base;
- l.tableW = std::max(120.f, width - base - MARGIN); l.colW = l.tableW / l.cols;
- l.x = base + CELL_PAD; l.w = l.tableW - CELL_PAD; l.pad = ROW_PAD;
- }
- float lead = p.kind == K_ROW ? 0.f : p.list == L_CHECK ? 28.f : p.list != L_NONE ? 24.f : 0.f;
- if (p.kind != K_ROW) { l.x = base + lead; l.base = base; l.w = std::max(40.f, width - l.x - MARGIN); }
- std::wstring s = p.text;
- int resultAt = -1;
- if (i < (int)math.size() && !math[i].result.empty()) {
- if (s.size() >= 2 && s.back() == L'=' && s[s.size() - 2] == L' ') s += L' '; // "x =" -> "x = 5"
- resultAt = (int)s.size(); s += math[i].result;
- }
- l.resultAt = resultAt;
- const StyleM& m = SM[p.style];
- gfx::dw->CreateTextLayout(s.c_str(), (UINT32)s.size(), fmt[p.style], l.w, 10000, &l.tl);
- if (!l.tl) continue;
- l.tl->SetLineSpacing(DWRITE_LINE_SPACING_METHOD_UNIFORM, m.line, m.line * 0.8f);
- if (p.kind == K_ROW) { l.tl->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP); l.tl->SetIncrementalTabStop(l.colW); }
- UINT32 n = (UINT32)p.text.size();
- for (UINT32 k = 0; k < n;) { // corridas de atributos
- UINT32 j = k; uint8_t a = p.at[k];
- while (j < n && p.at[j] == a) j++;
- DWRITE_TEXT_RANGE r{ k, j - k };
- if (a & A_BOLD) l.tl->SetFontWeight(p.style == S_BODY || p.style == S_MONO ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_HEAVY, r);
- if (a & A_ITALIC) l.tl->SetFontStyle(DWRITE_FONT_STYLE_ITALIC, r);
- if (a & A_UNDER) l.tl->SetUnderline(TRUE, r);
- if (a & A_STRIKE) l.tl->SetStrikethrough(TRUE, r);
- if (HiOf(a)) l.tl->SetDrawingEffect(brHi[HiOf(a)], r);
- k = j;
- }
- if (i < (int)math.size())
- for (auto& v : math[i].vars) l.tl->SetDrawingEffect(brAccent, { (UINT32)v.first, (UINT32)v.second });
- if (resultAt >= 0) l.tl->SetDrawingEffect(brAccent, { (UINT32)resultAt, (UINT32)math[i].result.size() });
- DWRITE_TEXT_METRICS tm{}; l.tl->GetMetrics(&tm);
- l.h = std::max(tm.height, m.line);
- l.y = y + l.pad;
- y += l.h + 2 * l.pad + After(i);
- }
- ComputeHidden();
- // recolhidos não ocupam espaço
- y = TOP_PAD;
- for (int i = 0; i < Count(); i++) {
- pl[i].y = y + pl[i].pad;
- if (!pl[i].hidden) y += pl[i].h + 2 * pl[i].pad + After(i);
- }
- contentH = y + 40;
-}
-
-void Changed() {
- if (!N) return;
- N->modified = store::Now();
- N->dirty = true;
- dirtyLayout = true;
- wantReveal = true;
- blinkOn = true;
- NoteEdited(N);
-}
-
-// cursor em coordenadas do conteúdo (antes da rolagem)
-D2D1_RECT_F CaretRectAt(Pos q) {
- if (q.p >= (int)pl.size() || !pl[q.p].tl) return { 0, 0, 0, 0 };
- if (P(q.p).kind == K_FILE) return { pl[q.p].x - 4, pl[q.p].y, pl[q.p].x - 2, pl[q.p].y + pl[q.p].h }; // à esquerda do anexo
- float x, y; DWRITE_HIT_TEST_METRICS m;
- pl[q.p].tl->HitTestTextPosition((UINT32)q.o, FALSE, &x, &y, &m);
- return { pl[q.p].x + x, pl[q.p].y + m.top, pl[q.p].x + x + 2, pl[q.p].y + m.top + m.height };
-}
-
-Pos HitContent(float x, float y) { // ponto no conteúdo -> posição
- Pos r{ 0, 0 };
- if (!N || pl.empty()) return r;
- int best = -1;
- for (int i = 0; i < Count(); i++) {
- if (pl[i].hidden) continue;
- best = i;
- if (y < pl[i].y + pl[i].h + pl[i].pad + After(i)) break;
- }
- if (best < 0) return r;
- r.p = best;
- if (!pl[best].tl) return r;
- BOOL trailing, inside; DWRITE_HIT_TEST_METRICS m;
- pl[best].tl->HitTestPoint(x - pl[best].x, y - pl[best].y, &trailing, &inside, &m);
- r.o = std::min((int)(m.textPosition + (trailing ? m.length : 0)), (int)P(best).text.size());
- return r;
-}
-
-void Reveal() {
- if (!N || pl.empty()) return;
- D2D1_RECT_F c = CaretRectAt(caret);
- float h = area.bottom - area.top;
- if (c.top - 8 < scrollY) scrollY = c.top - 8;
- if (c.bottom + 24 > scrollY + h) scrollY = c.bottom + 24 - h;
- scrollY = std::clamp(scrollY, 0.f, std::max(0.f, contentH - h));
-}
-
-// ---------------------------------------------------------------------------
-// edição
-void Checkpoint(int kind) {
- if (!N) return;
- ULONGLONG now = GetTickCount64();
- if (kind == 3 || kind != N->lastEditKind || now - N->lastEditAt > 1500) {
- N->undo.push_back({ N->paras, caret.p, caret.o, anchor.p, anchor.o });
- if (N->undo.size() > 200) N->undo.erase(N->undo.begin());
- N->redo.clear();
- }
- N->lastEditKind = kind; N->lastEditAt = now;
-}
-
-uint8_t AttrAtCaret() {
- if (typingSet) return typing;
- Para& p = P(caret.p);
- if (caret.o > 0 && caret.o <= (int)p.at.size()) return p.at[caret.o - 1];
- if (!p.at.empty()) return p.at[0];
- return 0;
-}
-
-void DeleteRange(Pos a, Pos b) {
- if (!Less(a, b)) return;
- Para& pa = P(a.p);
- if (a.p == b.p) {
- pa.text.erase(a.o, b.o - a.o);
- pa.at.erase(pa.at.begin() + a.o, pa.at.begin() + b.o);
- } else if (P(b.p).kind == K_FILE && b.o == 0) { // a seleção para antes do anexo: ele fica inteiro
- if (pa.kind == K_FILE) { N->paras.erase(N->paras.begin() + a.p, N->paras.begin() + b.p); caret = anchor = { a.p, 0 }; return; }
- pa.text.resize(a.o); pa.at.resize(a.o);
- N->paras.erase(N->paras.begin() + a.p + 1, N->paras.begin() + b.p);
- } else {
- Para& pb = P(b.p);
- if (pa.kind == K_FILE) { pa.kind = pb.kind; pa.src = pb.src; pa.style = pb.style; pa.list = pb.list; pa.indent = pb.indent; pa.checked = pb.checked; } // o anexo selecionado some
- pa.text = pa.text.substr(0, a.o) + pb.text.substr(b.o);
- std::vector<uint8_t> at(pa.at.begin(), pa.at.begin() + a.o);
- at.insert(at.end(), pb.at.begin() + b.o, pb.at.end());
- pa.at = at;
- if (a.o == 0 && pa.text.size() == pb.text.size() - b.o && b.o == 0) { pa.style = pb.style; pa.list = pb.list; pa.indent = pb.indent; pa.checked = pb.checked; }
- N->paras.erase(N->paras.begin() + a.p + 1, N->paras.begin() + b.p + 1);
- }
- caret = anchor = a;
-}
-
-void DeleteSel() { if (HasSel()) { Pos a = SelStart(), b = SelEnd(); DeleteRange(a, b); } }
-
-void InsertPlain(const std::wstring& s, uint8_t at) {
- Para& p = P(caret.p);
- p.text.insert(caret.o, s);
- p.at.insert(p.at.begin() + caret.o, s.size(), at);
- caret.o += (int)s.size();
- anchor = caret;
-}
-
-void SplitPara() {
- Para& p = P(caret.p);
- Para np;
- np.text = p.text.substr(caret.o);
- np.at.assign(p.at.begin() + caret.o, p.at.end());
- p.text.resize(caret.o);
- p.at.resize(caret.o);
- np.list = p.list; np.indent = p.indent;
- np.style = p.style <= S_SUBHEADING ? (uint8_t)S_BODY : p.style;
- if (p.collapsed) p.collapsed = false;
- N->paras.insert(N->paras.begin() + caret.p + 1, np);
- caret = anchor = { caret.p + 1, 0 };
-}
-
-void InsertParas(std::vector<Para> v) {
- if (v.empty()) return;
- DeleteSel();
- if (v.size() == 1) {
- Para& p = P(caret.p);
- p.text.insert(caret.o, v[0].text);
- p.at.insert(p.at.begin() + caret.o, v[0].at.begin(), v[0].at.end());
- caret.o += (int)v[0].text.size(); anchor = caret;
- return;
- }
- Para& p = P(caret.p);
- std::wstring tail = p.text.substr(caret.o);
- std::vector<uint8_t> tailAt(p.at.begin() + caret.o, p.at.end());
- p.text.resize(caret.o); p.at.resize(caret.o);
- p.text += v[0].text; p.at.insert(p.at.end(), v[0].at.begin(), v[0].at.end());
- if (caret.o == 0) { p.style = v[0].style; p.list = v[0].list; p.indent = v[0].indent; p.checked = v[0].checked; }
- int at = caret.p + 1;
- for (size_t k = 1; k < v.size(); k++) N->paras.insert(N->paras.begin() + at++, v[k]);
- Para& last = P(at - 1);
- caret = anchor = { at - 1, (int)last.text.size() };
- last.text += tail; last.at.insert(last.at.end(), tailAt.begin(), tailAt.end());
-}
-
-bool IsWordChar(wchar_t c) { return iswalnum(c) || c == L'_'; }
-int PrevWord(const std::wstring& t, int i) { while (i > 0 && !IsWordChar(t[i - 1])) i--; while (i > 0 && IsWordChar(t[i - 1])) i--; return i; }
-int NextWord(const std::wstring& t, int i) { int n = (int)t.size(); while (i < n && !IsWordChar(t[i])) i++; while (i < n && IsWordChar(t[i])) i++; return i; }
-
-void UncollapseAround(int i) { // o cursor entrou numa seção recolhida: abre os títulos que a escondem
- if (pl.size() != (size_t)Count() || !pl[i].hidden) return;
- for (int k = i - 1; k >= 0; k--) if (P(k).collapsed && Level(P(k)) < Level(P(i))) { P(k).collapsed = false; }
- dirtyLayout = true;
-}
-
-int PrevVisible(int i) { for (int k = i - 1; k >= 0; k--) if (k >= (int)pl.size() || !pl[k].hidden) return k; return -1; }
-int NextVisible(int i) { for (int k = i + 1; k < Count(); k++) if (k >= (int)pl.size() || !pl[k].hidden) return k; return -1; }
-
-// parágrafos atingidos pela seleção (ou o do cursor)
-void SelParas(int& a, int& b) {
- Pos s = SelStart(), e = SelEnd();
- a = s.p; b = e.p;
- if (HasSel() && e.o == 0 && e.p > s.p) b--; // seleção que termina no começo do parágrafo não o inclui
-}
-
-std::vector<Para> SelectionParas() {
- std::vector<Para> v;
- Pos s = SelStart(), e = SelEnd();
- for (int i = s.p; i <= e.p; i++) {
- Para p = P(i);
- int a = i == s.p ? s.o : 0, b = i == e.p ? e.o : (int)p.text.size();
- p.text = p.text.substr(a, b - a);
- p.at = std::vector<uint8_t>(P(i).at.begin() + a, P(i).at.begin() + b);
- p.collapsed = false;
- v.push_back(p);
- }
- return v;
-}
-
-UINT ClipFormat() { static UINT f = RegisterClipboardFormatW(L"NotasParagrafos"); return f; }
-
-} // namespace
-
-// ---------------------------------------------------------------------------
-namespace editor {
-
-void SetFormats(const std::wstring& fam, const std::wstring& mono) {
- family = fam; monoFamily = mono;
- for (int s = 0; s < 5; s++) {
- if (fmt[s]) fmt[s]->Release();
- gfx::dw->CreateTextFormat(s == S_MONO ? monoFamily.c_str() : family.c_str(), nullptr, SM[s].w, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, SM[s].size, L"pt-br", &fmt[s]);
- if (fmt[s]) fmt[s]->SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
- }
- ReleaseLayouts();
-}
-void SetDark(bool d) { dark = d; ReleaseBrushes(); ReleaseLayouts(); }
-void SetSearch(const std::wstring& q) { query = q; for (auto& c : query) c = towlower(c); }
-
-Note* Current() { return N; }
-
-void SetNote(Note* n) {
- if (n == N) return;
- N = n;
- caret = anchor = { 0, 0 };
- scrollY = 0; desiredX = -1; typingSet = false;
- ReleaseLayouts();
- if (N && N->paras.empty()) N->paras.push_back(Para{});
-}
-
-void PlaceCaretAtEnd() {
- if (!N) return;
- caret.p = Count() - 1; caret.o = (int)P(caret.p).text.size(); anchor = caret;
- wantReveal = true;
-}
-
-void Focus(bool on) { focused = on; blinkOn = true; }
-bool Focused() { return focused; }
-void BlinkReset() { blinkOn = true; }
-void ToggleBlink() { blinkOn = !blinkOn; }
-void Invalidate() { dirtyLayout = true; }
-bool HasSelection() { return N && HasSel(); }
-
-// grade da tabela que começa no parágrafo i: contorno arredondado, linhas entre as linhas e entre as colunas
-void DrawTableGrid(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, int i, float ox, float oy) {
- int j = i;
- while (IsRow(j + 1)) j++;
- PL& a = pl[i]; PL& b = pl[j];
- float L = ox + a.base, R = L + a.tableW, T = oy + a.y - a.pad, B = oy + b.y + b.h + b.pad;
- br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.20f) : D2D1::ColorF(0, 0, 0, 0.16f));
- for (int k = i; k < j; k++) { if (pl[k].hidden) continue; float y = oy + pl[k].y + pl[k].h + pl[k].pad; dc->DrawLine({ L, y }, { R, y }, br, 1); }
- for (int c = 1; c < a.cols; c++) { float x = L + c * a.colW; dc->DrawLine({ x, T }, { x, B }, br, 1); }
- dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(L + 0.5f, T + 0.5f, R - 0.5f, B - 0.5f), 6, 6), br, 1);
-}
-
-// anexo: a imagem (cantos de 8) ou um cartão com a folha, o nome e o tamanho; clique duplo abre
-void DrawFile(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, const Para& p, const PL& l, float ox, float oy, bool inSel, D2D1_COLOR_F accent) {
- D2D1_RECT_F r = D2D1::RectF(ox + l.x, oy + l.y, ox + l.x + l.imgW, oy + l.y + l.imgH);
- ID2D1Factory* f = nullptr; dc->GetFactory(&f);
- if (ID2D1Bitmap* b = imgs.count(p.src) ? imgs[p.src] : nullptr) {
- ID2D1RoundedRectangleGeometry* g = nullptr;
- if (f) f->CreateRoundedRectangleGeometry(D2D1::RoundedRect(r, 8, 8), &g);
- if (g) dc->PushLayer(D2D1::LayerParameters(D2D1::InfiniteRect(), g), nullptr);
- dc->DrawBitmap(b, r, 1, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR);
- if (g) { dc->PopLayer(); g->Release(); }
- br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.12f) : D2D1::ColorF(0, 0, 0, 0.10f));
- dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(r.left + 0.5f, r.top + 0.5f, r.right - 0.5f, r.bottom - 0.5f), 7.5f, 7.5f), br, 1);
- } else {
- br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.07f) : D2D1::ColorF(0, 0, 0, 0.035f));
- dc->FillRoundedRectangle(D2D1::RoundedRect(r, 10, 10), br);
- br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.12f) : D2D1::ColorF(0, 0, 0, 0.10f));
- dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(r.left + 0.5f, r.top + 0.5f, r.right - 0.5f, r.bottom - 0.5f), 9.5f, 9.5f), br, 1);
- // folha com a ponta dobrada
- float fx = r.left + 14, fy = r.top + 11, fw = 22, fh = 30, d = 7;
- ID2D1PathGeometry* g = nullptr;
- if (f && SUCCEEDED(f->CreatePathGeometry(&g))) {
- ID2D1GeometrySink* k = nullptr; g->Open(&k);
- k->BeginFigure({ fx, fy }, D2D1_FIGURE_BEGIN_FILLED);
- k->AddLine({ fx + fw - d, fy }); k->AddLine({ fx + fw, fy + d }); k->AddLine({ fx + fw, fy + fh }); k->AddLine({ fx, fy + fh });
- k->EndFigure(D2D1_FIGURE_END_CLOSED); k->Close(); k->Release();
- br->SetColor(dark ? D2D1::ColorF(0.30f, 0.30f, 0.32f) : D2D1::ColorF(1, 1, 1));
- dc->FillGeometry(g, br);
- br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.45f) : D2D1::ColorF(0, 0, 0, 0.35f));
- dc->DrawGeometry(g, br, 1);
- dc->DrawLine({ fx + fw - d, fy }, { fx + fw - d, fy + d }, br, 1); dc->DrawLine({ fx + fw - d, fy + d }, { fx + fw, fy + d }, br, 1);
- g->Release();
- }
- std::wstring name = ShownName(p.src), info;
- WIN32_FILE_ATTRIBUTE_DATA fa{};
- if (GetFileAttributesExW(p.src.c_str(), GetFileExInfoStandard, &fa)) {
- double kb = (((ULONGLONG)fa.nFileSizeHigh << 32) | fa.nFileSizeLow) / 1024.0;
- wchar_t b[64];
- if (kb < 1024) swprintf_s(b, L"%.0f KB", std::max(1.0, kb)); else swprintf_s(b, L"%.1f MB", kb / 1024);
- info = b;
- } else info = Tr(L"Arquivo não encontrado");
- std::wstring ext = name.substr(name.find_last_of(L'.') + 1);
- if (ext.size() < name.size() && ext.size() <= 5) { for (auto& c : ext) c = towupper(c); info = ext + L" · " + info; }
- IDWriteTextFormat *t1 = nullptr, *t2 = nullptr;
- gfx::dw->CreateTextFormat(family.c_str(), nullptr, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 13, L"pt-br", &t1);
- gfx::dw->CreateTextFormat(family.c_str(), nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 11, L"pt-br", &t2);
- DWRITE_TRIMMING tr{ DWRITE_TRIMMING_GRANULARITY_CHARACTER, 0, 0 };
- if (t1) { t1->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP); t1->SetTrimming(&tr, nullptr); br->SetColor(TextColor()); dc->DrawTextW(name.c_str(), (UINT32)name.size(), t1, D2D1::RectF(r.left + 48, r.top + 9, r.right - 10, r.top + 27), br); t1->Release(); }
- if (t2) { br->SetColor(Text2()); dc->DrawTextW(info.c_str(), (UINT32)info.size(), t2, D2D1::RectF(r.left + 48, r.top + 28, r.right - 10, r.top + 44), br); t2->Release(); }
- }
- if (f) f->Release();
- if (inSel) { br->SetColor(D2D1::ColorF(accent.r, accent.g, accent.b, focused ? 0.38f : 0.18f)); dc->FillRoundedRectangle(D2D1::RoundedRect(r, 8, 8), br); }
-}
-
-void Draw(ID2D1DeviceContext* dc, D2D1_RECT_F a) {
- area = a;
- if (!N) return;
- Clamp();
- BuildLayouts(dc, a.right - a.left);
- if (wantReveal) { Reveal(); wantReveal = false; }
- float h = a.bottom - a.top;
- scrollY = std::clamp(scrollY, 0.f, std::max(0.f, contentH - h));
- float ox = a.left, oy = a.top - scrollY;
- dc->PushAxisAlignedClip(a, D2D1_ANTIALIAS_MODE_ALIASED);
- ID2D1SolidColorBrush* br = nullptr;
- dc->CreateSolidColorBrush(TextColor(), &br);
- if (semaforo::Leopard()) {
- // Leopard: o bloco amarelo das Notas do Mail — amarelo-claro, as pautas finas a cada 24 (rolam com o texto) e a
- // margem dupla avermelhada à esquerda
- br->SetColor(D2D1::ColorF(1, 0.976f, 0.73f));
- dc->FillRectangle(a, br);
- br->SetColor(D2D1::ColorF(0.55f, 0.62f, 0.80f, 0.35f));
- float y0 = a.top + 40 - std::fmod(scrollY, 24.f);
- for (float y = y0; y < a.bottom; y += 24) dc->DrawLine({ a.left, y }, { a.right, y }, br, 1);
- br->SetColor(D2D1::ColorF(0.85f, 0.35f, 0.30f, 0.45f));
- dc->DrawLine({ a.left + 10, a.top }, { a.left + 10, a.bottom }, br, 1);
- dc->DrawLine({ a.left + 13, a.top }, { a.left + 13, a.bottom }, br, 1);
- br->SetColor(TextColor());
- }
-
- // data no alto, centralizada e cinza
- {
- std::wstring d = LongDate(N->modified);
- IDWriteTextFormat* tf = nullptr;
- gfx::dw->CreateTextFormat(family.c_str(), nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 12, L"pt-br", &tf);
- if (tf) {
- tf->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
- br->SetColor(Text2());
- dc->DrawTextW(d.c_str(), (UINT32)d.size(), tf, D2D1::RectF(ox, oy + 6, a.right, oy + 24), br);
- tf->Release();
- }
- }
- Pos ss = SelStart(), se = SelEnd();
- bool sel = HasSel();
- D2D1_COLOR_F accent = Accent();
- for (int i = 0; i < Count(); i++) {
- PL& l = pl[i];
- if (l.hidden || !l.tl) continue;
- float py = oy + l.y;
- if (py > a.bottom || py + l.h < a.top) continue;
- Para& p = P(i);
- float px = ox + l.x;
- bool inSel = sel && i >= ss.p && i <= se.p && !(i == se.p && se.o == 0 && se.p > ss.p);
- if (p.kind == K_FILE) { DrawFile(dc, br, p, l, ox, oy, inSel, accent); continue; }
- if (p.kind == K_ROW && !IsRow(i - 1)) DrawTableGrid(dc, br, i, ox, oy);
- auto rangeRects = [&](int from, int len, D2D1_COLOR_F c, float pad) {
- if (len <= 0) return;
- UINT32 cnt = 0;
- l.tl->HitTestTextRange(from, len, 0, 0, nullptr, 0, &cnt);
- std::vector<DWRITE_HIT_TEST_METRICS> ms(cnt);
- l.tl->HitTestTextRange(from, len, 0, 0, ms.data(), cnt, &cnt);
- br->SetColor(c);
- for (auto& m : ms) dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(px + m.left - pad, py + m.top + 1, px + m.left + m.width + pad, py + m.top + m.height), 3, 3), br);
- };
- // realces
- for (int k = 0; k < (int)p.at.size();) {
- int j = k; int hcol = HiOf(p.at[k]);
- while (j < (int)p.at.size() && HiOf(p.at[j]) == hcol) j++;
- if (hcol) rangeRects(k, j - k, HiBack(hcol), 1);
- k = j;
- }
- // resultados das contas: fundo amarelado discreto
- if (i < (int)math.size() && !math[i].result.empty())
- rangeRects(l.resultAt, (int)math[i].result.size(), D2D1::ColorF(accent.r, accent.g, accent.b, dark ? 0.16f : 0.13f), 1);
- // busca
- if (!query.empty() && query.size() <= p.text.size()) {
- std::wstring low = p.text; for (auto& c : low) c = towlower(c);
- for (size_t f = low.find(query); f != std::wstring::npos; f = low.find(query, f + query.size()))
- rangeRects((int)f, (int)query.size(), D2D1::ColorF(1.0f, 0.85f, 0.1f, dark ? 0.55f : 0.6f), 0.5f);
- }
- // seleção
- if (sel && i >= ss.p && i <= se.p) {
- int from = i == ss.p ? ss.o : 0, to = i == se.p ? se.o : (int)p.text.size();
- D2D1_COLOR_F sc = focused ? D2D1::ColorF(accent.r, accent.g, accent.b, dark ? 0.40f : 0.38f) : (dark ? D2D1::ColorF(1, 1, 1, 0.14f) : D2D1::ColorF(0, 0, 0, 0.10f));
- rangeRects(from, to - from, sc, 0);
- if (i < se.p) { // a quebra de linha também está selecionada
- D2D1_RECT_F c = CaretRectAt({ i, (int)p.text.size() });
- br->SetColor(sc);
- dc->FillRectangle(D2D1::RectF(ox + c.left, oy + c.top + 1, ox + c.left + 6, oy + c.bottom), br);
- }
- }
- // marcador da lista
- float x0, y0; DWRITE_HIT_TEST_METRICS m0;
- l.tl->HitTestTextPosition(0, FALSE, &x0, &y0, &m0);
- float cy = py + m0.top + m0.height / 2;
- float mx = ox + l.base;
- if (p.list == L_CHECK) {
- D2D1_POINT_2F c{ mx + 9, cy };
- if (p.checked) {
- br->SetColor(accent);
- dc->FillEllipse(D2D1::Ellipse(c, 8.5f, 8.5f), br);
- br->SetColor(D2D1::ColorF(1, 1, 1));
- simbolo::Draw(dc, L"checkmark", D2D1::RectF(c.x - 4.6f, c.y - 4.2f, c.x + 4.6f, c.y + 4.2f), br);
- } else {
- br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.38f) : D2D1::ColorF(0, 0, 0, 0.30f));
- dc->DrawEllipse(D2D1::Ellipse(c, 8, 8), br, 1.1f);
- }
- } else if (p.list != L_NONE && p.kind == K_TEXT) {
- std::wstring mk = p.list == L_BULLET ? L"•" : p.list == L_DASH ? L"–" : std::to_wstring(l.number) + L".";
- IDWriteTextLayout* ml = nullptr;
- gfx::dw->CreateTextLayout(mk.c_str(), (UINT32)mk.size(), fmt[p.style], 40, 100, &ml);
- if (ml) {
- ml->SetLineSpacing(DWRITE_LINE_SPACING_METHOD_UNIFORM, SM[p.style].line, SM[p.style].line * 0.8f);
- DWRITE_TEXT_METRICS tm{}; ml->GetMetrics(&tm);
- float x = p.list == L_NUMBER ? mx + 19 - tm.width : mx + 4;
- br->SetColor(TextColor());
- dc->DrawTextLayout(D2D1::Point2F(x, py), ml, br);
- ml->Release();
- }
- }
- // seta das seções recolhíveis (títulos): aparece com o mouse em cima ou quando recolhida
- if (Level(p) < 99 && (p.collapsed || hoverChevron == i)) {
- br->SetColor(Text2());
- float cx = ox + 11, s = 4.2f;
- ID2D1PathGeometry* g = nullptr; ID2D1Factory* f = nullptr; dc->GetFactory(&f);
- if (f && SUCCEEDED(f->CreatePathGeometry(&g))) {
- ID2D1GeometrySink* k = nullptr; g->Open(&k);
- if (p.collapsed) { k->BeginFigure({ cx - s / 2, cy - s }, D2D1_FIGURE_BEGIN_HOLLOW); k->AddLine({ cx + s / 2, cy }); k->AddLine({ cx - s / 2, cy + s }); }
- else { k->BeginFigure({ cx - s, cy - s / 2 }, D2D1_FIGURE_BEGIN_HOLLOW); k->AddLine({ cx, cy + s / 2 }); k->AddLine({ cx + s, cy - s / 2 }); }
- k->EndFigure(D2D1_FIGURE_END_OPEN); k->Close(); k->Release();
- ID2D1StrokeStyle* rs = nullptr;
- f->CreateStrokeStyle(D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_ROUND), nullptr, 0, &rs);
- dc->DrawGeometry(g, br, 1.6f, rs);
- if (rs) rs->Release();
- g->Release();
- }
- if (f) f->Release();
- }
- br->SetColor(TextColor());
- dc->DrawTextLayout(D2D1::Point2F(px, py), l.tl, br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT);
- }
- // cursor amarelo
- if (focused && blinkOn && !sel && caret.p < (int)pl.size() && !pl[caret.p].hidden) {
- D2D1_RECT_F c = CaretRectAt(caret);
- br->SetColor(accent);
- dc->FillRectangle(D2D1::RectF(ox + c.left - 0.5f, oy + c.top, ox + c.left + 1.5f, oy + c.bottom), br);
- }
- br->Release();
- dc->PopAxisAlignedClip();
-}
-
-void CaretScreenRect(D2D1_RECT_F& r) {
- D2D1_RECT_F c = CaretRectAt(caret);
- r = { area.left + c.left, area.top - scrollY + c.top, area.left + c.right, area.top - scrollY + c.bottom };
-}
-
-void OnWheel(float dy) { scrollY = std::max(0.f, scrollY - dy); }
-
-static int ChevronAt(D2D1_POINT_2F p) {
- if (!N || pl.size() != (size_t)Count() || p.x < area.left || p.x > area.left + MARGIN) return -1;
- float y = p.y - area.top + scrollY;
- for (int i = 0; i < Count(); i++)
- if (!pl[i].hidden && Level(P(i)) < 99 && y >= pl[i].y && y < pl[i].y + SM[P(i).style].line + 2) return i;
- return -1;
-}
-bool OverChevronArea(D2D1_POINT_2F p) { return ChevronAt(p) >= 0; }
-
-void OnMouseMove(D2D1_POINT_2F p, bool dragging) {
- if (!N) return;
- if (!dragging) {
- // a seta aparece com o mouse em qualquer lugar da linha do título
- int hc = -1;
- if (pl.size() == (size_t)Count() && p.x >= area.left && p.x < area.right) {
- float y = p.y - area.top + scrollY;
- for (int i = 0; i < Count(); i++)
- if (!pl[i].hidden && Level(P(i)) < 99 && y >= pl[i].y && y < pl[i].y + pl[i].h) { hc = i; break; }
- }
- if (hc != hoverChevron) { hoverChevron = hc; RequestPaint(); }
- return;
- }
- Pos q = HitContent(p.x - area.left, p.y - area.top + scrollY);
- if (clickMode == 2) {
- const std::wstring& t = P(q.p).text;
- if (Less(q, clickA)) { caret = { q.p, PrevWord(t, std::min(q.o + 1, (int)t.size())) }; anchor = clickB; }
- else { caret = { q.p, NextWord(t, q.o) }; anchor = clickA; }
- } else if (clickMode == 3) {
- if (q.p < clickA.p) { caret = { q.p, 0 }; anchor = clickB; }
- else { caret = { q.p, (int)P(q.p).text.size() }; anchor = clickA; }
- } else caret = q;
- if (p.y < area.top) scrollY = std::max(0.f, scrollY - 12);
- if (p.y > area.bottom) scrollY += 12;
- desiredX = -1;
- RequestPaint();
-}
-
-void OnMouseDown(D2D1_POINT_2F p, bool shift, int clicks) {
- if (!N) return;
- focused = true; blinkOn = true;
- int ch = ChevronAt(p);
- if (ch >= 0 && clicks == 1) {
- Checkpoint(3);
- P(ch).collapsed = !P(ch).collapsed;
- if (P(ch).collapsed && caret.p > ch) { caret = anchor = { ch, (int)P(ch).text.size() }; }
- N->dirty = true; dirtyLayout = true; NoteEdited(N);
- return;
- }
- float cx = p.x - area.left, cy = p.y - area.top + scrollY;
- // bolinha da lista de verificação
- for (int i = 0; i < Count() && pl.size() == (size_t)Count(); i++) {
- if (pl[i].hidden || P(i).list != L_CHECK || !pl[i].tl) continue;
- float x0, y0; DWRITE_HIT_TEST_METRICS m0;
- pl[i].tl->HitTestTextPosition(0, FALSE, &x0, &y0, &m0);
- float ccx = pl[i].base + 9, ccy = pl[i].y + m0.top + m0.height / 2;
- if (std::fabs(cx - ccx) <= 11 && std::fabs(cy - ccy) <= 11) {
- Checkpoint(3);
- P(i).checked = !P(i).checked;
- Changed();
- wantReveal = false;
- return;
- }
- }
- Pos q = HitContent(cx, cy);
- typingSet = false; desiredX = -1;
- if (P(q.p).kind == K_FILE) { // anexo: clique põe o cursor nele; clique duplo abre no programa padrão
- caret = q; if (!shift) anchor = q;
- clickMode = 1;
- if (clicks == 2) ShellExecuteW(nullptr, L"open", P(q.p).src.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
- RequestPaint();
- return;
- }
- const std::wstring& t = P(q.p).text;
- if (clicks == 2) {
- int a = q.o, b = q.o;
- if (a < (int)t.size() && IsWordChar(t[a])) { while (a > 0 && IsWordChar(t[a - 1])) a--; while (b < (int)t.size() && IsWordChar(t[b])) b++; }
- else if (b < (int)t.size()) b++;
- anchor = { q.p, a }; caret = { q.p, b };
- clickA = anchor; clickB = caret; clickMode = 2;
- } else if (clicks >= 3) {
- anchor = { q.p, 0 }; caret = { q.p, (int)t.size() };
- clickA = anchor; clickB = caret; clickMode = 3;
- } else {
- caret = q;
- if (!shift) anchor = q;
- clickMode = 1;
- }
- RequestPaint();
-}
-
-void SelectAll() { if (!N) return; anchor = { 0, 0 }; caret = { Count() - 1, (int)P(Count() - 1).text.size() }; }
-
-void Copy(bool cut) {
- if (!N || !HasSel()) return;
- auto v = SelectionParas();
- std::wstring plain;
- for (size_t i = 0; i < v.size(); i++) { if (i) plain += L"\r\n"; plain += v[i].text; }
- std::wstring rich = store::Serialize(v);
- if (OpenClipboard(nullptr)) {
- EmptyClipboard();
- auto put = [](UINT fmtId, const std::wstring& s) {
- HGLOBAL g = GlobalAlloc(GMEM_MOVEABLE, (s.size() + 1) * sizeof(wchar_t));
- if (!g) return;
- memcpy(GlobalLock(g), s.c_str(), (s.size() + 1) * sizeof(wchar_t));
- GlobalUnlock(g);
- if (!SetClipboardData(fmtId, g)) GlobalFree(g);
- };
- put(CF_UNICODETEXT, plain);
- put(ClipFormat(), rich);
- CloseClipboard();
- }
- if (cut) { Checkpoint(3); DeleteSel(); Changed(); }
-}
-
-void Paste() {
- if (!N || !OpenClipboard(nullptr)) return;
- std::vector<Para> v;
- if (HANDLE h = GetClipboardData(ClipFormat())) {
- if (auto* p = (const wchar_t*)GlobalLock(h)) { v = store::Deserialize(p); GlobalUnlock(h); }
- } else if (HANDLE h2 = GetClipboardData(CF_UNICODETEXT)) {
- if (auto* p = (const wchar_t*)GlobalLock(h2)) {
- std::wstring s = p; GlobalUnlock(h2);
- uint8_t at = AttrAtCaret() & ~0x70; // texto colado sem realce
- size_t a = 0;
- for (;;) {
- size_t e = s.find(L'\n', a);
- std::wstring line = s.substr(a, e == std::wstring::npos ? std::wstring::npos : e - a);
- if (!line.empty() && line.back() == L'\r') line.pop_back();
- Para q; q.text = line; q.at.assign(line.size(), at);
- q.style = S_BODY;
- v.push_back(q);
- if (e == std::wstring::npos) break;
- a = e + 1;
- }
- if (v.size() == 1) v[0].style = P(caret.p).style;
- }
- }
- CloseClipboard();
- if (v.empty()) return;
- Checkpoint(3);
- InsertParas(v);
- typingSet = false;
- Changed();
-}
-
-void Undo() {
- if (!N || N->undo.empty()) return;
- N->redo.push_back({ N->paras, caret.p, caret.o, anchor.p, anchor.o });
- auto s = N->undo.back(); N->undo.pop_back();
- N->paras = s.paras; caret = { s.cp, s.co }; anchor = { s.ap, s.ao };
- N->lastEditKind = 0;
- Clamp(); Changed();
-}
-void Redo() {
- if (!N || N->redo.empty()) return;
- N->undo.push_back({ N->paras, caret.p, caret.o, anchor.p, anchor.o });
- auto s = N->redo.back(); N->redo.pop_back();
- N->paras = s.paras; caret = { s.cp, s.co }; anchor = { s.ap, s.ao };
- N->lastEditKind = 0;
- Clamp(); Changed();
-}
-
+ float imgW = 0, imgH = 0; }; // anexo: tamanho na nota
+std::vector<PL> pl;
+bool dirtyLayout = true;
+float layoutW = -1;
+float contentH;
+std::vector<MathLine> math;
+ID2D1DeviceContext* lastDc;
+ID2D1SolidColorBrush *brAccent, *brHi[HI_COUNT + 1];
+IDWriteTextFormat* fmt[5];
+
+const float MARGIN = 24, INDENT = 26, TOP_PAD = 34, CELL_PAD = 8, ROW_PAD = 7;
+
+// medidas de cada estilo (tamanho, altura da linha, espaço depois)
+struct StyleM { float size, line, after; DWRITE_FONT_WEIGHT w; };
+const StyleM SM[5] = {
+ { 24, 30, 6, DWRITE_FONT_WEIGHT_BOLD }, // Título
+ { 18, 23, 4, DWRITE_FONT_WEIGHT_BOLD }, // Cabeçalho
+ { 14, 18, 3, DWRITE_FONT_WEIGHT_BOLD }, // Subcabeçalho
+ { 13, 17.5f, 0, DWRITE_FONT_WEIGHT_NORMAL }, // Corpo
+ { 12, 16.5f, 0, DWRITE_FONT_WEIGHT_NORMAL }, // Monoespaçado
+};
+
+D2D1_COLOR_F TextColor() { return dark ? D2D1::ColorF(1, 1, 1, 0.88f) : D2D1::ColorF(0.11f, 0.11f, 0.12f); }
+D2D1_COLOR_F Text2() { return dark ? D2D1::ColorF(1, 1, 1, 0.45f) : D2D1::ColorF(0, 0, 0, 0.45f); }
+
+// realces do Sequoia: roxo, rosa, laranja, menta, azul (texto na cor, fundo claro da mesma cor)
+D2D1_COLOR_F HiText(int h) {
+ static const D2D1_COLOR_F L[HI_COUNT] = { D2D1::ColorF(0.55f, 0.27f, 0.85f), D2D1::ColorF(0.86f, 0.18f, 0.45f), D2D1::ColorF(0.85f, 0.42f, 0.0f), D2D1::ColorF(0.0f, 0.55f, 0.48f), D2D1::ColorF(0.0f, 0.45f, 0.90f) };
+ static const D2D1_COLOR_F D[HI_COUNT] = { D2D1::ColorF(0.80f, 0.62f, 1.0f), D2D1::ColorF(1.0f, 0.50f, 0.68f), D2D1::ColorF(1.0f, 0.68f, 0.35f), D2D1::ColorF(0.40f, 0.90f, 0.80f), D2D1::ColorF(0.45f, 0.72f, 1.0f) };
+ return dark ? D[h - 1] : L[h - 1];
+}
+D2D1_COLOR_F HiBack(int h) {
+ static const D2D1_COLOR_F c[HI_COUNT] = { D2D1::ColorF(0.69f, 0.42f, 0.98f), D2D1::ColorF(1.0f, 0.30f, 0.55f), D2D1::ColorF(1.0f, 0.58f, 0.15f), D2D1::ColorF(0.20f, 0.82f, 0.72f), D2D1::ColorF(0.25f, 0.60f, 1.0f) };
+ D2D1_COLOR_F k = c[h - 1]; k.a = dark ? 0.30f : 0.22f; return k;
+}
+
+bool Less(Pos a, Pos b) { return a.p < b.p || (a.p == b.p && a.o < b.o); }
+bool Same(Pos a, Pos b) { return a.p == b.p && a.o == b.o; }
+Pos SelStart() { return Less(caret, anchor) ? caret : anchor; }
+Pos SelEnd() { return Less(caret, anchor) ? anchor : caret; }
+bool HasSel() { return !Same(caret, anchor); }
+Para& P(int i) { return N->paras[i]; }
+int Count() { return N ? (int)N->paras.size() : 0; }
+int Level(const Para& p) { return p.kind == K_TEXT && p.style <= S_SUBHEADING ? p.style : 99; }
+bool IsRow(int i) { return i >= 0 && i < Count() && P(i).kind == K_ROW; }
+bool IsFile(int i) { return i >= 0 && i < Count() && P(i).kind == K_FILE; }
+int Tabs(const std::wstring& s) { return (int)std::count(s.begin(), s.end(), L'\t'); }
+int TableCols(int i) { // colunas do bloco de linhas que contém i (a linha mais larga manda)
+ int a = i, b = i, n = 1;
+ while (IsRow(a - 1)) a--;
+ while (IsRow(b + 1)) b++;
+ for (int k = a; k <= b; k++) n = std::max(n, Tabs(P(k).text) + 1);
+ return n;
+}
+float After(int i) { return IsFile(i) ? 10.f : IsRow(i) ? (IsRow(i + 1) ? 0.f : 10.f) : SM[P(i).style].after; }
+bool IsImageFile(const std::wstring& path) {
+ std::wstring e = path.substr(path.find_last_of(L'.') + 1);
+ for (auto& c : e) c = towlower(c);
+ return e == L"png" || e == L"jpg" || e == L"jpeg" || e == L"gif" || e == L"bmp" || e == L"tif" || e == L"tiff" || e == L"webp" || e == L"heic" || e == L"ico";
+}
+// nome mostrado: sem o prefixo único que o AddAttachment põe ("1dd7...-foto.png" -> "foto.png")
+std::wstring ShownName(const std::wstring& path) {
+ std::wstring n = path.substr(path.find_last_of(L"\\/") + 1);
+ size_t d = n.find(L'-');
+ if (d != std::wstring::npos && d >= 8 && n.find_first_not_of(L"0123456789abcdef") == d) n = n.substr(d + 1);
+ return n;
+}
+
+// imagens dos anexos (por contexto do Direct2D; nullptr guardado = não é imagem ou não abriu)
+std::map<std::wstring, ID2D1Bitmap*> imgs;
+IWICImagingFactory* wic;
+void ReleaseImages() { for (auto& k : imgs) if (k.second) k.second->Release(); imgs.clear(); }
+ID2D1Bitmap* Img(ID2D1DeviceContext* dc, const std::wstring& path) {
+ auto it = imgs.find(path);
+ if (it != imgs.end()) return it->second;
+ ID2D1Bitmap* bmp = nullptr;
+ if (IsImageFile(path)) {
+ if (!wic) CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic));
+ IWICBitmapDecoder* dec = nullptr; IWICBitmapFrameDecode* fr = nullptr; IWICFormatConverter* cv = nullptr;
+ if (wic && SUCCEEDED(wic->CreateDecoderFromFilename(path.c_str(), nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &dec)) &&
+ SUCCEEDED(dec->GetFrame(0, &fr)) && SUCCEEDED(wic->CreateFormatConverter(&cv)) &&
+ SUCCEEDED(cv->Initialize(fr, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeMedianCut)))
+ dc->CreateBitmapFromWicBitmap(cv, nullptr, &bmp);
+ if (cv) cv->Release(); if (fr) fr->Release(); if (dec) dec->Release();
+ }
+ imgs[path] = bmp;
+ return bmp;
+}
+
+void ReleaseLayouts() { for (auto& l : pl) if (l.tl) l.tl->Release(); pl.clear(); dirtyLayout = true; }
+void ReleaseBrushes() {
+ ReleaseImages();
+ if (brAccent) brAccent->Release(); brAccent = nullptr;
+ for (auto& b : brHi) { if (b) b->Release(); b = nullptr; }
+}
+
+void Clamp() {
+ if (!N) return;
+ auto fix = [](Pos& q) { q.p = std::clamp(q.p, 0, Count() - 1); q.o = std::clamp(q.o, 0, (int)P(q.p).text.size()); };
+ fix(caret); fix(anchor);
+}
+
+// ---------------------------------------------------------------------------
+// layout
+void ComputeHidden() {
+ int hideLevel = -1; // escondendo até achar um título de nível <= hideLevel
+ for (int i = 0; i < Count(); i++) {
+ int lv = Level(P(i));
+ if (hideLevel >= 0) {
+ if (lv <= hideLevel) hideLevel = -1;
+ else { pl[i].hidden = true; continue; }
+ }
+ pl[i].hidden = false;
+ if (P(i).collapsed && lv < 99) hideLevel = lv;
+ }
+}
+
+void BuildLayouts(ID2D1DeviceContext* dc, float width) {
+ if (dc != lastDc) { ReleaseBrushes(); ReleaseLayouts(); lastDc = dc; }
+ if (!brAccent) {
+ dc->CreateSolidColorBrush(AccentText(), &brAccent);
+ for (int h = 1; h <= HI_COUNT; h++) dc->CreateSolidColorBrush(HiText(h), &brHi[h]);
+ }
+ if (!dirtyLayout && width == layoutW && (int)pl.size() == Count()) return;
+ for (auto& l : pl) if (l.tl) l.tl->Release();
+ pl.assign(Count(), PL{});
+ layoutW = width;
+ dirtyLayout = false;
+ math = EvalMath(N->paras);
+ int counters[10] = {};
+ float y = TOP_PAD;
+ for (int i = 0; i < Count(); i++) {
+ Para& p = P(i);
+ PL& l = pl[i];
+ // numeração das listas numeradas
+ if (p.list == L_NONE) std::fill(std::begin(counters), std::end(counters), 0);
+ else {
+ for (int k = p.indent + 1; k < 10; k++) counters[k] = 0;
+ if (p.list == L_NUMBER) l.number = ++counters[std::min<int>(p.indent, 9)];
+ else counters[std::min<int>(p.indent, 9)] = 0;
+ }
+ float base = MARGIN + p.indent * INDENT;
+ if (p.kind == K_FILE) { // anexo: imagem na largura possível (até 400 de altura) ou cartão de 52
+ l.x = l.base = base; l.w = std::max(40.f, width - base - MARGIN);
+ gfx::dw->CreateTextLayout(L"", 0, fmt[S_BODY], l.w, 10000, &l.tl);
+ if (l.tl) l.tl->SetLineSpacing(DWRITE_LINE_SPACING_METHOD_UNIFORM, SM[S_BODY].line, SM[S_BODY].line * 0.8f);
+ if (ID2D1Bitmap* b = Img(dc, p.src)) {
+ D2D1_SIZE_U px = b->GetPixelSize();
+ // desenhos do Notas são gravados em 2x; o resto, 1 pixel = 1 pt
+ float k = ShownName(p.src).rfind(L"desenho-", 0) == 0 || p.src.find(L"\\desenho-") != std::wstring::npos ? 0.5f : 1.f;
+ float w = std::min(l.w, std::max(1.f, px.width * k)), h = w * px.height / std::max(1u, px.width);
+ if (h > 400) { w *= 400 / h; h = 400; }
+ l.imgW = w; l.imgH = h;
+ } else { l.imgW = std::min(l.w, 320.f); l.imgH = 52; }
+ l.h = l.imgH; l.y = y; y += l.h + After(i);
+ continue;
+ }
+ if (p.kind == K_ROW) { // linha de tabela: uma parada de tabulação por coluna, sem quebra
+ l.cols = TableCols(i); l.base = base;
+ l.tableW = std::max(120.f, width - base - MARGIN); l.colW = l.tableW / l.cols;
+ l.x = base + CELL_PAD; l.w = l.tableW - CELL_PAD; l.pad = ROW_PAD;
+ }
+ float lead = p.kind == K_ROW ? 0.f : p.list == L_CHECK ? 28.f : p.list != L_NONE ? 24.f : 0.f;
+ if (p.kind != K_ROW) { l.x = base + lead; l.base = base; l.w = std::max(40.f, width - l.x - MARGIN); }
+ std::wstring s = p.text;
+ int resultAt = -1;
+ if (i < (int)math.size() && !math[i].result.empty()) {
+ if (s.size() >= 2 && s.back() == L'=' && s[s.size() - 2] == L' ') s += L' '; // "x =" -> "x = 5"
+ resultAt = (int)s.size(); s += math[i].result;
+ }
+ l.resultAt = resultAt;
+ const StyleM& m = SM[p.style];
+ gfx::dw->CreateTextLayout(s.c_str(), (UINT32)s.size(), fmt[p.style], l.w, 10000, &l.tl);
+ if (!l.tl) continue;
+ l.tl->SetLineSpacing(DWRITE_LINE_SPACING_METHOD_UNIFORM, m.line, m.line * 0.8f);
+ if (p.kind == K_ROW) { l.tl->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP); l.tl->SetIncrementalTabStop(l.colW); }
+ UINT32 n = (UINT32)p.text.size();
+ for (UINT32 k = 0; k < n;) { // corridas de atributos
+ UINT32 j = k; uint8_t a = p.at[k];
+ while (j < n && p.at[j] == a) j++;
+ DWRITE_TEXT_RANGE r{ k, j - k };
+ if (a & A_BOLD) l.tl->SetFontWeight(p.style == S_BODY || p.style == S_MONO ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_HEAVY, r);
+ if (a & A_ITALIC) l.tl->SetFontStyle(DWRITE_FONT_STYLE_ITALIC, r);
+ if (a & A_UNDER) l.tl->SetUnderline(TRUE, r);
+ if (a & A_STRIKE) l.tl->SetStrikethrough(TRUE, r);
+ if (HiOf(a)) l.tl->SetDrawingEffect(brHi[HiOf(a)], r);
+ k = j;
+ }
+ if (i < (int)math.size())
+ for (auto& v : math[i].vars) l.tl->SetDrawingEffect(brAccent, { (UINT32)v.first, (UINT32)v.second });
+ if (resultAt >= 0) l.tl->SetDrawingEffect(brAccent, { (UINT32)resultAt, (UINT32)math[i].result.size() });
+ DWRITE_TEXT_METRICS tm{}; l.tl->GetMetrics(&tm);
+ l.h = std::max(tm.height, m.line);
+ l.y = y + l.pad;
+ y += l.h + 2 * l.pad + After(i);
+ }
+ ComputeHidden();
+ // recolhidos não ocupam espaço
+ y = TOP_PAD;
+ for (int i = 0; i < Count(); i++) {
+ pl[i].y = y + pl[i].pad;
+ if (!pl[i].hidden) y += pl[i].h + 2 * pl[i].pad + After(i);
+ }
+ contentH = y + 40;
+}
+
+void Changed() {
+ if (!N) return;
+ N->modified = store::Now();
+ N->dirty = true;
+ dirtyLayout = true;
+ wantReveal = true;
+ blinkOn = true;
+ NoteEdited(N);
+}
+
+// cursor em coordenadas do conteúdo (antes da rolagem)
+D2D1_RECT_F CaretRectAt(Pos q) {
+ if (q.p >= (int)pl.size() || !pl[q.p].tl) return { 0, 0, 0, 0 };
+ if (P(q.p).kind == K_FILE) return { pl[q.p].x - 4, pl[q.p].y, pl[q.p].x - 2, pl[q.p].y + pl[q.p].h }; // à esquerda do anexo
+ float x, y; DWRITE_HIT_TEST_METRICS m;
+ pl[q.p].tl->HitTestTextPosition((UINT32)q.o, FALSE, &x, &y, &m);
+ return { pl[q.p].x + x, pl[q.p].y + m.top, pl[q.p].x + x + 2, pl[q.p].y + m.top + m.height };
+}
+
+Pos HitContent(float x, float y) { // ponto no conteúdo -> posição
+ Pos r{ 0, 0 };
+ if (!N || pl.empty()) return r;
+ int best = -1;
+ for (int i = 0; i < Count(); i++) {
+ if (pl[i].hidden) continue;
+ best = i;
+ if (y < pl[i].y + pl[i].h + pl[i].pad + After(i)) break;
+ }
+ if (best < 0) return r;
+ r.p = best;
+ if (!pl[best].tl) return r;
+ BOOL trailing, inside; DWRITE_HIT_TEST_METRICS m;
+ pl[best].tl->HitTestPoint(x - pl[best].x, y - pl[best].y, &trailing, &inside, &m);
+ r.o = std::min((int)(m.textPosition + (trailing ? m.length : 0)), (int)P(best).text.size());
+ return r;
+}
+
+void Reveal() {
+ if (!N || pl.empty()) return;
+ D2D1_RECT_F c = CaretRectAt(caret);
+ float h = area.bottom - area.top;
+ if (c.top - 8 < scrollY) scrollY = c.top - 8;
+ if (c.bottom + 24 > scrollY + h) scrollY = c.bottom + 24 - h;
+ scrollY = std::clamp(scrollY, 0.f, std::max(0.f, contentH - h));
+}
+
+// ---------------------------------------------------------------------------
+// edição
+void Checkpoint(int kind) {
+ if (!N) return;
+ ULONGLONG now = GetTickCount64();
+ if (kind == 3 || kind != N->lastEditKind || now - N->lastEditAt > 1500) {
+ N->undo.push_back({ N->paras, caret.p, caret.o, anchor.p, anchor.o });
+ if (N->undo.size() > 200) N->undo.erase(N->undo.begin());
+ N->redo.clear();
+ }
+ N->lastEditKind = kind; N->lastEditAt = now;
+}
+
+uint8_t AttrAtCaret() {
+ if (typingSet) return typing;
+ Para& p = P(caret.p);
+ if (caret.o > 0 && caret.o <= (int)p.at.size()) return p.at[caret.o - 1];
+ if (!p.at.empty()) return p.at[0];
+ return 0;
+}
+
+void DeleteRange(Pos a, Pos b) {
+ if (!Less(a, b)) return;
+ Para& pa = P(a.p);
+ if (a.p == b.p) {
+ pa.text.erase(a.o, b.o - a.o);
+ pa.at.erase(pa.at.begin() + a.o, pa.at.begin() + b.o);
+ } else if (P(b.p).kind == K_FILE && b.o == 0) { // a seleção para antes do anexo: ele fica inteiro
+ if (pa.kind == K_FILE) { N->paras.erase(N->paras.begin() + a.p, N->paras.begin() + b.p); caret = anchor = { a.p, 0 }; return; }
+ pa.text.resize(a.o); pa.at.resize(a.o);
+ N->paras.erase(N->paras.begin() + a.p + 1, N->paras.begin() + b.p);
+ } else {
+ Para& pb = P(b.p);
+ if (pa.kind == K_FILE) { pa.kind = pb.kind; pa.src = pb.src; pa.style = pb.style; pa.list = pb.list; pa.indent = pb.indent; pa.checked = pb.checked; } // o anexo selecionado some
+ pa.text = pa.text.substr(0, a.o) + pb.text.substr(b.o);
+ std::vector<uint8_t> at(pa.at.begin(), pa.at.begin() + a.o);
+ at.insert(at.end(), pb.at.begin() + b.o, pb.at.end());
+ pa.at = at;
+ if (a.o == 0 && pa.text.size() == pb.text.size() - b.o && b.o == 0) { pa.style = pb.style; pa.list = pb.list; pa.indent = pb.indent; pa.checked = pb.checked; }
+ N->paras.erase(N->paras.begin() + a.p + 1, N->paras.begin() + b.p + 1);
+ }
+ caret = anchor = a;
+}
+
+void DeleteSel() { if (HasSel()) { Pos a = SelStart(), b = SelEnd(); DeleteRange(a, b); } }
+
+void InsertPlain(const std::wstring& s, uint8_t at) {
+ Para& p = P(caret.p);
+ p.text.insert(caret.o, s);
+ p.at.insert(p.at.begin() + caret.o, s.size(), at);
+ caret.o += (int)s.size();
+ anchor = caret;
+}
+
+void SplitPara() {
+ Para& p = P(caret.p);
+ Para np;
+ np.text = p.text.substr(caret.o);
+ np.at.assign(p.at.begin() + caret.o, p.at.end());
+ p.text.resize(caret.o);
+ p.at.resize(caret.o);
+ np.list = p.list; np.indent = p.indent;
+ np.style = p.style <= S_SUBHEADING ? (uint8_t)S_BODY : p.style;
+ if (p.collapsed) p.collapsed = false;
+ N->paras.insert(N->paras.begin() + caret.p + 1, np);
+ caret = anchor = { caret.p + 1, 0 };
+}
+
+void InsertParas(std::vector<Para> v) {
+ if (v.empty()) return;
+ DeleteSel();
+ if (v.size() == 1) {
+ Para& p = P(caret.p);
+ p.text.insert(caret.o, v[0].text);
+ p.at.insert(p.at.begin() + caret.o, v[0].at.begin(), v[0].at.end());
+ caret.o += (int)v[0].text.size(); anchor = caret;
+ return;
+ }
+ Para& p = P(caret.p);
+ std::wstring tail = p.text.substr(caret.o);
+ std::vector<uint8_t> tailAt(p.at.begin() + caret.o, p.at.end());
+ p.text.resize(caret.o); p.at.resize(caret.o);
+ p.text += v[0].text; p.at.insert(p.at.end(), v[0].at.begin(), v[0].at.end());
+ if (caret.o == 0) { p.style = v[0].style; p.list = v[0].list; p.indent = v[0].indent; p.checked = v[0].checked; }
+ int at = caret.p + 1;
+ for (size_t k = 1; k < v.size(); k++) N->paras.insert(N->paras.begin() + at++, v[k]);
+ Para& last = P(at - 1);
+ caret = anchor = { at - 1, (int)last.text.size() };
+ last.text += tail; last.at.insert(last.at.end(), tailAt.begin(), tailAt.end());
+}
+
+bool IsWordChar(wchar_t c) { return iswalnum(c) || c == L'_'; }
+int PrevWord(const std::wstring& t, int i) { while (i > 0 && !IsWordChar(t[i - 1])) i--; while (i > 0 && IsWordChar(t[i - 1])) i--; return i; }
+int NextWord(const std::wstring& t, int i) { int n = (int)t.size(); while (i < n && !IsWordChar(t[i])) i++; while (i < n && IsWordChar(t[i])) i++; return i; }
+
+void UncollapseAround(int i) { // o cursor entrou numa seção recolhida: abre os títulos que a escondem
+ if (pl.size() != (size_t)Count() || !pl[i].hidden) return;
+ for (int k = i - 1; k >= 0; k--) if (P(k).collapsed && Level(P(k)) < Level(P(i))) { P(k).collapsed = false; }
+ dirtyLayout = true;
+}
+
+int PrevVisible(int i) { for (int k = i - 1; k >= 0; k--) if (k >= (int)pl.size() || !pl[k].hidden) return k; return -1; }
+int NextVisible(int i) { for (int k = i + 1; k < Count(); k++) if (k >= (int)pl.size() || !pl[k].hidden) return k; return -1; }
+
+// parágrafos atingidos pela seleção (ou o do cursor)
+void SelParas(int& a, int& b) {
+ Pos s = SelStart(), e = SelEnd();
+ a = s.p; b = e.p;
+ if (HasSel() && e.o == 0 && e.p > s.p) b--; // seleção que termina no começo do parágrafo não o inclui
+}
+
+std::vector<Para> SelectionParas() {
+ std::vector<Para> v;
+ Pos s = SelStart(), e = SelEnd();
+ for (int i = s.p; i <= e.p; i++) {
+ Para p = P(i);
+ int a = i == s.p ? s.o : 0, b = i == e.p ? e.o : (int)p.text.size();
+ p.text = p.text.substr(a, b - a);
+ p.at = std::vector<uint8_t>(P(i).at.begin() + a, P(i).at.begin() + b);
+ p.collapsed = false;
+ v.push_back(p);
+ }
+ return v;
+}
+
+UINT ClipFormat() { static UINT f = RegisterClipboardFormatW(L"NotasParagrafos"); return f; }
+
+} // namespace
+
+// ---------------------------------------------------------------------------
+namespace editor {
+
+void SetFormats(const std::wstring& fam, const std::wstring& mono) {
+ family = fam; monoFamily = mono;
+ for (int s = 0; s < 5; s++) {
+ if (fmt[s]) fmt[s]->Release();
+ gfx::dw->CreateTextFormat(s == S_MONO ? monoFamily.c_str() : family.c_str(), nullptr, SM[s].w, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, SM[s].size, L"pt-br", &fmt[s]);
+ if (fmt[s]) fmt[s]->SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
+ }
+ ReleaseLayouts();
+}
+void SetDark(bool d) { dark = d; ReleaseBrushes(); ReleaseLayouts(); }
+void SetSearch(const std::wstring& q) { query = q; for (auto& c : query) c = towlower(c); }
+
+Note* Current() { return N; }
+
+void SetNote(Note* n) {
+ if (n == N) return;
+ N = n;
+ caret = anchor = { 0, 0 };
+ scrollY = 0; desiredX = -1; typingSet = false;
+ ReleaseLayouts();
+ if (N && N->paras.empty()) N->paras.push_back(Para{});
+}
+
+void PlaceCaretAtEnd() {
+ if (!N) return;
+ caret.p = Count() - 1; caret.o = (int)P(caret.p).text.size(); anchor = caret;
+ wantReveal = true;
+}
+
+void Focus(bool on) { focused = on; blinkOn = true; }
+bool Focused() { return focused; }
+void BlinkReset() { blinkOn = true; }
+void ToggleBlink() { blinkOn = !blinkOn; }
+void Invalidate() { dirtyLayout = true; }
+bool HasSelection() { return N && HasSel(); }
+
+// grade da tabela que começa no parágrafo i: contorno arredondado, linhas entre as linhas e entre as colunas
+void DrawTableGrid(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, int i, float ox, float oy) {
+ int j = i;
+ while (IsRow(j + 1)) j++;
+ PL& a = pl[i]; PL& b = pl[j];
+ float L = ox + a.base, R = L + a.tableW, T = oy + a.y - a.pad, B = oy + b.y + b.h + b.pad;
+ br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.20f) : D2D1::ColorF(0, 0, 0, 0.16f));
+ for (int k = i; k < j; k++) { if (pl[k].hidden) continue; float y = oy + pl[k].y + pl[k].h + pl[k].pad; dc->DrawLine({ L, y }, { R, y }, br, 1); }
+ for (int c = 1; c < a.cols; c++) { float x = L + c * a.colW; dc->DrawLine({ x, T }, { x, B }, br, 1); }
+ dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(L + 0.5f, T + 0.5f, R - 0.5f, B - 0.5f), 6, 6), br, 1);
+}
+
+// anexo: a imagem (cantos de 8) ou um cartão com a folha, o nome e o tamanho; clique duplo abre
+void DrawFile(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, const Para& p, const PL& l, float ox, float oy, bool inSel, D2D1_COLOR_F accent) {
+ D2D1_RECT_F r = D2D1::RectF(ox + l.x, oy + l.y, ox + l.x + l.imgW, oy + l.y + l.imgH);
+ ID2D1Factory* f = nullptr; dc->GetFactory(&f);
+ if (ID2D1Bitmap* b = imgs.count(p.src) ? imgs[p.src] : nullptr) {
+ ID2D1RoundedRectangleGeometry* g = nullptr;
+ if (f) f->CreateRoundedRectangleGeometry(D2D1::RoundedRect(r, 8, 8), &g);
+ if (g) dc->PushLayer(D2D1::LayerParameters(D2D1::InfiniteRect(), g), nullptr);
+ dc->DrawBitmap(b, r, 1, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR);
+ if (g) { dc->PopLayer(); g->Release(); }
+ br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.12f) : D2D1::ColorF(0, 0, 0, 0.10f));
+ dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(r.left + 0.5f, r.top + 0.5f, r.right - 0.5f, r.bottom - 0.5f), 7.5f, 7.5f), br, 1);
+ } else {
+ br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.07f) : D2D1::ColorF(0, 0, 0, 0.035f));
+ dc->FillRoundedRectangle(D2D1::RoundedRect(r, 10, 10), br);
+ br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.12f) : D2D1::ColorF(0, 0, 0, 0.10f));
+ dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(r.left + 0.5f, r.top + 0.5f, r.right - 0.5f, r.bottom - 0.5f), 9.5f, 9.5f), br, 1);
+ // folha com a ponta dobrada
+ float fx = r.left + 14, fy = r.top + 11, fw = 22, fh = 30, d = 7;
+ ID2D1PathGeometry* g = nullptr;
+ if (f && SUCCEEDED(f->CreatePathGeometry(&g))) {
+ ID2D1GeometrySink* k = nullptr; g->Open(&k);
+ k->BeginFigure({ fx, fy }, D2D1_FIGURE_BEGIN_FILLED);
+ k->AddLine({ fx + fw - d, fy }); k->AddLine({ fx + fw, fy + d }); k->AddLine({ fx + fw, fy + fh }); k->AddLine({ fx, fy + fh });
+ k->EndFigure(D2D1_FIGURE_END_CLOSED); k->Close(); k->Release();
+ br->SetColor(dark ? D2D1::ColorF(0.30f, 0.30f, 0.32f) : D2D1::ColorF(1, 1, 1));
+ dc->FillGeometry(g, br);
+ br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.45f) : D2D1::ColorF(0, 0, 0, 0.35f));
+ dc->DrawGeometry(g, br, 1);
+ dc->DrawLine({ fx + fw - d, fy }, { fx + fw - d, fy + d }, br, 1); dc->DrawLine({ fx + fw - d, fy + d }, { fx + fw, fy + d }, br, 1);
+ g->Release();
+ }
+ std::wstring name = ShownName(p.src), info;
+ WIN32_FILE_ATTRIBUTE_DATA fa{};
+ if (GetFileAttributesExW(p.src.c_str(), GetFileExInfoStandard, &fa)) {
+ double kb = (((ULONGLONG)fa.nFileSizeHigh << 32) | fa.nFileSizeLow) / 1024.0;
+ wchar_t b[64];
+ if (kb < 1024) swprintf_s(b, L"%.0f KB", std::max(1.0, kb)); else swprintf_s(b, L"%.1f MB", kb / 1024);
+ info = b;
+ } else info = Tr(L"Arquivo não encontrado");
+ std::wstring ext = name.substr(name.find_last_of(L'.') + 1);
+ if (ext.size() < name.size() && ext.size() <= 5) { for (auto& c : ext) c = towupper(c); info = ext + L" · " + info; }
+ IDWriteTextFormat *t1 = nullptr, *t2 = nullptr;
+ gfx::dw->CreateTextFormat(family.c_str(), nullptr, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 13, L"pt-br", &t1);
+ gfx::dw->CreateTextFormat(family.c_str(), nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 11, L"pt-br", &t2);
+ DWRITE_TRIMMING tr{ DWRITE_TRIMMING_GRANULARITY_CHARACTER, 0, 0 };
+ if (t1) { t1->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP); t1->SetTrimming(&tr, nullptr); br->SetColor(TextColor()); dc->DrawTextW(name.c_str(), (UINT32)name.size(), t1, D2D1::RectF(r.left + 48, r.top + 9, r.right - 10, r.top + 27), br); t1->Release(); }
+ if (t2) { br->SetColor(Text2()); dc->DrawTextW(info.c_str(), (UINT32)info.size(), t2, D2D1::RectF(r.left + 48, r.top + 28, r.right - 10, r.top + 44), br); t2->Release(); }
+ }
+ if (f) f->Release();
+ if (inSel) { br->SetColor(D2D1::ColorF(accent.r, accent.g, accent.b, focused ? 0.38f : 0.18f)); dc->FillRoundedRectangle(D2D1::RoundedRect(r, 8, 8), br); }
+}
+
+void Draw(ID2D1DeviceContext* dc, D2D1_RECT_F a) {
+ area = a;
+ if (!N) return;
+ Clamp();
+ BuildLayouts(dc, a.right - a.left);
+ if (wantReveal) { Reveal(); wantReveal = false; }
+ float h = a.bottom - a.top;
+ scrollY = std::clamp(scrollY, 0.f, std::max(0.f, contentH - h));
+ float ox = a.left, oy = a.top - scrollY;
+ dc->PushAxisAlignedClip(a, D2D1_ANTIALIAS_MODE_ALIASED);
+ ID2D1SolidColorBrush* br = nullptr;
+ dc->CreateSolidColorBrush(TextColor(), &br);
+ if (semaforo::Leopard()) {
+ // Leopard: o bloco amarelo das Notas do Mail — amarelo-claro, as pautas finas a cada 24 (rolam com o texto) e a
+ // margem dupla avermelhada à esquerda
+ br->SetColor(D2D1::ColorF(1, 0.976f, 0.73f));
+ dc->FillRectangle(a, br);
+ br->SetColor(D2D1::ColorF(0.55f, 0.62f, 0.80f, 0.35f));
+ float y0 = a.top + 40 - std::fmod(scrollY, 24.f);
+ for (float y = y0; y < a.bottom; y += 24) dc->DrawLine({ a.left, y }, { a.right, y }, br, 1);
+ br->SetColor(D2D1::ColorF(0.85f, 0.35f, 0.30f, 0.45f));
+ dc->DrawLine({ a.left + 10, a.top }, { a.left + 10, a.bottom }, br, 1);
+ dc->DrawLine({ a.left + 13, a.top }, { a.left + 13, a.bottom }, br, 1);
+ br->SetColor(TextColor());
+ }
+
+ // data no alto, centralizada e cinza
+ {
+ std::wstring d = LongDate(N->modified);
+ IDWriteTextFormat* tf = nullptr;
+ gfx::dw->CreateTextFormat(family.c_str(), nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 12, L"pt-br", &tf);
+ if (tf) {
+ tf->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
+ br->SetColor(Text2());
+ dc->DrawTextW(d.c_str(), (UINT32)d.size(), tf, D2D1::RectF(ox, oy + 6, a.right, oy + 24), br);
+ tf->Release();
+ }
+ }
+ Pos ss = SelStart(), se = SelEnd();
+ bool sel = HasSel();
+ D2D1_COLOR_F accent = Accent();
+ for (int i = 0; i < Count(); i++) {
+ PL& l = pl[i];
+ if (l.hidden || !l.tl) continue;
+ float py = oy + l.y;
+ if (py > a.bottom || py + l.h < a.top) continue;
+ Para& p = P(i);
+ float px = ox + l.x;
+ bool inSel = sel && i >= ss.p && i <= se.p && !(i == se.p && se.o == 0 && se.p > ss.p);
+ if (p.kind == K_FILE) { DrawFile(dc, br, p, l, ox, oy, inSel, accent); continue; }
+ if (p.kind == K_ROW && !IsRow(i - 1)) DrawTableGrid(dc, br, i, ox, oy);
+ auto rangeRects = [&](int from, int len, D2D1_COLOR_F c, float pad) {
+ if (len <= 0) return;
+ UINT32 cnt = 0;
+ l.tl->HitTestTextRange(from, len, 0, 0, nullptr, 0, &cnt);
+ std::vector<DWRITE_HIT_TEST_METRICS> ms(cnt);
+ l.tl->HitTestTextRange(from, len, 0, 0, ms.data(), cnt, &cnt);
+ br->SetColor(c);
+ for (auto& m : ms) dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(px + m.left - pad, py + m.top + 1, px + m.left + m.width + pad, py + m.top + m.height), 3, 3), br);
+ };
+ // realces
+ for (int k = 0; k < (int)p.at.size();) {
+ int j = k; int hcol = HiOf(p.at[k]);
+ while (j < (int)p.at.size() && HiOf(p.at[j]) == hcol) j++;
+ if (hcol) rangeRects(k, j - k, HiBack(hcol), 1);
+ k = j;
+ }
+ // resultados das contas: fundo amarelado discreto
+ if (i < (int)math.size() && !math[i].result.empty())
+ rangeRects(l.resultAt, (int)math[i].result.size(), D2D1::ColorF(accent.r, accent.g, accent.b, dark ? 0.16f : 0.13f), 1);
+ // busca
+ if (!query.empty() && query.size() <= p.text.size()) {
+ std::wstring low = p.text; for (auto& c : low) c = towlower(c);
+ for (size_t f = low.find(query); f != std::wstring::npos; f = low.find(query, f + query.size()))
+ rangeRects((int)f, (int)query.size(), D2D1::ColorF(1.0f, 0.85f, 0.1f, dark ? 0.55f : 0.6f), 0.5f);
+ }
+ // seleção
+ if (sel && i >= ss.p && i <= se.p) {
+ int from = i == ss.p ? ss.o : 0, to = i == se.p ? se.o : (int)p.text.size();
+ D2D1_COLOR_F sc = focused ? D2D1::ColorF(accent.r, accent.g, accent.b, dark ? 0.40f : 0.38f) : (dark ? D2D1::ColorF(1, 1, 1, 0.14f) : D2D1::ColorF(0, 0, 0, 0.10f));
+ rangeRects(from, to - from, sc, 0);
+ if (i < se.p) { // a quebra de linha também está selecionada
+ D2D1_RECT_F c = CaretRectAt({ i, (int)p.text.size() });
+ br->SetColor(sc);
+ dc->FillRectangle(D2D1::RectF(ox + c.left, oy + c.top + 1, ox + c.left + 6, oy + c.bottom), br);
+ }
+ }
+ // marcador da lista
+ float x0, y0; DWRITE_HIT_TEST_METRICS m0;
+ l.tl->HitTestTextPosition(0, FALSE, &x0, &y0, &m0);
+ float cy = py + m0.top + m0.height / 2;
+ float mx = ox + l.base;
+ if (p.list == L_CHECK) {
+ D2D1_POINT_2F c{ mx + 9, cy };
+ if (p.checked) {
+ br->SetColor(accent);
+ dc->FillEllipse(D2D1::Ellipse(c, 8.5f, 8.5f), br);
+ br->SetColor(D2D1::ColorF(1, 1, 1));
+ simbolo::Draw(dc, L"checkmark", D2D1::RectF(c.x - 4.6f, c.y - 4.2f, c.x + 4.6f, c.y + 4.2f), br);
+ } else {
+ br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.38f) : D2D1::ColorF(0, 0, 0, 0.30f));
+ dc->DrawEllipse(D2D1::Ellipse(c, 8, 8), br, 1.1f);
+ }
+ } else if (p.list != L_NONE && p.kind == K_TEXT) {
+ std::wstring mk = p.list == L_BULLET ? L"•" : p.list == L_DASH ? L"–" : std::to_wstring(l.number) + L".";
+ IDWriteTextLayout* ml = nullptr;
+ gfx::dw->CreateTextLayout(mk.c_str(), (UINT32)mk.size(), fmt[p.style], 40, 100, &ml);
+ if (ml) {
+ ml->SetLineSpacing(DWRITE_LINE_SPACING_METHOD_UNIFORM, SM[p.style].line, SM[p.style].line * 0.8f);
+ DWRITE_TEXT_METRICS tm{}; ml->GetMetrics(&tm);
+ float x = p.list == L_NUMBER ? mx + 19 - tm.width : mx + 4;
+ br->SetColor(TextColor());
+ dc->DrawTextLayout(D2D1::Point2F(x, py), ml, br);
+ ml->Release();
+ }
+ }
+ // seta das seções recolhíveis (títulos): aparece com o mouse em cima ou quando recolhida
+ if (Level(p) < 99 && (p.collapsed || hoverChevron == i)) {
+ br->SetColor(Text2());
+ float cx = ox + 11, s = 4.2f;
+ ID2D1PathGeometry* g = nullptr; ID2D1Factory* f = nullptr; dc->GetFactory(&f);
+ if (f && SUCCEEDED(f->CreatePathGeometry(&g))) {
+ ID2D1GeometrySink* k = nullptr; g->Open(&k);
+ if (p.collapsed) { k->BeginFigure({ cx - s / 2, cy - s }, D2D1_FIGURE_BEGIN_HOLLOW); k->AddLine({ cx + s / 2, cy }); k->AddLine({ cx - s / 2, cy + s }); }
+ else { k->BeginFigure({ cx - s, cy - s / 2 }, D2D1_FIGURE_BEGIN_HOLLOW); k->AddLine({ cx, cy + s / 2 }); k->AddLine({ cx + s, cy - s / 2 }); }
+ k->EndFigure(D2D1_FIGURE_END_OPEN); k->Close(); k->Release();
+ ID2D1StrokeStyle* rs = nullptr;
+ f->CreateStrokeStyle(D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_ROUND), nullptr, 0, &rs);
+ dc->DrawGeometry(g, br, 1.6f, rs);
+ if (rs) rs->Release();
+ g->Release();
+ }
+ if (f) f->Release();
+ }
+ br->SetColor(TextColor());
+ dc->DrawTextLayout(D2D1::Point2F(px, py), l.tl, br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT);
+ }
+ // cursor amarelo
+ if (focused && blinkOn && !sel && caret.p < (int)pl.size() && !pl[caret.p].hidden) {
+ D2D1_RECT_F c = CaretRectAt(caret);
+ br->SetColor(accent);
+ dc->FillRectangle(D2D1::RectF(ox + c.left - 0.5f, oy + c.top, ox + c.left + 1.5f, oy + c.bottom), br);
+ }
+ br->Release();
+ dc->PopAxisAlignedClip();
+}
+
+void CaretScreenRect(D2D1_RECT_F& r) {
+ D2D1_RECT_F c = CaretRectAt(caret);
+ r = { area.left + c.left, area.top - scrollY + c.top, area.left + c.right, area.top - scrollY + c.bottom };
+}
+
+void OnWheel(float dy) { scrollY = std::max(0.f, scrollY - dy); }
+
+static int ChevronAt(D2D1_POINT_2F p) {
+ if (!N || pl.size() != (size_t)Count() || p.x < area.left || p.x > area.left + MARGIN) return -1;
+ float y = p.y - area.top + scrollY;
+ for (int i = 0; i < Count(); i++)
+ if (!pl[i].hidden && Level(P(i)) < 99 && y >= pl[i].y && y < pl[i].y + SM[P(i).style].line + 2) return i;
+ return -1;
+}
+bool OverChevronArea(D2D1_POINT_2F p) { return ChevronAt(p) >= 0; }
+
+void OnMouseMove(D2D1_POINT_2F p, bool dragging) {
+ if (!N) return;
+ if (!dragging) {
+ // a seta aparece com o mouse em qualquer lugar da linha do título
+ int hc = -1;
+ if (pl.size() == (size_t)Count() && p.x >= area.left && p.x < area.right) {
+ float y = p.y - area.top + scrollY;
+ for (int i = 0; i < Count(); i++)
+ if (!pl[i].hidden && Level(P(i)) < 99 && y >= pl[i].y && y < pl[i].y + pl[i].h) { hc = i; break; }
+ }
+ if (hc != hoverChevron) { hoverChevron = hc; RequestPaint(); }
+ return;
+ }
+ Pos q = HitContent(p.x - area.left, p.y - area.top + scrollY);
+ if (clickMode == 2) {
+ const std::wstring& t = P(q.p).text;
+ if (Less(q, clickA)) { caret = { q.p, PrevWord(t, std::min(q.o + 1, (int)t.size())) }; anchor = clickB; }
+ else { caret = { q.p, NextWord(t, q.o) }; anchor = clickA; }
+ } else if (clickMode == 3) {
+ if (q.p < clickA.p) { caret = { q.p, 0 }; anchor = clickB; }
+ else { caret = { q.p, (int)P(q.p).text.size() }; anchor = clickA; }
+ } else caret = q;
+ if (p.y < area.top) scrollY = std::max(0.f, scrollY - 12);
+ if (p.y > area.bottom) scrollY += 12;
+ desiredX = -1;
+ RequestPaint();
+}
+
+void OnMouseDown(D2D1_POINT_2F p, bool shift, int clicks) {
+ if (!N) return;
+ focused = true; blinkOn = true;
+ int ch = ChevronAt(p);
+ if (ch >= 0 && clicks == 1) {
+ Checkpoint(3);
+ P(ch).collapsed = !P(ch).collapsed;
+ if (P(ch).collapsed && caret.p > ch) { caret = anchor = { ch, (int)P(ch).text.size() }; }
+ N->dirty = true; dirtyLayout = true; NoteEdited(N);
+ return;
+ }
+ float cx = p.x - area.left, cy = p.y - area.top + scrollY;
+ // bolinha da lista de verificação
+ for (int i = 0; i < Count() && pl.size() == (size_t)Count(); i++) {
+ if (pl[i].hidden || P(i).list != L_CHECK || !pl[i].tl) continue;
+ float x0, y0; DWRITE_HIT_TEST_METRICS m0;
+ pl[i].tl->HitTestTextPosition(0, FALSE, &x0, &y0, &m0);
+ float ccx = pl[i].base + 9, ccy = pl[i].y + m0.top + m0.height / 2;
+ if (std::fabs(cx - ccx) <= 11 && std::fabs(cy - ccy) <= 11) {
+ Checkpoint(3);
+ P(i).checked = !P(i).checked;
+ Changed();
+ wantReveal = false;
+ return;
+ }
+ }
+ Pos q = HitContent(cx, cy);
+ typingSet = false; desiredX = -1;
+ if (P(q.p).kind == K_FILE) { // anexo: clique põe o cursor nele; clique duplo abre no programa padrão
+ caret = q; if (!shift) anchor = q;
+ clickMode = 1;
+ if (clicks == 2) ShellExecuteW(nullptr, L"open", P(q.p).src.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
+ RequestPaint();
+ return;
+ }
+ const std::wstring& t = P(q.p).text;
+ if (clicks == 2) {
+ int a = q.o, b = q.o;
+ if (a < (int)t.size() && IsWordChar(t[a])) { while (a > 0 && IsWordChar(t[a - 1])) a--; while (b < (int)t.size() && IsWordChar(t[b])) b++; }
+ else if (b < (int)t.size()) b++;
+ anchor = { q.p, a }; caret = { q.p, b };
+ clickA = anchor; clickB = caret; clickMode = 2;
+ } else if (clicks >= 3) {
+ anchor = { q.p, 0 }; caret = { q.p, (int)t.size() };
+ clickA = anchor; clickB = caret; clickMode = 3;
+ } else {
+ caret = q;
+ if (!shift) anchor = q;
+ clickMode = 1;
+ }
+ RequestPaint();
+}
+
+void SelectAll() { if (!N) return; anchor = { 0, 0 }; caret = { Count() - 1, (int)P(Count() - 1).text.size() }; }
+
+void Copy(bool cut) {
+ if (!N || !HasSel()) return;
+ auto v = SelectionParas();
+ std::wstring plain;
+ for (size_t i = 0; i < v.size(); i++) { if (i) plain += L"\r\n"; plain += v[i].text; }
+ std::wstring rich = store::Serialize(v);
+ if (OpenClipboard(nullptr)) {
+ EmptyClipboard();
+ auto put = [](UINT fmtId, const std::wstring& s) {
+ HGLOBAL g = GlobalAlloc(GMEM_MOVEABLE, (s.size() + 1) * sizeof(wchar_t));
+ if (!g) return;
+ memcpy(GlobalLock(g), s.c_str(), (s.size() + 1) * sizeof(wchar_t));
+ GlobalUnlock(g);
+ if (!SetClipboardData(fmtId, g)) GlobalFree(g);
+ };
+ put(CF_UNICODETEXT, plain);
+ put(ClipFormat(), rich);
+ CloseClipboard();
+ }
+ if (cut) { Checkpoint(3); DeleteSel(); Changed(); }
+}
+
+void Paste() {
+ if (!N || !OpenClipboard(nullptr)) return;
+ std::vector<Para> v;
+ if (HANDLE h = GetClipboardData(ClipFormat())) {
+ if (auto* p = (const wchar_t*)GlobalLock(h)) { v = store::Deserialize(p); GlobalUnlock(h); }
+ } else if (HANDLE h2 = GetClipboardData(CF_UNICODETEXT)) {
+ if (auto* p = (const wchar_t*)GlobalLock(h2)) {
+ std::wstring s = p; GlobalUnlock(h2);
+ uint8_t at = AttrAtCaret() & ~0x70; // texto colado sem realce
+ size_t a = 0;
+ for (;;) {
+ size_t e = s.find(L'\n', a);
+ std::wstring line = s.substr(a, e == std::wstring::npos ? std::wstring::npos : e - a);
+ if (!line.empty() && line.back() == L'\r') line.pop_back();
+ Para q; q.text = line; q.at.assign(line.size(), at);
+ q.style = S_BODY;
+ v.push_back(q);
+ if (e == std::wstring::npos) break;
+ a = e + 1;
+ }
+ if (v.size() == 1) v[0].style = P(caret.p).style;
+ }
+ }
+ CloseClipboard();
+ if (v.empty()) return;
+ Checkpoint(3);
+ InsertParas(v);
+ typingSet = false;
+ Changed();
+}
+
+void Undo() {
+ if (!N || N->undo.empty()) return;
+ N->redo.push_back({ N->paras, caret.p, caret.o, anchor.p, anchor.o });
+ auto s = N->undo.back(); N->undo.pop_back();
+ N->paras = s.paras; caret = { s.cp, s.co }; anchor = { s.ap, s.ao };
+ N->lastEditKind = 0;
+ Clamp(); Changed();
+}
+void Redo() {
+ if (!N || N->redo.empty()) return;
+ N->undo.push_back({ N->paras, caret.p, caret.o, anchor.p, anchor.o });
+ auto s = N->redo.back(); N->redo.pop_back();
+ N->paras = s.paras; caret = { s.cp, s.co }; anchor = { s.ap, s.ao };
+ N->lastEditKind = 0;
+ Clamp(); Changed();
+}
+
bool InTable() { return N && IsRow(caret.p); }
void InsertTable(int rows, int cols) {
@@ -1039,340 +1039,463 @@ bool Transform(int kind) {
return true;
}
-int CurrentStyle() { return N ? P(caret.p).style : S_BODY; }
-int CurrentList() { return N ? P(caret.p).list : L_NONE; }
-uint8_t CurrentAttrs() {
- if (!N) return 0;
- if (HasSel()) { Pos s = SelStart(); return s.o < (int)P(s.p).at.size() ? P(s.p).at[s.o] : 0; }
- return AttrAtCaret();
-}
-
-void ApplyStyle(int style) {
- if (!N) return;
- Checkpoint(3);
- int a, b; SelParas(a, b);
- for (int i = a; i <= b; i++) { P(i).style = (uint8_t)style; if (style > S_SUBHEADING) P(i).collapsed = false; }
- Changed();
-}
-
-void ToggleAttr(uint8_t flag) {
- if (!N) return;
- if (!HasSel()) { typing = AttrAtCaret() ^ flag; typingSet = true; return; }
- Checkpoint(3);
- Pos s = SelStart(), e = SelEnd();
- bool all = true;
- for (int i = s.p; i <= e.p; i++) {
- int from = i == s.p ? s.o : 0, to = i == e.p ? e.o : (int)P(i).text.size();
- for (int k = from; k < to; k++) if (!(P(i).at[k] & flag)) all = false;
- }
- for (int i = s.p; i <= e.p; i++) {
- int from = i == s.p ? s.o : 0, to = i == e.p ? e.o : (int)P(i).text.size();
- for (int k = from; k < to; k++) P(i).at[k] = all ? (P(i).at[k] & ~flag) : (P(i).at[k] | flag);
- }
- Changed();
-}
-
-void SetHighlight(int h) {
- if (!N) return;
- if (!HasSel()) { typing = WithHi(AttrAtCaret(), h); typingSet = true; return; }
- Checkpoint(3);
- Pos s = SelStart(), e = SelEnd();
- for (int i = s.p; i <= e.p; i++) {
- int from = i == s.p ? s.o : 0, to = i == e.p ? e.o : (int)P(i).text.size();
- for (int k = from; k < to; k++) P(i).at[k] = WithHi(P(i).at[k], h);
- }
- Changed();
-}
-
-void ToggleList(int kind) {
- if (!N) return;
- Checkpoint(3);
- int a, b; SelParas(a, b);
- bool all = true;
- for (int i = a; i <= b; i++) if (P(i).list != kind) all = false;
- for (int i = a; i <= b; i++) {
- if (P(i).kind != K_TEXT) continue;
- P(i).list = all ? (uint8_t)L_NONE : (uint8_t)kind;
- if (!all && P(i).style != S_MONO) P(i).style = P(i).style <= S_SUBHEADING && P(i).text.empty() ? (uint8_t)S_BODY : P(i).style;
- P(i).checked = false;
- }
- Changed();
-}
-
-void Indent(int d) {
- if (!N) return;
- Checkpoint(3);
- int a, b; SelParas(a, b);
- for (int i = a; i <= b; i++) P(i).indent = (uint8_t)std::clamp(P(i).indent + d, 0, 8);
- Changed();
-}
-
-void ToggleChecked() {
- if (!N) return;
- Checkpoint(3);
- int a, b; SelParas(a, b);
- for (int i = a; i <= b; i++) if (P(i).list == L_CHECK) P(i).checked = !P(i).checked;
- Changed();
-}
-
-void OnChar(wchar_t c) {
- if (!N || !focused) return;
- if ((c == L'\r' || c == L'\n') && !HasSel() && (IsFile(caret.p) || IsRow(caret.p))) {
- Checkpoint(3);
- int i = caret.p;
- if (IsFile(i)) { N->paras.insert(N->paras.begin() + i + 1, Para{}); caret = anchor = { i + 1, 0 }; }
- else {
- Para& r = P(i);
- bool empty = r.text.find_first_not_of(L'\t') == std::wstring::npos;
- if (empty && !IsRow(i + 1) && IsRow(i - 1)) { r.kind = K_TEXT; r.text.clear(); r.at.clear(); caret = anchor = { i, 0 }; } // sai da tabela
- else {
- Para nr; nr.kind = K_ROW; nr.text.assign(TableCols(i) - 1, L'\t'); nr.at.assign(nr.text.size(), 0);
- N->paras.insert(N->paras.begin() + i + 1, nr);
- caret = anchor = { i + 1, 0 };
- }
- }
- typingSet = false;
- Changed();
- return;
- }
- if (c == L'\r' || c == L'\n') {
- Checkpoint(3);
- DeleteSel();
- Para& p = P(caret.p);
- if (p.list != L_NONE && p.text.empty()) { // Enter na linha vazia da lista: sai da lista (ou volta um nível)
- if (p.indent > 0) p.indent--; else p.list = L_NONE;
- } else if (caret.o == 0 && !p.text.empty()) { // no começo: abre uma linha em cima com a mesma formatação
- Para np = p; np.text.clear(); np.at.clear(); np.checked = false; np.collapsed = false;
- N->paras.insert(N->paras.begin() + caret.p, np);
- caret = anchor = { caret.p + 1, 0 };
- } else SplitPara();
- typingSet = false;
- Changed();
- return;
- }
- if (c == L'\t') return; // tratado em OnKey
- if (c < 32 || c == 127) return;
- Checkpoint(1);
- if (!HasSel() && IsFile(caret.p)) { // digitou com o cursor no anexo: o texto vai num parágrafo novo depois dele
- Checkpoint(3);
- N->paras.insert(N->paras.begin() + caret.p + 1, Para{});
- caret = anchor = { caret.p + 1, 0 };
- }
- uint8_t at = AttrAtCaret();
- DeleteSel();
- Para& p = P(caret.p);
- // atalhos de digitação: "* " / "- " / "1. " viram listas, como no Mac
- if (c == L' ' && p.list == L_NONE && caret.o == (int)p.text.size() && p.style != S_MONO) {
- int kind = -1;
- if (p.text == L"*" || p.text == L"•") kind = L_BULLET;
- else if (p.text == L"-" || p.text == L"–") kind = L_DASH;
- else if (p.text == L"1." || p.text == L"1)") kind = L_NUMBER;
- else if (p.text == L"[]" || p.text == L"[ ]") kind = L_CHECK;
- if (kind >= 0 && p.kind == K_TEXT) {
- Checkpoint(3);
- p.text.clear(); p.at.clear(); p.list = (uint8_t)kind; caret.o = 0; anchor = caret;
- if (p.style <= S_SUBHEADING) p.style = S_BODY;
- Changed();
- return;
- }
- }
- InsertPlain(std::wstring(1, c), at);
- typing = at; // continua com o mesmo atributo
- Changed();
-}
-
-bool OnKey(UINT vk) {
- if (!N || !focused) return false;
- bool ctrl = GetKeyState(VK_CONTROL) < 0, shift = GetKeyState(VK_SHIFT) < 0;
- blinkOn = true;
- auto move = [&](Pos q, bool keepX = false) {
- caret = q;
- if (!shift) anchor = q;
- if (!keepX) desiredX = -1;
- typingSet = false;
- if (q.p < (int)pl.size() && pl[q.p].hidden) UncollapseAround(q.p);
- wantReveal = true;
- };
- // atalhos de formatação (Ctrl no lugar do Cmd)
- if (ctrl && shift) {
- switch (vk) {
- case 'T': ApplyStyle(S_TITLE); return true;
- case 'H': ApplyStyle(S_HEADING); return true;
- case 'J': ApplyStyle(S_SUBHEADING); return true;
- case 'B': ApplyStyle(S_BODY); return true;
- case 'M': ApplyStyle(S_MONO); return true;
- case '7': ToggleList(L_BULLET); return true;
- case '8': ToggleList(L_DASH); return true;
- case '9': ToggleList(L_NUMBER); return true;
- case 'L': ToggleList(L_CHECK); return true;
- case 'U': ToggleChecked(); return true;
- case 'X': ToggleAttr(A_STRIKE); return true;
- case 'Z': Redo(); return true;
- }
- }
- if (ctrl && !shift) {
- switch (vk) {
- case 'B': ToggleAttr(A_BOLD); return true;
- case 'I': ToggleAttr(A_ITALIC); return true;
- case 'U': ToggleAttr(A_UNDER); return true;
- case 'A': SelectAll(); return true;
- case 'C': Copy(false); return true;
- case 'X': Copy(true); return true;
- case 'V': Paste(); return true;
- case 'Z': Undo(); return true;
- case 'Y': Redo(); return true;
- case VK_OEM_6: Indent(1); return true; // Ctrl+]
- case VK_OEM_4: Indent(-1); return true; // Ctrl+[
- }
- }
- Para& p = P(caret.p);
- auto jump = [&](Pos q) { caret = anchor = q; desiredX = -1; typingSet = false; wantReveal = true; };
- auto eraseFile = [&](int i) { // apaga o anexo inteiro (fica pelo menos um parágrafo)
- Checkpoint(3);
- if (Count() == 1) { P(0) = Para{}; caret = anchor = { 0, 0 }; }
- else { N->paras.erase(N->paras.begin() + i); int k = std::min(i, Count() - 1); caret = anchor = { k, k < i ? (int)P(k).text.size() : 0 }; }
- Changed();
- };
- if (!HasSel() && !ctrl) {
- // tabela: Tab/Shift+Tab de célula em célula (Tab na última célula abre uma linha nova)
- if (vk == VK_TAB && IsRow(caret.p)) {
- const std::wstring& t = p.text;
- if (!shift) {
- size_t k = t.find(L'\t', caret.o);
- if (k != std::wstring::npos) jump({ caret.p, (int)k + 1 });
- else if (IsRow(caret.p + 1)) jump({ caret.p + 1, 0 });
- else {
- Checkpoint(3);
- Para nr; nr.kind = K_ROW; nr.text.assign(TableCols(caret.p) - 1, L'\t'); nr.at.assign(nr.text.size(), 0);
- N->paras.insert(N->paras.begin() + caret.p + 1, nr);
- jump({ caret.p + 1, 0 });
- Changed();
- }
- } else {
- int s0 = caret.o == 0 ? 0 : (int)(t.rfind(L'\t', caret.o - 1) == std::wstring::npos ? 0 : t.rfind(L'\t', caret.o - 1) + 1);
- if (s0 > 0) { size_t k = s0 >= 2 ? t.rfind(L'\t', s0 - 2) : std::wstring::npos; jump({ caret.p, k == std::wstring::npos ? 0 : (int)k + 1 }); }
- else if (IsRow(caret.p - 1)) { const std::wstring& u = P(caret.p - 1).text; size_t k = u.rfind(L'\t'); jump({ caret.p - 1, k == std::wstring::npos ? 0 : (int)k + 1 }); }
- }
- return true;
- }
- if (vk == VK_BACK || vk == VK_DELETE) {
- if (IsFile(caret.p)) { eraseFile(caret.p); return true; }
- if (IsRow(caret.p)) {
- const std::wstring& t = p.text;
- if (vk == VK_BACK && caret.o > 0 && t[caret.o - 1] == L'\t') { jump({ caret.p, caret.o - 1 }); return true; } // não junta células
- if (vk == VK_DELETE && (caret.o >= (int)t.size() || t[caret.o] == L'\t')) return true;
- if (vk == VK_BACK && caret.o == 0) {
- if (t.find_first_not_of(L'\t') == std::wstring::npos) { // linha vazia: some (a última vira texto)
- Checkpoint(3);
- if (IsRow(caret.p - 1) || IsRow(caret.p + 1)) {
- N->paras.erase(N->paras.begin() + caret.p);
- int k = std::max(0, caret.p - 1);
- caret = anchor = { k, (int)P(k).text.size() };
- } else { p.kind = K_TEXT; p.text.clear(); p.at.clear(); }
- Changed();
- }
- return true;
- }
- }
- if (vk == VK_BACK && caret.o == 0 && caret.p > 0) {
- int k = PrevVisible(caret.p);
- if (IsFile(k)) { eraseFile(k); return true; }
- if (IsRow(k)) { jump({ k, (int)P(k).text.size() }); return true; }
- }
- if (vk == VK_DELETE && caret.o == (int)p.text.size()) {
- int k = NextVisible(caret.p);
- if (IsFile(k)) { int keep = caret.p; eraseFile(k); caret = anchor = { keep, (int)P(keep).text.size() }; return true; }
- if (IsRow(k)) return true;
- }
- }
- }
- switch (vk) {
- case VK_LEFT:
- if (!shift && HasSel()) { move(SelStart()); return true; }
- if (caret.o > 0) move({ caret.p, ctrl ? PrevWord(p.text, caret.o) : caret.o - 1 });
- else { int k = PrevVisible(caret.p); if (k >= 0) move({ k, (int)P(k).text.size() }); }
- return true;
- case VK_RIGHT:
- if (!shift && HasSel()) { move(SelEnd()); return true; }
- if (caret.o < (int)p.text.size()) move({ caret.p, ctrl ? NextWord(p.text, caret.o) : caret.o + 1 });
- else { int k = NextVisible(caret.p); if (k >= 0) move({ k, 0 }); }
- return true;
- case VK_UP: case VK_DOWN: {
- if (pl.size() != (size_t)Count()) return true;
- if (ctrl) { move(vk == VK_UP ? Pos{ 0, 0 } : Pos{ Count() - 1, (int)P(Count() - 1).text.size() }); return true; }
- D2D1_RECT_F c = CaretRectAt(caret);
- if (desiredX < 0) desiredX = c.left;
- float y = vk == VK_UP ? c.top - 2 : c.bottom + 2;
- if (vk == VK_UP && caret.p == 0 && c.top <= pl[0].y + 1) { move({ 0, 0 }, true); return true; }
- if (vk == VK_DOWN && y >= contentH - 40) { move({ Count() - 1, (int)P(Count() - 1).text.size() }, true); return true; }
- // pula o espaço entre parágrafos
- Pos q = HitContent(desiredX, y);
- if (Same(q, caret)) q = HitContent(desiredX, vk == VK_UP ? y - 6 : y + 6);
- move(q, true);
- return true;
- }
- case VK_HOME: case VK_END: {
- if (ctrl) { move(vk == VK_HOME ? Pos{ 0, 0 } : Pos{ Count() - 1, (int)P(Count() - 1).text.size() }); return true; }
- if (pl.size() != (size_t)Count() || !pl[caret.p].tl) return true;
- D2D1_RECT_F c = CaretRectAt(caret);
- BOOL tr, in; DWRITE_HIT_TEST_METRICS m;
- pl[caret.p].tl->HitTestPoint(vk == VK_HOME ? -1000.f : 100000.f, (c.top + c.bottom) / 2 - pl[caret.p].y, &tr, &in, &m);
- int o = (int)m.textPosition + (tr ? (int)m.length : 0);
- o = std::min(o, (int)p.text.size());
- if (vk == VK_END && o > 0 && o < (int)p.text.size() && p.text[o - 1] == L' ') o--; // fim da linha quebrada
- move({ caret.p, o });
- return true;
- }
- case VK_PRIOR: case VK_NEXT: {
- float h = area.bottom - area.top;
- D2D1_RECT_F c = CaretRectAt(caret);
- scrollY += vk == VK_PRIOR ? -h : h;
- move(HitContent(c.left, (c.top + c.bottom) / 2 + (vk == VK_PRIOR ? -h : h)));
- return true;
- }
- case VK_BACK:
- if (HasSel()) { Checkpoint(2); DeleteSel(); Changed(); return true; }
- if (caret.o == 0) {
- Checkpoint(3);
- if (p.list != L_NONE) p.list = L_NONE;
- else if (p.indent > 0) p.indent--;
- else if (caret.p > 0) {
- int k = PrevVisible(caret.p);
- if (k < 0) k = caret.p - 1;
- if (P(k).text.empty() && !p.text.empty()) { // linha vazia em cima: some ela, este fica como está
- N->paras.erase(N->paras.begin() + k);
- caret = anchor = { k, 0 };
- } else {
- for (int z = k; z < caret.p; z++) P(z).collapsed = false;
- Pos a{ k, (int)P(k).text.size() };
- DeleteRange(a, { caret.p, 0 });
- }
- } else if (p.style != S_BODY && p.text.empty() && Count() > 1) p.style = S_BODY;
- Changed();
- return true;
- }
- Checkpoint(2);
- DeleteRange({ caret.p, ctrl ? PrevWord(p.text, caret.o) : caret.o - 1 }, caret);
- Changed();
- return true;
- case VK_DELETE:
- if (HasSel()) { Checkpoint(2); DeleteSel(); Changed(); return true; }
- Checkpoint(2);
- if (caret.o < (int)p.text.size()) DeleteRange(caret, { caret.p, ctrl ? NextWord(p.text, caret.o) : caret.o + 1 });
- else if (caret.p + 1 < Count()) { P(caret.p).collapsed = false; DeleteRange(caret, { caret.p + 1, 0 }); }
- Changed();
- return true;
- case VK_TAB: {
- int a, b; SelParas(a, b);
- if (p.list != L_NONE || a != b) { Indent(shift ? -1 : 1); return true; }
- if (!shift) { Checkpoint(1); uint8_t at = AttrAtCaret(); DeleteSel(); InsertPlain(L"\t", at); Changed(); }
- return true;
- }
- case VK_ESCAPE:
- if (HasSel()) { anchor = caret; return true; }
- return false;
- }
- return false;
-}
-
-} // namespace editor
+// ---- Ferramentas de Escrita com IA
+// Markdown simples nos dois sentidos: o modelo entende e devolve listas, títulos e tabelas que viram parágrafos de verdade
+static std::wstring ParaMd(const Para& p, int numero) {
+ if (p.kind == K_FILE) return L"";
+ if (p.kind == K_ROW) {
+ std::wstring t = L"| ";
+ for (wchar_t c : p.text) t += c == L'\t' ? std::wstring(L" | ") : std::wstring(1, c);
+ return t + L" |";
+ }
+ std::wstring pre(p.indent * 2, L' ');
+ if (p.style == S_TITLE) pre += L"# ";
+ else if (p.style == S_HEADING) pre += L"## ";
+ else if (p.style == S_SUBHEADING) pre += L"### ";
+ if (p.list == L_BULLET || p.list == L_DASH) pre += L"- ";
+ else if (p.list == L_NUMBER) pre += std::to_wstring(numero) + L". ";
+ else if (p.list == L_CHECK) pre += p.checked ? L"- [x] " : L"- [ ] ";
+ return pre + p.text;
+}
+
+editor::AiRange AiTake() {
+ editor::AiRange r;
+ if (!N) return r;
+ r.n = N;
+ r.all = !HasSel();
+ if (r.all) { r.a = 0; r.b = Count() - 1; } else SelParas(r.a, r.b);
+ int num = 0;
+ for (int i = r.a; i <= r.b; i++) {
+ const Para& p = P(i);
+ num = p.list == L_NUMBER ? num + 1 : 0;
+ std::wstring l = ParaMd(p, num);
+ if (p.kind == K_FILE) continue;
+ r.antes += l + L"\n";
+ }
+ while (!r.antes.empty() && r.antes.back() == L'\n') r.antes.pop_back();
+ return r;
+}
+
+static std::wstring SemMarcas(std::wstring t) { // **negrito**, __x__ e `código` viram texto puro
+ for (const wchar_t* m : { L"**", L"__", L"`" }) for (size_t i; (i = t.find(m)) != std::wstring::npos;) t.erase(i, wcslen(m));
+ return t;
+}
+
+bool AiReplace(const editor::AiRange& r, const std::wstring& md) {
+ if (!N || N != r.n || r.b >= Count()) return false;
+ { // a nota mudou enquanto a IA escrevia: não troca (o texto novo iria para o lugar errado)
+ editor::AiRange agora; agora.n = N; agora.a = r.a; agora.b = r.b;
+ int num = 0; std::wstring t;
+ for (int i = r.a; i <= r.b; i++) { const Para& p = P(i); num = p.list == L_NUMBER ? num + 1 : 0; if (p.kind != K_FILE) t += ParaMd(p, num) + L"\n"; }
+ while (!t.empty() && t.back() == L'\n') t.pop_back();
+ if (t != r.antes) return false;
+ }
+ std::vector<Para> novos;
+ std::wstring s = md;
+ // o modelo às vezes embrulha tudo num bloco ```
+ if (s.rfind(L"```", 0) == 0) { size_t q = s.find(L'\n'); s = q == std::wstring::npos ? L"" : s.substr(q + 1); }
+ if (s.size() >= 3 && s.compare(s.size() - 3, 3, L"```") == 0) s.resize(s.size() - 3);
+ size_t i = 0;
+ bool brancoAntes = false;
+ while (i <= s.size()) {
+ size_t f = s.find(L'\n', i); if (f == std::wstring::npos) f = s.size();
+ std::wstring l = s.substr(i, f - i);
+ i = f + 1;
+ if (!l.empty() && l.back() == L'\r') l.pop_back();
+ size_t ind = 0; while (ind < l.size() && (l[ind] == L' ' || l[ind] == L'\t')) ind++;
+ std::wstring t = l.substr(ind);
+ if (t.empty()) { brancoAntes = true; if (f >= s.size()) break; continue; }
+ Para p;
+ p.indent = (uint8_t)std::min<size_t>(ind / 2, 4);
+ if (t[0] == L'|') { // tabela; a linha de traços (|---|) some
+ bool tracos = t.find_first_not_of(L"|-: ") == std::wstring::npos;
+ if (tracos) continue;
+ std::wstring c = t.substr(1);
+ if (!c.empty() && c.back() == L'|') c.pop_back();
+ std::wstring cel, o;
+ for (size_t k = 0; k <= c.size(); k++) {
+ if (k == c.size() || c[k] == L'|') {
+ size_t x = cel.find_first_not_of(L' '), y = cel.find_last_not_of(L' ');
+ o += (x == std::wstring::npos ? L"" : cel.substr(x, y - x + 1));
+ if (k < c.size()) o += L'\t';
+ cel.clear();
+ } else cel += c[k];
+ }
+ p.kind = K_ROW; p.text = SemMarcas(o); p.indent = 0;
+ } else {
+ if (t.rfind(L"### ", 0) == 0) { p.style = S_SUBHEADING; t = t.substr(4); }
+ else if (t.rfind(L"## ", 0) == 0) { p.style = S_HEADING; t = t.substr(3); }
+ else if (t.rfind(L"# ", 0) == 0) { p.style = S_TITLE; t = t.substr(2); }
+ if (t.rfind(L"- [ ] ", 0) == 0 || t.rfind(L"* [ ] ", 0) == 0) { p.list = L_CHECK; t = t.substr(6); }
+ else if (t.rfind(L"- [x] ", 0) == 0 || t.rfind(L"- [X] ", 0) == 0) { p.list = L_CHECK; p.checked = true; t = t.substr(6); }
+ else if (t.rfind(L"- ", 0) == 0 || t.rfind(L"* ", 0) == 0 || t.rfind(L"• ", 0) == 0) { p.list = L_BULLET; t = t.substr(2); }
+ else {
+ size_t d = 0; while (d < t.size() && iswdigit(t[d])) d++;
+ if (d > 0 && d < 4 && d + 1 < t.size() && (t[d] == L'.' || t[d] == L')') && t[d + 1] == L' ') { p.list = L_NUMBER; t = t.substr(d + 2); }
+ }
+ p.text = SemMarcas(t);
+ if (p.list != L_NONE && p.style != S_BODY) p.style = S_BODY;
+ }
+ // um parágrafo em branco entre blocos de texto comum (como o modelo separa): fica um vazio na nota também
+ if (brancoAntes && !novos.empty() && p.list == L_NONE && p.kind == K_TEXT && novos.back().list == L_NONE && novos.back().kind == K_TEXT)
+ novos.push_back(Para{});
+ brancoAntes = false;
+ p.at.assign(p.text.size(), 0);
+ novos.push_back(std::move(p));
+ if (f >= s.size()) break;
+ }
+ if (novos.empty()) return false;
+ // a nota inteira: o primeiro parágrafo continua título (o nome da nota na lista)
+ if (r.all && r.a == 0 && P(0).style == S_TITLE && novos[0].kind == K_TEXT && novos[0].list == L_NONE) novos[0].style = S_TITLE;
+ // anexos dentro do trecho ficam (no fim do texto novo)
+ for (int k = r.a; k <= r.b; k++) if (P(k).kind == K_FILE) novos.push_back(P(k));
+ Checkpoint(3);
+ N->paras.erase(N->paras.begin() + r.a, N->paras.begin() + r.b + 1);
+ N->paras.insert(N->paras.begin() + r.a, novos.begin(), novos.end());
+ if (N->paras.empty()) N->paras.push_back(Para{});
+ // a seleção cobre o texto novo (como no Mac: dá para ver o que mudou e desfazer com Ctrl+Z)
+ int fim = r.a + (int)novos.size() - 1;
+ anchor = { r.a, 0 };
+ caret = { fim, (int)P(fim).text.size() };
+ Clamp();
+ Changed();
+ return true;
+}
+
+int CurrentStyle() { return N ? P(caret.p).style : S_BODY; }
+int CurrentList() { return N ? P(caret.p).list : L_NONE; }
+uint8_t CurrentAttrs() {
+ if (!N) return 0;
+ if (HasSel()) { Pos s = SelStart(); return s.o < (int)P(s.p).at.size() ? P(s.p).at[s.o] : 0; }
+ return AttrAtCaret();
+}
+
+void ApplyStyle(int style) {
+ if (!N) return;
+ Checkpoint(3);
+ int a, b; SelParas(a, b);
+ for (int i = a; i <= b; i++) { P(i).style = (uint8_t)style; if (style > S_SUBHEADING) P(i).collapsed = false; }
+ Changed();
+}
+
+void ToggleAttr(uint8_t flag) {
+ if (!N) return;
+ if (!HasSel()) { typing = AttrAtCaret() ^ flag; typingSet = true; return; }
+ Checkpoint(3);
+ Pos s = SelStart(), e = SelEnd();
+ bool all = true;
+ for (int i = s.p; i <= e.p; i++) {
+ int from = i == s.p ? s.o : 0, to = i == e.p ? e.o : (int)P(i).text.size();
+ for (int k = from; k < to; k++) if (!(P(i).at[k] & flag)) all = false;
+ }
+ for (int i = s.p; i <= e.p; i++) {
+ int from = i == s.p ? s.o : 0, to = i == e.p ? e.o : (int)P(i).text.size();
+ for (int k = from; k < to; k++) P(i).at[k] = all ? (P(i).at[k] & ~flag) : (P(i).at[k] | flag);
+ }
+ Changed();
+}
+
+void SetHighlight(int h) {
+ if (!N) return;
+ if (!HasSel()) { typing = WithHi(AttrAtCaret(), h); typingSet = true; return; }
+ Checkpoint(3);
+ Pos s = SelStart(), e = SelEnd();
+ for (int i = s.p; i <= e.p; i++) {
+ int from = i == s.p ? s.o : 0, to = i == e.p ? e.o : (int)P(i).text.size();
+ for (int k = from; k < to; k++) P(i).at[k] = WithHi(P(i).at[k], h);
+ }
+ Changed();
+}
+
+void ToggleList(int kind) {
+ if (!N) return;
+ Checkpoint(3);
+ int a, b; SelParas(a, b);
+ bool all = true;
+ for (int i = a; i <= b; i++) if (P(i).list != kind) all = false;
+ for (int i = a; i <= b; i++) {
+ if (P(i).kind != K_TEXT) continue;
+ P(i).list = all ? (uint8_t)L_NONE : (uint8_t)kind;
+ if (!all && P(i).style != S_MONO) P(i).style = P(i).style <= S_SUBHEADING && P(i).text.empty() ? (uint8_t)S_BODY : P(i).style;
+ P(i).checked = false;
+ }
+ Changed();
+}
+
+void Indent(int d) {
+ if (!N) return;
+ Checkpoint(3);
+ int a, b; SelParas(a, b);
+ for (int i = a; i <= b; i++) P(i).indent = (uint8_t)std::clamp(P(i).indent + d, 0, 8);
+ Changed();
+}
+
+void ToggleChecked() {
+ if (!N) return;
+ Checkpoint(3);
+ int a, b; SelParas(a, b);
+ for (int i = a; i <= b; i++) if (P(i).list == L_CHECK) P(i).checked = !P(i).checked;
+ Changed();
+}
+
+void OnChar(wchar_t c) {
+ if (!N || !focused) return;
+ if ((c == L'\r' || c == L'\n') && !HasSel() && (IsFile(caret.p) || IsRow(caret.p))) {
+ Checkpoint(3);
+ int i = caret.p;
+ if (IsFile(i)) { N->paras.insert(N->paras.begin() + i + 1, Para{}); caret = anchor = { i + 1, 0 }; }
+ else {
+ Para& r = P(i);
+ bool empty = r.text.find_first_not_of(L'\t') == std::wstring::npos;
+ if (empty && !IsRow(i + 1) && IsRow(i - 1)) { r.kind = K_TEXT; r.text.clear(); r.at.clear(); caret = anchor = { i, 0 }; } // sai da tabela
+ else {
+ Para nr; nr.kind = K_ROW; nr.text.assign(TableCols(i) - 1, L'\t'); nr.at.assign(nr.text.size(), 0);
+ N->paras.insert(N->paras.begin() + i + 1, nr);
+ caret = anchor = { i + 1, 0 };
+ }
+ }
+ typingSet = false;
+ Changed();
+ return;
+ }
+ if (c == L'\r' || c == L'\n') {
+ Checkpoint(3);
+ DeleteSel();
+ Para& p = P(caret.p);
+ if (p.list != L_NONE && p.text.empty()) { // Enter na linha vazia da lista: sai da lista (ou volta um nível)
+ if (p.indent > 0) p.indent--; else p.list = L_NONE;
+ } else if (caret.o == 0 && !p.text.empty()) { // no começo: abre uma linha em cima com a mesma formatação
+ Para np = p; np.text.clear(); np.at.clear(); np.checked = false; np.collapsed = false;
+ N->paras.insert(N->paras.begin() + caret.p, np);
+ caret = anchor = { caret.p + 1, 0 };
+ } else SplitPara();
+ typingSet = false;
+ Changed();
+ return;
+ }
+ if (c == L'\t') return; // tratado em OnKey
+ if (c < 32 || c == 127) return;
+ Checkpoint(1);
+ if (!HasSel() && IsFile(caret.p)) { // digitou com o cursor no anexo: o texto vai num parágrafo novo depois dele
+ Checkpoint(3);
+ N->paras.insert(N->paras.begin() + caret.p + 1, Para{});
+ caret = anchor = { caret.p + 1, 0 };
+ }
+ uint8_t at = AttrAtCaret();
+ DeleteSel();
+ Para& p = P(caret.p);
+ // atalhos de digitação: "* " / "- " / "1. " viram listas, como no Mac
+ if (c == L' ' && p.list == L_NONE && caret.o == (int)p.text.size() && p.style != S_MONO) {
+ int kind = -1;
+ if (p.text == L"*" || p.text == L"•") kind = L_BULLET;
+ else if (p.text == L"-" || p.text == L"–") kind = L_DASH;
+ else if (p.text == L"1." || p.text == L"1)") kind = L_NUMBER;
+ else if (p.text == L"[]" || p.text == L"[ ]") kind = L_CHECK;
+ if (kind >= 0 && p.kind == K_TEXT) {
+ Checkpoint(3);
+ p.text.clear(); p.at.clear(); p.list = (uint8_t)kind; caret.o = 0; anchor = caret;
+ if (p.style <= S_SUBHEADING) p.style = S_BODY;
+ Changed();
+ return;
+ }
+ }
+ InsertPlain(std::wstring(1, c), at);
+ typing = at; // continua com o mesmo atributo
+ Changed();
+}
+
+bool OnKey(UINT vk) {
+ if (!N || !focused) return false;
+ bool ctrl = GetKeyState(VK_CONTROL) < 0, shift = GetKeyState(VK_SHIFT) < 0;
+ blinkOn = true;
+ auto move = [&](Pos q, bool keepX = false) {
+ caret = q;
+ if (!shift) anchor = q;
+ if (!keepX) desiredX = -1;
+ typingSet = false;
+ if (q.p < (int)pl.size() && pl[q.p].hidden) UncollapseAround(q.p);
+ wantReveal = true;
+ };
+ // atalhos de formatação (Ctrl no lugar do Cmd)
+ if (ctrl && shift) {
+ switch (vk) {
+ case 'T': ApplyStyle(S_TITLE); return true;
+ case 'H': ApplyStyle(S_HEADING); return true;
+ case 'J': ApplyStyle(S_SUBHEADING); return true;
+ case 'B': ApplyStyle(S_BODY); return true;
+ case 'M': ApplyStyle(S_MONO); return true;
+ case '7': ToggleList(L_BULLET); return true;
+ case '8': ToggleList(L_DASH); return true;
+ case '9': ToggleList(L_NUMBER); return true;
+ case 'L': ToggleList(L_CHECK); return true;
+ case 'U': ToggleChecked(); return true;
+ case 'X': ToggleAttr(A_STRIKE); return true;
+ case 'Z': Redo(); return true;
+ }
+ }
+ if (ctrl && !shift) {
+ switch (vk) {
+ case 'B': ToggleAttr(A_BOLD); return true;
+ case 'I': ToggleAttr(A_ITALIC); return true;
+ case 'U': ToggleAttr(A_UNDER); return true;
+ case 'A': SelectAll(); return true;
+ case 'C': Copy(false); return true;
+ case 'X': Copy(true); return true;
+ case 'V': Paste(); return true;
+ case 'Z': Undo(); return true;
+ case 'Y': Redo(); return true;
+ case VK_OEM_6: Indent(1); return true; // Ctrl+]
+ case VK_OEM_4: Indent(-1); return true; // Ctrl+[
+ }
+ }
+ Para& p = P(caret.p);
+ auto jump = [&](Pos q) { caret = anchor = q; desiredX = -1; typingSet = false; wantReveal = true; };
+ auto eraseFile = [&](int i) { // apaga o anexo inteiro (fica pelo menos um parágrafo)
+ Checkpoint(3);
+ if (Count() == 1) { P(0) = Para{}; caret = anchor = { 0, 0 }; }
+ else { N->paras.erase(N->paras.begin() + i); int k = std::min(i, Count() - 1); caret = anchor = { k, k < i ? (int)P(k).text.size() : 0 }; }
+ Changed();
+ };
+ if (!HasSel() && !ctrl) {
+ // tabela: Tab/Shift+Tab de célula em célula (Tab na última célula abre uma linha nova)
+ if (vk == VK_TAB && IsRow(caret.p)) {
+ const std::wstring& t = p.text;
+ if (!shift) {
+ size_t k = t.find(L'\t', caret.o);
+ if (k != std::wstring::npos) jump({ caret.p, (int)k + 1 });
+ else if (IsRow(caret.p + 1)) jump({ caret.p + 1, 0 });
+ else {
+ Checkpoint(3);
+ Para nr; nr.kind = K_ROW; nr.text.assign(TableCols(caret.p) - 1, L'\t'); nr.at.assign(nr.text.size(), 0);
+ N->paras.insert(N->paras.begin() + caret.p + 1, nr);
+ jump({ caret.p + 1, 0 });
+ Changed();
+ }
+ } else {
+ int s0 = caret.o == 0 ? 0 : (int)(t.rfind(L'\t', caret.o - 1) == std::wstring::npos ? 0 : t.rfind(L'\t', caret.o - 1) + 1);
+ if (s0 > 0) { size_t k = s0 >= 2 ? t.rfind(L'\t', s0 - 2) : std::wstring::npos; jump({ caret.p, k == std::wstring::npos ? 0 : (int)k + 1 }); }
+ else if (IsRow(caret.p - 1)) { const std::wstring& u = P(caret.p - 1).text; size_t k = u.rfind(L'\t'); jump({ caret.p - 1, k == std::wstring::npos ? 0 : (int)k + 1 }); }
+ }
+ return true;
+ }
+ if (vk == VK_BACK || vk == VK_DELETE) {
+ if (IsFile(caret.p)) { eraseFile(caret.p); return true; }
+ if (IsRow(caret.p)) {
+ const std::wstring& t = p.text;
+ if (vk == VK_BACK && caret.o > 0 && t[caret.o - 1] == L'\t') { jump({ caret.p, caret.o - 1 }); return true; } // não junta células
+ if (vk == VK_DELETE && (caret.o >= (int)t.size() || t[caret.o] == L'\t')) return true;
+ if (vk == VK_BACK && caret.o == 0) {
+ if (t.find_first_not_of(L'\t') == std::wstring::npos) { // linha vazia: some (a última vira texto)
+ Checkpoint(3);
+ if (IsRow(caret.p - 1) || IsRow(caret.p + 1)) {
+ N->paras.erase(N->paras.begin() + caret.p);
+ int k = std::max(0, caret.p - 1);
+ caret = anchor = { k, (int)P(k).text.size() };
+ } else { p.kind = K_TEXT; p.text.clear(); p.at.clear(); }
+ Changed();
+ }
+ return true;
+ }
+ }
+ if (vk == VK_BACK && caret.o == 0 && caret.p > 0) {
+ int k = PrevVisible(caret.p);
+ if (IsFile(k)) { eraseFile(k); return true; }
+ if (IsRow(k)) { jump({ k, (int)P(k).text.size() }); return true; }
+ }
+ if (vk == VK_DELETE && caret.o == (int)p.text.size()) {
+ int k = NextVisible(caret.p);
+ if (IsFile(k)) { int keep = caret.p; eraseFile(k); caret = anchor = { keep, (int)P(keep).text.size() }; return true; }
+ if (IsRow(k)) return true;
+ }
+ }
+ }
+ switch (vk) {
+ case VK_LEFT:
+ if (!shift && HasSel()) { move(SelStart()); return true; }
+ if (caret.o > 0) move({ caret.p, ctrl ? PrevWord(p.text, caret.o) : caret.o - 1 });
+ else { int k = PrevVisible(caret.p); if (k >= 0) move({ k, (int)P(k).text.size() }); }
+ return true;
+ case VK_RIGHT:
+ if (!shift && HasSel()) { move(SelEnd()); return true; }
+ if (caret.o < (int)p.text.size()) move({ caret.p, ctrl ? NextWord(p.text, caret.o) : caret.o + 1 });
+ else { int k = NextVisible(caret.p); if (k >= 0) move({ k, 0 }); }
+ return true;
+ case VK_UP: case VK_DOWN: {
+ if (pl.size() != (size_t)Count()) return true;
+ if (ctrl) { move(vk == VK_UP ? Pos{ 0, 0 } : Pos{ Count() - 1, (int)P(Count() - 1).text.size() }); return true; }
+ D2D1_RECT_F c = CaretRectAt(caret);
+ if (desiredX < 0) desiredX = c.left;
+ float y = vk == VK_UP ? c.top - 2 : c.bottom + 2;
+ if (vk == VK_UP && caret.p == 0 && c.top <= pl[0].y + 1) { move({ 0, 0 }, true); return true; }
+ if (vk == VK_DOWN && y >= contentH - 40) { move({ Count() - 1, (int)P(Count() - 1).text.size() }, true); return true; }
+ // pula o espaço entre parágrafos
+ Pos q = HitContent(desiredX, y);
+ if (Same(q, caret)) q = HitContent(desiredX, vk == VK_UP ? y - 6 : y + 6);
+ move(q, true);
+ return true;
+ }
+ case VK_HOME: case VK_END: {
+ if (ctrl) { move(vk == VK_HOME ? Pos{ 0, 0 } : Pos{ Count() - 1, (int)P(Count() - 1).text.size() }); return true; }
+ if (pl.size() != (size_t)Count() || !pl[caret.p].tl) return true;
+ D2D1_RECT_F c = CaretRectAt(caret);
+ BOOL tr, in; DWRITE_HIT_TEST_METRICS m;
+ pl[caret.p].tl->HitTestPoint(vk == VK_HOME ? -1000.f : 100000.f, (c.top + c.bottom) / 2 - pl[caret.p].y, &tr, &in, &m);
+ int o = (int)m.textPosition + (tr ? (int)m.length : 0);
+ o = std::min(o, (int)p.text.size());
+ if (vk == VK_END && o > 0 && o < (int)p.text.size() && p.text[o - 1] == L' ') o--; // fim da linha quebrada
+ move({ caret.p, o });
+ return true;
+ }
+ case VK_PRIOR: case VK_NEXT: {
+ float h = area.bottom - area.top;
+ D2D1_RECT_F c = CaretRectAt(caret);
+ scrollY += vk == VK_PRIOR ? -h : h;
+ move(HitContent(c.left, (c.top + c.bottom) / 2 + (vk == VK_PRIOR ? -h : h)));
+ return true;
+ }
+ case VK_BACK:
+ if (HasSel()) { Checkpoint(2); DeleteSel(); Changed(); return true; }
+ if (caret.o == 0) {
+ Checkpoint(3);
+ if (p.list != L_NONE) p.list = L_NONE;
+ else if (p.indent > 0) p.indent--;
+ else if (caret.p > 0) {
+ int k = PrevVisible(caret.p);
+ if (k < 0) k = caret.p - 1;
+ if (P(k).text.empty() && !p.text.empty()) { // linha vazia em cima: some ela, este fica como está
+ N->paras.erase(N->paras.begin() + k);
+ caret = anchor = { k, 0 };
+ } else {
+ for (int z = k; z < caret.p; z++) P(z).collapsed = false;
+ Pos a{ k, (int)P(k).text.size() };
+ DeleteRange(a, { caret.p, 0 });
+ }
+ } else if (p.style != S_BODY && p.text.empty() && Count() > 1) p.style = S_BODY;
+ Changed();
+ return true;
+ }
+ Checkpoint(2);
+ DeleteRange({ caret.p, ctrl ? PrevWord(p.text, caret.o) : caret.o - 1 }, caret);
+ Changed();
+ return true;
+ case VK_DELETE:
+ if (HasSel()) { Checkpoint(2); DeleteSel(); Changed(); return true; }
+ Checkpoint(2);
+ if (caret.o < (int)p.text.size()) DeleteRange(caret, { caret.p, ctrl ? NextWord(p.text, caret.o) : caret.o + 1 });
+ else if (caret.p + 1 < Count()) { P(caret.p).collapsed = false; DeleteRange(caret, { caret.p + 1, 0 }); }
+ Changed();
+ return true;
+ case VK_TAB: {
+ int a, b; SelParas(a, b);
+ if (p.list != L_NONE || a != b) { Indent(shift ? -1 : 1); return true; }
+ if (!shift) { Checkpoint(1); uint8_t at = AttrAtCaret(); DeleteSel(); InsertPlain(L"\t", at); Changed(); }
+ return true;
+ }
+ case VK_ESCAPE:
+ if (HasSel()) { anchor = caret; return true; }
+ return false;
+ }
+ return false;
+}
+
+} // namespace editor
diff --git a/src/notas/main.cpp b/src/notas/main.cpp
index 2c1b152..00a2a80 100644
--- a/src/notas/main.cpp
+++ b/src/notas/main.cpp
@@ -22,7 +22,10 @@
#include "../comum/ampliacao.h" // botão verde com a animação do ampliar do Shell
#include "../comum/idioma.h"
#include "../comum/semaforo.h"
-#include "../comum/leopard.h" // tema Mac OS X Leopard: a barra de metal e a barra lateral azul-acinzentada
+#include "../comum/leopard.h"
+#include "../comum/siri.h" // Ferramentas de Escrita com IA: o serviço e a chave da Siri
+#include "../comum/ajustes_arquivo.h"
+#include <thread> // tema Mac OS X Leopard: a barra de metal e a barra lateral azul-acinzentada
#pragma comment(lib, "imm32.lib")
#pragma comment(lib, "windowscodecs.lib")
@@ -45,7 +48,8 @@ namespace {
// medidas (pt), da referência do Notas no Sequoia
const float TOOLBAR_H = 52, TOOL_CY = 26, SIDE_ROW_H = 28, SIDE_HDR_H = 30;
const float SIDE_MIN = 160, SIDE_MAX = 340, LIST_MIN = 200, LIST_MAX = 480, EDITOR_MIN = 300; // lista: 200 (era 220, issue #8)
-const UINT_PTR T_BLINK = 1, T_SAVE = 2, T_FRONT = 3;
+const UINT_PTR T_BLINK = 1, T_SAVE = 2, T_FRONT = 3, T_IA = 4;
+const UINT WM_APP_IA = WM_APP + 8; // a thread da IA terminou (lParam = new IaFeito)
const UINT WM_APP_TRAZER = WM_APP + 7; // segunda cópia aberta (Launchpad, Spotlight, Dock): vem para a frente
HWND g_hwnd;
@@ -77,7 +81,11 @@ Note* g_dragNote; bool g_dragging; POINT g_dragFrom; D2D1_POINT_2F g_dragAt; std
int g_divDrag; // 1 borda da barra lateral, 2 borda da lista
// folha de confirmação
-struct Sheet { bool on = false; std::wstring title, msg, ok; std::function<void()> act; } g_sheet;
+struct Sheet { bool on = false; std::wstring title, msg, ok; std::function<void()> act; bool campo = false, aviso = false; } g_sheet; // campo: com o g_iaCampo; aviso: só OK
+TextField g_iaCampo; // "Pedir à IA…": o que a pessoa quer que a IA faça
+// a IA escrevendo (o aviso embaixo do editor)
+struct Ia { bool on = false; ULONGLONG t0 = 0; std::wstring rotulo; } g_ia;
+struct IaFeito { editor::AiRange r; siri::Gerado g; bool juntar = false; };
D2D1_RECT_F g_sheetOk, g_sheetCancel;
// folha de desenho (botão de marcação): uma tela branca para rabiscar com o mouse ou a caneta; "Inserir" grava um PNG
@@ -119,6 +127,7 @@ float ToolStart() { return g_sideHidden ? 128.f : SideW(); } // onde começam o
// ---- cores
struct Pal { D2D1_COLOR_F side, list, editor, text, text2, text3, line, sel, selFocus, icon, iconOff, hover, field; };
+void DrawIa(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, const Pal& pal); // Ferramentas de Escrita com IA (mais abaixo)
Pal ColorsNormal();
Pal Colors() {
// issue #8 (macOS 26/27): o acrílico do Windows sozinho deixava a lateral num cinza turvo (e chapado com a janela
@@ -889,21 +898,39 @@ void DrawSheet(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, const Pal& pal)
gfx::dw->CreateTextLayout(g_sheet.msg.c_str(), (UINT32)g_sheet.msg.size(), g_f11, W - 40, 400, &ml);
float mh = 0;
if (ml) { ml->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER); DWRITE_TEXT_METRICS m{}; ml->GetMetrics(&m); mh = m.height; }
- float H = 20 + 20 + 8 + mh + 20 + 28 + 16;
+ if (g_sheet.campo) W = 360, x = (c.width - W) / 2;
+ float campoH = g_sheet.campo ? 38.f : 0.f;
+ float H = 20 + 20 + 8 + mh + 20 + campoH + 28 + 16;
D2D1_RECT_F r{ x, y, x + W, y + H };
for (int k = 6; k >= 1; k--) { br->SetColor(D2D1::ColorF(0, 0, 0, 0.04f)); dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(x - k, y - k + 4, x + W + k, y + H + k + 6), 14.f + k, 14.f + k), br); }
br->SetColor(g_dark ? D2D1::ColorF(0.20f, 0.20f, 0.21f) : D2D1::ColorF(0.96f, 0.96f, 0.96f));
dc->FillRoundedRectangle(D2D1::RoundedRect(r, 13, 13), br);
Text(dc, br, g_sheet.title, g_f13c, D2D1::RectF(x + 16, y + 20, x + W - 16, y + 40), pal.text);
if (ml) { br->SetColor(pal.text); dc->DrawTextLayout({ x + 20, y + 46 }, ml, br); ml->Release(); }
+ if (g_sheet.campo) { // o campo do pedido
+ D2D1_RECT_F fr{ x + 16, y + 46 + mh + 14, x + W - 16, y + 46 + mh + 14 + 28 };
+ br->SetColor(g_dark ? D2D1::ColorF(0, 0, 0, 0.25f) : D2D1::ColorF(1, 1, 1));
+ dc->FillRoundedRectangle(D2D1::RoundedRect(fr, 7, 7), br);
+ auto a = Accent(); br->SetColor(D2D1::ColorF(a.r, a.g, a.b, 0.6f));
+ dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(fr.left - 1, fr.top - 1, fr.right + 1, fr.bottom + 1), 8, 8), br, 2);
+ D2D1_RECT_F tr{ fr.left + 9, fr.top, fr.right - 9, fr.bottom };
+ if (g_iaCampo.text.empty()) Text(dc, br, Tr(L"Ex.: organize em tópicos, traduza para o inglês…"), g_f13, tr, pal.text3);
+ ID2D1SolidColorBrush *tb = nullptr, *sb = nullptr, *cb = nullptr;
+ dc->CreateSolidColorBrush(pal.text, &tb); dc->CreateSolidColorBrush(D2D1::ColorF(a.r, a.g, a.b, 0.4f), &sb); dc->CreateSolidColorBrush(a, &cb);
+ if (tb && sb && cb) g_iaCampo.Draw(dc, g_f13, tr, tb, sb, cb, true, false);
+ if (tb) tb->Release(); if (sb) sb->Release(); if (cb) cb->Release();
+ }
float by = y + H - 16 - 28, bw = (W - 44) / 2;
- g_sheetCancel = { x + 16, by, x + 16 + bw, by + 28 };
- g_sheetOk = { x + W - 16 - bw, by, x + W - 16, by + 28 };
- br->SetColor(g_dark ? D2D1::ColorF(1, 1, 1, 0.16f) : D2D1::ColorF(0, 0, 0, 0.07f));
- dc->FillRoundedRectangle(D2D1::RoundedRect(g_sheetCancel, 7, 7), br);
- br->SetColor(D2D1::ColorF(1.0f, 0.27f, 0.23f));
+ g_sheetCancel = g_sheet.aviso ? D2D1_RECT_F{} : D2D1_RECT_F{ x + 16, by, x + 16 + bw, by + 28 };
+ g_sheetOk = g_sheet.aviso ? D2D1_RECT_F{ x + (W - bw) / 2, by, x + (W + bw) / 2, by + 28 } : D2D1_RECT_F{ x + W - 16 - bw, by, x + W - 16, by + 28 };
+ if (!g_sheet.aviso) {
+ br->SetColor(g_dark ? D2D1::ColorF(1, 1, 1, 0.16f) : D2D1::ColorF(0, 0, 0, 0.07f));
+ dc->FillRoundedRectangle(D2D1::RoundedRect(g_sheetCancel, 7, 7), br);
+ Text(dc, br, Tr(L"Cancelar"), g_f13c, g_sheetCancel, pal.text);
+ }
+ // apagar: vermelho; os outros (pedir à IA, avisos): a cor de destaque do sistema
+ br->SetColor(g_sheet.campo || g_sheet.aviso ? D2D1::ColorF(0.0f, 0.48f, 1.0f) : D2D1::ColorF(1.0f, 0.27f, 0.23f));
dc->FillRoundedRectangle(D2D1::RoundedRect(g_sheetOk, 7, 7), br);
- Text(dc, br, Tr(L"Cancelar"), g_f13c, g_sheetCancel, pal.text);
Text(dc, br, g_sheet.ok, g_f13c, g_sheetOk, D2D1::ColorF(1, 1, 1));
}
@@ -967,6 +994,7 @@ void Render(ID2D1DeviceContext* dc) {
DrawToolbarButtons(dc, br, pal);
DrawFormatPanel(dc, br, pal);
DrawDragGhost(dc, br, pal);
+ DrawIa(dc, br, pal);
DrawSheet(dc, br, pal);
DrawSketch(dc, br, pal);
br->Release();
@@ -1346,15 +1374,169 @@ void AttachCmd() {
}
// Ferramentas de Escrita: sem o Apple Intelligence, só o que dá para fazer aqui mesmo, sem IA e sem internet
+// ---- Ferramentas de Escrita com IA (como as do Apple Intelligence): o pedido vai para o serviço escolhido para a Siri
+// (Ajustes do Sistema > Apple Intelligence e Siri), com a chave dela, numa thread. O resultado troca a seleção (ou a nota
+// inteira, sem seleção) e fica selecionado; Ctrl+Z desfaz. Resumo e pontos-chave entram depois do texto, sem apagá-lo.
+std::wstring AjusteDaSiri(const wchar_t* k, const wchar_t* padrao) {
+ wchar_t* p = nullptr; std::wstring dir;
+ if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) { dir = p; CoTaskMemFree(p); }
+ std::map<std::wstring, std::wstring> m;
+ ajarq::Ler(dir + L"\\Shell\\ajustes.txt", m);
+ auto it = m.find(k);
+ return it == m.end() ? padrao : it->second;
+}
+int ServicoDaIa() {
+ int p = _wtoi(AjusteDaSiri(L"siri_provedor", L"0").c_str());
+ return p > 0 && p < (int)siri::Provedores().size() ? p : 0;
+}
+
+void DrawIa(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, const Pal& pal) {
+ if (!g_ia.on || !editor::Current()) return;
+ auto c = ClientDip();
+ double t = (double)(GetTickCount64() - g_ia.t0);
+ std::wstring txt = g_ia.rotulo;
+ float tw = TextW(g_f13, txt) + 56, x0 = EdL() + (c.width - EdL() - tw) / 2, y0 = c.height - 54;
+ D2D1_RECT_F r{ x0, y0, x0 + tw, y0 + 34 };
+ // o brilho colorido em volta da cápsula (as cores do Apple Intelligence, girando)
+ D2D1_GRADIENT_STOP gs[5] = { { 0, D2D1::ColorF(1.f, 0.62f, 0.10f) }, { 0.3f, D2D1::ColorF(1.f, 0.24f, 0.42f) },
+ { 0.55f, D2D1::ColorF(0.74f, 0.33f, 0.95f) }, { 0.8f, D2D1::ColorF(0.40f, 0.45f, 1.f) }, { 1, D2D1::ColorF(0.15f, 0.55f, 1.f) } };
+ ID2D1GradientStopCollection* sc = nullptr;
+ ID2D1LinearGradientBrush* lg = nullptr;
+ float a = (float)(t / 900.0);
+ D2D1_POINT_2F mid{ (r.left + r.right) / 2, (r.top + r.bottom) / 2 };
+ if (SUCCEEDED(dc->CreateGradientStopCollection(gs, 5, &sc)))
+ dc->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ mid.x + std::cos(a) * tw / 2, mid.y + std::sin(a) * 17 }, { mid.x - std::cos(a) * tw / 2, mid.y - std::sin(a) * 17 }), sc, &lg);
+ for (int k = 5; k >= 1; k--) {
+ br->SetColor(D2D1::ColorF(0, 0, 0, g_dark ? 0.10f : 0.035f));
+ dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(r.left - k, r.top - k + 3, r.right + k, r.bottom + k + 3), 17.f + k, 17.f + k), br);
+ }
+ br->SetColor(g_dark ? D2D1::ColorF(0.17f, 0.17f, 0.18f) : D2D1::ColorF(1, 1, 1));
+ dc->FillRoundedRectangle(D2D1::RoundedRect(r, 17, 17), br);
+ if (lg) {
+ float pulso = 0.75f + 0.25f * (float)std::sin(t / 320.0);
+ lg->SetOpacity(pulso);
+ dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(r.left + 0.75f, r.top + 0.75f, r.right - 0.75f, r.bottom - 0.75f), 16.25f, 16.25f), lg, 1.5f);
+ lg->SetOpacity(1);
+ if (!simbolo::Draw(dc, L"apple.intelligence", D2D1::RectF(r.left + 12, mid.y - 8, r.left + 28, mid.y + 8), lg))
+ dc->FillEllipse(D2D1::Ellipse({ r.left + 20, mid.y }, 6, 6), lg);
+ lg->Release();
+ }
+ if (sc) sc->Release();
+ Text(dc, br, txt, g_f13, D2D1::RectF(r.left + 36, r.top, r.right - 10, r.bottom), pal.text2);
+}
+
+void PedeIa(const std::wstring& rotulo, const std::wstring& tarefa, bool juntar) {
+ if (g_ia.on || !editor::Current()) return;
+ int p = ServicoDaIa();
+ if (!p) return;
+ editor::AiRange r = editor::AiTake();
+ if (r.antes.find_first_not_of(L" \n\t") == std::wstring::npos) {
+ g_sheet = { true, Tr(L"Ferramentas de Escrita"), Tr(L"Escreva algo na nota (ou selecione um trecho) antes de usar as Ferramentas de Escrita."), L"OK", nullptr, false, true };
+ Invalidate();
+ return;
+ }
+ std::wstring modelo = AjusteDaSiri(L"siri_modelo", L"");
+ g_ia = { true, GetTickCount64(), rotulo };
+ SetTimer(g_hwnd, T_IA, 33, nullptr);
+ Invalidate();
+ Log(L"escrita com IA: %ls (%ls, %zu letras%ls)", rotulo.c_str(), siri::Provedores()[p].nome, r.antes.size(), r.all ? L", a nota inteira" : L"");
+ HWND h = g_hwnd;
+ std::thread([h, p, modelo, r, tarefa, juntar] {
+ const std::wstring sistema =
+ L"You are the Writing Tools of a notes app. You receive part of a note written in simple Markdown "
+ L"(# title, ## heading, ### subheading, - bullet list, 1. numbered list, - [ ] checklist, | table | rows). "
+ L"Do what is asked and reply ONLY with the resulting text, in the same simple Markdown and in the same language "
+ L"as the note unless the request says otherwise. No explanations, no preamble, no code fences, no bold or italics.";
+ auto* f = new IaFeito{ r, siri::Gera(p, modelo, sistema, tarefa + L"\n\nText:\n" + r.antes), juntar };
+ if (!PostMessageW(h, WM_APP_IA, 0, (LPARAM)f)) delete f;
+ }).detach();
+}
+
+void IaPronta(IaFeito* f) {
+ std::unique_ptr<IaFeito> dono(f);
+ KillTimer(g_hwnd, T_IA);
+ g_ia.on = false;
+ auto& g = f->g;
+ std::wstring erro;
+ if (g.erro == 1) erro = Tr(L"Escolha um serviço de IA em Ajustes do Sistema > Apple Intelligence e Siri.");
+ else if (g.erro == 2) erro = Tr(L"Falta a chave da API. Cole a chave em Ajustes do Sistema > Apple Intelligence e Siri.");
+ else if (g.erro == 3) erro = Tr(L"Não deu para falar com o serviço. Confira a internet.");
+ else if (g.erro == 5) erro = Tr(L"O app não respondeu. Ele está instalado e com a conta entrada?") + std::wstring(L" (") + g.msg + L")";
+ else if (g.erro) erro = std::wstring(Tr(L"O serviço recusou o pedido:")) + L" " + g.msg;
+ std::wstring t = g.texto;
+ while (!t.empty() && iswspace(t.back())) t.pop_back();
+ size_t s0 = t.find_first_not_of(L" \r\n\t"); t = s0 == std::wstring::npos ? L"" : t.substr(s0);
+ if (erro.empty() && t.empty()) erro = Tr(L"O serviço respondeu sem texto.");
+ if (erro.empty()) {
+ std::wstring md = f->juntar ? f->r.antes + L"\n\n" + t : t;
+ if (!editor::AiReplace(f->r, md)) erro = Tr(L"A nota mudou enquanto a IA escrevia. Tente de novo.");
+ else { Log(L"escrita com IA: pronto (%zu letras)", t.size()); FocusEditor(); }
+ }
+ if (!erro.empty()) {
+ Log(L"escrita com IA: %ls", erro.c_str());
+ g_sheet = { true, Tr(L"Ferramentas de Escrita"), erro, L"OK", nullptr, false, true };
+ }
+ Invalidate();
+}
+
+void PedirIaLivre() { // "Pedir à IA…": a pessoa escreve o que quer
+ g_iaCampo.SetText(L"", false);
+ g_sheet = { true, Tr(L"Pedir à IA"), Tr(L"Descreva o que fazer com o texto selecionado (ou com a nota inteira)."), Tr(L"Enviar"), [] {
+ std::wstring q = g_iaCampo.text;
+ if (q.find_first_not_of(L' ') == std::wstring::npos) return;
+ PedeIa(Tr(L"Escrevendo…"), L"Request from the user: " + q, false);
+ }, true, false };
+ Invalidate();
+}
+
void WritingMenu() {
if (!editor::Current()) return;
+ if (g_ia.on) return; // a IA já está escrevendo
+ if (int p = ServicoDaIa()) { // com um serviço de IA escolhido: as Ferramentas de Escrita do Apple Intelligence
+ auto r = g_btn[B_WRITING].r;
+ std::wstring titulo = std::wstring(Tr(L"Ferramentas de Escrita")) + L" (" + siri::Provedores()[p].nome + L")";
+ std::vector<Item> items = { I(titulo.c_str(), 0, true), Sep(),
+ I(Tr(L"Revisar"), 101), I(Tr(L"Reescrever"), 102), Sep(),
+ I(Tr(L"Amigável"), 103), I(Tr(L"Profissional"), 104), I(Tr(L"Conciso"), 105), Sep(),
+ I(Tr(L"Resumo"), 106), I(Tr(L"Pontos-chave"), 107), I(Tr(L"Lista"), 108), I(Tr(L"Tabela"), 109), Sep(),
+ I(Tr(L"Pedir à IA…"), 110), Sep() };
+ Item local = I(Tr(L"No computador, sem IA"), 0);
+ local.sub = { I(Tr(L"Revisar"), 1), Sep(), I(Tr(L"Converter em Lista"), 2), I(Tr(L"Converter em Tabela"), 3), Sep(),
+ I(Tr(L"MAIÚSCULAS"), 4), I(Tr(L"minúsculas"), 5), I(Tr(L"Iniciais Maiúsculas"), 6) };
+ items.push_back(local);
+ int id = ctxmenu::ShowItems(g_hwnd, ScreenPt(r.left, r.bottom + 4), items);
+ const int kinds[7] = { -1, editor::W_PROOF, editor::W_LIST, editor::W_TABLE, editor::W_UPPER, editor::W_LOWER, editor::W_TITLE };
+ if (id >= 1 && id <= 6) { bool ch = editor::Transform(kinds[id]); Log(L"escrita %d: %ls", id, ch ? L"mudou" : L"nada a mudar"); FocusEditor(); return; }
+ struct { int id; const wchar_t* rot; const wchar_t* tarefa; bool juntar; } t[] = {
+ { 101, L"Revisando…", L"Proofread it: fix spelling, grammar and punctuation. Keep the wording, meaning and formatting.", false },
+ { 102, L"Reescrevendo…", L"Rewrite it so it reads better, keeping the meaning and the formatting.", false },
+ { 103, L"Reescrevendo…", L"Rewrite it in a friendlier, warmer tone, keeping the meaning and the formatting.", false },
+ { 104, L"Reescrevendo…", L"Rewrite it in a more professional tone, keeping the meaning and the formatting.", false },
+ { 105, L"Reescrevendo…", L"Make it more concise, keeping the important information and the formatting.", false },
+ { 106, L"Resumindo…", L"Write a short summary of it as one paragraph, starting with a '## Summary' heading translated to the note's language.", true },
+ { 107, L"Resumindo…", L"List its key points as a short bulleted list, starting with a '## Key Points' heading translated to the note's language.", true },
+ { 108, L"Organizando…", L"Organize it as a clear bulleted list (use nested items where it helps).", false },
+ { 109, L"Organizando…", L"Organize the information into a table (Markdown table with a header row).", false },
+ };
+ for (auto& x : t) if (x.id == id) { PedeIa(Tr(x.rot), x.tarefa, x.juntar); return; }
+ if (id == 110) { PedirIaLivre(); return; }
+ FocusEditor();
+ return;
+ }
auto r = g_btn[B_WRITING].r;
+ // sem serviço de IA: as transformações no computador, e o caminho para ligar a IA
std::vector<Item> items = { I(Tr(L"Ferramentas de Escrita (no computador, sem IA)"), 0, true), Sep(), I(Tr(L"Revisar"), 1), Sep(),
I(Tr(L"Converter em Lista"), 2), I(Tr(L"Converter em Tabela"), 3), Sep(),
- I(Tr(L"MAIÚSCULAS"), 4), I(Tr(L"minúsculas"), 5), I(Tr(L"Iniciais Maiúsculas"), 6) };
+ I(Tr(L"MAIÚSCULAS"), 4), I(Tr(L"minúsculas"), 5), I(Tr(L"Iniciais Maiúsculas"), 6), Sep(),
+ I(Tr(L"Usar IA: escolha um serviço em Ajustes do Sistema > Apple Intelligence e Siri"), 20) };
int id = ctxmenu::ShowItems(g_hwnd, ScreenPt(r.left, r.bottom + 4), items);
const int kinds[7] = { -1, editor::W_PROOF, editor::W_LIST, editor::W_TABLE, editor::W_UPPER, editor::W_LOWER, editor::W_TITLE };
if (id >= 1 && id <= 6) { bool ch = editor::Transform(kinds[id]); Log(L"escrita %d: %ls", id, ch ? L"mudou" : L"nada a mudar"); }
+ if (id == 20) { // os Ajustes do Sistema na página Apple Intelligence e Siri (ao lado deste exe)
+ wchar_t exe[MAX_PATH]; GetModuleFileNameW(nullptr, exe, MAX_PATH);
+ std::wstring aj = exe; aj = aj.substr(0, aj.find_last_of(L'\\')) + L"\\WacOSSettings.exe";
+ ShellExecuteW(nullptr, L"open", aj.c_str(), L"--pagina=inteligencia", nullptr, SW_SHOWNORMAL);
+ }
FocusEditor();
}
@@ -1684,12 +1866,14 @@ LRESULT CALLBACK WndProc(HWND h, UINT m, WPARAM w, LPARAM l) {
}
return 0;
case WM_APP_TRAZER: Bring(); return 0;
+ case WM_APP_IA: IaPronta((IaFeito*)l); return 0;
case WM_TIMER:
if (w == T_FRONT) { // abriu pelo Launchpad: confere de novo depois da animação de fechar
KillTimer(h, T_FRONT);
if (GetForegroundWindow() != h && ShellInFront()) Bring();
return 0;
}
+ if (w == T_IA) { Invalidate(); return 0; } // a cápsula "Escrevendo…" brilhando
if (w == T_BLINK) {
if (editor::Focused()) editor::ToggleBlink();
Invalidate();
@@ -1761,6 +1945,7 @@ LRESULT CALLBACK WndProc(HWND h, UINT m, WPARAM w, LPARAM l) {
if (g_sheet.on) {
if (In(g_sheetOk, p)) { auto act = g_sheet.act; g_sheet = Sheet{}; if (act) act(); }
else if (In(g_sheetCancel, p)) g_sheet = Sheet{};
+ else if (g_sheet.campo && In(g_iaCampo.lastRect, p)) g_iaCampo.Click(g_f13, p, GetKeyState(VK_SHIFT) < 0);
Invalidate();
return 0;
}
@@ -1906,6 +2091,7 @@ LRESULT CALLBACK WndProc(HWND h, UINT m, WPARAM w, LPARAM l) {
if (g_sheet.on) {
if (w == VK_ESCAPE) g_sheet = Sheet{};
else if (w == VK_RETURN) { auto act = g_sheet.act; g_sheet = Sheet{}; if (act) act(); }
+ else if (g_sheet.campo) g_iaCampo.OnKey((UINT)w, shift, ctrl);
Invalidate();
return 0;
}
@@ -1981,6 +2167,7 @@ LRESULT CALLBACK WndProc(HWND h, UINT m, WPARAM w, LPARAM l) {
return 0;
}
case WM_CHAR:
+ if (g_sheet.on && g_sheet.campo && w >= 32 && w != 127) { g_iaCampo.OnChar((wchar_t)w); Invalidate(); return 0; }
if (g_sheet.on || g_sk.on) return 0;
if (g_focus == F_RENAME) { if (w >= 32) g_rename.OnChar((wchar_t)w); Invalidate(); return 0; }
if (g_focus == F_SEARCH) { if (w >= 32 && w != 127) { g_search.OnChar((wchar_t)w); SearchChanged(); } Invalidate(); return 0; }
diff --git a/src/notas/notas.h b/src/notas/notas.h
index 81aa23c..ad8d610 100644
--- a/src/notas/notas.h
+++ b/src/notas/notas.h
@@ -122,8 +122,8 @@ void InsertTable(int rows, int cols);
void InsertAttachment(const std::wstring& path);
enum Writing { W_PROOF, W_LIST, W_TABLE, W_UPPER, W_LOWER, W_TITLE };
bool Transform(int kind); // false: nada mudou
-bool InTable();
-enum TableOp { T_ADD_ROW, T_ADD_COL, T_DEL_ROW, T_DEL_COL, T_TO_TEXT };
+bool InTable();
+enum TableOp { T_ADD_ROW, T_ADD_COL, T_DEL_ROW, T_DEL_COL, T_TO_TEXT };
void Table(int op); // com o cursor numa tabela
void Undo();
void Redo();
@@ -131,6 +131,11 @@ void CaretScreenRect(D2D1_RECT_F& r); // em DIPs (para o IME)
void Copy(bool cut);
void Paste();
bool HasSelection();
+// Ferramentas de Escrita com IA (main.cpp faz o pedido numa thread): o texto da seleção (parágrafos inteiros) ou da nota
+// toda, em Markdown simples (# títulos, - listas, - [ ] tarefas, | tabelas |); e a troca pelo texto que a IA devolveu.
+struct AiRange { Note* n = nullptr; int a = 0, b = -1; std::wstring antes; bool all = false; };
+AiRange AiTake();
+bool AiReplace(const AiRange& r, const std::wstring& markdown); // false: a nota mudou enquanto a IA escrevia
}
// ---- main.cpp (para o editor avisar)
diff --git a/src/shell/atalhos.cpp b/src/shell/atalhos.cpp
index 5d9ee7b..6e0f540 100644
--- a/src/shell/atalhos.cpp
+++ b/src/shell/atalhos.cpp
@@ -421,11 +421,15 @@ void atalhos::MediaCommand(const std::wstring& exePath, const std::wstring& aumi
std::thread([exePath, aumid, cmd] {
winrt::init_apartment(winrt::apartment_type::multi_threaded);
try {
- if (auto s = SessionOf(exePath, aumid)) {
+ // sem app: a sessão atual do Windows (as teclas de mídia do teclado)
+ auto s = exePath.empty() && aumid.empty() ? wmc::GlobalSystemMediaTransportControlsSessionManager::RequestAsync().get().GetCurrentSession()
+ : SessionOf(exePath, aumid);
+ if (s) {
if (cmd == 0) s.TryTogglePlayPauseAsync().get();
else if (cmd == 1) s.TrySkipNextAsync().get();
- else s.TrySkipPreviousAsync().get();
- }
+ else if (cmd == 2) s.TrySkipPreviousAsync().get();
+ else s.TryStopAsync().get();
+ } else Log(L"mídia: nenhuma sessão de mídia para o comando %d", cmd);
} catch (...) {}
}).detach();
}
diff --git a/src/shell/backdrop.cpp b/src/shell/backdrop.cpp
index 9d896b9..fbb1132 100644
--- a/src/shell/backdrop.cpp
+++ b/src/shell/backdrop.cpp
@@ -1767,11 +1767,38 @@ void backdrop::Fade(HWND h, float opacity, float scale, float cx, float cy) {
auto it = g_entries.find(h);
if (it == g_entries.end()) return;
auto& e = it->second;
+ try { e.root.StopAnimation(L"Opacity"); e.root.StopAnimation(L"Scale"); } catch (...) {} // uma de FadeAnim ainda andando
e.root.Opacity(std::clamp(opacity, 0.f, 1.f));
e.root.CenterPoint({ cx, cy, 0 });
e.root.Scale({ scale, scale, 1 });
}
+// a mola inteira pela Composição (quadros-chave a cada passoMs, retos entre eles): o DWM toca no ritmo da tela, e a
+// thread da interface ocupada (o gênio do Dock, um menu) não faz o painel pular quadros
+void backdrop::FadeAnim(HWND h, float cx, float cy, const std::vector<float>& escala, const std::vector<float>& opac, float passoMs) {
+ auto it = g_entries.find(h);
+ if (it == g_entries.end() || escala.size() < 2 || opac.size() < 2) return;
+ auto& e = it->second;
+ try {
+ e.root.CenterPoint({ cx, cy, 0 });
+ auto lin = g_comp.CreateLinearEasingFunction();
+ auto o = g_comp.CreateScalarKeyFrameAnimation();
+ auto sv = g_comp.CreateVector3KeyFrameAnimation();
+ size_t n = std::min(escala.size(), opac.size());
+ for (size_t i = 0; i < n; i++) {
+ float p = (float)i / (float)(n - 1);
+ o.InsertKeyFrame(p, std::clamp(opac[i], 0.f, 1.f), lin);
+ sv.InsertKeyFrame(p, { escala[i], escala[i], 1 }, lin);
+ }
+ auto dur = std::chrono::milliseconds(std::max(1, (int)std::lround((n - 1) * passoMs)));
+ o.Duration(dur); sv.Duration(dur);
+ e.root.StartAnimation(L"Opacity", o);
+ e.root.StartAnimation(L"Scale", sv);
+ } catch (...) {
+ Fade(h, opac.back(), escala.back(), cx, cy);
+ }
+}
+
// some sozinho na Composição (o DWM anima): vale mesmo que esta thread fique ocupada (a ação escolhida no menu)
void backdrop::FadeOutAnim(HWND h, int ms) {
auto it = g_entries.find(h);
diff --git a/src/shell/main.cpp b/src/shell/main.cpp
index 8490a73..cdf334d 100644
--- a/src/shell/main.cpp
+++ b/src/shell/main.cpp
@@ -1,1510 +1,1565 @@
-// Shell.exe: barra de menus + Dock + bandeja no estilo do macOS Sequoia, por cima do Explorador.
-// Enquanto roda, esconde a barra de tarefas do Windows e ajusta a área de trabalho; ao sair
-// (menu do logo → Sair do Shell, Ctrl+Alt+Shift+F12, ou erro), devolve tudo como estava.
-#include "shell.h"
-#include "../comum/simbolos.h"
-#include "../comum/ajustes_arquivo.h"
-#include "../menu/context_menu.h"
-#include <shlobj.h>
-#include <propkey.h>
-#include <dwmapi.h>
-#include <share.h>
-#include <cstdarg>
-#include <map>
-#include <thread>
-#include <atomic>
-#include <mutex>
-#include <condition_variable>
-#include <mmsystem.h>
-#pragma comment(lib, "winmm.lib")
-
-HINSTANCE shell::inst;
-std::wstring shell::dir;
-bool shell::nativo;
-
-DWORD shell::SemProprio() { return nativo ? 0 : WINEVENT_SKIPOWNPROCESS; }
-
-// Gancho global (WH_MOUSE_LL / WH_KEYBOARD_LL): o Windows segura cada tecla e cada clique do PC INTEIRO até a thread do
-// gancho responder. Numa CPU fraca e ocupada (i3, notebook na bateria) uma thread de prioridade normal esperava a vez
-// atrás do resto e o ponteiro/teclado engasgavam (issues #10 e #33). No modo jogo o processo vai para o EcoQoS (núcleos
-// lentos, jogo.cpp): a thread do gancho fica fora dele, senão cada tecla do jogo esperava um núcleo de eficiência acordar.
-void shell::ThreadDeGancho() {
- SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
- THREAD_POWER_THROTTLING_STATE s{ THREAD_POWER_THROTTLING_CURRENT_VERSION, THREAD_POWER_THROTTLING_EXECUTION_SPEED, 0 };
- SetThreadInformation(GetCurrentThread(), ThreadPowerThrottling, &s, sizeof(s));
-}
-
-// Janela do próprio Shell. Fora do modo nativo: qualquer janela deste processo. No nativo o processo é o
-// explorer.exe: as janelas dele (pastas, Executar, avisos de copiar/apagar) são de app; nossas são só as
-// criadas com o módulo do Shell (a MacBarra.dll).
-bool shell::Nossa(HWND h) {
- DWORD pid = 0; GetWindowThreadProcessId(h, &pid);
- if (pid != GetCurrentProcessId()) return false;
- if (!nativo) return true;
- return (HINSTANCE)GetWindowLongPtrW(h, GWLP_HINSTANCE) == inst || apps::IsShellWindow(h);
-}
-
-static FILE* g_log;
-static HWND g_msg;
-static UINT WM_SHELLHOOK;
-static RECT g_origWork;
-static std::vector<HWND> g_hiddenBars;
-static std::map<std::wstring, std::wstring> g_settings;
-static bool g_quitting;
-static bool g_crashed, g_sessionEnding; // Restore() sem abrir o Explorador (o vigia ou o logoff cuidam)
-
-// ---- tecla Windows: sozinha abre o Launchpad; com outra tecla (Win+E, Win+D, Win+L...) segue para o
-// Windows normalmente. O gancho roda numa thread própria para nunca atrasar o teclado.
-const ULONG_PTR KEY_MARK = 0x53484C4C; // teclas que nós mesmos injetamos
-const UINT WM_APP_LAUNCHPAD = WM_APP + 30, WM_APP_SETTINGS = WM_APP + 31, WM_APP_MISSION = WM_APP + 32, WM_APP_SNAP = WM_APP + 33, WM_APP_SPOTLIGHT = WM_APP + 34, WM_APP_MONITOR = WM_APP + 35, WM_APP_SWITCH = WM_APP + 36, WM_APP_SWITCH_KEY = WM_APP + 37, WM_APP_SWITCH_END = WM_APP + 38;
-static std::atomic<bool> g_altTab; // seletor de apps aberto (Alt seguro desde o primeiro Tab)
-static HHOOK g_kbHook;
-static bool g_winDown, g_winCombo, g_winEaten, g_spaceHeld, g_tabHeld; // eaten: a combinação foi nossa (Win+I)
-static DWORD g_winVk, g_winAt; // At: quando a tecla Win desceu (ms do gancho)
-static bool g_winPassed; // uma tecla de combinação foi para o Windows (Win+V, Win+.): ele não abre o Iniciar ao soltar
-
-
-static void Inject(DWORD vk, bool up) {
- INPUT in{ INPUT_KEYBOARD };
- in.ki.wVk = (WORD)vk;
- in.ki.dwFlags = (up ? KEYEVENTF_KEYUP : 0) | (vk == VK_LWIN || vk == VK_RWIN ? KEYEVENTF_EXTENDEDKEY : 0);
- in.ki.dwExtraInfo = KEY_MARK;
- SendInput(1, &in, sizeof(in));
-}
-
-const UINT WM_APP_LOCK = WM_APP + 39, WM_APP_WINKEY = WM_APP + 40, WM_APP_CAPTURA = WM_APP + 41;
-static bool g_capturaExe; // WacOSScreenshot.exe existe: Win+Shift+3/4/5/S são dela
-// Win+Q / Win+H / Win+W = Cmd+Q / Cmd+H / Cmd+W do Mac (encerrar o app, ocultar, fechar a janela).
-// Ajustes > Teclado > "Atalhos do Mac para apps" (atalhos_mac); desligado, os atalhos voltam ao Windows
-const UINT WM_APP_MACKEY = WM_APP + 43;
-const UINT WM_APP_EXPOSE = WM_APP + 44; // Ctrl+Win+↓: Exposé do app da frente (Ctrl+↓ no Mac)
-static volatile bool g_macKeys = true;
-static DWORD g_macKeyVk; // a tecla do atalho: soltar também é nosso (o app não vê uma letra solta)
-static DWORD g_capKey; // tecla do atalho da Captura de Tela ainda segurada
-static bool g_fullHook = true; // false: o gancho só existe para a tela de bloqueio (tecla Windows do Launchpad desligada)
-const UINT WM_APP_VOLUME = WM_APP + 42;
-static bool g_volumeKeys = true; // ajuste volume_mac: teclas de volume com o aviso do Mac (0 = o Windows trata)
-
-static LRESULT CALLBACK KeyHook(int code, WPARAM w, LPARAM l) {
- if (code == HC_ACTION && w == WM_KEYDOWN && ((KBDLLHOOKSTRUCT*)l)->vkCode == VK_CAPITAL) ilha::CapsLock(); // Ilha Dinâmica: aviso do Caps Lock
- if (code == HC_ACTION && g_volumeKeys && !bloqueio::Active()) {
- // teclas de volume (Fn + F-teclas): o Shell muda o volume em 16 passos e mostra o aviso do Mac
- // (o painel do Windows não aparece). Só essas três teclas: os atalhos Ctrl+Alt+Shift+F11/F12 seguem livres.
- auto* k = (KBDLLHOOKSTRUCT*)l;
- // F14/F15: as teclas de brilho do teclado do Mac (e um atalho para teclados de PC com teclas programáveis); issue #38
- // sem nenhuma tela com brilho controlável (já conferido), elas passam: F13-F24 são atalhos comuns de teclas de
- // macro (cenas do OBS...) e antes sumiam no PC inteiro sem fazer nada
- if (k->dwExtraInfo != KEY_MARK && (k->vkCode == VK_F14 || k->vkCode == VK_F15) && !central::SemBrilho()) {
- if (w == WM_KEYDOWN || w == WM_SYSKEYDOWN) PostMessageW(g_msg, WM_APP_VOLUME, k->vkCode, 0);
- return 1;
- }
- if (k->dwExtraInfo != KEY_MARK && (k->vkCode == VK_VOLUME_UP || k->vkCode == VK_VOLUME_DOWN || k->vkCode == VK_VOLUME_MUTE)) {
- if (w == WM_KEYDOWN || w == WM_SYSKEYDOWN) {
- bool fine = GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_MENU) < 0;
- PostMessageW(g_msg, WM_APP_VOLUME, k->vkCode, fine);
- }
- return 1;
- }
- }
- if (code == HC_ACTION && bloqueio::Active()) {
- // tela travada: nada de Iniciar, Alt+Tab, Ctrl+Esc, Alt+Esc, Alt+F4, Ctrl+Shift+Esc (Ctrl+Alt+Del não dá para barrar)
- auto* k = (KBDLLHOOKSTRUCT*)l;
- bool alt = (k->flags & LLKHF_ALTDOWN) != 0, ctrl = GetAsyncKeyState(VK_CONTROL) < 0;
- DWORD vk = k->vkCode;
- if (vk == VK_LWIN || vk == VK_RWIN || vk == VK_APPS) { g_winDown = false; return 1; }
- if ((alt && (vk == VK_TAB || vk == VK_ESCAPE || vk == VK_F4 || vk == VK_SPACE)) || (ctrl && vk == VK_ESCAPE)) return 1;
- g_altTab = false;
- return CallNextHookEx(g_kbHook, code, w, l);
- }
- if (!g_fullHook) return CallNextHookEx(g_kbHook, code, w, l);
- if (code == HC_ACTION) {
- auto* k = (KBDLLHOOKSTRUCT*)l;
- if (k->dwExtraInfo != KEY_MARK) {
- bool down = w == WM_KEYDOWN || w == WM_SYSKEYDOWN;
- bool win = k->vkCode == VK_LWIN || k->vkCode == VK_RWIN;
- if (win) {
- auto mods = [] { return GetAsyncKeyState(VK_CONTROL) < 0 || GetAsyncKeyState(VK_SHIFT) < 0 || GetAsyncKeyState(VK_MENU) < 0; };
- if (shell::nativo) {
- // modo nativo (dentro do explorer): a tecla segue para o Windows; o atalho reinjetado daqui não
- // valia (Win+R não abria). Sozinha, ao soltar, abre o Launchpad
- if (down) {
- if (!g_winDown) { g_winDown = true; g_winCombo = mods(); g_winEaten = false; g_spaceHeld = false; g_tabHeld = false; g_winVk = k->vkCode; g_winAt = k->time; }
- } else if (g_winDown) {
- g_winDown = false;
- if (!g_winCombo && k->time - g_winAt <= 1000) PostMessageW(g_msg, WM_APP_LAUNCHPAD, 0, 0);
- }
- return CallNextHookEx(g_kbHook, code, w, l);
- }
- // A tecla segue para o Windows desde que desce (como no modo nativo): AltSnap e afins (Win + arrastar) a veem
- // segurada, sem atraso e sem o Shell mexer no clique (issue #21: segurar o clique e devolver dava um tranco,
- // o cursor não mudava e o clique direito às vezes travava). Os nossos atalhos (Win+Espaço, Win+I...) comem só a
- // letra. Ao soltar, a tecla muda (0xE8) antes do Win: o Windows não vê um Win "sozinho" e o Iniciar não abre.
- if (down) {
- if (!g_winDown) {
- g_winDown = true; g_winCombo = mods(); g_winEaten = false; g_spaceHeld = false; g_tabHeld = false; g_winVk = k->vkCode; g_winAt = k->time;
- g_winPassed = false;
- }
- return CallNextHookEx(g_kbHook, code, w, l);
- }
- if (g_winDown) {
- g_winDown = false;
- if (!g_winCombo && k->time - g_winAt <= 1000) PostMessageW(g_msg, WM_APP_LAUNCHPAD, 0, 0); // sozinha: Launchpad/Spotlight
- // Combinação que foi para o Windows (Win+V, Win+.): ele mesmo não abre o Iniciar, e a tecla muda chegava
- // ao painel que acabou de abrir: o histórico da Área de Transferência piscava e fechava (issue #27, 22/11/2026)
- if (g_winPassed && !g_winEaten) return CallNextHookEx(g_kbHook, code, w, l);
- // a tecla muda e o soltar do Win vão juntos, nesta ordem: deixando o soltar de verdade passar, a muda
- // (mandada daqui de dentro) chegava depois dele e o Iniciar abria
- Inject(0xE8, false); Inject(0xE8, true);
- Inject(k->vkCode, true);
- return 1;
- }
- return CallNextHookEx(g_kbHook, code, w, l);
- } else if (k->vkCode == VK_TAB && down && !g_winDown && GetAsyncKeyState(VK_MENU) < 0 && GetAsyncKeyState(VK_CONTROL) >= 0) {
- // Alt+Tab: o seletor de apps do Mac no lugar do Alternar Tarefas do Windows. A tecla "muda"
- // (0xE8) evita que o app da frente veja um Alt sozinho ao soltar e abra o menu dele
- if (!g_altTab) { Inject(0xE8, false); Inject(0xE8, true); }
- g_altTab = true;
- PostMessageW(g_msg, WM_APP_SWITCH, GetAsyncKeyState(VK_SHIFT) < 0 ? (WPARAM)-1 : 1, 0);
- return 1;
- } else if (g_altTab && down && (k->vkCode == 'Q' || k->vkCode == 'H' || k->vkCode == VK_ESCAPE || k->vkCode == VK_LEFT || k->vkCode == VK_RIGHT)) {
- if (k->vkCode == VK_ESCAPE) g_altTab = false;
- PostMessageW(g_msg, WM_APP_SWITCH_KEY, k->vkCode, 0);
- return 1;
- } else if (g_altTab && !down && (k->vkCode == VK_LMENU || k->vkCode == VK_RMENU || k->vkCode == VK_MENU)) {
- g_altTab = false;
- PostMessageW(g_msg, WM_APP_SWITCH_END, 0, 0); // o Alt solto segue para o Windows normalmente
- } else if (k->vkCode == VK_ESCAPE && down && GetAsyncKeyState(VK_CONTROL) < 0 && GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_MENU) >= 0) {
- // Ctrl+Shift+Esc: o nosso Monitor de Atividade no lugar do Gerenciador de Tarefas
- PostMessageW(g_msg, WM_APP_MONITOR, 0, 0);
- return 1;
- } else if (k->vkCode == VK_ESCAPE && down && GetAsyncKeyState(VK_CONTROL) < 0 && GetAsyncKeyState(VK_MENU) < 0 && GetAsyncKeyState(VK_SHIFT) >= 0) {
- // Ctrl+Alt+Esc: Forçar Encerrar Aplicativos (Command+Option+Esc do Mac)
- PostMessageW(g_msg, WM_APP_MONITOR, 1, 0);
- return 1;
- } else if (k->vkCode == VK_SPACE && g_winDown && (!g_winCombo || g_winEaten)) {
- // Win+Espaço: o Spotlight (Cmd+Espaço no Mac; no Windows trocaria o idioma do teclado).
- // Segurando o Win, cada Espaço abre/fecha de novo; repetição de tecla segurada não conta e
- // nenhum Espaço chega ao app de baixo
- if (down && !g_spaceHeld) PostMessageW(g_msg, WM_APP_SPOTLIGHT, 0, 0);
- g_spaceHeld = down;
- g_winCombo = g_winEaten = true;
- return 1;
- } else if (k->vkCode == VK_TAB && g_winDown && (!g_winCombo || g_winEaten)) {
- // Win+Tab: o Mission Control (no lugar da Visão de Tarefas). Segurando o Win, cada Tab abre/fecha
- // de novo (igual ao Espaço); repetição de tecla segurada não conta
- if (down && !g_tabHeld) PostMessageW(g_msg, WM_APP_MISSION, 0, 0);
- g_tabHeld = down;
- g_winCombo = g_winEaten = true;
- return 1;
- } else if (g_winDown && down && (k->vkCode == VK_F12 || k->vkCode == VK_F8) && liquid::Leopard()) {
- // Leopard: Win+F12 = Dashboard (o F12 do Mac), Win+F8 = Spaces (o F8 do Mac). Só com o Win: o F12 sozinho
- // continua dos apps (ferramentas do navegador)
- static UINT openPanel = RegisterWindowMessageW(L"ShellAbrirPainel");
- PostMessageW(g_msg, openPanel, k->vkCode == VK_F12 ? 16 : 17, 0);
- g_winCombo = g_winEaten = true;
- return 1;
- } else if (g_winDown && down && !g_winCombo && (k->vkCode == 'I' || k->vkCode == VK_TAB)) {
- // Win+I: o nosso Ajustes do Sistema; Win+Tab: o Mission Control (no lugar da Visão de Tarefas)
- g_winCombo = g_winEaten = true;
- PostMessageW(g_msg, k->vkCode == VK_TAB ? WM_APP_MISSION : WM_APP_SETTINGS, 0, 0);
- return 1;
- } else if (!shell::nativo && g_winDown && down && (k->vkCode == VK_LEFT || k->vkCode == VK_RIGHT) && GetAsyncKeyState(VK_CONTROL) >= 0 &&
- GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_MENU) >= 0) {
- // Win+←/→: metade da tela (o encaixe do Windows fica desligado enquanto o Shell roda: encaixe.cpp)
- if (!g_winCombo) g_winCombo = g_winEaten = true;
- PostMessageW(g_msg, WM_APP_SNAP, k->vkCode, 0);
- return 1;
- } else if (g_winDown && down && !g_winCombo && (k->vkCode == VK_UP || k->vkCode == VK_DOWN) &&
- GetPropW(GetForegroundWindow(), L"MacJanela")) {
- // Win+↑/↓ em janela com a barra do Mac: sem o botão de maximizar o Windows ignora; fazemos nós
- g_winCombo = g_winEaten = true;
- PostMessageW(g_msg, WM_APP_SNAP, k->vkCode, 0);
- return 1;
- } else if (!shell::nativo && g_winDown && down && k->vkCode == 'Q' && GetAsyncKeyState(VK_CONTROL) < 0 && GetAsyncKeyState(VK_MENU) >= 0) {
- // Ctrl+Win+Q: o atalho do Mac (Control+Command+Q) para bloquear (o bloqueio do Windows)
- if (!g_winCombo) g_winCombo = g_winEaten = true;
- PostMessageW(g_msg, WM_APP_LOCK, 0, 0);
- return 1;
- } else if (g_winDown && (k->vkCode == VK_UP || k->vkCode == VK_DOWN) && GetAsyncKeyState(VK_CONTROL) < 0 &&
- GetAsyncKeyState(VK_MENU) >= 0 && GetAsyncKeyState(VK_SHIFT) >= 0) {
- // Ctrl+Win+↑ / ↓ = Ctrl+↑ / ↓ do Mac: Mission Control / Exposé do app da frente (Ctrl+Win+←/→
- // já trocam de Mesa, como Ctrl+←/→ no Mac). A repetição da tecla segurada não abre de novo
- if (down && g_macKeyVk != k->vkCode) PostMessageW(g_msg, k->vkCode == VK_UP ? WM_APP_MISSION : WM_APP_EXPOSE, 0, 0);
- g_macKeyVk = down ? k->vkCode : 0;
- if (!g_winCombo) g_winCombo = g_winEaten = true;
- return 1;
- } else if (g_macKeyVk && k->vkCode == g_macKeyVk && !down) {
- g_macKeyVk = 0;
- return 1;
- } else if (g_macKeys && g_winDown && down && (!g_winCombo || g_winEaten) && (k->vkCode == 'Q' || k->vkCode == 'H' || k->vkCode == 'W') &&
- GetAsyncKeyState(VK_CONTROL) >= 0 && GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_MENU) >= 0) {
- // Win+Q encerra o app da frente, Win+H oculta, Win+W fecha a janela (como Cmd no Mac). Segurando o
- // Win, cada toque vale de novo; a repetição da tecla segurada não conta
- if (g_macKeyVk != k->vkCode) PostMessageW(g_msg, WM_APP_MACKEY, k->vkCode, 0);
- g_macKeyVk = k->vkCode;
- g_winCombo = g_winEaten = true;
- return 1;
- } else if (g_capKey && k->vkCode == g_capKey && !down) {
- g_capKey = 0; // fim do atalho da Captura de Tela: a tecla solta também é nossa
- return 1;
- } else if (g_winDown && down && GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_MENU) >= 0 &&
- (k->vkCode == '3' || k->vkCode == '4' || k->vkCode == '5' || k->vkCode == 'S') && g_capturaExe) {
- // Win+Shift+3/4/5 (Cmd+Shift+3/4/5 do Mac) e Win+Shift+S: a nossa Captura de Tela
- // (WacOSScreenshot.exe) no lugar da Ferramenta de Captura; com Ctrl, só área de transferência.
- // A tecla segurada (repetição) não abre de novo; a tecla muda (0xE8) faz o Windows não ver
- // um Win sozinho ao soltar (o Win e o Shift já foram devolvidos a ele: combinação)
- if (g_capKey != k->vkCode) {
- g_capKey = k->vkCode;
- Inject(0xE8, false); Inject(0xE8, true);
- int kind = k->vkCode == 'S' ? 4 : (int)(k->vkCode - '0');
- PostMessageW(g_msg, WM_APP_CAPTURA, kind, GetAsyncKeyState(VK_CONTROL) < 0 ? 1 : 0);
- }
- return 1;
- } else if (g_winDown && down && k->vkCode == 'S' && GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_CONTROL) >= 0 && mesa::Standalone()) {
- // Win+Shift+S sem a nossa Captura de Tela: a Ferramenta de Captura do Windows (quem atende é
- // o Explorador quando ele é o shell; sem ele, fazemos nós)
- PostMessageW(g_msg, WM_APP_WINKEY, 'S', 0);
- return 1;
- } else if (g_winDown && down && !g_winCombo && !shell::nativo && k->vkCode == 'E' && GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_CONTROL) >= 0) {
- // Win+E com o Explorador rodando (explorer=fundo): ele abria a página "Início" dele, que não é pasta de
- // disco e o Finder não trocava (17/11/2026). O Shell atende sempre: Finder (ou o Explorador, se
- // "Abrir pastas no Finder" estiver desligado — mesa::WinKey decide)
- g_winCombo = g_winEaten = true;
- PostMessageW(g_msg, WM_APP_WINKEY, 'E', 0);
- return 1;
- } else if (g_winDown && down && !g_winCombo && !shell::nativo && k->vkCode == 'D') {
- // Win+D é sempre nosso: com o Explorador de fundo, o "mostrar a área de trabalho" dele punha a mesa
- // DELE na frente e a nossa voltava por cima em seguida (piscava, os widgets sumiam e voltavam)
- g_winCombo = g_winEaten = true;
- PostMessageW(g_msg, WM_APP_WINKEY, 'D', 0);
- return 1;
- } else if (g_winDown && down && !g_winCombo && mesa::Standalone() && (k->vkCode == 'E' || k->vkCode == 'R' || k->vkCode == 'D')) {
- // sem o Explorador ninguém trata Win+E/R/D: fazemos nós (Finder, Executar, mostrar a mesa)
- g_winCombo = g_winEaten = true;
- PostMessageW(g_msg, WM_APP_WINKEY, k->vkCode, 0);
- return 1;
- } else if (g_winDown && down && !g_winCombo && shell::nativo) {
- g_winCombo = true; // nativo: a tecla Windows já foi para o Windows; esta segue também
- } else if (g_winDown && down && !g_winCombo) {
- // combinação do Windows: a tecla Win já foi para ele; esta segue também
- g_winCombo = true;
- g_winPassed = true;
- }
- }
- }
- return CallNextHookEx(g_kbHook, code, w, l);
-}
-
-static void KeyThread() {
- shell::ThreadDeGancho();
- g_kbHook = SetWindowsHookExW(WH_KEYBOARD_LL, KeyHook, GetModuleHandleW(nullptr), 0);
- MSG m;
- while (GetMessageW(&m, nullptr, 0, 0)) {}
- if (g_kbHook) UnhookWindowsHookEx(g_kbHook);
-}
-
-// O log vai para o disco numa thread própria. Gravando direto (fwprintf + fflush a cada linha), a thread da interface
-// ficava presa no WriteFile quando o disco demorava (torrent, antivírus, agente de monitoramento): o vigia via o Shell
-// sem responder por 5 s e o reiniciava, várias vezes seguidas (22/11/2026: as duas pilhas tiradas no travamento
-// estavam no Log -> fflush -> WriteFile, chamado pelo vidro real).
-static std::mutex g_logMx, g_logDisco;
-static std::condition_variable g_logCv;
-static std::wstring g_logFila;
-static void LogGrava() { // o que está na fila vai para o arquivo (só uma thread grava de cada vez)
- std::wstring s;
- { std::lock_guard<std::mutex> l(g_logMx); s.swap(g_logFila); }
- if (s.empty() || !g_log) return;
- std::lock_guard<std::mutex> d(g_logDisco);
- fputws(s.c_str(), g_log); fflush(g_log);
-}
-static void EsperaAjustes();
-static void LogDescarrega() { EsperaAjustes(); LogGrava(); } // fim do Shell: o que faltou vai junto (log e ajustes.txt)
-
-void Log(const wchar_t* fmt, ...) {
- if (!g_log) return;
- SYSTEMTIME st; GetLocalTime(&st);
- wchar_t pre[16]; swprintf_s(pre, L"%02d:%02d:%02d ", st.wHour, st.wMinute, st.wSecond);
- va_list a; va_start(a, fmt);
- va_list b; va_copy(b, a);
- int n = _vscwprintf(fmt, a);
- std::wstring linha;
- if (n > 0) { linha.resize((size_t)n + 1); vswprintf_s(linha.data(), linha.size(), fmt, b); linha.resize((size_t)n); }
- va_end(b); va_end(a);
- static std::once_flag once;
- std::call_once(once, [] {
- std::thread([] {
- for (;;) {
- { std::unique_lock<std::mutex> l(g_logMx); g_logCv.wait(l, [] { return !g_logFila.empty(); }); }
- LogGrava();
- }
- }).detach();
- });
- {
- std::lock_guard<std::mutex> l(g_logMx);
- if (g_logFila.size() < 4 * 1024 * 1024) { g_logFila += pre; g_logFila += linha; g_logFila += L'\n'; } // disco parado de vez: não cresce sem fim
- }
- g_logCv.notify_one();
-}
-
-// g_settings é lido de várias threads (vidro, índice, ilha, widgets...) enquanto a interface relê o arquivo
-// (LoadSettings troca o mapa inteiro): sem trava, a leitura podia pegar o mapa no meio da troca e derrubar o Shell
-static SRWLOCK g_settingsLock = SRWLOCK_INIT;
-std::wstring shell::Setting(const wchar_t* key, const wchar_t* def) {
- AcquireSRWLockShared(&g_settingsLock);
- auto it = g_settings.find(key);
- std::wstring r = it != g_settings.end() ? it->second : (def ? def : L"");
- ReleaseSRWLockShared(&g_settingsLock);
- return r;
-}
-
-static std::wstring SettingsPath() {
- PWSTR p = nullptr;
- std::wstring f;
- if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) { f = std::wstring(p) + L"\\Shell"; CoTaskMemFree(p); }
- CreateDirectoryW(f.c_str(), nullptr);
- return f + L"\\ajustes.txt";
-}
-
-// O ajustes.txt vai para o disco numa thread (como o log). Gravando aqui, cada mudança (Dock, Central de Controle,
-// Launchpad, widgets...) esperava o disco na thread da interface: num HD com o antivírus olhando, 20 a 200 ms de tela
-// parada a cada clique (issue #10, Core i3 com HD). O valor vale na hora (g_settings); o arquivo segue logo depois, e
-// várias mudanças seguidas viram uma gravação só. Quem relê o arquivo (LoadSettings) e a saída do Shell esperam a fila.
-static std::mutex g_ajMx;
-static std::condition_variable g_ajCv;
-static std::map<std::wstring, std::wstring> g_ajMapa; // os ajustes inteiros a gravar (os mais novos)
-static bool g_ajTem = false, g_ajOcupado = false;
-static void EsperaAjustes() {
- std::unique_lock<std::mutex> l(g_ajMx);
- g_ajCv.wait_for(l, std::chrono::seconds(3), [] { return !g_ajTem && !g_ajOcupado; });
-}
-void shell::SetSetting(const wchar_t* key, const std::wstring& value) {
- std::map<std::wstring, std::wstring> copia;
- AcquireSRWLockExclusive(&g_settingsLock);
- g_settings[key] = value;
- copia = g_settings;
- ReleaseSRWLockExclusive(&g_settingsLock);
- // na thread de gravação, atômico (.tmp + troca): quem lê no meio não vê o arquivo vazio
- { std::lock_guard<std::mutex> l(g_ajMx); g_ajMapa = std::move(copia); g_ajTem = true; }
- static std::once_flag umaVez;
- std::call_once(umaVez, [] {
- std::thread([] {
- for (;;) {
- std::map<std::wstring, std::wstring> m;
- {
- std::unique_lock<std::mutex> l(g_ajMx);
- g_ajCv.wait(l, [] { return g_ajTem; });
- m.swap(g_ajMapa); g_ajTem = false; g_ajOcupado = true;
- }
- ajarq::Gravar(SettingsPath(), m);
- { std::lock_guard<std::mutex> l(g_ajMx); g_ajOcupado = false; }
- g_ajCv.notify_all();
- }
- }).detach();
- });
- g_ajCv.notify_all();
-}
-
-// Calculadora (Calculadora.exe) no lugar da Calculadora do Windows: Launchpad, Spotlight e Dock passam
-// o alvo (AUMID, atalho ou .exe) por aqui. Sem o Calculadora.exe, segue a do Windows (devolve false).
-bool shell::OpenCalculator(const std::wstring& target) {
- std::wstring t = target;
- for (auto& c : t) c = towlower(c);
- auto ends = [&](const wchar_t* s) { size_t n = wcslen(s); return t.size() >= n && t.compare(t.size() - n, n, s) == 0; };
- bool calc = t.find(L"microsoft.windowscalculator") != std::wstring::npos || t == L"calc.exe" || t == L"calc" ||
- ends(L"\\calc.exe") || ends(L"calculatorapp.exe") || ends(L"\\calculadora.exe") || ends(L"\\wacoscalculator.exe");
- if (!calc) return false;
- std::wstring exe = shell::dir + L"\\" EXE_CALCULATOR;
- if (GetFileAttributesW(exe.c_str()) == INVALID_FILE_ATTRIBUTES) return false;
- shell::Abrir(L"open", exe.c_str());
- return true;
-}
-
-// Monitor de Atividade (MonitorAtividade.exe); sem ele, o Gerenciador de Tarefas do Windows
-void shell::OpenMonitor() {
- std::wstring exe = shell::dir + L"\\" EXE_MONITOR;
- if (GetFileAttributesW(exe.c_str()) == INVALID_FILE_ATTRIBUTES) exe = L"taskmgr.exe";
- shell::Abrir(L"open", exe.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
-}
-
-// Forçar Encerrar Aplicativos (WacOSForceQuit.exe); sem ele, o Monitor de Atividade
-void shell::OpenForceQuit(bool memory) {
- std::wstring exe = shell::dir + L"\\" EXE_FORCEQUIT;
- if (GetFileAttributesW(exe.c_str()) == INVALID_FILE_ATTRIBUTES) { shell::OpenMonitor(); return; }
- AllowSetForegroundWindow(ASFW_ANY); // aberta pela pressão de memória, sem clique: precisa vir para a frente
- shell::Abrir(L"open", exe.c_str(), memory ? L"--memoria" : nullptr, nullptr, SW_SHOWNORMAL);
-}
-
-void shell::Sound(const wchar_t* name) {
- std::wstring root = shell::dir.substr(0, shell::dir.find_last_of(L'\\')); // a pasta do projeto (bin fica dentro dela)
- PlaySoundW((root + L"\\sons\\mac\\" + name + L".wav").c_str(), nullptr, SND_FILENAME | SND_ASYNC | SND_NODEFAULT);
-}
-
-void shell::OpenSettings(const std::wstring& page) {
- std::wstring args = page.empty() ? L"" : (page.rfind(L"ms-settings:", 0) == 0 ? page : L"--pagina=" + page);
- shell::Abrir(L"open", (shell::dir + L"\\" EXE_SETTINGS).c_str(), args.c_str());
-}
-
-// ShellExecute numa thread: na thread da interface ele chegou a segurar o Shell 3,2 s (abrir o Ajustes pela Ilha com o
-// disco ocupado; pilha de 22/11/2026 19:54, issue #32). A thread espera o ShellExecute terminar (SEE_MASK_NOASYNC).
-std::wstring shell::PastaDoApp(const std::wstring& alvo) {
- auto pastaDoExe = [](std::wstring p) -> std::wstring {
- if (p.size() > 1 && p.front() == L'"') p = p.substr(1, p.find(L'"', 1) - 1);
- if (p.size() < 5 || _wcsicmp(p.c_str() + p.size() - 4, L".exe") || p.find(L":\\") == std::wstring::npos) return L"";
- size_t b = p.find_last_of(L'\\');
- return b == std::wstring::npos ? L"" : p.substr(0, b);
- };
- if (std::wstring d = pastaDoExe(alvo); !d.empty()) return d;
- // item da pasta Aplicativos ou atalho: o caminho do programa que ele abre (System.Link.TargetParsingPath)
- std::wstring r;
- IShellItem2* it = nullptr;
- if (SUCCEEDED(SHCreateItemFromParsingName(alvo.c_str(), nullptr, IID_PPV_ARGS(&it)))) {
- PWSTR t = nullptr;
- if (SUCCEEDED(it->GetString(PKEY_Link_TargetParsingPath, &t)) && t) { r = pastaDoExe(t); CoTaskMemFree(t); }
- it->Release();
- }
- return r;
-}
-
-void shell::Abrir(const wchar_t* verb, const wchar_t* file, const wchar_t* args, const wchar_t* dir, int show) {
- if (!file) return;
- AllowSetForegroundWindow(ASFW_ANY); // o app aberto pela thread vem para a frente como antes
- std::wstring v = verb ? verb : L"", f = file, a = args ? args : L"", d = dir ? dir : L"";
- if (d.empty() && f.size() > 4 && !_wcsicmp(f.c_str() + f.size() - 4, L".exe")) d = shell::PastaDoApp(f); // a pasta do programa (issue #38)
- bool temVerbo = verb != nullptr;
- std::thread([v, f, a, d, show, temVerbo] {
- HRESULT ci = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
- SHELLEXECUTEINFOW se{ sizeof(se) };
- se.fMask = SEE_MASK_NOASYNC;
- se.lpVerb = temVerbo ? v.c_str() : nullptr;
- se.lpFile = f.c_str();
- se.lpParameters = a.empty() ? nullptr : a.c_str();
- se.lpDirectory = d.empty() ? nullptr : d.c_str();
- se.nShow = show;
- if (!ShellExecuteExW(&se)) Log(L"abrir: não abriu %ls (%lu)", f.c_str(), GetLastError());
- if (SUCCEEDED(ci)) CoUninitialize();
- }).detach();
-}
-
-// trabalho feito numa thread devolve o resultado para a interface (dock: a Lixeira cheia ou vazia)
-static const UINT WM_NA_INTERFACE = WM_APP + 60;
-void shell::NaInterface(std::function<void()> f) {
- auto* p = new std::function<void()>(std::move(f));
- if (!g_msg || !PostMessageW(g_msg, WM_NA_INTERFACE, 0, (LPARAM)p)) delete p;
-}
-
-static void LoadSettings() {
- EsperaAjustes(); // uma gravação nossa ainda na fila: ela vai antes (senão a releitura traria o valor antigo)
- PWSTR p = nullptr;
- if (FAILED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) return;
- std::wstring f = std::wstring(p) + L"\\Shell\\ajustes.txt";
- CoTaskMemFree(p);
- // Do zero a cada leitura: uma linha tirada do arquivo (ajuste de volta ao padrão) continuava valendo com o valor
- // antigo até reiniciar o Shell (23/11/2026: ocultar=1 apagado deixava o Dock sem reserva na área de trabalho).
- // Linhas de qualquer tamanho (apps_ordem passava de 512 caracteres e era cortada).
- std::map<std::wstring, std::wstring> novo;
- if (!ajarq::Ler(f, novo)) return;
- AcquireSRWLockExclusive(&g_settingsLock);
- g_settings.swap(novo);
- ReleaseSRWLockExclusive(&g_settingsLock);
- backdrop::Reload(); // Transparência e Efeitos (Liquid Glass, reduzir transparência, tinta)
- anim::reduceMotion = shell::Setting(L"reduzir_movimento", L"0") == L"1";
-}
-
-// ---- barra de tarefas do Windows: escondida enquanto o shell roda
-static void HideTaskbars() {
- if (shell::nativo) return; // nativo: a barra do Windows é o próprio Shell (a MacBarra a mantém escondida)
- EnumWindows([](HWND h, LPARAM) -> BOOL {
- wchar_t c[64]; GetClassNameW(h, c, 64);
- if ((!wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd")) && !apps::IsShellWindow(h)) {
- // sem esperar o Explorador: travado ou ainda subindo, ele segurava o Shell aqui (o vigia reiniciava o
- // Shell em ciclo, 09/11/2026)
- if (IsWindowVisible(h)) ShowWindowAsync(h, SW_HIDE);
- if (std::find(g_hiddenBars.begin(), g_hiddenBars.end(), h) == g_hiddenBars.end()) g_hiddenBars.push_back(h);
- }
- return TRUE;
- }, 0);
-}
-
-// A barra do Explorador que ele mostra de novo (Win, notificação, Explorador reiniciado) some na hora. Antes só o tique de
-// 1 s a escondia: ela "aparecia às vezes" por até um segundo (issue #40)
-static void CALLBACK OnBarraWindows(HWINEVENTHOOK, DWORD, HWND h, LONG obj, LONG child, DWORD, DWORD) {
- if (obj != OBJID_WINDOW || child != CHILDID_SELF || g_quitting || shell::nativo || !h) return;
- wchar_t c[32] = {}; GetClassNameW(h, c, 32);
- if (wcscmp(c, L"Shell_TrayWnd") && wcscmp(c, L"Shell_SecondaryTrayWnd")) return;
- DWORD pid = 0; GetWindowThreadProcessId(h, &pid);
- if (pid == GetCurrentProcessId() || apps::IsShellWindow(h)) return;
- ShowWindowAsync(h, SW_HIDE);
- if (std::find(g_hiddenBars.begin(), g_hiddenBars.end(), h) == g_hiddenBars.end()) g_hiddenBars.push_back(h);
-}
-
-static void ShowTaskbars() {
- for (HWND h : g_hiddenBars) if (IsWindow(h)) ShowWindowAsync(h, SW_SHOWNOACTIVATE);
- g_hiddenBars.clear();
- // issue #37 (a barra do Windows sumia ao sair): o Explorador que reiniciou com o Shell aberto cria uma barra nova,
- // que não está na lista acima. Toda barra do Explorador escondida volta.
- EnumWindows([](HWND h, LPARAM) -> BOOL {
- wchar_t c[64] = {}; GetClassNameW(h, c, 64);
- if ((!wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd")) && !apps::IsShellWindow(h) && !IsWindowVisible(h)) {
- DWORD pid = 0; GetWindowThreadProcessId(h, &pid);
- if (pid != GetCurrentProcessId()) ShowWindowAsync(h, SW_SHOWNOACTIVATE);
- }
- return TRUE;
- }, 0);
-}
-
-// Barra do Windows nos outros monitores: só esconder não segurava (o Explorador a mostrava de novo e ela
-// reservava espaço). Enquanto o Shell roda, desliga "Mostrar a barra de tarefas em todos os monitores"
-// (HKCU ...\Explorer\Advanced\MMTaskbarEnabled = 0, a mesma chave da Configuração do Windows). O valor de antes
-// fica em ajustes.txt (barra_windows_monitores_antes: 0, 1 ou "x" = não existia) e volta ao sair.
-static const wchar_t* MM_KEY = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";
-
-static void TellExplorerTray() { // o Explorador relê o ajuste da barra (como a Configuração faz)
- std::thread([] {
- EnumWindows([](HWND h, LPARAM) -> BOOL {
- wchar_t c[64] = {}; GetClassNameW(h, c, 64);
- if (!wcscmp(c, L"Shell_TrayWnd") && !apps::IsShellWindow(h))
- SendMessageTimeoutW(h, WM_SETTINGCHANGE, 0, (LPARAM)L"TraySettings", SMTO_ABORTIFHUNG, 1000, nullptr);
- return TRUE;
- }, 0);
- }).detach();
-}
-
-static void SecondaryTaskbarsOff() {
- if (shell::nativo) return;
- DWORD v = 0, cb = sizeof(v);
- bool had = RegGetValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled", RRF_RT_REG_DWORD, nullptr, &v, &cb) == ERROR_SUCCESS;
- if (had && v == 0) return; // já desligado (pelo usuário ou por nós antes)
- if (shell::Setting(L"barra_windows_monitores_antes", L"").empty())
- shell::SetSetting(L"barra_windows_monitores_antes", had ? std::to_wstring(v) : L"x");
- DWORD zero = 0;
- if (RegSetKeyValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled", REG_DWORD, &zero, sizeof(zero)) == ERROR_SUCCESS) {
- Log(L"registro: HKCU\\%ls\\MMTaskbarEnabled = 0 (antes: %ls) - barra do Windows só no monitor principal", MM_KEY, had ? std::to_wstring(v).c_str() : L"não existia");
- TellExplorerTray();
- }
-}
-
-static void SecondaryTaskbarsRestore() {
- std::wstring before = shell::Setting(L"barra_windows_monitores_antes", L"");
- if (before.empty()) return;
- if (before == L"x") RegDeleteKeyValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled");
- else { DWORD v = (DWORD)_wtoi(before.c_str()); RegSetKeyValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled", REG_DWORD, &v, sizeof(v)); }
- shell::SetSetting(L"barra_windows_monitores_antes", L"");
- Log(L"registro: MMTaskbarEnabled devolvido (%ls)", before == L"x" ? L"apagado, não existia" : before.c_str());
- TellExplorerTray();
-}
-
-// Área de trabalho de cada monitor: a barra de menus em cima (todos têm a sua) e o Dock embaixo (só no
-// monitor dele). O SPI_SETWORKAREA vale para o monitor que contém o retângulo.
-std::vector<HWND> shell::AlheiasNoTopo() {
- std::vector<HWND> v; // de cima para baixo
- DWORD eu = GetCurrentProcessId();
- for (HWND w = GetTopWindow(nullptr); w && v.size() < 32; w = GetWindow(w, GW_HWNDNEXT)) {
- if (!(GetWindowLongW(w, GWL_EXSTYLE) & WS_EX_TOPMOST)) break; // acabou a faixa das "sempre por cima"
- if (!IsWindowVisible(w)) continue;
- DWORD pid = 0; GetWindowThreadProcessId(w, &pid);
- if (pid == eu) break; // daqui para baixo já estavam abaixo das nossas
- DWORD cloak = 0; DwmGetWindowAttribute(w, DWMWA_CLOAKED, &cloak, sizeof(cloak));
- if (cloak) continue;
- wchar_t c[64] = {}; GetClassNameW(w, c, 64);
- if (!wcscmp(c, L"tooltips_class32") || !wcscmp(c, L"#32768") || !wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd")) continue;
- RECT r; if (!GetWindowRect(w, &r) || r.right - r.left < 2 || r.bottom - r.top < 2) continue;
- v.push_back(w);
- }
- return v;
-}
-
-void shell::DevolveAlheias(const std::vector<HWND>& v) {
- for (auto it = v.rbegin(); it != v.rend(); ++it) // de baixo para cima: a de cima termina por cima
- if (IsWindow(*it) && IsWindowVisible(*it))
- SetWindowPos(*it, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_ASYNCWINDOWPOS);
-}
-
-RECT shell::WorkAreaFor(HMONITOR hm) {
- MONITORINFO mi{ sizeof(mi) };
- if (!GetMonitorInfoW(hm, &mi)) return {};
- RECT want = mi.rcMonitor;
- want.top += menubar::ReservedOn(hm); // secundário sem barra (barra_todos_monitores=0): o topo é das janelas
- if (hm == dock::MonitorHandle()) { // o Dock na borda escolhida (Ajustes > Posição na tela)
- int r = dock::ReservedHeight();
- if (dock::Posicao() == 1) want.left += r;
- else if (dock::Posicao() == 2) want.right -= r;
- else want.bottom -= std::max(r, menubar::ReservedBottom(hm)); // barra embaixo: com o Dock oculto, a altura dela
- }
- return want;
-}
-
-void shell::ApplyWorkArea() {
- if (g_quitting) return;
- struct Ctx { HMONITOR dock; bool changed; } ctx{ dock::MonitorHandle(), false };
- EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hm, HDC, LPRECT, LPARAM p) -> BOOL {
- auto* c = (Ctx*)p;
- MONITORINFO mi{ sizeof(mi) };
- if (!GetMonitorInfoW(hm, &mi)) return TRUE;
- RECT want = shell::WorkAreaFor(hm), cur = mi.rcWork;
- (void)c;
- if (EqualRect(&want, &cur)) return TRUE;
- static int times;
- Log(L"área de trabalho estava %d,%d-%d,%d; agora %d,%d-%d,%d (vez %d)", cur.left, cur.top, cur.right, cur.bottom,
- want.left, want.top, want.right, want.bottom, ++times);
- // Sem SPIF_SENDCHANGE: o aviso geral fazia o Explorador recalcular e desfazer (briga a cada 2 s).
- SystemParametersInfoW(SPI_SETWORKAREA, 0, &want, 0);
- c->changed = true;
- return TRUE;
- }, (LPARAM)&ctx);
- if (!ctx.changed) return;
- // Avisa só as janelas dos apps: o DefWindowProc reencaixa as maximizadas na área nova.
- EnumWindows([](HWND h, LPARAM) -> BOOL {
- if (!IsWindowVisible(h) || apps::IsShellWindow(h)) return TRUE;
- wchar_t c[64]; GetClassNameW(h, c, 64);
- if (!wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd") || mesa::IsDeskClass(c)) return TRUE;
- if (IsZoomed(h)) SendMessageTimeoutW(h, WM_SETTINGCHANGE, SPI_SETWORKAREA, 0, SMTO_ABORTIFHUNG, 200, nullptr);
- return TRUE;
- }, 0);
-}
-
-static void Restore() {
- if (g_quitting) return;
- g_quitting = true;
- tray::Stop();
- menus::Stop();
- dialogs::Stop();
- janelas::Stop();
- encaixe::Stop();
- memoria::Stop();
- barras::Stop();
- sombras::Stop();
- alertas::Stop();
- progresso::Stop(); // as janelas de progresso do Windows voltam para a tela
- if (!shell::nativo) { // no nativo a tela de bloqueio continua do Windows (não foi trocada)
- bloqueio::Stop(); // Win+L volta para o Windows (política apagada)
- mesa::Stop(!g_crashed && !g_sessionEnding); // sem Explorador: ele volta (ao cair, quem abre é o vigia)
- } else mesa::Stop(true); // nativo: a nossa mesa some e a do Explorador (que ficou atrás) reaparece
- revelar::Stop(); // janelas que estavam nas bordas voltam
- ponteiro::Stop(); // o cursor volta ao tamanho do esquema
- palco::Stop(); // Organizador Visual: as janelas escondidas por ele voltam
- genio::Stop(); // a animação de minimizar do Windows volta como estava
- notificacoes::Stop(); // o banner de notificação do Windows volta
- ShowTaskbars();
- SecondaryTaskbarsRestore();
- // os outros monitores voltam inteiros (a barra do Windows, se voltar lá, reserva o espaço dela)
- EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hm, HDC, LPRECT, LPARAM) -> BOOL {
- MONITORINFO mi{ sizeof(mi) };
- if (GetMonitorInfoW(hm, &mi) && !(mi.dwFlags & MONITORINFOF_PRIMARY)) SystemParametersInfoW(SPI_SETWORKAREA, 0, &mi.rcMonitor, 0);
- return TRUE;
- }, 0);
- SystemParametersInfoW(SPI_SETWORKAREA, 0, &g_origWork, SPIF_SENDCHANGE);
- Log(L"saindo: barra do Windows e área de trabalho devolvidas");
-}
-
-// Saindo de verdade (não o reiniciar): o WacOS fecha por inteiro (issue #37: depois de sair, o Win+E e as pastas
-// ainda abriam o Finder, e o Finder reserva e a Captura residente continuavam abertos, escondidos).
-// As pastas voltam para o Explorador e finder_volta=1 faz o Shell, ao abrir de novo, devolvê-las ao Finder (o mesmo
-// caminho do "Desligar o WacOS"). Quem desligou "Abrir pastas no Finder" à mão (finder_padrao=0) não é mexido.
-static void SaiPorInteiro() {
- static UINT capMsg = RegisterWindowMessageW(L"SequoiaCaptura");
- if (HWND w = FindWindowW(L"SequoiaCapturaMsg", nullptr)) PostMessageW(w, capMsg, 0, 0); // wParam 0 = sair
- if (HWND w = FindWindowW(L"ArquivosJanela", L"​ArquivosReserva")) // a reserva nunca foi usada: não tem nada do usuário
- PostThreadMessageW(GetWindowThreadProcessId(w, nullptr), WM_QUIT, 0, 0);
- std::wstring finder = shell::dir + L"\\" EXE_FINDER;
- if (shell::Setting(L"finder_padrao", L"1") == L"1" && GetFileAttributesW(finder.c_str()) != INVALID_FILE_ATTRIBUTES) {
- shell::SetSetting(L"finder_volta", L"1");
- std::wstring cmd = L"\"" + finder + L"\" --padrao off --quieto";
- STARTUPINFOW si{ sizeof(si) }; si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;
- PROCESS_INFORMATION pi{};
- if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, shell::dir.c_str(), &si, &pi)) {
- WaitForSingleObject(pi.hProcess, 3000); // antes de uma atualização abrir o Shell novo (que religa)
- CloseHandle(pi.hThread); CloseHandle(pi.hProcess);
- Log(L"saindo: pastas e Win+E de volta ao Explorador (o Finder volta ao abrir o WacOS)");
- }
- }
-}
-
-void shell::Quit(const wchar_t* why) {
- Log(L"pedido para sair: %ls", why);
- if (wcscmp(why, L"reiniciar")) SaiPorInteiro();
- pastas::Stop();
- limites::Stop();
- bloqueio::Fallback(); // saiu com a tela travada (ex.: Ctrl+Alt+Shift+F12): o Windows bloqueia
- Restore();
- PostQuitMessage(0);
-}
-
-static LONG WINAPI OnCrash(EXCEPTION_POINTERS* ep) {
- HMODULE mod = nullptr;
- void* at = ep->ExceptionRecord->ExceptionAddress;
- GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)at, &mod);
- wchar_t name[MAX_PATH] = L"?"; if (mod) GetModuleFileNameW(mod, name, MAX_PATH);
- Log(L"ERRO 0x%08X em %ls+0x%llX", ep->ExceptionRecord->ExceptionCode, name, (unsigned long long)((BYTE*)at - (BYTE*)mod));
- bloqueio::Fallback(); // caiu com a tela travada: o Windows bloqueia de verdade
- g_crashed = true;
- Restore(); // nunca deixar o usuário sem barra de tarefas
- return EXCEPTION_CONTINUE_SEARCH;
-}
-
-// Finder reserva: um Arquivos.exe já inicializado e escondido. Abrir uma pasta, o Win+E ou a janela
-// de Abrir/Salvar entregam o pedido a ele (aparece na hora); quando é usado, preparamos outro.
-// Captura de Tela (WacOSScreenshot.exe) sempre aberta e escondida: a mira do Win+Shift+4 aparece na hora
-bool shell::SoDock() { static int v = -1; if (v < 0) v = shell::Setting(L"modo", L"completo") == L"dock" ? 1 : 0; return v == 1; }
-
-static void EnsureScreenshot() {
- static DWORD lastSpawn;
- if (g_quitting || !g_capturaExe || FindWindowW(L"SequoiaCapturaMsg", nullptr)) return;
- if (lastSpawn && GetTickCount() - lastSpawn < 10000) return;
- lastSpawn = GetTickCount();
- std::wstring cmd = L"\"" + shell::dir + L"\\" EXE_SCREENSHOT L"\" /residente";
- STARTUPINFOW si{ sizeof(si) };
- PROCESS_INFORMATION pi{};
- std::thread([cmd, si, pi]() mutable { // como o Finder reserva: abrir programa espera o disco
- if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) {
- CloseHandle(pi.hProcess); CloseHandle(pi.hThread);
- Log(L"Captura de Tela residente aberta");
- }
- }).detach();
-}
-
-// pedido do atalho: 3 tela inteira, 4 região/janela, 5 barra de ferramentas; clip = Ctrl seguro
-static void Screenshot(int kind, bool clip) {
- static UINT msg = RegisterWindowMessageW(L"SequoiaCaptura");
- if (HWND w = FindWindowW(L"SequoiaCapturaMsg", nullptr)) {
- DWORD pid = 0; GetWindowThreadProcessId(w, &pid);
- AllowSetForegroundWindow(pid);
- PostMessageW(w, msg, kind, clip ? 1 : 0);
- return;
- }
- std::wstring args = L"/" + std::to_wstring(kind) + (clip ? L" /c" : L"");
- shell::Abrir(L"open", (shell::dir + L"\\" EXE_SCREENSHOT).c_str(), args.c_str(), nullptr, SW_SHOWNORMAL);
- Log(L"Captura de Tela aberta agora (%ls)", args.c_str());
-}
-
-void shell::AbrirFinder(const std::wstring& args) {
- if (shell::nativo) {
- HMODULE m = GetModuleHandleW(L"MacFinder.dll");
- auto pedir = m ? (BOOL(WINAPI*)(const wchar_t*))GetProcAddress(m, "FinderPedir") : nullptr;
- if (pedir && pedir(args.c_str())) { Log(L"Finder (nativo): %ls", args.c_str()); return; }
- Log(L"Finder nativo indisponível, abrindo o exe: %ls", args.c_str());
- }
- shell::Abrir(L"open", (shell::dir + L"\\" EXE_FINDER).c_str(), args.c_str(), nullptr, SW_SHOWNORMAL);
-}
-
-static void EnsureReserve() {
- if (shell::nativo) return; // no nativo a reserva é a janela do Finder dentro do explorer (MacFinder.dll)
- static DWORD lastSpawn;
- if (g_quitting || FindWindowW(L"ArquivosJanela", L"​ArquivosReserva")) return;
- if (lastSpawn && GetTickCount() - lastSpawn < 4000) return; // um por vez
- lastSpawn = GetTickCount();
- std::wstring cmd = L"\"" + shell::dir + L"\\" EXE_FINDER L"\" --reserva";
- STARTUPINFOW si{ sizeof(si) };
- si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;
- PROCESS_INFORMATION pi{};
- // numa thread: com o disco cheio o CreateProcess levou 2,9 s e a interface esperava (pilha de 22/11/2026, 15:25)
- std::thread([cmd, si, pi]() mutable {
- if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) {
- CloseHandle(pi.hProcess); CloseHandle(pi.hThread);
- Log(L"Finder reserva preparado");
- }
- }).detach();
-}
-
-// Pré-carga: lê os .exe dos outros apps do projeto para o cache de arquivos do Windows (memória de
-// espera, que o sistema devolve quando precisa). Assim o primeiro clique abre como se já tivesse sido
-// aberto antes, sem deixar nenhum processo rodando. Prioridade de fundo, depois que o Shell está pronto.
-// os painéis que montam coisa cara na primeira abertura: prepara com o Shell já parado, na thread
-// principal (o compositor e a GPU são dela)
-static void CALLBACK WarmPanels(HWND, UINT, UINT_PTR id, DWORD) {
- KillTimer(nullptr, id);
- missioncontrol::Warm();
- launchpad::Warm();
-}
-
-static void PreloadApps() {
- SetTimer(nullptr, 0, 4000, WarmPanels);
- std::thread([] {
- SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
- Sleep(3000);
- static const wchar_t* files[] = { EXE_SETTINGS, EXE_NOTES, EXE_CALCULATOR, EXE_TERMINAL, EXE_MONITOR, DLL_WINDOW32 };
- std::vector<char> buf(1 << 20);
- size_t total = 0;
- for (auto* f : files) {
- HANDLE h = CreateFileW((shell::dir + L"\\" + f).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr,
- OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
- if (h == INVALID_HANDLE_VALUE) continue;
- DWORD got = 0;
- while (ReadFile(h, buf.data(), (DWORD)buf.size(), &got, nullptr) && got) total += got;
- CloseHandle(h);
- }
- Log(L"pré-carga: %zu KB dos apps no cache", total / 1024);
- SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
- }).detach();
-}
-
-// App da frente cobrindo o monitor inteiro (vídeo, jogo, F11): Dock e barra de menus somem, como no Mac.
-static bool IsFullscreen(HWND fg) {
- if (!fg || !IsWindowVisible(fg) || IsIconic(fg) || apps::IsShellWindow(fg)) return false;
- // Trocadores de papel de parede com transição (YASB, Lively...) põem a janela da animação DENTRO da mesa do Windows
- // (filha da WorkerW/Progman) e ela fica sendo a "janela da frente". Cobrindo o monitor, parecia um app em tela
- // cheia: o Dock e a barra de menus sumiam e o vidro ficava sem fundo, e como o YASB mantém a janela viva depois da
- // transição, ficava assim até reiniciar o WacOS (Reddit, 23/11/2026; reproduzido com o mesmo truque do YASB).
- // Janela filha conta pela de topo dela: sendo a mesa, não é tela cheia.
- if (HWND root = GetAncestor(fg, GA_ROOT); root && root != fg) {
- wchar_t rc[64] = {}; GetClassNameW(root, rc, 64);
- if (mesa::IsDeskClass(rc)) return false;
- fg = root;
- if (!IsWindowVisible(fg) || IsIconic(fg) || apps::IsShellWindow(fg)) return false;
- }
- wchar_t cls[64] = {}; GetClassNameW(fg, cls, 64);
- if (mesa::IsDeskClass(cls) || !wcscmp(cls, L"Shell_TrayWnd")) return false;
- if (IsZoomed(fg) && (GetWindowLongW(fg, GWL_STYLE) & WS_CAPTION) == WS_CAPTION) return false; // só maximizada
- MONITORINFO mi{ sizeof(mi) };
- if (!GetMonitorInfoW(MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST), &mi)) return false;
- RECT r; if (!GetWindowRect(fg, &r)) return false;
- return r.left <= mi.rcMonitor.left && r.top <= mi.rcMonitor.top && r.right >= mi.rcMonitor.right && r.bottom >= mi.rcMonitor.bottom;
-}
-
-// Jogo/vídeo em tela cheia no monitor `mon` (ou o Windows em modo "não incomodar": Direct3D exclusivo,
-// apresentação): os banners de notificação não aparecem, só vão para a Central. Uma janela "sempre no topo" por cima
-// do jogo tirava ele da tela cheia (17/11/2026, Fortnite caindo a cada notificação).
-bool shell::NaoIncomodar(HMONITOR mon) {
- QUERY_USER_NOTIFICATION_STATE q{};
- if (SUCCEEDED(SHQueryUserNotificationState(&q)) && (q == QUNS_RUNNING_D3D_FULL_SCREEN || q == QUNS_PRESENTATION_MODE || q == QUNS_BUSY))
- return true;
- HWND fg = GetForegroundWindow();
- if (!IsFullscreen(fg)) return false;
- return !mon || MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST) == mon;
-}
-
-// Com mais de um monitor, só some o que está no monitor do app em tela cheia (a barra daquele monitor; o Dock
-// se ele estiver lá). Tela travada: tudo some.
-static void CheckFullscreen() {
- HWND fg = GetForegroundWindow();
- bool locked = bloqueio::Active();
- bool fs = !locked && IsFullscreen(fg);
- HMONITOR fm = fs ? MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST) : nullptr;
- { // registro: quem fez o Dock e a barra de menus sumirem (uma vez por janela)
- static HWND visto;
- if (fs && fg != visto) {
- wchar_t c[80] = {}, t[80] = {}; GetClassNameW(fg, c, 80); GetWindowTextW(fg, t, 80);
- DWORD pid = 0; GetWindowThreadProcessId(fg, &pid);
- Log(L"tela cheia: janela %p classe '%ls' título '%ls' pid %lu estilo %08lX ex %08lX", fg, c, t, pid, GetWindowLongW(fg, GWL_STYLE), GetWindowLongW(fg, GWL_EXSTYLE));
- }
- visto = fs ? fg : nullptr;
- }
- dock::SetFullscreen(locked || (fs && fm == dock::MonitorHandle()));
- menubar::SetFullscreen(locked || fs, fm);
- ilha::SetFullscreen(locked); // a ilha confere sozinha a tela cheia do monitor principal (jogo, vídeo, app)
-}
-
-static void CALLBACK OnWinEvent(HWINEVENTHOOK, DWORD ev, HWND h, LONG obj, LONG, DWORD, DWORD) {
- // maximizada por cima da barra/do Dock (issue #24): qualquer janela de topo (a conferência é barata e sai cedo)
- if (ev == EVENT_OBJECT_LOCATIONCHANGE && obj == OBJID_WINDOW && !shell::nativo && h && GetAncestor(h, GA_ROOT) == h) limites::Maximizada(h);
- if (ev == EVENT_OBJECT_LOCATIONCHANGE && (obj != OBJID_WINDOW || h != GetForegroundWindow())) return;
- if (ev == EVENT_SYSTEM_FOREGROUND) { revelar::Foreground(h); jogo::Foreground(h); }
- CheckFullscreen();
-}
-
-static void Changed() {
- if (apps::Refresh()) dock::Update();
- menubar::Update();
-}
-
-// Aparência "Automático" (Ajustes do Sistema): claro das 7h às 19h, escuro no resto do dia.
-static void AutoAppearance() {
- if (shell::Setting(L"aparencia_auto", L"0") != L"1") return;
- SYSTEMTIME st; GetLocalTime(&st);
- DWORD want = st.wHour >= 7 && st.wHour < 19 ? 1 : 0, cur = 1, cb = sizeof(cur);
- const wchar_t* key = L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
- RegGetValueW(HKEY_CURRENT_USER, key, L"AppsUseLightTheme", RRF_RT_REG_DWORD, nullptr, &cur, &cb);
- if (cur == want) return;
- RegSetKeyValueW(HKEY_CURRENT_USER, key, L"AppsUseLightTheme", REG_DWORD, &want, sizeof(want));
- RegSetKeyValueW(HKEY_CURRENT_USER, key, L"SystemUsesLightTheme", REG_DWORD, &want, sizeof(want));
- Log(L"aparência automática: %ls", want ? L"clara" : L"escura");
- // numa thread, como na Central (central.cpp): para todas as janelas, o limite de 200 ms vale para CADA uma ocupada,
- // e a interface do Shell ficava parada esse tempo todo
- std::thread([] { SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)L"ImmersiveColorSet", SMTO_ABORTIFHUNG, 200, nullptr); }).detach();
-}
-
-static LRESULT CALLBACK MsgProc(HWND h, UINT m, WPARAM w, LPARAM l) {
- if (m == WM_NA_INTERFACE) { auto* p = (std::function<void()>*)l; if (p) { (*p)(); delete p; } return 0; }
- // Outro programa (o Explorador, com a barra do Windows escondida ou em ocultar automaticamente) devolveu a área de
- // trabalho para a tela inteira: reaplica a nossa NA HORA. Antes esperava o tique de 1 s, e nesse meio-tempo as
- // janelas maximizadas e os ícones da mesa subiam para baixo da barra de menus e voltavam (issue #1: "a área
- // pula sem parar"). O nosso próprio SPI_SETWORKAREA vai sem aviso (sem SPIF_SENDCHANGE), então não volta aqui.
- if (m == WM_SETTINGCHANGE && w == SPI_SETWORKAREA && !g_quitting) {
- static DWORD win = 0; static int n = 0;
- DWORD now = GetTickCount();
- if (now - win > 1000) { win = now; n = 0; }
- if (++n <= 8) shell::ApplyWorkArea(); // no máximo 8 por segundo (se alguém brigar sem parar, não gira em laço)
- }
- static UINT reload = RegisterWindowMessageW(L"ShellAjustesMudaram");
- static UINT openCC = RegisterWindowMessageW(L"ShellAbrirCentral"); // abre/fecha a Central de Controle de fora
- static UINT restart = RegisterWindowMessageW(L"ShellReiniciar"); // reiniciar: sai sem abrir o Explorador e abre o Shell de novo
- if (m == restart && restart) {
- // o Shell novo abre já (no mesmo caminho: depois de compilar, é a versão nova) e espera este sair
- wchar_t exe[MAX_PATH]; GetModuleFileNameW(nullptr, exe, MAX_PATH);
- std::wstring dir = exe; dir = dir.substr(0, dir.find_last_of(L'\\'));
- std::wstring cmd = std::wstring(L"\"") + exe + L"\" --depois-de " + std::to_wstring(GetCurrentProcessId());
- STARTUPINFOW si{ sizeof(si) }; PROCESS_INFORMATION pi{};
- if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, dir.c_str(), &si, &pi)) { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); }
- else Log(L"reiniciar: não abriu o Shell novo (%lu)", GetLastError());
- mesa::NoExplorerOnExit();
- tray::SemAvisoAoSair();
- janelas::ManterAoReiniciar(); // as janelas ficam com a barra do Mac (o Shell novo assume; ver janelas::Stop)
- shell::Quit(L"reiniciar");
- return 0;
- }
- if (m == openCC && openCC) { central::Toggle(); return 0; }
- static UINT openNC = RegisterWindowMessageW(L"ShellAbrirNotificacoes"); // abre/fecha a Central de Notificações de fora
- if (m == openNC && openNC) { notificacoes::Toggle(); return 0; }
- static UINT openSP = RegisterWindowMessageW(L"ShellAbrirSpotlight"); // abre/fecha o Spotlight de fora (como o Win+Espaço)
- if (m == openSP && openSP) { PostMessageW(h, WM_APP_SPOTLIGHT, 0, 0); return 0; }
- // abre um painel de fora (fotos do README, testes): 1 Launchpad/Apps, 2 Mission Control, 3..6 Spotlight no modo 1..4,
- // 7 Spotlight, 8 Sobre Este Mac
- static UINT openPanel = RegisterWindowMessageW(L"ShellAbrirPainel");
- if (m == openPanel && openPanel) {
- // pedido de fora: o Windows não deixa o Shell vir para a frente sozinho (o Spotlight e o Launchpad fechavam na
- // hora, sem foco). Entra na fila de entrada da janela da frente enquanto abre, como os alertas fazem.
- HWND fg = GetForegroundWindow();
- DWORD ft = fg ? GetWindowThreadProcessId(fg, nullptr) : 0, me = GetCurrentThreadId();
- bool att = ft && ft != me && AttachThreadInput(me, ft, TRUE);
- if (w == 1) launchpad::Toggle();
- else if (w == 2) missioncontrol::Toggle();
- else if (w >= 3 && w <= 6) spotlight::OpenMode((int)w - 2);
- else if (w == 7) spotlight::Toggle();
- else if (w == 8) sobre::Show(); // Sobre Este Mac
- else if (w == 9) central::Toggle(); // Central de Controle (testes)
- else if (w == 10) notificacoes::Toggle(); // Central de Notificações (testes)
- else if (w == 12) dock::OpenAppsStack(); // Leopard: a pilha Aplicativos (testes)
- else if (w == 13) seletor::Step(1); // o seletor de apps sem segurar o Alt (testes; 14 fecha)
- else if (w == 14) seletor::Key(VK_ESCAPE);
- else if (w == 15) dock::OpenDownloadsStack(); // a pilha Downloads (testes)
- else if (w == 16) dashboard::Toggle(); // Leopard: Dashboard (Win+F12)
- else if (w == 17) espacos::Toggle(); // Leopard: Spaces (Win+F8)
- else if (w == 18) tempo::Enter(); // Leopard: a viagem no tempo do Time Machine
- else if (w == 11) { // Quick Look de uma foto do macOS 27 (testes)
- wchar_t p[MAX_PATH] = {}; GetEnvironmentVariableW(L"USERPROFILE", p, MAX_PATH);
- quicklook::Toggle(std::wstring(p) + L"\\Pictures\\Wallpapers macOS\\macOS 27\\macos-27-golden-4096x2160-27635.jpg");
- }
- if (att) AttachThreadInput(me, ft, FALSE);
- return 0;
- }
- if (atualizacao::Handle(m)) return 0;
- if (LRESULT mr; menus::VidroMsg(m, w, l, &mr)) return mr; // menu de contexto de um app nosso pedindo o vidro
- // Ajustes > Aparência > "Reiniciar o Liquid Glass": refaz o vidro real do zero (se ele desistiu ou travou)
- static UINT redoGlass = RegisterWindowMessageW(L"ShellReiniciarVidro");
- if (m == redoGlass && redoGlass) { backdrop::Restart(); return 1; }
- static UINT capVis = RegisterWindowMessageW(L"ShellCapturaVisivel"); // a Captura de Tela vai tirar a foto
- if (m == capVis && capVis) { backdrop::CaptureVisible(w != 0); return 1; }
- static UINT capDone = RegisterWindowMessageW(L"ShellCapturaFeita"); // a Captura salvou (0) ou copiou (1): aviso na ilha
- if (m == capDone && capDone) { ilha::Captura(w != 0); return 0; }
- if (m == WM_COPYDATA && l && ((COPYDATASTRUCT*)l)->dwData == 0x4C504150 /*'PAPL'*/) { // Ajustes: papel de parede escolhido
- auto* cd = (COPYDATASTRUCT*)l;
- if (!cd->lpData || cd->cbData < sizeof(wchar_t) || cd->cbData > 4096) return FALSE;
- std::wstring p((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t));
- while (!p.empty() && !p.back()) p.pop_back();
- mesa::WallpaperNow(p);
- return TRUE;
- }
- if (m == WM_COPYDATA && l && ((COPYDATASTRUCT*)l)->dwData == 0x514C4F4B /*'QLOK'*/) { // Finder: Quick Look (vazio = fechar)
- auto* cd = (COPYDATASTRUCT*)l;
- if (cd->cbData > 8192) return FALSE;
- std::wstring p = cd->lpData ? std::wstring((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t)) : L"";
- while (!p.empty() && !p.back()) p.pop_back();
- // responde já e abre logo depois: o vídeo leva mais que o tempo de espera do Finder (0,8 s), e ele achava
- // que tinha falhado e abria também o painel antigo dele
- auto* copy = new std::wstring(p);
- PostMessageW(h, WM_APP + 77, 0, (LPARAM)copy);
- return TRUE;
- }
- // 'SIRI': pergunta à Siri (texto UTF-16) vinda de fora (atalhos, scripts, testes); 'BRIL': mostra o brilho n (0-100)
- // na Ilha como se a tela tivesse mudado (teste do aviso num PC de mesa, que não manda o evento do WMI)
- if (m == WM_COPYDATA && l && (((COPYDATASTRUCT*)l)->dwData == 0x49524953 /*'SIRI'*/ || ((COPYDATASTRUCT*)l)->dwData == 0x54524953 /*'SIRT': teste, sem pegar a frente*/ || ((COPYDATASTRUCT*)l)->dwData == 0x41524953 /*'SIRA': abre o campo (teste)*/ || ((COPYDATASTRUCT*)l)->dwData == 0x4C495242 /*'BRIL'*/)) {
- auto* cd = (COPYDATASTRUCT*)l;
- if (!cd->lpData || cd->cbData < sizeof(wchar_t) || cd->cbData > 16384) return FALSE;
- std::wstring t((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t));
- while (!t.empty() && !t.back()) t.pop_back();
- if (cd->dwData == 0x4C495242) { ilha::Brilho(_wtoi(t.c_str())); return TRUE; }
- if (cd->dwData == 0x41524953) { PostMessageW(h, WM_APP + 79, 0, 0); return TRUE; }
- PostMessageW(h, WM_APP + 78, cd->dwData == 0x54524953, (LPARAM)new std::wstring(t)); // depois de responder: quem mandou não fica esperando
- return TRUE;
- }
- if (m == WM_APP + 79) { siri::Abrir(true); return 0; }
- if (m == WM_APP + 78 && l) { std::unique_ptr<std::wstring> q((std::wstring*)l); siri::Perguntar(*q, w != 0); return 0; }
- if (m == WM_APP + 77 && l) { // o Quick Look pedido pelo Finder (acima)
- std::unique_ptr<std::wstring> p((std::wstring*)l);
- if (p->empty()) quicklook::Close();
- else quicklook::Toggle(*p, false); // o Finder fica com o foco
- return 0;
- }
- if (m == WM_COPYDATA && l && ((COPYDATASTRUCT*)l)->dwData == 0x414D504C /*'AMPL'*/) { // MacJanela.dll: ampliar animado
- struct Msg { unsigned long long hwnd; RECT from, to; int flags; COLORREF cap; };
- auto* cd = (COPYDATASTRUCT*)l;
- if (cd->cbData != sizeof(Msg) || !cd->lpData) return FALSE;
- auto* mm = (Msg*)cd->lpData;
- // nativo: janelas de barra própria (flags 8: Chrome, Edge, Electron...) têm a barra do Mac por fora (barras.cpp).
- // A animação usa uma foto da janela de verdade, com a barra e os botões do Windows: por meio segundo as
- // bolinhas sumiam e apareciam os botões antigos (vídeo do usuário de 12/11/2026). Sem animação: muda na hora.
- if (shell::nativo && (mm->flags & 8)) return FALSE;
- return ampliar::Start((HWND)(UINT_PTR)mm->hwnd, mm->from, mm->to, mm->flags, mm->cap) ? TRUE : FALSE;
- }
- static UINT ampFoto = RegisterWindowMessageW(L"ShellAmpliarFoto"); // MacJanela.dll: a janela já mudou de tamanho
- if (m == ampFoto && ampFoto) { ampliar::SecondPhoto((HWND)w); return 0; }
- static UINT iconeMudou = RegisterWindowMessageW(L"ShellIconeMudou"); // ícone próprio de um app escolhido/restaurado (apps.cpp)
- if (m == iconeMudou && iconeMudou) { apps::ReloadIcons(); Log(L"ícone próprio: Dock, Alt+Tab e Launchpad recarregados"); return 0; }
- static UINT ampPronto = RegisterWindowMessageW(L"ShellAmpliarPronto"); // a janela já reapareceu
- if (m == ampPronto && ampPronto) { ampliar::Shown((HWND)w); return 0; }
- static UINT menuVerde = RegisterWindowMessageW(L"ShellMenuVerde"); // ponteiro parado no botão verde (DLL ou app nosso)
- if (m == menuVerde && menuVerde) { verde::Show((HWND)w, POINT{ (short)LOWORD(l), (short)HIWORD(l) }); return 0; }
- static UINT jAbrir = RegisterWindowMessageW(L"ShellJanelaAbrir"); // WacOSWindow.dll: janela nova, escondida e pintada
- if (m == jAbrir && jAbrir) { abrir::Open((HWND)w, (HWND)l); return 0; }
- static UINT jFechar = RegisterWindowMessageW(L"ShellJanelaFechar"); // WacOSWindow.dll: a janela vai sumir agora
- if (m == jFechar && jFechar) return ampliar::Fechar((HWND)w, l) ? 1 : 0;
- if (m == WM_COPYDATA && l) { // o Ajustes do Sistema manda "chave=valor": o Shell grava no arquivo que ele mesmo lê
- // (o Ajustes pode estar num contêiner que desvia o %APPDATA% dele para outra cópia do ajustes.txt)
- auto* cd = (COPYDATASTRUCT*)l;
- if (cd->dwData == 0x534A5354 /*'SJST'*/ && cd->lpData && cd->cbData >= sizeof(wchar_t)) {
- std::wstring kv((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t));
- while (!kv.empty() && !kv.back()) kv.pop_back();
- size_t eq = kv.find(L'=');
- if (eq != std::wstring::npos && eq > 0 && eq < 128 && kv.find(L'\n') == std::wstring::npos) {
- shell::SetSetting(kv.substr(0, eq).c_str(), kv.substr(eq + 1));
- PostMessageW(h, reload, 0, 0);
- }
- return TRUE;
- }
- }
- if (m == reload && reload) { // o Ajustes do Sistema gravou ajustes.txt
- g_macKeys = !shell::SoDock() && shell::Setting(L"atalhos_mac", L"1") == L"1";
- static int lastLiquid = -1;
- if (lastLiquid < 0) lastLiquid = liquid::Leopard() ? 3 : liquid::Golden() ? 2 : liquid::On();
- static int lastTheme = -1; // 0 Sequoia, 1 Tahoe, 2 Golden Gate, 3 Leopard
- auto themeNow = [] { return liquid::Leopard() ? 3 : liquid::Golden() ? 2 : (int)liquid::On(); };
- if (lastTheme < 0) lastTheme = themeNow();
- LoadSettings();
- ilha::Reload();
- { // barra_todos_monitores mudou: cria ou tira as barras dos monitores secundários (e a área de trabalho deles)
- static std::wstring lastAll = L"?";
- std::wstring all = shell::Setting(L"barra_todos_monitores", L"1");
- if (lastAll != L"?" && all != lastAll) { menubar::Displays(); dock::ReloadSettings(); }
- lastAll = all;
- static std::wstring lastBaixo = L"?"; // barra de menus em cima ou na linha do Dock (issue #29)
- std::wstring baixo = shell::Setting(L"barra_embaixo", L"0");
- if (baixo != lastBaixo) { menubar::Displays(); dock::ReloadSettings(); }
- lastBaixo = baixo;
- static std::wstring lastOcultar = L"?"; // ocultar a barra de menus automaticamente (issue #40)
- std::wstring ocultar = shell::Setting(L"barra_ocultar", L"0");
- if (lastOcultar != L"?" && ocultar != lastOcultar) { menubar::Displays(); dock::ReloadSettings(); }
- lastOcultar = ocultar;
- }
- static int lastLang = -1;
- if (lastLang < 0) lastLang = idioma::Current();
- if (int lang = idioma::FromCode(shell::Setting(L"idioma", L"en")); lang != lastLang) { // Ajustes > Geral > Idioma
- lastLang = lang;
- idioma::Set(lang);
- apps::Relabel();
- dock::IconsChanged();
- Log(L"idioma: %ls", idioma::Code());
- }
- if ((liquid::Leopard() ? 3 : liquid::Golden() ? 2 : (int)liquid::On()) != lastLiquid) { // tema Sequoia/Tahoe/Golden Gate/Leopard: outro pacote de ícones
- lastLiquid = liquid::Leopard() ? 3 : liquid::Golden() ? 2 : liquid::On();
- for (auto& a : apps::list) { a.icon.clear(); a.iw = a.ih = 0; a.mac = false; }
- dock::IconsChanged();
- seletor::IconsChanged();
- Log(L"tema mudou: ícones do Dock e do seletor recarregados");
- }
- if (themeNow() != lastTheme) {
- // tema trocado: as janelas com a barra do Mac (WacOSWindow.dll) redesenham já (barra metálica e botões de gel
- // do Leopard, ou de volta) em vez de esperar a próxima ativação
- lastTheme = themeNow();
- EnumWindows([](HWND w, LPARAM msg) -> BOOL {
- if (GetPropW(w, L"MacJanela")) PostMessageW(w, (UINT)msg, 0, 0);
- return TRUE;
- }, (LPARAM)reload);
- Log(L"tema: %d (janelas avisadas)", lastTheme);
- ponteiro::TemaLeopard(lastTheme == 3); // Leopard: cursor do Mac OS X; saindo, o cursor de antes
- }
- dock::ReloadSettings();
- dock::ApplyTheme();
- menubar::ApplyTheme();
- menubar::Update();
- shell::ApplyWorkArea();
- mesa::SettingsChanged();
- widgets::SettingsChanged(); // Personalizar a Mesa: widgets ligados/desligados
- jogo::Reload(); // modo_jogo e jogos.txt
- palco::Sync();
- // "Clicar no papel de parede para mostrar a mesa" saiu de "Nunca": com o Shell aberto em "Nunca" o gancho do mouse
- // nunca era criado e a opção nova só valia depois de reiniciar (Start não faz nada se já estiver ligado)
- if (!shell::SoDock() && !jogo::Ativo()) revelar::Start();
- return 0;
- }
- if (m == WM_SHELLHOOK && WM_SHELLHOOK) {
- switch (w & 0x7FFF) {
- case HSHELL_WINDOWCREATED: case HSHELL_WINDOWDESTROYED: case HSHELL_WINDOWACTIVATED: case HSHELL_REDRAW:
- Changed();
- if ((w & 0x7FFF) == HSHELL_REDRAW && (w & 0x8000)) { // HSHELL_FLASH: app pedindo atenção
- apps::Refresh();
- if (App* a = apps::OfWindow((HWND)l)) { a->attentionAt = GetTickCount(); dock::Update(); }
- }
- break;
- case HSHELL_GETMINRECT: { // para onde a janela encolhe ao minimizar: o Dock, antes da Lixeira
- auto* shi = (SHELLHOOKINFO*)l;
- RECT r{};
- if (shi && genio::OnMinRect(shi->hwnd, &r)) { shi->rc = r; return TRUE; } // o gênio já começou, com a janela ainda na tela
- r = dock::MinimizeTarget(shi ? shi->hwnd : nullptr);
- if (shi && r.right > r.left) { shi->rc = r; SetTimer(g_msg, 7, 450, nullptr); return TRUE; } // e o Dock se atualiza logo depois
- break;
- }
- }
- return 0;
- }
- switch (m) {
- case WM_TIMER:
- if (w == 7) { KillTimer(g_msg, 7); Changed(); return 0; }
- if (w == 1) {
- static int ticks;
- if (ticks++ % 60 == 0) AutoAppearance();
- Changed(); CheckFullscreen(); HideTaskbars(); shell::ApplyWorkArea(); if (shell::Setting(L"finder_reserva", L"1") == L"1") EnsureReserve(); EnsureScreenshot();
- }
- if (w == 2) tray::Keepalive();
- if (w == 9) { // extensões do menu de contexto carregadas cedo: o 1º botão direito na mesa/Spotlight/Launchpad sai rápido
- KillTimer(g_msg, 9);
- wchar_t* p = nullptr; std::wstring desk;
- if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Desktop, 0, nullptr, &p))) { desk = p; CoTaskMemFree(p); }
- std::wstring file;
- WIN32_FIND_DATAW fd; HANDLE fh = desk.empty() ? INVALID_HANDLE_VALUE : FindFirstFileW((desk + L"\\*").c_str(), &fd);
- if (fh != INVALID_HANDLE_VALUE) {
- do if (!(fd.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_HIDDEN))) { file = desk + L"\\" + fd.cFileName; break; }
- while (FindNextFileW(fh, &fd));
- FindClose(fh);
- }
- if (!desk.empty()) ctxmenu::WarmupAsync(desk, file);
- }
- return 0;
- case WM_HOTKEY: shell::Quit(L"atalho Ctrl+Alt+Shift+F12"); return 0;
- case WM_APP_SETTINGS: shell::OpenSettings(L""); return 0;
- case WM_APP_SNAP: {
- HWND fg = GetForegroundWindow();
- if (!fg) return 0;
- if (w == VK_LEFT || w == VK_RIGHT) {
- HWND root = GetAncestor(fg, GA_ROOT);
- if (root && !apps::IsShellWindow(root) && (GetWindowLongW(root, GWL_STYLE) & WS_THICKFRAME)) encaixe::Half(root, w == VK_RIGHT);
- return 0;
- }
- // o "ampliar" do Mac (MacJanela.dll): ocupa a área de trabalho e mantém cantos e sombra
- static UINT zoom = RegisterWindowMessageW(L"MacJanelaAmpliar");
- bool ampliada = GetPropW(fg, L"MacJanelaAmpliada") != nullptr;
- if (w == VK_UP) { if (!ampliada) PostMessageW(fg, zoom, 0, 0); }
- else if (ampliada) PostMessageW(fg, zoom, 0, 0);
- else ShowWindowAsync(fg, SW_MINIMIZE);
- return 0;
- }
- case WM_APP_MISSION:
- if (launchpad::IsOpen()) launchpad::Toggle();
- shell::LiberaFrente(); // permite ao Mission Control vir para a frente
- missioncontrol::Toggle();
- return 0;
- case WM_APP_EXPOSE: {
- HWND fg = GetForegroundWindow();
- HWND root = fg ? GetAncestor(fg, GA_ROOTOWNER) : nullptr;
- apps::Refresh();
- App* a = root && !apps::IsShellWindow(root) ? apps::OfWindow(root) : nullptr;
- if (!a) { Log(L"Exposé do app: a janela da frente não é de um app do Dock"); return 0; }
- if (launchpad::IsOpen()) launchpad::Toggle();
- shell::LiberaFrente(); // permite ao Exposé vir para a frente
- missioncontrol::ToggleApp(a->id, a->name);
- return 0;
- }
- case WM_APP_MACKEY: {
- HWND fg = GetForegroundWindow();
- HWND root = fg ? GetAncestor(fg, GA_ROOT) : nullptr;
- if (!root || apps::IsShellWindow(root) || apps::IsShellWindow(GetAncestor(root, GA_ROOTOWNER))) return 0; // Dock, mesa, painéis
- if (w == 'W') { // fecha só a janela da frente (o app continua aberto)
- Log(L"atalho Win+W: fechando a janela %p", root);
- PostMessageW(root, WM_SYSCOMMAND, SC_CLOSE, 0);
- return 0;
- }
- apps::Refresh();
- App* a = apps::OfWindow(GetAncestor(root, GA_ROOTOWNER));
- if (!a) a = apps::OfWindow(root);
- if (!a) { Log(L"atalho Win+%lc: janela da frente sem app no Dock", (wchar_t)w); return 0; }
- if (w == 'Q') {
- if (a->finder) return 0; // como no Mac: o Finder não se encerra
- Log(L"atalho Win+Q: encerrando %ls", a->name.c_str());
- apps::Quit(*a);
- } else {
- Log(L"atalho Win+H: ocultando %ls", a->name.c_str());
- apps::Hide(*a);
- }
- dock::Update();
- return 0;
- }
- case WM_APP_LOCK:
- bloqueio::Lock(); // o bloqueio do Windows (a tela do WacOS saiu)
- return 0;
- case WM_APP_MONITOR:
- if (w == 1) shell::OpenForceQuit(false); else shell::OpenMonitor();
- return 0;
- case WM_APP_SWITCH: seletor::Step((int)(INT_PTR)w); return 0;
- case WM_APP_SWITCH_KEY: seletor::Key((UINT)w); return 0;
- case WM_APP_SWITCH_END: seletor::Release(); return 0;
- case WM_APP_SPOTLIGHT:
- if (launchpad::IsOpen()) launchpad::Toggle();
- shell::LiberaFrente(); // permite ao Spotlight vir para a frente e receber o teclado
- spotlight::Toggle();
- return 0;
- case WM_APP_LAUNCHPAD:
- shell::LiberaFrente(); // permite ao Launchpad vir para a frente
- launchpad::Toggle();
- return 0;
- case WM_APP_WINKEY: mesa::WinKey((UINT)w); return 0;
- case WM_APP_CAPTURA: Screenshot((int)w, l != 0); return 0;
- case WM_APP_VOLUME:
- if (w == VK_F14 || w == VK_F15) { central::BrilhoPasso(w == VK_F15 ? 1 : -1); return 0; } // brilho (issue #38)
- som::Key((UINT)w, l != 0); return 0;
- case WM_SYSCOMMAND:
- if ((w & 0xFFF0) == SC_TASKLIST) { // Ctrl+Esc com o Shell como Taskman (sem Explorador): Launchpad
- shell::LiberaFrente();
- launchpad::Toggle();
- return 0;
- }
- break;
- case WM_QUERYENDSESSION: return TRUE;
- case WM_ENDSESSION: if (w) { Log(L"fim da sessão do Windows"); g_sessionEnding = true; Restore(); } return 0;
- }
- return DefWindowProcW(h, m, w, l);
-}
-
-int AjudanteRodar(const wchar_t* cmd); // ajudante.cpp: --sair, --aplicar-cursor... (para os scripts do instalador)
-
-int WINAPI wWinMain(HINSTANCE hi, HINSTANCE, PWSTR, int) {
- if (int r = AjudanteRodar(GetCommandLineW()); r >= 0) return r;
- if (migrar::TrocarPeloNovo()) return 0; // nome velho (SequoiaShell.exe): o WacOSShell.exe ao lado assume
- if (const wchar_t* a = wcsstr(GetCommandLineW(), L"--depois-de ")) { // reinício: espera o Shell antigo sair (até 20 s)
- if (HANDLE old = OpenProcess(SYNCHRONIZE, FALSE, wcstoul(a + 12, nullptr, 10))) { WaitForSingleObject(old, 20000); CloseHandle(old); }
- }
- if (bloqueio::Watchdog(GetCommandLineW())) return 0; // vigia da tela de bloqueio (outro processo)
- if (mesa::Watchdog(GetCommandLineW())) return 0; // vigia da mesa: Shell caiu sem Explorador → abre o Explorador
- if (wcsstr(GetCommandLineW(), L"--bloqueio-png ")) { // imagem de teste da tela de bloqueio
- SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
- OleInitialize(nullptr);
- LoadSettings(); // o tema (Tahoe/Sequoia) e o idioma valem também na imagem de teste
- if (ui::Init()) bloqueio::RenderPng(GetCommandLineW());
- return 0;
- }
- if (wcsstr(GetCommandLineW(), L"--senha-bloqueio")) { // define a senha própria da tela de bloqueio
- SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
- return bloqueio::SetPasswordUi(hi);
- }
- if (wcsstr(GetCommandLineW(), L"--testar-bloqueio")) { // a tela de bloqueio por ~3,5 s, sem conferir senha
- SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
- OleInitialize(nullptr);
- return ui::Init() ? bloqueio::Preview(hi) : 1;
- }
- if (wcsstr(GetCommandLineW(), L"--testar-boot")) { SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); return boot::Preview(hi); }
- HANDLE single = CreateMutexW(nullptr, TRUE, L"ShellProprioUmaInstancia");
- if (GetLastError() == ERROR_ALREADY_EXISTS) {
- // reinício: o Shell antigo ainda não largou (preso no relatório de erro do Windows, por exemplo).
- // Antes o novo desistia e ficava sem Shell nenhum; agora espera ele sair (até 60 s)
- DWORD w = wcsstr(GetCommandLineW(), L"--depois-de ") && single ? WaitForSingleObject(single, 60000) : WAIT_TIMEOUT;
- if (w != WAIT_OBJECT_0 && w != WAIT_ABANDONED) return 0;
- }
- SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
- shell::inst = hi;
- wchar_t exe[MAX_PATH]; GetModuleFileNameW(nullptr, exe, MAX_PATH);
- shell::dir = exe; shell::dir = shell::dir.substr(0, shell::dir.find_last_of(L'\\'));
- // o log da sessão anterior fica em shell-anterior.log (o vigia escreve lá o motivo de um reinício)
- MoveFileExW((shell::dir + L"\\shell.log").c_str(), (shell::dir + L"\\shell-anterior.log").c_str(), MOVEFILE_REPLACE_EXISTING);
- g_log = _wfsopen((shell::dir + L"\\shell.log").c_str(), L"w, ccs=UTF-8", _SH_DENYNO);
- Log(L"Shell iniciando");
- OleInitialize(nullptr);
- ctxmenu::Init(hi, nullptr); // sem log: o menu gravava e esperava o disco na thread da interface (mesma trava do arquivo do Log)
- if (!ui::Init()) { Log(L"erro: Direct2D/DirectWrite"); return 1; }
- LoadSettings();
- migrar::Registro(); // caminhos com o nome velho (Sequoia) no registro do Windows (depois dos ajustes: grava um)
- // Voltando depois de "Desligar o WacOS" (Ajustes > Geral): o desligar mandou as pastas e o Win+E de volta para o
- // Explorador (finder_padrao=0). Abrir o WacOS de novo devolve ao Finder; antes o 0 ficava e o Win+E abria o
- // Explorador até apagar os ajustes (issue #1). Quem desligar "Abrir pastas no Finder" à mão continua com o 0.
- if (shell::Setting(L"finder_volta", L"") == L"1") {
- shell::SetSetting(L"finder_volta", L"");
- std::wstring finder = shell::dir + L"\\" EXE_FINDER;
- if (GetFileAttributesW(finder.c_str()) != INVALID_FILE_ATTRIBUTES) {
- shell::SetSetting(L"finder_padrao", L"1");
- shell::Abrir(L"open", finder.c_str(), L"--quieto --padrao on", nullptr, SW_HIDE);
- Log(L"finder: de volta depois do Desligar (finder_padrao=1, --padrao on)");
- }
- }
- boot::Show(hi); // tela de inicialização do Mac (só logo depois do login)
- SetUnhandledExceptionFilter(OnCrash);
- SystemParametersInfoW(SPI_GETWORKAREA, 0, &g_origWork, 0);
-
- simbolo::Dir() = shell::dir.substr(0, shell::dir.find_last_of(L'\\')) + L"\\icones\\simbolos"; // SF Symbols da barra de menus
- apps::Load(shell::dir + L"\\" EXE_FINDER);
- apps::Refresh();
-
- WNDCLASSW mc{}; mc.lpfnWndProc = MsgProc; mc.hInstance = hi; mc.lpszClassName = L"ShellMensagens";
- RegisterClassW(&mc);
- g_msg = CreateWindowExW(WS_EX_TOOLWINDOW, mc.lpszClassName, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, hi, nullptr);
- apps::ours.push_back(g_msg);
- // os menus de contexto dos apps (Finder...) pedem o vidro mesmo com o Shell como administrador
- ChangeWindowMessageFilterEx(g_msg, RegisterWindowMessageW(L"WacOSMenuVidro"), MSGFLT_ALLOW, nullptr);
- atualizacao::Start(g_msg); // aviso de versão nova no GitHub (90 s depois e a cada 6 h)
- boot::Progress(0.2f);
-
- if (!menubar::Create(hi) || !dock::Create(hi) || !launchpad::Create(hi) || !missioncontrol::Create(hi) || !central::Create(hi) || !spotlight::Create(hi) || !alertas::Create(hi) || !sobre::Create(hi) || !seletor::Create(hi) || !som::Create(hi)) { Log(L"erro criando as janelas"); Restore(); return 1; }
- // "Só Dock e barra de menus" (Reddit, anybody001): o que não é a barra nem o Dock fica de fora (ver shell::SoDock)
- const bool soDock = shell::SoDock();
- if (soDock) Log(L"modo: só Dock e barra de menus (a área de trabalho, o Alt+Tab, as pastas e as barras de título ficam com o Windows)");
- instalados::Start(); // programa instalado ou removido: o Spotlight e o Launchpad releem os apps
- indice::Start(); // índice de arquivos do Spotlight (thread de fundo)
- if (!soDock) revelar::Start(); // clique no vazio da área de trabalho mostra a mesa
- if (!soDock) ponteiro::Start(); // sacudir o mouse: o ponteiro cresce para achar
- ponteiro::TemaLeopard(liquid::Leopard()); // tema Leopard: o cursor do Mac OS X (ou devolve o de antes)
- genio::Create(hi); // efeito gênio ao minimizar
- if (!soDock) palco::Sync(); // Organizador Visual (Stage Manager), se ligado
- if (!soDock) widgets::Create(hi); // widgets na mesa (abaixo de todas as janelas)
- // a tela de bloqueio do WacOS saiu (21/11/2026): bloquear usa o do Windows (bloqueio::Lock)
- notificacoes::Create(hi); // Central de Notificações (clique no relógio da barra de menus)
- ilha::Create(hi); // Ilha Dinâmica (ajuste ilha=1)
- if (!soDock) notarapida::Create(hi); // canto inferior direito: Nota Rápida
- if (!soDock) progresso::Create(hi); // copiar/mover/apagar: a janela de progresso do Finder no lugar da do Windows
- if (!soDock) cantos::Start(); // Cantos Ativos (Mission Control, mesa, Launchpad... por canto)
- jogo::Start(); // Modo Jogo: jogo na frente desliga o que mais pesa (vidro real, ganchos do mouse...)
- leve::Start(); // Modo leve: PC fraco ou na bateria (sem vidro real, ~60 quadros/s); vigia tomada/bateria
- brilho::Start(); // brilho da tela do notebook na Ilha (issue #39)
- boot::Progress(0.7f);
- tray::Start([] { menubar::Update(); });
- mesa::Start(hi, g_msg); // ajuste explorer=0: a mesa é nossa e o explorer.exe sai (só Dock: a do Windows, mas o vigia fica)
- menus::Start();
- if (!soDock) dialogs::Start();
- if (!soDock) janelas::Start();
- if (!soDock) encaixe::Start(); // arrastar até a borda: metade, quarto, preencher (com a prévia)
- if (!soDock) memoria::Start(); // pressão de memória, soneca de apps (App Nap), memória descartável
- if (!soDock) pastas::Start(); // janelas de pasta do Explorador viram o Finder
- limites::Start(); // janelas não cruzam a barra de menus nem o Dock
- if (!soDock) sombras::Start();
- HideTaskbars();
- if (!shell::nativo) SetWinEventHook(EVENT_OBJECT_SHOW, EVENT_OBJECT_SHOW, nullptr, OnBarraWindows, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
- SecondaryTaskbarsOff(); // barra do Windows nos outros monitores: desligada enquanto o Shell roda
- shell::ApplyWorkArea();
-
- WM_SHELLHOOK = RegisterWindowMessageW(L"SHELLHOOK");
- RegisterShellHookWindow(g_msg);
- RegisterHotKey(g_msg, 1, MOD_CONTROL | MOD_ALT | MOD_SHIFT | MOD_NOREPEAT, VK_F12); // era Q: fácil de apertar sem querer
- // só Dock: a tecla Windows, o Alt+Tab e a captura de tela ficam com o Windows (o gancho só deixa passar)
- g_fullHook = !soDock && shell::Setting(L"tecla_windows_launchpad", L"1") == L"1";
- g_macKeys = !soDock && shell::Setting(L"atalhos_mac", L"1") == L"1";
- g_capturaExe = !soDock && GetFileAttributesW((shell::dir + L"\\" EXE_SCREENSHOT).c_str()) != INVALID_FILE_ATTRIBUTES;
- if (!soDock) EnsureScreenshot();
- g_volumeKeys = shell::Setting(L"volume_mac", L"1") == L"1";
- if (g_fullHook || g_volumeKeys || (!soDock && shell::Setting(L"bloqueio", L"1") != L"0")) std::thread(KeyThread).detach(); // sem o Launchpad: só barra teclas com a tela travada
- SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr, OnWinEvent, 0, 0, WINEVENT_OUTOFCONTEXT);
- jogo::GanchoPosicao(OnWinEvent, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS); // sai no modo jogo (jogo.cpp)
- SetTimer(g_msg, 1, 1000, nullptr);
- SetTimer(g_msg, 2, 200, nullptr);
- SetTimer(g_msg, 9, 3000, nullptr); // pré-carregar o menu de contexto (depois que o Shell já apareceu)
- Log(L"pronto: %zu apps no Dock", apps::list.size());
- boot::Done();
- mesa::RunStartupApps(); // só quando o Shell é o shell do Windows (o Explorador não abre no login)
- PreloadApps();
-
- MSG msg;
- sentinela::Start(g_msg); // interface parada 1 s ou mais: o shell.log diz onde (issue #32)
- while (GetMessageW(&msg, nullptr, 0, 0)) { mesa::Pulse(); sentinela::ultimaMsg = msg.message; sentinela::ultimaJanela = msg.hwnd; TranslateMessage(&msg); DispatchMessageW(&msg); } // pulso: ver mesa::Pulse
- Restore();
- DeregisterShellHookWindow(g_msg);
- // Sai daqui direto (TerminateProcess), com tudo já devolvido ao Windows. Voltar do wWinMain roda o
- // encerramento do C++ (fecha todos os arquivos, inclusive o log; OleUninitialize desmonta o COM) com as
- // threads de fundo (vidro real, índice, notificações) ainda rodando: elas escreviam no log fechado e o
- // Shell caía ao reiniciar (0xC0000005), e o Windows segurava o processo morto no relatório de erro.
- LogDescarrega();
- if (g_log) fflush(g_log);
- ReleaseMutex(single);
- TerminateProcess(GetCurrentProcess(), 0);
- return 0;
-}
-
-// ---- modo nativo: o Shell como a barra de tarefas do Windows (barra-nativa\MacBarra.dll, dentro do explorer.exe).
-// A MacBarra chama numa thread própria quando o explorer cria a barra (ITrayUI::OnCreate) e esta função só
-// volta quando a barra é destruída. Mesmas peças do WacOSShell.exe, menos as que são de processo:
-// mutex de instância única, DPI do processo, tela de inicialização, filtro de falhas, TerminateProcess,
-// mesa própria (a mesa é do explorer), tela de bloqueio própria (é o AuthUX), ganchos com DLL nos outros
-// programas (janelas.cpp) e esconder a barra do Windows (ela somos nós).
-int shell::RodarNativo(HINSTANCE hi, const std::wstring& dirBin, const std::wstring& logPath) {
- nativo = true;
- SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
- shell::inst = hi;
- shell::dir = dirBin;
- g_log = _wfsopen(logPath.c_str(), L"w, ccs=UTF-8", _SH_DENYNO);
- Log(L"Shell nativo iniciando dentro do explorer (pid %lu), pasta %ls", GetCurrentProcessId(), dirBin.c_str());
- OleInitialize(nullptr);
- ctxmenu::Init(hi, nullptr); // sem log: o menu gravava e esperava o disco na thread da interface (mesma trava do arquivo do Log)
- if (!ui::Init()) { Log(L"erro: Direct2D/DirectWrite"); return 1; }
- LoadSettings();
- SystemParametersInfoW(SPI_GETWORKAREA, 0, &g_origWork, 0);
-
- simbolo::Dir() = shell::dir.substr(0, shell::dir.find_last_of(L'\\')) + L"\\icones\\simbolos";
- simbolo::Preload(); // os SF Symbols numa thread: desenhar nunca espera o disco (simbolos.h)
- apps::Load(shell::dir + L"\\" EXE_FINDER);
- apps::Refresh();
-
- WNDCLASSW mc{}; mc.lpfnWndProc = MsgProc; mc.hInstance = hi; mc.lpszClassName = L"ShellMensagens";
- RegisterClassW(&mc);
- g_msg = CreateWindowExW(WS_EX_TOOLWINDOW, mc.lpszClassName, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, hi, nullptr);
- apps::ours.push_back(g_msg);
- ChangeWindowMessageFilterEx(g_msg, RegisterWindowMessageW(L"WacOSMenuVidro"), MSGFLT_ALLOW, nullptr);
- atualizacao::Start(g_msg); // aviso de versão nova no GitHub (90 s depois e a cada 6 h)
-
- if (!menubar::Create(hi) || !dock::Create(hi) || !launchpad::Create(hi) || !missioncontrol::Create(hi) || !central::Create(hi) || !spotlight::Create(hi) || !alertas::Create(hi) || !sobre::Create(hi) || !seletor::Create(hi) || !som::Create(hi)) { Log(L"erro criando as janelas"); Restore(); return 1; }
- instalados::Start();
- indice::Start();
- revelar::Start();
- ponteiro::Start();
- ponteiro::TemaLeopard(liquid::Leopard());
- genio::Create(hi);
- widgets::Create(hi);
- notificacoes::Create(hi);
- ilha::Create(hi);
- notarapida::Create(hi);
- progresso::Create(hi);
- cantos::Start();
- tray::Start([] { menubar::Update(); }); // nativo: sem janela; os ícones chegam por tray::DoExplorer
- menus::Start();
- dialogs::Start();
- pastas::Start();
- if (GetFileAttributesW(L"C:\\Users\\Public\\MacMesa-desligada.txt") == INVALID_FILE_ATTRIBUTES)
- mesa::Start(hi, g_msg); // nativo: a mesa do projeto por cima da do Explorador (mesmo processo)
- else Log(L"MacMesa-desligada.txt: a mesa fica com o Windows");
- limites::Start();
- sombras::Start();
- // Cantos do Mac (maiores que os 8 px do Windows), sombra e animações nas janelas com a barra padrão: só a
- // WacOSWindow.dll DENTRO dos programas consegue (autorizado pelo usuário em 12/11/2026, "pode injetar").
- // Ela cuida das janelas de barra padrão; as de barra própria (Chrome, Bloco de Notas...) continuam com barras.cpp.
- // C:\Users\Public\MacInjecao-desligada.txt volta a não carregar nada nos outros programas.
- if (GetFileAttributesW(L"C:\\Users\\Public\\MacInjecao-desligada.txt") == INVALID_FILE_ATTRIBUTES) janelas::Start();
- else Log(L"MacInjecao-desligada.txt: nada é carregado nos outros programas (cantos de 8 px)");
- barras::Start(); // nativo: barra de título do Mac por fora (sem nada dentro dos outros programas)
- shell::ApplyWorkArea();
-
- WM_SHELLHOOK = RegisterWindowMessageW(L"SHELLHOOK");
- RegisterShellHookWindow(g_msg);
- g_fullHook = shell::Setting(L"tecla_windows_launchpad", L"1") == L"1";
- g_macKeys = shell::Setting(L"atalhos_mac", L"1") == L"1";
- g_capturaExe = GetFileAttributesW((shell::dir + L"\\" EXE_SCREENSHOT).c_str()) != INVALID_FILE_ATTRIBUTES;
- EnsureScreenshot();
- g_volumeKeys = shell::Setting(L"volume_mac", L"1") == L"1";
- if (g_fullHook || g_volumeKeys) std::thread(KeyThread).detach();
- SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr, OnWinEvent, 0, 0, WINEVENT_OUTOFCONTEXT);
- jogo::GanchoPosicao(OnWinEvent, WINEVENT_OUTOFCONTEXT); // sai no modo jogo (jogo.cpp)
- SetTimer(g_msg, 1, 1000, nullptr);
- SetTimer(g_msg, 9, 3000, nullptr);
- Log(L"pronto (nativo): %zu apps no Dock", apps::list.size());
- PreloadApps();
-
- MSG msg;
- sentinela::Start(g_msg); // interface parada 1 s ou mais: o shell.log diz onde (issue #32)
- while (GetMessageW(&msg, nullptr, 0, 0)) { mesa::Pulse(); sentinela::ultimaMsg = msg.message; sentinela::ultimaJanela = msg.hwnd; TranslateMessage(&msg); DispatchMessageW(&msg); } // pulso: ver mesa::Pulse
- Restore();
- DeregisterShellHookWindow(g_msg);
- Log(L"Shell nativo encerrado");
- LogDescarrega();
- if (g_log) fflush(g_log);
- return 0;
-}
+// Shell.exe: barra de menus + Dock + bandeja no estilo do macOS Sequoia, por cima do Explorador.
+// Enquanto roda, esconde a barra de tarefas do Windows e ajusta a área de trabalho; ao sair
+// (menu do logo → Sair do Shell, Ctrl+Alt+Shift+F12, ou erro), devolve tudo como estava.
+#include "shell.h"
+#include "../comum/simbolos.h"
+#include "../comum/ajustes_arquivo.h"
+#include "../menu/context_menu.h"
+#include <shlobj.h>
+#include <propkey.h>
+#include <dwmapi.h>
+#include <share.h>
+#include <cstdarg>
+#include <map>
+#include <thread>
+#include <atomic>
+#include <mutex>
+#include <condition_variable>
+#include <mmsystem.h>
+#pragma comment(lib, "winmm.lib")
+
+HINSTANCE shell::inst;
+std::wstring shell::dir;
+bool shell::nativo;
+
+DWORD shell::SemProprio() { return nativo ? 0 : WINEVENT_SKIPOWNPROCESS; }
+
+// Gancho global (WH_MOUSE_LL / WH_KEYBOARD_LL): o Windows segura cada tecla e cada clique do PC INTEIRO até a thread do
+// gancho responder. Numa CPU fraca e ocupada (i3, notebook na bateria) uma thread de prioridade normal esperava a vez
+// atrás do resto e o ponteiro/teclado engasgavam (issues #10 e #33). No modo jogo o processo vai para o EcoQoS (núcleos
+// lentos, jogo.cpp): a thread do gancho fica fora dele, senão cada tecla do jogo esperava um núcleo de eficiência acordar.
+void shell::ThreadDeGancho() {
+ SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
+ THREAD_POWER_THROTTLING_STATE s{ THREAD_POWER_THROTTLING_CURRENT_VERSION, THREAD_POWER_THROTTLING_EXECUTION_SPEED, 0 };
+ SetThreadInformation(GetCurrentThread(), ThreadPowerThrottling, &s, sizeof(s));
+}
+
+// Janela do próprio Shell. Fora do modo nativo: qualquer janela deste processo. No nativo o processo é o
+// explorer.exe: as janelas dele (pastas, Executar, avisos de copiar/apagar) são de app; nossas são só as
+// criadas com o módulo do Shell (a MacBarra.dll).
+bool shell::Nossa(HWND h) {
+ DWORD pid = 0; GetWindowThreadProcessId(h, &pid);
+ if (pid != GetCurrentProcessId()) return false;
+ if (!nativo) return true;
+ return (HINSTANCE)GetWindowLongPtrW(h, GWLP_HINSTANCE) == inst || apps::IsShellWindow(h);
+}
+
+static FILE* g_log;
+static HWND g_msg;
+static UINT WM_SHELLHOOK;
+static RECT g_origWork;
+static std::vector<HWND> g_hiddenBars;
+static std::map<std::wstring, std::wstring> g_settings;
+static bool g_quitting;
+static bool g_crashed, g_sessionEnding; // Restore() sem abrir o Explorador (o vigia ou o logoff cuidam)
+
+// ---- tecla Windows: sozinha abre o Launchpad; com outra tecla (Win+E, Win+D, Win+L...) segue para o
+// Windows normalmente. O gancho roda numa thread própria para nunca atrasar o teclado.
+const ULONG_PTR KEY_MARK = 0x53484C4C; // teclas que nós mesmos injetamos
+const UINT WM_APP_LAUNCHPAD = WM_APP + 30, WM_APP_SETTINGS = WM_APP + 31, WM_APP_MISSION = WM_APP + 32, WM_APP_SNAP = WM_APP + 33, WM_APP_SPOTLIGHT = WM_APP + 34, WM_APP_MONITOR = WM_APP + 35, WM_APP_SWITCH = WM_APP + 36, WM_APP_SWITCH_KEY = WM_APP + 37, WM_APP_SWITCH_END = WM_APP + 38;
+static std::atomic<bool> g_altTab; // seletor de apps aberto (Alt seguro desde o primeiro Tab)
+static HHOOK g_kbHook;
+static bool g_winDown, g_winCombo, g_winEaten, g_spaceHeld, g_tabHeld; // eaten: a combinação foi nossa (Win+I)
+static DWORD g_winVk, g_winAt; // At: quando a tecla Win desceu (ms do gancho)
+static bool g_winPassed; // uma tecla de combinação foi para o Windows (Win+V, Win+.): ele não abre o Iniciar ao soltar
+
+
+static void Inject(DWORD vk, bool up) {
+ INPUT in{ INPUT_KEYBOARD };
+ in.ki.wVk = (WORD)vk;
+ in.ki.dwFlags = (up ? KEYEVENTF_KEYUP : 0) | (vk == VK_LWIN || vk == VK_RWIN ? KEYEVENTF_EXTENDEDKEY : 0);
+ in.ki.dwExtraInfo = KEY_MARK;
+ SendInput(1, &in, sizeof(in));
+}
+
+const UINT WM_APP_LOCK = WM_APP + 39, WM_APP_WINKEY = WM_APP + 40, WM_APP_CAPTURA = WM_APP + 41;
+static bool g_capturaExe; // WacOSScreenshot.exe existe: Win+Shift+3/4/5/S são dela
+// Win+Q / Win+H / Win+W = Cmd+Q / Cmd+H / Cmd+W do Mac (encerrar o app, ocultar, fechar a janela).
+// Ajustes > Teclado > "Atalhos do Mac para apps" (atalhos_mac); desligado, os atalhos voltam ao Windows
+const UINT WM_APP_MACKEY = WM_APP + 43;
+const UINT WM_APP_EXPOSE = WM_APP + 44; // Ctrl+Win+↓: Exposé do app da frente (Ctrl+↓ no Mac)
+static volatile bool g_macKeys = true;
+static DWORD g_macKeyVk; // a tecla do atalho: soltar também é nosso (o app não vê uma letra solta)
+static DWORD g_capKey; // tecla do atalho da Captura de Tela ainda segurada
+static bool g_fullHook = true; // false: o gancho só existe para a tela de bloqueio (tecla Windows do Launchpad desligada)
+const UINT WM_APP_VOLUME = WM_APP + 42;
+const UINT WM_APP_SIRI = WM_APP + 45; // Win+S
+static bool g_volumeKeys = true; // ajuste volume_mac: teclas de volume com o aviso do Mac (0 = o Windows trata)
+
+static LRESULT CALLBACK KeyHook(int code, WPARAM w, LPARAM l) {
+ if (code == HC_ACTION && w == WM_KEYDOWN && ((KBDLLHOOKSTRUCT*)l)->vkCode == VK_CAPITAL) ilha::CapsLock(); // Ilha Dinâmica: aviso do Caps Lock
+ if (code == HC_ACTION && g_volumeKeys && !bloqueio::Active()) {
+ // teclas de volume (Fn + F-teclas): o Shell muda o volume em 16 passos e mostra o aviso do Mac
+ // (o painel do Windows não aparece). Só essas três teclas: os atalhos Ctrl+Alt+Shift+F11/F12 seguem livres.
+ auto* k = (KBDLLHOOKSTRUCT*)l;
+ // F14/F15: as teclas de brilho do teclado do Mac (e um atalho para teclados de PC com teclas programáveis); issue #38
+ // sem nenhuma tela com brilho controlável (já conferido), elas passam: F13-F24 são atalhos comuns de teclas de
+ // macro (cenas do OBS...) e antes sumiam no PC inteiro sem fazer nada
+ if (k->dwExtraInfo != KEY_MARK && (k->vkCode == VK_F14 || k->vkCode == VK_F15) && !central::SemBrilho()) {
+ if (w == WM_KEYDOWN || w == WM_SYSKEYDOWN) PostMessageW(g_msg, WM_APP_VOLUME, k->vkCode, 0);
+ return 1;
+ }
+ if (k->dwExtraInfo != KEY_MARK && (k->vkCode == VK_VOLUME_UP || k->vkCode == VK_VOLUME_DOWN || k->vkCode == VK_VOLUME_MUTE)) {
+ if (w == WM_KEYDOWN || w == WM_SYSKEYDOWN) {
+ bool fine = GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_MENU) < 0;
+ PostMessageW(g_msg, WM_APP_VOLUME, k->vkCode, fine);
+ }
+ return 1;
+ }
+ }
+ if (code == HC_ACTION && !bloqueio::Active()) {
+ // teclas de mídia (issue #37: com o WacOS aberto não faziam nada): o Shell manda o comando à sessão de mídia
+ // atual do Windows (a mesma que a Ilha mostra), sem depender do caminho do Explorador
+ auto* k = (KBDLLHOOKSTRUCT*)l;
+ DWORD vk = k->vkCode;
+ if (k->dwExtraInfo != KEY_MARK && (vk == VK_MEDIA_PLAY_PAUSE || vk == VK_MEDIA_NEXT_TRACK || vk == VK_MEDIA_PREV_TRACK || vk == VK_MEDIA_STOP)) {
+ if (w == WM_KEYDOWN || w == WM_SYSKEYDOWN) PostMessageW(g_msg, WM_APP_VOLUME, vk, 0);
+ return 1;
+ }
+ }
+ if (code == HC_ACTION && bloqueio::Active()) {
+ // tela travada: nada de Iniciar, Alt+Tab, Ctrl+Esc, Alt+Esc, Alt+F4, Ctrl+Shift+Esc (Ctrl+Alt+Del não dá para barrar)
+ auto* k = (KBDLLHOOKSTRUCT*)l;
+ bool alt = (k->flags & LLKHF_ALTDOWN) != 0, ctrl = GetAsyncKeyState(VK_CONTROL) < 0;
+ DWORD vk = k->vkCode;
+ if (vk == VK_LWIN || vk == VK_RWIN || vk == VK_APPS) { g_winDown = false; return 1; }
+ if ((alt && (vk == VK_TAB || vk == VK_ESCAPE || vk == VK_F4 || vk == VK_SPACE)) || (ctrl && vk == VK_ESCAPE)) return 1;
+ g_altTab = false;
+ return CallNextHookEx(g_kbHook, code, w, l);
+ }
+ if (!g_fullHook) return CallNextHookEx(g_kbHook, code, w, l);
+ if (code == HC_ACTION) {
+ auto* k = (KBDLLHOOKSTRUCT*)l;
+ if (k->dwExtraInfo != KEY_MARK) {
+ bool down = w == WM_KEYDOWN || w == WM_SYSKEYDOWN;
+ bool win = k->vkCode == VK_LWIN || k->vkCode == VK_RWIN;
+ if (win) {
+ auto mods = [] { return GetAsyncKeyState(VK_CONTROL) < 0 || GetAsyncKeyState(VK_SHIFT) < 0 || GetAsyncKeyState(VK_MENU) < 0; };
+ if (shell::nativo) {
+ // modo nativo (dentro do explorer): a tecla segue para o Windows; o atalho reinjetado daqui não
+ // valia (Win+R não abria). Sozinha, ao soltar, abre o Launchpad
+ if (down) {
+ if (!g_winDown) { g_winDown = true; g_winCombo = mods(); g_winEaten = false; g_spaceHeld = false; g_tabHeld = false; g_winVk = k->vkCode; g_winAt = k->time; }
+ } else if (g_winDown) {
+ g_winDown = false;
+ if (!g_winCombo && k->time - g_winAt <= 1000) PostMessageW(g_msg, WM_APP_LAUNCHPAD, 0, 0);
+ }
+ return CallNextHookEx(g_kbHook, code, w, l);
+ }
+ // A tecla segue para o Windows desde que desce (como no modo nativo): AltSnap e afins (Win + arrastar) a veem
+ // segurada, sem atraso e sem o Shell mexer no clique (issue #21: segurar o clique e devolver dava um tranco,
+ // o cursor não mudava e o clique direito às vezes travava). Os nossos atalhos (Win+Espaço, Win+I...) comem só a
+ // letra. Ao soltar, a tecla muda (0xE8) antes do Win: o Windows não vê um Win "sozinho" e o Iniciar não abre.
+ if (down) {
+ if (!g_winDown) {
+ g_winDown = true; g_winCombo = mods(); g_winEaten = false; g_spaceHeld = false; g_tabHeld = false; g_winVk = k->vkCode; g_winAt = k->time;
+ g_winPassed = false;
+ }
+ return CallNextHookEx(g_kbHook, code, w, l);
+ }
+ if (g_winDown) {
+ g_winDown = false;
+ if (!g_winCombo && k->time - g_winAt <= 1000) PostMessageW(g_msg, WM_APP_LAUNCHPAD, 0, 0); // sozinha: Launchpad/Spotlight
+ // Combinação que foi para o Windows (Win+V, Win+.): ele mesmo não abre o Iniciar, e a tecla muda chegava
+ // ao painel que acabou de abrir: o histórico da Área de Transferência piscava e fechava (issue #27, 22/11/2026)
+ if (g_winPassed && !g_winEaten) return CallNextHookEx(g_kbHook, code, w, l);
+ // a tecla muda e o soltar do Win vão juntos, nesta ordem: deixando o soltar de verdade passar, a muda
+ // (mandada daqui de dentro) chegava depois dele e o Iniciar abria
+ Inject(0xE8, false); Inject(0xE8, true);
+ Inject(k->vkCode, true);
+ return 1;
+ }
+ return CallNextHookEx(g_kbHook, code, w, l);
+ } else if (k->vkCode == VK_TAB && down && !g_winDown && GetAsyncKeyState(VK_MENU) < 0 && GetAsyncKeyState(VK_CONTROL) >= 0) {
+ // Alt+Tab: o seletor de apps do Mac no lugar do Alternar Tarefas do Windows. A tecla "muda"
+ // (0xE8) evita que o app da frente veja um Alt sozinho ao soltar e abra o menu dele
+ if (!g_altTab) { Inject(0xE8, false); Inject(0xE8, true); }
+ g_altTab = true;
+ PostMessageW(g_msg, WM_APP_SWITCH, GetAsyncKeyState(VK_SHIFT) < 0 ? (WPARAM)-1 : 1, 0);
+ return 1;
+ } else if (g_altTab && down && (k->vkCode == 'Q' || k->vkCode == 'H' || k->vkCode == VK_ESCAPE || k->vkCode == VK_LEFT || k->vkCode == VK_RIGHT)) {
+ if (k->vkCode == VK_ESCAPE) g_altTab = false;
+ PostMessageW(g_msg, WM_APP_SWITCH_KEY, k->vkCode, 0);
+ return 1;
+ } else if (g_altTab && !down && (k->vkCode == VK_LMENU || k->vkCode == VK_RMENU || k->vkCode == VK_MENU)) {
+ g_altTab = false;
+ PostMessageW(g_msg, WM_APP_SWITCH_END, 0, 0); // o Alt solto segue para o Windows normalmente
+ } else if (k->vkCode == VK_ESCAPE && down && GetAsyncKeyState(VK_CONTROL) < 0 && GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_MENU) >= 0) {
+ // Ctrl+Shift+Esc: o nosso Monitor de Atividade no lugar do Gerenciador de Tarefas
+ PostMessageW(g_msg, WM_APP_MONITOR, 0, 0);
+ return 1;
+ } else if (k->vkCode == VK_ESCAPE && down && GetAsyncKeyState(VK_CONTROL) < 0 && GetAsyncKeyState(VK_MENU) < 0 && GetAsyncKeyState(VK_SHIFT) >= 0) {
+ // Ctrl+Alt+Esc: Forçar Encerrar Aplicativos (Command+Option+Esc do Mac)
+ PostMessageW(g_msg, WM_APP_MONITOR, 1, 0);
+ return 1;
+ } else if (k->vkCode == VK_SPACE && g_winDown && (!g_winCombo || g_winEaten)) {
+ // Win+Espaço: o Spotlight (Cmd+Espaço no Mac; no Windows trocaria o idioma do teclado).
+ // Segurando o Win, cada Espaço abre/fecha de novo; repetição de tecla segurada não conta e
+ // nenhum Espaço chega ao app de baixo
+ if (down && !g_spaceHeld) PostMessageW(g_msg, WM_APP_SPOTLIGHT, 0, 0);
+ g_spaceHeld = down;
+ g_winCombo = g_winEaten = true;
+ return 1;
+ } else if (k->vkCode == VK_TAB && g_winDown && (!g_winCombo || g_winEaten)) {
+ // Win+Tab: o Mission Control (no lugar da Visão de Tarefas). Segurando o Win, cada Tab abre/fecha
+ // de novo (igual ao Espaço); repetição de tecla segurada não conta
+ if (down && !g_tabHeld) PostMessageW(g_msg, WM_APP_MISSION, 0, 0);
+ g_tabHeld = down;
+ g_winCombo = g_winEaten = true;
+ return 1;
+ } else if (g_winDown && down && (k->vkCode == VK_F12 || k->vkCode == VK_F8) && liquid::Leopard()) {
+ // Leopard: Win+F12 = Dashboard (o F12 do Mac), Win+F8 = Spaces (o F8 do Mac). Só com o Win: o F12 sozinho
+ // continua dos apps (ferramentas do navegador)
+ static UINT openPanel = RegisterWindowMessageW(L"ShellAbrirPainel");
+ PostMessageW(g_msg, openPanel, k->vkCode == VK_F12 ? 16 : 17, 0);
+ g_winCombo = g_winEaten = true;
+ return 1;
+ } else if (g_winDown && down && !g_winCombo && k->vkCode == 'S' && GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_CONTROL) >= 0 &&
+ GetAsyncKeyState(VK_MENU) >= 0 && siri::Pronta()) {
+ // Win+S: a Siri com o campo para digitar (no Windows, o atalho da busca/assistente); de novo fecha
+ g_winCombo = g_winEaten = true;
+ PostMessageW(g_msg, WM_APP_SIRI, 0, 0);
+ return 1;
+ } else if (g_winDown && down && !g_winCombo && (k->vkCode == 'I' || k->vkCode == VK_TAB)) {
+ // Win+I: o nosso Ajustes do Sistema; Win+Tab: o Mission Control (no lugar da Visão de Tarefas)
+ g_winCombo = g_winEaten = true;
+ PostMessageW(g_msg, k->vkCode == VK_TAB ? WM_APP_MISSION : WM_APP_SETTINGS, 0, 0);
+ return 1;
+ } else if (!shell::nativo && g_winDown && down && (k->vkCode == VK_LEFT || k->vkCode == VK_RIGHT) && GetAsyncKeyState(VK_CONTROL) >= 0 &&
+ GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_MENU) >= 0) {
+ // Win+←/→: metade da tela (o encaixe do Windows fica desligado enquanto o Shell roda: encaixe.cpp)
+ if (!g_winCombo) g_winCombo = g_winEaten = true;
+ PostMessageW(g_msg, WM_APP_SNAP, k->vkCode, 0);
+ return 1;
+ } else if (g_winDown && down && !g_winCombo && (k->vkCode == VK_UP || k->vkCode == VK_DOWN) &&
+ GetPropW(GetForegroundWindow(), L"MacJanela")) {
+ // Win+↑/↓ em janela com a barra do Mac: sem o botão de maximizar o Windows ignora; fazemos nós
+ g_winCombo = g_winEaten = true;
+ PostMessageW(g_msg, WM_APP_SNAP, k->vkCode, 0);
+ return 1;
+ } else if (!shell::nativo && g_winDown && down && k->vkCode == 'Q' && GetAsyncKeyState(VK_CONTROL) < 0 && GetAsyncKeyState(VK_MENU) >= 0) {
+ // Ctrl+Win+Q: o atalho do Mac (Control+Command+Q) para bloquear (o bloqueio do Windows)
+ if (!g_winCombo) g_winCombo = g_winEaten = true;
+ PostMessageW(g_msg, WM_APP_LOCK, 0, 0);
+ return 1;
+ } else if (g_winDown && (k->vkCode == VK_UP || k->vkCode == VK_DOWN) && GetAsyncKeyState(VK_CONTROL) < 0 &&
+ GetAsyncKeyState(VK_MENU) >= 0 && GetAsyncKeyState(VK_SHIFT) >= 0) {
+ // Ctrl+Win+↑ / ↓ = Ctrl+↑ / ↓ do Mac: Mission Control / Exposé do app da frente (Ctrl+Win+←/→
+ // já trocam de Mesa, como Ctrl+←/→ no Mac). A repetição da tecla segurada não abre de novo
+ if (down && g_macKeyVk != k->vkCode) PostMessageW(g_msg, k->vkCode == VK_UP ? WM_APP_MISSION : WM_APP_EXPOSE, 0, 0);
+ g_macKeyVk = down ? k->vkCode : 0;
+ if (!g_winCombo) g_winCombo = g_winEaten = true;
+ return 1;
+ } else if (g_macKeyVk && k->vkCode == g_macKeyVk && !down) {
+ g_macKeyVk = 0;
+ return 1;
+ } else if (g_macKeys && g_winDown && down && (!g_winCombo || g_winEaten) && (k->vkCode == 'Q' || k->vkCode == 'H' || k->vkCode == 'W') &&
+ GetAsyncKeyState(VK_CONTROL) >= 0 && GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_MENU) >= 0) {
+ // Win+Q encerra o app da frente, Win+H oculta, Win+W fecha a janela (como Cmd no Mac). Segurando o
+ // Win, cada toque vale de novo; a repetição da tecla segurada não conta
+ if (g_macKeyVk != k->vkCode) PostMessageW(g_msg, WM_APP_MACKEY, k->vkCode, 0);
+ g_macKeyVk = k->vkCode;
+ g_winCombo = g_winEaten = true;
+ return 1;
+ } else if (g_capKey && k->vkCode == g_capKey && !down) {
+ g_capKey = 0; // fim do atalho da Captura de Tela: a tecla solta também é nossa
+ return 1;
+ } else if (g_winDown && down && GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_MENU) >= 0 &&
+ (k->vkCode == '3' || k->vkCode == '4' || k->vkCode == '5' || k->vkCode == 'S') && g_capturaExe) {
+ // Win+Shift+3/4/5 (Cmd+Shift+3/4/5 do Mac) e Win+Shift+S: a nossa Captura de Tela
+ // (WacOSScreenshot.exe) no lugar da Ferramenta de Captura; com Ctrl, só área de transferência.
+ // A tecla segurada (repetição) não abre de novo; a tecla muda (0xE8) faz o Windows não ver
+ // um Win sozinho ao soltar (o Win e o Shift já foram devolvidos a ele: combinação)
+ if (g_capKey != k->vkCode) {
+ g_capKey = k->vkCode;
+ Inject(0xE8, false); Inject(0xE8, true);
+ int kind = k->vkCode == 'S' ? 4 : (int)(k->vkCode - '0');
+ PostMessageW(g_msg, WM_APP_CAPTURA, kind, GetAsyncKeyState(VK_CONTROL) < 0 ? 1 : 0);
+ }
+ return 1;
+ } else if (g_winDown && down && k->vkCode == 'S' && GetAsyncKeyState(VK_SHIFT) < 0 && GetAsyncKeyState(VK_CONTROL) >= 0 && mesa::Standalone()) {
+ // Win+Shift+S sem a nossa Captura de Tela: a Ferramenta de Captura do Windows (quem atende é
+ // o Explorador quando ele é o shell; sem ele, fazemos nós)
+ PostMessageW(g_msg, WM_APP_WINKEY, 'S', 0);
+ return 1;
+ } else if (g_winDown && down && !g_winCombo && !shell::nativo && k->vkCode == 'E' && GetAsyncKeyState(VK_SHIFT) >= 0 && GetAsyncKeyState(VK_CONTROL) >= 0) {
+ // Win+E com o Explorador rodando (explorer=fundo): ele abria a página "Início" dele, que não é pasta de
+ // disco e o Finder não trocava (17/11/2026). O Shell atende sempre: Finder (ou o Explorador, se
+ // "Abrir pastas no Finder" estiver desligado — mesa::WinKey decide)
+ g_winCombo = g_winEaten = true;
+ PostMessageW(g_msg, WM_APP_WINKEY, 'E', 0);
+ return 1;
+ } else if (g_winDown && down && !g_winCombo && !shell::nativo && k->vkCode == 'D') {
+ // Win+D é sempre nosso: com o Explorador de fundo, o "mostrar a área de trabalho" dele punha a mesa
+ // DELE na frente e a nossa voltava por cima em seguida (piscava, os widgets sumiam e voltavam)
+ g_winCombo = g_winEaten = true;
+ PostMessageW(g_msg, WM_APP_WINKEY, 'D', 0);
+ return 1;
+ } else if (g_winDown && down && !g_winCombo && mesa::Standalone() && (k->vkCode == 'E' || k->vkCode == 'R' || k->vkCode == 'D')) {
+ // sem o Explorador ninguém trata Win+E/R/D: fazemos nós (Finder, Executar, mostrar a mesa)
+ g_winCombo = g_winEaten = true;
+ PostMessageW(g_msg, WM_APP_WINKEY, k->vkCode, 0);
+ return 1;
+ } else if (g_winDown && down && !g_winCombo && shell::nativo) {
+ g_winCombo = true; // nativo: a tecla Windows já foi para o Windows; esta segue também
+ } else if (g_winDown && down && !g_winCombo) {
+ // combinação do Windows: a tecla Win já foi para ele; esta segue também
+ g_winCombo = true;
+ g_winPassed = true;
+ }
+ }
+ }
+ return CallNextHookEx(g_kbHook, code, w, l);
+}
+
+static void KeyThread() {
+ shell::ThreadDeGancho();
+ g_kbHook = SetWindowsHookExW(WH_KEYBOARD_LL, KeyHook, GetModuleHandleW(nullptr), 0);
+ MSG m;
+ while (GetMessageW(&m, nullptr, 0, 0)) {}
+ if (g_kbHook) UnhookWindowsHookEx(g_kbHook);
+}
+
+// O log vai para o disco numa thread própria. Gravando direto (fwprintf + fflush a cada linha), a thread da interface
+// ficava presa no WriteFile quando o disco demorava (torrent, antivírus, agente de monitoramento): o vigia via o Shell
+// sem responder por 5 s e o reiniciava, várias vezes seguidas (22/11/2026: as duas pilhas tiradas no travamento
+// estavam no Log -> fflush -> WriteFile, chamado pelo vidro real).
+static std::mutex g_logMx, g_logDisco;
+static std::condition_variable g_logCv;
+static std::wstring g_logFila;
+static void LogGrava() { // o que está na fila vai para o arquivo (só uma thread grava de cada vez)
+ std::wstring s;
+ { std::lock_guard<std::mutex> l(g_logMx); s.swap(g_logFila); }
+ if (s.empty() || !g_log) return;
+ std::lock_guard<std::mutex> d(g_logDisco);
+ fputws(s.c_str(), g_log); fflush(g_log);
+}
+static void EsperaAjustes();
+static void LogDescarrega() { EsperaAjustes(); LogGrava(); } // fim do Shell: o que faltou vai junto (log e ajustes.txt)
+
+void Log(const wchar_t* fmt, ...) {
+ if (!g_log) return;
+ SYSTEMTIME st; GetLocalTime(&st);
+ wchar_t pre[16]; swprintf_s(pre, L"%02d:%02d:%02d ", st.wHour, st.wMinute, st.wSecond);
+ va_list a; va_start(a, fmt);
+ va_list b; va_copy(b, a);
+ int n = _vscwprintf(fmt, a);
+ std::wstring linha;
+ if (n > 0) { linha.resize((size_t)n + 1); vswprintf_s(linha.data(), linha.size(), fmt, b); linha.resize((size_t)n); }
+ va_end(b); va_end(a);
+ static std::once_flag once;
+ std::call_once(once, [] {
+ std::thread([] {
+ for (;;) {
+ { std::unique_lock<std::mutex> l(g_logMx); g_logCv.wait(l, [] { return !g_logFila.empty(); }); }
+ LogGrava();
+ }
+ }).detach();
+ });
+ {
+ std::lock_guard<std::mutex> l(g_logMx);
+ if (g_logFila.size() < 4 * 1024 * 1024) { g_logFila += pre; g_logFila += linha; g_logFila += L'\n'; } // disco parado de vez: não cresce sem fim
+ }
+ g_logCv.notify_one();
+}
+
+// g_settings é lido de várias threads (vidro, índice, ilha, widgets...) enquanto a interface relê o arquivo
+// (LoadSettings troca o mapa inteiro): sem trava, a leitura podia pegar o mapa no meio da troca e derrubar o Shell
+static SRWLOCK g_settingsLock = SRWLOCK_INIT;
+std::wstring shell::Setting(const wchar_t* key, const wchar_t* def) {
+ AcquireSRWLockShared(&g_settingsLock);
+ auto it = g_settings.find(key);
+ std::wstring r = it != g_settings.end() ? it->second : (def ? def : L"");
+ ReleaseSRWLockShared(&g_settingsLock);
+ return r;
+}
+
+static std::wstring SettingsPath() {
+ PWSTR p = nullptr;
+ std::wstring f;
+ if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) { f = std::wstring(p) + L"\\Shell"; CoTaskMemFree(p); }
+ CreateDirectoryW(f.c_str(), nullptr);
+ return f + L"\\ajustes.txt";
+}
+
+// O ajustes.txt vai para o disco numa thread (como o log). Gravando aqui, cada mudança (Dock, Central de Controle,
+// Launchpad, widgets...) esperava o disco na thread da interface: num HD com o antivírus olhando, 20 a 200 ms de tela
+// parada a cada clique (issue #10, Core i3 com HD). O valor vale na hora (g_settings); o arquivo segue logo depois, e
+// várias mudanças seguidas viram uma gravação só. Quem relê o arquivo (LoadSettings) e a saída do Shell esperam a fila.
+static std::mutex g_ajMx;
+static std::condition_variable g_ajCv;
+static std::map<std::wstring, std::wstring> g_ajMapa; // os ajustes inteiros a gravar (os mais novos)
+static bool g_ajTem = false, g_ajOcupado = false;
+static void EsperaAjustes() {
+ std::unique_lock<std::mutex> l(g_ajMx);
+ g_ajCv.wait_for(l, std::chrono::seconds(3), [] { return !g_ajTem && !g_ajOcupado; });
+}
+void shell::SetSetting(const wchar_t* key, const std::wstring& value) {
+ std::map<std::wstring, std::wstring> copia;
+ AcquireSRWLockExclusive(&g_settingsLock);
+ g_settings[key] = value;
+ copia = g_settings;
+ ReleaseSRWLockExclusive(&g_settingsLock);
+ // na thread de gravação, atômico (.tmp + troca): quem lê no meio não vê o arquivo vazio
+ { std::lock_guard<std::mutex> l(g_ajMx); g_ajMapa = std::move(copia); g_ajTem = true; }
+ static std::once_flag umaVez;
+ std::call_once(umaVez, [] {
+ std::thread([] {
+ for (;;) {
+ std::map<std::wstring, std::wstring> m;
+ {
+ std::unique_lock<std::mutex> l(g_ajMx);
+ g_ajCv.wait(l, [] { return g_ajTem; });
+ m.swap(g_ajMapa); g_ajTem = false; g_ajOcupado = true;
+ }
+ ajarq::Gravar(SettingsPath(), m);
+ { std::lock_guard<std::mutex> l(g_ajMx); g_ajOcupado = false; }
+ g_ajCv.notify_all();
+ }
+ }).detach();
+ });
+ g_ajCv.notify_all();
+}
+
+// Calculadora (Calculadora.exe) no lugar da Calculadora do Windows: Launchpad, Spotlight e Dock passam
+// o alvo (AUMID, atalho ou .exe) por aqui. Sem o Calculadora.exe, segue a do Windows (devolve false).
+bool shell::OpenCalculator(const std::wstring& target) {
+ std::wstring t = target;
+ for (auto& c : t) c = towlower(c);
+ auto ends = [&](const wchar_t* s) { size_t n = wcslen(s); return t.size() >= n && t.compare(t.size() - n, n, s) == 0; };
+ bool calc = t.find(L"microsoft.windowscalculator") != std::wstring::npos || t == L"calc.exe" || t == L"calc" ||
+ ends(L"\\calc.exe") || ends(L"calculatorapp.exe") || ends(L"\\calculadora.exe") || ends(L"\\wacoscalculator.exe");
+ if (!calc) return false;
+ std::wstring exe = shell::dir + L"\\" EXE_CALCULATOR;
+ if (GetFileAttributesW(exe.c_str()) == INVALID_FILE_ATTRIBUTES) return false;
+ shell::Abrir(L"open", exe.c_str());
+ return true;
+}
+
+// Monitor de Atividade (MonitorAtividade.exe); sem ele, o Gerenciador de Tarefas do Windows
+void shell::OpenMonitor() {
+ std::wstring exe = shell::dir + L"\\" EXE_MONITOR;
+ if (GetFileAttributesW(exe.c_str()) == INVALID_FILE_ATTRIBUTES) exe = L"taskmgr.exe";
+ shell::Abrir(L"open", exe.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
+}
+
+// Forçar Encerrar Aplicativos (WacOSForceQuit.exe); sem ele, o Monitor de Atividade
+void shell::OpenForceQuit(bool memory) {
+ std::wstring exe = shell::dir + L"\\" EXE_FORCEQUIT;
+ if (GetFileAttributesW(exe.c_str()) == INVALID_FILE_ATTRIBUTES) { shell::OpenMonitor(); return; }
+ AllowSetForegroundWindow(ASFW_ANY); // aberta pela pressão de memória, sem clique: precisa vir para a frente
+ shell::Abrir(L"open", exe.c_str(), memory ? L"--memoria" : nullptr, nullptr, SW_SHOWNORMAL);
+}
+
+void shell::Sound(const wchar_t* name) {
+ std::wstring root = shell::dir.substr(0, shell::dir.find_last_of(L'\\')); // a pasta do projeto (bin fica dentro dela)
+ PlaySoundW((root + L"\\sons\\mac\\" + name + L".wav").c_str(), nullptr, SND_FILENAME | SND_ASYNC | SND_NODEFAULT);
+}
+
+void shell::OpenSettings(const std::wstring& page) {
+ std::wstring args = page.empty() ? L"" : (page.rfind(L"ms-settings:", 0) == 0 ? page : L"--pagina=" + page);
+ shell::Abrir(L"open", (shell::dir + L"\\" EXE_SETTINGS).c_str(), args.c_str());
+}
+
+// ShellExecute numa thread: na thread da interface ele chegou a segurar o Shell 3,2 s (abrir o Ajustes pela Ilha com o
+// disco ocupado; pilha de 22/11/2026 19:54, issue #32). A thread espera o ShellExecute terminar (SEE_MASK_NOASYNC).
+std::wstring shell::PastaDoApp(const std::wstring& alvo) {
+ auto pastaDoExe = [](std::wstring p) -> std::wstring {
+ if (p.size() > 1 && p.front() == L'"') p = p.substr(1, p.find(L'"', 1) - 1);
+ if (p.size() < 5 || _wcsicmp(p.c_str() + p.size() - 4, L".exe") || p.find(L":\\") == std::wstring::npos) return L"";
+ size_t b = p.find_last_of(L'\\');
+ return b == std::wstring::npos ? L"" : p.substr(0, b);
+ };
+ if (std::wstring d = pastaDoExe(alvo); !d.empty()) return d;
+ // item da pasta Aplicativos ou atalho: o caminho do programa que ele abre (System.Link.TargetParsingPath)
+ std::wstring r;
+ IShellItem2* it = nullptr;
+ if (SUCCEEDED(SHCreateItemFromParsingName(alvo.c_str(), nullptr, IID_PPV_ARGS(&it)))) {
+ PWSTR t = nullptr;
+ if (SUCCEEDED(it->GetString(PKEY_Link_TargetParsingPath, &t)) && t) { r = pastaDoExe(t); CoTaskMemFree(t); }
+ it->Release();
+ }
+ return r;
+}
+
+void shell::Abrir(const wchar_t* verb, const wchar_t* file, const wchar_t* args, const wchar_t* dir, int show) {
+ if (!file) return;
+ AllowSetForegroundWindow(ASFW_ANY); // o app aberto pela thread vem para a frente como antes
+ std::wstring v = verb ? verb : L"", f = file, a = args ? args : L"", d = dir ? dir : L"";
+ if (d.empty() && f.size() > 4 && !_wcsicmp(f.c_str() + f.size() - 4, L".exe")) d = shell::PastaDoApp(f); // a pasta do programa (issue #38)
+ bool temVerbo = verb != nullptr;
+ std::thread([v, f, a, d, show, temVerbo] {
+ HRESULT ci = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
+ SHELLEXECUTEINFOW se{ sizeof(se) };
+ se.fMask = SEE_MASK_NOASYNC;
+ se.lpVerb = temVerbo ? v.c_str() : nullptr;
+ se.lpFile = f.c_str();
+ se.lpParameters = a.empty() ? nullptr : a.c_str();
+ se.lpDirectory = d.empty() ? nullptr : d.c_str();
+ se.nShow = show;
+ if (!ShellExecuteExW(&se)) Log(L"abrir: não abriu %ls (%lu)", f.c_str(), GetLastError());
+ if (SUCCEEDED(ci)) CoUninitialize();
+ }).detach();
+}
+
+// trabalho feito numa thread devolve o resultado para a interface (dock: a Lixeira cheia ou vazia)
+static const UINT WM_NA_INTERFACE = WM_APP + 60;
+void shell::NaInterface(std::function<void()> f) {
+ auto* p = new std::function<void()>(std::move(f));
+ if (!g_msg || !PostMessageW(g_msg, WM_NA_INTERFACE, 0, (LPARAM)p)) delete p;
+}
+
+static void LoadSettings() {
+ EsperaAjustes(); // uma gravação nossa ainda na fila: ela vai antes (senão a releitura traria o valor antigo)
+ PWSTR p = nullptr;
+ if (FAILED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) return;
+ std::wstring f = std::wstring(p) + L"\\Shell\\ajustes.txt";
+ CoTaskMemFree(p);
+ // Do zero a cada leitura: uma linha tirada do arquivo (ajuste de volta ao padrão) continuava valendo com o valor
+ // antigo até reiniciar o Shell (23/11/2026: ocultar=1 apagado deixava o Dock sem reserva na área de trabalho).
+ // Linhas de qualquer tamanho (apps_ordem passava de 512 caracteres e era cortada).
+ std::map<std::wstring, std::wstring> novo;
+ if (!ajarq::Ler(f, novo)) return;
+ AcquireSRWLockExclusive(&g_settingsLock);
+ g_settings.swap(novo);
+ ReleaseSRWLockExclusive(&g_settingsLock);
+ backdrop::Reload(); // Transparência e Efeitos (Liquid Glass, reduzir transparência, tinta)
+ anim::reduceMotion = shell::Setting(L"reduzir_movimento", L"0") == L"1";
+}
+
+// ---- barra de tarefas do Windows: escondida enquanto o shell roda
+static void HideTaskbars() {
+ if (shell::nativo) return; // nativo: a barra do Windows é o próprio Shell (a MacBarra a mantém escondida)
+ EnumWindows([](HWND h, LPARAM) -> BOOL {
+ wchar_t c[64]; GetClassNameW(h, c, 64);
+ if ((!wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd")) && !apps::IsShellWindow(h)) {
+ // sem esperar o Explorador: travado ou ainda subindo, ele segurava o Shell aqui (o vigia reiniciava o
+ // Shell em ciclo, 09/11/2026)
+ if (IsWindowVisible(h)) ShowWindowAsync(h, SW_HIDE);
+ if (std::find(g_hiddenBars.begin(), g_hiddenBars.end(), h) == g_hiddenBars.end()) g_hiddenBars.push_back(h);
+ }
+ return TRUE;
+ }, 0);
+}
+
+// A barra do Explorador que ele mostra de novo (Win, notificação, Explorador reiniciado) some na hora. Antes só o tique de
+// 1 s a escondia: ela "aparecia às vezes" por até um segundo (issue #40)
+static void CALLBACK OnBarraWindows(HWINEVENTHOOK, DWORD, HWND h, LONG obj, LONG child, DWORD, DWORD) {
+ if (obj != OBJID_WINDOW || child != CHILDID_SELF || g_quitting || shell::nativo || !h) return;
+ wchar_t c[32] = {}; GetClassNameW(h, c, 32);
+ if (wcscmp(c, L"Shell_TrayWnd") && wcscmp(c, L"Shell_SecondaryTrayWnd")) return;
+ DWORD pid = 0; GetWindowThreadProcessId(h, &pid);
+ if (pid == GetCurrentProcessId() || apps::IsShellWindow(h)) return;
+ ShowWindowAsync(h, SW_HIDE);
+ if (std::find(g_hiddenBars.begin(), g_hiddenBars.end(), h) == g_hiddenBars.end()) g_hiddenBars.push_back(h);
+}
+
+static void ShowTaskbars() {
+ for (HWND h : g_hiddenBars) if (IsWindow(h)) ShowWindowAsync(h, SW_SHOWNOACTIVATE);
+ g_hiddenBars.clear();
+ // issue #37 (a barra do Windows sumia ao sair): o Explorador que reiniciou com o Shell aberto cria uma barra nova,
+ // que não está na lista acima. Toda barra do Explorador escondida volta.
+ EnumWindows([](HWND h, LPARAM) -> BOOL {
+ wchar_t c[64] = {}; GetClassNameW(h, c, 64);
+ if ((!wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd")) && !apps::IsShellWindow(h) && !IsWindowVisible(h)) {
+ DWORD pid = 0; GetWindowThreadProcessId(h, &pid);
+ if (pid != GetCurrentProcessId()) ShowWindowAsync(h, SW_SHOWNOACTIVATE);
+ }
+ return TRUE;
+ }, 0);
+}
+
+// Barra do Windows nos outros monitores: só esconder não segurava (o Explorador a mostrava de novo e ela
+// reservava espaço). Enquanto o Shell roda, desliga "Mostrar a barra de tarefas em todos os monitores"
+// (HKCU ...\Explorer\Advanced\MMTaskbarEnabled = 0, a mesma chave da Configuração do Windows). O valor de antes
+// fica em ajustes.txt (barra_windows_monitores_antes: 0, 1 ou "x" = não existia) e volta ao sair.
+static const wchar_t* MM_KEY = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";
+
+static void TellExplorerTray() { // o Explorador relê o ajuste da barra (como a Configuração faz)
+ std::thread([] {
+ EnumWindows([](HWND h, LPARAM) -> BOOL {
+ wchar_t c[64] = {}; GetClassNameW(h, c, 64);
+ if (!wcscmp(c, L"Shell_TrayWnd") && !apps::IsShellWindow(h))
+ SendMessageTimeoutW(h, WM_SETTINGCHANGE, 0, (LPARAM)L"TraySettings", SMTO_ABORTIFHUNG, 1000, nullptr);
+ return TRUE;
+ }, 0);
+ }).detach();
+}
+
+// Barra do Windows em "ocultar automaticamente" (issue #37): com ela escondida pelo Shell, o Explorador devolvia a área
+// de trabalho para a tela inteira ~6 vezes por segundo, o Shell punha a dele de volta, e as janelas maximizadas eram
+// reencaixadas a cada vez (as travadas). Ao sair, a barra ficava num estado estranho e não voltava. Enquanto o Shell
+// roda, o ocultar automático fica desligado (a barra está escondida de qualquer jeito) e volta ao sair; o estado de
+// antes fica em ajustes.txt (barra_windows_ocultar_antes).
+static UINT_PTR EstadoDaBarra(bool set, UINT_PTR estado) {
+ APPBARDATA d{ sizeof(d) };
+ d.lParam = (LPARAM)estado;
+ return SHAppBarMessage(set ? ABM_SETSTATE : ABM_GETSTATE, &d);
+}
+static void OcultarAutomaticoOff() {
+ UINT_PTR st = EstadoDaBarra(false, 0);
+ if (!(st & ABS_AUTOHIDE)) return;
+ if (shell::Setting(L"barra_windows_ocultar_antes", L"").empty())
+ shell::SetSetting(L"barra_windows_ocultar_antes", std::to_wstring((unsigned)st));
+ EstadoDaBarra(true, st & ~(UINT_PTR)ABS_AUTOHIDE);
+ Log(L"barra do Windows: ocultar automaticamente desligado enquanto o Shell roda (estado %u)", (unsigned)st);
+}
+static void OcultarAutomaticoRestore() {
+ std::wstring before = shell::Setting(L"barra_windows_ocultar_antes", L"");
+ if (before.empty()) return;
+ EstadoDaBarra(true, (UINT_PTR)_wtoi(before.c_str()));
+ shell::SetSetting(L"barra_windows_ocultar_antes", L"");
+ Log(L"barra do Windows: ocultar automaticamente devolvido (estado %ls)", before.c_str());
+}
+
+static void SecondaryTaskbarsOff() {
+ if (shell::nativo) return;
+ OcultarAutomaticoOff();
+ DWORD v = 0, cb = sizeof(v);
+ bool had = RegGetValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled", RRF_RT_REG_DWORD, nullptr, &v, &cb) == ERROR_SUCCESS;
+ if (had && v == 0) return; // já desligado (pelo usuário ou por nós antes)
+ if (shell::Setting(L"barra_windows_monitores_antes", L"").empty())
+ shell::SetSetting(L"barra_windows_monitores_antes", had ? std::to_wstring(v) : L"x");
+ DWORD zero = 0;
+ if (RegSetKeyValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled", REG_DWORD, &zero, sizeof(zero)) == ERROR_SUCCESS) {
+ Log(L"registro: HKCU\\%ls\\MMTaskbarEnabled = 0 (antes: %ls) - barra do Windows só no monitor principal", MM_KEY, had ? std::to_wstring(v).c_str() : L"não existia");
+ TellExplorerTray();
+ }
+}
+
+static void SecondaryTaskbarsRestore() {
+ OcultarAutomaticoRestore();
+ std::wstring before = shell::Setting(L"barra_windows_monitores_antes", L"");
+ if (before.empty()) return;
+ if (before == L"x") RegDeleteKeyValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled");
+ else { DWORD v = (DWORD)_wtoi(before.c_str()); RegSetKeyValueW(HKEY_CURRENT_USER, MM_KEY, L"MMTaskbarEnabled", REG_DWORD, &v, sizeof(v)); }
+ shell::SetSetting(L"barra_windows_monitores_antes", L"");
+ Log(L"registro: MMTaskbarEnabled devolvido (%ls)", before == L"x" ? L"apagado, não existia" : before.c_str());
+ TellExplorerTray();
+}
+
+// Área de trabalho de cada monitor: a barra de menus em cima (todos têm a sua) e o Dock embaixo (só no
+// monitor dele). O SPI_SETWORKAREA vale para o monitor que contém o retângulo.
+std::vector<HWND> shell::AlheiasNoTopo() {
+ std::vector<HWND> v; // de cima para baixo
+ DWORD eu = GetCurrentProcessId();
+ for (HWND w = GetTopWindow(nullptr); w && v.size() < 32; w = GetWindow(w, GW_HWNDNEXT)) {
+ if (!(GetWindowLongW(w, GWL_EXSTYLE) & WS_EX_TOPMOST)) break; // acabou a faixa das "sempre por cima"
+ if (!IsWindowVisible(w)) continue;
+ DWORD pid = 0; GetWindowThreadProcessId(w, &pid);
+ if (pid == eu) break; // daqui para baixo já estavam abaixo das nossas
+ DWORD cloak = 0; DwmGetWindowAttribute(w, DWMWA_CLOAKED, &cloak, sizeof(cloak));
+ if (cloak) continue;
+ wchar_t c[64] = {}; GetClassNameW(w, c, 64);
+ if (!wcscmp(c, L"tooltips_class32") || !wcscmp(c, L"#32768") || !wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd")) continue;
+ RECT r; if (!GetWindowRect(w, &r) || r.right - r.left < 2 || r.bottom - r.top < 2) continue;
+ v.push_back(w);
+ }
+ return v;
+}
+
+void shell::DevolveAlheias(const std::vector<HWND>& v) {
+ for (auto it = v.rbegin(); it != v.rend(); ++it) // de baixo para cima: a de cima termina por cima
+ if (IsWindow(*it) && IsWindowVisible(*it))
+ SetWindowPos(*it, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_ASYNCWINDOWPOS);
+}
+
+RECT shell::WorkAreaFor(HMONITOR hm) {
+ MONITORINFO mi{ sizeof(mi) };
+ if (!GetMonitorInfoW(hm, &mi)) return {};
+ RECT want = mi.rcMonitor;
+ want.top += menubar::ReservedOn(hm); // secundário sem barra (barra_todos_monitores=0): o topo é das janelas
+ if (hm == dock::MonitorHandle()) { // o Dock na borda escolhida (Ajustes > Posição na tela)
+ int r = dock::ReservedHeight();
+ if (dock::Posicao() == 1) want.left += r;
+ else if (dock::Posicao() == 2) want.right -= r;
+ else want.bottom -= std::max(r, menubar::ReservedBottom(hm)); // barra embaixo: com o Dock oculto, a altura dela
+ }
+ return want;
+}
+
+void shell::ApplyWorkArea() {
+ if (g_quitting) return;
+ struct Ctx { HMONITOR dock; bool changed; } ctx{ dock::MonitorHandle(), false };
+ EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hm, HDC, LPRECT, LPARAM p) -> BOOL {
+ auto* c = (Ctx*)p;
+ MONITORINFO mi{ sizeof(mi) };
+ if (!GetMonitorInfoW(hm, &mi)) return TRUE;
+ RECT want = shell::WorkAreaFor(hm), cur = mi.rcWork;
+ (void)c;
+ if (EqualRect(&want, &cur)) return TRUE;
+ static int times;
+ Log(L"área de trabalho estava %d,%d-%d,%d; agora %d,%d-%d,%d (vez %d)", cur.left, cur.top, cur.right, cur.bottom,
+ want.left, want.top, want.right, want.bottom, ++times);
+ // Sem SPIF_SENDCHANGE: o aviso geral fazia o Explorador recalcular e desfazer (briga a cada 2 s).
+ SystemParametersInfoW(SPI_SETWORKAREA, 0, &want, 0);
+ c->changed = true;
+ return TRUE;
+ }, (LPARAM)&ctx);
+ if (!ctx.changed) return;
+ // Avisa só as janelas dos apps: o DefWindowProc reencaixa as maximizadas na área nova.
+ EnumWindows([](HWND h, LPARAM) -> BOOL {
+ if (!IsWindowVisible(h) || apps::IsShellWindow(h)) return TRUE;
+ wchar_t c[64]; GetClassNameW(h, c, 64);
+ if (!wcscmp(c, L"Shell_TrayWnd") || !wcscmp(c, L"Shell_SecondaryTrayWnd") || mesa::IsDeskClass(c)) return TRUE;
+ if (IsZoomed(h)) SendMessageTimeoutW(h, WM_SETTINGCHANGE, SPI_SETWORKAREA, 0, SMTO_ABORTIFHUNG, 200, nullptr);
+ return TRUE;
+ }, 0);
+}
+
+static void Restore() {
+ if (g_quitting) return;
+ g_quitting = true;
+ tray::Stop();
+ menus::Stop();
+ dialogs::Stop();
+ janelas::Stop();
+ encaixe::Stop();
+ memoria::Stop();
+ barras::Stop();
+ sombras::Stop();
+ alertas::Stop();
+ progresso::Stop(); // as janelas de progresso do Windows voltam para a tela
+ if (!shell::nativo) { // no nativo a tela de bloqueio continua do Windows (não foi trocada)
+ bloqueio::Stop(); // Win+L volta para o Windows (política apagada)
+ mesa::Stop(!g_crashed && !g_sessionEnding); // sem Explorador: ele volta (ao cair, quem abre é o vigia)
+ } else mesa::Stop(true); // nativo: a nossa mesa some e a do Explorador (que ficou atrás) reaparece
+ revelar::Stop(); // janelas que estavam nas bordas voltam
+ ponteiro::Stop(); // o cursor volta ao tamanho do esquema
+ palco::Stop(); // Organizador Visual: as janelas escondidas por ele voltam
+ genio::Stop(); // a animação de minimizar do Windows volta como estava
+ notificacoes::Stop(); // o banner de notificação do Windows volta
+ ShowTaskbars();
+ SecondaryTaskbarsRestore();
+ // os outros monitores voltam inteiros (a barra do Windows, se voltar lá, reserva o espaço dela)
+ EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hm, HDC, LPRECT, LPARAM) -> BOOL {
+ MONITORINFO mi{ sizeof(mi) };
+ if (GetMonitorInfoW(hm, &mi) && !(mi.dwFlags & MONITORINFOF_PRIMARY)) SystemParametersInfoW(SPI_SETWORKAREA, 0, &mi.rcMonitor, 0);
+ return TRUE;
+ }, 0);
+ SystemParametersInfoW(SPI_SETWORKAREA, 0, &g_origWork, SPIF_SENDCHANGE);
+ Log(L"saindo: barra do Windows e área de trabalho devolvidas");
+}
+
+// Saindo de verdade (não o reiniciar): o WacOS fecha por inteiro (issue #37: depois de sair, o Win+E e as pastas
+// ainda abriam o Finder, e o Finder reserva e a Captura residente continuavam abertos, escondidos).
+// As pastas voltam para o Explorador e finder_volta=1 faz o Shell, ao abrir de novo, devolvê-las ao Finder (o mesmo
+// caminho do "Desligar o WacOS"). Quem desligou "Abrir pastas no Finder" à mão (finder_padrao=0) não é mexido.
+static void SaiPorInteiro() {
+ static UINT capMsg = RegisterWindowMessageW(L"SequoiaCaptura");
+ if (HWND w = FindWindowW(L"SequoiaCapturaMsg", nullptr)) PostMessageW(w, capMsg, 0, 0); // wParam 0 = sair
+ if (HWND w = FindWindowW(L"ArquivosJanela", L"​ArquivosReserva")) // a reserva nunca foi usada: não tem nada do usuário
+ PostThreadMessageW(GetWindowThreadProcessId(w, nullptr), WM_QUIT, 0, 0);
+ std::wstring finder = shell::dir + L"\\" EXE_FINDER;
+ if (shell::Setting(L"finder_padrao", L"1") == L"1" && GetFileAttributesW(finder.c_str()) != INVALID_FILE_ATTRIBUTES) {
+ shell::SetSetting(L"finder_volta", L"1");
+ std::wstring cmd = L"\"" + finder + L"\" --padrao off --quieto";
+ STARTUPINFOW si{ sizeof(si) }; si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;
+ PROCESS_INFORMATION pi{};
+ if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, shell::dir.c_str(), &si, &pi)) {
+ WaitForSingleObject(pi.hProcess, 3000); // antes de uma atualização abrir o Shell novo (que religa)
+ CloseHandle(pi.hThread); CloseHandle(pi.hProcess);
+ Log(L"saindo: pastas e Win+E de volta ao Explorador (o Finder volta ao abrir o WacOS)");
+ }
+ }
+}
+
+void shell::Quit(const wchar_t* why) {
+ Log(L"pedido para sair: %ls", why);
+ if (wcscmp(why, L"reiniciar")) SaiPorInteiro();
+ pastas::Stop();
+ limites::Stop();
+ bloqueio::Fallback(); // saiu com a tela travada (ex.: Ctrl+Alt+Shift+F12): o Windows bloqueia
+ Restore();
+ PostQuitMessage(0);
+}
+
+static LONG WINAPI OnCrash(EXCEPTION_POINTERS* ep) {
+ HMODULE mod = nullptr;
+ void* at = ep->ExceptionRecord->ExceptionAddress;
+ GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)at, &mod);
+ wchar_t name[MAX_PATH] = L"?"; if (mod) GetModuleFileNameW(mod, name, MAX_PATH);
+ Log(L"ERRO 0x%08X em %ls+0x%llX", ep->ExceptionRecord->ExceptionCode, name, (unsigned long long)((BYTE*)at - (BYTE*)mod));
+ bloqueio::Fallback(); // caiu com a tela travada: o Windows bloqueia de verdade
+ g_crashed = true;
+ Restore(); // nunca deixar o usuário sem barra de tarefas
+ return EXCEPTION_CONTINUE_SEARCH;
+}
+
+// Finder reserva: um Arquivos.exe já inicializado e escondido. Abrir uma pasta, o Win+E ou a janela
+// de Abrir/Salvar entregam o pedido a ele (aparece na hora); quando é usado, preparamos outro.
+// Captura de Tela (WacOSScreenshot.exe) sempre aberta e escondida: a mira do Win+Shift+4 aparece na hora
+bool shell::SoDock() { static int v = -1; if (v < 0) v = shell::Setting(L"modo", L"completo") == L"dock" ? 1 : 0; return v == 1; }
+
+static void EnsureScreenshot() {
+ static DWORD lastSpawn;
+ if (g_quitting || !g_capturaExe || FindWindowW(L"SequoiaCapturaMsg", nullptr)) return;
+ if (lastSpawn && GetTickCount() - lastSpawn < 10000) return;
+ lastSpawn = GetTickCount();
+ std::wstring cmd = L"\"" + shell::dir + L"\\" EXE_SCREENSHOT L"\" /residente";
+ STARTUPINFOW si{ sizeof(si) };
+ PROCESS_INFORMATION pi{};
+ std::thread([cmd, si, pi]() mutable { // como o Finder reserva: abrir programa espera o disco
+ if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) {
+ CloseHandle(pi.hProcess); CloseHandle(pi.hThread);
+ Log(L"Captura de Tela residente aberta");
+ }
+ }).detach();
+}
+
+// pedido do atalho: 3 tela inteira, 4 região/janela, 5 barra de ferramentas; clip = Ctrl seguro
+static void Screenshot(int kind, bool clip) {
+ static UINT msg = RegisterWindowMessageW(L"SequoiaCaptura");
+ if (HWND w = FindWindowW(L"SequoiaCapturaMsg", nullptr)) {
+ DWORD pid = 0; GetWindowThreadProcessId(w, &pid);
+ AllowSetForegroundWindow(pid);
+ PostMessageW(w, msg, kind, clip ? 1 : 0);
+ return;
+ }
+ std::wstring args = L"/" + std::to_wstring(kind) + (clip ? L" /c" : L"");
+ shell::Abrir(L"open", (shell::dir + L"\\" EXE_SCREENSHOT).c_str(), args.c_str(), nullptr, SW_SHOWNORMAL);
+ Log(L"Captura de Tela aberta agora (%ls)", args.c_str());
+}
+
+void shell::AbrirFinder(const std::wstring& args) {
+ if (shell::nativo) {
+ HMODULE m = GetModuleHandleW(L"MacFinder.dll");
+ auto pedir = m ? (BOOL(WINAPI*)(const wchar_t*))GetProcAddress(m, "FinderPedir") : nullptr;
+ if (pedir && pedir(args.c_str())) { Log(L"Finder (nativo): %ls", args.c_str()); return; }
+ Log(L"Finder nativo indisponível, abrindo o exe: %ls", args.c_str());
+ }
+ shell::Abrir(L"open", (shell::dir + L"\\" EXE_FINDER).c_str(), args.c_str(), nullptr, SW_SHOWNORMAL);
+}
+
+static void EnsureReserve() {
+ if (shell::nativo) return; // no nativo a reserva é a janela do Finder dentro do explorer (MacFinder.dll)
+ static DWORD lastSpawn;
+ if (g_quitting || FindWindowW(L"ArquivosJanela", L"​ArquivosReserva")) return;
+ if (lastSpawn && GetTickCount() - lastSpawn < 4000) return; // um por vez
+ lastSpawn = GetTickCount();
+ std::wstring cmd = L"\"" + shell::dir + L"\\" EXE_FINDER L"\" --reserva";
+ STARTUPINFOW si{ sizeof(si) };
+ si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;
+ PROCESS_INFORMATION pi{};
+ // numa thread: com o disco cheio o CreateProcess levou 2,9 s e a interface esperava (pilha de 22/11/2026, 15:25)
+ std::thread([cmd, si, pi]() mutable {
+ if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) {
+ CloseHandle(pi.hProcess); CloseHandle(pi.hThread);
+ Log(L"Finder reserva preparado");
+ }
+ }).detach();
+}
+
+// Pré-carga: lê os .exe dos outros apps do projeto para o cache de arquivos do Windows (memória de
+// espera, que o sistema devolve quando precisa). Assim o primeiro clique abre como se já tivesse sido
+// aberto antes, sem deixar nenhum processo rodando. Prioridade de fundo, depois que o Shell está pronto.
+// os painéis que montam coisa cara na primeira abertura: prepara com o Shell já parado, na thread
+// principal (o compositor e a GPU são dela)
+static void CALLBACK WarmPanels(HWND, UINT, UINT_PTR id, DWORD) {
+ KillTimer(nullptr, id);
+ missioncontrol::Warm();
+ launchpad::Warm();
+}
+
+static void PreloadApps() {
+ SetTimer(nullptr, 0, 4000, WarmPanels);
+ std::thread([] {
+ SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
+ Sleep(3000);
+ static const wchar_t* files[] = { EXE_SETTINGS, EXE_NOTES, EXE_CALCULATOR, EXE_TERMINAL, EXE_MONITOR, DLL_WINDOW32 };
+ std::vector<char> buf(1 << 20);
+ size_t total = 0;
+ for (auto* f : files) {
+ HANDLE h = CreateFileW((shell::dir + L"\\" + f).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr,
+ OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
+ if (h == INVALID_HANDLE_VALUE) continue;
+ DWORD got = 0;
+ while (ReadFile(h, buf.data(), (DWORD)buf.size(), &got, nullptr) && got) total += got;
+ CloseHandle(h);
+ }
+ Log(L"pré-carga: %zu KB dos apps no cache", total / 1024);
+ SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
+ }).detach();
+}
+
+// App da frente cobrindo o monitor inteiro (vídeo, jogo, F11): Dock e barra de menus somem, como no Mac.
+static bool IsFullscreen(HWND fg) {
+ if (!fg || !IsWindowVisible(fg) || IsIconic(fg) || apps::IsShellWindow(fg)) return false;
+ // Trocadores de papel de parede com transição (YASB, Lively...) põem a janela da animação DENTRO da mesa do Windows
+ // (filha da WorkerW/Progman) e ela fica sendo a "janela da frente". Cobrindo o monitor, parecia um app em tela
+ // cheia: o Dock e a barra de menus sumiam e o vidro ficava sem fundo, e como o YASB mantém a janela viva depois da
+ // transição, ficava assim até reiniciar o WacOS (Reddit, 23/11/2026; reproduzido com o mesmo truque do YASB).
+ // Janela filha conta pela de topo dela: sendo a mesa, não é tela cheia.
+ if (HWND root = GetAncestor(fg, GA_ROOT); root && root != fg) {
+ wchar_t rc[64] = {}; GetClassNameW(root, rc, 64);
+ if (mesa::IsDeskClass(rc)) return false;
+ fg = root;
+ if (!IsWindowVisible(fg) || IsIconic(fg) || apps::IsShellWindow(fg)) return false;
+ }
+ wchar_t cls[64] = {}; GetClassNameW(fg, cls, 64);
+ if (mesa::IsDeskClass(cls) || !wcscmp(cls, L"Shell_TrayWnd")) return false;
+ if (IsZoomed(fg) && (GetWindowLongW(fg, GWL_STYLE) & WS_CAPTION) == WS_CAPTION) return false; // só maximizada
+ MONITORINFO mi{ sizeof(mi) };
+ if (!GetMonitorInfoW(MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST), &mi)) return false;
+ RECT r; if (!GetWindowRect(fg, &r)) return false;
+ return r.left <= mi.rcMonitor.left && r.top <= mi.rcMonitor.top && r.right >= mi.rcMonitor.right && r.bottom >= mi.rcMonitor.bottom;
+}
+
+// Jogo/vídeo em tela cheia no monitor `mon` (ou o Windows em modo "não incomodar": Direct3D exclusivo,
+// apresentação): os banners de notificação não aparecem, só vão para a Central. Uma janela "sempre no topo" por cima
+// do jogo tirava ele da tela cheia (17/11/2026, Fortnite caindo a cada notificação).
+bool shell::NaoIncomodar(HMONITOR mon) {
+ QUERY_USER_NOTIFICATION_STATE q{};
+ if (SUCCEEDED(SHQueryUserNotificationState(&q)) && (q == QUNS_RUNNING_D3D_FULL_SCREEN || q == QUNS_PRESENTATION_MODE || q == QUNS_BUSY))
+ return true;
+ HWND fg = GetForegroundWindow();
+ if (!IsFullscreen(fg)) return false;
+ return !mon || MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST) == mon;
+}
+
+// Com mais de um monitor, só some o que está no monitor do app em tela cheia (a barra daquele monitor; o Dock
+// se ele estiver lá). Tela travada: tudo some.
+static void CheckFullscreen() {
+ HWND fg = GetForegroundWindow();
+ bool locked = bloqueio::Active();
+ bool fs = !locked && IsFullscreen(fg);
+ HMONITOR fm = fs ? MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST) : nullptr;
+ { // registro: quem fez o Dock e a barra de menus sumirem (uma vez por janela)
+ static HWND visto;
+ if (fs && fg != visto) {
+ wchar_t c[80] = {}, t[80] = {}; GetClassNameW(fg, c, 80); GetWindowTextW(fg, t, 80);
+ DWORD pid = 0; GetWindowThreadProcessId(fg, &pid);
+ Log(L"tela cheia: janela %p classe '%ls' título '%ls' pid %lu estilo %08lX ex %08lX", fg, c, t, pid, GetWindowLongW(fg, GWL_STYLE), GetWindowLongW(fg, GWL_EXSTYLE));
+ }
+ visto = fs ? fg : nullptr;
+ }
+ dock::SetFullscreen(locked || (fs && fm == dock::MonitorHandle()));
+ menubar::SetFullscreen(locked || fs, fm);
+ ilha::SetFullscreen(locked); // a ilha confere sozinha a tela cheia do monitor principal (jogo, vídeo, app)
+}
+
+static void CALLBACK OnWinEvent(HWINEVENTHOOK, DWORD ev, HWND h, LONG obj, LONG, DWORD, DWORD) {
+ // maximizada por cima da barra/do Dock (issue #24): qualquer janela de topo (a conferência é barata e sai cedo)
+ if (ev == EVENT_OBJECT_LOCATIONCHANGE && obj == OBJID_WINDOW && !shell::nativo && h && GetAncestor(h, GA_ROOT) == h) limites::Maximizada(h);
+ if (ev == EVENT_OBJECT_LOCATIONCHANGE && (obj != OBJID_WINDOW || h != GetForegroundWindow())) return;
+ if (ev == EVENT_SYSTEM_FOREGROUND) { revelar::Foreground(h); jogo::Foreground(h); }
+ CheckFullscreen();
+}
+
+static void Changed() {
+ if (apps::Refresh()) dock::Update();
+ menubar::Update();
+}
+
+// Aparência "Automático" (Ajustes do Sistema): claro das 7h às 19h, escuro no resto do dia.
+static void AutoAppearance() {
+ if (shell::Setting(L"aparencia_auto", L"0") != L"1") return;
+ SYSTEMTIME st; GetLocalTime(&st);
+ DWORD want = st.wHour >= 7 && st.wHour < 19 ? 1 : 0, cur = 1, cb = sizeof(cur);
+ const wchar_t* key = L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
+ RegGetValueW(HKEY_CURRENT_USER, key, L"AppsUseLightTheme", RRF_RT_REG_DWORD, nullptr, &cur, &cb);
+ if (cur == want) return;
+ RegSetKeyValueW(HKEY_CURRENT_USER, key, L"AppsUseLightTheme", REG_DWORD, &want, sizeof(want));
+ RegSetKeyValueW(HKEY_CURRENT_USER, key, L"SystemUsesLightTheme", REG_DWORD, &want, sizeof(want));
+ Log(L"aparência automática: %ls", want ? L"clara" : L"escura");
+ // numa thread, como na Central (central.cpp): para todas as janelas, o limite de 200 ms vale para CADA uma ocupada,
+ // e a interface do Shell ficava parada esse tempo todo
+ std::thread([] { SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)L"ImmersiveColorSet", SMTO_ABORTIFHUNG, 200, nullptr); }).detach();
+}
+
+static LRESULT CALLBACK MsgProc(HWND h, UINT m, WPARAM w, LPARAM l) {
+ if (m == WM_NA_INTERFACE) { auto* p = (std::function<void()>*)l; if (p) { (*p)(); delete p; } return 0; }
+ // Outro programa (o Explorador, com a barra do Windows escondida ou em ocultar automaticamente) devolveu a área de
+ // trabalho para a tela inteira: reaplica a nossa NA HORA. Antes esperava o tique de 1 s, e nesse meio-tempo as
+ // janelas maximizadas e os ícones da mesa subiam para baixo da barra de menus e voltavam (issue #1: "a área
+ // pula sem parar"). O nosso próprio SPI_SETWORKAREA vai sem aviso (sem SPIF_SENDCHANGE), então não volta aqui.
+ if (m == WM_SETTINGCHANGE && w == SPI_SETWORKAREA && !g_quitting) {
+ static DWORD win = 0; static int n = 0;
+ DWORD now = GetTickCount();
+ if (now - win > 1000) { win = now; n = 0; }
+ if (++n <= 8) shell::ApplyWorkArea(); // no máximo 8 por segundo (se alguém brigar sem parar, não gira em laço)
+ }
+ static UINT reload = RegisterWindowMessageW(L"ShellAjustesMudaram");
+ static UINT openCC = RegisterWindowMessageW(L"ShellAbrirCentral"); // abre/fecha a Central de Controle de fora
+ static UINT restart = RegisterWindowMessageW(L"ShellReiniciar"); // reiniciar: sai sem abrir o Explorador e abre o Shell de novo
+ if (m == restart && restart) {
+ // o Shell novo abre já (no mesmo caminho: depois de compilar, é a versão nova) e espera este sair
+ wchar_t exe[MAX_PATH]; GetModuleFileNameW(nullptr, exe, MAX_PATH);
+ std::wstring dir = exe; dir = dir.substr(0, dir.find_last_of(L'\\'));
+ std::wstring cmd = std::wstring(L"\"") + exe + L"\" --depois-de " + std::to_wstring(GetCurrentProcessId());
+ STARTUPINFOW si{ sizeof(si) }; PROCESS_INFORMATION pi{};
+ if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, dir.c_str(), &si, &pi)) { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); }
+ else Log(L"reiniciar: não abriu o Shell novo (%lu)", GetLastError());
+ mesa::NoExplorerOnExit();
+ tray::SemAvisoAoSair();
+ janelas::ManterAoReiniciar(); // as janelas ficam com a barra do Mac (o Shell novo assume; ver janelas::Stop)
+ shell::Quit(L"reiniciar");
+ return 0;
+ }
+ if (m == openCC && openCC) { central::Toggle(); return 0; }
+ static UINT openNC = RegisterWindowMessageW(L"ShellAbrirNotificacoes"); // abre/fecha a Central de Notificações de fora
+ if (m == openNC && openNC) { notificacoes::Toggle(); return 0; }
+ static UINT openSP = RegisterWindowMessageW(L"ShellAbrirSpotlight"); // abre/fecha o Spotlight de fora (como o Win+Espaço)
+ if (m == openSP && openSP) { PostMessageW(h, WM_APP_SPOTLIGHT, 0, 0); return 0; }
+ // abre um painel de fora (fotos do README, testes): 1 Launchpad/Apps, 2 Mission Control, 3..6 Spotlight no modo 1..4,
+ // 7 Spotlight, 8 Sobre Este Mac
+ static UINT openPanel = RegisterWindowMessageW(L"ShellAbrirPainel");
+ if (m == openPanel && openPanel) {
+ // pedido de fora: o Windows não deixa o Shell vir para a frente sozinho (o Spotlight e o Launchpad fechavam na
+ // hora, sem foco). Entra na fila de entrada da janela da frente enquanto abre, como os alertas fazem.
+ HWND fg = GetForegroundWindow();
+ DWORD ft = fg ? GetWindowThreadProcessId(fg, nullptr) : 0, me = GetCurrentThreadId();
+ bool att = ft && ft != me && AttachThreadInput(me, ft, TRUE);
+ if (w == 1) launchpad::Toggle();
+ else if (w == 2) missioncontrol::Toggle();
+ else if (w >= 3 && w <= 6) spotlight::OpenMode((int)w - 2);
+ else if (w == 7) spotlight::Toggle();
+ else if (w == 8) sobre::Show(); // Sobre Este Mac
+ else if (w == 9) central::Toggle(); // Central de Controle (testes)
+ else if (w == 10) notificacoes::Toggle(); // Central de Notificações (testes)
+ else if (w == 12) dock::OpenAppsStack(); // Leopard: a pilha Aplicativos (testes)
+ else if (w == 13) seletor::Step(1); // o seletor de apps sem segurar o Alt (testes; 14 fecha)
+ else if (w == 14) seletor::Key(VK_ESCAPE);
+ else if (w == 15) dock::OpenDownloadsStack(); // a pilha Downloads (testes)
+ else if (w == 16) dashboard::Toggle(); // Leopard: Dashboard (Win+F12)
+ else if (w == 17) espacos::Toggle(); // Leopard: Spaces (Win+F8)
+ else if (w == 18) tempo::Enter(); // Leopard: a viagem no tempo do Time Machine
+ else if (w == 11) { // Quick Look de uma foto do macOS 27 (testes)
+ wchar_t p[MAX_PATH] = {}; GetEnvironmentVariableW(L"USERPROFILE", p, MAX_PATH);
+ quicklook::Toggle(std::wstring(p) + L"\\Pictures\\Wallpapers macOS\\macOS 27\\macos-27-golden-4096x2160-27635.jpg");
+ }
+ if (att) AttachThreadInput(me, ft, FALSE);
+ return 0;
+ }
+ if (atualizacao::Handle(m)) return 0;
+ if (LRESULT mr; menus::VidroMsg(m, w, l, &mr)) return mr; // menu de contexto de um app nosso pedindo o vidro
+ // Ajustes > Aparência > "Reiniciar o Liquid Glass": refaz o vidro real do zero (se ele desistiu ou travou)
+ static UINT redoGlass = RegisterWindowMessageW(L"ShellReiniciarVidro");
+ if (m == redoGlass && redoGlass) { backdrop::Restart(); return 1; }
+ static UINT capVis = RegisterWindowMessageW(L"ShellCapturaVisivel"); // a Captura de Tela vai tirar a foto
+ if (m == capVis && capVis) { backdrop::CaptureVisible(w != 0); return 1; }
+ static UINT capDone = RegisterWindowMessageW(L"ShellCapturaFeita"); // a Captura salvou (0) ou copiou (1): aviso na ilha
+ if (m == capDone && capDone) { ilha::Captura(w != 0); return 0; }
+ if (m == WM_COPYDATA && l && ((COPYDATASTRUCT*)l)->dwData == 0x4C504150 /*'PAPL'*/) { // Ajustes: papel de parede escolhido
+ auto* cd = (COPYDATASTRUCT*)l;
+ if (!cd->lpData || cd->cbData < sizeof(wchar_t) || cd->cbData > 4096) return FALSE;
+ std::wstring p((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t));
+ while (!p.empty() && !p.back()) p.pop_back();
+ mesa::WallpaperNow(p);
+ return TRUE;
+ }
+ if (m == WM_COPYDATA && l && ((COPYDATASTRUCT*)l)->dwData == 0x514C4F4B /*'QLOK'*/) { // Finder: Quick Look (vazio = fechar)
+ auto* cd = (COPYDATASTRUCT*)l;
+ if (cd->cbData > 8192) return FALSE;
+ std::wstring p = cd->lpData ? std::wstring((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t)) : L"";
+ while (!p.empty() && !p.back()) p.pop_back();
+ // responde já e abre logo depois: o vídeo leva mais que o tempo de espera do Finder (0,8 s), e ele achava
+ // que tinha falhado e abria também o painel antigo dele
+ auto* copy = new std::wstring(p);
+ PostMessageW(h, WM_APP + 77, 0, (LPARAM)copy);
+ return TRUE;
+ }
+ // 'SIRI': pergunta à Siri (texto UTF-16) vinda de fora (atalhos, scripts, testes); 'BRIL': mostra o brilho n (0-100)
+ // na Ilha como se a tela tivesse mudado (teste do aviso num PC de mesa, que não manda o evento do WMI)
+ if (m == WM_COPYDATA && l && (((COPYDATASTRUCT*)l)->dwData == 0x49524953 /*'SIRI'*/ || ((COPYDATASTRUCT*)l)->dwData == 0x54524953 /*'SIRT': teste, sem pegar a frente*/ || ((COPYDATASTRUCT*)l)->dwData == 0x41524953 /*'SIRA': abre o campo (teste)*/ || ((COPYDATASTRUCT*)l)->dwData == 0x4C495242 /*'BRIL'*/)) {
+ auto* cd = (COPYDATASTRUCT*)l;
+ if (!cd->lpData || cd->cbData < sizeof(wchar_t) || cd->cbData > 16384) return FALSE;
+ std::wstring t((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t));
+ while (!t.empty() && !t.back()) t.pop_back();
+ if (cd->dwData == 0x4C495242) { ilha::Brilho(_wtoi(t.c_str())); return TRUE; }
+ if (cd->dwData == 0x41524953) { PostMessageW(h, WM_APP + 79, 0, 0); return TRUE; }
+ PostMessageW(h, WM_APP + 78, cd->dwData == 0x54524953, (LPARAM)new std::wstring(t)); // depois de responder: quem mandou não fica esperando
+ return TRUE;
+ }
+ if (m == WM_APP + 79) { siri::Abrir(true); return 0; }
+ if (m == WM_APP + 78 && l) { std::unique_ptr<std::wstring> q((std::wstring*)l); siri::Perguntar(*q, w != 0); return 0; }
+ if (m == WM_APP + 77 && l) { // o Quick Look pedido pelo Finder (acima)
+ std::unique_ptr<std::wstring> p((std::wstring*)l);
+ if (p->empty()) quicklook::Close();
+ else quicklook::Toggle(*p, false); // o Finder fica com o foco
+ return 0;
+ }
+ if (m == WM_COPYDATA && l && ((COPYDATASTRUCT*)l)->dwData == 0x414D504C /*'AMPL'*/) { // MacJanela.dll: ampliar animado
+ struct Msg { unsigned long long hwnd; RECT from, to; int flags; COLORREF cap; };
+ auto* cd = (COPYDATASTRUCT*)l;
+ if (cd->cbData != sizeof(Msg) || !cd->lpData) return FALSE;
+ auto* mm = (Msg*)cd->lpData;
+ // nativo: janelas de barra própria (flags 8: Chrome, Edge, Electron...) têm a barra do Mac por fora (barras.cpp).
+ // A animação usa uma foto da janela de verdade, com a barra e os botões do Windows: por meio segundo as
+ // bolinhas sumiam e apareciam os botões antigos (vídeo do usuário de 12/11/2026). Sem animação: muda na hora.
+ if (shell::nativo && (mm->flags & 8)) return FALSE;
+ return ampliar::Start((HWND)(UINT_PTR)mm->hwnd, mm->from, mm->to, mm->flags, mm->cap) ? TRUE : FALSE;
+ }
+ static UINT ampFoto = RegisterWindowMessageW(L"ShellAmpliarFoto"); // MacJanela.dll: a janela já mudou de tamanho
+ if (m == ampFoto && ampFoto) { ampliar::SecondPhoto((HWND)w); return 0; }
+ static UINT iconeMudou = RegisterWindowMessageW(L"ShellIconeMudou"); // ícone próprio de um app escolhido/restaurado (apps.cpp)
+ if (m == iconeMudou && iconeMudou) { apps::ReloadIcons(); Log(L"ícone próprio: Dock, Alt+Tab e Launchpad recarregados"); return 0; }
+ static UINT ampPronto = RegisterWindowMessageW(L"ShellAmpliarPronto"); // a janela já reapareceu
+ if (m == ampPronto && ampPronto) { ampliar::Shown((HWND)w); return 0; }
+ static UINT menuVerde = RegisterWindowMessageW(L"ShellMenuVerde"); // ponteiro parado no botão verde (DLL ou app nosso)
+ if (m == menuVerde && menuVerde) { verde::Show((HWND)w, POINT{ (short)LOWORD(l), (short)HIWORD(l) }); return 0; }
+ static UINT jAbrir = RegisterWindowMessageW(L"ShellJanelaAbrir"); // WacOSWindow.dll: janela nova, escondida e pintada
+ if (m == jAbrir && jAbrir) { abrir::Open((HWND)w, (HWND)l); return 0; }
+ static UINT jFechar = RegisterWindowMessageW(L"ShellJanelaFechar"); // WacOSWindow.dll: a janela vai sumir agora
+ if (m == jFechar && jFechar) return ampliar::Fechar((HWND)w, l) ? 1 : 0;
+ if (m == WM_COPYDATA && l) { // o Ajustes do Sistema manda "chave=valor": o Shell grava no arquivo que ele mesmo lê
+ // (o Ajustes pode estar num contêiner que desvia o %APPDATA% dele para outra cópia do ajustes.txt)
+ auto* cd = (COPYDATASTRUCT*)l;
+ if (cd->dwData == 0x534A5354 /*'SJST'*/ && cd->lpData && cd->cbData >= sizeof(wchar_t)) {
+ std::wstring kv((const wchar_t*)cd->lpData, cd->cbData / sizeof(wchar_t));
+ while (!kv.empty() && !kv.back()) kv.pop_back();
+ size_t eq = kv.find(L'=');
+ if (eq != std::wstring::npos && eq > 0 && eq < 128 && kv.find(L'\n') == std::wstring::npos) {
+ shell::SetSetting(kv.substr(0, eq).c_str(), kv.substr(eq + 1));
+ PostMessageW(h, reload, 0, 0);
+ }
+ return TRUE;
+ }
+ }
+ if (m == reload && reload) { // o Ajustes do Sistema gravou ajustes.txt
+ g_macKeys = !shell::SoDock() && shell::Setting(L"atalhos_mac", L"1") == L"1";
+ static int lastLiquid = -1;
+ if (lastLiquid < 0) lastLiquid = liquid::Leopard() ? 3 : liquid::Golden() ? 2 : liquid::On();
+ static int lastTheme = -1; // 0 Sequoia, 1 Tahoe, 2 Golden Gate, 3 Leopard
+ auto themeNow = [] { return liquid::Leopard() ? 3 : liquid::Golden() ? 2 : (int)liquid::On(); };
+ if (lastTheme < 0) lastTheme = themeNow();
+ LoadSettings();
+ ilha::Reload();
+ { // barra_todos_monitores mudou: cria ou tira as barras dos monitores secundários (e a área de trabalho deles)
+ static std::wstring lastAll = L"?";
+ std::wstring all = shell::Setting(L"barra_todos_monitores", L"1");
+ if (lastAll != L"?" && all != lastAll) { menubar::Displays(); dock::ReloadSettings(); }
+ lastAll = all;
+ static std::wstring lastBaixo = L"?"; // barra de menus em cima ou na linha do Dock (issue #29)
+ std::wstring baixo = shell::Setting(L"barra_embaixo", L"0");
+ if (baixo != lastBaixo) { menubar::Displays(); dock::ReloadSettings(); }
+ lastBaixo = baixo;
+ static std::wstring lastOcultar = L"?"; // ocultar a barra de menus automaticamente (issue #40)
+ std::wstring ocultar = shell::Setting(L"barra_ocultar", L"0");
+ if (lastOcultar != L"?" && ocultar != lastOcultar) { menubar::Displays(); dock::ReloadSettings(); }
+ lastOcultar = ocultar;
+ }
+ static int lastLang = -1;
+ if (lastLang < 0) lastLang = idioma::Current();
+ if (int lang = idioma::FromCode(shell::Setting(L"idioma", L"en")); lang != lastLang) { // Ajustes > Geral > Idioma
+ lastLang = lang;
+ idioma::Set(lang);
+ apps::Relabel();
+ dock::IconsChanged();
+ Log(L"idioma: %ls", idioma::Code());
+ }
+ if ((liquid::Leopard() ? 3 : liquid::Golden() ? 2 : (int)liquid::On()) != lastLiquid) { // tema Sequoia/Tahoe/Golden Gate/Leopard: outro pacote de ícones
+ lastLiquid = liquid::Leopard() ? 3 : liquid::Golden() ? 2 : liquid::On();
+ for (auto& a : apps::list) { a.icon.clear(); a.iw = a.ih = 0; a.mac = false; }
+ dock::IconsChanged();
+ seletor::IconsChanged();
+ Log(L"tema mudou: ícones do Dock e do seletor recarregados");
+ }
+ if (themeNow() != lastTheme) {
+ // tema trocado: as janelas com a barra do Mac (WacOSWindow.dll) redesenham já (barra metálica e botões de gel
+ // do Leopard, ou de volta) em vez de esperar a próxima ativação
+ lastTheme = themeNow();
+ EnumWindows([](HWND w, LPARAM msg) -> BOOL {
+ if (GetPropW(w, L"MacJanela")) PostMessageW(w, (UINT)msg, 0, 0);
+ return TRUE;
+ }, (LPARAM)reload);
+ Log(L"tema: %d (janelas avisadas)", lastTheme);
+ ponteiro::TemaLeopard(lastTheme == 3); // Leopard: cursor do Mac OS X; saindo, o cursor de antes
+ }
+ dock::ReloadSettings();
+ dock::ApplyTheme();
+ menubar::ApplyTheme();
+ menubar::Update();
+ shell::ApplyWorkArea();
+ mesa::SettingsChanged();
+ widgets::SettingsChanged(); // Personalizar a Mesa: widgets ligados/desligados
+ jogo::Reload(); // modo_jogo e jogos.txt
+ palco::Sync();
+ // "Clicar no papel de parede para mostrar a mesa" saiu de "Nunca": com o Shell aberto em "Nunca" o gancho do mouse
+ // nunca era criado e a opção nova só valia depois de reiniciar (Start não faz nada se já estiver ligado)
+ if (!shell::SoDock() && !jogo::Ativo()) revelar::Start();
+ return 0;
+ }
+ if (m == WM_SHELLHOOK && WM_SHELLHOOK) {
+ switch (w & 0x7FFF) {
+ case HSHELL_WINDOWCREATED: case HSHELL_WINDOWDESTROYED: case HSHELL_WINDOWACTIVATED: case HSHELL_REDRAW:
+ Changed();
+ if ((w & 0x7FFF) == HSHELL_REDRAW && (w & 0x8000)) { // HSHELL_FLASH: app pedindo atenção
+ apps::Refresh();
+ if (App* a = apps::OfWindow((HWND)l)) { a->attentionAt = GetTickCount(); dock::Update(); }
+ }
+ break;
+ case HSHELL_GETMINRECT: { // para onde a janela encolhe ao minimizar: o Dock, antes da Lixeira
+ auto* shi = (SHELLHOOKINFO*)l;
+ RECT r{};
+ if (shi && genio::OnMinRect(shi->hwnd, &r)) { shi->rc = r; return TRUE; } // o gênio já começou, com a janela ainda na tela
+ r = dock::MinimizeTarget(shi ? shi->hwnd : nullptr);
+ if (shi && r.right > r.left) { shi->rc = r; SetTimer(g_msg, 7, 450, nullptr); return TRUE; } // e o Dock se atualiza logo depois
+ break;
+ }
+ }
+ return 0;
+ }
+ switch (m) {
+ case WM_TIMER:
+ if (w == 7) { KillTimer(g_msg, 7); Changed(); return 0; }
+ if (w == 1) {
+ static int ticks;
+ if (ticks++ % 60 == 0) AutoAppearance();
+ Changed(); CheckFullscreen(); HideTaskbars(); shell::ApplyWorkArea(); if (shell::Setting(L"finder_reserva", L"1") == L"1") EnsureReserve(); EnsureScreenshot();
+ }
+ if (w == 2) tray::Keepalive();
+ if (w == 9) { // extensões do menu de contexto carregadas cedo: o 1º botão direito na mesa/Spotlight/Launchpad sai rápido
+ KillTimer(g_msg, 9);
+ wchar_t* p = nullptr; std::wstring desk;
+ if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Desktop, 0, nullptr, &p))) { desk = p; CoTaskMemFree(p); }
+ std::wstring file;
+ WIN32_FIND_DATAW fd; HANDLE fh = desk.empty() ? INVALID_HANDLE_VALUE : FindFirstFileW((desk + L"\\*").c_str(), &fd);
+ if (fh != INVALID_HANDLE_VALUE) {
+ do if (!(fd.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_HIDDEN))) { file = desk + L"\\" + fd.cFileName; break; }
+ while (FindNextFileW(fh, &fd));
+ FindClose(fh);
+ }
+ if (!desk.empty()) ctxmenu::WarmupAsync(desk, file);
+ }
+ return 0;
+ case WM_HOTKEY: shell::Quit(L"atalho Ctrl+Alt+Shift+F12"); return 0;
+ case WM_APP_SETTINGS: shell::OpenSettings(L""); return 0;
+ case WM_APP_SNAP: {
+ HWND fg = GetForegroundWindow();
+ if (!fg) return 0;
+ if (w == VK_LEFT || w == VK_RIGHT) {
+ HWND root = GetAncestor(fg, GA_ROOT);
+ if (root && !apps::IsShellWindow(root) && (GetWindowLongW(root, GWL_STYLE) & WS_THICKFRAME)) encaixe::Half(root, w == VK_RIGHT);
+ return 0;
+ }
+ // o "ampliar" do Mac (MacJanela.dll): ocupa a área de trabalho e mantém cantos e sombra
+ static UINT zoom = RegisterWindowMessageW(L"MacJanelaAmpliar");
+ bool ampliada = GetPropW(fg, L"MacJanelaAmpliada") != nullptr;
+ if (w == VK_UP) { if (!ampliada) PostMessageW(fg, zoom, 0, 0); }
+ else if (ampliada) PostMessageW(fg, zoom, 0, 0);
+ else ShowWindowAsync(fg, SW_MINIMIZE);
+ return 0;
+ }
+ case WM_APP_MISSION:
+ if (launchpad::IsOpen()) launchpad::Toggle();
+ shell::LiberaFrente(); // permite ao Mission Control vir para a frente
+ missioncontrol::Toggle();
+ return 0;
+ case WM_APP_EXPOSE: {
+ HWND fg = GetForegroundWindow();
+ HWND root = fg ? GetAncestor(fg, GA_ROOTOWNER) : nullptr;
+ apps::Refresh();
+ App* a = root && !apps::IsShellWindow(root) ? apps::OfWindow(root) : nullptr;
+ if (!a) { Log(L"Exposé do app: a janela da frente não é de um app do Dock"); return 0; }
+ if (launchpad::IsOpen()) launchpad::Toggle();
+ shell::LiberaFrente(); // permite ao Exposé vir para a frente
+ missioncontrol::ToggleApp(a->id, a->name);
+ return 0;
+ }
+ case WM_APP_MACKEY: {
+ HWND fg = GetForegroundWindow();
+ HWND root = fg ? GetAncestor(fg, GA_ROOT) : nullptr;
+ if (!root || apps::IsShellWindow(root) || apps::IsShellWindow(GetAncestor(root, GA_ROOTOWNER))) return 0; // Dock, mesa, painéis
+ if (w == 'W') { // fecha só a janela da frente (o app continua aberto)
+ Log(L"atalho Win+W: fechando a janela %p", root);
+ PostMessageW(root, WM_SYSCOMMAND, SC_CLOSE, 0);
+ return 0;
+ }
+ apps::Refresh();
+ App* a = apps::OfWindow(GetAncestor(root, GA_ROOTOWNER));
+ if (!a) a = apps::OfWindow(root);
+ if (!a) { Log(L"atalho Win+%lc: janela da frente sem app no Dock", (wchar_t)w); return 0; }
+ if (w == 'Q') {
+ if (a->finder) return 0; // como no Mac: o Finder não se encerra
+ Log(L"atalho Win+Q: encerrando %ls", a->name.c_str());
+ apps::Quit(*a);
+ } else {
+ Log(L"atalho Win+H: ocultando %ls", a->name.c_str());
+ apps::Hide(*a);
+ }
+ dock::Update();
+ return 0;
+ }
+ case WM_APP_LOCK:
+ bloqueio::Lock(); // o bloqueio do Windows (a tela do WacOS saiu)
+ return 0;
+ case WM_APP_MONITOR:
+ if (w == 1) shell::OpenForceQuit(false); else shell::OpenMonitor();
+ return 0;
+ case WM_APP_SWITCH: seletor::Step((int)(INT_PTR)w); return 0;
+ case WM_APP_SWITCH_KEY: seletor::Key((UINT)w); return 0;
+ case WM_APP_SWITCH_END: seletor::Release(); return 0;
+ case WM_APP_SIRI:
+ if (launchpad::IsOpen()) launchpad::Toggle();
+ if (spotlight::IsOpen()) spotlight::Toggle();
+ shell::LiberaFrente();
+ siri::Abrir();
+ return 0;
+ case WM_APP_SPOTLIGHT:
+ if (launchpad::IsOpen()) launchpad::Toggle();
+ shell::LiberaFrente(); // permite ao Spotlight vir para a frente e receber o teclado
+ spotlight::Toggle();
+ return 0;
+ case WM_APP_LAUNCHPAD:
+ shell::LiberaFrente(); // permite ao Launchpad vir para a frente
+ launchpad::Toggle();
+ return 0;
+ case WM_APP_WINKEY: mesa::WinKey((UINT)w); return 0;
+ case WM_APP_CAPTURA: Screenshot((int)w, l != 0); return 0;
+ case WM_APP_VOLUME:
+ if (w == VK_F14 || w == VK_F15) { central::BrilhoPasso(w == VK_F15 ? 1 : -1); return 0; } // brilho (issue #38)
+ if (w == VK_MEDIA_PLAY_PAUSE || w == VK_MEDIA_NEXT_TRACK || w == VK_MEDIA_PREV_TRACK || w == VK_MEDIA_STOP) { // issue #37
+ atalhos::MediaCommand(L"", L"", w == VK_MEDIA_NEXT_TRACK ? 1 : w == VK_MEDIA_PREV_TRACK ? 2 : w == VK_MEDIA_STOP ? 3 : 0);
+ return 0;
+ }
+ som::Key((UINT)w, l != 0); return 0;
+ case WM_SYSCOMMAND:
+ if ((w & 0xFFF0) == SC_TASKLIST) { // Ctrl+Esc com o Shell como Taskman (sem Explorador): Launchpad
+ shell::LiberaFrente();
+ launchpad::Toggle();
+ return 0;
+ }
+ break;
+ case WM_QUERYENDSESSION: return TRUE;
+ case WM_ENDSESSION: if (w) { Log(L"fim da sessão do Windows"); g_sessionEnding = true; Restore(); } return 0;
+ }
+ return DefWindowProcW(h, m, w, l);
+}
+
+int AjudanteRodar(const wchar_t* cmd); // ajudante.cpp: --sair, --aplicar-cursor... (para os scripts do instalador)
+
+int WINAPI wWinMain(HINSTANCE hi, HINSTANCE, PWSTR, int) {
+ if (int r = AjudanteRodar(GetCommandLineW()); r >= 0) return r;
+ if (migrar::TrocarPeloNovo()) return 0; // nome velho (SequoiaShell.exe): o WacOSShell.exe ao lado assume
+ if (const wchar_t* a = wcsstr(GetCommandLineW(), L"--depois-de ")) { // reinício: espera o Shell antigo sair (até 20 s)
+ if (HANDLE old = OpenProcess(SYNCHRONIZE, FALSE, wcstoul(a + 12, nullptr, 10))) { WaitForSingleObject(old, 20000); CloseHandle(old); }
+ }
+ if (bloqueio::Watchdog(GetCommandLineW())) return 0; // vigia da tela de bloqueio (outro processo)
+ if (mesa::Watchdog(GetCommandLineW())) return 0; // vigia da mesa: Shell caiu sem Explorador → abre o Explorador
+ if (wcsstr(GetCommandLineW(), L"--bloqueio-png ")) { // imagem de teste da tela de bloqueio
+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ OleInitialize(nullptr);
+ LoadSettings(); // o tema (Tahoe/Sequoia) e o idioma valem também na imagem de teste
+ if (ui::Init()) bloqueio::RenderPng(GetCommandLineW());
+ return 0;
+ }
+ if (wcsstr(GetCommandLineW(), L"--senha-bloqueio")) { // define a senha própria da tela de bloqueio
+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ return bloqueio::SetPasswordUi(hi);
+ }
+ if (wcsstr(GetCommandLineW(), L"--testar-bloqueio")) { // a tela de bloqueio por ~3,5 s, sem conferir senha
+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ OleInitialize(nullptr);
+ return ui::Init() ? bloqueio::Preview(hi) : 1;
+ }
+ if (wcsstr(GetCommandLineW(), L"--testar-boot")) { SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); return boot::Preview(hi); }
+ HANDLE single = CreateMutexW(nullptr, TRUE, L"ShellProprioUmaInstancia");
+ if (GetLastError() == ERROR_ALREADY_EXISTS) {
+ // reinício: o Shell antigo ainda não largou (preso no relatório de erro do Windows, por exemplo).
+ // Antes o novo desistia e ficava sem Shell nenhum; agora espera ele sair (até 60 s)
+ DWORD w = wcsstr(GetCommandLineW(), L"--depois-de ") && single ? WaitForSingleObject(single, 60000) : WAIT_TIMEOUT;
+ if (w != WAIT_OBJECT_0 && w != WAIT_ABANDONED) return 0;
+ }
+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ shell::inst = hi;
+ wchar_t exe[MAX_PATH]; GetModuleFileNameW(nullptr, exe, MAX_PATH);
+ shell::dir = exe; shell::dir = shell::dir.substr(0, shell::dir.find_last_of(L'\\'));
+ // o log da sessão anterior fica em shell-anterior.log (o vigia escreve lá o motivo de um reinício)
+ MoveFileExW((shell::dir + L"\\shell.log").c_str(), (shell::dir + L"\\shell-anterior.log").c_str(), MOVEFILE_REPLACE_EXISTING);
+ g_log = _wfsopen((shell::dir + L"\\shell.log").c_str(), L"w, ccs=UTF-8", _SH_DENYNO);
+ Log(L"Shell iniciando");
+ OleInitialize(nullptr);
+ ctxmenu::Init(hi, nullptr); // sem log: o menu gravava e esperava o disco na thread da interface (mesma trava do arquivo do Log)
+ if (!ui::Init()) { Log(L"erro: Direct2D/DirectWrite"); return 1; }
+ LoadSettings();
+ migrar::Registro(); // caminhos com o nome velho (Sequoia) no registro do Windows (depois dos ajustes: grava um)
+ // Voltando depois de "Desligar o WacOS" (Ajustes > Geral): o desligar mandou as pastas e o Win+E de volta para o
+ // Explorador (finder_padrao=0). Abrir o WacOS de novo devolve ao Finder; antes o 0 ficava e o Win+E abria o
+ // Explorador até apagar os ajustes (issue #1). Quem desligar "Abrir pastas no Finder" à mão continua com o 0.
+ if (shell::Setting(L"finder_volta", L"") == L"1") {
+ shell::SetSetting(L"finder_volta", L"");
+ std::wstring finder = shell::dir + L"\\" EXE_FINDER;
+ if (GetFileAttributesW(finder.c_str()) != INVALID_FILE_ATTRIBUTES) {
+ shell::SetSetting(L"finder_padrao", L"1");
+ shell::Abrir(L"open", finder.c_str(), L"--quieto --padrao on", nullptr, SW_HIDE);
+ Log(L"finder: de volta depois do Desligar (finder_padrao=1, --padrao on)");
+ }
+ }
+ boot::Show(hi); // tela de inicialização do Mac (só logo depois do login)
+ SetUnhandledExceptionFilter(OnCrash);
+ SystemParametersInfoW(SPI_GETWORKAREA, 0, &g_origWork, 0);
+
+ simbolo::Dir() = shell::dir.substr(0, shell::dir.find_last_of(L'\\')) + L"\\icones\\simbolos"; // SF Symbols da barra de menus
+ apps::Load(shell::dir + L"\\" EXE_FINDER);
+ apps::Refresh();
+
+ WNDCLASSW mc{}; mc.lpfnWndProc = MsgProc; mc.hInstance = hi; mc.lpszClassName = L"ShellMensagens";
+ RegisterClassW(&mc);
+ g_msg = CreateWindowExW(WS_EX_TOOLWINDOW, mc.lpszClassName, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, hi, nullptr);
+ apps::ours.push_back(g_msg);
+ // os menus de contexto dos apps (Finder...) pedem o vidro mesmo com o Shell como administrador
+ ChangeWindowMessageFilterEx(g_msg, RegisterWindowMessageW(L"WacOSMenuVidro"), MSGFLT_ALLOW, nullptr);
+ atualizacao::Start(g_msg); // aviso de versão nova no GitHub (90 s depois e a cada 6 h)
+ boot::Progress(0.2f);
+
+ if (!menubar::Create(hi) || !dock::Create(hi) || !launchpad::Create(hi) || !missioncontrol::Create(hi) || !central::Create(hi) || !spotlight::Create(hi) || !alertas::Create(hi) || !sobre::Create(hi) || !seletor::Create(hi) || !som::Create(hi)) { Log(L"erro criando as janelas"); Restore(); return 1; }
+ // "Só Dock e barra de menus" (Reddit, anybody001): o que não é a barra nem o Dock fica de fora (ver shell::SoDock)
+ const bool soDock = shell::SoDock();
+ if (soDock) Log(L"modo: só Dock e barra de menus (a área de trabalho, o Alt+Tab, as pastas e as barras de título ficam com o Windows)");
+ instalados::Start(); // programa instalado ou removido: o Spotlight e o Launchpad releem os apps
+ indice::Start(); // índice de arquivos do Spotlight (thread de fundo)
+ if (!soDock) revelar::Start(); // clique no vazio da área de trabalho mostra a mesa
+ if (!soDock) ponteiro::Start(); // sacudir o mouse: o ponteiro cresce para achar
+ ponteiro::TemaLeopard(liquid::Leopard()); // tema Leopard: o cursor do Mac OS X (ou devolve o de antes)
+ genio::Create(hi); // efeito gênio ao minimizar
+ if (!soDock) palco::Sync(); // Organizador Visual (Stage Manager), se ligado
+ if (!soDock) widgets::Create(hi); // widgets na mesa (abaixo de todas as janelas)
+ // a tela de bloqueio do WacOS saiu (21/11/2026): bloquear usa o do Windows (bloqueio::Lock)
+ notificacoes::Create(hi); // Central de Notificações (clique no relógio da barra de menus)
+ ilha::Create(hi); // Ilha Dinâmica (ajuste ilha=1)
+ if (!soDock) notarapida::Create(hi); // canto inferior direito: Nota Rápida
+ if (!soDock) progresso::Create(hi); // copiar/mover/apagar: a janela de progresso do Finder no lugar da do Windows
+ if (!soDock) cantos::Start(); // Cantos Ativos (Mission Control, mesa, Launchpad... por canto)
+ jogo::Start(); // Modo Jogo: jogo na frente desliga o que mais pesa (vidro real, ganchos do mouse...)
+ leve::Start(); // Modo leve: PC fraco ou na bateria (sem vidro real, ~60 quadros/s); vigia tomada/bateria
+ brilho::Start(); // brilho da tela do notebook na Ilha (issue #39)
+ boot::Progress(0.7f);
+ tray::Start([] { menubar::Update(); });
+ mesa::Start(hi, g_msg); // ajuste explorer=0: a mesa é nossa e o explorer.exe sai (só Dock: a do Windows, mas o vigia fica)
+ menus::Start();
+ if (!soDock) dialogs::Start();
+ if (!soDock) janelas::Start();
+ if (!soDock) encaixe::Start(); // arrastar até a borda: metade, quarto, preencher (com a prévia)
+ if (!soDock) memoria::Start(); // pressão de memória, soneca de apps (App Nap), memória descartável
+ if (!soDock) pastas::Start(); // janelas de pasta do Explorador viram o Finder
+ limites::Start(); // janelas não cruzam a barra de menus nem o Dock
+ if (!soDock) sombras::Start();
+ HideTaskbars();
+ if (!shell::nativo) SetWinEventHook(EVENT_OBJECT_SHOW, EVENT_OBJECT_SHOW, nullptr, OnBarraWindows, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
+ SecondaryTaskbarsOff(); // barra do Windows nos outros monitores: desligada enquanto o Shell roda
+ shell::ApplyWorkArea();
+
+ WM_SHELLHOOK = RegisterWindowMessageW(L"SHELLHOOK");
+ RegisterShellHookWindow(g_msg);
+ RegisterHotKey(g_msg, 1, MOD_CONTROL | MOD_ALT | MOD_SHIFT | MOD_NOREPEAT, VK_F12); // era Q: fácil de apertar sem querer
+ // só Dock: a tecla Windows, o Alt+Tab e a captura de tela ficam com o Windows (o gancho só deixa passar)
+ g_fullHook = !soDock && shell::Setting(L"tecla_windows_launchpad", L"1") == L"1";
+ g_macKeys = !soDock && shell::Setting(L"atalhos_mac", L"1") == L"1";
+ g_capturaExe = !soDock && GetFileAttributesW((shell::dir + L"\\" EXE_SCREENSHOT).c_str()) != INVALID_FILE_ATTRIBUTES;
+ if (!soDock) EnsureScreenshot();
+ g_volumeKeys = shell::Setting(L"volume_mac", L"1") == L"1";
+ if (g_fullHook || g_volumeKeys || (!soDock && shell::Setting(L"bloqueio", L"1") != L"0")) std::thread(KeyThread).detach(); // sem o Launchpad: só barra teclas com a tela travada
+ SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr, OnWinEvent, 0, 0, WINEVENT_OUTOFCONTEXT);
+ jogo::GanchoPosicao(OnWinEvent, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS); // sai no modo jogo (jogo.cpp)
+ SetTimer(g_msg, 1, 1000, nullptr);
+ SetTimer(g_msg, 2, 200, nullptr);
+ SetTimer(g_msg, 9, 3000, nullptr); // pré-carregar o menu de contexto (depois que o Shell já apareceu)
+ Log(L"pronto: %zu apps no Dock", apps::list.size());
+ boot::Done();
+ mesa::RunStartupApps(); // só quando o Shell é o shell do Windows (o Explorador não abre no login)
+ PreloadApps();
+
+ MSG msg;
+ sentinela::Start(g_msg); // interface parada 1 s ou mais: o shell.log diz onde (issue #32)
+ while (GetMessageW(&msg, nullptr, 0, 0)) { mesa::Pulse(); sentinela::ultimaMsg = msg.message; sentinela::ultimaJanela = msg.hwnd; TranslateMessage(&msg); DispatchMessageW(&msg); } // pulso: ver mesa::Pulse
+ Restore();
+ DeregisterShellHookWindow(g_msg);
+ // Sai daqui direto (TerminateProcess), com tudo já devolvido ao Windows. Voltar do wWinMain roda o
+ // encerramento do C++ (fecha todos os arquivos, inclusive o log; OleUninitialize desmonta o COM) com as
+ // threads de fundo (vidro real, índice, notificações) ainda rodando: elas escreviam no log fechado e o
+ // Shell caía ao reiniciar (0xC0000005), e o Windows segurava o processo morto no relatório de erro.
+ LogDescarrega();
+ if (g_log) fflush(g_log);
+ ReleaseMutex(single);
+ TerminateProcess(GetCurrentProcess(), 0);
+ return 0;
+}
+
+// ---- modo nativo: o Shell como a barra de tarefas do Windows (barra-nativa\MacBarra.dll, dentro do explorer.exe).
+// A MacBarra chama numa thread própria quando o explorer cria a barra (ITrayUI::OnCreate) e esta função só
+// volta quando a barra é destruída. Mesmas peças do WacOSShell.exe, menos as que são de processo:
+// mutex de instância única, DPI do processo, tela de inicialização, filtro de falhas, TerminateProcess,
+// mesa própria (a mesa é do explorer), tela de bloqueio própria (é o AuthUX), ganchos com DLL nos outros
+// programas (janelas.cpp) e esconder a barra do Windows (ela somos nós).
+int shell::RodarNativo(HINSTANCE hi, const std::wstring& dirBin, const std::wstring& logPath) {
+ nativo = true;
+ SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ shell::inst = hi;
+ shell::dir = dirBin;
+ g_log = _wfsopen(logPath.c_str(), L"w, ccs=UTF-8", _SH_DENYNO);
+ Log(L"Shell nativo iniciando dentro do explorer (pid %lu), pasta %ls", GetCurrentProcessId(), dirBin.c_str());
+ OleInitialize(nullptr);
+ ctxmenu::Init(hi, nullptr); // sem log: o menu gravava e esperava o disco na thread da interface (mesma trava do arquivo do Log)
+ if (!ui::Init()) { Log(L"erro: Direct2D/DirectWrite"); return 1; }
+ LoadSettings();
+ SystemParametersInfoW(SPI_GETWORKAREA, 0, &g_origWork, 0);
+
+ simbolo::Dir() = shell::dir.substr(0, shell::dir.find_last_of(L'\\')) + L"\\icones\\simbolos";
+ simbolo::Preload(); // os SF Symbols numa thread: desenhar nunca espera o disco (simbolos.h)
+ apps::Load(shell::dir + L"\\" EXE_FINDER);
+ apps::Refresh();
+
+ WNDCLASSW mc{}; mc.lpfnWndProc = MsgProc; mc.hInstance = hi; mc.lpszClassName = L"ShellMensagens";
+ RegisterClassW(&mc);
+ g_msg = CreateWindowExW(WS_EX_TOOLWINDOW, mc.lpszClassName, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, hi, nullptr);
+ apps::ours.push_back(g_msg);
+ ChangeWindowMessageFilterEx(g_msg, RegisterWindowMessageW(L"WacOSMenuVidro"), MSGFLT_ALLOW, nullptr);
+ atualizacao::Start(g_msg); // aviso de versão nova no GitHub (90 s depois e a cada 6 h)
+
+ if (!menubar::Create(hi) || !dock::Create(hi) || !launchpad::Create(hi) || !missioncontrol::Create(hi) || !central::Create(hi) || !spotlight::Create(hi) || !alertas::Create(hi) || !sobre::Create(hi) || !seletor::Create(hi) || !som::Create(hi)) { Log(L"erro criando as janelas"); Restore(); return 1; }
+ instalados::Start();
+ indice::Start();
+ revelar::Start();
+ ponteiro::Start();
+ ponteiro::TemaLeopard(liquid::Leopard());
+ genio::Create(hi);
+ widgets::Create(hi);
+ notificacoes::Create(hi);
+ ilha::Create(hi);
+ notarapida::Create(hi);
+ progresso::Create(hi);
+ cantos::Start();
+ tray::Start([] { menubar::Update(); }); // nativo: sem janela; os ícones chegam por tray::DoExplorer
+ menus::Start();
+ dialogs::Start();
+ pastas::Start();
+ if (GetFileAttributesW(L"C:\\Users\\Public\\MacMesa-desligada.txt") == INVALID_FILE_ATTRIBUTES)
+ mesa::Start(hi, g_msg); // nativo: a mesa do projeto por cima da do Explorador (mesmo processo)
+ else Log(L"MacMesa-desligada.txt: a mesa fica com o Windows");
+ limites::Start();
+ sombras::Start();
+ // Cantos do Mac (maiores que os 8 px do Windows), sombra e animações nas janelas com a barra padrão: só a
+ // WacOSWindow.dll DENTRO dos programas consegue (autorizado pelo usuário em 12/11/2026, "pode injetar").
+ // Ela cuida das janelas de barra padrão; as de barra própria (Chrome, Bloco de Notas...) continuam com barras.cpp.
+ // C:\Users\Public\MacInjecao-desligada.txt volta a não carregar nada nos outros programas.
+ if (GetFileAttributesW(L"C:\\Users\\Public\\MacInjecao-desligada.txt") == INVALID_FILE_ATTRIBUTES) janelas::Start();
+ else Log(L"MacInjecao-desligada.txt: nada é carregado nos outros programas (cantos de 8 px)");
+ barras::Start(); // nativo: barra de título do Mac por fora (sem nada dentro dos outros programas)
+ shell::ApplyWorkArea();
+
+ WM_SHELLHOOK = RegisterWindowMessageW(L"SHELLHOOK");
+ RegisterShellHookWindow(g_msg);
+ g_fullHook = shell::Setting(L"tecla_windows_launchpad", L"1") == L"1";
+ g_macKeys = shell::Setting(L"atalhos_mac", L"1") == L"1";
+ g_capturaExe = GetFileAttributesW((shell::dir + L"\\" EXE_SCREENSHOT).c_str()) != INVALID_FILE_ATTRIBUTES;
+ EnsureScreenshot();
+ g_volumeKeys = shell::Setting(L"volume_mac", L"1") == L"1";
+ if (g_fullHook || g_volumeKeys) std::thread(KeyThread).detach();
+ SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr, OnWinEvent, 0, 0, WINEVENT_OUTOFCONTEXT);
+ jogo::GanchoPosicao(OnWinEvent, WINEVENT_OUTOFCONTEXT); // sai no modo jogo (jogo.cpp)
+ SetTimer(g_msg, 1, 1000, nullptr);
+ SetTimer(g_msg, 9, 3000, nullptr);
+ Log(L"pronto (nativo): %zu apps no Dock", apps::list.size());
+ PreloadApps();
+
+ MSG msg;
+ sentinela::Start(g_msg); // interface parada 1 s ou mais: o shell.log diz onde (issue #32)
+ while (GetMessageW(&msg, nullptr, 0, 0)) { mesa::Pulse(); sentinela::ultimaMsg = msg.message; sentinela::ultimaJanela = msg.hwnd; TranslateMessage(&msg); DispatchMessageW(&msg); } // pulso: ver mesa::Pulse
+ Restore();
+ DeregisterShellHookWindow(g_msg);
+ Log(L"Shell nativo encerrado");
+ LogDescarrega();
+ if (g_log) fflush(g_log);
+ return 0;
+}
diff --git a/src/shell/menubar.cpp b/src/shell/menubar.cpp
index 1d2b007..d7f180a 100644
--- a/src/shell/menubar.cpp
+++ b/src/shell/menubar.cpp
@@ -888,20 +888,16 @@ void Render() {
// Controle e a data/hora: laranja = microfone, verde = câmera (a câmera ganha). barra_privacidade=0 tira.
if (shell::Setting(L"barra_privacidade", L"1") != L"0")
if (int pv = ilha::Privacidade()) {
+ D2D1_COLOR_F antes = br->GetColor();
br->SetColor(pv & 2 ? D2D1::ColorF(0.20f, 0.78f, 0.35f) : D2D1::ColorF(1.0f, 0.58f, 0.0f));
rt->FillEllipse(D2D1::Ellipse({ r, H / 2 }, 3, 3), br); // no meio do vão (os dois PAD): nada anda de lugar
+ br->SetColor(antes); // os ícones seguintes (Siri, Central de Controle) voltam à cor da barra
}
// a Siri entre o relógio e a Central de Controle, como no macOS (só com um serviço escolhido; barra_siri=0 tira)
if (siri::Pronta() && shell::Setting(L"barra_siri", L"1") != L"0") {
auto bx = slot(16, K_SIRI, 0);
- float cx = (bx.left + bx.right) / 2, r = 7.f;
- D2D1_GRADIENT_STOP gs[3] = { { 0, D2D1::ColorF(0.98f, 0.36f, 0.62f) }, { 0.5f, D2D1::ColorF(0.62f, 0.38f, 1.f) }, { 1, D2D1::ColorF(0.25f, 0.62f, 1.f) } };
- ID2D1GradientStopCollection* gsc = nullptr; ID2D1LinearGradientBrush* lg = nullptr;
- if (SUCCEEDED(rt->CreateGradientStopCollection(gs, 3, &gsc)) &&
- SUCCEEDED(rt->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ cx - r, H / 2 - r }, { cx + r, H / 2 + r }), gsc, &lg)))
- rt->FillEllipse(D2D1::Ellipse({ cx, H / 2 }, r, r), lg);
- if (lg) lg->Release();
- if (gsc) gsc->Release();
+ // como no macOS: o símbolo do Apple Intelligence na cor da barra, igual aos outros ícones (o colorido fica no app)
+ if (!sym(L"apple.intelligence", bx, 16)) rt->DrawEllipse(D2D1::Ellipse({ (bx.left + bx.right) / 2, H / 2 }, 6.5f, 6.5f), br, 1.6f);
}
{ auto bx = slot(18, K_CC, 0); if (!sym(L"switch.2", bx, 14)) DrawCC(rt, br, (bx.left + bx.right) / 2, H / 2); }
if (!leo && shell::Setting(L"barra_spotlight", L"1") == L"1") {
diff --git a/src/shell/mesa.cpp b/src/shell/mesa.cpp
index c655f2f..f5e3d8a 100644
--- a/src/shell/mesa.cpp
+++ b/src/shell/mesa.cpp
@@ -1674,7 +1674,9 @@ void Tick() {
if (shell::SoDock()) opt = L"1"; // só Dock e barra de menus: a área de trabalho e os ícones são os do Windows
bool registered = WinlogonIsOurs();
bool want0 = opt == L"0";
- g_fundo = opt == L"fundo" || (opt.empty() && registered);
+ // sem o ajuste: fundo (o padrão do instalador). Antes, vazio e sem o registro do Winlogon = a mesa do Explorador, e quem
+ // perdeu a linha do ajustes.txt ficava com os ícones e o menu de clique direito do Windows (23/11/2026)
+ g_fundo = opt == L"fundo" || opt.empty();
// nativo: o Shell roda dentro do explorer.exe; a mesa do projeto fica por cima da dele (os ícones e o papel
// de parede do Windows ficam atrás, sem uso) e nunca se pede para o Explorador sair
if (shell::nativo) { g_fundo = true; g_uwpWant = false; }
diff --git a/src/shell/shell.h b/src/shell/shell.h
index b2ad52f..b9e1686 100644
--- a/src/shell/shell.h
+++ b/src/shell/shell.h
@@ -94,6 +94,8 @@ void GpuSoltarEscondida(GpuSurface& s); // painel de tela cheia: solta os buffe
void GpuOffset(GpuSurface& s, float x, float y);
void GpuScale(GpuSurface& s, float scale, float cx, float cy); // escala o desenho em volta de (cx, cy) px (animação dos painéis)
void GpuMotion(GpuSurface& s, float scale, float cx, float cy, float opacity); // escala e opacidade (a mola dos painéis)
+// a mesma coisa animada pelo compositor: a curva amostrada a cada passoMs (escala e opacidade), tocada pelo DWM no vsync
+void GpuMotionAnim(GpuSurface& s, float cx, float cy, const std::vector<float>& escala, const std::vector<float>& opac, float passoMs);
// Desliza o conteúdo (px) de (fromX, fromY) até (toX, toY) em `ms`, com ease-out, pelo próprio compositor.
void GpuSlide(GpuSurface& s, float fromX, float fromY, float toX, float toY, float ms);
// Quadros no ritmo do monitor: enquanto `on`, manda `msg` para `hwnd` a cada atualização da tela.
@@ -352,6 +354,8 @@ bool IsOpen();
void OpenMode(int mode); // Tahoe: abre direto num modo (1 Aplicativos = o "Apps" do Dock, 2 Arquivos, 3 Ações); de novo fecha
void Rescan(); // relê a lista de apps (um programa foi instalado ou removido)
void ClickedDesktop(); // clique na mesa (gancho do revelar.cpp, outra thread): aberto, fecha
+RECT Lugar(); // onde o painel abre agora (px): a Siri abre alinhada a ele
+float LarguraCampo(); // a largura do campo de busca (DIP) no tema atual
}
namespace dashboard { // Dashboard do Leopard (dashboard.cpp): Win+F12 / ShellAbrirPainel 16
bool Create(HINSTANCE hi);
@@ -469,6 +473,12 @@ void PrivacidadeMudou(); // a bandeja mudou: relê o ícone de privacidad
void Captura(bool copiada); // a Captura de Tela terminou: aviso rápido "Captura feita" / "Captura copiada"
int Privacidade(); // 1 microfone, 2 câmera em uso (bits); a 1ª chamada liga a vigia; mudou = menubar::Update()
}
+namespace voz { // voz.cpp: ditado pelo reconhecimento de fala do Windows (o microfone da Siri e do Spotlight)
+enum Tipo { V_PARCIAL, V_FINAL, V_ERRO, V_PRIVACIDADE };
+void Ouvir(HWND to, UINT msg); // uma frase: msg com wParam = Tipo e lParam = new std::wstring (quem recebe apaga)
+void Parar();
+bool Ouvindo();
+}
namespace siri { // siri.cpp: a Siri com a chave do usuário (issue #39); provedores e chave em src/comum/siri.h
bool Pronta(); // um serviço escolhido nos Ajustes (e a chave, se ele pede)
void Perguntar(const std::wstring& q, bool teste = false);
@@ -509,7 +519,7 @@ void Run(const Item& it);
// o que o app está tocando (controles de mídia do Windows), como no menu do Spotify no Dock do Mac
struct Media { bool has = false, playing = false, canNext = false, canPrev = false; std::wstring title, artist; };
Media MediaOf(const std::wstring& exePath, const std::wstring& aumid);
-void MediaCommand(const std::wstring& exePath, const std::wstring& aumid, int cmd); // 0 tocar/pausar, 1 próxima, 2 anterior
+void MediaCommand(const std::wstring& exePath, const std::wstring& aumid, int cmd); // 0 tocar/pausar, 1 próxima, 2 anterior, 3 parar; sem app: a sessão atual
}
namespace cantos { // Cantos Ativos (cantos.cpp): canto_se/sd/ie/id = nada|mission|mesa|launchpad|notificacoes|central|spotlight|bloquear|tela|nota
void Start();
@@ -583,6 +593,7 @@ void Detach(HWND h); // a janela vai ser destruída: solta o vidro dela
void Restart(); // refaz o vidro real do zero (Ajustes: "Reiniciar o Liquid Glass")
void Set(HWND h, float w, float hgt, float radius, D2D1_COLOR_F tint); // px
void Fade(HWND h, float opacity, float scale, float cx, float cy); // animação: opacidade e escala em volta de (cx, cy) px
+void FadeAnim(HWND h, float cx, float cy, const std::vector<float>& escala, const std::vector<float>& opac, float passoMs); // pela Composição
void FadeOutAnim(HWND h, int ms); // some em ms pela Composição (não depende desta thread)
// Conteúdo desenhado DENTRO do vidro (mesma árvore da Composição): vidro e desenho chegam à tela no mesmo
// quadro. Numa janela à parte (swap chain), a borda do vidro ficava um quadro atrás do desenho quando o
diff --git a/src/shell/siri.cpp b/src/shell/siri.cpp
index 7974d14..94725a1 100644
--- a/src/shell/siri.cpp
+++ b/src/shell/siri.cpp
@@ -1,659 +1,820 @@
-// Siri (issue #39, 23/11/2026): pergunta pelo Spotlight ("Perguntar à Siri") e a resposta num painel de vidro no alto
-// da tela, como a Siri do macOS. Não há servidor do WacOS: a pergunta vai direto do PC para o serviço que o usuário
-// escolheu nos Ajustes (Gemini, Groq, OpenAI ou o Ollama local), com a chave dele (src/comum/siri.h).
-// A chamada roda numa thread (WinHTTP, até 60 s); cada pergunta tem um número, e a resposta de uma pergunta antiga
-// (painel fechado ou outra pergunta feita) é descartada. Esc ou clicar fora fecha; Ctrl+C copia a resposta.
-#include "shell.h"
-#include "../comum/siri.h"
-#include "../comum/simbolos.h"
-#include "../comum/idioma.h"
-#include <dwmapi.h>
-#include <windowsx.h>
-#include <thread>
-#include <atomic>
-#include <algorithm>
-#include <cmath>
-
-namespace {
-
-const UINT WM_SIRI_FIM = WM_APP + 70, WM_SIRI_FRAME = WM_APP + 71;
-const UINT_PTR T_PONTOS = 1;
-const float W = 560, PAD = 20, ORB = 30, R = 22;
-const float M = 28; // folga em volta do painel para o brilho (os cliques nela atravessam: WM_NCHITTEST)
-
-HWND g_wnd, g_back;
-ui::GpuSurface g_s;
-bool g_glass, g_inGlass, g_open;
-std::wstring g_q, g_a;
-bool g_busy, g_erro;
-std::atomic<int> g_num{ 0 };
-int g_pontos;
-float g_scroll, g_contentH, g_viewH;
-double g_openAt, g_answerAt, g_closeAt;
-bool g_closing;
-bool g_teste;
-// campo de digitar (aberta pelo ícone da barra, ou digitando depois de uma resposta): g_texto é o que foi digitado
-bool g_entrada;
-std::wstring g_texto;
-const UINT_PTR T_CURSOR = 2;
-bool g_cursorOn = true; // 'SIRT' (teste com um jogo na frente): não pega a frente, não fecha ao perder a frente, some em 8 s
-ID2D1StrokeStyle* g_round;
-IDWriteTextFormat *g_tfQ, *g_tfA;
-
-// ---------------------------------------------------------------- a pergunta (thread)
-std::wstring Limpa(std::wstring t) { // os modelos insistem em Markdown: tira o que fica feio em texto puro
- for (const wchar_t* m : { L"**", L"__", L"`" }) for (size_t i; (i = t.find(m)) != std::wstring::npos;) t.erase(i, wcslen(m));
- std::wstring o; bool ini = true;
- for (size_t i = 0; i < t.size(); i++) {
- if (ini) { // "# Título" e "* item" no começo da linha
- while (i < t.size() && t[i] == L'#') i++;
- if (i + 1 < t.size() && (t[i] == L'*' || t[i] == L'-') && t[i + 1] == L' ') { o += L"• "; i += 2; }
- while (i < t.size() && t[i] == L' ' && !o.empty() && o.back() == L'\n') i++;
- }
- if (i >= t.size()) break;
- o += t[i];
- ini = t[i] == L'\n';
- }
- while (!o.empty() && iswspace(o.back())) o.pop_back();
- size_t s = 0; while (s < o.size() && iswspace(o[s])) s++;
- return o.substr(s);
-}
-
-// o modelo não existe mais (ou nunca existiu) para esta conta: os serviços dizem isso de jeitos diferentes
-bool ModeloSumiu(DWORD status, const std::wstring& msg) {
- if (status != 400 && status != 404) return false;
- std::wstring l = msg; for (auto& c : l) c = (wchar_t)towlower(c);
- for (const wchar_t* w : { L"no longer available", L"not found", L"does not exist", L"not supported", L"decommissioned", L"deprecated",
- L"invalid model", L"unknown model", L"model_not_found", L"is not a valid model" })
- if (l.find(w) != std::wstring::npos) return true;
- return false;
-}
-
-// outro modelo da lista para esta pergunta: estável (sem preview/omni/exp/latest/lite), da mesma família (Flash no Gemini)
-std::wstring Reserva(const std::vector<std::wstring>& lista, const std::wstring& atual, bool gemini) {
- std::wstring alt;
- for (auto& m : lista) {
- if (m == atual || m.find(L"lite") != std::wstring::npos || m.find(L"preview") != std::wstring::npos ||
- m.find(L"omni") != std::wstring::npos || m.find(L"exp") != std::wstring::npos || m.find(L"latest") != std::wstring::npos) continue;
- if (!gemini || m.find(L"flash") != std::wstring::npos) return m;
- if (alt.empty()) alt = m;
- }
- return alt;
-}
-
-std::wstring PerguntaCli(const siri::Provedor& pv, const std::wstring& q, bool& erro, int num) {
- const std::wstring instr = L"Answer briefly and clearly, in the same language as the question, in plain text without Markdown. "
- L"Do not run commands or edit files. Question: ";
- DWORD codigo = 0; bool tempo = false;
- wchar_t tmp[MAX_PATH]; GetTempPathW(MAX_PATH, tmp);
- std::wstring ultima = std::wstring(tmp) + L"WacOS-Siri\\ultima.txt";
- DeleteFileW(ultima.c_str());
- // outra pergunta feita ou o painel fechado (g_num mudou): o CLI é encerrado na hora, em vez de seguir até 3 min
- std::wstring r = siri::RodaCli(pv.caminho, instr + q, codigo, tempo, [](void* c) { return *(int*)c != g_num.load(); }, &num);
- if (codigo == ERROR_CANCELLED) return L""; // descartada
- Log(L"siri: %ls -> código %lu, %zu caracteres%ls", pv.nome, codigo, r.size(), tempo ? L" (passou do tempo)" : L"");
- if (tempo) return Tr(L"O app demorou demais para responder.");
- if (codigo == 9009 || codigo == ERROR_FILE_NOT_FOUND) // o cmd não achou o comando
- return std::wstring(Tr(L"Não achei o app neste PC. Instale e entre na sua conta nele:")) + L" " + pv.site;
- // o Codex grava a última mensagem num arquivo (a saída tem o resto da conversa)
- HANDLE h = CreateFileW(ultima.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
- if (h != INVALID_HANDLE_VALUE) {
- DWORD sz = GetFileSize(h, nullptr), n = 0;
- std::string b(sz < (1u << 20) ? sz : 0, 0);
- if (!b.empty() && ReadFile(h, b.data(), sz, &n, nullptr)) r = siri::Wide(b);
- CloseHandle(h);
- DeleteFileW(ultima.c_str());
- }
- if (codigo != 0 || r.empty()) {
- std::wstring t = Limpa(r);
- if (t.size() > 400) t = t.substr(t.size() - 400);
- return std::wstring(Tr(L"O app não respondeu. Ele está instalado e com a conta entrada?")) + (t.empty() ? L"" : L"\n\n" + t);
- }
- erro = false;
- return Limpa(r);
-}
-
-std::wstring Pergunta(const std::wstring& q, bool& erro, int num) {
- erro = true;
- const auto& provs = siri::Provedores();
- int p = std::clamp(_wtoi(shell::Setting(L"siri_provedor", L"0").c_str()), 0, (int)provs.size() - 1);
- if (p == 0) return Tr(L"Escolha um serviço para a Siri em Ajustes do Sistema > Apple Intelligence e Siri.");
- const auto& pv = provs[p];
- if (pv.fmt == siri::F_CLI) return PerguntaCli(pv, q, erro, num);
- std::wstring modelo = shell::Setting(L"siri_modelo", pv.modelos.empty() ? L"" : pv.modelos[0]);
- std::wstring chave = pv.precisaChave ? siri::LeChave(p) : L"";
- if (pv.precisaChave && chave.empty()) return Tr(L"Falta a chave da API. Cole a chave em Ajustes do Sistema > Apple Intelligence e Siri.");
- if (modelo.empty()) { // LM Studio e afins: o modelo carregado
- std::wstring e; auto l = siri::ListaModelos(p, e);
- if (!l.empty()) modelo = l[0];
- }
- const std::wstring sistema = L"You are Siri inside WacOS, a macOS-style desktop for Windows. Answer briefly and clearly, "
- L"in the same language as the question. Use plain text, without Markdown.";
- std::wstring cab = siri::Cabecalhos(pv, chave);
- SecureZeroMemory(chave.data(), chave.size() * sizeof(wchar_t));
- siri::Resposta r;
- bool web = shell::Setting(L"siri_web", L"1") != L"0";
- for (int tentativa = 0; tentativa < 3; tentativa++) {
- std::string body;
- std::wstring caminho = pv.caminho;
- if (pv.fmt == siri::F_GEMINI) {
- size_t m = caminho.find(L"{m}"); if (m != std::wstring::npos) caminho.replace(m, 3, modelo);
- body = "{\"systemInstruction\":{\"parts\":[{\"text\":" + siri::JStr(sistema) + "}]},\"contents\":[{\"role\":\"user\",\"parts\":[{\"text\":" + siri::JStr(q) + "}]}]" +
- // siri_web (issue #42): o Gemini pesquisa no Google antes de responder (notícias, tempo, resultados de hoje)
- (web ? ",\"tools\":[{\"google_search\":{}}]}" : "}");
- } else if (pv.fmt == siri::F_ANTHROPIC) {
- body = "{\"model\":" + siri::JStr(modelo) + ",\"max_tokens\":1024,\"system\":" + siri::JStr(sistema) +
- ",\"messages\":[{\"role\":\"user\",\"content\":" + siri::JStr(q) + "}]}";
- } else { // OpenAI e compatíveis (Groq, OpenRouter, Mistral, DeepSeek, xAI, LM Studio) e Ollama
- body = "{\"model\":" + siri::JStr(modelo) + ",\"messages\":[{\"role\":\"system\",\"content\":" + siri::JStr(sistema) + "},{\"role\":\"user\",\"content\":" + siri::JStr(q) + "}]" +
- (pv.fmt == siri::F_OLLAMA ? ",\"stream\":false}" : "}");
- }
- r = siri::Http(pv, L"POST", caminho, cab, body);
- Log(L"siri: %ls %ls -> %lu (%zu bytes, erro %lu)", pv.nome, modelo.c_str(), r.status, r.corpo.size(), r.falha);
- if (r.falha || tentativa >= 2) break;
- if (web && r.status == 400 && pv.fmt == siri::F_GEMINI) { // o modelo não aceita a pesquisa: de novo, sem ela
- std::wstring m = siri::ErroDoServico(r.corpo); for (auto& c : m) c = (wchar_t)towlower(c);
- if (m.find(L"search") != std::wstring::npos || m.find(L"tool") != std::wstring::npos) { web = false; Log(L"siri: %ls sem a pesquisa na web", modelo.c_str()); continue; }
- }
- if (r.status == 503 || r.status == 500 || r.status == 529) { // sobrecarregado: de novo; depois, outro modelo da lista (só nesta pergunta)
- if (!tentativa) { Sleep(1500); continue; }
- std::wstring e; auto lista = siri::ListaModelos(p, e);
- std::wstring alt;
- alt = Reserva(lista, modelo, pv.fmt == siri::F_GEMINI);
- if (!alt.empty()) { Log(L"siri: %ls sobrecarregado; tentando %ls", modelo.c_str(), alt.c_str()); modelo = alt; continue; }
- break;
- }
- // cota zerada deste modelo (o plano grátis não inclui todos): tenta o preferido da lista, que costuma estar no plano
- std::wstring msgErro = siri::ErroDoServico(r.corpo), lm = msgErro;
- for (auto& c : lm) c = (wchar_t)towlower(c);
- bool semCota = r.status == 429 && lm.find(L"quota") != std::wstring::npos;
- if (semCota) {
- std::wstring e; auto lista = siri::ListaModelos(p, e);
- std::wstring outro = !lista.empty() && lista[0] != modelo ? lista[0] : Reserva(lista, modelo, pv.fmt == siri::F_GEMINI);
- if (!outro.empty()) {
- Log(L"siri: sem cota em %ls; tentando %ls", modelo.c_str(), outro.c_str());
- modelo = outro;
- continue; // só nesta pergunta: a cota volta amanhã, e o escolhido nos Ajustes fica
- }
- }
- if (!ModeloSumiu(r.status, msgErro)) { if (r.status >= 400) Log(L"siri: erro do serviço: %ls", siri::ErroDoServico(r.corpo).substr(0, 200).c_str()); break; }
- // o modelo saiu do ar: pega a lista atual do serviço, guarda o preferido dela e pergunta de novo
- std::wstring e; auto lista = siri::ListaModelos(p, e);
- if (lista.empty() || lista[0] == modelo) { Log(L"siri: o modelo saiu do ar, mas a lista não trouxe outro (%ls)", e.empty() ? L"vazia" : e.c_str()); break; }
- Log(L"siri: %ls não existe mais; agora %ls", modelo.c_str(), lista[0].c_str());
- modelo = lista[0];
- std::wstring junta; for (auto& m : lista) junta += (junta.empty() ? L"" : L"|") + m;
- // pela thread da interface: SetSetting grava o ajustes.txt (num .tmp de nome fixo), e esta thread gravando ao
- // mesmo tempo que a interface podia misturar as duas gravações
- shell::NaInterface([modelo, junta, p] {
- shell::SetSetting(L"siri_modelo", modelo);
- shell::SetSetting((L"siri_modelos_" + std::to_wstring(p)).c_str(), junta);
- });
- }
- SecureZeroMemory(cab.data(), cab.size() * sizeof(wchar_t)); // a chave ia no cabeçalho
- if (r.falha) {
- if (pv.porta != 443) return std::wstring(Tr(L"Não deu para falar com o app neste PC. Ele está aberto?")) + L" (" + pv.nome + L")";
- return Tr(L"Não deu para falar com o serviço. Confira a internet.");
- }
- std::wstring t;
- if (r.status >= 200 && r.status < 300) {
- bool ok = pv.fmt == siri::F_GEMINI ? siri::JLe(r.corpo, "text", r.corpo.find("\"candidates\""), t)
- : pv.fmt == siri::F_ANTHROPIC ? siri::JLe(r.corpo, "text", r.corpo.find("\"content\""), t)
- : siri::JLe(r.corpo, "content", r.corpo.find("\"message\""), t);
- if (ok && !t.empty()) { erro = false; return Limpa(t); }
- return Tr(L"O serviço respondeu sem texto.");
- }
- t = siri::ErroDoServico(r.corpo);
- if (r.status == 429) {
- std::wstring l = t; for (auto& c : l) c = (wchar_t)towlower(c);
- if (l.find(L"quota") != std::wstring::npos || l.find(L"rate") != std::wstring::npos)
- return std::wstring(Tr(L"Acabou a cota deste modelo no seu plano (o grátis tem limite por minuto e por dia). Espere um pouco ou escolha outro modelo em Ajustes do Sistema > Apple Intelligence e Siri.")) + L" (" + modelo + L")";
- }
- // as mensagens dos serviços podem ter várias linhas e links: só a primeira frase
- if (size_t nlPos = t.find(L'\n'); nlPos != std::wstring::npos) t = t.substr(0, nlPos);
- if (t.size() > 240) t = t.substr(0, 237) + L"...";
- if (!t.empty()) return (r.status == 401 || r.status == 403 ? std::wstring(Tr(L"Chave recusada pelo serviço.")) + L" " : std::wstring()) + t;
- return std::wstring(Tr(L"O serviço recusou a pergunta")) + L" (" + std::to_wstring(r.status) + L").";
-}
-
-// ---------------------------------------------------------------- painel
-float Sc() { return g_wnd ? ui::Scale(g_wnd) : 1.f; }
-
-float AlturaTexto(const std::wstring& t, IDWriteTextFormat* f, float w) {
- IDWriteTextLayout* l = nullptr; float h = 0;
- if (f && SUCCEEDED(ui::dw->CreateTextLayout(t.c_str(), (UINT32)t.size(), f, w, 10000, &l))) { DWRITE_TEXT_METRICS m{}; l->GetMetrics(&m); h = m.height; l->Release(); }
- return h;
-}
-
-// ---- o brilho da Siri: uma luz colorida que corre pela borda do painel e se espalha para fora, como a do Apple
-// Intelligence. A cor de cada ponto da borda depende da posição nela e do tempo (as cores andam em volta); por baixo, três
-// traços largos e fracos fazem o brilho; por cima, o fio forte. Enquanto pensa: inteiro e "respirando"; quando a resposta
-// chega, apaga em 0,9 s.
-D2D1_COLOR_F CorDaVolta(float u) { // u em [0,1): rosa, roxo, azul, ciano, laranja e de volta ao rosa
- static const D2D1_COLOR_F c[] = { { 1.f, 0.33f, 0.62f, 1 }, { 0.68f, 0.36f, 1.f, 1 }, { 0.26f, 0.52f, 1.f, 1 },
- { 0.30f, 0.86f, 1.f, 1 }, { 1.f, 0.64f, 0.30f, 1 } };
- const int n = 5;
- u = u - std::floor(u);
- float f = u * n; int a = (int)f % n, b = (a + 1) % n; float k = f - std::floor(f);
- k = k * k * (3 - 2 * k); // suave entre as cores
- return { c[a].r + (c[b].r - c[a].r) * k, c[a].g + (c[b].g - c[a].g) * k, c[a].b + (c[b].b - c[a].b) * k, 1 };
-}
-// ponto da borda do retângulo arredondado em u (0..1, sentido horário a partir do meio de cima)
-D2D1_POINT_2F PontoDaBorda(const D2D1_RECT_F& r, float rad, float u) {
- float w = r.right - r.left, h = r.bottom - r.top, arco = 1.5707963f * rad;
- float retoX = w - 2 * rad, retoY = h - 2 * rad, total = 2 * retoX + 2 * retoY + 4 * arco;
- float d = (u - std::floor(u)) * total;
- auto canto = [&](float cx, float cy, float a0, float t) { float a = a0 + t / rad; return D2D1_POINT_2F{ cx + std::cos(a) * rad, cy + std::sin(a) * rad }; };
- float x0 = r.left + w / 2;
- // do meio de cima para a direita
- float seg = retoX / 2; if (d < seg) return { x0 + d, r.top }; d -= seg;
- if (d < arco) return canto(r.right - rad, r.top + rad, -1.5707963f, d); d -= arco;
- if (d < retoY) return { r.right, r.top + rad + d }; d -= retoY;
- if (d < arco) return canto(r.right - rad, r.bottom - rad, 0, d); d -= arco;
- if (d < retoX) return { r.right - rad - d, r.bottom }; d -= retoX;
- if (d < arco) return canto(r.left + rad, r.bottom - rad, 1.5707963f, d); d -= arco;
- if (d < retoY) return { r.left, r.bottom - rad - d }; d -= retoY;
- if (d < arco) return canto(r.left + rad, r.top + rad, 3.1415926f, d); d -= arco;
- return { r.left + rad + std::min(d, retoX / 2), r.top };
-}
-void Brilho(ID2D1DeviceContext* dc, const D2D1_RECT_F& box, float rad, double tMs, float forca) {
- if (forca <= 0.01f) return;
- ID2D1SolidColorBrush* br = nullptr;
- dc->CreateSolidColorBrush(D2D1::ColorF(1, 1, 1), &br);
- if (!br) return;
- const int N = 240;
- float gira = (float)(tMs / 2600.0); // as cores dão uma volta a cada 2,6 s
- struct Camada { float largura, alfa; } camadas[] = { { 22, 0.06f }, { 13, 0.10f }, { 7, 0.18f }, { 2.6f, 0.95f } };
- ID2D1Factory* fab = nullptr; dc->GetFactory(&fab);
- static ID2D1Factory* fabDoTraco = nullptr;
- if (fab && fab != fabDoTraco) {
- if (g_round) { g_round->Release(); g_round = nullptr; }
- D2D1_STROKE_STYLE_PROPERTIES sp = D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_ROUND);
- fab->CreateStrokeStyle(sp, nullptr, 0, &g_round);
- fabDoTraco = fab;
- }
- if (fab) fab->Release();
- std::vector<D2D1_POINT_2F> pts(N + 1);
- for (int k = 0; k <= N; k++) pts[k] = PontoDaBorda(box, rad, (float)k / N);
- for (auto& cm : camadas) {
- for (int k = 0; k < N; k++) {
- float u = (float)k / N;
- D2D1_COLOR_F c = CorDaVolta(u * 2 + gira); // duas voltas de cor pela borda inteira
- // um trecho mais claro corre pela borda (a "onda" de luz)
- float onda = 0.55f + 0.45f * std::cos(6.2831853f * (u - gira * 0.7f));
- c.a = cm.alfa * forca * (cm.largura > 3 ? onda : 0.75f + 0.25f * onda);
- br->SetColor(c);
- // pontas retas nas camadas translúcidas (as redondas se sobrepunham e faziam "contas" na borda); redondas no fio
- dc->DrawLine(pts[k], pts[k + 1], br, cm.largura, cm.largura > 3 ? nullptr : g_round);
- }
- }
- br->Release();
-}
-
-void Orbe(ID2D1DeviceContext* dc, D2D1_POINT_2F c, float r, double t) {
- // a bolinha da Siri: as cores giram enquanto pensa (e devagar depois), com um brilho que pulsa
- D2D1_GRADIENT_STOP gs[4] = { { 0, D2D1::ColorF(0.98f, 0.36f, 0.62f) }, { 0.35f, D2D1::ColorF(0.62f, 0.38f, 1.f) },
- { 0.7f, D2D1::ColorF(0.25f, 0.62f, 1.f) }, { 1, D2D1::ColorF(1.f, 0.62f, 0.32f) } };
- ID2D1GradientStopCollection* sc = nullptr;
- if (FAILED(dc->CreateGradientStopCollection(gs, 4, &sc))) return;
- float a = (float)(t / (g_busy ? 700.0 : 2400.0));
- float pulso = g_busy ? 1.f + 0.07f * (float)std::sin(t / 260.0) : 1.f;
- float rr = r * pulso;
- ID2D1SolidColorBrush* br = nullptr;
- dc->CreateSolidColorBrush(D2D1::ColorF(0.62f, 0.38f, 1.f, g_busy ? 0.22f : 0.12f), &br);
- if (br) { dc->FillEllipse(D2D1::Ellipse(c, rr + 5, rr + 5), br); } // halo
- D2D1_POINT_2F p0{ c.x + std::cos(a) * rr, c.y + std::sin(a) * rr }, p1{ c.x - std::cos(a) * rr, c.y - std::sin(a) * rr };
- ID2D1LinearGradientBrush* lg = nullptr;
- if (SUCCEEDED(dc->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties(p0, p1), sc, &lg))) {
- dc->FillEllipse(D2D1::Ellipse(c, rr, rr), lg);
- lg->Release();
- }
- sc->Release();
- if (br) { // reflexo em cima, como uma bolha de vidro
- br->SetColor(D2D1::ColorF(1, 1, 1, 0.38f));
- dc->FillEllipse(D2D1::Ellipse({ c.x - rr * 0.25f, c.y - rr * 0.38f }, rr * 0.45f, rr * 0.25f), br);
- br->SetColor(D2D1::ColorF(1, 1, 1, 0.35f));
- dc->DrawEllipse(D2D1::Ellipse(c, rr - 0.5f, rr - 0.5f), br, 1);
- br->Release();
- }
-}
-
-// quanto do brilho aparece agora (1 pensando, apagando em 0,9 s depois da resposta)
-float ForcaBrilho(double now) {
- if (g_entrada) return 0;
- if (g_busy) return 0.85f + 0.15f * (float)std::sin(now / 420.0);
- float k = (float)((now - g_answerAt) / 900.0);
- return k >= 1 ? 0.f : (1 - k) * (1 - k);
-}
-bool Animando(double now) {
- double digitar = g_a.size() / std::max(110.0, g_a.size() / 2.2) * 1000.0; // o tempo da resposta "digitando"
- return g_closing || g_busy || !anim::PanelIn(now - g_openAt).done || now - g_answerAt < std::max(950.0, digitar + 50);
-}
-
-void Paint() {
- if ((!g_open && !g_closing) || !g_wnd) return;
- double now = anim::Now();
- float sc = Sc();
- bool dark = ui::Dark();
- float textW = W - PAD * 2 - ORB - 14;
- std::wstring a = g_busy ? std::wstring(Tr(L"Pensando")) + std::wstring((size_t)(g_pontos % 3 + 1), L'.') : g_a;
- float ah = AlturaTexto(a, g_tfA, textW); // a altura é a do texto inteiro: o painel não cresce aos pulos enquanto ele "digita"
- // a resposta aparece como se fosse digitada (issue #38): ~110 letras por segundo, no máximo 2,2 s (as longas vão mais rápido)
- if (!g_busy && !g_entrada && g_answerAt > 0) {
- double vel = std::max(110.0, g_a.size() / 2.2);
- size_t n = (size_t)std::max(0.0, (now - g_answerAt) / 1000.0 * vel);
- if (n < a.size()) { a = a.substr(0, n); if (n && IS_HIGH_SURROGATE(a.back())) a.pop_back(); }
- }
- float qh = AlturaTexto(g_q, g_tfQ, textW);
- g_contentH = PAD + qh + 8 + ah + PAD;
- if (g_entrada) { // só o campo: uma linha (ou mais, se o texto quebrar)
- qh = 0; ah = std::max(AlturaTexto(g_texto.empty() ? L"M" : g_texto, g_tfA, textW), 20.f);
- g_contentH = std::max(ORB + PAD * 2, PAD + ah + PAD + 4);
- }
- HMONITOR hm = MonitorFromWindow(g_wnd, MONITOR_DEFAULTTONEAREST);
- MONITORINFO mi{ sizeof(mi) }; GetMonitorInfoW(hm, &mi);
- float maxH = (mi.rcWork.bottom - mi.rcWork.top) / sc * 0.6f;
- float H = std::clamp(g_contentH, ORB + PAD * 2, maxH);
- g_viewH = H;
- g_scroll = std::clamp(g_scroll, 0.f, std::max(0.f, g_contentH - H));
- int wpx = (int)std::lround((W + 2 * M) * sc), hpx = (int)std::lround((H + 2 * M) * sc);
- RECT wr; GetWindowRect(g_wnd, &wr);
- if (wr.bottom - wr.top != hpx || wr.right - wr.left != wpx) {
- SetWindowPos(g_wnd, nullptr, 0, 0, wpx, hpx, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
- if (g_back) SetWindowPos(g_back, g_wnd, wr.left, wr.top, wpx, hpx, SWP_NOACTIVATE);
- }
- float mpx = M * sc;
- if (g_glass) backdrop::SetPieces(g_back, (float)wpx, (float)hpx, { { D2D1::RectF(mpx, mpx, wpx - mpx, hpx - mpx), R * sc } },
- dark ? D2D1::ColorF(0.13f, 0.13f, 0.14f, 0.55f) : D2D1::ColorF(0.96f, 0.96f, 0.97f, 0.50f), 24.f);
- ID2D1DeviceContext* dc = g_glass ? backdrop::ContentBegin(g_back, wpx, hpx, sc) : nullptr;
- g_inGlass = dc != nullptr;
- if (!dc) dc = ui::GpuBegin(g_s, wpx, hpx, sc);
- if (!dc) return;
- D2D1_MATRIX_3X2_F base; dc->GetTransform(&base);
- dc->SetTransform(D2D1::Matrix3x2F::Translation(M, M) * base); // o painel começa na folga
- ID2D1SolidColorBrush* br = nullptr;
- dc->CreateSolidColorBrush(D2D1::ColorF(1, 1, 1), &br);
- if (br) {
- D2D1_RECT_F box = D2D1::RectF(0, 0, W, H);
- if (!g_inGlass) Brilho(dc, D2D1::RectF(-1, -1, W + 1, H + 1), R + 1, now - g_openAt, ForcaBrilho(now));
- if (!g_glass) { br->SetColor(dark ? D2D1::ColorF(0.16f, 0.16f, 0.17f, 0.95f) : D2D1::ColorF(0.96f, 0.96f, 0.97f, 0.95f)); dc->FillRoundedRectangle(D2D1::RoundedRect(box, R, R), br); }
- if (liquid::On()) liquid::Rim(dc, box, R, dark);
- else { br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.14f) : D2D1::ColorF(0, 0, 0, 0.12f)); dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(0.5f, 0.5f, W - 0.5f, H - 0.5f), R, R), br, 1); }
- Orbe(dc, { PAD + ORB / 2, PAD + ORB / 2 }, ORB / 2, now - g_openAt);
- float x = PAD + ORB + 14;
- if (g_entrada) { // o campo: o texto digitado (ou o convite em cinza) e o cursor piscando
- float y0 = (H - ah) / 2;
- bool vazio = g_texto.empty();
- const std::wstring& t = vazio ? std::wstring(Tr(L"Pergunte à Siri…")) : g_texto;
- br->SetColor(vazio ? (dark ? D2D1::ColorF(1, 1, 1, 0.38f) : D2D1::ColorF(0, 0, 0, 0.35f)) : (dark ? D2D1::ColorF(1, 1, 1, 0.95f) : D2D1::ColorF(0, 0, 0, 0.88f)));
- dc->DrawTextW(t.c_str(), (UINT32)t.size(), g_tfA, D2D1::RectF(x, y0, x + textW, y0 + ah + 4), br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT);
- if (g_cursorOn) { // o cursor no fim do texto
- IDWriteTextLayout* lay = nullptr; float cx = x, cy = y0, ch = 18;
- if (!vazio && SUCCEEDED(ui::dw->CreateTextLayout(g_texto.c_str(), (UINT32)g_texto.size(), g_tfA, textW, 10000, &lay))) {
- DWRITE_HIT_TEST_METRICS hm{}; FLOAT px = 0, py = 0;
- lay->HitTestTextPosition((UINT32)g_texto.size() - 1, TRUE, &px, &py, &hm);
- cx = x + px; cy = y0 + py; ch = hm.height; lay->Release();
- }
- br->SetColor(D2D1::ColorF(0.40f, 0.52f, 1.f));
- dc->FillRectangle(D2D1::RectF(cx + 1, cy + 1, cx + 3, cy + ch - 1), br);
- }
- br->Release();
- dc->SetTransform(base);
- if (g_inGlass) {
- backdrop::ContentEnd(g_back);
- if (ID2D1DeviceContext* gd = ui::GpuBegin(g_s, wpx, hpx, sc)) ui::GpuEnd(g_s); // sem brilho enquanto digita
- } else ui::GpuEnd(g_s);
- return;
- }
- dc->PushAxisAlignedClip(D2D1::RectF(x - 2, 8, W - PAD + 2, H - 8), D2D1_ANTIALIAS_MODE_ALIASED);
- float y = PAD - g_scroll;
- br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.55f) : D2D1::ColorF(0, 0, 0, 0.5f));
- dc->DrawTextW(g_q.c_str(), (UINT32)g_q.size(), g_tfQ, D2D1::RectF(x, y, x + textW, y + qh + 4), br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT);
- y += qh + 8;
- // a resposta entra subindo um pouco e aparecendo (0,35 s)
- float k = g_busy ? 1.f : std::clamp((float)((now - g_answerAt) / 350.0), 0.f, 1.f);
- float e = 1 - (1 - k) * (1 - k) * (1 - k);
- D2D1_COLOR_F tc = g_erro ? D2D1::ColorF(1.f, 0.42f, 0.38f) : dark ? D2D1::ColorF(1, 1, 1, 0.95f) : D2D1::ColorF(0, 0, 0, 0.88f);
- tc.a *= g_busy ? 0.6f + 0.25f * (float)std::sin(now / 300.0) : e;
- br->SetColor(tc);
- float dy = (1 - e) * 8;
- dc->DrawTextW(a.c_str(), (UINT32)a.size(), g_tfA, D2D1::RectF(x, y + dy, x + textW, y + dy + ah + 4), br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT); // emoji colorido
- dc->PopAxisAlignedClip();
- if (g_contentH > H) { // barrinha de rolagem fina
- float bh = std::max(24.f, H * H / g_contentH), by = 6 + (H - 12 - bh) * (g_scroll / (g_contentH - H));
- br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.3f) : D2D1::ColorF(0, 0, 0, 0.25f));
- dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(W - 8, by, W - 4, by + bh), 2, 2), br);
- }
- br->Release();
- }
- dc->SetTransform(base);
- if (g_inGlass) {
- backdrop::ContentEnd(g_back);
- // o desenho dentro do vidro é recortado no formato do painel: o brilho, que passa para fora, vai na janela da frente
- // (transparente, do tamanho da folga)
- if (ID2D1DeviceContext* gd = ui::GpuBegin(g_s, wpx, hpx, sc)) {
- D2D1_MATRIX_3X2_F b2; gd->GetTransform(&b2);
- gd->SetTransform(D2D1::Matrix3x2F::Translation(M, M) * b2);
- Brilho(gd, D2D1::RectF(-1, -1, W + 1, H + 1), R + 1, now - g_openAt, ForcaBrilho(now));
- gd->SetTransform(b2);
- ui::GpuEnd(g_s);
- }
- } else ui::GpuEnd(g_s);
-}
-
-// a mola de abrir (crescendo do meio) e a de fechar: escala e opacidade pelo compositor
-void Movimento() {
- double now = anim::Now();
- anim::Panel mo = g_closing ? anim::PanelOut(now - g_closeAt) : anim::PanelIn(now - g_openAt);
- RECT wr; GetWindowRect(g_wnd, &wr);
- float cx = (wr.right - wr.left) / 2.f, cy = (wr.bottom - wr.top) / 2.f;
- ui::GpuMotion(g_s, mo.scale, cx, cy, mo.fade); // o brilho (ou tudo, sem vidro)
- if (g_back) backdrop::Fade(g_back, mo.fade, mo.scale, cx, cy);
-}
-
-void Esconde() {
- Log(L"siri: painel escondido");
- g_closing = false;
- ui::FrameClock(g_wnd, WM_SIRI_FRAME, false);
- ShowWindow(g_wnd, SW_HIDE);
- if (g_back) ShowWindow(g_back, SW_HIDE);
-}
-
-void Fecha() {
- if (!g_open) return;
- g_open = false; g_busy = false;
- g_num++; // a resposta que ainda vem é descartada
- KillTimer(g_wnd, T_PONTOS);
- if (anim::reduceMotion) { Esconde(); return; }
- g_closing = true; g_closeAt = anim::Now();
- ui::FrameClock(g_wnd, WM_SIRI_FRAME, true);
-}
-
-void Copia() {
- if (g_busy || g_a.empty() || !OpenClipboard(g_wnd)) return;
- EmptyClipboard();
- size_t n = (g_a.size() + 1) * sizeof(wchar_t);
- if (HGLOBAL g = GlobalAlloc(GMEM_MOVEABLE, n)) {
- if (void* d = GlobalLock(g)) { memcpy(d, g_a.c_str(), n); GlobalUnlock(g); if (!SetClipboardData(CF_UNICODETEXT, g)) GlobalFree(g); }
- else GlobalFree(g);
- }
- CloseClipboard();
-}
-
-LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {
- switch (m) {
- case WM_SIRI_FIM: {
- std::wstring* r = (std::wstring*)l;
- if ((int)w == g_num && g_open) {
- g_erro = r->size() > 1 && (*r)[0] == L'\x1';
- g_a = g_erro ? r->substr(1) : *r;
- g_busy = false; g_scroll = 0;
- g_answerAt = anim::Now();
- KillTimer(h, T_PONTOS);
- Paint(); // o brilho apaga e a resposta entra: os quadros continuam (WM_SIRI_FRAME)
- }
- delete r;
- return 0;
- }
- case WM_SIRI_FRAME: {
- ui::FrameAck(h, WM_SIRI_FRAME);
- double now = anim::Now();
- if (g_closing) {
- Movimento();
- if (anim::PanelOut(now - g_closeAt).done) Esconde();
- return 0;
- }
- Paint(); Movimento();
- if (!Animando(now)) ui::FrameClock(h, WM_SIRI_FRAME, false);
- return 0;
- }
- case WM_NCHITTEST: { // só o painel pega o clique; a folga do brilho deixa passar
- POINT pt{ GET_X_LPARAM(l), GET_Y_LPARAM(l) };
- RECT wr; GetWindowRect(h, &wr);
- float sc = Sc(); int mpx = (int)std::lround(M * sc);
- return pt.x >= wr.left + mpx && pt.x < wr.right - mpx && pt.y >= wr.top + mpx && pt.y < wr.bottom - mpx ? HTCLIENT : HTTRANSPARENT;
- }
- case WM_TIMER: if (w == 9) { KillTimer(h, 9); Fecha(); return 0; }
- if (w == T_CURSOR) { g_cursorOn = !g_cursorOn; if (g_entrada) Paint(); else KillTimer(h, T_CURSOR); return 0; }
- if (w == T_PONTOS) { g_pontos++; if (!Animando(anim::Now())) Paint(); } return 0;
- case WM_MOUSEWHEEL: g_scroll -= GET_WHEEL_DELTA_WPARAM(w) / 120.f * 48; Paint(); return 0;
- case WM_CHAR:
- { static int n; if (n++ < 3) Log(L"siri: tecla %u (aberta %d, pensando %d, campo %d)", (unsigned)w, g_open, g_busy, g_entrada); }
- if (!g_open || g_busy) return 0;
- if (w == 13) { // Enter: pergunta
- if (g_entrada && !g_texto.empty()) { std::wstring q = g_texto; siri::Perguntar(q, g_teste); }
- return 0;
- }
- if (w == 8) { if (g_entrada && !g_texto.empty()) { g_texto.pop_back(); g_cursorOn = true; Paint(); } return 0; }
- if (w >= 32 && w != 127 && !(GetKeyState(VK_CONTROL) < 0 && GetKeyState(VK_MENU) >= 0)) {
- if (!g_entrada) { g_entrada = true; g_texto.clear(); g_q.clear(); g_a.clear(); g_scroll = 0; } // digitou depois da resposta: outra pergunta
- if (g_texto.size() < 2000) g_texto += (wchar_t)w;
- g_cursorOn = true; SetTimer(h, T_CURSOR, 530, nullptr);
- Paint();
- }
- return 0;
- case WM_KEYDOWN:
- if (w == 'V' && GetKeyState(VK_CONTROL) < 0 && !g_busy && OpenClipboard(h)) { // colar no campo
- if (HANDLE cb = GetClipboardData(CF_UNICODETEXT)) {
- if (auto* p = (const wchar_t*)GlobalLock(cb)) {
- std::wstring t = p; GlobalUnlock(cb);
- for (auto& c : t) if (c == L'\r' || c == L'\n' || c == L'\t') c = L' ';
- if (!g_entrada) { g_entrada = true; g_texto.clear(); g_q.clear(); g_a.clear(); }
- g_texto += t.substr(0, 2000 - std::min<size_t>(2000, g_texto.size()));
- }
- }
- CloseClipboard();
- Paint();
- return 0;
- }
- if (w == VK_ESCAPE) Fecha();
- else if (w == 'C' && GetKeyState(VK_CONTROL) < 0) Copia();
- else if (w == VK_DOWN) { g_scroll += 40; Paint(); }
- else if (w == VK_UP) { g_scroll -= 40; Paint(); }
- return 0;
- case WM_ACTIVATE:
- if (LOWORD(w) == WA_INACTIVE && g_open && !g_teste) {
- wchar_t c[64] = {}; if (l) GetClassNameW((HWND)l, c, 64);
- Log(L"siri: perdeu a frente para %ls; fecha", c[0] ? c : L"(nenhuma)");
- Fecha();
- }
- return 0;
- case WM_CLOSE: Fecha(); return 0;
- }
- return DefWindowProcW(h, m, w, l);
-}
-LRESULT CALLBACK BackProc(HWND h, UINT m, WPARAM w, LPARAM l) {
- if (m == WM_MOUSEACTIVATE) return MA_NOACTIVATE;
- if (m == WM_NCHITTEST) return HTTRANSPARENT;
- return DefWindowProcW(h, m, w, l);
-}
-
-bool Ready() {
- if (g_wnd && IsWindow(g_wnd)) return true;
- HINSTANCE hi = shell::inst;
- WNDCLASSW wc{}; wc.lpfnWndProc = Proc; wc.hInstance = hi; wc.lpszClassName = L"ShellSiri"; wc.hCursor = LoadCursorW(nullptr, IDC_ARROW);
- RegisterClassW(&wc);
- WNDCLASSW bc{}; bc.lpfnWndProc = BackProc; bc.hInstance = hi; bc.lpszClassName = L"ShellSiriFundo";
- RegisterClassW(&bc);
- g_wnd = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP, wc.lpszClassName, L"Siri", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);
- g_back = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP, bc.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);
- if (!g_wnd || !g_back) { Log(L"siri: janela não criada (%lu)", GetLastError()); return false; }
- g_glass = backdrop::Attach(g_back);
- if (!g_glass) { DestroyWindow(g_back); g_back = nullptr; }
- apps::ours.push_back(g_wnd); if (g_back) apps::ours.push_back(g_back);
- g_s.hwnd = g_wnd;
- g_tfQ = ui::Format(12.5f, DWRITE_FONT_WEIGHT_NORMAL);
- g_tfA = ui::Format(15, DWRITE_FONT_WEIGHT_NORMAL);
- for (auto* f : { g_tfQ, g_tfA }) if (f) f->SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
- return true;
-}
-
-} // namespace
-
-bool siri::Pronta() {
- const auto& provs = siri::Provedores();
- int p = _wtoi(shell::Setting(L"siri_provedor", L"0").c_str());
- if (p <= 0 || p >= (int)provs.size()) return false;
- return !provs[p].precisaChave || GetFileAttributesW(siri::ArquivoChave(p).c_str()) != INVALID_FILE_ATTRIBUTES;
-}
-
-// mostra o painel (a mola de abrir); já aberto, fica onde está e só muda o conteúdo
-static void MostraPainel(bool teste) {
- if (g_open && IsWindowVisible(g_wnd)) {
- Paint();
- ui::FrameClock(g_wnd, WM_SIRI_FRAME, true);
- return;
- }
- // no alto do monitor do ponteiro, centralizado (onde a Siri do Mac aparece... e onde o Spotlight estava)
- POINT pt; GetCursorPos(&pt);
- HMONITOR hm = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
- MONITORINFO mi{ sizeof(mi) }; GetMonitorInfoW(hm, &mi);
- float sc = ui::Scale(g_wnd);
- int wpx = (int)std::lround((W + 2 * M) * sc), hpx = (int)std::lround((ORB + PAD * 2 + 2 * M) * sc);
- int x = (mi.rcWork.left + mi.rcWork.right - wpx) / 2, y = mi.rcWork.top + (mi.rcWork.bottom - mi.rcWork.top) / 6 - (int)std::lround(M * sc);
- SetWindowPos(g_wnd, HWND_TOPMOST, x, y, wpx, hpx, SWP_NOACTIVATE);
- if (g_back) SetWindowPos(g_back, g_wnd, x, y, wpx, hpx, SWP_NOACTIVATE);
- g_open = true; g_closing = false; g_openAt = anim::Now(); g_answerAt = 0;
- if (g_glass) backdrop::Fade(g_back, 0, 0.94f, wpx / 2.f, hpx / 2.f); // nasce invisível e um pouco menor: a mola leva até o tamanho
- ui::GpuMotion(g_s, 0.94f, wpx / 2.f, hpx / 2.f, 0);
- Paint();
- if (g_back) ShowWindow(g_back, SW_SHOWNOACTIVATE);
- ShowWindow(g_wnd, teste ? SW_SHOWNOACTIVATE : SW_SHOW);
- if (teste) SetTimer(g_wnd, 9, 8000, nullptr);
- else { shell::LiberaFrente(); SetForegroundWindow(g_wnd); SetFocus(g_wnd); }
- ui::FrameClock(g_wnd, WM_SIRI_FRAME, true); // a mola de abrir, o brilho e a bolinha enquanto pensa
-}
-
-void siri::Abrir(bool teste) { // o ícone da barra: o painel com o campo para digitar
- if (!Ready()) return;
- if (g_open && g_entrada) { Fecha(); return; } // clicar de novo fecha
- g_teste = teste;
- g_entrada = true; g_texto.clear(); g_q.clear(); g_a.clear(); g_busy = false; g_erro = false; g_scroll = 0;
- g_num++;
- g_cursorOn = true;
- MostraPainel(teste);
- SetTimer(g_wnd, T_CURSOR, 530, nullptr);
-}
-
-bool siri::Aberta() { return g_open; }
-
-void siri::Perguntar(const std::wstring& q, bool teste) {
- if (q.empty() || !Ready()) return;
- g_teste = teste;
- g_entrada = false; g_texto.clear();
- KillTimer(g_wnd, T_CURSOR);
- g_q = q; g_a.clear(); g_busy = true; g_erro = false; g_scroll = 0; g_pontos = 0;
- g_answerAt = 0;
- int num = ++g_num;
- MostraPainel(teste);
- SetTimer(g_wnd, T_PONTOS, 420, nullptr);
- HWND to = g_wnd;
- std::thread([q, num, to] {
- CoInitializeEx(nullptr, COINIT_MULTITHREADED);
- bool erro = false;
- std::wstring r = Pergunta(q, erro, num);
- auto* res = new std::wstring((erro ? L"\x1" : L"") + r);
- if (!PostMessageW(to, WM_SIRI_FIM, (WPARAM)num, (LPARAM)res)) delete res; // janela já fechada: não vaza
- CoUninitialize();
- }).detach();
-}
+// Siri (issue #39, 23/11/2026): pergunta pelo Spotlight ("Perguntar à Siri") e a resposta num painel de vidro no alto
+// da tela, como a Siri do macOS. Não há servidor do WacOS: a pergunta vai direto do PC para o serviço que o usuário
+// escolheu nos Ajustes (Gemini, Groq, OpenAI ou o Ollama local), com a chave dele (src/comum/siri.h).
+// A chamada roda numa thread (WinHTTP, até 60 s); cada pergunta tem um número, e a resposta de uma pergunta antiga
+// (painel fechado ou outra pergunta feita) é descartada. Esc ou clicar fora fecha; Ctrl+C copia a resposta.
+#include "shell.h"
+#include "../comum/siri.h"
+#include "../comum/simbolos.h"
+#include "../comum/idioma.h"
+#include <dwmapi.h>
+#include <d2d1effects_2.h>
+#include <windowsx.h>
+#include <thread>
+#include <atomic>
+#include <algorithm>
+#include <cmath>
+
+namespace {
+
+const UINT WM_SIRI_FIM = WM_APP + 70, WM_SIRI_FRAME = WM_APP + 71, WM_SIRI_VOZ = WM_APP + 72;
+D2D1_RECT_F g_mic{}; // o botão do microfone no campo (coordenadas do painel, DIP)
+const UINT_PTR T_PONTOS = 1;
+float W = 560; // a largura do campo do Spotlight (MostraPainel): os dois alinhados
+const float PAD = 20, ORB = 30, R = 22;
+const float M = 28; // folga em volta do painel para o brilho (os cliques nela atravessam: WM_NCHITTEST)
+
+HWND g_wnd, g_back;
+ui::GpuSurface g_s;
+bool g_glass, g_inGlass, g_open;
+std::wstring g_q, g_a;
+bool g_busy, g_erro;
+std::atomic<int> g_num{ 0 };
+int g_pontos;
+float g_scroll, g_contentH, g_viewH;
+double g_openAt, g_answerAt, g_closeAt;
+bool g_closing;
+bool g_teste;
+// campo de digitar (aberta pelo ícone da barra, ou digitando depois de uma resposta): g_texto é o que foi digitado
+bool g_entrada;
+std::wstring g_texto;
+const UINT_PTR T_CURSOR = 2;
+bool g_cursorOn = true; // 'SIRT' (teste com um jogo na frente): não pega a frente, não fecha ao perder a frente, some em 8 s
+ID2D1StrokeStyle* g_round;
+struct { int n, cont, longos; double soma, max, gapMax; } g_med; // medição dos quadros
+int g_wpx, g_hpx; float g_H; // o tamanho do último Paint (a camada da frente redesenha sem refazer o resto)
+int g_pecasW = -1, g_pecasH = -1; bool g_pecasDark; double g_pecasAt; // o vidro já posto (não refazer a cada quadro)
+IDWriteTextFormat *g_tfQ, *g_tfA;
+
+// ---------------------------------------------------------------- a pergunta (thread)
+std::wstring Limpa(std::wstring t) { // os modelos insistem em Markdown: tira o que fica feio em texto puro
+ for (const wchar_t* m : { L"**", L"__", L"`" }) for (size_t i; (i = t.find(m)) != std::wstring::npos;) t.erase(i, wcslen(m));
+ std::wstring o; bool ini = true;
+ for (size_t i = 0; i < t.size(); i++) {
+ if (ini) { // "# Título" e "* item" no começo da linha
+ while (i < t.size() && t[i] == L'#') i++;
+ if (i + 1 < t.size() && (t[i] == L'*' || t[i] == L'-') && t[i + 1] == L' ') { o += L"• "; i += 2; }
+ while (i < t.size() && t[i] == L' ' && !o.empty() && o.back() == L'\n') i++;
+ }
+ if (i >= t.size()) break;
+ o += t[i];
+ ini = t[i] == L'\n';
+ }
+ while (!o.empty() && iswspace(o.back())) o.pop_back();
+ size_t s = 0; while (s < o.size() && iswspace(o[s])) s++;
+ return o.substr(s);
+}
+
+// o modelo não existe mais (ou nunca existiu) para esta conta: os serviços dizem isso de jeitos diferentes
+bool ModeloSumiu(DWORD status, const std::wstring& msg) {
+ if (status != 400 && status != 404) return false;
+ std::wstring l = msg; for (auto& c : l) c = (wchar_t)towlower(c);
+ for (const wchar_t* w : { L"no longer available", L"not found", L"does not exist", L"not supported", L"decommissioned", L"deprecated",
+ L"invalid model", L"unknown model", L"model_not_found", L"is not a valid model" })
+ if (l.find(w) != std::wstring::npos) return true;
+ return false;
+}
+
+// outro modelo da lista para esta pergunta: estável (sem preview/omni/exp/latest/lite), da mesma família (Flash no Gemini)
+std::wstring Reserva(const std::vector<std::wstring>& lista, const std::wstring& atual, bool gemini) {
+ std::wstring alt;
+ for (auto& m : lista) {
+ if (m == atual || m.find(L"lite") != std::wstring::npos || m.find(L"preview") != std::wstring::npos ||
+ m.find(L"omni") != std::wstring::npos || m.find(L"exp") != std::wstring::npos || m.find(L"latest") != std::wstring::npos) continue;
+ if (!gemini || m.find(L"flash") != std::wstring::npos) return m;
+ if (alt.empty()) alt = m;
+ }
+ return alt;
+}
+
+std::wstring PerguntaCli(const siri::Provedor& pv, const std::wstring& q, bool& erro, int num) {
+ const std::wstring instr = L"Answer briefly and clearly, in the same language as the question, in plain text without Markdown. "
+ L"Do not run commands or edit files. Question: ";
+ DWORD codigo = 0; bool tempo = false;
+ wchar_t tmp[MAX_PATH]; GetTempPathW(MAX_PATH, tmp);
+ std::wstring ultima = std::wstring(tmp) + L"WacOS-Siri\\ultima.txt";
+ DeleteFileW(ultima.c_str());
+ // outra pergunta feita ou o painel fechado (g_num mudou): o CLI é encerrado na hora, em vez de seguir até 3 min
+ std::wstring r = siri::RodaCli(pv.caminho, instr + q, codigo, tempo, [](void* c) { return *(int*)c != g_num.load(); }, &num);
+ if (codigo == ERROR_CANCELLED) return L""; // descartada
+ Log(L"siri: %ls -> código %lu, %zu caracteres%ls", pv.nome, codigo, r.size(), tempo ? L" (passou do tempo)" : L"");
+ if (tempo) return Tr(L"O app demorou demais para responder.");
+ if (codigo == 9009 || codigo == ERROR_FILE_NOT_FOUND) // o cmd não achou o comando
+ return std::wstring(Tr(L"Não achei o app neste PC. Instale e entre na sua conta nele:")) + L" " + pv.site;
+ // o Codex grava a última mensagem num arquivo (a saída tem o resto da conversa)
+ HANDLE h = CreateFileW(ultima.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
+ if (h != INVALID_HANDLE_VALUE) {
+ DWORD sz = GetFileSize(h, nullptr), n = 0;
+ std::string b(sz < (1u << 20) ? sz : 0, 0);
+ if (!b.empty() && ReadFile(h, b.data(), sz, &n, nullptr)) r = siri::Wide(b);
+ CloseHandle(h);
+ DeleteFileW(ultima.c_str());
+ }
+ if (codigo != 0 || r.empty()) {
+ std::wstring t = Limpa(r);
+ if (t.size() > 400) t = t.substr(t.size() - 400);
+ return std::wstring(Tr(L"O app não respondeu. Ele está instalado e com a conta entrada?")) + (t.empty() ? L"" : L"\n\n" + t);
+ }
+ erro = false;
+ return Limpa(r);
+}
+
+std::wstring Pergunta(const std::wstring& q, bool& erro, int num) {
+ erro = true;
+ const auto& provs = siri::Provedores();
+ int p = std::clamp(_wtoi(shell::Setting(L"siri_provedor", L"0").c_str()), 0, (int)provs.size() - 1);
+ if (p == 0) return Tr(L"Escolha um serviço para a Siri em Ajustes do Sistema > Apple Intelligence e Siri.");
+ const auto& pv = provs[p];
+ if (pv.fmt == siri::F_CLI) return PerguntaCli(pv, q, erro, num);
+ std::wstring modelo = shell::Setting(L"siri_modelo", pv.modelos.empty() ? L"" : pv.modelos[0]);
+ std::wstring chave = pv.precisaChave ? siri::LeChave(p) : L"";
+ if (pv.precisaChave && chave.empty()) return Tr(L"Falta a chave da API. Cole a chave em Ajustes do Sistema > Apple Intelligence e Siri.");
+ if (modelo.empty()) { // LM Studio e afins: o modelo carregado
+ std::wstring e; auto l = siri::ListaModelos(p, e);
+ if (!l.empty()) modelo = l[0];
+ }
+ const std::wstring sistema = L"You are Siri inside WacOS, a macOS-style desktop for Windows. Answer briefly and clearly, "
+ L"in the same language as the question. Use plain text, without Markdown.";
+ std::wstring cab = siri::Cabecalhos(pv, chave);
+ SecureZeroMemory(chave.data(), chave.size() * sizeof(wchar_t));
+ siri::Resposta r;
+ bool web = shell::Setting(L"siri_web", L"1") != L"0";
+ for (int tentativa = 0; tentativa < 3; tentativa++) {
+ std::string body;
+ std::wstring caminho = pv.caminho;
+ if (pv.fmt == siri::F_GEMINI) {
+ size_t m = caminho.find(L"{m}"); if (m != std::wstring::npos) caminho.replace(m, 3, modelo);
+ body = "{\"systemInstruction\":{\"parts\":[{\"text\":" + siri::JStr(sistema) + "}]},\"contents\":[{\"role\":\"user\",\"parts\":[{\"text\":" + siri::JStr(q) + "}]}]" +
+ // siri_web (issue #42): o Gemini pesquisa no Google antes de responder (notícias, tempo, resultados de hoje)
+ (web ? ",\"tools\":[{\"google_search\":{}}]}" : "}");
+ } else if (pv.fmt == siri::F_ANTHROPIC) {
+ body = "{\"model\":" + siri::JStr(modelo) + ",\"max_tokens\":1024,\"system\":" + siri::JStr(sistema) +
+ ",\"messages\":[{\"role\":\"user\",\"content\":" + siri::JStr(q) + "}]}";
+ } else { // OpenAI e compatíveis (Groq, OpenRouter, Mistral, DeepSeek, xAI, LM Studio) e Ollama
+ body = "{\"model\":" + siri::JStr(modelo) + ",\"messages\":[{\"role\":\"system\",\"content\":" + siri::JStr(sistema) + "},{\"role\":\"user\",\"content\":" + siri::JStr(q) + "}]" +
+ (pv.fmt == siri::F_OLLAMA ? ",\"stream\":false}" : "}");
+ }
+ r = siri::Http(pv, L"POST", caminho, cab, body);
+ Log(L"siri: %ls %ls -> %lu (%zu bytes, erro %lu)", pv.nome, modelo.c_str(), r.status, r.corpo.size(), r.falha);
+ if (r.falha || tentativa >= 2) break;
+ if (web && r.status == 400 && pv.fmt == siri::F_GEMINI) { // o modelo não aceita a pesquisa: de novo, sem ela
+ std::wstring m = siri::ErroDoServico(r.corpo); for (auto& c : m) c = (wchar_t)towlower(c);
+ if (m.find(L"search") != std::wstring::npos || m.find(L"tool") != std::wstring::npos) { web = false; Log(L"siri: %ls sem a pesquisa na web", modelo.c_str()); continue; }
+ }
+ if (r.status == 503 || r.status == 500 || r.status == 529) { // sobrecarregado: de novo; depois, outro modelo da lista (só nesta pergunta)
+ if (!tentativa) { Sleep(1500); continue; }
+ std::wstring e; auto lista = siri::ListaModelos(p, e);
+ std::wstring alt;
+ alt = Reserva(lista, modelo, pv.fmt == siri::F_GEMINI);
+ if (!alt.empty()) { Log(L"siri: %ls sobrecarregado; tentando %ls", modelo.c_str(), alt.c_str()); modelo = alt; continue; }
+ break;
+ }
+ // cota zerada deste modelo (o plano grátis não inclui todos): tenta o preferido da lista, que costuma estar no plano
+ std::wstring msgErro = siri::ErroDoServico(r.corpo), lm = msgErro;
+ for (auto& c : lm) c = (wchar_t)towlower(c);
+ bool semCota = r.status == 429 && lm.find(L"quota") != std::wstring::npos;
+ if (semCota) {
+ std::wstring e; auto lista = siri::ListaModelos(p, e);
+ std::wstring outro = !lista.empty() && lista[0] != modelo ? lista[0] : Reserva(lista, modelo, pv.fmt == siri::F_GEMINI);
+ if (!outro.empty()) {
+ Log(L"siri: sem cota em %ls; tentando %ls", modelo.c_str(), outro.c_str());
+ modelo = outro;
+ continue; // só nesta pergunta: a cota volta amanhã, e o escolhido nos Ajustes fica
+ }
+ }
+ if (!ModeloSumiu(r.status, msgErro)) { if (r.status >= 400) Log(L"siri: erro do serviço: %ls", siri::ErroDoServico(r.corpo).substr(0, 200).c_str()); break; }
+ // o modelo saiu do ar: pega a lista atual do serviço, guarda o preferido dela e pergunta de novo
+ std::wstring e; auto lista = siri::ListaModelos(p, e);
+ if (lista.empty() || lista[0] == modelo) { Log(L"siri: o modelo saiu do ar, mas a lista não trouxe outro (%ls)", e.empty() ? L"vazia" : e.c_str()); break; }
+ Log(L"siri: %ls não existe mais; agora %ls", modelo.c_str(), lista[0].c_str());
+ modelo = lista[0];
+ std::wstring junta; for (auto& m : lista) junta += (junta.empty() ? L"" : L"|") + m;
+ // pela thread da interface: SetSetting grava o ajustes.txt (num .tmp de nome fixo), e esta thread gravando ao
+ // mesmo tempo que a interface podia misturar as duas gravações
+ shell::NaInterface([modelo, junta, p] {
+ shell::SetSetting(L"siri_modelo", modelo);
+ shell::SetSetting((L"siri_modelos_" + std::to_wstring(p)).c_str(), junta);
+ });
+ }
+ SecureZeroMemory(cab.data(), cab.size() * sizeof(wchar_t)); // a chave ia no cabeçalho
+ if (r.falha) {
+ if (pv.porta != 443) return std::wstring(Tr(L"Não deu para falar com o app neste PC. Ele está aberto?")) + L" (" + pv.nome + L")";
+ return Tr(L"Não deu para falar com o serviço. Confira a internet.");
+ }
+ std::wstring t;
+ if (r.status >= 200 && r.status < 300) {
+ bool ok = pv.fmt == siri::F_GEMINI ? siri::JLe(r.corpo, "text", r.corpo.find("\"candidates\""), t)
+ : pv.fmt == siri::F_ANTHROPIC ? siri::JLe(r.corpo, "text", r.corpo.find("\"content\""), t)
+ : siri::JLe(r.corpo, "content", r.corpo.find("\"message\""), t);
+ if (ok && !t.empty()) { erro = false; return Limpa(t); }
+ return Tr(L"O serviço respondeu sem texto.");
+ }
+ t = siri::ErroDoServico(r.corpo);
+ if (r.status == 429) {
+ std::wstring l = t; for (auto& c : l) c = (wchar_t)towlower(c);
+ if (l.find(L"quota") != std::wstring::npos || l.find(L"rate") != std::wstring::npos)
+ return std::wstring(Tr(L"Acabou a cota deste modelo no seu plano (o grátis tem limite por minuto e por dia). Espere um pouco ou escolha outro modelo em Ajustes do Sistema > Apple Intelligence e Siri.")) + L" (" + modelo + L")";
+ }
+ // as mensagens dos serviços podem ter várias linhas e links: só a primeira frase
+ if (size_t nlPos = t.find(L'\n'); nlPos != std::wstring::npos) t = t.substr(0, nlPos);
+ if (t.size() > 240) t = t.substr(0, 237) + L"...";
+ if (!t.empty()) return (r.status == 401 || r.status == 403 ? std::wstring(Tr(L"Chave recusada pelo serviço.")) + L" " : std::wstring()) + t;
+ return std::wstring(Tr(L"O serviço recusou a pergunta")) + L" (" + std::to_wstring(r.status) + L").";
+}
+
+// ---------------------------------------------------------------- painel
+float Sc() { return g_wnd ? ui::Scale(g_wnd) : 1.f; }
+
+float AlturaTexto(const std::wstring& t, IDWriteTextFormat* f, float w) {
+ IDWriteTextLayout* l = nullptr; float h = 0;
+ if (f && SUCCEEDED(ui::dw->CreateTextLayout(t.c_str(), (UINT32)t.size(), f, w, 10000, &l))) { DWRITE_TEXT_METRICS m{}; l->GetMetrics(&m); h = m.height; l->Release(); }
+ return h;
+}
+
+// ---- o brilho da Siri: uma luz colorida que corre pela borda do painel e se espalha para fora, como a do Apple
+// Intelligence. A cor de cada ponto da borda depende da posição nela e do tempo (as cores andam em volta); por baixo, três
+// traços largos e fracos fazem o brilho; por cima, o fio forte. Enquanto pensa: inteiro e "respirando"; quando a resposta
+// chega, apaga em 0,9 s.
+D2D1_COLOR_F CorDaVolta(float u) { // u em [0,1): rosa, roxo, azul, ciano, laranja e de volta ao rosa
+ static const D2D1_COLOR_F c[] = { { 1.f, 0.33f, 0.62f, 1 }, { 0.68f, 0.36f, 1.f, 1 }, { 0.26f, 0.52f, 1.f, 1 },
+ { 0.30f, 0.86f, 1.f, 1 }, { 1.f, 0.64f, 0.30f, 1 } };
+ const int n = 5;
+ u = u - std::floor(u);
+ float f = u * n; int a = (int)f % n, b = (a + 1) % n; float k = f - std::floor(f);
+ k = k * k * (3 - 2 * k); // suave entre as cores
+ return { c[a].r + (c[b].r - c[a].r) * k, c[a].g + (c[b].g - c[a].g) * k, c[a].b + (c[b].b - c[a].b) * k, 1 };
+}
+// ponto da borda do retângulo arredondado em u (0..1, sentido horário a partir do meio de cima)
+D2D1_POINT_2F PontoDaBorda(const D2D1_RECT_F& r, float rad, float u) {
+ float w = r.right - r.left, h = r.bottom - r.top, arco = 1.5707963f * rad;
+ float retoX = w - 2 * rad, retoY = h - 2 * rad, total = 2 * retoX + 2 * retoY + 4 * arco;
+ float d = (u - std::floor(u)) * total;
+ auto canto = [&](float cx, float cy, float a0, float t) { float a = a0 + t / rad; return D2D1_POINT_2F{ cx + std::cos(a) * rad, cy + std::sin(a) * rad }; };
+ float x0 = r.left + w / 2;
+ // do meio de cima para a direita
+ float seg = retoX / 2; if (d < seg) return { x0 + d, r.top }; d -= seg;
+ if (d < arco) return canto(r.right - rad, r.top + rad, -1.5707963f, d); d -= arco;
+ if (d < retoY) return { r.right, r.top + rad + d }; d -= retoY;
+ if (d < arco) return canto(r.right - rad, r.bottom - rad, 0, d); d -= arco;
+ if (d < retoX) return { r.right - rad - d, r.bottom }; d -= retoX;
+ if (d < arco) return canto(r.left + rad, r.bottom - rad, 1.5707963f, d); d -= arco;
+ if (d < retoY) return { r.left, r.bottom - rad - d }; d -= retoY;
+ if (d < arco) return canto(r.left + rad, r.top + rad, 3.1415926f, d); d -= arco;
+ return { r.left + rad + std::min(d, retoX / 2), r.top };
+}
+// O brilho da borda (como o do Apple Intelligence): um anel colorido que gira, com uma onda de luz correndo, gravado numa
+// lista de comandos e desfocado na GPU (dois desfoques: um largo e suave, outro curto e forte), e o fio nítido por cima.
+// Antes eram 4 camadas de 240 traços sobrepostos: pesado e com "degraus" na luz.
+void Brilho(ID2D1DeviceContext* dc, const D2D1_RECT_F& box, float rad, double tMs, float forca) {
+ if (forca <= 0.01f) return;
+ ID2D1SolidColorBrush* br = nullptr;
+ dc->CreateSolidColorBrush(D2D1::ColorF(1, 1, 1), &br);
+ if (!br) return;
+ const int N = 144;
+ float gira = (float)(tMs / 2600.0); // as cores dão uma volta a cada 2,6 s
+ ID2D1Factory* fab = nullptr; dc->GetFactory(&fab);
+ static ID2D1Factory* fabDoTraco = nullptr;
+ if (fab && fab != fabDoTraco) {
+ if (g_round) { g_round->Release(); g_round = nullptr; }
+ D2D1_STROKE_STYLE_PROPERTIES sp = D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_ROUND);
+ fab->CreateStrokeStyle(sp, nullptr, 0, &g_round);
+ fabDoTraco = fab;
+ }
+ if (fab) fab->Release();
+ D2D1_POINT_2F pts[N + 1];
+ D2D1_COLOR_F cores[N]; float ondas[N];
+ for (int k = 0; k <= N; k++) pts[k] = PontoDaBorda(box, rad, (float)k / N);
+ for (int k = 0; k < N; k++) {
+ float u = (k + 0.5f) / N;
+ cores[k] = CorDaVolta(u * 2 + gira); // duas voltas de cor pela borda inteira
+ ondas[k] = 0.55f + 0.45f * std::cos(6.2831853f * (u - gira * 0.7f)); // o trecho mais claro que corre
+ }
+ // a luz: o anel grosso numa lista de comandos, desfocado
+ ID2D1CommandList* cl = nullptr;
+ ID2D1Image* alvo = nullptr;
+ if (SUCCEEDED(dc->CreateCommandList(&cl))) {
+ dc->GetTarget(&alvo);
+ dc->SetTarget(cl);
+ for (int k = 0; k < N; k++) {
+ D2D1_COLOR_F c = cores[k]; c.a = 1;
+ br->SetColor(c);
+ dc->DrawLine(pts[k], pts[k + 1], br, 7.f + 5.f * ondas[k], g_round); // opaco: as pontas redondas se sobrepõem sem marcas
+ }
+ dc->SetTarget(alvo);
+ cl->Close();
+ D2D1_MATRIX_3X2_F t; dc->GetTransform(&t);
+ dc->SetTransform(D2D1::Matrix3x2F::Identity()); // a lista já está no lugar (gravada com a transformação)
+ struct { float desvio, alfa; } passes[] = { { 11.f * (t._11 > 0 ? t._11 : 1), 0.55f }, { 3.5f * (t._11 > 0 ? t._11 : 1), 0.45f } };
+ for (auto& ps : passes) {
+ ID2D1Effect *blur = nullptr, *opa = nullptr;
+ if (SUCCEEDED(dc->CreateEffect(CLSID_D2D1GaussianBlur, &blur)) && SUCCEEDED(dc->CreateEffect(CLSID_D2D1Opacity, &opa))) {
+ blur->SetInput(0, cl);
+ blur->SetValue(D2D1_GAUSSIANBLUR_PROP_STANDARD_DEVIATION, ps.desvio);
+ blur->SetValue(D2D1_GAUSSIANBLUR_PROP_OPTIMIZATION, D2D1_GAUSSIANBLUR_OPTIMIZATION_SPEED);
+ opa->SetInputEffect(0, blur);
+ opa->SetValue(D2D1_OPACITY_PROP_OPACITY, ps.alfa * forca);
+ dc->DrawImage(opa, D2D1_INTERPOLATION_MODE_LINEAR, D2D1_COMPOSITE_MODE_SOURCE_OVER);
+ }
+ if (opa) opa->Release();
+ if (blur) blur->Release();
+ }
+ dc->SetTransform(t);
+ if (alvo) alvo->Release();
+ cl->Release();
+ }
+ // o fio nítido na borda
+ for (int k = 0; k < N; k++) {
+ D2D1_COLOR_F c = cores[k];
+ c.a = 0.95f * forca * (0.75f + 0.25f * ondas[k]);
+ br->SetColor(c);
+ dc->DrawLine(pts[k], pts[k + 1], br, 2.2f, nullptr);
+ }
+ br->Release();
+}
+
+// O ícone do Apple Intelligence (o símbolo apple.intelligence) com o degradê dele: laranja, rosa, roxo e azul, que gira
+// devagar e pulsa enquanto pensa. Sem o símbolo instalado, a bolinha de antes.
+void OrbeAntiga(ID2D1DeviceContext* dc, D2D1_POINT_2F c, float r, double t);
+void Orbe(ID2D1DeviceContext* dc, D2D1_POINT_2F c, float r, double t) {
+ D2D1_GRADIENT_STOP gs[5] = { { 0, D2D1::ColorF(1.f, 0.62f, 0.10f) }, { 0.3f, D2D1::ColorF(1.f, 0.24f, 0.42f) },
+ { 0.55f, D2D1::ColorF(0.74f, 0.33f, 0.95f) }, { 0.8f, D2D1::ColorF(0.40f, 0.45f, 1.f) }, { 1, D2D1::ColorF(0.15f, 0.55f, 1.f) } };
+ ID2D1GradientStopCollection* sc = nullptr;
+ if (FAILED(dc->CreateGradientStopCollection(gs, 5, &sc))) return;
+ float a = (float)(t / (g_busy ? 900.0 : 4000.0)) + 2.3f;
+ float pulso = g_busy ? 1.f + 0.06f * (float)std::sin(t / 260.0) : 1.f;
+ float rr = r * pulso;
+ D2D1_POINT_2F p0{ c.x + std::cos(a) * rr, c.y + std::sin(a) * rr }, p1{ c.x - std::cos(a) * rr, c.y - std::sin(a) * rr };
+ ID2D1LinearGradientBrush* lg = nullptr;
+ bool ok = false;
+ if (SUCCEEDED(dc->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties(p0, p1), sc, &lg))) {
+ ok = simbolo::Draw(dc, L"apple.intelligence", D2D1::RectF(c.x - rr, c.y - rr, c.x + rr, c.y + rr), lg);
+ lg->Release();
+ }
+ sc->Release();
+ if (!ok) OrbeAntiga(dc, c, r, t);
+}
+void OrbeAntiga(ID2D1DeviceContext* dc, D2D1_POINT_2F c, float r, double t) {
+ // a bolinha da Siri: as cores giram enquanto pensa (e devagar depois), com um brilho que pulsa
+ D2D1_GRADIENT_STOP gs[4] = { { 0, D2D1::ColorF(0.98f, 0.36f, 0.62f) }, { 0.35f, D2D1::ColorF(0.62f, 0.38f, 1.f) },
+ { 0.7f, D2D1::ColorF(0.25f, 0.62f, 1.f) }, { 1, D2D1::ColorF(1.f, 0.62f, 0.32f) } };
+ ID2D1GradientStopCollection* sc = nullptr;
+ if (FAILED(dc->CreateGradientStopCollection(gs, 4, &sc))) return;
+ float a = (float)(t / (g_busy ? 700.0 : 2400.0));
+ float pulso = g_busy ? 1.f + 0.07f * (float)std::sin(t / 260.0) : 1.f;
+ float rr = r * pulso;
+ ID2D1SolidColorBrush* br = nullptr;
+ dc->CreateSolidColorBrush(D2D1::ColorF(0.62f, 0.38f, 1.f, g_busy ? 0.22f : 0.12f), &br);
+ if (br) { dc->FillEllipse(D2D1::Ellipse(c, rr + 5, rr + 5), br); } // halo
+ D2D1_POINT_2F p0{ c.x + std::cos(a) * rr, c.y + std::sin(a) * rr }, p1{ c.x - std::cos(a) * rr, c.y - std::sin(a) * rr };
+ ID2D1LinearGradientBrush* lg = nullptr;
+ if (SUCCEEDED(dc->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties(p0, p1), sc, &lg))) {
+ dc->FillEllipse(D2D1::Ellipse(c, rr, rr), lg);
+ lg->Release();
+ }
+ sc->Release();
+ if (br) { // reflexo em cima, como uma bolha de vidro
+ br->SetColor(D2D1::ColorF(1, 1, 1, 0.38f));
+ dc->FillEllipse(D2D1::Ellipse({ c.x - rr * 0.25f, c.y - rr * 0.38f }, rr * 0.45f, rr * 0.25f), br);
+ br->SetColor(D2D1::ColorF(1, 1, 1, 0.35f));
+ dc->DrawEllipse(D2D1::Ellipse(c, rr - 0.5f, rr - 0.5f), br, 1);
+ br->Release();
+ }
+}
+
+// quanto do brilho aparece agora (1 pensando, apagando em 0,9 s depois da resposta)
+float ForcaBrilho(double now) {
+ if (g_entrada) return 0;
+ if (g_busy) return 0.85f + 0.15f * (float)std::sin(now / 420.0);
+ float k = (float)((now - g_answerAt) / 900.0);
+ return k >= 1 ? 0.f : (1 - k) * (1 - k);
+}
+bool Animando(double now) {
+ if (g_entrada && voz::Ouvindo()) return true;
+ double digitar = g_a.size() / std::max(110.0, g_a.size() / 2.2) * 1000.0; // o tempo da resposta "digitando"
+ return g_closing || g_busy || !anim::PanelIn(now - g_openAt).done || now - g_answerAt < std::max(950.0, digitar + 50);
+}
+
+void PaintFrente();
+void Paint() {
+ if ((!g_open && !g_closing) || !g_wnd) return;
+ double now = anim::Now();
+ float sc = Sc();
+ bool dark = ui::Dark();
+ float textW = W - PAD * 2 - ORB - 14;
+ std::wstring a = g_busy ? std::wstring(Tr(L"Pensando")) + std::wstring((size_t)(g_pontos % 3 + 1), L'.') : g_a;
+ float ah = AlturaTexto(a, g_tfA, textW); // a altura é a do texto inteiro: o painel não cresce aos pulos enquanto ele "digita"
+ // a resposta aparece como se fosse digitada (issue #38): ~110 letras por segundo, no máximo 2,2 s (as longas vão mais rápido)
+ if (!g_busy && !g_entrada && g_answerAt > 0) {
+ double vel = std::max(110.0, g_a.size() / 2.2);
+ size_t n = (size_t)std::max(0.0, (now - g_answerAt) / 1000.0 * vel);
+ if (n < a.size()) { a = a.substr(0, n); if (n && IS_HIGH_SURROGATE(a.back())) a.pop_back(); }
+ }
+ float qh = AlturaTexto(g_q, g_tfQ, textW);
+ g_contentH = PAD + qh + 8 + ah + PAD;
+ if (g_entrada) { // só o campo: uma linha (ou mais, se o texto quebrar)
+ qh = 0; ah = std::max(AlturaTexto(g_texto.empty() ? L"M" : g_texto, g_tfA, textW), 20.f);
+ g_contentH = std::max(ORB + PAD * 2, PAD + ah + PAD + 4);
+ }
+ HMONITOR hm = MonitorFromWindow(g_wnd, MONITOR_DEFAULTTONEAREST);
+ MONITORINFO mi{ sizeof(mi) }; GetMonitorInfoW(hm, &mi);
+ float maxH = (mi.rcWork.bottom - mi.rcWork.top) / sc * 0.6f;
+ float H = std::clamp(g_contentH, ORB + PAD * 2, maxH);
+ g_viewH = H;
+ g_scroll = std::clamp(g_scroll, 0.f, std::max(0.f, g_contentH - H));
+ int wpx = (int)std::lround((W + 2 * M) * sc), hpx = (int)std::lround((H + 2 * M) * sc);
+ RECT wr; GetWindowRect(g_wnd, &wr);
+ if (wr.bottom - wr.top != hpx || wr.right - wr.left != wpx) {
+ SetWindowPos(g_wnd, nullptr, 0, 0, wpx, hpx, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
+ if (g_back) SetWindowPos(g_back, g_wnd, wr.left, wr.top, wpx, hpx, SWP_NOACTIVATE);
+ }
+ float mpx = M * sc;
+ g_wpx = wpx; g_hpx = hpx; g_H = H;
+ if (g_glass && (wpx != g_pecasW || hpx != g_pecasH || dark != g_pecasDark || now - g_pecasAt > 250)) {
+ g_pecasW = wpx; g_pecasH = hpx; g_pecasDark = dark; g_pecasAt = now;
+ backdrop::SetPieces(g_back, (float)wpx, (float)hpx, { { D2D1::RectF(mpx, mpx, wpx - mpx, hpx - mpx), R * sc } },
+ dark ? D2D1::ColorF(0.13f, 0.13f, 0.14f, 0.55f) : D2D1::ColorF(0.96f, 0.96f, 0.97f, 0.50f), 24.f);
+ }
+ ID2D1DeviceContext* dc = g_glass ? backdrop::ContentBegin(g_back, wpx, hpx, sc) : nullptr;
+ g_inGlass = dc != nullptr;
+ if (!dc) dc = ui::GpuBegin(g_s, wpx, hpx, sc);
+ if (!dc) return;
+ D2D1_MATRIX_3X2_F base; dc->GetTransform(&base);
+ dc->SetTransform(D2D1::Matrix3x2F::Translation(M, M) * base); // o painel começa na folga
+ ID2D1SolidColorBrush* br = nullptr;
+ dc->CreateSolidColorBrush(D2D1::ColorF(1, 1, 1), &br);
+ if (br) {
+ D2D1_RECT_F box = D2D1::RectF(0, 0, W, H);
+ if (!g_inGlass) Brilho(dc, D2D1::RectF(-1, -1, W + 1, H + 1), R + 1, now - g_openAt, ForcaBrilho(now));
+ if (!g_glass) { br->SetColor(dark ? D2D1::ColorF(0.16f, 0.16f, 0.17f, 0.95f) : D2D1::ColorF(0.96f, 0.96f, 0.97f, 0.95f)); dc->FillRoundedRectangle(D2D1::RoundedRect(box, R, R), br); }
+ if (liquid::On()) liquid::Rim(dc, box, R, dark);
+ else { br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.14f) : D2D1::ColorF(0, 0, 0, 0.12f)); dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(0.5f, 0.5f, W - 0.5f, H - 0.5f), R, R), br, 1); }
+ if (!g_inGlass) Orbe(dc, { PAD + ORB / 2, PAD + ORB / 2 }, ORB / 2, now - g_openAt);
+ float x = PAD + ORB + 14;
+ if (g_entrada) { // o campo: o texto digitado (ou o convite em cinza), o cursor piscando e o microfone à direita
+ float y0 = (H - ah) / 2;
+ bool ouvindo = voz::Ouvindo();
+ bool vazio = g_texto.empty();
+ const std::wstring& t = vazio ? std::wstring(ouvindo ? Tr(L"Ouvindo…") : Tr(L"Pergunte à Siri…")) : g_texto;
+ { // o microfone (clique: ditar; de novo: parar)
+ float mx = W - PAD - 14, my = H / 2;
+ g_mic = D2D1::RectF(mx - 16, my - 16, mx + 16, my + 16);
+ if (ouvindo) {
+ float k = 0.5f + 0.5f * (float)std::sin(now / 220.0);
+ br->SetColor(D2D1::ColorF(1.f, 0.23f, 0.19f, 0.18f + 0.14f * k));
+ dc->FillEllipse(D2D1::Ellipse({ mx, my }, 13 + 3 * k, 13 + 3 * k), br);
+ }
+ br->SetColor(ouvindo ? D2D1::ColorF(1.f, 0.27f, 0.23f) : (dark ? D2D1::ColorF(1, 1, 1, 0.75f) : D2D1::ColorF(0, 0, 0, 0.6f)));
+ if (!simbolo::Draw(dc, L"microphone.fill", D2D1::RectF(mx - 7, my - 10, mx + 7, my + 10), br)) {
+ dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(mx - 4, my - 9, mx + 4, my + 3), 4, 4), br);
+ dc->DrawLine({ mx, my + 6 }, { mx, my + 10 }, br, 1.6f);
+ }
+ }
+ textW -= 34;
+ br->SetColor(vazio ? (dark ? D2D1::ColorF(1, 1, 1, 0.38f) : D2D1::ColorF(0, 0, 0, 0.35f)) : (dark ? D2D1::ColorF(1, 1, 1, 0.95f) : D2D1::ColorF(0, 0, 0, 0.88f)));
+ dc->DrawTextW(t.c_str(), (UINT32)t.size(), g_tfA, D2D1::RectF(x, y0, x + textW, y0 + ah + 4), br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT);
+ if (g_cursorOn) { // o cursor no fim do texto
+ IDWriteTextLayout* lay = nullptr; float cx = x, cy = y0, ch = 18;
+ if (!vazio && SUCCEEDED(ui::dw->CreateTextLayout(g_texto.c_str(), (UINT32)g_texto.size(), g_tfA, textW, 10000, &lay))) {
+ DWRITE_HIT_TEST_METRICS hm{}; FLOAT px = 0, py = 0;
+ lay->HitTestTextPosition((UINT32)g_texto.size() - 1, TRUE, &px, &py, &hm);
+ cx = x + px; cy = y0 + py; ch = hm.height; lay->Release();
+ }
+ br->SetColor(D2D1::ColorF(0.40f, 0.52f, 1.f));
+ dc->FillRectangle(D2D1::RectF(cx + 1, cy + 1, cx + 3, cy + ch - 1), br);
+ }
+ br->Release();
+ dc->SetTransform(base);
+ if (g_inGlass) {
+ backdrop::ContentEnd(g_back);
+ PaintFrente(); // o ícone (sem brilho enquanto digita)
+ } else ui::GpuEnd(g_s);
+ return;
+ }
+ dc->PushAxisAlignedClip(D2D1::RectF(x - 2, 8, W - PAD + 2, H - 8), D2D1_ANTIALIAS_MODE_ALIASED);
+ float y = PAD - g_scroll;
+ br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.55f) : D2D1::ColorF(0, 0, 0, 0.5f));
+ dc->DrawTextW(g_q.c_str(), (UINT32)g_q.size(), g_tfQ, D2D1::RectF(x, y, x + textW, y + qh + 4), br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT);
+ y += qh + 8;
+ // a resposta entra subindo um pouco e aparecendo (0,35 s)
+ float k = g_busy ? 1.f : std::clamp((float)((now - g_answerAt) / 350.0), 0.f, 1.f);
+ float e = 1 - (1 - k) * (1 - k) * (1 - k);
+ D2D1_COLOR_F tc = g_erro ? D2D1::ColorF(1.f, 0.42f, 0.38f) : dark ? D2D1::ColorF(1, 1, 1, 0.95f) : D2D1::ColorF(0, 0, 0, 0.88f);
+ tc.a *= g_busy ? 0.6f : e;
+ br->SetColor(tc);
+ float dy = (1 - e) * 8;
+ dc->DrawTextW(a.c_str(), (UINT32)a.size(), g_tfA, D2D1::RectF(x, y + dy, x + textW, y + dy + ah + 4), br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT); // emoji colorido
+ dc->PopAxisAlignedClip();
+ if (g_contentH > H) { // barrinha de rolagem fina
+ float bh = std::max(24.f, H * H / g_contentH), by = 6 + (H - 12 - bh) * (g_scroll / (g_contentH - H));
+ br->SetColor(dark ? D2D1::ColorF(1, 1, 1, 0.3f) : D2D1::ColorF(0, 0, 0, 0.25f));
+ dc->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(W - 8, by, W - 4, by + bh), 2, 2), br);
+ }
+ br->Release();
+ }
+ dc->SetTransform(base);
+ if (g_inGlass) {
+ backdrop::ContentEnd(g_back);
+ PaintFrente();
+ } else ui::GpuEnd(g_s);
+}
+
+// A camada da frente (com vidro): o brilho e o ícone. O desenho dentro do vidro é recortado no formato do painel, e o
+// brilho passa para fora; e, separados, os quadros da animação redesenham só isto (o vidro e o texto ficam parados).
+void PaintFrente() {
+ if ((!g_open && !g_closing) || !g_wnd || !g_inGlass || !g_wpx) return;
+ double now = anim::Now();
+ if (ID2D1DeviceContext* gd = ui::GpuBegin(g_s, g_wpx, g_hpx, Sc())) {
+ D2D1_MATRIX_3X2_F b2; gd->GetTransform(&b2);
+ gd->SetTransform(D2D1::Matrix3x2F::Translation(M, M) * b2);
+ Brilho(gd, D2D1::RectF(-1, -1, W + 1, g_H + 1), R + 1, now - g_openAt, ForcaBrilho(now));
+ Orbe(gd, { PAD + ORB / 2, PAD + ORB / 2 }, ORB / 2, now - g_openAt);
+ gd->SetTransform(b2);
+ ui::GpuEnd(g_s);
+ }
+}
+
+// o conteúdo (texto) muda neste quadro? Sem vidro, tudo é uma camada só e vai sempre
+bool ConteudoMexe(double now) {
+ if (!g_inGlass) return true;
+ if (g_entrada) return voz::Ouvindo(); // o microfone pulsando
+ if (g_busy) return false; // os pontinhos mudam pelo T_PONTOS
+ double digitar = g_a.size() / std::max(110.0, g_a.size() / 2.2) * 1000.0;
+ return now - g_answerAt < std::max(400.0, digitar + 50); // a resposta entrando e "digitando"
+}
+
+// a mola de abrir (crescendo do meio) e a de fechar: escala e opacidade pelo compositor
+void Movimento() {
+ double now = anim::Now();
+ anim::Panel mo = g_closing ? anim::PanelOut(now - g_closeAt) : anim::PanelIn(now - g_openAt);
+ RECT wr; GetWindowRect(g_wnd, &wr);
+ float cx = (wr.right - wr.left) / 2.f, cy = (wr.bottom - wr.top) / 2.f;
+ ui::GpuMotion(g_s, mo.scale, cx, cy, mo.fade); // o brilho (ou tudo, sem vidro)
+ if (g_back) backdrop::Fade(g_back, mo.fade, mo.scale, cx, cy);
+}
+
+// a mola de abrir ou de fechar entregue ao compositor de uma vez (amostrada a cada 10 ms): a escala e a opacidade andam
+// no vsync pelo DWM, sem depender dos nossos quadros (antes, cada quadro atrasado na thread da interface fazia o painel
+// pular). Os nossos quadros ficam só para o brilho e o texto.
+void MolaNoCompositor(bool fechar) {
+ if (!g_wnd) return;
+ std::vector<float> es, op;
+ const float passo = 10.f;
+ for (int i = 0; i < 400; i++) {
+ anim::Panel mo = fechar ? anim::PanelOut(i * passo) : anim::PanelIn(i * passo);
+ es.push_back(mo.scale); op.push_back(mo.fade);
+ if (mo.done) break;
+ }
+ if (es.size() < 2) { es.push_back(es.empty() ? 1.f : es.back()); op.push_back(op.empty() ? 1.f : op.back()); }
+ RECT wr; GetWindowRect(g_wnd, &wr);
+ float cx = (wr.right - wr.left) / 2.f, cy = (wr.bottom - wr.top) / 2.f;
+ ui::GpuMotionAnim(g_s, cx, cy, es, op, passo);
+ if (g_back) backdrop::FadeAnim(g_back, cx, cy, es, op, passo);
+}
+
+void Esconde() {
+ Log(L"siri: painel escondido (%d quadros, %d com o texto; desenho médio %.2f ms, máx %.1f ms; intervalo máx %.0f ms, %d acima de 25 ms)",
+ g_med.n, g_med.cont, g_med.n ? g_med.soma / g_med.n : 0.0, g_med.max, g_med.gapMax, g_med.longos);
+ g_med = {};
+ g_closing = false;
+ ui::FrameClock(g_wnd, WM_SIRI_FRAME, false);
+ ShowWindow(g_wnd, SW_HIDE);
+ if (g_back) ShowWindow(g_back, SW_HIDE);
+}
+
+void Fecha() {
+ if (!g_open) return;
+ voz::Parar();
+ g_open = false; g_busy = false;
+ g_num++; // a resposta que ainda vem é descartada
+ KillTimer(g_wnd, T_PONTOS);
+ if (anim::reduceMotion) { Esconde(); return; }
+ g_closing = true; g_closeAt = anim::Now();
+ MolaNoCompositor(true);
+ ui::FrameClock(g_wnd, WM_SIRI_FRAME, true);
+}
+
+void Copia() {
+ if (g_busy || g_a.empty() || !OpenClipboard(g_wnd)) return;
+ EmptyClipboard();
+ size_t n = (g_a.size() + 1) * sizeof(wchar_t);
+ if (HGLOBAL g = GlobalAlloc(GMEM_MOVEABLE, n)) {
+ if (void* d = GlobalLock(g)) { memcpy(d, g_a.c_str(), n); GlobalUnlock(g); if (!SetClipboardData(CF_UNICODETEXT, g)) GlobalFree(g); }
+ else GlobalFree(g);
+ }
+ CloseClipboard();
+}
+
+LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {
+ switch (m) {
+ case WM_SIRI_FIM: {
+ std::wstring* r = (std::wstring*)l;
+ if ((int)w == g_num && g_open) {
+ g_erro = r->size() > 1 && (*r)[0] == L'\x1';
+ g_a = g_erro ? r->substr(1) : *r;
+ g_busy = false; g_scroll = 0;
+ g_answerAt = anim::Now();
+ KillTimer(h, T_PONTOS);
+ Paint(); // o brilho apaga e a resposta entra: os quadros continuam (WM_SIRI_FRAME)
+ }
+ delete r;
+ return 0;
+ }
+ case WM_LBUTTONUP: { // o microfone do campo
+ float sc = Sc();
+ float x = GET_X_LPARAM(l) / sc - M, y = GET_Y_LPARAM(l) / sc - M;
+ Log(L"siri: clique em %.0f,%.0f (campo %d, microfone %.0f,%.0f-%.0f,%.0f)", x, y, g_entrada, g_mic.left, g_mic.top, g_mic.right, g_mic.bottom);
+ if (g_entrada && x >= g_mic.left && x <= g_mic.right && y >= g_mic.top && y <= g_mic.bottom) {
+ if (voz::Ouvindo()) voz::Parar();
+ else { voz::Ouvir(h, WM_SIRI_VOZ); ui::FrameClock(h, WM_SIRI_FRAME, true); }
+ Paint();
+ }
+ return 0;
+ }
+ case WM_SIRI_VOZ: { // voz.cpp: o texto enquanto fala, o final (pergunta sozinha) ou o aviso
+ std::unique_ptr<std::wstring> t((std::wstring*)l);
+ if (!g_open || !g_entrada) return 0;
+ if (w == voz::V_PARCIAL) { g_texto = *t; Paint(); }
+ else if (w == voz::V_FINAL) {
+ if (!t->empty()) { std::wstring q = *t; siri::Perguntar(q, g_teste); } // como a Siri: falou, perguntou
+ else Paint();
+ } else { // erro: aparece no painel, em vermelho
+ g_entrada = false; g_q.clear(); g_a = *t; g_erro = true; g_answerAt = anim::Now();
+ KillTimer(h, T_CURSOR);
+ ui::FrameClock(h, WM_SIRI_FRAME, true);
+ Paint();
+ }
+ return 0;
+ }
+ case WM_SIRI_FRAME: {
+ ui::FrameAck(h, WM_SIRI_FRAME);
+ double now = anim::Now();
+ if (g_closing) { // a mola de fechar é do compositor
+ if (anim::PanelOut(now - g_closeAt).done) Esconde();
+ return 0;
+ }
+ { // medição dos quadros (no log ao esconder): quanto cada um custa e o intervalo entre eles
+ LARGE_INTEGER f, t0, t1; QueryPerformanceFrequency(&f); QueryPerformanceCounter(&t0);
+ bool cont = ConteudoMexe(now);
+ if (cont) Paint(); else PaintFrente();
+ QueryPerformanceCounter(&t1);
+ double ms = (t1.QuadPart - t0.QuadPart) * 1000.0 / f.QuadPart;
+ static double ultimo;
+ double gap = ultimo > 0 ? now - ultimo : 0; ultimo = now;
+ g_med.n++; g_med.soma += ms; g_med.max = std::max(g_med.max, ms); if (cont) g_med.cont++;
+ if (gap > 0 && gap < 500) { g_med.gapMax = std::max(g_med.gapMax, gap); if (gap > 25) g_med.longos++; }
+ }
+ if (!Animando(now)) ui::FrameClock(h, WM_SIRI_FRAME, false);
+ return 0;
+ }
+ case WM_NCHITTEST: { // só o painel pega o clique; a folga do brilho deixa passar
+ POINT pt{ GET_X_LPARAM(l), GET_Y_LPARAM(l) };
+ RECT wr; GetWindowRect(h, &wr);
+ float sc = Sc(); int mpx = (int)std::lround(M * sc);
+ return pt.x >= wr.left + mpx && pt.x < wr.right - mpx && pt.y >= wr.top + mpx && pt.y < wr.bottom - mpx ? HTCLIENT : HTTRANSPARENT;
+ }
+ case WM_TIMER: if (w == 9) { KillTimer(h, 9); Fecha(); return 0; }
+ if (w == T_CURSOR) { g_cursorOn = !g_cursorOn; if (g_entrada) Paint(); else KillTimer(h, T_CURSOR); return 0; }
+ if (w == T_PONTOS) { g_pontos++; Paint(); } return 0;
+ case WM_MOUSEWHEEL: g_scroll -= GET_WHEEL_DELTA_WPARAM(w) / 120.f * 48; Paint(); return 0;
+ case WM_CHAR:
+ { static int n; if (n++ < 3) Log(L"siri: tecla %u (aberta %d, pensando %d, campo %d)", (unsigned)w, g_open, g_busy, g_entrada); }
+ if (!g_open || g_busy) return 0;
+ if (w == 13) { // Enter: pergunta
+ if (g_entrada && !g_texto.empty()) { std::wstring q = g_texto; siri::Perguntar(q, g_teste); }
+ return 0;
+ }
+ if (w == 8) { if (g_entrada && !g_texto.empty()) { g_texto.pop_back(); g_cursorOn = true; Paint(); } return 0; }
+ if (w >= 32 && w != 127 && !(GetKeyState(VK_CONTROL) < 0 && GetKeyState(VK_MENU) >= 0)) {
+ if (!g_entrada) { g_entrada = true; g_texto.clear(); g_q.clear(); g_a.clear(); g_scroll = 0; } // digitou depois da resposta: outra pergunta
+ if (g_texto.size() < 2000) g_texto += (wchar_t)w;
+ g_cursorOn = true; SetTimer(h, T_CURSOR, 530, nullptr);
+ Paint();
+ }
+ return 0;
+ case WM_KEYDOWN:
+ if (w == 'V' && GetKeyState(VK_CONTROL) < 0 && !g_busy && OpenClipboard(h)) { // colar no campo
+ if (HANDLE cb = GetClipboardData(CF_UNICODETEXT)) {
+ if (auto* p = (const wchar_t*)GlobalLock(cb)) {
+ std::wstring t = p; GlobalUnlock(cb);
+ for (auto& c : t) if (c == L'\r' || c == L'\n' || c == L'\t') c = L' ';
+ if (!g_entrada) { g_entrada = true; g_texto.clear(); g_q.clear(); g_a.clear(); }
+ g_texto += t.substr(0, 2000 - std::min<size_t>(2000, g_texto.size()));
+ }
+ }
+ CloseClipboard();
+ Paint();
+ return 0;
+ }
+ if (w == VK_ESCAPE) Fecha();
+ else if (w == 'C' && GetKeyState(VK_CONTROL) < 0) Copia();
+ else if (w == VK_DOWN) { g_scroll += 40; Paint(); }
+ else if (w == VK_UP) { g_scroll -= 40; Paint(); }
+ return 0;
+ case WM_ACTIVATE:
+ if (LOWORD(w) == WA_INACTIVE && g_open && !g_teste) {
+ wchar_t c[64] = {}; if (l) GetClassNameW((HWND)l, c, 64);
+ Log(L"siri: perdeu a frente para %ls; fecha", c[0] ? c : L"(nenhuma)");
+ Fecha();
+ }
+ return 0;
+ case WM_CLOSE: Fecha(); return 0;
+ }
+ return DefWindowProcW(h, m, w, l);
+}
+LRESULT CALLBACK BackProc(HWND h, UINT m, WPARAM w, LPARAM l) {
+ if (m == WM_MOUSEACTIVATE) return MA_NOACTIVATE;
+ if (m == WM_NCHITTEST) return HTTRANSPARENT;
+ return DefWindowProcW(h, m, w, l);
+}
+
+bool Ready() {
+ if (g_wnd && IsWindow(g_wnd)) return true;
+ HINSTANCE hi = shell::inst;
+ WNDCLASSW wc{}; wc.lpfnWndProc = Proc; wc.hInstance = hi; wc.lpszClassName = L"ShellSiri"; wc.hCursor = LoadCursorW(nullptr, IDC_ARROW);
+ RegisterClassW(&wc);
+ WNDCLASSW bc{}; bc.lpfnWndProc = BackProc; bc.hInstance = hi; bc.lpszClassName = L"ShellSiriFundo";
+ RegisterClassW(&bc);
+ g_wnd = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP, wc.lpszClassName, L"Siri", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);
+ g_back = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP, bc.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, hi, nullptr);
+ if (!g_wnd || !g_back) { Log(L"siri: janela não criada (%lu)", GetLastError()); return false; }
+ g_glass = backdrop::Attach(g_back);
+ if (!g_glass) { DestroyWindow(g_back); g_back = nullptr; }
+ apps::ours.push_back(g_wnd); if (g_back) apps::ours.push_back(g_back);
+ g_s.hwnd = g_wnd;
+ g_tfQ = ui::Format(12.5f, DWRITE_FONT_WEIGHT_NORMAL);
+ g_tfA = ui::Format(15, DWRITE_FONT_WEIGHT_NORMAL);
+ for (auto* f : { g_tfQ, g_tfA }) if (f) f->SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
+ return true;
+}
+
+} // namespace
+
+bool siri::Pronta() {
+ const auto& provs = siri::Provedores();
+ int p = _wtoi(shell::Setting(L"siri_provedor", L"0").c_str());
+ if (p <= 0 || p >= (int)provs.size()) return false;
+ return !provs[p].precisaChave || GetFileAttributesW(siri::ArquivoChave(p).c_str()) != INVALID_FILE_ATTRIBUTES;
+}
+
+// mostra o painel (a mola de abrir); já aberto, fica onde está e só muda o conteúdo
+static void MostraPainel(bool teste) {
+ if (g_open && IsWindowVisible(g_wnd)) {
+ Paint();
+ ui::FrameClock(g_wnd, WM_SIRI_FRAME, true);
+ return;
+ }
+ // no alto do monitor do ponteiro, centralizado (onde a Siri do Mac aparece... e onde o Spotlight estava)
+ // alinhada ao Spotlight: o mesmo monitor (o do ponteiro), o mesmo centro e o topo do painel na altura do campo dele
+ float sc = ui::Scale(g_wnd);
+ W = spotlight::LarguraCampo();
+ int wpx = (int)std::lround((W + 2 * M) * sc), hpx = (int)std::lround((ORB + PAD * 2 + 2 * M) * sc);
+ RECT sp = spotlight::Lugar();
+ int x = (sp.left + sp.right - wpx) / 2, y = sp.top - (int)std::lround(M * sc);
+ SetWindowPos(g_wnd, HWND_TOPMOST, x, y, wpx, hpx, SWP_NOACTIVATE);
+ if (g_back) SetWindowPos(g_back, g_wnd, x, y, wpx, hpx, SWP_NOACTIVATE);
+ g_open = true; g_closing = false; g_openAt = anim::Now(); g_answerAt = 0; g_pecasW = -1;
+ if (g_glass) backdrop::Fade(g_back, 0, 0.94f, wpx / 2.f, hpx / 2.f); // nasce invisível e um pouco menor: a mola leva até o tamanho
+ ui::GpuMotion(g_s, 0.94f, wpx / 2.f, hpx / 2.f, 0);
+ Paint();
+ MolaNoCompositor(false);
+ if (g_back) ShowWindow(g_back, SW_SHOWNOACTIVATE);
+ ShowWindow(g_wnd, teste ? SW_SHOWNOACTIVATE : SW_SHOW);
+ if (teste) SetTimer(g_wnd, 9, 8000, nullptr);
+ else { shell::LiberaFrente(); SetForegroundWindow(g_wnd); SetFocus(g_wnd); }
+ ui::FrameClock(g_wnd, WM_SIRI_FRAME, true); // a mola de abrir, o brilho e a bolinha enquanto pensa
+}
+
+void siri::Abrir(bool teste) { // o ícone da barra: o painel com o campo para digitar
+ if (!Ready()) return;
+ if (g_open && g_entrada) { Fecha(); return; } // clicar de novo fecha
+ g_teste = teste;
+ g_entrada = true; g_texto.clear(); g_q.clear(); g_a.clear(); g_busy = false; g_erro = false; g_scroll = 0;
+ g_num++;
+ g_cursorOn = true;
+ MostraPainel(teste);
+ SetTimer(g_wnd, T_CURSOR, 530, nullptr);
+}
+
+bool siri::Aberta() { return g_open; }
+
+void siri::Perguntar(const std::wstring& q, bool teste) {
+ if (q.empty() || !Ready()) return;
+ g_teste = teste;
+ if (voz::Ouvindo()) voz::Parar();
+ g_entrada = false; g_texto.clear();
+ KillTimer(g_wnd, T_CURSOR);
+ g_q = q; g_a.clear(); g_busy = true; g_erro = false; g_scroll = 0; g_pontos = 0;
+ g_answerAt = 0;
+ int num = ++g_num;
+ MostraPainel(teste);
+ SetTimer(g_wnd, T_PONTOS, 420, nullptr);
+ HWND to = g_wnd;
+ std::thread([q, num, to] {
+ CoInitializeEx(nullptr, COINIT_MULTITHREADED);
+ bool erro = false;
+ std::wstring r = Pergunta(q, erro, num);
+ auto* res = new std::wstring((erro ? L"\x1" : L"") + r);
+ if (!PostMessageW(to, WM_SIRI_FIM, (WPARAM)num, (LPARAM)res)) delete res; // janela já fechada: não vaza
+ CoUninitialize();
+ }).detach();
+}
diff --git a/src/shell/spotlight.cpp b/src/shell/spotlight.cpp
index 3cb290a..88e36d0 100644
--- a/src/shell/spotlight.cpp
+++ b/src/shell/spotlight.cpp
@@ -69,7 +69,8 @@ void Metricas() {
}
const float LEO_ROW = 20, LEO_COL = 112; // Leopard: linhas de 20 e a coluna das categorias
const UINT WM_SP_FILES = WM_APP + 60, WM_SP_ICON = WM_APP + 61, WM_SP_APPS = WM_APP + 62, WM_SP_FRAME = WM_APP + 63, WM_SP_SUGG = WM_APP + 64, WM_SP_FORA = WM_APP + 65;
-const UINT_PTR T_SEARCH = 1, T_CARET = 2, T_ICONS = 3, T_REGRAB = 4;
+const UINT_PTR T_SEARCH = 1, T_CARET = 2, T_ICONS = 3, T_REGRAB = 4, T_VOZ = 5;
+const UINT WM_SP_VOZ = WM_APP + 66; // voz.cpp: o texto falado (ditado pelo microfone do campo)
enum Kind { K_APP, K_SETTING, K_DOC, K_FOLDER, K_IMAGE, K_MEDIA, K_OTHER, K_CALC, K_WEB, K_AI }; // K_AI: Perguntar à Siri (issue #39)
@@ -1097,6 +1098,7 @@ void ModeChanged() {
bool g_appsList; // apps em lista em vez de grade (botão ⋯)
std::vector<D2D1_RECT_F> g_chipR;
D2D1_RECT_F g_moreR{};
+D2D1_RECT_F g_micR{}; // o microfone do campo (o clique: ditar a busca)
bool ModePanel() { return liquid::On() && g_mode >= 1 && g_mode <= 3; }
std::vector<std::wstring> Chips() {
@@ -1839,9 +1841,17 @@ void Paint() {
D2D1_RECT_F field = gg ? D2D1::RectF(g_query.empty() && g_mode != 0 ? 58.f : 20.f, 0, fpw - 38, FIELD_H) : D2D1::RectF(56, 0, fpw - 20, FIELD_H);
static IDWriteTextFormat* tfFieldGG = ui::Format(22, DWRITE_FONT_WEIGHT_NORMAL);
IDWriteTextFormat* const tfF = gg && tfFieldGG ? tfFieldGG : g_tfField;
- if (g_query.empty() && gg && g_mode == 0) { // macOS 27: microfone (contorno) a ~50 da borda direita, só com o campo vazio
- float mx = fpw - 50 - 18, my = FIELD_H / 2;
- br->SetColor(pf.text2);
+ g_micR = {};
+ bool ouvindo = voz::Ouvindo();
+ if ((g_query.empty() && g_mode == 0) || ouvindo) { // microfone (contorno) à direita: clique dita a busca. macOS 27: a ~50 da borda
+ float mx = gg ? fpw - 50 - 18 : fpw - 36, my = FIELD_H / 2;
+ g_micR = D2D1::RectF(mx - 18 + (gg ? fx0 + 18 : 0), my - 18, mx + 18 + (gg ? fx0 + 18 : 0), my + 18); // o clique é sem o deslocamento do desenho
+ if (ouvindo) {
+ float k = 0.5f + 0.5f * (float)std::sin(anim::Now() / 220.0);
+ br->SetColor(D2D1::ColorF(1.f, 0.23f, 0.19f, 0.16f + 0.14f * k));
+ dc->FillEllipse(D2D1::Ellipse({ mx, my }, 15 + 3 * k, 15 + 3 * k), br);
+ }
+ br->SetColor(ouvindo ? D2D1::ColorF(1.f, 0.27f, 0.23f) : pf.text2);
dc->DrawRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(mx - 4.5f, my - 11, mx + 4.5f, my + 3), 4.5f, 4.5f), br, 1.6f);
ID2D1Factory* fac = nullptr; dc->GetFactory(&fac);
ID2D1PathGeometry* pg = nullptr;
@@ -2336,6 +2346,7 @@ Composicao g_comp; // sílaba ainda em composição no fim da busca (composicao
void Close(bool restore = false) {
if (!g_open) return;
+ if (voz::Ouvindo()) voz::Parar(); // o ditado não continua com o Spotlight fechado
g_comp.Cancela(g_wnd, g_query);
g_open = false;
menubar::SoundChanged(false); // a cápsula da lupa da barra sai
@@ -2620,6 +2631,23 @@ LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {
delete v;
return 0;
}
+ case WM_SP_VOZ: { // voz.cpp: o texto enquanto fala e o final viram a busca; um aviso vira a busca também (em cinza não dá)
+ std::unique_ptr<std::wstring> t((std::wstring*)l);
+ if (!g_open) return 0;
+ if (w == voz::V_PARCIAL || w == voz::V_FINAL) {
+ if (!t->empty() || w == voz::V_FINAL) {
+ if (!t->empty()) { g_query = *t; g_selAll = false; QueryChanged(); }
+ }
+ if (w == voz::V_FINAL) KillTimer(h, T_VOZ);
+ } else {
+ KillTimer(h, T_VOZ);
+ Log(L"spotlight: ditado: %ls", t->c_str());
+ MessageBeep(MB_ICONWARNING);
+ g_query = *t; g_selAll = true; QueryChanged(); // o aviso aparece no campo, todo selecionado (digitar substitui)
+ }
+ Paint();
+ return 0;
+ }
case WM_TIMER:
if (w == T_SEARCH) {
KillTimer(h, T_SEARCH);
@@ -2629,6 +2657,7 @@ LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {
std::thread(SearchFiles, gen, q).detach();
if (!q.empty() && shell::Setting(L"spotlight_google", L"1") == L"1") std::thread(FetchSuggestions, gen, q).detach();
} else if (w == T_CARET) { g_caretOn = !g_caretOn; Paint(); }
+ else if (w == T_VOZ) { if (!voz::Ouvindo()) KillTimer(h, T_VOZ); Paint(); } // o microfone pulsando
else if (w == T_REGRAB) { KillTimer(h, T_REGRAB); if (g_open) Grab(h); }
else if (w == T_ICONS) { KillTimer(h, T_ICONS); Paint(); }
else if (w == T_HOLD) { // segurou um app: a grade treme (como no Launchpad)
@@ -2754,6 +2783,12 @@ LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {
auto pt = Pt(l);
auto in = [&](D2D1_RECT_F r) { return pt.x >= r.left && pt.x < r.right && pt.y >= r.top && pt.y < r.bottom; };
if (g_moreR.right > g_moreR.left && in(g_moreR)) { g_appsList = !g_appsList; g_scroll = 0; ModeChanged(); Refresh(); return 0; } // grade ↔ lista
+ if (g_micR.right > g_micR.left && in(g_micR)) { // o microfone: dita a busca (de novo: para)
+ if (voz::Ouvindo()) { voz::Parar(); KillTimer(h, T_VOZ); }
+ else { voz::Ouvir(h, WM_SP_VOZ); SetTimer(h, T_VOZ, 50, nullptr); }
+ Paint();
+ return 0;
+ }
if (HasChips() && pt.y > FIELD_H && pt.y < ListTop()) { // filtros
for (int c = 0; c < (int)g_chipR.size(); c++)
if (in(g_chipR[c])) { g_chip = g_chip == c + 1 ? 0 : c + 1; g_scroll = 0; ModeChanged(); Refresh(); return 0; }
@@ -2965,6 +3000,13 @@ LRESULT CALLBACK BackProc(HWND h, UINT m, WPARAM w, LPARAM l) {
} // namespace
+RECT spotlight::Lugar() { return PlaceRect(); }
+float spotlight::LarguraCampo() { // o campo do modo de busca (o Apps é mais largo, mas o campo não)
+ if (liquid::Leopard()) return 560.f; // o do Leopard é um menu na ponta direita: a Siri fica com o tamanho dela
+ if (!liquid::On()) return 720.f;
+ return liquid::Golden() ? GG_BAR_W : 640.f;
+}
+
bool spotlight::Create(HINSTANCE hi) {
WNDCLASSW wc{}; wc.lpfnWndProc = Proc; wc.hInstance = hi; wc.lpszClassName = L"ShellSpotlight";
wc.hCursor = LoadCursorW(nullptr, IDC_ARROW); wc.style = CS_DBLCLKS;
diff --git a/src/shell/ui.cpp b/src/shell/ui.cpp
index 600a7c5..66937a6 100644
--- a/src/shell/ui.cpp
+++ b/src/shell/ui.cpp
@@ -1,67 +1,67 @@
-// Desenho comum do shell: Direct2D numa DIB de 32 bits (como o menu de contexto), acrílico,
-// fontes e os ícones próprios (pasta azul do Arquivos, lixeira).
-#include "shell.h"
-#include <shlobj.h>
-#include <shobjidl.h>
-#include <wincodec.h>
-#include "../comum/docicone.h"
-#include <d3d11_4.h>
-#include <dxgi1_2.h>
-#include <dcomp.h>
-#include "../comum/gpu.h"
-#include <dwmapi.h>
-#include <atomic>
-#include <mutex>
-#include <thread>
-#include <algorithm>
-#include <cmath>
-
-ID2D1Factory* ui::d2d;
-IDWriteFactory* ui::dw;
-std::wstring ui::family = L"Segoe UI";
-std::wstring ui::iconFamily = L"Segoe Fluent Icons";
-
-static bool HasFamily(const wchar_t* name) {
- IDWriteFontCollection* fc = nullptr;
- if (FAILED(ui::dw->GetSystemFontCollection(&fc))) return false;
- UINT32 i; BOOL ok = FALSE;
- fc->FindFamilyName(name, &i, &ok);
- fc->Release();
- return ok;
-}
-
-bool ui::Init() {
- if (FAILED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2d))) return false;
- if (FAILED(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), (IUnknown**)&dw))) return false;
- for (auto f : { L"SF Pro Text", L"Inter", L"Segoe UI Variable Text", L"Segoe UI" }) if (HasFamily(f)) { family = f; break; }
- if (!HasFamily(L"Segoe Fluent Icons")) iconFamily = L"Segoe MDL2 Assets";
- Log(L"fonte: %ls, ícones: %ls", family.c_str(), iconFamily.c_str());
- // Fontes carregadas numa thread logo no começo: o DirectWrite abre o arquivo de cada fonte no primeiro texto
- // desenhado com ela, e com o disco ocupado a 1ª abertura da Estante da Ilha (ícones) parou a interface 2,9 s
- // (pilha de 22/11/2026 19:55, issue #32). A fábrica é compartilhada: o que esta thread carrega fica no cache.
- std::thread([fam = family, ic = iconFamily] {
- SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
- DWORD t0 = GetTickCount();
- for (const std::wstring& f : { fam, ic, std::wstring(L"SF Pro Display"), std::wstring(L"SF Pro Rounded"), std::wstring(L"Segoe UI") })
- for (DWRITE_FONT_WEIGHT w : { DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_FONT_WEIGHT_BOLD }) {
- IDWriteTextFormat* tf = nullptr;
- if (FAILED(dw->CreateTextFormat(f.c_str(), nullptr, w, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 13, L"", &tf)) || !tf) continue;
- IDWriteTextLayout* tl = nullptr;
- const wchar_t txt[] = L"Ag 0123 \xE7B8\xE8C8\xE73E\xE7C3";
- if (SUCCEEDED(dw->CreateTextLayout(txt, (UINT32)wcslen(txt), tf, 400, 40, &tl)) && tl) {
- DWRITE_TEXT_METRICS m{}; tl->GetMetrics(&m);
- DWRITE_OVERHANG_METRICS o{}; tl->GetOverhangMetrics(&o);
- tl->Release();
- }
- tf->Release();
- if (f == ic) break; // ícones: um peso basta
- }
- Log(L"fontes: carregadas em %lu ms (fora da interface)", GetTickCount() - t0);
- SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
- }).detach();
- return true;
-}
-
+// Desenho comum do shell: Direct2D numa DIB de 32 bits (como o menu de contexto), acrílico,
+// fontes e os ícones próprios (pasta azul do Arquivos, lixeira).
+#include "shell.h"
+#include <shlobj.h>
+#include <shobjidl.h>
+#include <wincodec.h>
+#include "../comum/docicone.h"
+#include <d3d11_4.h>
+#include <dxgi1_2.h>
+#include <dcomp.h>
+#include "../comum/gpu.h"
+#include <dwmapi.h>
+#include <atomic>
+#include <mutex>
+#include <thread>
+#include <algorithm>
+#include <cmath>
+
+ID2D1Factory* ui::d2d;
+IDWriteFactory* ui::dw;
+std::wstring ui::family = L"Segoe UI";
+std::wstring ui::iconFamily = L"Segoe Fluent Icons";
+
+static bool HasFamily(const wchar_t* name) {
+ IDWriteFontCollection* fc = nullptr;
+ if (FAILED(ui::dw->GetSystemFontCollection(&fc))) return false;
+ UINT32 i; BOOL ok = FALSE;
+ fc->FindFamilyName(name, &i, &ok);
+ fc->Release();
+ return ok;
+}
+
+bool ui::Init() {
+ if (FAILED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2d))) return false;
+ if (FAILED(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), (IUnknown**)&dw))) return false;
+ for (auto f : { L"SF Pro Text", L"Inter", L"Segoe UI Variable Text", L"Segoe UI" }) if (HasFamily(f)) { family = f; break; }
+ if (!HasFamily(L"Segoe Fluent Icons")) iconFamily = L"Segoe MDL2 Assets";
+ Log(L"fonte: %ls, ícones: %ls", family.c_str(), iconFamily.c_str());
+ // Fontes carregadas numa thread logo no começo: o DirectWrite abre o arquivo de cada fonte no primeiro texto
+ // desenhado com ela, e com o disco ocupado a 1ª abertura da Estante da Ilha (ícones) parou a interface 2,9 s
+ // (pilha de 22/11/2026 19:55, issue #32). A fábrica é compartilhada: o que esta thread carrega fica no cache.
+ std::thread([fam = family, ic = iconFamily] {
+ SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
+ DWORD t0 = GetTickCount();
+ for (const std::wstring& f : { fam, ic, std::wstring(L"SF Pro Display"), std::wstring(L"SF Pro Rounded"), std::wstring(L"Segoe UI") })
+ for (DWRITE_FONT_WEIGHT w : { DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_FONT_WEIGHT_BOLD }) {
+ IDWriteTextFormat* tf = nullptr;
+ if (FAILED(dw->CreateTextFormat(f.c_str(), nullptr, w, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 13, L"", &tf)) || !tf) continue;
+ IDWriteTextLayout* tl = nullptr;
+ const wchar_t txt[] = L"Ag 0123 \xE7B8\xE8C8\xE73E\xE7C3";
+ if (SUCCEEDED(dw->CreateTextLayout(txt, (UINT32)wcslen(txt), tf, 400, 40, &tl)) && tl) {
+ DWRITE_TEXT_METRICS m{}; tl->GetMetrics(&m);
+ DWRITE_OVERHANG_METRICS o{}; tl->GetOverhangMetrics(&o);
+ tl->Release();
+ }
+ tf->Release();
+ if (f == ic) break; // ícones: um peso basta
+ }
+ Log(L"fontes: carregadas em %lu ms (fora da interface)", GetTickCount() - t0);
+ SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
+ }).detach();
+ return true;
+}
+
// Dark() roda a cada peça de vidro de cada quadro (~300 vezes por segundo). Lendo o Registro toda vez, a interface
// parava quando ele demorava (RegOpenKeyEx: 1,1 s, pilha de 22/11/2026, 15:14). O Windows avisa quando a chave muda
// (o aviso já está lá quando o RegSetValue volta): só então lê de novo.
@@ -88,914 +88,941 @@ static bool TemaDoWindowsEscuro() {
return escuro;
}
-bool ui::Dark() { // ajuste "tema": auto (segue o Windows), claro ou escuro
- std::wstring t = shell::Setting(L"tema", L"auto");
- if (t == L"claro") return false;
- if (t == L"escuro") return true;
- return TemaDoWindowsEscuro();
-}
-
-float ui::Scale(HWND h) { return GetDpiForWindow(h) / 96.f; }
-
-ID2D1RenderTarget* ui::Begin(Surface& s, int w, int h, float scale) {
- w = std::max(w, 1); h = std::max(h, 1);
- if (s.w != w || s.h != h || !s.mem) {
- if (s.rt) { s.rt->Release(); s.rt = nullptr; }
- if (s.dib) DeleteObject(s.dib);
- if (!s.mem) s.mem = CreateCompatibleDC(nullptr);
- BITMAPINFO bi{};
- bi.bmiHeader = { sizeof(BITMAPINFOHEADER), w, -h, 1, 32, BI_RGB };
- s.dib = CreateDIBSection(nullptr, &bi, DIB_RGB_COLORS, &s.bits, nullptr, 0);
- SelectObject(s.mem, s.dib);
- s.w = w; s.h = h;
- }
- if (!s.rt) {
- auto props = D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT,
- D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED), 96, 96);
- if (FAILED(d2d->CreateDCRenderTarget(&props, &s.rt))) return nullptr;
- s.rt->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
- }
- s.scale = scale;
- RECT rc{ 0, 0, w, h };
- s.rt->BindDC(s.mem, &rc);
- s.rt->SetDpi(96 * scale, 96 * scale);
- s.rt->BeginDraw();
- s.rt->Clear(D2D1::ColorF(0, 0, 0, 0));
- return s.rt;
-}
-
-void ui::End(Surface& s, bool layered, POINT pos) {
- if (FAILED(s.rt->EndDraw())) { s.rt->Release(); s.rt = nullptr; return; }
- if (layered) {
- SIZE sz{ s.w, s.h };
- POINT src{ 0, 0 };
- BLENDFUNCTION bf{ AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
- UpdateLayeredWindow(s.hwnd, nullptr, &pos, &sz, s.mem, &src, 0, &bf, ULW_ALPHA);
- } else {
- HDC dc = GetDC(s.hwnd);
- BitBlt(dc, 0, 0, s.w, s.h, s.mem, 0, 0, SRCCOPY);
- ReleaseDC(s.hwnd, dc);
- }
-}
-
-void ui::Free(Surface& s) {
- if (s.rt) s.rt->Release();
- if (s.dib) DeleteObject(s.dib);
- if (s.mem) DeleteDC(s.mem);
- s = Surface{};
-}
-
-// ---- GPU: um dispositivo para o processo todo; cada janela tem sua swap chain na composição.
-namespace {
-ID3D11Device* g_d3d;
-IDXGIDevice* g_dxgi;
-ID2D1Factory1* g_f1;
-ID2D1Device* g_d2dDev;
-ID2D1DeviceContext* g_dc;
-IDCompositionDevice* g_dcomp;
-}
-
-ID2D1DeviceContext* ui::Gpu() {
- if (g_dc) return g_dc;
- // na placa que liga a tela (a do DWM), não no "padrão": em notebook com GPU híbrida o padrão pode ser a dedicada e cada
- // quadro atravessava as duas placas (comum/gpu.h, issue #33)
- bool naTela = false;
- HRESULT hr = gpu::CriarNaTela(D3D11CreateDevice, D3D11_CREATE_DEVICE_BGRA_SUPPORT, &g_d3d, nullptr, &naTela);
- if (FAILED(hr)) hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT, nullptr, 0, D3D11_SDK_VERSION, &g_d3d, nullptr, nullptr);
- if (FAILED(hr)) { Log(L"erro: D3D11 0x%08X", (unsigned)hr); return nullptr; }
- { wchar_t nome[128]; gpu::NomeDoAdaptador(g_d3d, nome, 128); Log(L"GPU: interface em %ls%ls", nome, naTela ? L" (a placa da tela)" : L" (padrão)"); }
- g_d3d->QueryInterface(IID_PPV_ARGS(&g_dxgi));
- // a captura de janelas (fotogpu.cpp) escreve quadros neste dispositivo de outras threads
- if (ID3D11Multithread* mt = nullptr; SUCCEEDED(g_d3d->QueryInterface(IID_PPV_ARGS(&mt)))) { mt->SetMultithreadProtected(TRUE); mt->Release(); }
- D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory1), nullptr, (void**)&g_f1);
- g_f1->CreateDevice(g_dxgi, &g_d2dDev);
- g_d2dDev->CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &g_dc);
- g_dc->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
- DCompositionCreateDevice(g_dxgi, IID_PPV_ARGS(&g_dcomp));
- return g_dc;
-}
-
-static void BindBack(ui::GpuSurface& s) {
- IDXGISurface* surf = nullptr;
- if (FAILED(s.swap->GetBuffer(0, IID_PPV_ARGS(&surf)))) return;
- auto props = D2D1::BitmapProperties1(D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
- D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED));
- g_dc->CreateBitmapFromDxgiSurface(surf, &props, &s.back);
- surf->Release();
-}
-
-ID2D1DeviceContext* ui::GpuBegin(GpuSurface& s, int w, int h, float scale) {
- if (!Gpu()) return nullptr;
- w = std::max(w, 1); h = std::max(h, 1);
- if (!s.swap) {
- IDXGIFactory2* fac = nullptr;
- CreateDXGIFactory2(0, IID_PPV_ARGS(&fac));
- DXGI_SWAP_CHAIN_DESC1 d{};
- d.Width = w; d.Height = h;
- d.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
- d.SampleDesc.Count = 1;
- d.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
- d.BufferCount = 2;
- d.Scaling = DXGI_SCALING_STRETCH;
- d.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
- d.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
- HRESULT hr = fac->CreateSwapChainForComposition(g_d3d, &d, nullptr, &s.swap);
- fac->Release();
- if (FAILED(hr)) { Log(L"erro: swap chain 0x%08X", (unsigned)hr); return nullptr; }
- g_dcomp->CreateTargetForHwnd(s.hwnd, TRUE, &s.target);
- g_dcomp->CreateVisual(&s.visual);
- s.visual->SetContent(s.swap);
- s.target->SetRoot(s.visual);
- g_dcomp->Commit();
- s.w = w; s.h = h;
- BindBack(s);
- } else if (s.w != w || s.h != h) {
- g_dc->SetTarget(nullptr);
- if (s.back) { s.back->Release(); s.back = nullptr; }
- s.swap->ResizeBuffers(2, w, h, DXGI_FORMAT_UNKNOWN, 0);
- s.w = w; s.h = h;
- BindBack(s);
- }
- g_dc->SetTarget(s.back);
- g_dc->SetDpi(96 * scale, 96 * scale);
- g_dc->BeginDraw();
- g_dc->SetTransform(D2D1::Matrix3x2F::Identity());
- g_dc->Clear(D2D1::ColorF(0, 0, 0, 0));
- return g_dc;
-}
-
-void ui::GpuEnd(GpuSurface& s) {
- HRESULT hr = g_dc->EndDraw();
- if (FAILED(hr)) Log(L"erro: EndDraw 0x%08X", (unsigned)hr);
- s.swap->Present(0, 0); // o ritmo vem do FrameClock (DwmFlush), não do Present
- g_dc->SetTarget(nullptr);
-}
-
-IDCompositionDevice* ui::Comp() { return Gpu() ? g_dcomp : nullptr; }
-ID3D11Device* ui::D3D() { return Gpu() ? g_d3d : nullptr; }
-
-IDCompositionSurface* ui::CompSurface(int w, int h, const std::function<void(ID2D1DeviceContext*)>& draw) {
- if (!Comp() || w < 1 || h < 1) return nullptr;
- IDCompositionSurface* cs = nullptr;
- if (FAILED(g_dcomp->CreateSurface(w, h, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_ALPHA_MODE_PREMULTIPLIED, &cs))) return nullptr;
- IDXGISurface* ds = nullptr; POINT off{};
- if (FAILED(cs->BeginDraw(nullptr, IID_PPV_ARGS(&ds), &off))) { cs->Release(); return nullptr; }
- auto props = D2D1::BitmapProperties1(D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
- D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED));
- ID2D1Bitmap1* bm = nullptr;
- g_dc->CreateBitmapFromDxgiSurface(ds, &props, &bm);
- ds->Release();
- bool ok = false;
- if (bm) {
- g_dc->SetTarget(bm);
- g_dc->SetDpi(96, 96);
- g_dc->BeginDraw();
- g_dc->SetTransform(D2D1::Matrix3x2F::Translation((float)off.x, (float)off.y));
- g_dc->PushAxisAlignedClip(D2D1::RectF(0, 0, (float)w, (float)h), D2D1_ANTIALIAS_MODE_ALIASED);
- g_dc->Clear(D2D1::ColorF(0, 0, 0, 0));
- draw(g_dc);
- g_dc->PopAxisAlignedClip();
- g_dc->SetTransform(D2D1::Matrix3x2F::Identity());
- ok = SUCCEEDED(g_dc->EndDraw());
- g_dc->SetTarget(nullptr);
- bm->Release();
- }
- cs->EndDraw();
- if (!ok) { cs->Release(); return nullptr; }
- return cs;
-}
-
-IDCompositionAnimation* ui::CompCurve(const std::vector<float>& v, float dur) {
- IDCompositionAnimation* an = nullptr;
- if (!Comp() || v.size() < 2 || FAILED(g_dcomp->CreateAnimation(&an))) return nullptr;
- int K = (int)v.size();
- float dt = dur / (K - 1);
- auto slope = [&](int k) {
- if (k == 0) return (v[1] - v[0]) / dt;
- if (k == K - 1) return (v[K - 1] - v[K - 2]) / dt;
- return (v[k + 1] - v[k - 1]) / (2 * dt);
- };
- for (int k = 0; k < K - 1; k++) {
- float p0 = v[k], p1 = v[k + 1], m0 = slope(k), m1 = slope(k + 1), d = (p1 - p0) / dt;
- an->AddCubic(k * dt, p0, m0, (3 * d - 2 * m0 - m1) / dt, (m0 + m1 - 2 * d) / (dt * dt));
- }
- an->End(dur, v[K - 1]);
- return an;
-}
-
-void ui::GpuScale(GpuSurface& s, float scale, float cx, float cy) {
- if (!s.visual || !g_dcomp) return;
- D2D1_MATRIX_3X2_F m = D2D1::Matrix3x2F::Scale(scale, scale, D2D1::Point2F(cx, cy));
- s.visual->SetTransform(m);
- g_dcomp->Commit();
-}
-
-void ui::GpuMotion(GpuSurface& s, float scale, float cx, float cy, float opacity) {
- if (!s.visual || !g_dcomp) return;
- s.visual->SetTransform(D2D1::Matrix3x2F::Scale(scale, scale, D2D1::Point2F(cx, cy)));
- IDCompositionEffectGroup* e = nullptr;
- if (SUCCEEDED(g_dcomp->CreateEffectGroup(&e))) { e->SetOpacity(std::clamp(opacity, 0.f, 1.f)); s.visual->SetEffect(e); e->Release(); }
- g_dcomp->Commit();
-}
-
-void ui::GpuOffset(GpuSurface& s, float x, float y) {
- if (!s.visual) return;
- s.visual->SetOffsetX(x);
- s.visual->SetOffsetY(y);
- g_dcomp->Commit();
-}
-
-// Deslize feito pelo compositor (DWM), não por quadros nossos: liso mesmo com a thread ocupada.
-// Curva ease-out cúbica: p(u) = a + d(3u - 3u² + u³), u = t/T.
-void ui::GpuSlide(GpuSurface& s, float fromX, float fromY, float toX, float toY, float ms) {
- if (!s.visual) return;
- float T = std::max(ms, 1.f) / 1000.f;
- auto curve = [&](float a, float b) -> IDCompositionAnimation* {
- IDCompositionAnimation* an = nullptr;
- if (FAILED(g_dcomp->CreateAnimation(&an))) return nullptr;
- float d = b - a;
- an->AddCubic(0, a, 3 * d / T, -3 * d / (T * T), d / (T * T * T));
- an->End(T, b);
- return an;
- };
- IDCompositionAnimation *ax = curve(fromX, toX), *ay = curve(fromY, toY);
- if (ax) { s.visual->SetOffsetX(ax); ax->Release(); } else s.visual->SetOffsetX(toX);
- if (ay) { s.visual->SetOffsetY(ay); ay->Release(); } else s.visual->SetOffsetY(toY);
- g_dcomp->Commit();
-}
-
-void ui::GpuFree(GpuSurface& s) {
- if (s.back) s.back->Release();
- if (s.visual) s.visual->Release();
- if (s.target) s.target->Release();
- if (s.swap) s.swap->Release();
- s = GpuSurface{ s.hwnd };
-}
-
-// Painéis de tela cheia (Launchpad, Mission Control, Dashboard, Mesas) guardavam os dois buffers do tamanho da tela
-// depois de fechar: ~40 MB cada numa tela 3440x1440, para sempre. Com vídeo integrado isso sai da RAM do PC (8 GB no
-// issue #10). Escondido há 2 minutos, o buffer é solto; a próxima pintura (que esses painéis fazem antes de aparecer)
-// cria outro em poucos ms.
-namespace {
-struct Soltavel { ui::GpuSurface* s; ULONGLONG escondida; };
-std::vector<Soltavel> g_soltaveis;
-}
-void ui::GpuSoltarEscondida(GpuSurface& s) {
- for (auto& x : g_soltaveis) if (x.s == &s) return;
- g_soltaveis.push_back({ &s, 0 });
- static UINT_PTR t = SetTimer(nullptr, 0, 20000, [](HWND, UINT, UINT_PTR, DWORD) {
- ULONGLONG agora = GetTickCount64();
- for (auto& x : g_soltaveis) {
- if (!x.s->swap || !x.s->hwnd || IsWindowVisible(x.s->hwnd)) { x.escondida = 0; continue; }
- if (!x.escondida) { x.escondida = agora; continue; }
- if (agora - x.escondida < 120000) continue;
- wchar_t c[64] = {}; GetClassNameW(x.s->hwnd, c, 64);
- Log(L"GPU: %ls escondida há 2 min: buffers de %dx%d soltos (~%d MB)", c, x.s->w, x.s->h, (int)(2.0 * x.s->w * x.s->h * 4 / (1024 * 1024)));
- GpuFree(*x.s); // fica a hwnd; GpuBegin cria tudo de novo
- if (g_dcomp) g_dcomp->Commit();
- x.escondida = 0;
- }
- });
- (void)t;
-}
-
-// Relógio de quadros: uma thread que espera a composição da tela (DwmFlush) e avisa a janela.
-namespace {
-// Parado, a thread dorme num evento (antes acordava a cada 8 ms para sempre: ~125 vezes por segundo por
-// relógio, mesmo sem nada animando). Animando, roda com prioridade alta para não perder quadro quando o
-// sistema está ocupado.
-// pending/acks: a janela que chama ui::FrameAck recebe o próximo quadro só depois de tratar o anterior (com o
-// desenho mais lento que a tela, as mensagens se acumulavam na fila e o que a pessoa digitava esperava atrás delas)
-struct Clock { HWND hwnd; UINT msg; std::atomic<bool> on; HANDLE wake; std::atomic<bool> pending{ false }, acks{ false }; DWORD postedAt = 0; };
-std::vector<Clock*> g_clocks;
-}
-
-// ---- Estilo dos ícones do macOS 26 (Aparência > Estilo de ícones e widgets)
-D2D1_COLOR_F ui::Accent() {
- static const std::pair<const wchar_t*, UINT32> acc[] = { { L"azul", 0x007AFF }, { L"roxo", 0x953D96 }, { L"rosa", 0xF74F9E }, { L"vermelho", 0xE0383E },
- { L"laranja", 0xF7821B }, { L"amarelo", 0xFCB827 }, { L"verde", 0x62BA46 }, { L"grafite", 0x8C8C8C }, { L"lavanda", 0x98A8D9 } }; // lavanda: a 10ª cor do macOS 27
- std::wstring d = shell::Setting(L"destaque", L"azul");
- UINT32 c = 0x007AFF;
- for (auto& [n, v] : acc) if (d == n) c = v;
- return D2D1::ColorF(((c >> 16) & 255) / 255.f, ((c >> 8) & 255) / 255.f, (c & 255) / 255.f, 1);
-}
-
-std::wstring ui::IconStyleKey() {
- std::wstring st = IconStyle();
- return st == L"padrao" ? st : st + L"/" + shell::Setting(L"destaque", L"azul") + (Dark() ? L"/e" : L"/c");
-}
-
-std::wstring ui::IconStyle() {
- if (!liquid::On()) return L"padrao";
- std::wstring st = shell::Setting(L"estilo_icones", L"padrao");
- // macOS 27: Escuro com "Auto" (estilo_escuro_auto=1) só vale no modo escuro
- if (st == L"escuro" && shell::Setting(L"estilo_escuro_auto", L"0") == L"1" && !Dark()) return L"padrao";
- return st;
-}
-
-// Ícones "Transparente" e "Tingido" do macOS 26: o ícone não ganha só um filtro de cor, vira uma peça de Liquid Glass.
-// O corpo (o próprio formato do ícone) fica translúcido — o vidro do Dock aparece através dele —, o desenho vira
-// branco gravado no vidro e a borda ganha o brilho especular (luz principal a −45° e de preenchimento a 135°, como o
-// CASDFKeyFillHighlightEffect; guia macOS26-Theme-Reference, seção 29.1) e um fio claro em volta. No Tingido o corpo
-// leva a cor de destaque. Tudo nos pixels (BGRA pré-multiplicado), então vale no Dock, no Apps, no Spotlight, na Pilha
-// de Downloads e na Lixeira.
-static void GlassIcon(UINT w, UINT h, std::vector<BYTE>& px, bool tinted, float tr, float tg, float tb, bool dark) {
- const size_t N = (size_t)w * h;
- // 1) cor de fundo do ícone: a média numa faixa a ~12 % da borda do desenho (onde só há fundo)
- double sr = 0, sg = 0, sb = 0; int n = 0;
- auto at = [&](UINT x, UINT y) {
- const BYTE* q = &px[((size_t)y * w + x) * 4];
- if (q[3] < 200) return;
- float a = q[3] / 255.f;
- sb += q[0] / 255.f / a; sg += q[1] / 255.f / a; sr += q[2] / 255.f / a; n++;
- };
- UINT m = std::max(2u, w * 14 / 100);
- for (UINT k = m; k + m < w; k++) { at(k, m); at(k, h - 1 - m); }
- for (UINT k = m; k + m < h; k++) { at(m, k); at(w - 1 - m, k); }
- float br_ = n ? (float)(sr / n) : 1, bg_ = n ? (float)(sg / n) : 1, bb_ = n ? (float)(sb / n) : 1;
- const float bgL = 0.2126f * br_ + 0.7152f * bg_ + 0.0722f * bb_; // claridade do fundo do ícone
- // 2) distância até a borda do formato (chamfer 3-4, duas passadas): a faixa da borda acende
- std::vector<float> dist(N);
- const float INF = 1e9f;
- for (size_t i = 0; i < N; i++) dist[i] = px[i * 4 + 3] >= 128 ? INF : 0;
- for (UINT y = 0; y < h; y++)
- for (UINT x = 0; x < w; x++) {
- float& d = dist[(size_t)y * w + x];
- if (d == 0) continue;
- if (x > 0) d = std::min(d, dist[(size_t)y * w + x - 1] + 1);
- if (y > 0) d = std::min(d, dist[(size_t)(y - 1) * w + x] + 1);
- if (x > 0 && y > 0) d = std::min(d, dist[(size_t)(y - 1) * w + x - 1] + 1.4142f);
- if (x + 1 < w && y > 0) d = std::min(d, dist[(size_t)(y - 1) * w + x + 1] + 1.4142f);
- if (x == 0 || y == 0 || x + 1 == w) d = std::min(d, 1.f);
- }
- for (int y = (int)h - 1; y >= 0; y--)
- for (int x = (int)w - 1; x >= 0; x--) {
- float& d = dist[(size_t)y * w + x];
- if (d == 0) continue;
- if (x + 1 < (int)w) d = std::min(d, dist[(size_t)y * w + x + 1] + 1);
- if (y + 1 < (int)h) d = std::min(d, dist[(size_t)(y + 1) * w + x] + 1);
- if (x + 1 < (int)w && y + 1 < (int)h) d = std::min(d, dist[(size_t)(y + 1) * w + x + 1] + 1.4142f);
- if (x > 0 && y + 1 < (int)h) d = std::min(d, dist[(size_t)(y + 1) * w + x - 1] + 1.4142f);
- if (y + 1 == (int)h || x == 0) d = std::min(d, 1.f);
- }
- const float s = w / 128.f; // escala (os desenhos vão de 32 a 256 px)
- const float cx = w / 2.f, cy = h / 2.f;
- // corpo do vidro: claro bem translúcido (Transparente) ou a cor de destaque (Tingido)
- // (referência do usuário, macOS 26: o corpo é um vidro fosco claro onde a cor de trás aparece, mais claro no alto)
- float bodyA = tinted ? (dark ? 0.30f : 0.36f) : (dark ? 0.10f : 0.16f); // Tingido: bem mais transparente (o usuário) // a cor de trás passa (o desenho branco se destaca)
- float bR = tinted ? tr : 1, bG = tinted ? tg : 1, bB = tinted ? tb : 1;
- // o desenho: o quanto cada pixel foge da cor de fundo do ícone (calculado antes, para a sombra do relevo)
- std::vector<float> fm(N, 0.f), lm(N, 0.f);
- for (size_t i = 0; i < N; i++) {
- BYTE* p = &px[i * 4];
- float a = p[3] / 255.f;
- if (a <= 0.004f) continue;
- float b = p[0] / 255.f / a, g = p[1] / 255.f / a, r = p[2] / 255.f / a;
- lm[i] = 0.2126f * r + 0.7152f * g + 0.0722f * b;
- float dc = std::sqrt((r - br_) * (r - br_) + (g - bg_) * (g - bg_) + (b - bb_) * (b - bb_));
- fm[i] = std::clamp((dc - 0.10f) / 0.30f, 0.f, 1.f);
- // Tingido (o usuário: "o branco, ao invés de ser branco, é transparente"): o que é claro no ícone original
- // vira branco de verdade, mesmo sendo o fundo do ícone (Chrome, Finder...); o resto fica o vidro colorido
- // (ícone de fundo claro: o fundo vira o vidro colorido e o desenho fica branco, senão sumiria tudo no branco)
- if (tinted && bgL < 0.62f) fm[i] = std::max(fm[i], std::clamp((lm[i] - 0.62f) / 0.22f, 0.f, 1.f));
- }
- // Transparente no escuro (print do Dock real do macOS 26, 16/11/2026): não é vidro claro, é uma peça de vidro
- // ESCURA (o fundo do ícone some num grafite translúcido) com o desenho em cinza-claro monocromático, mais claro
- // no alto e mais escuro embaixo, a claridade do original dando os tons (o verde do Spotify vira cinza médio, o
- // branco do Discord vira quase branco); a borda é só um fio fino e discreto, sem brilho largo nem sombra.
- // Tingido no escuro: o mesmo filtro (17/11/2026, o usuário), com a cor de destaque no corpo e no desenho
- if (dark) {
- for (size_t i = 0; i < N; i++) {
- BYTE* p = &px[i * 4];
- float a = p[3] / 255.f;
- if (a <= 0.004f) continue;
- if (dist[i] == 0) { // serrilhado fora do formato: um fio cinza fraco
- float k = a > 0.25f ? a * 0.35f : 0.f;
- p[0] = p[1] = p[2] = (BYTE)std::lround(k * 0.8f * 255); p[3] = (BYTE)std::lround(k * 255);
- continue;
- }
- UINT x = (UINT)(i % w), y = (UINT)(i / w);
- float yy = (float)y / h, l = lm[i], f = fm[i], d = dist[i];
- // corpo: grafite translúcido, um véu claro bem leve no alto
- // (medido sobre preto: a peça do Mac fica em 16/255, quase o fundo do Dock; a nossa estava em 30)
- // Transparente: vidro de verdade, quase sem corpo (com 50 % o papel de parede colorido ficava escurecido e o
- // ícone parecia tingido, 17/11/2026); o desenho claro e o fio da borda fazem a forma
- float oR = 0.06f, oG = 0.06f, oB = 0.065f, oa = 0.24f;
- if (tinted) { oR = tr * 0.30f; oG = tg * 0.30f; oB = tb * 0.30f; oa = 0.62f; }
- float top = 0.015f * std::clamp(1 - yy / 0.45f, 0.f, 1.f);
- oR += (1 - oR) * top; oG += (1 - oG) * top; oB += (1 - oB) * top;
- // desenho: cinza pelo tom do original, em degradê vertical (0,93 no alto, ~0,66 embaixo)
- float grad = 0.93f - 0.27f * yy;
- float gv = std::clamp(grad * (0.58f + 0.48f * l), 0.30f, 0.97f);
- float gR = gv, gG = gv, gB = std::min(1.f, gv + 0.01f);
- if (tinted) { gR = gv * (0.62f + 0.38f * tr); gG = gv * (0.62f + 0.38f * tg); gB = gv * (0.62f + 0.38f * tb); } // desenho claro puxado para o destaque
- oR = oR + (gR - oR) * f; oG = oG + (gG - oG) * f; oB = oB + (gB - oB) * f;
- oa = oa + (0.96f - oa) * f;
- // borda: fio de ~1 px, um pouco mais claro do lado de cima à esquerda
- float nx = x + 0.5f - cx, ny = y + 0.5f - cy, nl = std::sqrt(nx * nx + ny * ny);
- if (nl > 0) { nx /= nl; ny /= nl; }
- float key = std::max(0.f, -(nx + ny) * 0.70711f);
- float rim = d <= 1.2f * s ? 0.22f + 0.22f * key : 0.f;
- rim += std::exp(-std::max(0.f, d - 1) / (1.0f * s)) * 0.10f * key;
- rim = std::clamp(rim, 0.f, 0.5f);
- oR += (0.85f - oR) * rim; oG += (0.85f - oG) * rim; oB += (0.87f - oB) * rim;
- oa += (1 - oa) * rim * 0.6f;
- oa = std::clamp(oa, 0.f, 1.f) * a;
- p[0] = (BYTE)std::lround(std::clamp(oB, 0.f, 1.f) * oa * 255);
- p[1] = (BYTE)std::lround(std::clamp(oG, 0.f, 1.f) * oa * 255);
- p[2] = (BYTE)std::lround(std::clamp(oR, 0.f, 1.f) * oa * 255);
- p[3] = (BYTE)std::lround(oa * 255);
- }
- return;
- }
- const int sh = std::max(1, (int)std::lround(2.f * s)); // sombra do desenho, 2 px (a 128) para baixo
- for (size_t i = 0; i < N; i++) {
- BYTE* p = &px[i * 4];
- float a = p[3] / 255.f;
- if (a <= 0.004f) continue;
- if (dist[i] == 0) { // fora do formato: a sombra do desenho some (o vidro faz a dele); o serrilhado vira o fio claro
- float k = a > 0.25f ? a * 0.6f : 0.f;
- p[0] = p[1] = p[2] = p[3] = (BYTE)std::lround(k * 255);
- continue;
- }
- float l = lm[i], f = fm[i];
- UINT x = (UINT)(i % w), y = (UINT)(i / w);
- float shadow = y >= (UINT)sh ? fm[i - (size_t)sh * w] * (1 - f) : 0.f; // logo abaixo do desenho
- float d = dist[i];
- // a borda: um fio fino e o brilho que entra alguns px no vidro, mais forte do lado da luz
- float nx = x + 0.5f - cx, ny = y + 0.5f - cy, nl = std::sqrt(nx * nx + ny * ny);
- if (nl > 0) { nx /= nl; ny /= nl; }
- float key = std::max(0.f, -(nx + ny) * 0.70711f), fill = std::max(0.f, (nx + ny) * 0.70711f) * 0.5f;
- float edge = std::exp(-std::max(0.f, d - 1) / (2.2f * s));
- float rim = std::clamp((d <= 1.3f * s ? 0.70f : 0.f) + edge * (0.30f + 0.70f * std::pow(key + fill, 1.5f)), 0.f, 1.f);
- // vidro: corpo + bem mais claro no alto (o volume do vidro), sumindo até ~60 % da altura
- float yy = (float)y / h, top = 0.16f * std::clamp(1 - yy / 0.55f, 0.f, 1.f);
- float oa = bodyA + top;
- float oR = bR, oG = bG, oB = bB;
- // a sombra do relevo: um pouco mais escuro logo abaixo do desenho
- oR *= 1 - 0.55f * shadow; oG *= 1 - 0.55f * shadow; oB *= 1 - 0.55f * shadow; oa += 0.16f * shadow;
- // o desenho gravado em branco (com o relevo pela claridade do original)
- float gv = std::clamp(0.92f + 0.16f * (l - 0.5f), 0.f, 1.f);
- float ga = tinted ? 1.f : (dark ? 0.92f : 0.96f);
- oR = oR + (gv - oR) * f; oG = oG + (gv - oG) * f; oB = oB + (gv - oB) * f;
- oa = oa + (ga - oa) * f;
- // o brilho da borda por cima (branco)
- oR = oR + (1 - oR) * rim; oG = oG + (1 - oG) * rim; oB = oB + (1 - oB) * rim;
- oa = oa + (1 - oa) * rim * 0.9f;
- oa = std::clamp(oa, 0.f, 1.f) * a; // o formato (cantos) continua o do ícone
- p[0] = (BYTE)std::lround(std::clamp(oB, 0.f, 1.f) * oa * 255);
- p[1] = (BYTE)std::lround(std::clamp(oG, 0.f, 1.f) * oa * 255);
- p[2] = (BYTE)std::lround(std::clamp(oR, 0.f, 1.f) * oa * 255);
- p[3] = (BYTE)std::lround(oa * 255);
- }
-}
-
-// Escuro: o fundo claro do ícone vira grafite e o desenho colorido fica (um pouco mais vivo);
-// Transparente e Tingido: o ícone vira vidro (GlassIcon).
-void ui::StyleIcon(UINT w, UINT h, std::vector<BYTE>& px, const std::wstring& style) {
- if (style == L"padrao" || style.empty() || px.size() < (size_t)w * h * 4) return;
- float tr = 0.04f, tg = 0.52f, tb = 1.0f; // azul do Mac
- {
- static const std::pair<const wchar_t*, UINT32> acc[] = { { L"roxo", 0x953D96 }, { L"rosa", 0xF74F9E }, { L"vermelho", 0xE0383E },
- { L"laranja", 0xF7821B }, { L"amarelo", 0xFCB827 }, { L"verde", 0x62BA46 }, { L"grafite", 0x8C8C8C }, { L"lavanda", 0x98A8D9 } }; // lavanda: a 10ª cor do macOS 27
- std::wstring d = shell::Setting(L"destaque", L"azul");
- for (auto& [n, c] : acc) if (d == n) { tr = ((c >> 16) & 255) / 255.f; tg = ((c >> 8) & 255) / 255.f; tb = (c & 255) / 255.f; }
- }
- bool dark = ui::Dark();
- if (style == L"transparente" || style == L"tingido") { GlassIcon(w, h, px, style == L"tingido", tr, tg, tb, dark); return; }
- // Escuro: só ícone de fundo claro tem o fundo trocado (o "Live" do Ableton já é escuro, com letra branca).
- // O fundo é o que aparece perto da borda do desenho: média da claridade numa faixa a ~12% da borda.
- bool lightBg = false;
- if (style == L"escuro") {
- double sum = 0; int n = 0;
- auto at = [&](UINT x, UINT y) {
- const BYTE* q = &px[((size_t)y * w + x) * 4];
- if (q[3] < 200) return;
- sum += (0.2126 * q[2] + 0.7152 * q[1] + 0.0722 * q[0]) / q[3]; n++;
- };
- UINT m = std::max(2u, w * 12 / 100);
- for (UINT k = m; k + m < w; k++) { at(k, m); at(k, h - 1 - m); }
- for (UINT k = m; k + m < h; k++) { at(m, k); at(w - 1 - m, k); }
- lightBg = n > 0 && sum / n > 0.6;
- }
- for (size_t i = 0; i < (size_t)w * h; i++) {
- BYTE* p = &px[i * 4];
- float a = p[3] / 255.f;
- if (a <= 0) continue;
- float b = p[0] / 255.f / a, g = p[1] / 255.f / a, r = p[2] / 255.f / a; // sem o pré-multiplicado
- float l = 0.2126f * r + 0.7152f * g + 0.0722f * b;
- float mx = std::max({ r, g, b }), mn = std::min({ r, g, b }), sat = mx > 0 ? (mx - mn) / mx : 0;
- float nr = r, ng = g, nb = b, na = a;
- if (style == L"escuro") {
- if (!lightBg) continue; // fundo já escuro ou colorido: fica como está
- float bg = std::clamp((l - 0.62f) / 0.3f, 0.f, 1.f) * std::clamp(1 - sat / 0.3f, 0.f, 1.f); // fundo claro e pouco colorido
- float d = 0.13f + 0.10f * (1 - l);
- nr = r + (d - r) * bg; ng = g + (d - g) * bg; nb = b + (d - b) * bg;
- } else if (style == L"transparente") {
- float v = (dark ? 0.72f : 0.86f) + 0.70f * (l - 0.5f); // o desenho aparece pela claridade (bem marcado)
- v = std::clamp(v, 0.f, 1.f);
- nr = v; ng = v; nb = std::min(1.f, v + 0.02f);
- na = a * (dark ? 0.74f : 0.80f);
- } else if (style == L"tingido") {
- float v = std::clamp(0.25f + 0.85f * l, 0.f, 1.f);
- float k = std::clamp((v - 0.75f) / 0.25f, 0.f, 1.f); // partes bem claras puxam para o branco
- nr = tr * v + (1 - tr * v) * k * 0.8f; ng = tg * v + (1 - tg * v) * k * 0.8f; nb = tb * v + (1 - tb * v) * k * 0.8f;
- if (dark) { nr *= 0.85f; ng *= 0.85f; nb *= 0.85f; }
- }
- p[0] = (BYTE)std::lround(std::clamp(nb, 0.f, 1.f) * na * 255);
- p[1] = (BYTE)std::lround(std::clamp(ng, 0.f, 1.f) * na * 255);
- p[2] = (BYTE)std::lround(std::clamp(nr, 0.f, 1.f) * na * 255);
- p[3] = (BYTE)std::lround(na * 255);
- }
-}
-
-void ui::FrameAck(HWND hwnd, UINT msg) {
- for (auto* c : g_clocks) if (c->hwnd == hwnd && c->msg == msg) { c->acks = true; c->pending = false; return; }
-}
-
-// Um quadro por vez na fila, para todas as animações: o quadro saiu da fila = o relógio pode mandar o próximo. Sem
-// isso, a 174 Hz, um desenho de mais de 5,7 ms enchia a fila de quadros, e mensagem postada passa na frente do mouse e
-// do teclado: a animação e o resto da interface engasgavam juntos. É gancho da thread (vale também dentro dos laços de
-// menu e de arrastar).
-static LRESULT CALLBACK QuadroSaiu(int code, WPARAM w, LPARAM l) {
- if (code >= 0 && w == PM_REMOVE && l) {
- auto* m = (const MSG*)l;
- if (m->message >= WM_USER)
- for (auto* c : g_clocks)
- if (c->hwnd == m->hwnd && c->msg == m->message) { c->pending = false; break; }
- }
- return CallNextHookEx(nullptr, code, w, l);
-}
-
-void ui::FrameClock(HWND hwnd, UINT msg, bool on) {
- for (auto* c : g_clocks)
- if (c->hwnd == hwnd && c->msg == msg) {
- if (on && !c->on) { c->on = true; SetEvent(c->wake); }
- else if (!on) c->on = false;
- return;
- }
- if (!on) return;
- auto* c = new Clock{ hwnd, msg, true, CreateEventW(nullptr, FALSE, FALSE, nullptr) };
- {
- static thread_local HHOOK gancho;
- DWORD me = GetCurrentThreadId();
- if (GetWindowThreadProcessId(hwnd, nullptr) == me) {
- if (!gancho) gancho = SetWindowsHookExW(WH_GETMESSAGE, QuadroSaiu, nullptr, me);
- c->acks = gancho != nullptr;
- }
- }
- g_clocks.push_back(c);
- std::thread([c] {
- SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
- DWORD since = GetTickCount(); unsigned frames = 0;
- // modo leve (leve.cpp): numa tela de 120/144/165 Hz, um quadro a cada `passo` da tela (~60 por segundo). As
- // animações andam por tempo real: só ficam com menos quadros, e a GPU integrada desenha metade ou um terço
- unsigned vsync = 0, passo = 1;
- auto medePasso = [&passo] {
- DWM_TIMING_INFO ti{ sizeof(ti) };
- passo = 1;
- if (SUCCEEDED(DwmGetCompositionTimingInfo(nullptr, &ti)) && ti.rateRefresh.uiDenominator) {
- double hz = (double)ti.rateRefresh.uiNumerator / ti.rateRefresh.uiDenominator;
- if (hz > 75) passo = (unsigned)std::lround(hz / 60.0);
- }
- };
- if (leve::Ativo()) medePasso();
- for (;;) {
- if (!c->on) { WaitForSingleObject(c->wake, INFINITE); since = GetTickCount(); frames = 0; vsync = 0; if (leve::Ativo()) medePasso(); else passo = 1; continue; }
- DwmFlush();
- if (!c->on) continue;
- if (passo > 1 && (vsync++ % passo) != 0) continue; // modo leve: pula este quadro da tela
- // janela destruída não precisa de quadros: desliga sozinho (janela escondida pode precisar: os
- // widgets animam pela janela invisível do relógio deles)
- if (!IsWindow(c->hwnd)) { c->on = false; continue; }
- if (c->acks && c->pending && GetTickCount() - c->postedAt < 250) continue; // o anterior ainda não foi tratado
- c->pending = true; c->postedAt = GetTickCount();
- PostMessageW(c->hwnd, c->msg, 0, 0);
- if (++frames == 60 * 20) { // 20 s seguidos animando: avisa no log (algo pode ter ficado ligado)
- wchar_t cls[64] = {}; GetClassNameW(c->hwnd, cls, 64);
- Log(L"relógio de quadros: %ls (msg %u) ligado há %lu s", cls, c->msg, (GetTickCount() - since) / 1000);
- }
- }
- }).detach();
-}
-
-void ui::Acrylic(HWND h, DWORD tint) {
- struct ACCENT_POLICY { int state, flags; DWORD gradient; int anim; };
- struct WCA_DATA { int attr; PVOID data; SIZE_T size; };
- using Fn = BOOL(WINAPI*)(HWND, WCA_DATA*);
- static Fn fn = (Fn)GetProcAddress(GetModuleHandleW(L"user32.dll"), "SetWindowCompositionAttribute");
- if (!fn) return;
- // Transparência e Efeitos: a mesma regra de tinta do vidro da Composição (backdrop.cpp)
- float a = backdrop::AdjustAlpha((tint >> 24) / 255.f);
- tint = (tint & 0x00FFFFFFu) | ((DWORD)std::lround(std::clamp(a, 0.f, 1.f) * 255) << 24);
- ACCENT_POLICY ap{ 4 /*ACCENT_ENABLE_ACRYLICBLURBEHIND*/, 0, tint, 0 };
- WCA_DATA d{ 19 /*WCA_ACCENT_POLICY*/, &ap, sizeof(ap) };
- fn(h, &d);
-}
-
-IDWriteTextFormat* ui::Format(float size, DWRITE_FONT_WEIGHT w, bool icons, DWRITE_TEXT_ALIGNMENT a) {
- IDWriteTextFormat* tf = nullptr;
- dw->CreateTextFormat((icons ? iconFamily : family).c_str(), nullptr, w, DWRITE_FONT_STYLE_NORMAL,
- DWRITE_FONT_STRETCH_NORMAL, size, L"pt-br", &tf);
- tf->SetTextAlignment(a);
- tf->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
- tf->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
- return tf;
-}
-
-IDWriteTextFormat* ui::FormatFace(const wchar_t* face, float size, DWRITE_FONT_WEIGHT w) {
- IDWriteTextFormat* tf = nullptr;
- if (FAILED(dw->CreateTextFormat(face, nullptr, w, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, size, L"pt-br", &tf)) || !tf)
- return Format(size, w);
- tf->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
- tf->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
- return tf;
-}
-
-float ui::TextWidth(IDWriteTextFormat* tf, const std::wstring& s) {
- IDWriteTextLayout* tl = nullptr;
- if (FAILED(dw->CreateTextLayout(s.c_str(), (UINT32)s.size(), tf, 10000, 100, &tl))) return 0;
- DWRITE_TEXT_METRICS tm{}; tl->GetMetrics(&tm); tl->Release();
- return tm.widthIncludingTrailingWhitespace;
-}
-
-ID2D1Bitmap* ui::Bitmap(ID2D1RenderTarget* rt, UINT w, UINT h, const std::vector<BYTE>& bgra) {
- if (!w || !h || bgra.size() < (size_t)w * h * 4) return nullptr;
- ID2D1Bitmap* b = nullptr;
- rt->CreateBitmap(D2D1::SizeU(w, h), bgra.data(), w * 4,
- D2D1::BitmapProperties(D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED)), &b);
- return b;
-}
-
-static bool ImagemDoItem(IShellItemImageFactory* f, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra, bool iconOnly) {
- HBITMAP hb = nullptr;
- HRESULT hr = f->GetImage(SIZE{ px, px }, SIIGBF_RESIZETOFIT | (iconOnly ? SIIGBF_ICONONLY : 0), &hb);
- f->Release();
- if (FAILED(hr) || !hb) return false;
- BITMAP bm{}; GetObjectW(hb, sizeof(bm), &bm);
- w = bm.bmWidth; h = std::abs(bm.bmHeight);
- BITMAPINFO bi{};
- bi.bmiHeader = { sizeof(BITMAPINFOHEADER), (LONG)w, -(LONG)h, 1, 32, BI_RGB };
- bgra.resize((size_t)w * h * 4);
- HDC screen = GetDC(nullptr);
- GetDIBits(screen, hb, 0, h, bgra.data(), &bi, DIB_RGB_COLORS);
- ReleaseDC(nullptr, screen);
- DeleteObject(hb);
- bool anyAlpha = false, straight = false;
- for (size_t i = 0; i < bgra.size(); i += 4) {
- if (bgra[i + 3]) anyAlpha = true;
- if (bgra[i] > bgra[i + 3] || bgra[i + 1] > bgra[i + 3] || bgra[i + 2] > bgra[i + 3]) straight = true;
- }
- if (!anyAlpha) for (size_t i = 3; i < bgra.size(); i += 4) bgra[i] = 255;
- else if (straight) // alfa "reto": pré-multiplica (sem isso fica uma borda clara serrilhada)
- for (size_t i = 0; i < bgra.size(); i += 4)
- for (int c = 0; c < 3; c++) bgra[i + c] = (BYTE)(bgra[i + c] * bgra[i + 3] / 255);
- return true;
-}
-
-bool ui::ShellImage(const std::wstring& name, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra, bool iconOnly) {
- IShellItemImageFactory* f = nullptr;
- if (FAILED(SHCreateItemFromParsingName(name.c_str(), nullptr, IID_PPV_ARGS(&f)))) return false;
- return ImagemDoItem(f, px, w, h, bgra, iconOnly);
-}
-
-bool ui::ShellImageId(const std::vector<BYTE>& idList, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra) {
- IShellItemImageFactory* f = nullptr;
- if (idList.empty() || FAILED(SHCreateItemFromIDList((PCIDLIST_ABSOLUTE)idList.data(), IID_PPV_ARGS(&f)))) return false;
- return ImagemDoItem(f, px, w, h, bgra, true);
-}
-
-bool ui::FileImage(const std::wstring& path, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra) {
- DWORD at = GetFileAttributesW(path.c_str());
- bool plain = at != INVALID_FILE_ATTRIBUTES && !(at & FILE_ATTRIBUTE_DIRECTORY) && !docicone::IsApp(path);
- if (plain) {
- IShellItemImageFactory* f = nullptr;
- HBITMAP hb = nullptr;
- if (SUCCEEDED(SHCreateItemFromParsingName(path.c_str(), nullptr, IID_PPV_ARGS(&f)))) {
- if (FAILED(f->GetImage(SIZE{ px, px }, SIIGBF_RESIZETOFIT | SIIGBF_THUMBNAILONLY, &hb))) hb = nullptr;
- f->Release();
- }
- if (hb) { DeleteObject(hb); return ShellImage(path, px, w, h, bgra, false); } // tem miniatura: o mesmo caminho de sempre
- if (docicone::Pixels(path, px, w, h, bgra)) return true;
- }
- return ShellImage(path, px, w, h, bgra, false) || ShellImage(path, px, w, h, bgra, true);
-}
-
-bool ui::LoadPng(const std::wstring& path, UINT& w, UINT& h, std::vector<BYTE>& bgra) {
- static IWICImagingFactory* wic = nullptr;
- if (!wic && FAILED(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic)))) return false;
- IWICBitmapDecoder* dec = nullptr;
- if (FAILED(wic->CreateDecoderFromFilename(path.c_str(), nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &dec))) return false;
- bool ok = false;
- IWICBitmapFrameDecode* fr = nullptr;
- IWICFormatConverter* cv = nullptr;
- if (SUCCEEDED(dec->GetFrame(0, &fr)) && SUCCEEDED(wic->CreateFormatConverter(&cv)) &&
- SUCCEEDED(cv->Initialize(fr, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeCustom))) {
- cv->GetSize(&w, &h);
- bgra.resize((size_t)w * h * 4);
- ok = SUCCEEDED(cv->CopyPixels(nullptr, w * 4, (UINT)bgra.size(), bgra.data()));
- }
- if (cv) cv->Release();
- if (fr) fr->Release();
- dec->Release();
- return ok;
-}
-
-// Foto inteira pelo WIC (o Quick Look): a miniatura do Windows para em ~1024 px e ficava borrada numa tela de
-// 3440. Gira pela orientação do EXIF (foto de celular) e reduz (Fant) até maxSide; nunca amplia.
-bool ui::LoadPhoto(const std::wstring& path, UINT maxSide, UINT& w, UINT& h, std::vector<BYTE>& bgra) {
- IWICImagingFactory* wic = nullptr;
- if (FAILED(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic)))) return false;
- IWICBitmapDecoder* dec = nullptr;
- bool ok = false;
- if (SUCCEEDED(wic->CreateDecoderFromFilename(path.c_str(), nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &dec))) {
- IWICBitmapFrameDecode* fr = nullptr;
- if (SUCCEEDED(dec->GetFrame(0, &fr))) {
- UINT fw = 0, fh = 0; fr->GetSize(&fw, &fh);
- USHORT orient = 1; // 1 normal, 3 = 180°, 6 = 90° horário, 8 = 90° anti-horário (2/4/5/7: espelhadas)
- IWICMetadataQueryReader* q = nullptr;
- if (SUCCEEDED(fr->GetMetadataQueryReader(&q))) {
- for (auto key : { L"/app1/ifd/{ushort=274}", L"/ifd/{ushort=274}", L"System.Photo.Orientation" }) {
- PROPVARIANT v; PropVariantInit(&v);
- if (SUCCEEDED(q->GetMetadataByName(key, &v)) && v.vt == VT_UI2) { orient = v.uiVal; PropVariantClear(&v); break; }
- PropVariantClear(&v);
- }
- q->Release();
- }
- IWICBitmapSource* src = fr; src->AddRef();
- if (fw && fh && maxSide && (fw > maxSide || fh > maxSide)) {
- double k = (double)maxSide / std::max(fw, fh);
- IWICBitmapScaler* sc = nullptr;
- if (SUCCEEDED(wic->CreateBitmapScaler(&sc)) &&
- SUCCEEDED(sc->Initialize(src, std::max(1u, (UINT)(fw * k)), std::max(1u, (UINT)(fh * k)), WICBitmapInterpolationModeFant))) {
- src->Release(); src = sc;
- } else if (sc) sc->Release();
- }
- WICBitmapTransformOptions tr = WICBitmapTransformRotate0;
- switch (orient) {
- case 2: tr = WICBitmapTransformFlipHorizontal; break;
- case 3: tr = WICBitmapTransformRotate180; break;
- case 4: tr = WICBitmapTransformFlipVertical; break;
- case 5: tr = (WICBitmapTransformOptions)(WICBitmapTransformRotate90 | WICBitmapTransformFlipHorizontal); break;
- case 6: tr = WICBitmapTransformRotate90; break;
- case 7: tr = (WICBitmapTransformOptions)(WICBitmapTransformRotate270 | WICBitmapTransformFlipHorizontal); break;
- case 8: tr = WICBitmapTransformRotate270; break;
- }
- if (tr != WICBitmapTransformRotate0) {
- IWICBitmapFlipRotator* rot = nullptr;
- if (SUCCEEDED(wic->CreateBitmapFlipRotator(&rot)) && SUCCEEDED(rot->Initialize(src, tr))) { src->Release(); src = rot; }
- else if (rot) rot->Release();
- }
- IWICFormatConverter* cv = nullptr;
- if (SUCCEEDED(wic->CreateFormatConverter(&cv)) &&
- SUCCEEDED(cv->Initialize(src, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeCustom))) {
- cv->GetSize(&w, &h);
- if (w && h && (size_t)w * h <= 80'000'000) {
- bgra.resize((size_t)w * h * 4);
- ok = SUCCEEDED(cv->CopyPixels(nullptr, w * 4, (UINT)bgra.size(), bgra.data()));
- }
- }
- if (cv) cv->Release();
- src->Release();
- fr->Release();
- }
- dec->Release();
- }
- wic->Release();
- if (!ok) bgra.clear();
- return ok;
-}
-
-// Pasta dos ícones do Sequoia (icones\sequoia, ao lado de bin\): uso pessoal, ver icones\LEIA-ME.txt.
-std::wstring ui::PackIcon(const std::wstring& name) {
- std::wstring root = shell::dir.substr(0, shell::dir.find_last_of(L'\\')) + L"\\icones";
- if (liquid::Leopard()) { // Leopard: os ícones do 10.5 (icones\leopard, tools\icones-leopard.py) vencem até o extra
- std::wstring g = root + L"\\leopard\\" + name + L".png"; // (lá estão as versões Aqua dos ícones do extra)
- if (GetFileAttributesW(g.c_str()) != INVALID_FILE_ATTRIBUTES) return g;
- }
- std::wstring extra = root + L"\\extra\\" + name + L".png"; // escolhidos pelo usuário vencem
- if (GetFileAttributesW(extra.c_str()) != INVALID_FILE_ATTRIBUTES) return extra;
- if (liquid::Golden()) { // Golden Gate: os ícones do macOS 27 (icones\goldengate, tools\icones-goldengate.py)
- std::wstring g = root + L"\\goldengate\\" + name + L".png";
- if (GetFileAttributesW(g.c_str()) != INVALID_FILE_ATTRIBUTES) return g;
- }
- if (liquid::On()) { // Tema Tahoe: icones\tahoe antes do pacote do Sequoia
- std::wstring t = root + L"\\tahoe\\" + name + L".png";
- if (GetFileAttributesW(t.c_str()) != INVALID_FILE_ATTRIBUTES) return t;
- }
- std::wstring dir = shell::Setting(L"icones", L"");
- if (dir.empty()) dir = root + L"\\sequoia";
- std::wstring p = dir + L"\\" + name + L".png";
- return GetFileAttributesW(p.c_str()) != INVALID_FILE_ATTRIBUTES ? p : L"";
-}
-
-// Corta a margem transparente e centraliza num quadrado: todos os ícones ocupam o mesmo espaço,
-// como no Mac (cada ícone do Windows vem com uma margem diferente).
-void ui::TrimToSquare(UINT& w, UINT& h, std::vector<BYTE>& bgra) {
- int x0 = (int)w, y0 = (int)h, x1 = -1, y1 = -1;
- for (int y = 0; y < (int)h; y++)
- for (int x = 0; x < (int)w; x++)
- if (bgra[((size_t)y * w + x) * 4 + 3] > 24) { x0 = std::min(x0, x); y0 = std::min(y0, y); x1 = std::max(x1, x); y1 = std::max(y1, y); }
- if (x1 < 0) return;
- int cw = x1 - x0 + 1, ch = y1 - y0 + 1, s = std::max(cw, ch);
- if (s >= (int)w - 1 && s >= (int)h - 1) return; // já sem margem
- std::vector<BYTE> out((size_t)s * s * 4, 0);
- int ox = (s - cw) / 2, oy = (s - ch) / 2;
- for (int y = 0; y < ch; y++)
- memcpy(&out[((size_t)(y + oy) * s + ox) * 4], &bgra[((size_t)(y + y0) * w + x0) * 4], (size_t)cw * 4);
- bgra.swap(out);
- w = h = (UINT)s;
-}
-
-// Pasta azul (as mesmas cores medidas do Arquivos), com símbolo opcional.
-void ui::DrawFolder(ID2D1RenderTarget* rt, D2D1_RECT_F box, wchar_t glyph) {
- float S = box.right - box.left, x0 = box.left, y0 = box.top;
- auto R = [&](float a, float b, float c, float d) { return D2D1::RectF(x0 + a * S, y0 + b * S, x0 + c * S, y0 + d * S); };
- float rad = 0.06f * S;
- ID2D1SolidColorBrush* br = nullptr;
- rt->CreateSolidColorBrush(D2D1::ColorF(0.06f, 0.49f, 0.78f), &br);
- rt->FillRoundedRectangle(D2D1::RoundedRect(R(0.03f, 0.08f, 0.38f, 0.20f), 0.035f * S, 0.035f * S), br);
- rt->FillRoundedRectangle(D2D1::RoundedRect(R(0.03f, 0.13f, 0.97f, 0.90f), rad, rad), br);
- auto front = R(0.03f, 0.19f, 0.97f, 0.90f);
- ID2D1GradientStopCollection* stops = nullptr;
- D2D1_GRADIENT_STOP gs[2] = { { 0, D2D1::ColorF(0.32f, 0.78f, 0.98f) }, { 1, D2D1::ColorF(0.14f, 0.63f, 0.87f) } };
- rt->CreateGradientStopCollection(gs, 2, &stops);
- ID2D1LinearGradientBrush* lg = nullptr;
- rt->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, front.top }, { 0, front.bottom }), stops, &lg);
- rt->FillRoundedRectangle(D2D1::RoundedRect(front, rad, rad), lg);
- lg->Release(); stops->Release();
- br->SetColor(D2D1::ColorF(1, 1, 1, 0.28f));
- rt->DrawLine({ front.left + rad, front.top + 0.6f }, { front.right - rad, front.top + 0.6f }, br, 1.0f);
- if (glyph) {
- IDWriteTextFormat* tf = Format(std::round(0.40f * S), DWRITE_FONT_WEIGHT_NORMAL, true, DWRITE_TEXT_ALIGNMENT_CENTER);
- auto er = R(0.03f, 0.25f, 0.97f, 0.86f);
- br->SetColor(D2D1::ColorF(0.05f, 0.42f, 0.72f, 0.9f));
- rt->DrawTextW(&glyph, 1, tf, er, br);
- tf->Release();
- }
- br->Release();
-}
-
-// Lixeira: cesto de tela translúcido (vazio) ou com papéis (cheio).
-void ui::DrawTrash(ID2D1RenderTarget* rt, D2D1_RECT_F box, bool full) {
- float S = box.right - box.left, cx = (box.left + box.right) / 2;
- float top = box.top + 0.14f * S, bottom = box.bottom - 0.04f * S;
- float wt = 0.62f * S, wb = 0.50f * S;
- ID2D1Factory* f = nullptr; rt->GetFactory(&f);
- ID2D1PathGeometry* g = nullptr; f->CreatePathGeometry(&g);
- ID2D1GeometrySink* sk = nullptr; g->Open(&sk);
- sk->BeginFigure({ cx - wt / 2, top }, D2D1_FIGURE_BEGIN_FILLED);
- sk->AddLine({ cx + wt / 2, top });
- sk->AddLine({ cx + wb / 2, bottom });
- sk->AddLine({ cx - wb / 2, bottom });
- sk->EndFigure(D2D1_FIGURE_END_CLOSED);
- sk->Close(); sk->Release();
- ID2D1SolidColorBrush* br = nullptr;
- rt->CreateSolidColorBrush(D2D1::ColorF(0.86f, 0.88f, 0.90f, 0.55f), &br);
- if (full) { // papéis amassados aparecendo por cima
- br->SetColor(D2D1::ColorF(0.97f, 0.97f, 0.96f, 1));
- rt->FillEllipse(D2D1::Ellipse({ cx - 0.10f * S, top + 0.02f * S }, 0.15f * S, 0.10f * S), br);
- br->SetColor(D2D1::ColorF(0.90f, 0.92f, 0.95f, 1));
- rt->FillEllipse(D2D1::Ellipse({ cx + 0.10f * S, top + 0.04f * S }, 0.14f * S, 0.09f * S), br);
- br->SetColor(D2D1::ColorF(0.86f, 0.88f, 0.90f, 0.55f));
- }
- rt->FillGeometry(g, br);
- br->SetColor(D2D1::ColorF(0.55f, 0.58f, 0.62f, 0.85f)); // tela: linhas verticais
- for (int k = 1; k < 7; k++) {
- float t = k / 7.f;
- rt->DrawLine({ cx - wt / 2 + wt * t, top + 0.06f * S }, { cx - wb / 2 + wb * t, bottom - 0.02f * S }, br, std::max(0.8f, 0.012f * S));
- }
- rt->DrawGeometry(g, br, std::max(1.f, 0.02f * S));
- br->SetColor(D2D1::ColorF(0.78f, 0.80f, 0.83f, 1)); // aro
- rt->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(cx - wt / 2 - 0.03f * S, top - 0.035f * S, cx + wt / 2 + 0.03f * S, top + 0.035f * S), 0.03f * S, 0.03f * S), br);
- br->Release(); g->Release(); f->Release();
-}
-
-// Reduz uma imagem BGRA pré-multiplicada para caber em maxSide × maxSide, pela média da área coberta
-// (sem serrilhado). Os ícones guardados em memória ficam do tamanho em que são desenhados.
-void ui::Downscale(UINT& w, UINT& h, std::vector<BYTE>& px, UINT maxSide) {
- if (!w || !h || (w <= maxSide && h <= maxSide) || px.size() < (size_t)w * h * 4) return;
- double k = (double)maxSide / std::max(w, h);
- UINT nw = std::max<UINT>(1, (UINT)std::lround(w * k)), nh = std::max<UINT>(1, (UINT)std::lround(h * k));
- double sx = (double)w / nw, sy = (double)h / nh;
- std::vector<BYTE> out((size_t)nw * nh * 4);
- for (UINT y = 0; y < nh; y++) {
- double y0 = y * sy, y1 = y0 + sy;
- for (UINT x = 0; x < nw; x++) {
- double x0 = x * sx, x1 = x0 + sx, acc[4] = {}, area = 0;
- for (UINT yy = (UINT)y0; yy < h && yy < y1; yy++) {
- double wy = std::min<double>(yy + 1, y1) - std::max<double>(yy, y0);
- for (UINT xx = (UINT)x0; xx < w && xx < x1; xx++) {
- double wgt = wy * (std::min<double>(xx + 1, x1) - std::max<double>(xx, x0));
- const BYTE* p = &px[((size_t)yy * w + xx) * 4];
- for (int c = 0; c < 4; c++) acc[c] += p[c] * wgt;
- area += wgt;
- }
- }
- BYTE* o = &out[((size_t)y * nw + x) * 4];
- for (int c = 0; c < 4; c++) o[c] = (BYTE)std::clamp(std::lround(acc[c] / area), 0L, 255L);
- }
- }
- px.swap(out);
- w = nw; h = nh;
-}
+bool ui::Dark() { // ajuste "tema": auto (segue o Windows), claro ou escuro
+ std::wstring t = shell::Setting(L"tema", L"auto");
+ if (t == L"claro") return false;
+ if (t == L"escuro") return true;
+ return TemaDoWindowsEscuro();
+}
+
+float ui::Scale(HWND h) { return GetDpiForWindow(h) / 96.f; }
+
+ID2D1RenderTarget* ui::Begin(Surface& s, int w, int h, float scale) {
+ w = std::max(w, 1); h = std::max(h, 1);
+ if (s.w != w || s.h != h || !s.mem) {
+ if (s.rt) { s.rt->Release(); s.rt = nullptr; }
+ if (s.dib) DeleteObject(s.dib);
+ if (!s.mem) s.mem = CreateCompatibleDC(nullptr);
+ BITMAPINFO bi{};
+ bi.bmiHeader = { sizeof(BITMAPINFOHEADER), w, -h, 1, 32, BI_RGB };
+ s.dib = CreateDIBSection(nullptr, &bi, DIB_RGB_COLORS, &s.bits, nullptr, 0);
+ SelectObject(s.mem, s.dib);
+ s.w = w; s.h = h;
+ }
+ if (!s.rt) {
+ auto props = D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT,
+ D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED), 96, 96);
+ if (FAILED(d2d->CreateDCRenderTarget(&props, &s.rt))) return nullptr;
+ s.rt->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
+ }
+ s.scale = scale;
+ RECT rc{ 0, 0, w, h };
+ s.rt->BindDC(s.mem, &rc);
+ s.rt->SetDpi(96 * scale, 96 * scale);
+ s.rt->BeginDraw();
+ s.rt->Clear(D2D1::ColorF(0, 0, 0, 0));
+ return s.rt;
+}
+
+void ui::End(Surface& s, bool layered, POINT pos) {
+ if (FAILED(s.rt->EndDraw())) { s.rt->Release(); s.rt = nullptr; return; }
+ if (layered) {
+ SIZE sz{ s.w, s.h };
+ POINT src{ 0, 0 };
+ BLENDFUNCTION bf{ AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
+ UpdateLayeredWindow(s.hwnd, nullptr, &pos, &sz, s.mem, &src, 0, &bf, ULW_ALPHA);
+ } else {
+ HDC dc = GetDC(s.hwnd);
+ BitBlt(dc, 0, 0, s.w, s.h, s.mem, 0, 0, SRCCOPY);
+ ReleaseDC(s.hwnd, dc);
+ }
+}
+
+void ui::Free(Surface& s) {
+ if (s.rt) s.rt->Release();
+ if (s.dib) DeleteObject(s.dib);
+ if (s.mem) DeleteDC(s.mem);
+ s = Surface{};
+}
+
+// ---- GPU: um dispositivo para o processo todo; cada janela tem sua swap chain na composição.
+namespace {
+ID3D11Device* g_d3d;
+IDXGIDevice* g_dxgi;
+ID2D1Factory1* g_f1;
+ID2D1Device* g_d2dDev;
+ID2D1DeviceContext* g_dc;
+IDCompositionDevice* g_dcomp;
+}
+
+ID2D1DeviceContext* ui::Gpu() {
+ if (g_dc) return g_dc;
+ // na placa que liga a tela (a do DWM), não no "padrão": em notebook com GPU híbrida o padrão pode ser a dedicada e cada
+ // quadro atravessava as duas placas (comum/gpu.h, issue #33)
+ bool naTela = false;
+ HRESULT hr = gpu::CriarNaTela(D3D11CreateDevice, D3D11_CREATE_DEVICE_BGRA_SUPPORT, &g_d3d, nullptr, &naTela);
+ if (FAILED(hr)) hr = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT, nullptr, 0, D3D11_SDK_VERSION, &g_d3d, nullptr, nullptr);
+ if (FAILED(hr)) { Log(L"erro: D3D11 0x%08X", (unsigned)hr); return nullptr; }
+ { wchar_t nome[128]; gpu::NomeDoAdaptador(g_d3d, nome, 128); Log(L"GPU: interface em %ls%ls", nome, naTela ? L" (a placa da tela)" : L" (padrão)"); }
+ g_d3d->QueryInterface(IID_PPV_ARGS(&g_dxgi));
+ // a captura de janelas (fotogpu.cpp) escreve quadros neste dispositivo de outras threads
+ if (ID3D11Multithread* mt = nullptr; SUCCEEDED(g_d3d->QueryInterface(IID_PPV_ARGS(&mt)))) { mt->SetMultithreadProtected(TRUE); mt->Release(); }
+ D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory1), nullptr, (void**)&g_f1);
+ g_f1->CreateDevice(g_dxgi, &g_d2dDev);
+ g_d2dDev->CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &g_dc);
+ g_dc->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
+ DCompositionCreateDevice(g_dxgi, IID_PPV_ARGS(&g_dcomp));
+ return g_dc;
+}
+
+static void BindBack(ui::GpuSurface& s) {
+ IDXGISurface* surf = nullptr;
+ if (FAILED(s.swap->GetBuffer(0, IID_PPV_ARGS(&surf)))) return;
+ auto props = D2D1::BitmapProperties1(D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
+ D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED));
+ g_dc->CreateBitmapFromDxgiSurface(surf, &props, &s.back);
+ surf->Release();
+}
+
+ID2D1DeviceContext* ui::GpuBegin(GpuSurface& s, int w, int h, float scale) {
+ if (!Gpu()) return nullptr;
+ w = std::max(w, 1); h = std::max(h, 1);
+ if (!s.swap) {
+ IDXGIFactory2* fac = nullptr;
+ CreateDXGIFactory2(0, IID_PPV_ARGS(&fac));
+ DXGI_SWAP_CHAIN_DESC1 d{};
+ d.Width = w; d.Height = h;
+ d.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
+ d.SampleDesc.Count = 1;
+ d.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
+ d.BufferCount = 2;
+ d.Scaling = DXGI_SCALING_STRETCH;
+ d.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
+ d.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
+ HRESULT hr = fac->CreateSwapChainForComposition(g_d3d, &d, nullptr, &s.swap);
+ fac->Release();
+ if (FAILED(hr)) { Log(L"erro: swap chain 0x%08X", (unsigned)hr); return nullptr; }
+ g_dcomp->CreateTargetForHwnd(s.hwnd, TRUE, &s.target);
+ g_dcomp->CreateVisual(&s.visual);
+ s.visual->SetContent(s.swap);
+ s.target->SetRoot(s.visual);
+ g_dcomp->Commit();
+ s.w = w; s.h = h;
+ BindBack(s);
+ } else if (s.w != w || s.h != h) {
+ g_dc->SetTarget(nullptr);
+ if (s.back) { s.back->Release(); s.back = nullptr; }
+ s.swap->ResizeBuffers(2, w, h, DXGI_FORMAT_UNKNOWN, 0);
+ s.w = w; s.h = h;
+ BindBack(s);
+ }
+ g_dc->SetTarget(s.back);
+ g_dc->SetDpi(96 * scale, 96 * scale);
+ g_dc->BeginDraw();
+ g_dc->SetTransform(D2D1::Matrix3x2F::Identity());
+ g_dc->Clear(D2D1::ColorF(0, 0, 0, 0));
+ return g_dc;
+}
+
+void ui::GpuEnd(GpuSurface& s) {
+ HRESULT hr = g_dc->EndDraw();
+ if (FAILED(hr)) Log(L"erro: EndDraw 0x%08X", (unsigned)hr);
+ s.swap->Present(0, 0); // o ritmo vem do FrameClock (DwmFlush), não do Present
+ g_dc->SetTarget(nullptr);
+}
+
+IDCompositionDevice* ui::Comp() { return Gpu() ? g_dcomp : nullptr; }
+ID3D11Device* ui::D3D() { return Gpu() ? g_d3d : nullptr; }
+
+IDCompositionSurface* ui::CompSurface(int w, int h, const std::function<void(ID2D1DeviceContext*)>& draw) {
+ if (!Comp() || w < 1 || h < 1) return nullptr;
+ IDCompositionSurface* cs = nullptr;
+ if (FAILED(g_dcomp->CreateSurface(w, h, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_ALPHA_MODE_PREMULTIPLIED, &cs))) return nullptr;
+ IDXGISurface* ds = nullptr; POINT off{};
+ if (FAILED(cs->BeginDraw(nullptr, IID_PPV_ARGS(&ds), &off))) { cs->Release(); return nullptr; }
+ auto props = D2D1::BitmapProperties1(D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
+ D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED));
+ ID2D1Bitmap1* bm = nullptr;
+ g_dc->CreateBitmapFromDxgiSurface(ds, &props, &bm);
+ ds->Release();
+ bool ok = false;
+ if (bm) {
+ g_dc->SetTarget(bm);
+ g_dc->SetDpi(96, 96);
+ g_dc->BeginDraw();
+ g_dc->SetTransform(D2D1::Matrix3x2F::Translation((float)off.x, (float)off.y));
+ g_dc->PushAxisAlignedClip(D2D1::RectF(0, 0, (float)w, (float)h), D2D1_ANTIALIAS_MODE_ALIASED);
+ g_dc->Clear(D2D1::ColorF(0, 0, 0, 0));
+ draw(g_dc);
+ g_dc->PopAxisAlignedClip();
+ g_dc->SetTransform(D2D1::Matrix3x2F::Identity());
+ ok = SUCCEEDED(g_dc->EndDraw());
+ g_dc->SetTarget(nullptr);
+ bm->Release();
+ }
+ cs->EndDraw();
+ if (!ok) { cs->Release(); return nullptr; }
+ return cs;
+}
+
+IDCompositionAnimation* ui::CompCurve(const std::vector<float>& v, float dur) {
+ IDCompositionAnimation* an = nullptr;
+ if (!Comp() || v.size() < 2 || FAILED(g_dcomp->CreateAnimation(&an))) return nullptr;
+ int K = (int)v.size();
+ float dt = dur / (K - 1);
+ auto slope = [&](int k) {
+ if (k == 0) return (v[1] - v[0]) / dt;
+ if (k == K - 1) return (v[K - 1] - v[K - 2]) / dt;
+ return (v[k + 1] - v[k - 1]) / (2 * dt);
+ };
+ for (int k = 0; k < K - 1; k++) {
+ float p0 = v[k], p1 = v[k + 1], m0 = slope(k), m1 = slope(k + 1), d = (p1 - p0) / dt;
+ an->AddCubic(k * dt, p0, m0, (3 * d - 2 * m0 - m1) / dt, (m0 + m1 - 2 * d) / (dt * dt));
+ }
+ an->End(dur, v[K - 1]);
+ return an;
+}
+
+void ui::GpuScale(GpuSurface& s, float scale, float cx, float cy) {
+ if (!s.visual || !g_dcomp) return;
+ D2D1_MATRIX_3X2_F m = D2D1::Matrix3x2F::Scale(scale, scale, D2D1::Point2F(cx, cy));
+ s.visual->SetTransform(m);
+ g_dcomp->Commit();
+}
+
+void ui::GpuMotion(GpuSurface& s, float scale, float cx, float cy, float opacity) {
+ if (!s.visual || !g_dcomp) return;
+ s.visual->SetTransform(D2D1::Matrix3x2F::Scale(scale, scale, D2D1::Point2F(cx, cy)));
+ IDCompositionEffectGroup* e = nullptr;
+ if (SUCCEEDED(g_dcomp->CreateEffectGroup(&e))) { e->SetOpacity(std::clamp(opacity, 0.f, 1.f)); s.visual->SetEffect(e); e->Release(); }
+ g_dcomp->Commit();
+}
+
+// A curva vira trechos retos entre as amostras (a cada passoMs): o DWM toca sozinho, no ritmo da tela
+void ui::GpuMotionAnim(GpuSurface& s, float cx, float cy, const std::vector<float>& escala, const std::vector<float>& opac, float passoMs) {
+ if (!s.visual || !g_dcomp || escala.size() < 2 || opac.size() < 2) return;
+ float dt = std::max(passoMs, 1.f) / 1000.f;
+ auto curva = [&](const std::vector<float>& v) -> IDCompositionAnimation* {
+ IDCompositionAnimation* an = nullptr;
+ if (FAILED(g_dcomp->CreateAnimation(&an))) return nullptr;
+ for (size_t i = 0; i + 1 < v.size(); i++) an->AddCubic(i * dt, v[i], (v[i + 1] - v[i]) / dt, 0, 0);
+ an->End((v.size() - 1) * dt, v.back());
+ return an;
+ };
+ IDCompositionScaleTransform* st = nullptr;
+ if (SUCCEEDED(g_dcomp->CreateScaleTransform(&st))) {
+ st->SetCenterX(cx); st->SetCenterY(cy);
+ if (IDCompositionAnimation* a = curva(escala)) { st->SetScaleX(a); st->SetScaleY(a); a->Release(); }
+ s.visual->SetTransform(st);
+ st->Release();
+ }
+ IDCompositionEffectGroup* e = nullptr;
+ if (SUCCEEDED(g_dcomp->CreateEffectGroup(&e))) {
+ if (IDCompositionAnimation* a = curva(opac)) { e->SetOpacity(a); a->Release(); }
+ s.visual->SetEffect(e);
+ e->Release();
+ }
+ g_dcomp->Commit();
+}
+
+void ui::GpuOffset(GpuSurface& s, float x, float y) {
+ if (!s.visual) return;
+ s.visual->SetOffsetX(x);
+ s.visual->SetOffsetY(y);
+ g_dcomp->Commit();
+}
+
+// Deslize feito pelo compositor (DWM), não por quadros nossos: liso mesmo com a thread ocupada.
+// Curva ease-out cúbica: p(u) = a + d(3u - 3u² + u³), u = t/T.
+void ui::GpuSlide(GpuSurface& s, float fromX, float fromY, float toX, float toY, float ms) {
+ if (!s.visual) return;
+ float T = std::max(ms, 1.f) / 1000.f;
+ auto curve = [&](float a, float b) -> IDCompositionAnimation* {
+ IDCompositionAnimation* an = nullptr;
+ if (FAILED(g_dcomp->CreateAnimation(&an))) return nullptr;
+ float d = b - a;
+ an->AddCubic(0, a, 3 * d / T, -3 * d / (T * T), d / (T * T * T));
+ an->End(T, b);
+ return an;
+ };
+ IDCompositionAnimation *ax = curve(fromX, toX), *ay = curve(fromY, toY);
+ if (ax) { s.visual->SetOffsetX(ax); ax->Release(); } else s.visual->SetOffsetX(toX);
+ if (ay) { s.visual->SetOffsetY(ay); ay->Release(); } else s.visual->SetOffsetY(toY);
+ g_dcomp->Commit();
+}
+
+void ui::GpuFree(GpuSurface& s) {
+ if (s.back) s.back->Release();
+ if (s.visual) s.visual->Release();
+ if (s.target) s.target->Release();
+ if (s.swap) s.swap->Release();
+ s = GpuSurface{ s.hwnd };
+}
+
+// Painéis de tela cheia (Launchpad, Mission Control, Dashboard, Mesas) guardavam os dois buffers do tamanho da tela
+// depois de fechar: ~40 MB cada numa tela 3440x1440, para sempre. Com vídeo integrado isso sai da RAM do PC (8 GB no
+// issue #10). Escondido há 2 minutos, o buffer é solto; a próxima pintura (que esses painéis fazem antes de aparecer)
+// cria outro em poucos ms.
+namespace {
+struct Soltavel { ui::GpuSurface* s; ULONGLONG escondida; };
+std::vector<Soltavel> g_soltaveis;
+}
+void ui::GpuSoltarEscondida(GpuSurface& s) {
+ for (auto& x : g_soltaveis) if (x.s == &s) return;
+ g_soltaveis.push_back({ &s, 0 });
+ static UINT_PTR t = SetTimer(nullptr, 0, 20000, [](HWND, UINT, UINT_PTR, DWORD) {
+ ULONGLONG agora = GetTickCount64();
+ for (auto& x : g_soltaveis) {
+ if (!x.s->swap || !x.s->hwnd || IsWindowVisible(x.s->hwnd)) { x.escondida = 0; continue; }
+ if (!x.escondida) { x.escondida = agora; continue; }
+ if (agora - x.escondida < 120000) continue;
+ wchar_t c[64] = {}; GetClassNameW(x.s->hwnd, c, 64);
+ Log(L"GPU: %ls escondida há 2 min: buffers de %dx%d soltos (~%d MB)", c, x.s->w, x.s->h, (int)(2.0 * x.s->w * x.s->h * 4 / (1024 * 1024)));
+ GpuFree(*x.s); // fica a hwnd; GpuBegin cria tudo de novo
+ if (g_dcomp) g_dcomp->Commit();
+ x.escondida = 0;
+ }
+ });
+ (void)t;
+}
+
+// Relógio de quadros: uma thread que espera a composição da tela (DwmFlush) e avisa a janela.
+namespace {
+// Parado, a thread dorme num evento (antes acordava a cada 8 ms para sempre: ~125 vezes por segundo por
+// relógio, mesmo sem nada animando). Animando, roda com prioridade alta para não perder quadro quando o
+// sistema está ocupado.
+// pending/acks: a janela que chama ui::FrameAck recebe o próximo quadro só depois de tratar o anterior (com o
+// desenho mais lento que a tela, as mensagens se acumulavam na fila e o que a pessoa digitava esperava atrás delas)
+struct Clock { HWND hwnd; UINT msg; std::atomic<bool> on; HANDLE wake; std::atomic<bool> pending{ false }, acks{ false }; DWORD postedAt = 0; };
+std::vector<Clock*> g_clocks;
+}
+
+// ---- Estilo dos ícones do macOS 26 (Aparência > Estilo de ícones e widgets)
+D2D1_COLOR_F ui::Accent() {
+ static const std::pair<const wchar_t*, UINT32> acc[] = { { L"azul", 0x007AFF }, { L"roxo", 0x953D96 }, { L"rosa", 0xF74F9E }, { L"vermelho", 0xE0383E },
+ { L"laranja", 0xF7821B }, { L"amarelo", 0xFCB827 }, { L"verde", 0x62BA46 }, { L"grafite", 0x8C8C8C }, { L"lavanda", 0x98A8D9 } }; // lavanda: a 10ª cor do macOS 27
+ std::wstring d = shell::Setting(L"destaque", L"azul");
+ UINT32 c = 0x007AFF;
+ for (auto& [n, v] : acc) if (d == n) c = v;
+ return D2D1::ColorF(((c >> 16) & 255) / 255.f, ((c >> 8) & 255) / 255.f, (c & 255) / 255.f, 1);
+}
+
+std::wstring ui::IconStyleKey() {
+ std::wstring st = IconStyle();
+ return st == L"padrao" ? st : st + L"/" + shell::Setting(L"destaque", L"azul") + (Dark() ? L"/e" : L"/c");
+}
+
+std::wstring ui::IconStyle() {
+ if (!liquid::On()) return L"padrao";
+ std::wstring st = shell::Setting(L"estilo_icones", L"padrao");
+ // macOS 27: Escuro com "Auto" (estilo_escuro_auto=1) só vale no modo escuro
+ if (st == L"escuro" && shell::Setting(L"estilo_escuro_auto", L"0") == L"1" && !Dark()) return L"padrao";
+ return st;
+}
+
+// Ícones "Transparente" e "Tingido" do macOS 26: o ícone não ganha só um filtro de cor, vira uma peça de Liquid Glass.
+// O corpo (o próprio formato do ícone) fica translúcido — o vidro do Dock aparece através dele —, o desenho vira
+// branco gravado no vidro e a borda ganha o brilho especular (luz principal a −45° e de preenchimento a 135°, como o
+// CASDFKeyFillHighlightEffect; guia macOS26-Theme-Reference, seção 29.1) e um fio claro em volta. No Tingido o corpo
+// leva a cor de destaque. Tudo nos pixels (BGRA pré-multiplicado), então vale no Dock, no Apps, no Spotlight, na Pilha
+// de Downloads e na Lixeira.
+static void GlassIcon(UINT w, UINT h, std::vector<BYTE>& px, bool tinted, float tr, float tg, float tb, bool dark) {
+ const size_t N = (size_t)w * h;
+ // 1) cor de fundo do ícone: a média numa faixa a ~12 % da borda do desenho (onde só há fundo)
+ double sr = 0, sg = 0, sb = 0; int n = 0;
+ auto at = [&](UINT x, UINT y) {
+ const BYTE* q = &px[((size_t)y * w + x) * 4];
+ if (q[3] < 200) return;
+ float a = q[3] / 255.f;
+ sb += q[0] / 255.f / a; sg += q[1] / 255.f / a; sr += q[2] / 255.f / a; n++;
+ };
+ UINT m = std::max(2u, w * 14 / 100);
+ for (UINT k = m; k + m < w; k++) { at(k, m); at(k, h - 1 - m); }
+ for (UINT k = m; k + m < h; k++) { at(m, k); at(w - 1 - m, k); }
+ float br_ = n ? (float)(sr / n) : 1, bg_ = n ? (float)(sg / n) : 1, bb_ = n ? (float)(sb / n) : 1;
+ const float bgL = 0.2126f * br_ + 0.7152f * bg_ + 0.0722f * bb_; // claridade do fundo do ícone
+ // 2) distância até a borda do formato (chamfer 3-4, duas passadas): a faixa da borda acende
+ std::vector<float> dist(N);
+ const float INF = 1e9f;
+ for (size_t i = 0; i < N; i++) dist[i] = px[i * 4 + 3] >= 128 ? INF : 0;
+ for (UINT y = 0; y < h; y++)
+ for (UINT x = 0; x < w; x++) {
+ float& d = dist[(size_t)y * w + x];
+ if (d == 0) continue;
+ if (x > 0) d = std::min(d, dist[(size_t)y * w + x - 1] + 1);
+ if (y > 0) d = std::min(d, dist[(size_t)(y - 1) * w + x] + 1);
+ if (x > 0 && y > 0) d = std::min(d, dist[(size_t)(y - 1) * w + x - 1] + 1.4142f);
+ if (x + 1 < w && y > 0) d = std::min(d, dist[(size_t)(y - 1) * w + x + 1] + 1.4142f);
+ if (x == 0 || y == 0 || x + 1 == w) d = std::min(d, 1.f);
+ }
+ for (int y = (int)h - 1; y >= 0; y--)
+ for (int x = (int)w - 1; x >= 0; x--) {
+ float& d = dist[(size_t)y * w + x];
+ if (d == 0) continue;
+ if (x + 1 < (int)w) d = std::min(d, dist[(size_t)y * w + x + 1] + 1);
+ if (y + 1 < (int)h) d = std::min(d, dist[(size_t)(y + 1) * w + x] + 1);
+ if (x + 1 < (int)w && y + 1 < (int)h) d = std::min(d, dist[(size_t)(y + 1) * w + x + 1] + 1.4142f);
+ if (x > 0 && y + 1 < (int)h) d = std::min(d, dist[(size_t)(y + 1) * w + x - 1] + 1.4142f);
+ if (y + 1 == (int)h || x == 0) d = std::min(d, 1.f);
+ }
+ const float s = w / 128.f; // escala (os desenhos vão de 32 a 256 px)
+ const float cx = w / 2.f, cy = h / 2.f;
+ // corpo do vidro: claro bem translúcido (Transparente) ou a cor de destaque (Tingido)
+ // (referência do usuário, macOS 26: o corpo é um vidro fosco claro onde a cor de trás aparece, mais claro no alto)
+ float bodyA = tinted ? (dark ? 0.30f : 0.36f) : (dark ? 0.10f : 0.16f); // Tingido: bem mais transparente (o usuário) // a cor de trás passa (o desenho branco se destaca)
+ float bR = tinted ? tr : 1, bG = tinted ? tg : 1, bB = tinted ? tb : 1;
+ // o desenho: o quanto cada pixel foge da cor de fundo do ícone (calculado antes, para a sombra do relevo)
+ std::vector<float> fm(N, 0.f), lm(N, 0.f);
+ for (size_t i = 0; i < N; i++) {
+ BYTE* p = &px[i * 4];
+ float a = p[3] / 255.f;
+ if (a <= 0.004f) continue;
+ float b = p[0] / 255.f / a, g = p[1] / 255.f / a, r = p[2] / 255.f / a;
+ lm[i] = 0.2126f * r + 0.7152f * g + 0.0722f * b;
+ float dc = std::sqrt((r - br_) * (r - br_) + (g - bg_) * (g - bg_) + (b - bb_) * (b - bb_));
+ fm[i] = std::clamp((dc - 0.10f) / 0.30f, 0.f, 1.f);
+ // Tingido (o usuário: "o branco, ao invés de ser branco, é transparente"): o que é claro no ícone original
+ // vira branco de verdade, mesmo sendo o fundo do ícone (Chrome, Finder...); o resto fica o vidro colorido
+ // (ícone de fundo claro: o fundo vira o vidro colorido e o desenho fica branco, senão sumiria tudo no branco)
+ if (tinted && bgL < 0.62f) fm[i] = std::max(fm[i], std::clamp((lm[i] - 0.62f) / 0.22f, 0.f, 1.f));
+ }
+ // Transparente no escuro (print do Dock real do macOS 26, 16/11/2026): não é vidro claro, é uma peça de vidro
+ // ESCURA (o fundo do ícone some num grafite translúcido) com o desenho em cinza-claro monocromático, mais claro
+ // no alto e mais escuro embaixo, a claridade do original dando os tons (o verde do Spotify vira cinza médio, o
+ // branco do Discord vira quase branco); a borda é só um fio fino e discreto, sem brilho largo nem sombra.
+ // Tingido no escuro: o mesmo filtro (17/11/2026, o usuário), com a cor de destaque no corpo e no desenho
+ if (dark) {
+ for (size_t i = 0; i < N; i++) {
+ BYTE* p = &px[i * 4];
+ float a = p[3] / 255.f;
+ if (a <= 0.004f) continue;
+ if (dist[i] == 0) { // serrilhado fora do formato: um fio cinza fraco
+ float k = a > 0.25f ? a * 0.35f : 0.f;
+ p[0] = p[1] = p[2] = (BYTE)std::lround(k * 0.8f * 255); p[3] = (BYTE)std::lround(k * 255);
+ continue;
+ }
+ UINT x = (UINT)(i % w), y = (UINT)(i / w);
+ float yy = (float)y / h, l = lm[i], f = fm[i], d = dist[i];
+ // corpo: grafite translúcido, um véu claro bem leve no alto
+ // (medido sobre preto: a peça do Mac fica em 16/255, quase o fundo do Dock; a nossa estava em 30)
+ // Transparente: vidro de verdade, quase sem corpo (com 50 % o papel de parede colorido ficava escurecido e o
+ // ícone parecia tingido, 17/11/2026); o desenho claro e o fio da borda fazem a forma
+ float oR = 0.06f, oG = 0.06f, oB = 0.065f, oa = 0.24f;
+ if (tinted) { oR = tr * 0.30f; oG = tg * 0.30f; oB = tb * 0.30f; oa = 0.62f; }
+ float top = 0.015f * std::clamp(1 - yy / 0.45f, 0.f, 1.f);
+ oR += (1 - oR) * top; oG += (1 - oG) * top; oB += (1 - oB) * top;
+ // desenho: cinza pelo tom do original, em degradê vertical (0,93 no alto, ~0,66 embaixo)
+ float grad = 0.93f - 0.27f * yy;
+ float gv = std::clamp(grad * (0.58f + 0.48f * l), 0.30f, 0.97f);
+ float gR = gv, gG = gv, gB = std::min(1.f, gv + 0.01f);
+ if (tinted) { gR = gv * (0.62f + 0.38f * tr); gG = gv * (0.62f + 0.38f * tg); gB = gv * (0.62f + 0.38f * tb); } // desenho claro puxado para o destaque
+ oR = oR + (gR - oR) * f; oG = oG + (gG - oG) * f; oB = oB + (gB - oB) * f;
+ oa = oa + (0.96f - oa) * f;
+ // borda: fio de ~1 px, um pouco mais claro do lado de cima à esquerda
+ float nx = x + 0.5f - cx, ny = y + 0.5f - cy, nl = std::sqrt(nx * nx + ny * ny);
+ if (nl > 0) { nx /= nl; ny /= nl; }
+ float key = std::max(0.f, -(nx + ny) * 0.70711f);
+ float rim = d <= 1.2f * s ? 0.22f + 0.22f * key : 0.f;
+ rim += std::exp(-std::max(0.f, d - 1) / (1.0f * s)) * 0.10f * key;
+ rim = std::clamp(rim, 0.f, 0.5f);
+ oR += (0.85f - oR) * rim; oG += (0.85f - oG) * rim; oB += (0.87f - oB) * rim;
+ oa += (1 - oa) * rim * 0.6f;
+ oa = std::clamp(oa, 0.f, 1.f) * a;
+ p[0] = (BYTE)std::lround(std::clamp(oB, 0.f, 1.f) * oa * 255);
+ p[1] = (BYTE)std::lround(std::clamp(oG, 0.f, 1.f) * oa * 255);
+ p[2] = (BYTE)std::lround(std::clamp(oR, 0.f, 1.f) * oa * 255);
+ p[3] = (BYTE)std::lround(oa * 255);
+ }
+ return;
+ }
+ const int sh = std::max(1, (int)std::lround(2.f * s)); // sombra do desenho, 2 px (a 128) para baixo
+ for (size_t i = 0; i < N; i++) {
+ BYTE* p = &px[i * 4];
+ float a = p[3] / 255.f;
+ if (a <= 0.004f) continue;
+ if (dist[i] == 0) { // fora do formato: a sombra do desenho some (o vidro faz a dele); o serrilhado vira o fio claro
+ float k = a > 0.25f ? a * 0.6f : 0.f;
+ p[0] = p[1] = p[2] = p[3] = (BYTE)std::lround(k * 255);
+ continue;
+ }
+ float l = lm[i], f = fm[i];
+ UINT x = (UINT)(i % w), y = (UINT)(i / w);
+ float shadow = y >= (UINT)sh ? fm[i - (size_t)sh * w] * (1 - f) : 0.f; // logo abaixo do desenho
+ float d = dist[i];
+ // a borda: um fio fino e o brilho que entra alguns px no vidro, mais forte do lado da luz
+ float nx = x + 0.5f - cx, ny = y + 0.5f - cy, nl = std::sqrt(nx * nx + ny * ny);
+ if (nl > 0) { nx /= nl; ny /= nl; }
+ float key = std::max(0.f, -(nx + ny) * 0.70711f), fill = std::max(0.f, (nx + ny) * 0.70711f) * 0.5f;
+ float edge = std::exp(-std::max(0.f, d - 1) / (2.2f * s));
+ float rim = std::clamp((d <= 1.3f * s ? 0.70f : 0.f) + edge * (0.30f + 0.70f * std::pow(key + fill, 1.5f)), 0.f, 1.f);
+ // vidro: corpo + bem mais claro no alto (o volume do vidro), sumindo até ~60 % da altura
+ float yy = (float)y / h, top = 0.16f * std::clamp(1 - yy / 0.55f, 0.f, 1.f);
+ float oa = bodyA + top;
+ float oR = bR, oG = bG, oB = bB;
+ // a sombra do relevo: um pouco mais escuro logo abaixo do desenho
+ oR *= 1 - 0.55f * shadow; oG *= 1 - 0.55f * shadow; oB *= 1 - 0.55f * shadow; oa += 0.16f * shadow;
+ // o desenho gravado em branco (com o relevo pela claridade do original)
+ float gv = std::clamp(0.92f + 0.16f * (l - 0.5f), 0.f, 1.f);
+ float ga = tinted ? 1.f : (dark ? 0.92f : 0.96f);
+ oR = oR + (gv - oR) * f; oG = oG + (gv - oG) * f; oB = oB + (gv - oB) * f;
+ oa = oa + (ga - oa) * f;
+ // o brilho da borda por cima (branco)
+ oR = oR + (1 - oR) * rim; oG = oG + (1 - oG) * rim; oB = oB + (1 - oB) * rim;
+ oa = oa + (1 - oa) * rim * 0.9f;
+ oa = std::clamp(oa, 0.f, 1.f) * a; // o formato (cantos) continua o do ícone
+ p[0] = (BYTE)std::lround(std::clamp(oB, 0.f, 1.f) * oa * 255);
+ p[1] = (BYTE)std::lround(std::clamp(oG, 0.f, 1.f) * oa * 255);
+ p[2] = (BYTE)std::lround(std::clamp(oR, 0.f, 1.f) * oa * 255);
+ p[3] = (BYTE)std::lround(oa * 255);
+ }
+}
+
+// Escuro: o fundo claro do ícone vira grafite e o desenho colorido fica (um pouco mais vivo);
+// Transparente e Tingido: o ícone vira vidro (GlassIcon).
+void ui::StyleIcon(UINT w, UINT h, std::vector<BYTE>& px, const std::wstring& style) {
+ if (style == L"padrao" || style.empty() || px.size() < (size_t)w * h * 4) return;
+ float tr = 0.04f, tg = 0.52f, tb = 1.0f; // azul do Mac
+ {
+ static const std::pair<const wchar_t*, UINT32> acc[] = { { L"roxo", 0x953D96 }, { L"rosa", 0xF74F9E }, { L"vermelho", 0xE0383E },
+ { L"laranja", 0xF7821B }, { L"amarelo", 0xFCB827 }, { L"verde", 0x62BA46 }, { L"grafite", 0x8C8C8C }, { L"lavanda", 0x98A8D9 } }; // lavanda: a 10ª cor do macOS 27
+ std::wstring d = shell::Setting(L"destaque", L"azul");
+ for (auto& [n, c] : acc) if (d == n) { tr = ((c >> 16) & 255) / 255.f; tg = ((c >> 8) & 255) / 255.f; tb = (c & 255) / 255.f; }
+ }
+ bool dark = ui::Dark();
+ if (style == L"transparente" || style == L"tingido") { GlassIcon(w, h, px, style == L"tingido", tr, tg, tb, dark); return; }
+ // Escuro: só ícone de fundo claro tem o fundo trocado (o "Live" do Ableton já é escuro, com letra branca).
+ // O fundo é o que aparece perto da borda do desenho: média da claridade numa faixa a ~12% da borda.
+ bool lightBg = false;
+ if (style == L"escuro") {
+ double sum = 0; int n = 0;
+ auto at = [&](UINT x, UINT y) {
+ const BYTE* q = &px[((size_t)y * w + x) * 4];
+ if (q[3] < 200) return;
+ sum += (0.2126 * q[2] + 0.7152 * q[1] + 0.0722 * q[0]) / q[3]; n++;
+ };
+ UINT m = std::max(2u, w * 12 / 100);
+ for (UINT k = m; k + m < w; k++) { at(k, m); at(k, h - 1 - m); }
+ for (UINT k = m; k + m < h; k++) { at(m, k); at(w - 1 - m, k); }
+ lightBg = n > 0 && sum / n > 0.6;
+ }
+ for (size_t i = 0; i < (size_t)w * h; i++) {
+ BYTE* p = &px[i * 4];
+ float a = p[3] / 255.f;
+ if (a <= 0) continue;
+ float b = p[0] / 255.f / a, g = p[1] / 255.f / a, r = p[2] / 255.f / a; // sem o pré-multiplicado
+ float l = 0.2126f * r + 0.7152f * g + 0.0722f * b;
+ float mx = std::max({ r, g, b }), mn = std::min({ r, g, b }), sat = mx > 0 ? (mx - mn) / mx : 0;
+ float nr = r, ng = g, nb = b, na = a;
+ if (style == L"escuro") {
+ if (!lightBg) continue; // fundo já escuro ou colorido: fica como está
+ float bg = std::clamp((l - 0.62f) / 0.3f, 0.f, 1.f) * std::clamp(1 - sat / 0.3f, 0.f, 1.f); // fundo claro e pouco colorido
+ float d = 0.13f + 0.10f * (1 - l);
+ nr = r + (d - r) * bg; ng = g + (d - g) * bg; nb = b + (d - b) * bg;
+ } else if (style == L"transparente") {
+ float v = (dark ? 0.72f : 0.86f) + 0.70f * (l - 0.5f); // o desenho aparece pela claridade (bem marcado)
+ v = std::clamp(v, 0.f, 1.f);
+ nr = v; ng = v; nb = std::min(1.f, v + 0.02f);
+ na = a * (dark ? 0.74f : 0.80f);
+ } else if (style == L"tingido") {
+ float v = std::clamp(0.25f + 0.85f * l, 0.f, 1.f);
+ float k = std::clamp((v - 0.75f) / 0.25f, 0.f, 1.f); // partes bem claras puxam para o branco
+ nr = tr * v + (1 - tr * v) * k * 0.8f; ng = tg * v + (1 - tg * v) * k * 0.8f; nb = tb * v + (1 - tb * v) * k * 0.8f;
+ if (dark) { nr *= 0.85f; ng *= 0.85f; nb *= 0.85f; }
+ }
+ p[0] = (BYTE)std::lround(std::clamp(nb, 0.f, 1.f) * na * 255);
+ p[1] = (BYTE)std::lround(std::clamp(ng, 0.f, 1.f) * na * 255);
+ p[2] = (BYTE)std::lround(std::clamp(nr, 0.f, 1.f) * na * 255);
+ p[3] = (BYTE)std::lround(na * 255);
+ }
+}
+
+void ui::FrameAck(HWND hwnd, UINT msg) {
+ for (auto* c : g_clocks) if (c->hwnd == hwnd && c->msg == msg) { c->acks = true; c->pending = false; return; }
+}
+
+// Um quadro por vez na fila, para todas as animações: o quadro saiu da fila = o relógio pode mandar o próximo. Sem
+// isso, a 174 Hz, um desenho de mais de 5,7 ms enchia a fila de quadros, e mensagem postada passa na frente do mouse e
+// do teclado: a animação e o resto da interface engasgavam juntos. É gancho da thread (vale também dentro dos laços de
+// menu e de arrastar).
+static LRESULT CALLBACK QuadroSaiu(int code, WPARAM w, LPARAM l) {
+ if (code >= 0 && w == PM_REMOVE && l) {
+ auto* m = (const MSG*)l;
+ if (m->message >= WM_USER)
+ for (auto* c : g_clocks)
+ if (c->hwnd == m->hwnd && c->msg == m->message) { c->pending = false; break; }
+ }
+ return CallNextHookEx(nullptr, code, w, l);
+}
+
+void ui::FrameClock(HWND hwnd, UINT msg, bool on) {
+ for (auto* c : g_clocks)
+ if (c->hwnd == hwnd && c->msg == msg) {
+ if (on && !c->on) { c->on = true; SetEvent(c->wake); }
+ else if (!on) c->on = false;
+ return;
+ }
+ if (!on) return;
+ auto* c = new Clock{ hwnd, msg, true, CreateEventW(nullptr, FALSE, FALSE, nullptr) };
+ {
+ static thread_local HHOOK gancho;
+ DWORD me = GetCurrentThreadId();
+ if (GetWindowThreadProcessId(hwnd, nullptr) == me) {
+ if (!gancho) gancho = SetWindowsHookExW(WH_GETMESSAGE, QuadroSaiu, nullptr, me);
+ c->acks = gancho != nullptr;
+ }
+ }
+ g_clocks.push_back(c);
+ std::thread([c] {
+ SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
+ DWORD since = GetTickCount(); unsigned frames = 0;
+ // modo leve (leve.cpp): numa tela de 120/144/165 Hz, um quadro a cada `passo` da tela (~60 por segundo). As
+ // animações andam por tempo real: só ficam com menos quadros, e a GPU integrada desenha metade ou um terço
+ unsigned vsync = 0, passo = 1;
+ auto medePasso = [&passo] {
+ DWM_TIMING_INFO ti{ sizeof(ti) };
+ passo = 1;
+ if (SUCCEEDED(DwmGetCompositionTimingInfo(nullptr, &ti)) && ti.rateRefresh.uiDenominator) {
+ double hz = (double)ti.rateRefresh.uiNumerator / ti.rateRefresh.uiDenominator;
+ if (hz > 75) passo = (unsigned)std::lround(hz / 60.0);
+ }
+ };
+ if (leve::Ativo()) medePasso();
+ for (;;) {
+ if (!c->on) { WaitForSingleObject(c->wake, INFINITE); since = GetTickCount(); frames = 0; vsync = 0; if (leve::Ativo()) medePasso(); else passo = 1; continue; }
+ DwmFlush();
+ if (!c->on) continue;
+ if (passo > 1 && (vsync++ % passo) != 0) continue; // modo leve: pula este quadro da tela
+ // janela destruída não precisa de quadros: desliga sozinho (janela escondida pode precisar: os
+ // widgets animam pela janela invisível do relógio deles)
+ if (!IsWindow(c->hwnd)) { c->on = false; continue; }
+ if (c->acks && c->pending && GetTickCount() - c->postedAt < 250) continue; // o anterior ainda não foi tratado
+ c->pending = true; c->postedAt = GetTickCount();
+ PostMessageW(c->hwnd, c->msg, 0, 0);
+ if (++frames == 60 * 20) { // 20 s seguidos animando: avisa no log (algo pode ter ficado ligado)
+ wchar_t cls[64] = {}; GetClassNameW(c->hwnd, cls, 64);
+ Log(L"relógio de quadros: %ls (msg %u) ligado há %lu s", cls, c->msg, (GetTickCount() - since) / 1000);
+ }
+ }
+ }).detach();
+}
+
+void ui::Acrylic(HWND h, DWORD tint) {
+ struct ACCENT_POLICY { int state, flags; DWORD gradient; int anim; };
+ struct WCA_DATA { int attr; PVOID data; SIZE_T size; };
+ using Fn = BOOL(WINAPI*)(HWND, WCA_DATA*);
+ static Fn fn = (Fn)GetProcAddress(GetModuleHandleW(L"user32.dll"), "SetWindowCompositionAttribute");
+ if (!fn) return;
+ // Transparência e Efeitos: a mesma regra de tinta do vidro da Composição (backdrop.cpp)
+ float a = backdrop::AdjustAlpha((tint >> 24) / 255.f);
+ tint = (tint & 0x00FFFFFFu) | ((DWORD)std::lround(std::clamp(a, 0.f, 1.f) * 255) << 24);
+ ACCENT_POLICY ap{ 4 /*ACCENT_ENABLE_ACRYLICBLURBEHIND*/, 0, tint, 0 };
+ WCA_DATA d{ 19 /*WCA_ACCENT_POLICY*/, &ap, sizeof(ap) };
+ fn(h, &d);
+}
+
+IDWriteTextFormat* ui::Format(float size, DWRITE_FONT_WEIGHT w, bool icons, DWRITE_TEXT_ALIGNMENT a) {
+ IDWriteTextFormat* tf = nullptr;
+ dw->CreateTextFormat((icons ? iconFamily : family).c_str(), nullptr, w, DWRITE_FONT_STYLE_NORMAL,
+ DWRITE_FONT_STRETCH_NORMAL, size, L"pt-br", &tf);
+ tf->SetTextAlignment(a);
+ tf->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
+ tf->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
+ return tf;
+}
+
+IDWriteTextFormat* ui::FormatFace(const wchar_t* face, float size, DWRITE_FONT_WEIGHT w) {
+ IDWriteTextFormat* tf = nullptr;
+ if (FAILED(dw->CreateTextFormat(face, nullptr, w, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, size, L"pt-br", &tf)) || !tf)
+ return Format(size, w);
+ tf->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
+ tf->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
+ return tf;
+}
+
+float ui::TextWidth(IDWriteTextFormat* tf, const std::wstring& s) {
+ IDWriteTextLayout* tl = nullptr;
+ if (FAILED(dw->CreateTextLayout(s.c_str(), (UINT32)s.size(), tf, 10000, 100, &tl))) return 0;
+ DWRITE_TEXT_METRICS tm{}; tl->GetMetrics(&tm); tl->Release();
+ return tm.widthIncludingTrailingWhitespace;
+}
+
+ID2D1Bitmap* ui::Bitmap(ID2D1RenderTarget* rt, UINT w, UINT h, const std::vector<BYTE>& bgra) {
+ if (!w || !h || bgra.size() < (size_t)w * h * 4) return nullptr;
+ ID2D1Bitmap* b = nullptr;
+ rt->CreateBitmap(D2D1::SizeU(w, h), bgra.data(), w * 4,
+ D2D1::BitmapProperties(D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED)), &b);
+ return b;
+}
+
+static bool ImagemDoItem(IShellItemImageFactory* f, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra, bool iconOnly) {
+ HBITMAP hb = nullptr;
+ HRESULT hr = f->GetImage(SIZE{ px, px }, SIIGBF_RESIZETOFIT | (iconOnly ? SIIGBF_ICONONLY : 0), &hb);
+ f->Release();
+ if (FAILED(hr) || !hb) return false;
+ BITMAP bm{}; GetObjectW(hb, sizeof(bm), &bm);
+ w = bm.bmWidth; h = std::abs(bm.bmHeight);
+ BITMAPINFO bi{};
+ bi.bmiHeader = { sizeof(BITMAPINFOHEADER), (LONG)w, -(LONG)h, 1, 32, BI_RGB };
+ bgra.resize((size_t)w * h * 4);
+ HDC screen = GetDC(nullptr);
+ GetDIBits(screen, hb, 0, h, bgra.data(), &bi, DIB_RGB_COLORS);
+ ReleaseDC(nullptr, screen);
+ DeleteObject(hb);
+ bool anyAlpha = false, straight = false;
+ for (size_t i = 0; i < bgra.size(); i += 4) {
+ if (bgra[i + 3]) anyAlpha = true;
+ if (bgra[i] > bgra[i + 3] || bgra[i + 1] > bgra[i + 3] || bgra[i + 2] > bgra[i + 3]) straight = true;
+ }
+ if (!anyAlpha) for (size_t i = 3; i < bgra.size(); i += 4) bgra[i] = 255;
+ else if (straight) // alfa "reto": pré-multiplica (sem isso fica uma borda clara serrilhada)
+ for (size_t i = 0; i < bgra.size(); i += 4)
+ for (int c = 0; c < 3; c++) bgra[i + c] = (BYTE)(bgra[i + c] * bgra[i + 3] / 255);
+ return true;
+}
+
+bool ui::ShellImage(const std::wstring& name, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra, bool iconOnly) {
+ IShellItemImageFactory* f = nullptr;
+ if (FAILED(SHCreateItemFromParsingName(name.c_str(), nullptr, IID_PPV_ARGS(&f)))) return false;
+ return ImagemDoItem(f, px, w, h, bgra, iconOnly);
+}
+
+bool ui::ShellImageId(const std::vector<BYTE>& idList, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra) {
+ IShellItemImageFactory* f = nullptr;
+ if (idList.empty() || FAILED(SHCreateItemFromIDList((PCIDLIST_ABSOLUTE)idList.data(), IID_PPV_ARGS(&f)))) return false;
+ return ImagemDoItem(f, px, w, h, bgra, true);
+}
+
+bool ui::FileImage(const std::wstring& path, int px, UINT& w, UINT& h, std::vector<BYTE>& bgra) {
+ DWORD at = GetFileAttributesW(path.c_str());
+ bool plain = at != INVALID_FILE_ATTRIBUTES && !(at & FILE_ATTRIBUTE_DIRECTORY) && !docicone::IsApp(path);
+ if (plain) {
+ IShellItemImageFactory* f = nullptr;
+ HBITMAP hb = nullptr;
+ if (SUCCEEDED(SHCreateItemFromParsingName(path.c_str(), nullptr, IID_PPV_ARGS(&f)))) {
+ if (FAILED(f->GetImage(SIZE{ px, px }, SIIGBF_RESIZETOFIT | SIIGBF_THUMBNAILONLY, &hb))) hb = nullptr;
+ f->Release();
+ }
+ if (hb) { DeleteObject(hb); return ShellImage(path, px, w, h, bgra, false); } // tem miniatura: o mesmo caminho de sempre
+ if (docicone::Pixels(path, px, w, h, bgra)) return true;
+ }
+ return ShellImage(path, px, w, h, bgra, false) || ShellImage(path, px, w, h, bgra, true);
+}
+
+bool ui::LoadPng(const std::wstring& path, UINT& w, UINT& h, std::vector<BYTE>& bgra) {
+ static IWICImagingFactory* wic = nullptr;
+ if (!wic && FAILED(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic)))) return false;
+ IWICBitmapDecoder* dec = nullptr;
+ if (FAILED(wic->CreateDecoderFromFilename(path.c_str(), nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &dec))) return false;
+ bool ok = false;
+ IWICBitmapFrameDecode* fr = nullptr;
+ IWICFormatConverter* cv = nullptr;
+ if (SUCCEEDED(dec->GetFrame(0, &fr)) && SUCCEEDED(wic->CreateFormatConverter(&cv)) &&
+ SUCCEEDED(cv->Initialize(fr, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeCustom))) {
+ cv->GetSize(&w, &h);
+ bgra.resize((size_t)w * h * 4);
+ ok = SUCCEEDED(cv->CopyPixels(nullptr, w * 4, (UINT)bgra.size(), bgra.data()));
+ }
+ if (cv) cv->Release();
+ if (fr) fr->Release();
+ dec->Release();
+ return ok;
+}
+
+// Foto inteira pelo WIC (o Quick Look): a miniatura do Windows para em ~1024 px e ficava borrada numa tela de
+// 3440. Gira pela orientação do EXIF (foto de celular) e reduz (Fant) até maxSide; nunca amplia.
+bool ui::LoadPhoto(const std::wstring& path, UINT maxSide, UINT& w, UINT& h, std::vector<BYTE>& bgra) {
+ IWICImagingFactory* wic = nullptr;
+ if (FAILED(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic)))) return false;
+ IWICBitmapDecoder* dec = nullptr;
+ bool ok = false;
+ if (SUCCEEDED(wic->CreateDecoderFromFilename(path.c_str(), nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &dec))) {
+ IWICBitmapFrameDecode* fr = nullptr;
+ if (SUCCEEDED(dec->GetFrame(0, &fr))) {
+ UINT fw = 0, fh = 0; fr->GetSize(&fw, &fh);
+ USHORT orient = 1; // 1 normal, 3 = 180°, 6 = 90° horário, 8 = 90° anti-horário (2/4/5/7: espelhadas)
+ IWICMetadataQueryReader* q = nullptr;
+ if (SUCCEEDED(fr->GetMetadataQueryReader(&q))) {
+ for (auto key : { L"/app1/ifd/{ushort=274}", L"/ifd/{ushort=274}", L"System.Photo.Orientation" }) {
+ PROPVARIANT v; PropVariantInit(&v);
+ if (SUCCEEDED(q->GetMetadataByName(key, &v)) && v.vt == VT_UI2) { orient = v.uiVal; PropVariantClear(&v); break; }
+ PropVariantClear(&v);
+ }
+ q->Release();
+ }
+ IWICBitmapSource* src = fr; src->AddRef();
+ if (fw && fh && maxSide && (fw > maxSide || fh > maxSide)) {
+ double k = (double)maxSide / std::max(fw, fh);
+ IWICBitmapScaler* sc = nullptr;
+ if (SUCCEEDED(wic->CreateBitmapScaler(&sc)) &&
+ SUCCEEDED(sc->Initialize(src, std::max(1u, (UINT)(fw * k)), std::max(1u, (UINT)(fh * k)), WICBitmapInterpolationModeFant))) {
+ src->Release(); src = sc;
+ } else if (sc) sc->Release();
+ }
+ WICBitmapTransformOptions tr = WICBitmapTransformRotate0;
+ switch (orient) {
+ case 2: tr = WICBitmapTransformFlipHorizontal; break;
+ case 3: tr = WICBitmapTransformRotate180; break;
+ case 4: tr = WICBitmapTransformFlipVertical; break;
+ case 5: tr = (WICBitmapTransformOptions)(WICBitmapTransformRotate90 | WICBitmapTransformFlipHorizontal); break;
+ case 6: tr = WICBitmapTransformRotate90; break;
+ case 7: tr = (WICBitmapTransformOptions)(WICBitmapTransformRotate270 | WICBitmapTransformFlipHorizontal); break;
+ case 8: tr = WICBitmapTransformRotate270; break;
+ }
+ if (tr != WICBitmapTransformRotate0) {
+ IWICBitmapFlipRotator* rot = nullptr;
+ if (SUCCEEDED(wic->CreateBitmapFlipRotator(&rot)) && SUCCEEDED(rot->Initialize(src, tr))) { src->Release(); src = rot; }
+ else if (rot) rot->Release();
+ }
+ IWICFormatConverter* cv = nullptr;
+ if (SUCCEEDED(wic->CreateFormatConverter(&cv)) &&
+ SUCCEEDED(cv->Initialize(src, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeCustom))) {
+ cv->GetSize(&w, &h);
+ if (w && h && (size_t)w * h <= 80'000'000) {
+ bgra.resize((size_t)w * h * 4);
+ ok = SUCCEEDED(cv->CopyPixels(nullptr, w * 4, (UINT)bgra.size(), bgra.data()));
+ }
+ }
+ if (cv) cv->Release();
+ src->Release();
+ fr->Release();
+ }
+ dec->Release();
+ }
+ wic->Release();
+ if (!ok) bgra.clear();
+ return ok;
+}
+
+// Pasta dos ícones do Sequoia (icones\sequoia, ao lado de bin\): uso pessoal, ver icones\LEIA-ME.txt.
+std::wstring ui::PackIcon(const std::wstring& name) {
+ std::wstring root = shell::dir.substr(0, shell::dir.find_last_of(L'\\')) + L"\\icones";
+ if (liquid::Leopard()) { // Leopard: os ícones do 10.5 (icones\leopard, tools\icones-leopard.py) vencem até o extra
+ std::wstring g = root + L"\\leopard\\" + name + L".png"; // (lá estão as versões Aqua dos ícones do extra)
+ if (GetFileAttributesW(g.c_str()) != INVALID_FILE_ATTRIBUTES) return g;
+ }
+ std::wstring extra = root + L"\\extra\\" + name + L".png"; // escolhidos pelo usuário vencem
+ if (GetFileAttributesW(extra.c_str()) != INVALID_FILE_ATTRIBUTES) return extra;
+ if (liquid::Golden()) { // Golden Gate: os ícones do macOS 27 (icones\goldengate, tools\icones-goldengate.py)
+ std::wstring g = root + L"\\goldengate\\" + name + L".png";
+ if (GetFileAttributesW(g.c_str()) != INVALID_FILE_ATTRIBUTES) return g;
+ }
+ if (liquid::On()) { // Tema Tahoe: icones\tahoe antes do pacote do Sequoia
+ std::wstring t = root + L"\\tahoe\\" + name + L".png";
+ if (GetFileAttributesW(t.c_str()) != INVALID_FILE_ATTRIBUTES) return t;
+ }
+ std::wstring dir = shell::Setting(L"icones", L"");
+ if (dir.empty()) dir = root + L"\\sequoia";
+ std::wstring p = dir + L"\\" + name + L".png";
+ return GetFileAttributesW(p.c_str()) != INVALID_FILE_ATTRIBUTES ? p : L"";
+}
+
+// Corta a margem transparente e centraliza num quadrado: todos os ícones ocupam o mesmo espaço,
+// como no Mac (cada ícone do Windows vem com uma margem diferente).
+void ui::TrimToSquare(UINT& w, UINT& h, std::vector<BYTE>& bgra) {
+ int x0 = (int)w, y0 = (int)h, x1 = -1, y1 = -1;
+ for (int y = 0; y < (int)h; y++)
+ for (int x = 0; x < (int)w; x++)
+ if (bgra[((size_t)y * w + x) * 4 + 3] > 24) { x0 = std::min(x0, x); y0 = std::min(y0, y); x1 = std::max(x1, x); y1 = std::max(y1, y); }
+ if (x1 < 0) return;
+ int cw = x1 - x0 + 1, ch = y1 - y0 + 1, s = std::max(cw, ch);
+ if (s >= (int)w - 1 && s >= (int)h - 1) return; // já sem margem
+ std::vector<BYTE> out((size_t)s * s * 4, 0);
+ int ox = (s - cw) / 2, oy = (s - ch) / 2;
+ for (int y = 0; y < ch; y++)
+ memcpy(&out[((size_t)(y + oy) * s + ox) * 4], &bgra[((size_t)(y + y0) * w + x0) * 4], (size_t)cw * 4);
+ bgra.swap(out);
+ w = h = (UINT)s;
+}
+
+// Pasta azul (as mesmas cores medidas do Arquivos), com símbolo opcional.
+void ui::DrawFolder(ID2D1RenderTarget* rt, D2D1_RECT_F box, wchar_t glyph) {
+ float S = box.right - box.left, x0 = box.left, y0 = box.top;
+ auto R = [&](float a, float b, float c, float d) { return D2D1::RectF(x0 + a * S, y0 + b * S, x0 + c * S, y0 + d * S); };
+ float rad = 0.06f * S;
+ ID2D1SolidColorBrush* br = nullptr;
+ rt->CreateSolidColorBrush(D2D1::ColorF(0.06f, 0.49f, 0.78f), &br);
+ rt->FillRoundedRectangle(D2D1::RoundedRect(R(0.03f, 0.08f, 0.38f, 0.20f), 0.035f * S, 0.035f * S), br);
+ rt->FillRoundedRectangle(D2D1::RoundedRect(R(0.03f, 0.13f, 0.97f, 0.90f), rad, rad), br);
+ auto front = R(0.03f, 0.19f, 0.97f, 0.90f);
+ ID2D1GradientStopCollection* stops = nullptr;
+ D2D1_GRADIENT_STOP gs[2] = { { 0, D2D1::ColorF(0.32f, 0.78f, 0.98f) }, { 1, D2D1::ColorF(0.14f, 0.63f, 0.87f) } };
+ rt->CreateGradientStopCollection(gs, 2, &stops);
+ ID2D1LinearGradientBrush* lg = nullptr;
+ rt->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, front.top }, { 0, front.bottom }), stops, &lg);
+ rt->FillRoundedRectangle(D2D1::RoundedRect(front, rad, rad), lg);
+ lg->Release(); stops->Release();
+ br->SetColor(D2D1::ColorF(1, 1, 1, 0.28f));
+ rt->DrawLine({ front.left + rad, front.top + 0.6f }, { front.right - rad, front.top + 0.6f }, br, 1.0f);
+ if (glyph) {
+ IDWriteTextFormat* tf = Format(std::round(0.40f * S), DWRITE_FONT_WEIGHT_NORMAL, true, DWRITE_TEXT_ALIGNMENT_CENTER);
+ auto er = R(0.03f, 0.25f, 0.97f, 0.86f);
+ br->SetColor(D2D1::ColorF(0.05f, 0.42f, 0.72f, 0.9f));
+ rt->DrawTextW(&glyph, 1, tf, er, br);
+ tf->Release();
+ }
+ br->Release();
+}
+
+// Lixeira: cesto de tela translúcido (vazio) ou com papéis (cheio).
+void ui::DrawTrash(ID2D1RenderTarget* rt, D2D1_RECT_F box, bool full) {
+ float S = box.right - box.left, cx = (box.left + box.right) / 2;
+ float top = box.top + 0.14f * S, bottom = box.bottom - 0.04f * S;
+ float wt = 0.62f * S, wb = 0.50f * S;
+ ID2D1Factory* f = nullptr; rt->GetFactory(&f);
+ ID2D1PathGeometry* g = nullptr; f->CreatePathGeometry(&g);
+ ID2D1GeometrySink* sk = nullptr; g->Open(&sk);
+ sk->BeginFigure({ cx - wt / 2, top }, D2D1_FIGURE_BEGIN_FILLED);
+ sk->AddLine({ cx + wt / 2, top });
+ sk->AddLine({ cx + wb / 2, bottom });
+ sk->AddLine({ cx - wb / 2, bottom });
+ sk->EndFigure(D2D1_FIGURE_END_CLOSED);
+ sk->Close(); sk->Release();
+ ID2D1SolidColorBrush* br = nullptr;
+ rt->CreateSolidColorBrush(D2D1::ColorF(0.86f, 0.88f, 0.90f, 0.55f), &br);
+ if (full) { // papéis amassados aparecendo por cima
+ br->SetColor(D2D1::ColorF(0.97f, 0.97f, 0.96f, 1));
+ rt->FillEllipse(D2D1::Ellipse({ cx - 0.10f * S, top + 0.02f * S }, 0.15f * S, 0.10f * S), br);
+ br->SetColor(D2D1::ColorF(0.90f, 0.92f, 0.95f, 1));
+ rt->FillEllipse(D2D1::Ellipse({ cx + 0.10f * S, top + 0.04f * S }, 0.14f * S, 0.09f * S), br);
+ br->SetColor(D2D1::ColorF(0.86f, 0.88f, 0.90f, 0.55f));
+ }
+ rt->FillGeometry(g, br);
+ br->SetColor(D2D1::ColorF(0.55f, 0.58f, 0.62f, 0.85f)); // tela: linhas verticais
+ for (int k = 1; k < 7; k++) {
+ float t = k / 7.f;
+ rt->DrawLine({ cx - wt / 2 + wt * t, top + 0.06f * S }, { cx - wb / 2 + wb * t, bottom - 0.02f * S }, br, std::max(0.8f, 0.012f * S));
+ }
+ rt->DrawGeometry(g, br, std::max(1.f, 0.02f * S));
+ br->SetColor(D2D1::ColorF(0.78f, 0.80f, 0.83f, 1)); // aro
+ rt->FillRoundedRectangle(D2D1::RoundedRect(D2D1::RectF(cx - wt / 2 - 0.03f * S, top - 0.035f * S, cx + wt / 2 + 0.03f * S, top + 0.035f * S), 0.03f * S, 0.03f * S), br);
+ br->Release(); g->Release(); f->Release();
+}
+
+// Reduz uma imagem BGRA pré-multiplicada para caber em maxSide × maxSide, pela média da área coberta
+// (sem serrilhado). Os ícones guardados em memória ficam do tamanho em que são desenhados.
+void ui::Downscale(UINT& w, UINT& h, std::vector<BYTE>& px, UINT maxSide) {
+ if (!w || !h || (w <= maxSide && h <= maxSide) || px.size() < (size_t)w * h * 4) return;
+ double k = (double)maxSide / std::max(w, h);
+ UINT nw = std::max<UINT>(1, (UINT)std::lround(w * k)), nh = std::max<UINT>(1, (UINT)std::lround(h * k));
+ double sx = (double)w / nw, sy = (double)h / nh;
+ std::vector<BYTE> out((size_t)nw * nh * 4);
+ for (UINT y = 0; y < nh; y++) {
+ double y0 = y * sy, y1 = y0 + sy;
+ for (UINT x = 0; x < nw; x++) {
+ double x0 = x * sx, x1 = x0 + sx, acc[4] = {}, area = 0;
+ for (UINT yy = (UINT)y0; yy < h && yy < y1; yy++) {
+ double wy = std::min<double>(yy + 1, y1) - std::max<double>(yy, y0);
+ for (UINT xx = (UINT)x0; xx < w && xx < x1; xx++) {
+ double wgt = wy * (std::min<double>(xx + 1, x1) - std::max<double>(xx, x0));
+ const BYTE* p = &px[((size_t)yy * w + xx) * 4];
+ for (int c = 0; c < 4; c++) acc[c] += p[c] * wgt;
+ area += wgt;
+ }
+ }
+ BYTE* o = &out[((size_t)y * nw + x) * 4];
+ for (int c = 0; c < 4; c++) o[c] = (BYTE)std::clamp(std::lround(acc[c] / area), 0L, 255L);
+ }
+ }
+ px.swap(out);
+ w = nw; h = nh;
+}
diff --git a/src/shell/voz.cpp b/src/shell/voz.cpp
new file mode 100644
index 0000000..f071ba8
--- /dev/null
+++ b/src/shell/voz.cpp
@@ -0,0 +1,102 @@
+// Ditado (o microfone da Siri e do Spotlight, pedido do usuário em 23/11/2026): o reconhecimento de fala do próprio
+// Windows (Windows.Media.SpeechRecognition), numa thread. Uma frase por vez: o texto parcial chega enquanto a pessoa fala
+// (HypothesisGenerated) e o final quando ela para (1,2 s de silêncio). Idioma: o do WacOS, se o Windows tiver; senão o de
+// fala do Windows. Precisa do "Reconhecimento de fala online" ligado (Privacidade > Fala); desligado, avisa (V_PRIVACIDADE).
+// Mensagens para a janela que pediu: wParam = voz::Tipo, lParam = new std::wstring (quem recebe apaga).
+#include "shell.h"
+#include <winrt/Windows.Foundation.h>
+#include <winrt/Windows.Foundation.Collections.h>
+#include <winrt/Windows.Globalization.h>
+#include <winrt/Windows.Media.SpeechRecognition.h>
+#include <thread>
+#include <mutex>
+#include <atomic>
+#pragma comment(lib, "windowsapp.lib")
+
+namespace sr = winrt::Windows::Media::SpeechRecognition;
+
+namespace {
+std::mutex g_mx;
+winrt::Windows::Foundation::IAsyncOperation<sr::SpeechRecognitionResult> g_op{ nullptr };
+std::atomic<int> g_gen{ 0 };
+std::atomic<bool> g_ativa{ false };
+
+void Manda(HWND to, UINT msg, int gen, voz::Tipo t, const std::wstring& s) {
+ if (gen != g_gen) return; // de uma escuta que já foi parada
+ if (!PostMessageW(to, msg, (WPARAM)t, (LPARAM)new std::wstring(s))) { /* janela sumiu: o texto se perde */ }
+}
+
+// o idioma do WacOS entre os que o Windows reconhece (pt-BR, en-US...); vazio = o de fala do Windows
+std::wstring IdiomaDeFala() {
+ std::wstring codigo = idioma::kInfo[idioma::Current()].code; // "pt", "en", "es"...
+ try {
+ for (auto const& l : sr::SpeechRecognizer::SupportedTopicLanguages()) {
+ std::wstring tag = l.LanguageTag().c_str();
+ if (_wcsnicmp(tag.c_str(), codigo.c_str(), codigo.size()) == 0) return tag;
+ }
+ } catch (...) {}
+ return L"";
+}
+} // namespace
+
+bool voz::Ouvindo() { return g_ativa; }
+
+void voz::Parar() {
+ g_gen++;
+ std::lock_guard<std::mutex> lk(g_mx);
+ if (g_op) { try { g_op.Cancel(); } catch (...) {} }
+ g_ativa = false;
+}
+
+void voz::Ouvir(HWND to, UINT msg) {
+ Parar();
+ int gen = ++g_gen;
+ g_ativa = true;
+ std::thread([to, msg, gen] {
+ winrt::init_apartment(winrt::apartment_type::multi_threaded);
+ try {
+ std::wstring tag = IdiomaDeFala();
+ sr::SpeechRecognizer rec = tag.empty() ? sr::SpeechRecognizer() : sr::SpeechRecognizer(winrt::Windows::Globalization::Language(tag));
+ rec.Timeouts().InitialSilenceTimeout(std::chrono::seconds(6));
+ rec.Timeouts().EndSilenceTimeout(std::chrono::milliseconds(1200));
+ rec.HypothesisGenerated([to, msg, gen](auto const&, sr::SpeechRecognitionHypothesisGeneratedEventArgs const& a) {
+ Manda(to, msg, gen, voz::V_PARCIAL, a.Hypothesis().Text().c_str());
+ });
+ auto c = rec.CompileConstraintsAsync().get();
+ if (c.Status() != sr::SpeechRecognitionResultStatus::Success) {
+ Log(L"voz: não preparou o reconhecimento (%d, %ls)", (int)c.Status(), tag.c_str());
+ Manda(to, msg, gen, voz::V_ERRO, Tr(L"O reconhecimento de fala do Windows não está disponível neste idioma."));
+ } else {
+ Log(L"voz: ouvindo (%ls)", tag.empty() ? L"idioma de fala do Windows" : tag.c_str());
+ {
+ std::lock_guard<std::mutex> lk(g_mx);
+ if (gen != g_gen) { g_ativa = false; return; }
+ g_op = rec.RecognizeAsync();
+ }
+ auto r = g_op.get();
+ std::wstring t = r.Text().c_str();
+ Log(L"voz: %zu letras (estado %d)", t.size(), (int)r.Status());
+ Manda(to, msg, gen, voz::V_FINAL, t);
+ }
+ } catch (winrt::hresult_canceled const&) {
+ // parada pela pessoa (clicou no microfone de novo, fechou o painel)
+ } catch (winrt::hresult_error const& e) {
+ unsigned hr = (unsigned)e.code();
+ Log(L"voz: erro 0x%08X %ls", hr, e.message().c_str());
+ if (hr == 0x80045509) { // SPERR_SPEECH_PRIVACY_POLICY_NOT_ACCEPTED: o reconhecimento online está desligado
+ // a pessoa clicou no microfone: abre a página do Windows onde se liga (Privacidade > Fala)
+ if (gen == g_gen) shell::Abrir(L"open", L"ms-settings:privacy-speech", nullptr, nullptr, SW_SHOWNORMAL);
+ Manda(to, msg, gen, voz::V_PRIVACIDADE, Tr(L"Para ditar, ligue o \"Reconhecimento de fala online\" em Configurações do Windows > Privacidade > Fala."));
+ } else if (hr == 0x80070005) // sem permissão do microfone
+ Manda(to, msg, gen, voz::V_ERRO, Tr(L"O Windows não deixou usar o microfone. Libere em Configurações > Privacidade > Microfone."));
+ else
+ Manda(to, msg, gen, voz::V_ERRO, Tr(L"Não deu para ouvir agora. Confira se há um microfone ligado."));
+ } catch (...) {
+ Manda(to, msg, gen, voz::V_ERRO, Tr(L"Não deu para ouvir agora. Confira se há um microfone ligado."));
+ }
+ {
+ std::lock_guard<std::mutex> lk(g_mx);
+ if (gen == g_gen) { g_op = nullptr; g_ativa = false; }
+ }
+ }).detach();
+}