A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
Dynamic Island: lyrics for KuGou, and a working progress bar (#342)
Eternity0706287e20b329e6cd
diff --git a/src/shell/ilha.cpp b/src/shell/ilha.cppindex 3007ebd..ee22ca5 100644--- a/src/shell/ilha.cpp+++ b/src/shell/ilha.cpp@@ -122,7 +122,7 @@ Spr g_w, g_h, g_rt, g_rb, g_a; // largura, altura, raio de cima (orelha no notcbool g_running;RECT g_rgn{};IDWriteTextFormat *g_tfTitle, *g_tfSub, *g_tfSmall, *g_tfSmallR, *g_tfSmallC, *g_tfWing, *g_tfWingR, *g_tfBig, *g_tfVal,- *g_tfIcon, *g_tfIconS, *g_tfIconL, *g_tfChip;+ *g_tfIcon, *g_tfIconS, *g_tfIconL, *g_tfChip, *g_tfSubC;// ---- estadosbool g_openOn, g_hoverIn, g_pauseHold, g_dragIn;@@ -186,7 +186,7 @@ struct Stats { std::deque<float> cpu, mem, net; float cpuNow = 0, memNow = 0; doULONGLONG g_lastIdle, g_lastKern, g_lastUser; double g_lastNetAt;// ---- interação-enum HitId { H_NONE, H_TAB, H_GEAR, H_PREV, H_PLAY, H_NEXT, H_SHUF, H_OUT, H_SEEK, H_ART, H_PRESET, H_TPAUSE, H_TSTOP, H_TPLUS,+enum HitId { H_NONE, H_TAB, H_GEAR, H_PREV, H_PLAY, H_NEXT, H_LYR, H_OUT, H_SEEK, H_ART, H_PRESET, H_TPAUSE, H_TSTOP, H_TPLUS,H_CLIP, H_CLIPCLR, H_SHELF, H_SHELFCLR, H_TMINUS };struct Hit { HitId id; D2D1_RECT_F r; int arg = 0; };std::vector<Hit> g_hits;@@ -338,6 +338,8 @@ void MediaThread() {std::wstring lastKey;int artRetry = 0; // capa atrasada: quantas vezes já esperou a da faixa novabool retrySoon = false; // acorda em instantes para tentar a capa de novo+ // #342: relogio proprio da faixa, para apps que nao informam duracao nem posicao (KuGou)+ std::wstring estKey; double estPos = 0, estAt = anim::Now(); bool estPlaying = false;for (;;) {bool rebind; std::vector<Cmd> cmds;{@@ -392,6 +394,8 @@ void MediaThread() {out.title = p.Title().c_str();out.artist = p.Artist().c_str();if (out.title.empty()) out.has = false; // sessão sem nada (aba do navegador parada)+ std::wstring key = out.title + L"\x1f" + out.artist + L"\x1f" + out.aumid;+ bool newTrack = key != lastKey;auto tl = ses.GetTimelineProperties();if (!tl) throw winrt::hresult_error(E_POINTER);double start = tl.StartTime().count() / 1e7, end = tl.EndTime().count() / 1e7, pos = tl.Position().count() / 1e7;@@ -402,10 +406,24 @@ void MediaThread() {double age = std::chrono::duration<double>(winrt::clock::now() - tl.LastUpdatedTime()).count();if (age > 0 && age < 6 * 3600) pos += age;}- out.pos = std::clamp(pos, 0.0, std::max(out.len, 0.0));- out.at = anim::Now();- std::wstring key = out.title + L"\x1f" + out.artist + L"\x1f" + out.aumid;- bool newTrack = key != lastKey;+ double agora = anim::Now();+ if (out.len <= 1.0) {+ // #342: o KuGou manda o TimelineProperties zerado (nem duracao, nem posicao).+ // quando o app nao informa nada o relogio da faixa passa a ser o nosso: conta o+ // tempo desde que ela comecou e zera ao trocar de faixa; apps que informam o+ // tempo nunca entram aqui+ if (key != estKey) { estKey = key; estPos = 0; estAt = agora; estPlaying = false; }+ if (estPlaying && out.playing) {+ double d = (agora - estAt) / 1000.0;+ if (d > 0 && d < 6 * 3600) estPos += d;+ }+ estAt = agora; estPlaying = out.playing;+ pos = estPos;+ } else {+ estKey.clear(); estPlaying = false;+ }+ out.pos = pos < 0 ? 0.0 : (out.len > 1.0 ? std::min(pos, out.len) : pos);+ out.at = agora;bool artEmpty; uint64_t curHash;{ std::lock_guard<std::mutex> l(g_mmx); artEmpty = g_md.art.empty(); curHash = g_artHash; }bool needArt = newTrack || artEmpty;@@ -954,6 +972,12 @@ struct Size { float w, h, rt, rb; };// as asas mostravam (capa, barrinhas, tempo, volume) cabe dentro do corpo; a ilha cresce só uns pontos (antes +80 com// música/timer e +132 com o volume no notch; na pílula, de 112 para 232/244).const float WING_ACT = 12, WING_HUD = 18;++// #342: a letra da música (letra.cpp). O botão dela fica no lugar do antigo "aleatório":+// vários apps de música daqui (KuGou, QQ Music) não deixam trocar o modo de reprodução por fora.+bool g_letraOn = true;+std::wstring g_letraT, g_letraA; // a faixa cuja letra já foi pedida+float LetraH() { return (g_letraOn && g_m.has && letra::Tem()) ? 24.f : 0.f; }Size SizeOf(Mode m) {float priv = g_priv ? 16.f : 0.f; // ponto verde/laranja na ponta direitaif (Notch()) {@@ -964,7 +988,7 @@ Size SizeOf(Mode m) {case M_MEDIA: case M_TIMER: return { NOTCH_W + 2 * WING_ACT + priv, H, 0, 6 };case M_HUD: return { NOTCH_W + 2 * WING_HUD, H, 0, 6 };case M_PEEK: return { 320, H + 50, 0, 10 };- case M_OPEN: return { OPEN_W, H + BODY_H, 0, 10 };+ case M_OPEN: return { OPEN_W, H + BODY_H + LetraH(), 0, 10 };default: return { NOTCH_W * 0.7f, H * 0.5f, 0, 4 };}}@@ -973,7 +997,7 @@ Size SizeOf(Mode m) {case M_MEDIA: case M_TIMER: return { NOTCH_W + 2 * WING_ACT + priv, H, 6, 9 };case M_HUD: return { NOTCH_W + 2 * WING_HUD, H, 6, 9 };case M_PEEK: return { 320 + 2 * 12, H + 50, 12, 20 };- case M_OPEN: return { OPEN_W + 2 * 19, H + BODY_H, 19, 24 }; // largura com as orelhas (Atoll: 19 em cima, 24 embaixo)+ case M_OPEN: return { OPEN_W + 2 * 19, H + BODY_H + LetraH(), 19, 24 }; // largura com as orelhas (Atoll: 19 em cima, 24 embaixo)default: return { NOTCH_W * 0.7f, H * 0.5f, 4, 6 };}}@@ -984,7 +1008,7 @@ Size SizeOf(Mode m) {case M_PEEK: return { 320, 54, 20, 20 };case M_OPEN: { // cantos do cartão por tema: Golden Gate maiores (macOS 27), Leopard o HUD do 10.5float r = liquid::Golden() ? 30.f : liquid::Leopard() ? 12.f : 24.f;- return { OPEN_W, 28 + BODY_H, r, r };+ return { OPEN_W, 28 + BODY_H + LetraH(), r, r };}default: return { 90, 14, 7, 7 };}@@ -1308,24 +1332,36 @@ void DrawHome(ID2D1DeviceContext* dc, ID2D1SolidColorBrush* br, D2D1_RECT_F b, fif (has) Text(dc, br, g_m.artist, g_tfSub, D2D1::RectF(art.right + 9, y0 + 20, R - 24, y0 + 35), GRAY);if (has) DrawBars(dc, br, D2D1::RectF(R - 16, y0 + 6, R, y0 + 18));float ty = y0 + 54;- double pos = 0, len = g_m.len;+ // #342: apps como o KuGou nunca informam o tempo da faixa (TimelineProperties zerado):+ // a duração que a letra conhece entra no lugar, e a barra de progresso volta a andar+ double len = g_m.len > 1 ? g_m.len : letra::Duracao();+ double pos = 0;bool tl = has && len > 1;- if (tl) pos = std::clamp(g_m.pos + (g_m.playing ? (anim::Now() - g_m.at) / 1000.0 : 0), 0.0, len);+ if (has) pos = std::clamp(g_m.pos + (g_m.playing ? (anim::Now() - g_m.at) / 1000.0 : 0), 0.0, len > 0 ? len : 0.0);D2D1_RECT_F tr = D2D1::RectF(L + 36, ty - 1.5f, R - 38, ty + 1.5f);Text(dc, br, tl ? ClockFloor(pos) : L"", g_tfSmall, D2D1::RectF(L, ty - 7, tr.left - 4, ty + 7), WHITE);Text(dc, br, tl ? L"-" + ClockFloor(len - pos) : L"", g_tfSmallR, D2D1::RectF(tr.right + 4, ty - 7, R, ty + 7), g_theme == TH_LEOPARD ? Accent() : g_m.tint);DrawProgressT(dc, br, Hover(H_SEEK) ? D2D1::RectF(tr.left, ty - 2.5f, tr.right, ty + 2.5f) : tr, tl ? (float)(pos / len) : 0);if (tl) AddHit(H_SEEK, D2D1::RectF(tr.left, ty - 7, tr.right, ty + 7));float cy = y0 + 82, cx = (b.left + b.right) / 2;+ // #342: a linha da letra embaixo dos botões (na introdução já mostra a primeira frase)+ if (LetraH() > 0) {+ D2D1_COLOR_F lc = g_theme == TH_LEOPARD ? Accent() : WHITE;+ Text(dc, br, letra::Texto(pos), g_tfSubC ? g_tfSubC : g_tfSub, D2D1::RectF(L + 4, cy + 9, R - 4, cy + 29), D2D1::ColorF(lc.r, lc.g, lc.b, 0.86f));+ }D2D1_COLOR_F ink = has ? WHITE : GRAY2;- struct B { HitId id; float x; } bs[] = { { H_SHUF, cx - 100 }, { H_PREV, cx - 50 }, { H_PLAY, cx }, { H_NEXT, cx + 50 }, { H_OUT, cx + 100 } };+ struct B { HitId id; float x; } bs[] = { { H_LYR, cx - 100 }, { H_PREV, cx - 50 }, { H_PLAY, cx }, { H_NEXT, cx + 50 }, { H_OUT, cx + 100 } };for (auto& bt : bs) {float s = bt.id == H_PLAY ? 32.f : 28.f;D2D1_RECT_F r = Around(bt.x, cy, s, s);bool live = has || bt.id == H_OUT;if (live && (Hover(bt.id) || g_pressHit == bt.id)) Chip(dc, br, r, s / 2, g_pressHit == bt.id ? 2.f : 1.f);switch (bt.id) {- case H_SHUF: Glyph(dc, br, 0xE8B1, g_tfIconS, r, has && g_m.shuffle ? (g_theme == TH_SEQUOIA ? g_m.tint : Accent()) : has && g_m.canShuffle ? WHITE : GRAY2); break;+ case H_LYR: { // #342: acesa quando a letra desta faixa está carregada+ D2D1_COLOR_F c = has && g_letraOn && letra::Tem() ? (g_theme == TH_SEQUOIA ? g_m.tint : Accent()) : has ? WHITE : GRAY2;+ if (!simbolo::Draw(dc, L"text.alignleft", r, br)) Glyph(dc, br, 0xE8D2, g_tfIconS, r, c);+ break;+ }case H_OUT: Glyph(dc, br, 0xE7F4, g_tfIconS, r, WHITE); break; // a saída de som (o menu Som)case H_PLAY:if (g_m.playing) Sym(dc, br, L"pause.fill", Around(bt.x, cy, 13, 17), ink);@@ -2019,7 +2055,7 @@ void ClickHit(const Hit& h, D2D1_POINT_2F p) {case H_PLAY: g_m.playing = !g_m.playing; MediaCmd(1); break; // já mostra o novo estado; o evento confirmacase H_NEXT: MediaCmd(2); break;case H_PREV: MediaCmd(3); break;- case H_SHUF: if (g_m.canShuffle) { g_m.shuffle = !g_m.shuffle; MediaCmd(4, g_m.shuffle); } break;+ case H_LYR: ilha::LetraToggle(); break; // #342: liga/desliga a letra na ilha e na barracase H_OUT: {Close();RECT r;@@ -2075,6 +2111,11 @@ LRESULT CALLBACK Proc(HWND h, UINT m, WPARAM w, LPARAM l) {KillTimer(h, TM_GONE);g_m = g_md;}+ if (g_m.title != g_letraT || g_m.artist != g_letraA) { // #342: faixa nova, letra nova+ g_letraT = g_m.title;+ g_letraA = g_m.artist;+ letra::Pedir(g_m.title, g_m.artist, g_m.len > 1.0 ? g_m.len : 0.0);+ }if (was && !g_m.playing && g_m.has) { g_pauseHold = true; SetTimer(h, TM_PAUSE, 5000, nullptr); }if (g_m.playing) { g_pauseHold = false; KillTimer(h, TM_PAUSE); }if (!g_m.has) g_pauseHold = false;@@ -2308,10 +2349,11 @@ IDWriteTextFormat* Fmt(float size, DWRITE_FONT_WEIGHT wt, DWRITE_TEXT_ALIGNMENT// fontes nas proporções do Atoll (título 12,5, artista 11, tempo 10,5); recriadas ao trocar de tema (Leopard: Lucida)void MakeFonts() {- for (auto** tf : { &g_tfTitle, &g_tfSub, &g_tfSmall, &g_tfSmallR, &g_tfSmallC, &g_tfWing, &g_tfWingR, &g_tfBig, &g_tfVal, &g_tfChip, &g_tfIcon, &g_tfIconS, &g_tfIconL })+ for (auto** tf : { &g_tfTitle, &g_tfSub, &g_tfSmall, &g_tfSmallR, &g_tfSmallC, &g_tfWing, &g_tfWingR, &g_tfBig, &g_tfVal, &g_tfChip, &g_tfIcon, &g_tfIconS, &g_tfIconL, &g_tfSubC })if (*tf) { (*tf)->Release(); *tf = nullptr; }g_tfTitle = Fmt(12.5f, DWRITE_FONT_WEIGHT_SEMI_BOLD);g_tfSub = Fmt(11, DWRITE_FONT_WEIGHT_NORMAL);+ g_tfSubC = Fmt(11, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_CENTER); // #342: a letra centrada, no mesmo tipo e tamanho do resto do painelg_tfSmall = Fmt(10.5f, DWRITE_FONT_WEIGHT_NORMAL);g_tfSmallR = Fmt(10.5f, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_TRAILING);g_tfSmallC = Fmt(10.5f, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_CENTER);@@ -2377,6 +2419,7 @@ void ilha::Reload() {g_volOn = shell::Setting(L"ilha_volume", L"1") != L"0";g_copyOn = shell::Setting(L"ilha_copiado", L"1") != L"0";g_hoverOpen = shell::Setting(L"ilha_passar", L"1") != L"0";+ g_letraOn = shell::Setting(L"ilha_letra", L"1") != L"0";bool wasGlass = UseGlass();g_glassOn = shell::Setting(L"ilha_vidro", L"0") == L"1";std::wstring gc = shell::Setting(L"ilha_cor", L"auto");@@ -2535,3 +2578,21 @@ bool ilha::On() { return g_on; }// microfone/câmera em uso (1 microfone, 2 câmera) para a barra de menus; a 1ª chamada começa a vigiar o registroint ilha::Privacidade() { StartPrivacy(); return g_priv; }++// #342: a letra — o botão da ilha e o item da barra de menus usam estes três+bool ilha::LetraOn() { return g_letraOn; }++void ilha::LetraToggle() {+ g_letraOn = !g_letraOn;+ shell::SetSetting(L"ilha_letra", g_letraOn ? L"1" : L"0");+ Update();+ menubar::Update(); // a barra de menus mostra ou esconde a letra na hora+ if (!g_running && g_shown) Paint();+}++std::wstring ilha::LetraTexto() {+ if (!g_m.has || !g_letraOn || !letra::Tem()) return std::wstring();+ double len = g_m.len > 1 ? g_m.len : letra::Duracao();+ double pos = std::clamp(g_m.pos + (g_m.playing ? (anim::Now() - g_m.at) / 1000.0 : 0), 0.0, len > 0 ? len : 0.0);+ return letra::Texto(pos);+}diff --git a/src/shell/letra.cpp b/src/shell/letra.cppnew file mode 100644index 0000000..0af7884--- /dev/null+++ b/src/shell/letra.cpp@@ -0,0 +1,615 @@+// letra.cpp: a letra da música na Ilha Dinâmica e na barra de menus (issue #342).+// O Windows (SMTC) manda o título e o artista, mas quase nenhum app manda a letra —+// e o KuGou Music nem manda o tempo da música (TimelineProperties vem todo zerado).+// Então aqui: 1) procura um .lrc nosso (pasta de letras ou ao lado do arquivo);+// 2) senão busca na API pública do NetEase Cloud Music, a mesma que+// vários players abertos usam para achar a letra de quem toca;+// 3) guarda em %APPDATA%\Shell\letras para abrir sem internet.+// Nada aqui desenha: a thread só acorda quando a música muda.+#include "shell.h"+#include <shellapi.h>+#include <objbase.h>+#include <shlobj.h>+#include <winhttp.h>+#include <algorithm>+#include <cmath>+#include <condition_variable>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <fstream>+#include <iterator>+#include <mutex>+#include <string>+#include <thread>+#include <vector>++#pragma comment(lib, "winhttp.lib")++namespace {++struct Linha { double t = 0; std::wstring s; };++std::mutex g_mx;+std::condition_variable g_cv;+bool g_acordar = false, g_parar = false, g_rodando = false;+std::wstring g_pedT, g_pedA; // o que a Ilha pediu (título e artista)+double g_pedDur = 0; // a duração que a Ilha conhece (0 = não sabe)+std::wstring g_cargaT, g_cargaA; // o que já está valendo ("" = nada)+std::vector<Linha> g_linhas;+double g_dur = 0; // duração da música (para a barra de progresso)++const std::wstring& Pasta() {+ static const std::wstring c = [] {+ std::wstring o;+ PWSTR p = nullptr;+ if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) {+ o = std::wstring(p) + L"\\Shell";+ CoTaskMemFree(p);+ }+ return o;+ }();+ return c;+}++std::wstring Minus(const std::wstring& s) {+ std::wstring o = s;+ for (auto& c : o) if (c >= L'A' && c <= L'Z') c = (wchar_t)(c - L'A' + L'a');+ return o;+}++bool Contem(const std::wstring& onde, const std::wstring& o) {+ if (o.empty()) return false;+ return Minus(onde).find(Minus(o)) != std::wstring::npos;+}++// "如愿 (电影《我和我的父辈》主题曲)" -> "如愿": o parêntese atrapalha a busca+std::wstring Simples(const std::wstring& s) {+ std::wstring o;+ int dentro = 0;+ for (wchar_t c : s) {+ if (c == L'(' || c == L'[' || c == L'(') dentro++;+ else if (c == L')' || c == L']' || c == L')') { if (dentro) dentro--; }+ else if (!dentro && c != L' ' && c != L'\t') o.push_back(c);+ }+ return Minus(o);+}++std::string U(const std::wstring& s) {+ if (s.empty()) return std::string();+ int n = WideCharToMultiByte(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0, nullptr, nullptr);+ std::string o((size_t)n, 0);+ WideCharToMultiByte(CP_UTF8, 0, s.data(), (int)s.size(), &o[0], n, nullptr, nullptr);+ return o;+}++std::wstring W(const std::string& s, UINT cp = CP_UTF8) {+ if (s.empty()) return std::wstring();+ int n = MultiByteToWideChar(cp, 0, s.data(), (int)s.size(), nullptr, 0);+ if (n <= 0) return std::wstring();+ std::wstring o((size_t)n, 0);+ MultiByteToWideChar(cp, 0, s.data(), (int)s.size(), &o[0], n);+ return o;+}++// arquivo .lrc antigo costuma estar em GBK: se o UTF-8 der lixo, tenta o 936+std::wstring Decodifica(const std::string& b) {+ std::wstring o = W(b);+ size_t ruins = 0;+ for (wchar_t c : o) if (c == 0xFFFD) ruins++;+ if (!o.empty() && ruins * 8 > o.size()) {+ std::wstring g = W(b, 936);+ if (!g.empty()) return g;+ }+ return o;+}++bool LerArquivo(const std::wstring& p, std::wstring& out) {+ std::ifstream f(p.c_str(), std::ios::binary);+ if (!f) return false;+ std::string b((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());+ if (b.empty() || b.size() > 4u * 1024 * 1024) return false;+ if (b.size() >= 3 && (unsigned char)b[0] == 0xEF && (unsigned char)b[1] == 0xBB && (unsigned char)b[2] == 0xBF) b.erase(0, 3);+ out = Decodifica(b);+ return !out.empty();+}++void GravaArquivo(const std::wstring& p, const std::wstring& txt) {+ std::ofstream f(p.c_str(), std::ios::binary | std::ios::trunc);+ if (f) { std::string b = U(txt); f.write(b.data(), (std::streamsize)b.size()); }+}++void CriaPasta(const std::wstring& p) { CreateDirectoryW(p.c_str(), nullptr); }++std::wstring NomeCache(const std::wstring& t, const std::wstring& a) {+ std::wstring k = Simples(t) + L"\x1f" + Minus(a);+ unsigned long long h = 1469598103934665603ULL;+ for (wchar_t c : k) { h ^= (unsigned long long)c; h *= 1099511628211ULL; }+ wchar_t b[32];+ swprintf_s(b, L"%016llx", h);+ return Pasta() + L"\\letras\\" + b + L".lrc";+}++// ---- LRC+bool LerTag(const std::wstring& s, double& t) {+ size_t c = s.find(L':');+ if (c == std::wstring::npos || c == 0) return false;+ for (size_t i = 0; i < s.size(); i++) {+ if (i == c) continue;+ if (s[i] < L'0' || s[i] > L'9') { if (s[i] != L'.') return false; }+ }+ double m = wcstod(s.substr(0, c).c_str(), nullptr);+ double g = wcstod(s.substr(c + 1).c_str(), nullptr);+ t = m * 60.0 + g;+ return true;+}++void ParseLRC(const std::wstring& txt, std::vector<Linha>& out) {+ size_t i = 0;+ while (i <= txt.size()) {+ size_t j = txt.find(L'\n', i);+ if (j == std::wstring::npos) j = txt.size();+ std::wstring ln = txt.substr(i, j - i);+ i = j + 1;+ while (!ln.empty() && (ln.back() == L'\r' || ln.back() == L'\t')) ln.pop_back();+ std::vector<double> ts;+ size_t k = 0;+ bool meta = false;+ while (k < ln.size() && ln[k] == L'[') {+ size_t e = ln.find(L']', k);+ if (e == std::wstring::npos) break;+ double t;+ if (!LerTag(ln.substr(k + 1, e - k - 1), t)) { meta = true; break; } // [ar:] [ti:] [length:]+ ts.push_back(t);+ k = e + 1;+ }+ if (meta || ts.empty()) { if (j == txt.size()) break; continue; }+ std::wstring corpo = ln.substr(k);+ while (!corpo.empty() && (corpo.front() == L' ' || corpo.front() == L'\t')) corpo.erase(0, 1);+ while (!corpo.empty() && (corpo.back() == L' ' || corpo.back() == L'\t')) corpo.pop_back();+ for (double t : ts) out.push_back({ t, corpo });+ if (j == txt.size()) break;+ }+ std::stable_sort(out.begin(), out.end(), [](const Linha& a, const Linha& b) { return a.t < b.t; });+}++// ---- JSON mínimo (a resposta do NetEase é previsível: só preciso de algumas chaves)+void PulaEsp(const std::string& s, size_t& p) {+ while (p < s.size() && (s[p] == ' ' || s[p] == '\t' || s[p] == '\n' || s[p] == '\r')) p++;+}++void Utf8Add(std::string& o, unsigned cp) {+ if (cp < 0x80) o.push_back((char)cp);+ else if (cp < 0x800) { o.push_back((char)(0xC0 | (cp >> 6))); o.push_back((char)(0x80 | (cp & 0x3F))); }+ else if (cp < 0x10000) {+ o.push_back((char)(0xE0 | (cp >> 12)));+ o.push_back((char)(0x80 | ((cp >> 6) & 0x3F)));+ o.push_back((char)(0x80 | (cp & 0x3F)));+ } else {+ o.push_back((char)(0xF0 | (cp >> 18)));+ o.push_back((char)(0x80 | ((cp >> 12) & 0x3F)));+ o.push_back((char)(0x80 | ((cp >> 6) & 0x3F)));+ o.push_back((char)(0x80 | (cp & 0x3F)));+ }+}++bool PegaStr(const std::string& s, size_t& p, std::wstring& out) {+ PulaEsp(s, p);+ if (p >= s.size() || s[p] != '"') return false;+ p++;+ std::string b;+ unsigned par = 0;+ while (p < s.size()) {+ unsigned char c = (unsigned char)s[p++];+ if (c == '"') { out = W(b); return true; }+ if (c != '\\') { b.push_back((char)c); continue; }+ if (p >= s.size()) break;+ char e = s[p++];+ if (e == 'n') b.push_back('\n');+ else if (e == 't') b.push_back('\t');+ else if (e == 'r') b.push_back('\r');+ else if (e == 'u' && p + 4 <= s.size()) {+ unsigned v = (unsigned)strtoul(s.substr(p, 4).c_str(), nullptr, 16);+ p += 4;+ if (v >= 0xD800 && v <= 0xDBFF) { par = v; continue; }+ if (v >= 0xDC00 && v <= 0xDFFF && par) { Utf8Add(b, 0x10000 + ((par - 0xD800) << 10) + (v - 0xDC00)); par = 0; continue; }+ Utf8Add(b, v); par = 0;+ } else b.push_back(e);+ }+ return false;+}++bool Chave(const std::string& s, size_t from, const char* nome, size_t& depois) {+ size_t p = s.find(nome, from);+ if (p == std::string::npos) return false;+ p += strlen(nome);+ PulaEsp(s, p);+ if (p >= s.size() || s[p] != ':') return false;+ depois = p + 1;+ return true;+}++// As chaves do proprio objeto da musica: o primeiro "id" e o primeiro "name" que aparecem dentro dele+// sao os do album/artista (id 0 e nome vazio), nao os da musica. Aqui so valem as chaves do nivel de cima.+bool ChaveTop(const std::string& s, const char* nome, size_t& depois) {+ int d = 0;+ bool emStr = false;+ size_t n = strlen(nome);+ for (size_t i = 0; i < s.size(); i++) {+ char c = s[i];+ if (emStr) {+ if (c == '\\') { i++; continue; }+ if (c == '"') emStr = false;+ continue;+ }+ if (c == '"') {+ if (d == 1 && s.compare(i, n, nome) == 0) {+ size_t p = i + n;+ PulaEsp(s, p);+ if (p < s.size() && s[p] == ':') { depois = p + 1; return true; }+ }+ emStr = true;+ continue;+ }+ if (c == '{' || c == '[') d++;+ else if (c == '}' || c == ']') d--;+ }+ return false;+}++std::wstring StrTop(const std::string& s, const char* nome) {+ size_t p;+ std::wstring o;+ if (!ChaveTop(s, nome, p)) return o;+ if (!PegaStr(s, p, o)) o.clear();+ return o;+}++long long NumTop(const std::string& s, const char* nome) {+ size_t p;+ if (!ChaveTop(s, nome, p)) return 0;+ PulaEsp(s, p);+ return strtoll(s.c_str() + p, nullptr, 10);+}+std::wstring StrDe(const std::string& s, size_t from, const char* nome) {+ size_t p;+ std::wstring o;+ if (!Chave(s, from, nome, p)) return o;+ if (!PegaStr(s, p, o)) o.clear();+ return o;+}++long long NumDe(const std::string& s, size_t from, const char* nome) {+ size_t p;+ if (!Chave(s, from, nome, p)) return 0;+ PulaEsp(s, p);+ return strtoll(s.c_str() + p, nullptr, 10);+}++struct Achado { long long id = 0, dur = 0; std::wstring nome, artista; };++std::wstring ArtistaDe(const std::string& obj) {+ size_t p;+ if (!Chave(obj, 0, "\"artists\"", p)) return std::wstring();+ size_t q = obj.find('[', p);+ if (q == std::string::npos) return std::wstring();+ return StrDe(obj, q, "\"name\"");+}++std::wstring UrlEnc(const std::wstring& s) {+ std::string u = U(s);+ std::wstring o;+ wchar_t b[8];+ for (unsigned char c : u) {+ if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||+ c == '-' || c == '_' || c == '.' || c == '~') o.push_back((wchar_t)c);+ else { swprintf_s(b, L"%%%02X", c); o += b; }+ }+ return o;+}++bool Http(const wchar_t* host, const std::wstring& caminho, std::string& corpo) {+ bool ok = false;+ HINTERNET ses = WinHttpOpen(L"WacOS/1.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,+ WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);+ if (!ses) { Log(L"letra: WinHttpOpen falhou"); return false; }+ WinHttpSetTimeouts(ses, 4000, 4000, 6000, 9000);+ HINTERNET con = WinHttpConnect(ses, host, INTERNET_DEFAULT_HTTPS_PORT, 0);+ if (!con) Log(L"letra: WinHttpConnect falhou (%lu)", GetLastError());+ HINTERNET req = con ? WinHttpOpenRequest(con, L"GET", caminho.c_str(), nullptr, WINHTTP_NO_REFERER,+ WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : nullptr;+ if (req) {+ const wchar_t* hdr = L"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\r\n"+ L"Referer: https://music.163.com/\r\nAccept: application/json\r\n";+ if (WinHttpSendRequest(req, hdr, (DWORD)-1L, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) &&+ WinHttpReceiveResponse(req, nullptr)) {+ DWORD st = 0, n = sizeof(st);+ WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,+ WINHTTP_HEADER_NAME_BY_INDEX, &st, &n, WINHTTP_NO_HEADER_INDEX);+ if (st == 200) {+ corpo.clear();+ DWORD lido = 0;+ char buf[8192];+ while (WinHttpReadData(req, buf, sizeof(buf), &lido) && lido > 0) {+ corpo.append(buf, lido);+ if (corpo.size() > 4u * 1024 * 1024) break;+ }+ ok = !corpo.empty();+ }+ }+ if (!ok) Log(L"letra: nada de %ls%ls", host, caminho.substr(0, 90).c_str());+ WinHttpCloseHandle(req);+ }+ if (con) WinHttpCloseHandle(con);+ WinHttpCloseHandle(ses);+ return ok;+}+// ---- busca+// Tira o que vem entre parênteses/colchetes: "Rain (Live)" e "Rain" são a mesma faixa+std::wstring Limpo(const std::wstring& s) {+ std::wstring o;+ int nivel = 0;+ for (wchar_t c : s) {+ if (c == L'(' || c == L'(' || c == L'[' || c == L'【') { nivel++; continue; }+ if (c == L')' || c == L')' || c == L']' || c == L'】') { if (nivel) nivel--; continue; }+ if (!nivel) o.push_back(c);+ }+ while (!o.empty() && o.front() == L' ') o.erase(0, 1);+ while (!o.empty() && o.back() == L' ') o.pop_back();+ return o;+}++// A letra só serve quando o título e o artista batem; se a duração é conhecida, também tem de bater.+// Na dúvida fica sem letra: melhor nada do que a letra de outra gravação.+int Nota(const Achado& a, const std::wstring& t, const std::wstring& art, double durPedido) {+ std::wstring an = Simples(a.nome), at = Simples(t);+ if (an.empty() || at.empty()) return -1;+ std::wstring ln = Limpo(an), lt = Limpo(at);+ int s;+ if (an == at) s = 100;+ else if (!ln.empty() && ln == lt) s = 85;+ else if (an.find(at) != std::wstring::npos || at.find(an) != std::wstring::npos) s = 40;+ else return -1;+ std::wstring aa = Minus(a.artista), ra = Minus(art);+ if (!aa.empty() && !ra.empty()) {+ if (aa.find(ra) != std::wstring::npos || ra.find(aa) != std::wstring::npos) s += 50;+ else return -1; // outro artista: recusa+ }+ if (durPedido > 1.0 && a.dur > 0) {+ double dif = durPedido - (double)a.dur / 1000.0;+ if (dif < 0) dif = -dif;+ if (dif <= 3.0) s += 25;+ else if (dif <= 8.0) s += 8;+ else return -1; // a duração não bate: recusa+ }+ return s;+}++bool TemLetra(const std::wstring& txt) {+ std::vector<Linha> l;+ ParseLRC(txt, l);+ for (auto& x : l) if (!x.s.empty()) return true;+ return false;+}++bool DoArquivo(const std::wstring& caminho, std::vector<Linha>& ls, double& dur) {+ std::wstring txt;+ if (!LerArquivo(caminho, txt)) return false;+ ls.clear();+ ParseLRC(txt, ls);+ if (ls.empty()) return false;+ dur = ls.back().t + 6.0;+ return true;+}++// .lrc nosso próprio: a pasta de cache e as pastas do ajuste letra_pasta (separadas por ';')+bool Local(const std::wstring& t, const std::wstring& a, std::wstring& achou) {+ std::wstring chave = Simples(t);+ std::wstring art = Minus(a);+ if (chave.size() < 2) return false;+ std::vector<std::wstring> pastas;+ std::wstring cfg = shell::Setting(L"letra_pasta", L"");+ size_t i = 0;+ while (i <= cfg.size()) {+ size_t j = cfg.find(L';', i);+ if (j == std::wstring::npos) j = cfg.size();+ std::wstring d = cfg.substr(i, j - i);+ while (!d.empty() && (d.front() == L' ' || d.front() == L'"' || d.front() == L'\r')) d.erase(0, 1);+ while (!d.empty() && (d.back() == L' ' || d.back() == L'"')) d.pop_back();+ if (!d.empty()) pastas.push_back(d);+ i = j + 1;+ if (j == cfg.size()) break;+ }+ pastas.push_back(Pasta() + L"\\letras");+ for (auto& d : pastas) {+ WIN32_FIND_DATAW fd;+ HANDLE h = FindFirstFileW((d + L"\\*.lrc").c_str(), &fd);+ if (h == INVALID_HANDLE_VALUE) continue;+ std::wstring forte, fraco;+ do {+ if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;+ if (!Contem(fd.cFileName, chave)) continue;+ std::wstring txt;+ if (!LerArquivo(d + L"\\" + fd.cFileName, txt) || !TemLetra(txt)) continue;+ // o ficheiro que também leva o nome do artista vale mais do que um homónimo+ if (!art.empty() && Contem(fd.cFileName, art)) { forte = txt; break; }+ if (fraco.empty()) fraco = txt;+ } while (FindNextFileW(h, &fd));+ FindClose(h);+ if (!forte.empty()) { achou = forte; return true; }+ if (!fraco.empty()) { achou = fraco; return true; }+ }+ return false;+}++bool Online(const std::wstring& t, const std::wstring& a, double durPedido, std::vector<Linha>& ls, double& dur) {+ std::wstring q = UrlEnc(a.empty() ? t : t + L" " + a);+ std::string js;+ if (!Http(L"music.163.com", L"/api/search/get/web?s=" + q + L"&type=1&limit=10", js)) {+ Log(L"letra: busca sem resposta");+ return false;+ }+ size_t p = js.find("\"songs\"");+ if (p == std::string::npos) {+ Log(L"letra: sem songs em %u bytes", (unsigned)js.size());+ return false;+ }+ std::vector<Achado> cand;+ while (p < js.size() && cand.size() < 10) {+ size_t ob = js.find('{', p);+ if (ob == std::string::npos) break;+ int d = 0;+ size_t k = ob;+ for (; k < js.size(); k++) {+ if (js[k] == '{') d++;+ else if (js[k] == '}') { d--; if (!d) break; }+ }+ if (k >= js.size()) break;+ std::string obj = js.substr(ob, k - ob + 1);+ Achado x;+ x.id = NumTop(obj, "\"id\"");+ x.dur = NumTop(obj, "\"duration\"");+ x.nome = StrTop(obj, "\"name\"");+ x.artista = ArtistaDe(obj);+ if (x.id > 0 && !x.nome.empty()) cand.push_back(x);+ p = k + 1;+ }+ int melhor = -1, nota = -1;+ for (size_t i = 0; i < cand.size(); i++) {+ int n = Nota(cand[(size_t)i], t, a, durPedido);+ if (n > nota) { nota = n; melhor = (int)i; }+ }+ if (melhor < 0 || nota < 0) {+ Log(L"letra: %u candidato(s), nenhum serve para %ls", (unsigned)cand.size(), t.c_str());+ return false;+ }+ wchar_t url[96];+ swprintf_s(url, L"/api/song/lyric?id=%lld&lv=1&kv=0&tv=0", cand[(size_t)melhor].id);+ if (!Http(L"music.163.com", url, js)) {+ Log(L"letra: sem resposta da letra");+ return false;+ }+ std::wstring lrc = StrDe(js, 0, "\"lyric\"");+ ls.clear();+ ParseLRC(lrc, ls);+ if (ls.empty()) {+ Log(L"letra: LRC vazio (%u chars)", (unsigned)lrc.size());+ return false;+ }+ dur = cand[(size_t)melhor].dur > 0 ? (double)cand[(size_t)melhor].dur / 1000.0 : ls.back().t + 6.0;+ return true;+}++bool Buscar(const std::wstring& t, const std::wstring& a, double durPedido, std::vector<Linha>& ls, double& dur) {+ std::wstring cache = NomeCache(t, a);+ if (DoArquivo(cache, ls, dur)) return true;+ std::wstring txt;+ if (Local(t, a, txt)) {+ ls.clear();+ ParseLRC(txt, ls);+ if (!ls.empty()) {+ dur = ls.back().t + 6.0;+ CriaPasta(Pasta() + L"\\letras");+ GravaArquivo(cache, txt);+ return true;+ }+ }+ if (!Online(t, a, durPedido, ls, dur)) return false;+ std::wstring saida;+ wchar_t b[40];+ for (auto& x : ls) {+ int m = (int)(x.t / 60.0);+ int s = (int)x.t - m * 60;+ int cs = (int)((x.t - (double)(int)x.t) * 100.0 + 0.5);+ if (cs > 99) cs = 99;+ swprintf_s(b, L"[%02d:%02d.%02d]", m, s, cs);+ saida += b;+ saida += x.s;+ saida += L"\n";+ }+ CriaPasta(Pasta() + L"\\letras");+ GravaArquivo(cache, saida);+ return true;+}++void Thread() {+ if (!Pasta().empty()) { CriaPasta(Pasta() + L"\\letras"); }+ for (;;) {+ std::wstring t, a; double durPedido = 0;+ {+ std::unique_lock<std::mutex> l(g_mx);+ g_cv.wait(l, [] { return g_acordar || g_parar; });+ if (g_parar) break;+ g_acordar = false;+ t = g_pedT; a = g_pedA; durPedido = g_pedDur;+ if (t == g_cargaT && a == g_cargaA) continue;+ }+ std::vector<Linha> ls;+ double dur = 0;+ bool ok = !t.empty() && Buscar(t, a, durPedido, ls, dur);+ size_t n = ls.size();+ {+ std::lock_guard<std::mutex> l(g_mx);+ if (g_pedT == t && g_pedA == a) {+ g_linhas = std::move(ls);+ g_dur = ok ? dur : 0.0;+ g_cargaT = t; g_cargaA = a;+ }+ }+ if (ok) Log(L"letra: %ls -> %u linha(s)", t.c_str(), (unsigned)n);+ else Log(L"letra: %ls sem letra", t.c_str());+ }+}++} // namespace++namespace letra {++void Pedir(const std::wstring& t, const std::wstring& a, double dur) {+ if (t.empty() && a.empty()) return;+ std::lock_guard<std::mutex> l(g_mx);+ g_pedDur = dur;+ if (t == g_cargaT && a == g_cargaA) { g_pedT = t; g_pedA = a; return; }+ if (t != g_pedT || a != g_pedA) {+ g_pedT = t; g_pedA = a;+ g_linhas.clear();+ g_dur = 0;+ g_cargaT.clear(); g_cargaA.clear();+ g_acordar = true;+ if (!g_rodando) { g_rodando = true; std::thread(Thread).detach(); }+ }+ g_cv.notify_one();+}++bool Tem() {+ std::lock_guard<std::mutex> l(g_mx);+ for (auto& x : g_linhas) if (!x.s.empty()) return true;+ return false;+}++double Duracao() {+ std::lock_guard<std::mutex> l(g_mx);+ return g_linhas.empty() ? g_dur : std::max(g_dur, g_linhas.back().t + 1.0);+}++std::wstring Texto(double pos) {+ std::lock_guard<std::mutex> l(g_mx);+ if (g_linhas.empty()) return std::wstring();+ int lo = 0, hi = (int)g_linhas.size() - 1, at = -1;+ while (lo <= hi) {+ int m = (lo + hi) / 2;+ if (g_linhas[(size_t)m].t <= pos) { at = m; lo = m + 1; } else hi = m - 1;+ }+ if (at >= 0 && !g_linhas[(size_t)at].s.empty()) return g_linhas[(size_t)at].s;+ for (int i = at + 1; i < (int)g_linhas.size(); i++)+ if (!g_linhas[(size_t)i].s.empty()) return g_linhas[(size_t)i].s; // intro: já mostra a 1ª frase+ return std::wstring();+}++void Parar() {+ std::lock_guard<std::mutex> l(g_mx);+ g_parar = true;+ g_cv.notify_all();+}++} // namespace letradiff --git a/src/shell/menubar.cpp b/src/shell/menubar.cppindex af4dab4..5d14386 100644--- a/src/shell/menubar.cpp+++ b/src/shell/menubar.cpp@@ -58,7 +58,7 @@ const float PAD_SEQUOIA = 10; // espaço de cada lado de um ícone de status#define PAD (liquid::On() ? 8.f : PAD_SEQUOIA)bool g_overflow; // macOS 27: algum ícone da bandeja não coube na barra (mostra a »)-enum Kind { K_LOGO, K_APP, K_MENU, K_TRAY, K_NET, K_SPOT, K_CC, K_CLOCK, K_MORE, K_BATT, K_SOUND, K_BT, K_INPUT, K_SIRI, K_STATS };+enum Kind { K_LOGO, K_APP, K_MENU, K_TRAY, K_NET, K_SPOT, K_CC, K_CLOCK, K_LETRA, K_MORE, K_BATT, K_SOUND, K_BT, K_INPUT, K_SIRI, K_STATS };struct Hit { D2D1_RECT_F r; Kind kind; int index; };HWND g_bar, g_owner; // g_bar: a barra do monitor principal@@ -1036,6 +1036,26 @@ void Render() {rt->DrawTextW(t.c_str(), (UINT32)t.size(), tfN, D2D1::RectF(r - w + PAD, 0, r, H), br);r -= w;}+ // #342: a letra da música aqui em cima, à esquerda do relógio (a linha que está tocando, cortada se for longa).+ // Sem faixa ou sem letra nada ocupa o lugar; barra_letra=0 tira.+ if (shell::Setting(L"barra_letra", L"1") != L"0") {+ std::wstring t = ilha::LetraTexto();+ if (!t.empty()) {+ const float maxW = 260.f;+ if (ui::TextWidth(tfN, t) > maxW) {+ std::wstring corte = t;+ while (!corte.empty() && ui::TextWidth(tfN, corte + L"…") > maxW) corte.pop_back();+ t = corte + L"…";+ }+ float w = std::min(ui::TextWidth(tfN, t), maxW) + 2 * PAD;+ if (r - w > limD) {+ add(D2D1::RectF(r - w, 0, r, H), K_LETRA, 0);+ br->SetColor(litNow ? D2D1::ColorF(1, 1, 1) : fgc);+ rt->DrawTextW(t.c_str(), (UINT32)t.size(), tfN, D2D1::RectF(r - w + PAD, 0, r - PAD, H), br);+ r -= w;+ }+ }+ }// microfone/câmera em uso (issue #8, todos os temas): como no macOS, uma bolinha de 6 pt no vão entre a Central de// Controle e a data/hora: laranja = microfone, verde = câmera (a câmera ganha). barra_privacidade=0 tira.if (shell::Setting(L"barra_privacidade", L"1") != L"0")@@ -1695,6 +1715,7 @@ void Click(D2D1_POINT_2F p, bool right) {});break;} // painel da Central de Controle (central.cpp)+ case K_LETRA: ilha::LetraToggle(); break; // #342: liga/desliga a letra (na ilha e aqui em cima)case K_CLOCK: {if (!right) { notificacoes::Toggle(); break; } // clique: Central de Notificações; botão direito: data e ajustesSYSTEMTIME st; GetLocalTime(&st);diff --git a/src/shell/shell.h b/src/shell/shell.hindex 18bbabd..968808b 100644--- a/src/shell/shell.h+++ b/src/shell/shell.h@@ -495,6 +495,17 @@ void CapsLock(); // a tecla Caps Lock foi apertada (gancho de tecvoid PrivacidadeMudou(); // a bandeja mudou: relê o ícone de privacidade do Windows (tray::PrivacyBits)void Captura(bool copiada); // a Captura de Tela terminou: aviso rápido "Captura feita" / "Captura copiada"int Privacidade(); // 1 microfone, 2 câmera em uso (bits); a 1ª chamada liga a vigia; mudou = menubar::Update()+// a letra da música (issue #342): o botão no lugar do "aleatório" e o item da barra de menus+bool LetraOn(); // o usuário quer a letra aparecendo (ajuste ilha_letra)+void LetraToggle(); // liga/desliga e grava o ajuste+std::wstring LetraTexto(); // a linha da letra agora (vazio: sem faixa, sem letra ou desligada)+}+namespace letra { // letra.cpp: .lrc nosso, senão o NetEase, guardado em %APPDATA%\\Shell\\letras (issue #342)+bool Tem(); // a faixa de agora tem letra carregada+double Duracao(); // a duração que a letra conhece (0 = nada). É o que salva a barra de progresso dos apps que não informam o tempo+std::wstring Texto(double pos); // a linha da letra na posição pos (na introdução, a primeira frase)+void Pedir(const std::wstring& titulo, const std::wstring& artista, double duracao = 0); // faixa nova (qualquer thread); duracao = o que a Ilha sabe (0 = nada)+void Parar();}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 };