diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index 71a710f..0000000 --- a/AGENTS.md +++ /dev/null @@ -1,180 +0,0 @@ -# Инструкция для AI-агентов (Git, коммиты и релизы на git.tatar) - -Этот репозиторий хостится на **Forgejo** (`https://git.tatar/marwy/yandex-music-rs`). -Авторизация на `https://git.tatar` должна храниться в Windows Credential Manager как **бессрочный Personal Access Token (PAT)** с `credential.https://git.tatar.provider = generic` (НЕ через OAuth-окно GCM — OAuth-токен Forgejo протухает через ~1 час, после чего `git push` удаляет запись из Credential Manager). - -> **ВАЖНО:** -> 1. **НИКОГДА не используй браузер** для создания релизов, загрузки ассетов или настройки репозитория на `git.tatar` — браузер не авторизован и упрётся в страницу логина. Все операции с `git.tatar` выполняются через **Forgejo REST API v1** с токеном из `git credential fill`. -> 2. **НИКОГДА не печатай токен** в stdout, логи, файлы или ответы пользователю. -> 3. **НИКОГДА не коммить** `target/`, `original_yandex_music/`, `Yandex_Music_*.exe`, локальные `.deb`/`.exe`/`.tar.gz` и личные OAuth-токены Яндекс Музыки. -> 4. **Перед `git push` проверяй токен без интерактива** (`$env:GCM_INTERACTIVE = "never"` + `GET https://git.tatar/api/v1/user`): если токен отсутствует или истёк (401), не вешай `git push` на невидимом окне GCM — сразу попроси пользователя сохранить бессрочный PAT из `https://git.tatar/user/settings/applications` (см. раздел 0). -> 5. **Релизы и теги строго иммутабельны — НИКОГДА не перезаписывай и не двигай уже выпущенную версию!** Запрещено делать `git tag -f` на существующий релиз, удалять/перезаливать ассеты под старым `vX.Y.Z` или пересобирать новую правку под уже отданным пользователю номером версии. Любое изменение после сборки/публикации `vX.Y.Z` **всегда** выходит как **новая версия** (`v0.1.2` → `v0.1.3`), чтобы у клиентов никогда не было разных бинарников под одним номером версии и автообновление работало корректно. - ---- - -## 0. Первичная настройка бессрочного токена (делается пользователем 1 раз) - -Если токен отсутствует или протух (401), пользователь создаёт **Access Token** на `https://git.tatar/user/settings/applications` (права: `write:repository`, `read:user`) и сохраняет его один раз: - -```powershell -git config --global credential.https://git.tatar.provider generic -"protocol=https`nhost=git.tatar`nusername=marwy`npassword=`n" | git credential approve -``` - -Проверка из агента (никогда не выводить `$token`, всегда ставить `GCM_INTERACTIVE=never`): - -```powershell -$env:GCM_INTERACTIVE = "never" -$credOut = "protocol=https`nhost=git.tatar`n`n" | git credential fill 2>$null -$token = ($credOut | Where-Object { $_ -like 'password=*' }) -replace '^password=','' -if (-not $token) { throw "No token in Credential Manager (need PAT for git.tatar)" } -$u = Invoke-RestMethod -Uri "https://git.tatar/api/v1/user" -Headers @{ Authorization = "token $token" } -Write-Output ("AUTH_OK: " + $u.login) -``` - ---- - -## 1. Коммиты и пуш (`git push`) - -- Ветка по умолчанию: `main`. -- Используй Conventional Commits (`feat: ...`, `fix: ...`, `chore(release): vX.Y.Z`, `docs: ...`). -- На Windows **PowerShell 5.1 не поддерживает `&&`** — разделяй команды через `;` с проверкой `if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }`. -- При добавлении новых shell-скриптов (`*.sh`, `packaging/debian/*`) на Windows обязательно выставляй бит исполняемости в индексе: - ```powershell - git update-index --chmod=+x packaging/build-deb.sh packaging/debian/postinst packaging/debian/postrm - ``` -- Обычный `git push origin main` и `git push origin vX.Y.Z` работают автоматически через системный Git Credential Manager (авторизация уже сохранена). - ---- - -## 2. Сборка релиза `vX.Y.Z` (Windows + Linux) - -1. Обнови версию в `Cargo.toml` (и при необходимости ссылки в `README.md`), закоммить и запушь: - ```powershell - git add Cargo.toml Cargo.lock README.md - git commit -m "chore(release): vX.Y.Z" - git push origin main - ``` -2. **Windows x64** (все ресурсы встроены через `include_bytes!`, получается единый portable `.exe`): - ```powershell - cargo build --release - ``` - Бинарник: `target\release\yandex-music-rs.exe`. -3. **Linux x64 (`.deb` + `.tar.gz`)** через WSL (передавай bash-скрипт через `stdin` в `wsl bash -s`, чтобы Windows не ломал кавычки): - ```powershell - $ver = "0.1.1" - $dist = "D:\YandexMusicRust\target\release-dist-v$ver" - New-Item -ItemType Directory -Force -Path $dist | Out-Null - - Copy-Item -Force "D:\YandexMusicRust\target\release\yandex-music-rs.exe" "$dist\yandex-music-rs-v$ver-windows-x86_64.exe" - - $bashScript = @" - set -euo pipefail - cd /mnt/d/YandexMusicRust - ./packaging/build-deb.sh - TMP=`$(mktemp -d) - cp "`$HOME/.cache/yandex-music-rs-target/release/yandex-music-rs" "`$TMP/yandex-music-rs" - chmod +x "`$TMP/yandex-music-rs" - cp /mnt/d/YandexMusicRust/README.md "`$TMP/README.md" - tar -czf "/mnt/d/YandexMusicRust/target/release-dist-v$ver/yandex-music-rs-v$ver-linux-x86_64.tar.gz" -C "`$TMP" yandex-music-rs README.md - rm -rf "`$TMP" - "@ -replace "`r`n", "`n" - $bashScript | wsl bash -s - - Copy-Item -Force "D:\YandexMusicRust\target\debian\yandex-music-rs_${ver}-1_amd64.deb" "$dist\yandex-music-rs_${ver}-1_amd64.deb" - ``` -4. **Контрольные суммы (`SHA256SUMS.txt`)**: - ```powershell - $files = @( - "yandex-music-rs-v$ver-windows-x86_64.exe", - "yandex-music-rs_${ver}-1_amd64.deb", - "yandex-music-rs-v$ver-linux-x86_64.tar.gz" - ) - $sums = foreach ($f in $files) { - $h = (Get-FileHash -Algorithm SHA256 "$dist\$f").Hash.ToLower() - "$h $f" - } - [System.IO.File]::WriteAllText("$dist\SHA256SUMS.txt", ($sums -join "`n") + "`n", [System.Text.UTF8Encoding]::new($false)) - ``` - ---- - -## 3. Публикация релиза на `git.tatar` через Forgejo API (БЕЗ браузера!) - -1. Создай и запушь аннотированный тег: - ```powershell - git tag -a "v$ver" -m "v$ver" - git push origin "v$ver" - ``` -2. Получи токен из Git Credential Manager (не выводя его в консоль) и создай релиз + загрузи файлы через `curl.exe`: - ```powershell - $ErrorActionPreference = "Stop" - $ver = "0.1.1" - $dist = "D:\YandexMusicRust\target\release-dist-v$ver" - - # Токен из Git Credential Manager (НИКОГДА не печатать!) - $credOut = "protocol=https`nhost=git.tatar`n`n" | git credential fill 2>$null - $token = ($credOut | Where-Object { $_ -like 'password=*' }) -replace '^password=','' - if (-not $token) { throw "No token from git credential fill" } - - $headers = @{ - "Authorization" = "token $token" - "Accept" = "application/json" - } - - # Создание релиза (обязательно UTF-8 bytes, чтобы кириллица не побилась в PowerShell 5.1) - $payloadObj = @{ - tag_name = "v$ver" - target_commitish = "main" - name = "v$ver" - body = "Описание изменений..." - draft = $false - prerelease = $false - } - $payloadBytes = [System.Text.Encoding]::UTF8.GetBytes(($payloadObj | ConvertTo-Json -Depth 5)) - - try { - $release = Invoke-RestMethod -Method Post ` - -Uri "https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases" ` - -Headers $headers ` - -ContentType "application/json; charset=utf-8" ` - -Body $payloadBytes - } catch { - # Если релиз для этого тега уже создан — получаем его ID - $release = Invoke-RestMethod -Method Get ` - -Uri "https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases/tags/v$ver" ` - -Headers $headers - } - - # Загрузка ассетов через curl.exe (multipart/form-data, поле attachment) - $uploadFiles = @( - "yandex-music-rs-v$ver-windows-x86_64.exe", - "yandex-music-rs_${ver}-1_amd64.deb", - "yandex-music-rs-v$ver-linux-x86_64.tar.gz", - "SHA256SUMS.txt" - ) - foreach ($fname in $uploadFiles) { - $fpath = "$dist\$fname" - $url = "https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases/$($release.id)/assets?name=$([uri]::EscapeDataString($fname))" - $resp = & curl.exe -sS -f -X POST -H "Authorization: token $token" -F "attachment=@$fpath" $url - if ($LASTEXITCODE -ne 0) { throw "Upload failed for $fname" } - $asset = $resp | ConvertFrom-Json - Write-Output ("OK: " + $asset.name + " (" + $asset.size + " bytes)") - } - ``` - -> **Совет для PowerShell 5.1 с кириллицей и Markdown:** -> - Для Markdown-текста описания релиза используй **одинарный** here-string `@' ... '@` (в `@" ... "@` обратные кавычки `` ` `` ломают синтаксис!). -> - Если сохраняешь временный `.ps1` скрипт в UTF-8 без BOM, запускай его через чтение в UTF-8, иначе PowerShell 5.1 прочитает его как Windows-1251: -> ```powershell -> $code = [System.IO.File]::ReadAllText("path\to\script.ps1", [System.Text.UTF8Encoding]::new($false)) -> Invoke-Expression $code -> ``` - ---- - -## 4. Другие полезные Forgejo API вызовы - -- Проверить токен: `GET https://git.tatar/api/v1/user` с заголовком `Authorization: token $token` -- Обновить аватар репозитория: `POST https://git.tatar/api/v1/repos/marwy/yandex-music-rs/avatar` с JSON `{ "image": "" }` -- Проверить список релизов: `GET https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases` diff --git a/Cargo.lock b/Cargo.lock index 80fc82e..e2b1707 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -186,15 +186,6 @@ dependencies = [ "x11rb", ] -[[package]] -name = "arc-swap" -version = "1.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" -dependencies = [ - "rustversion", -] - [[package]] name = "arrayref" version = "0.3.9" @@ -233,18 +224,6 @@ dependencies = [ "raw-window-metal", ] -[[package]] -name = "async-broadcast" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" -dependencies = [ - "event-listener", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - [[package]] name = "async-compression" version = "0.4.52" @@ -257,28 +236,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "async-recursion" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "async-trait" -version = "0.1.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - [[package]] name = "atk" version = "0.18.2" @@ -892,15 +849,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "crossbeam-queue" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" -dependencies = [ - "crossbeam-utils", -] - [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -1137,33 +1085,6 @@ dependencies = [ "simdutf8", ] -[[package]] -name = "endi" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" - -[[package]] -name = "enumflags2" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" -dependencies = [ - "enumflags2_derive", - "serde", -] - -[[package]] -name = "enumflags2_derive" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "env_filter" version = "2.1.0" @@ -1218,38 +1139,12 @@ dependencies = [ "num-traits", ] -[[package]] -name = "event-listener" -version = "5.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" -dependencies = [ - "parking", - "pin-project-lite", -] - -[[package]] -name = "event-listener-strategy" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" -dependencies = [ - "event-listener", - "pin-project-lite", -] - [[package]] name = "extended" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" -[[package]] -name = "fastrand" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" - [[package]] name = "fax" version = "0.2.7" @@ -1438,19 +1333,6 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" -[[package]] -name = "futures-lite" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" -dependencies = [ - "fastrand", - "futures-core", - "futures-io", - "parking", - "pin-project-lite", -] - [[package]] name = "futures-macro" version = "0.3.34" @@ -2468,21 +2350,6 @@ version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" -[[package]] -name = "ksni" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d49a7ac89853917f01d75f6bac3e7c8e282ae621dd63fbbfc50fe331304fa580" -dependencies = [ - "arc-swap", - "crossbeam-queue", - "futures-util", - "pastey", - "serde", - "tokio", - "zbus", -] - [[package]] name = "kuchikiki" version = "0.8.2" @@ -3328,16 +3195,6 @@ dependencies = [ "libredox", ] -[[package]] -name = "ordered-stream" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" -dependencies = [ - "futures-core", - "pin-project-lite", -] - [[package]] name = "owned_ttf_parser" version = "0.25.1" @@ -3372,12 +3229,6 @@ dependencies = [ "system-deps", ] -[[package]] -name = "parking" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" - [[package]] name = "parking_lot" version = "0.12.5" @@ -3401,12 +3252,6 @@ dependencies = [ "windows-link 0.2.1", ] -[[package]] -name = "pastey" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" - [[package]] name = "percent-encoding" version = "2.3.2" @@ -4366,17 +4211,6 @@ dependencies = [ "zmij", ] -[[package]] -name = "serde_repr" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - [[package]] name = "serde_spanned" version = "0.6.9" @@ -4431,16 +4265,6 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" -[[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - [[package]] name = "simd-adler32" version = "0.3.10" @@ -4993,19 +4817,6 @@ version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom 0.4.3", - "once_cell", - "rustix 1.1.6", - "windows-sys 0.61.2", -] - [[package]] name = "tendril" version = "0.4.3" @@ -5168,10 +4979,8 @@ dependencies = [ "libc", "mio", "pin-project-lite", - "signal-hook-registry", "socket2", "tokio-macros", - "tracing", "windows-sys 0.61.2", ] @@ -5341,21 +5150,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ "pin-project-lite", - "tracing-attributes", "tracing-core", ] -[[package]] -name = "tracing-attributes" -version = "0.1.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "tracing-core" version = "0.1.36" @@ -5407,17 +5204,6 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" -[[package]] -name = "uds_windows" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" -dependencies = [ - "memoffset", - "tempfile", - "windows-sys 0.61.2", -] - [[package]] name = "unicode-bidi" version = "0.3.18" @@ -5562,17 +5348,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" -[[package]] -name = "uuid" -version = "1.29.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" -dependencies = [ - "js-sys", - "serde_core", - "wasm-bindgen", -] - [[package]] name = "version-compare" version = "0.2.1" @@ -6550,7 +6325,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "yandex-music-rs" -version = "0.1.9" +version = "0.1.0" dependencies = [ "aes", "anyhow", @@ -6572,7 +6347,6 @@ dependencies = [ "hex", "hmac", "image", - "ksni", "log", "lru", "md-5", @@ -6626,71 +6400,6 @@ dependencies = [ "synstructure", ] -[[package]] -name = "zbus" -version = "5.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" -dependencies = [ - "async-broadcast", - "async-recursion", - "async-trait", - "enumflags2", - "event-listener", - "futures-core", - "futures-lite", - "hex", - "libc", - "ordered-stream", - "rustix 1.1.6", - "serde", - "serde_repr", - "tokio", - "tracing", - "uds_windows", - "uuid", - "windows-sys 0.61.2", - "winnow 1.0.5", - "zbus_macros", - "zbus_names", - "zvariant", -] - -[[package]] -name = "zbus_macros" -version = "5.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" -dependencies = [ - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 3.0.10", - "zbus_names", - "zvariant", - "zvariant_utils", -] - -[[package]] -name = "zbus_names" -version = "4.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" -dependencies = [ - "serde", - "winnow 1.0.5", - "zvariant", -] - -[[package]] -name = "zcheapstr" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907" -dependencies = [ - "serde", -] - [[package]] name = "zeno" version = "0.3.3" @@ -6818,44 +6527,3 @@ checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" dependencies = [ "zune-core 0.5.3", ] - -[[package]] -name = "zvariant" -version = "5.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" -dependencies = [ - "endi", - "enumflags2", - "serde", - "winnow 1.0.5", - "zcheapstr", - "zvariant_derive", - "zvariant_utils", -] - -[[package]] -name = "zvariant_derive" -version = "5.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" -dependencies = [ - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 3.0.10", - "zvariant_utils", -] - -[[package]] -name = "zvariant_utils" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "syn 3.0.10", - "winnow 1.0.5", -] diff --git a/Cargo.toml b/Cargo.toml index 00e7a8d..d4a4d28 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,22 +1,9 @@ [package] name = "yandex-music-rs" -version = "0.1.9" +version = "0.1.0" edition = "2021" description = "Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust + ash Vulkan SDF + taffy + cosmic-text" -[features] -default = [] -linux-webview = ["dep:wry", "dep:gtk"] - -[[bin]] -name = "yandex-music-rs" -path = "src/main.rs" - -[[bin]] -name = "yandex-music-auth" -path = "src/bin/yandex_music_auth.rs" -required-features = ["linux-webview"] - [dependencies] # Core Windowing & Native UI Engine (ash SDF + taffy + cosmic-text) winit = "0.30" @@ -81,9 +68,8 @@ windows-sys = { version = "0.59", features = [ ] } [target.'cfg(target_os = "linux")'.dependencies] -ksni = { version = "0.3", features = ["blocking"] } -wry = { version = "0.51", default-features = false, features = ["os-webview"], optional = true } -gtk = { version = "0.18", optional = true } +wry = { version = "0.51", default-features = false, features = ["os-webview"] } +gtk = "0.18" [build-dependencies] naga = { version = "24", features = ["wgsl-in", "spv-out"] } @@ -108,7 +94,6 @@ recommends = "libvulkan1, mesa-vulkan-drivers, libgl1, libegl1" maintainer-scripts = "packaging/debian" assets = [ ["target/release/yandex-music-rs", "usr/bin/", "755"], - ["target/release/yandex-music-auth", "usr/bin/", "755"], ["assets/icons/app_icon.png", "usr/share/pixmaps/yandex-music-rs.png", "644"], ["assets/icons/app_48.png", "usr/share/icons/hicolor/48x48/apps/yandex-music-rs.png", "644"], ["packaging/icons/64x64.png", "usr/share/icons/hicolor/64x64/apps/yandex-music-rs.png", "644"], diff --git a/README.md b/README.md index d66c72c..12c2cf7 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,12 @@ Готовые сборки доступны на странице [Releases](https://git.tatar/marwy/yandex-music-rs/releases): -- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.9-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). -- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.9-1_amd64.deb` и установите: +- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.0-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). +- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.0-1_amd64.deb` и установите: ```bash - sudo apt install ./yandex-music-rs_0.1.9-1_amd64.deb + sudo apt install ./yandex-music-rs_0.1.0-1_amd64.deb ``` -- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.9-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). +- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.0-linux-x86_64.tar.gz` с готовым бинарником. ## Стек и возможности diff --git a/assets/icons/navigationConcerts_selected_xs.svg b/assets/icons/navigationConcerts_selected_xs.svg index 06aacdc..5216578 100644 --- a/assets/icons/navigationConcerts_selected_xs.svg +++ b/assets/icons/navigationConcerts_selected_xs.svg @@ -1,3 +1,3 @@ - - - + + + \ No newline at end of file diff --git a/assets/icons/profile_account_xxs.svg b/assets/icons/profile_account_xxs.svg index f4f0295..7c386d9 100644 --- a/assets/icons/profile_account_xxs.svg +++ b/assets/icons/profile_account_xxs.svg @@ -1,5 +1,4 @@ - - - - + + + diff --git a/assets/icons/profile_add_account_xxs.svg b/assets/icons/profile_add_account_xxs.svg deleted file mode 100644 index a48312c..0000000 --- a/assets/icons/profile_add_account_xxs.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/assets/icons/profile_globe_xxs.svg b/assets/icons/profile_globe_xxs.svg index b37d0ff..d92bc72 100644 --- a/assets/icons/profile_globe_xxs.svg +++ b/assets/icons/profile_globe_xxs.svg @@ -1,3 +1,5 @@ - - + + + + diff --git a/assets/icons/profile_logout_xxs.svg b/assets/icons/profile_logout_xxs.svg index 59b3d6b..58e78e8 100644 --- a/assets/icons/profile_logout_xxs.svg +++ b/assets/icons/profile_logout_xxs.svg @@ -1,4 +1,4 @@ - - - + + + diff --git a/assets/icons/profile_plus_xxs.svg b/assets/icons/profile_plus_xxs.svg deleted file mode 100644 index a59e83f..0000000 --- a/assets/icons/profile_plus_xxs.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/assets/icons/profile_settings_xxs.svg b/assets/icons/profile_settings_xxs.svg deleted file mode 100644 index 94a2620..0000000 --- a/assets/icons/profile_settings_xxs.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/assets/icons/profile_support_xxs.svg b/assets/icons/profile_support_xxs.svg index 16bd5b0..8f760be 100644 --- a/assets/icons/profile_support_xxs.svg +++ b/assets/icons/profile_support_xxs.svg @@ -1,3 +1,6 @@ - - + + + + + diff --git a/assets/icons/theme_dark_xxs.svg b/assets/icons/theme_dark_xxs.svg index 24e39d0..28fbbaf 100644 --- a/assets/icons/theme_dark_xxs.svg +++ b/assets/icons/theme_dark_xxs.svg @@ -1,3 +1,3 @@ - - + + diff --git a/assets/icons/theme_light_xxs.svg b/assets/icons/theme_light_xxs.svg index f041a12..1019525 100644 --- a/assets/icons/theme_light_xxs.svg +++ b/assets/icons/theme_light_xxs.svg @@ -1,5 +1,4 @@ - - - - + + + diff --git a/assets/icons/theme_system_xxs.svg b/assets/icons/theme_system_xxs.svg index 4e20154..825e04f 100644 --- a/assets/icons/theme_system_xxs.svg +++ b/assets/icons/theme_system_xxs.svg @@ -1,4 +1,4 @@ - - - + + + diff --git a/assets/icons/thumb_car.svg b/assets/icons/thumb_car.svg deleted file mode 100644 index 7037c0a..0000000 --- a/assets/icons/thumb_car.svg +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/assets/icons/thumb_down_xxs.svg b/assets/icons/thumb_down_xxs.svg deleted file mode 100644 index e0b5649..0000000 --- a/assets/icons/thumb_down_xxs.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/assets/icons/thumb_duck.svg b/assets/icons/thumb_duck.svg deleted file mode 100644 index 18a11c0..0000000 --- a/assets/icons/thumb_duck.svg +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/assets/icons/thumb_up_xxs.svg b/assets/icons/thumb_up_xxs.svg deleted file mode 100644 index 47ad589..0000000 --- a/assets/icons/thumb_up_xxs.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/assets/icons/yandex_id_logo_en_dark.svg b/assets/icons/yandex_id_logo_en_dark.svg deleted file mode 100644 index 1589681..0000000 --- a/assets/icons/yandex_id_logo_en_dark.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/assets/icons/yandex_id_logo_en_light.svg b/assets/icons/yandex_id_logo_en_light.svg deleted file mode 100644 index d90a60a..0000000 --- a/assets/icons/yandex_id_logo_en_light.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/assets/icons/yandex_id_logo_ru_dark.svg b/assets/icons/yandex_id_logo_ru_dark.svg deleted file mode 100644 index 432a5c9..0000000 --- a/assets/icons/yandex_id_logo_ru_dark.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/assets/icons/yandex_id_logo_ru_light.svg b/assets/icons/yandex_id_logo_ru_light.svg deleted file mode 100644 index 50f67c9..0000000 --- a/assets/icons/yandex_id_logo_ru_light.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/packaging/build-deb.sh b/packaging/build-deb.sh index 8b2664e..da914ef 100755 --- a/packaging/build-deb.sh +++ b/packaging/build-deb.sh @@ -13,10 +13,5 @@ else fi cd "$PROJECT_DIR" -# 1. Main player binary: zero WebKit2GTK / GTK DT_NEEDED entries -cargo build --release --bin yandex-music-rs -# 2. Isolated Linux OAuth WebView helper binary -cargo build --release --features linux-webview --bin yandex-music-auth -# 3. Package both binaries into .deb (cargo-deb resolves target/release/* via CARGO_TARGET_DIR) -cargo deb --no-build --output "$PROJECT_DIR/target/debian/" +cargo deb --output "$PROJECT_DIR/target/debian/" ls -lh "$PROJECT_DIR/target/debian/"*.deb diff --git a/src/api/demo_data.rs b/src/api/demo_data.rs index 2a20ae1..d49e0f7 100644 --- a/src/api/demo_data.rs +++ b/src/api/demo_data.rs @@ -92,7 +92,6 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "rel_1".into(), title: "YAMAKASI (Deluxe)".into(), - version: None, year: Some(2026), cover_uri: None, artists: vec![artist("a1", "Miyagi & Эндшпиль")], @@ -104,7 +103,6 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "rel_2".into(), title: "Ночной проспект".into(), - version: None, year: Some(2026), cover_uri: None, artists: vec![artist("a2", "Zivert")], @@ -116,7 +114,6 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "rel_3".into(), title: "Зеркала и эхо".into(), - version: None, year: Some(2026), cover_uri: None, artists: vec![artist("a3", "Три дня дождя")], @@ -128,7 +125,6 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "rel_4".into(), title: "Midnight Horizons".into(), - version: None, year: Some(2026), cover_uri: None, artists: vec![artist("a4", "The Weeknd")], @@ -140,7 +136,6 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "rel_5".into(), title: "Синтетика".into(), - version: None, year: Some(2026), cover_uri: None, artists: vec![artist("a5", "Saluki")], @@ -152,7 +147,6 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "rel_6".into(), title: "Тихий океан".into(), - version: None, year: Some(2026), cover_uri: None, artists: vec![artist("a6", "Баста")], @@ -240,7 +234,6 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "pod_1".into(), title: "Подкаст «Запуск завтра»".into(), - version: None, year: Some(2026), cover_uri: None, artists: vec![artist("p1", "Самат Галимов")], @@ -252,7 +245,6 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "pod_2".into(), title: "Дневники Лоры Палны".into(), - version: None, year: Some(2026), cover_uri: None, artists: vec![artist("p2", "Студия Терменвокс")], @@ -264,7 +256,6 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "pod_3".into(), title: "Краткая история времени".into(), - version: None, year: Some(2025), cover_uri: None, artists: vec![artist("p3", "Стивен Хокинг (Аудиокнига)")], @@ -276,7 +267,6 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "pod_4".into(), title: "Хоббит, или Туда и обратно".into(), - version: None, year: Some(2025), cover_uri: None, artists: vec![artist("p4", "Дж. Р. Р. Толкин")], @@ -340,8 +330,6 @@ pub fn demo_landing() -> LandingData { vibe_tracks, podcasts, kids_playlists, - rich_new_releases: Vec::new(), - vibe_pick_tabs: Vec::new(), } } @@ -366,7 +354,6 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, }, Track { id: "demo_2".into(), @@ -387,7 +374,6 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, }, Track { id: "demo_3".into(), @@ -408,7 +394,6 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, }, Track { id: "demo_4".into(), @@ -429,7 +414,6 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, }, Track { id: "demo_5".into(), @@ -450,7 +434,6 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, }, Track { id: "demo_6".into(), @@ -471,7 +454,6 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, }, Track { id: "demo_7".into(), @@ -492,7 +474,6 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, }, Track { id: "demo_8".into(), @@ -513,7 +494,6 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, }, Track { id: "demo_9".into(), @@ -534,7 +514,6 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, }, Track { id: "demo_10".into(), @@ -555,7 +534,6 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, }, ] } @@ -577,7 +555,6 @@ pub fn demo_lyrics(track: &Track) -> TrackLyrics { is_synced: true, lines, writers: Some("Яндекс Музыка Rust (Демо-режим)".into()), - major: None, } } diff --git a/src/api/mod.rs b/src/api/mod.rs index 03dfd2b..5b0951c 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -245,19 +245,12 @@ impl YandexApiClient { .as_str() .filter(|s| !s.is_empty()) .map(|id| format!("https://avatars.yandex.net/get-yapic/{}/islands-200", id)); - let default_email = res["defaultEmail"] - .as_str() - .or_else(|| res["account"]["defaultEmail"].as_str()) - .or_else(|| res["email"].as_str()) - .filter(|s| !s.is_empty()) - .map(String::from); return Ok(UserAccount { uid, login, display_name, has_plus, avatar_uri, - default_email, }); } } @@ -276,19 +269,12 @@ impl YandexApiClient { let avatar_uri = acc["avatarHash"] .as_str() .map(|h| format!("https://avatars.yandex.net/get-yapic/{}/islands-200", h)); - let default_email = acc["defaultEmail"] - .as_str() - .or_else(|| res["defaultEmail"].as_str()) - .or_else(|| acc["email"].as_str()) - .filter(|s| !s.is_empty()) - .map(String::from); Ok(UserAccount { uid, login, display_name, has_plus, avatar_uri, - default_email, }) } @@ -398,74 +384,6 @@ impl YandexApiClient { } } - // Hydrate official 5.129.0 `For You` skeleton (`NEW_RELEASES` + `WAVES` / `SETS_BY_WAVES`) - let skel_ids: &[&str] = if self.has_token() { - &["web_main", "main"] - } else { - &["web_main", "main_nologin"] - }; - let mut main_skeleton: Option = None; - for sid in skel_ids { - if let Ok(sk) = self.fetch_landing_skeleton(sid).await { - if !collect_skeleton_blocks(&sk).is_empty() { - main_skeleton = Some(sk); - break; - } - } - } - if let Some(sk) = main_skeleton { - let blocks = collect_skeleton_blocks(&sk); - for block in blocks { - let btype = block["type"].as_str().unwrap_or("").to_ascii_uppercase(); - let bid = block["id"].as_str().unwrap_or("").to_ascii_lowercase(); - let uri_lc = block["source"]["uri"] - .as_str() - .or_else(|| block["data"]["source"]["uri"].as_str()) - .unwrap_or("") - .to_ascii_lowercase(); - - let is_new_releases = btype.contains("NEW_RELEASES") - || bid.contains("new_releases") - || bid.contains("new-releases") - || uri_lc.contains("new-releases") - || uri_lc.contains("new_releases"); - let is_waves = btype == "WAVES" - || btype.contains("SETS_BY_WAVES") - || bid.contains("waves") - || uri_lc.contains("waves"); - - if is_new_releases && landing.rich_new_releases.is_empty() { - let payload = if let Some(path) = build_skeleton_block_path(block) { - self.get_json(&path).await.ok() - } else { - Some(block.clone()) - }; - if let Some(val) = payload { - let rich = parse_new_releases_block(&val); - if !rich.is_empty() { - if landing.new_releases.is_empty() { - landing.new_releases = - rich.iter().map(|r| r.album.clone()).collect(); - } - landing.rich_new_releases = rich; - } - } - } else if is_waves && landing.vibe_pick_tabs.is_empty() { - let payload = if let Some(path) = build_skeleton_block_path(block) { - self.get_json(&path).await.ok() - } else { - Some(block.clone()) - }; - if let Some(val) = payload { - let tabs = parse_vibe_picks_block(&val); - if !tabs.is_empty() { - landing.vibe_pick_tabs = tabs; - } - } - } - } - } - // Try starting a real 5.128.0 Rotor Session (`POST /rotor/session/new`) if authenticated if self.has_token() { if let Ok(session) = self @@ -509,128 +427,57 @@ impl YandexApiClient { pub async fn fetch_podcast_chart(&self) -> Result> { let res = self.get_json("/chart/podcasts").await?; - Ok(extract_non_music_albums(&res)) - } - - /// Official 5.129.0 Books & Podcasts landing (`GET /landing/skeleton/non_music` + block fetches + `/chart/podcasts` fallback). - pub async fn fetch_non_music_landing( - &self, - ) -> Result<(Vec, Vec)> { - let mut sections: Vec = Vec::new(); - let mut flat_albums: Vec = Vec::new(); - let mut seen_album_ids: HashSet = HashSet::new(); - - let skel_res = match self.fetch_landing_skeleton("non_music").await { - Ok(v) => Ok(v), - Err(_) => self.fetch_landing_skeleton("non_music_nologin").await, - }; - - if let Ok(sk) = skel_res { - let blocks = collect_skeleton_blocks(&sk); - let mut fetched_blocks = 0usize; - for (idx, block) in blocks.into_iter().enumerate() { - if fetched_blocks >= 10 { - break; - } - let bid = block["id"] - .as_str() - .map(String::from) - .unwrap_or_else(|| format!("non_music_{}", idx)); - let btype = block["type"].as_str().unwrap_or("").to_string(); - let header_title = block["title"] - .as_str() - .or_else(|| block["data"]["title"].as_str()) - .or_else(|| block["source"]["title"].as_str()) - .unwrap_or("") - .to_string(); - - let payload = if let Some(path) = build_skeleton_block_path(block) { - fetched_blocks += 1; - match self.get_json(&path).await { - Ok(v) => v, - Err(_) => continue, - } - } else if block.get("data").map_or(false, Value::is_object) - || block.get("items").map_or(false, Value::is_array) - { - block.clone() - } else { - continue; - }; - - if let Some(sec) = parse_non_music_block(&bid, &header_title, &btype, &payload) { - for alb in &sec.albums { - if seen_album_ids.insert(alb.id.clone()) { - flat_albums.push(alb.clone()); - } - } - sections.push(sec); - } - } - } - - // Always merge `/chart/podcasts` if flat_albums is empty or no chart section was returned - if let Ok(chart_pods) = self.fetch_podcast_chart().await { - if !chart_pods.is_empty() { - let mut added_any = false; - for alb in &chart_pods { - if seen_album_ids.insert(alb.id.clone()) { - flat_albums.push(alb.clone()); - added_any = true; - } - } - if sections.is_empty() || (added_any && !sections.iter().any(|s| s.block_type.to_ascii_uppercase().contains("CHART"))) { - sections.push(NonMusicSection { - id: "podcast_chart".into(), - title: if self.is_ru_lang() { - "Чарт подкастов".into() - } else { - "Podcasts Chart".into() - }, - block_type: "CHART_ALBUMS".into(), - albums: chart_pods, - playlists: Vec::new(), - }); - } - } - } - - Ok((sections, flat_albums)) - } - - fn is_ru_lang(&self) -> bool { - self.language.to_ascii_lowercase().starts_with("ru") + let arr = res["podcasts"] + .as_array() + .or_else(|| res["albums"].as_array()) + .or_else(|| res.as_array()); + Ok(arr + .map(|a| a.iter().filter_map(parse_album).collect()) + .unwrap_or_default()) } pub async fn fetch_concerts_feed(&self) -> Result> { - if let Ok(res) = self.get_json("/concerts/feed").await { - let parsed = parse_concerts_feed_response(&res); - if !parsed.is_empty() { - return Ok(parsed); - } - } - - // Automatic fallback: `GET /landing/skeleton/concerts` + concert blocks (`source.uri`) - let sk = self.fetch_landing_skeleton("concerts").await?; - let mut out: Vec = Vec::new(); - let mut seen_ids: HashSet = HashSet::new(); - let mut fetched = 0usize; - for block in collect_skeleton_blocks(&sk) { - if fetched >= 6 { - break; - } - let payload = if let Some(path) = build_skeleton_block_path(block) { - fetched += 1; - match self.get_json(&path).await { - Ok(v) => v, - Err(_) => continue, - } - } else { - block.clone() - }; - for item in parse_concerts_feed_response(&payload) { - if seen_ids.insert(item.id.clone()) { - out.push(item); + let res = self.get_json("/concerts/feed").await?; + let mut out = Vec::new(); + let list = res["concerts"] + .as_array() + .or_else(|| res["items"].as_array()) + .or_else(|| res.as_array()); + if let Some(arr) = list { + for item in arr { + let c = if item.get("concert").is_some() { + &item["concert"] + } else { + item + }; + if let Some(id) = value_id(&c["id"]) { + out.push(ConcertItem { + id, + title: c["concertTitle"] + .as_str() + .or_else(|| c["title"].as_str()) + .unwrap_or("Concert") + .to_string(), + artist_name: c["artist"]["name"] + .as_str() + .or_else(|| c["artistName"].as_str()) + .unwrap_or("") + .to_string(), + city: c["city"].as_str().unwrap_or("").to_string(), + place: c["place"].as_str().unwrap_or("").to_string(), + date: c["datetime"] + .as_str() + .or_else(|| c["date"].as_str()) + .unwrap_or("") + .to_string(), + cover_uri: c["images"] + .as_array() + .and_then(|a| a.first()) + .and_then(|s| s.as_str()) + .or_else(|| c["artist"]["cover"]["uri"].as_str()) + .map(String::from), + afisha_url: c["afishaUrl"].as_str().map(String::from), + }); } } } @@ -670,7 +517,7 @@ impl YandexApiClient { let res = self.get_json("/pins").await?; let ru = self.language == "ru"; let mut out = Vec::new(); - let mut seen_keys: HashSet<(String, String)> = HashSet::new(); + let mut seen_likes = false; let arr = res["pins"].as_array().or_else(|| res.as_array()); if let Some(items) = arr { for item in items { @@ -679,37 +526,30 @@ impl YandexApiClient { match kind { "playlist" | "playlist_item" | "liked_playlist_item" | "personal_playlist_item" => { if let Some(pl) = parse_playlist(data) { - // Only explicit `liked_playlist_item` is guaranteed to be the user's own system Favorites. - // A friend's "Мне нравится" playlist ALSO has `pl.kind == "3"` (with a different `owner_uid`), - // so preserve `owner_uid:kind` here and let `AppState::normalize_pins` collapse only `my_uid:3`! - let is_system_likes = kind == "liked_playlist_item"; - let pin_kind = if is_system_likes { - "likes".to_string() - } else { - "playlist".to_string() - }; - let pin_id = if is_system_likes { - "likes".to_string() - } else { - format!("{}:{}", pl.owner_uid, pl.kind) - }; - if !seen_keys.insert((pin_kind.clone(), pin_id.clone())) { - continue; + let is_likes = pl.kind == "3" + || kind == "liked_playlist_item" + || pl.title == "Мне нравится" + || pl.title == "My Favorites"; + if is_likes { + if seen_likes { + continue; + } + seen_likes = true; } - let likes_title = if ru { "Мне нравится" } else { "My Favorites" }; - let title = if is_system_likes - || (pl.kind == "3" && pl.title.trim().is_empty()) - { - likes_title.into() - } else { - pl.title - }; out.push(PinnedItem { - id: pin_id, - kind: pin_kind, - title, + id: if is_likes { + "likes".into() + } else { + format!("{}:{}", pl.owner_uid, pl.kind) + }, + kind: if is_likes { "likes".into() } else { "playlist".into() }, + title: if is_likes { + if ru { "Мне нравится".into() } else { "My Favorites".into() } + } else { + pl.title + }, subtitle: if ru { "Плейлист".into() } else { "Playlist".into() }, - cover_uri: if is_system_likes { None } else { pl.cover_uri }, + cover_uri: if is_likes { None } else { pl.cover_uri }, owner_uid: Some(pl.owner_uid), }); } @@ -1374,7 +1214,7 @@ impl YandexApiClient { .as_array() .map(|arr| { arr.iter() - .take(5000) + .take(150) .filter_map(|t| { let tid = value_id(&t["id"])?; if let Some(aid) = value_id(&t["albumId"]) { @@ -1391,25 +1231,7 @@ impl YandexApiClient { return Ok(Vec::new()); } - // Hydrate ALL liked tracks in batches of 100 (up to 4 concurrent batches) preserving exact order! - let chunks: Vec> = ids.chunks(100).map(|c| c.to_vec()).collect(); - let mut all_tracks: Vec = Vec::with_capacity(ids.len()); - for group in chunks.chunks(4) { - let mut handles = Vec::with_capacity(group.len()); - for chunk in group { - let api = self.clone(); - let batch = chunk.clone(); - handles.push(tokio::spawn(async move { - api.fetch_tracks_by_ids_chunk(&batch).await - })); - } - for h in handles { - if let Ok(Ok(mut batch_tracks)) = h.await { - all_tracks.append(&mut batch_tracks); - } - } - } - Ok(all_tracks) + self.fetch_tracks_by_ids(&ids).await } pub async fn fetch_disliked_track_ids(&self, uid: u64) -> Result> { @@ -1424,22 +1246,6 @@ impl YandexApiClient { /// Primary 5.128.0 batch track hydration: `PUT /tracks/v2/tracks/get-batch`, fallback `POST /tracks` pub async fn fetch_tracks_by_ids(&self, ids: &[String]) -> Result> { - if ids.is_empty() { - return Ok(Vec::new()); - } - if ids.len() <= 100 { - return self.fetch_tracks_by_ids_chunk(ids).await; - } - let mut out = Vec::with_capacity(ids.len()); - for chunk in ids.chunks(100) { - if let Ok(mut batch) = self.fetch_tracks_by_ids_chunk(chunk).await { - out.append(&mut batch); - } - } - Ok(out) - } - - async fn fetch_tracks_by_ids_chunk(&self, ids: &[String]) -> Result> { if ids.is_empty() { return Ok(Vec::new()); } @@ -1746,200 +1552,102 @@ impl YandexApiClient { Ok(out) } - pub async fn fetch_albums_by_ids(&self, ids: &[String]) -> Result> { - if ids.is_empty() { - return Ok(Vec::new()); - } - let mut out = Vec::with_capacity(ids.len()); - let mut seen = HashSet::new(); - for chunk in ids.chunks(100) { - let joined = chunk.join(","); - if let Ok(res) = self - .post_form("/albums", &[("album-ids", joined)]) - .await - { - let arr = res.as_array().or_else(|| res["albums"].as_array()); - if let Some(items) = arr { - for item in items { - if let Some(alb) = parse_album(item) { - if seen.insert(alb.id.clone()) { - out.push(alb); - } - } - } - } - } - } - Ok(out) - } - - pub async fn fetch_artists_by_ids(&self, ids: &[String]) -> Result> { - if ids.is_empty() { - return Ok(Vec::new()); - } - let mut out = Vec::with_capacity(ids.len()); - let mut seen = HashSet::new(); - for chunk in ids.chunks(100) { - let joined = chunk.join(","); - if let Ok(res) = self - .post_form("/artists", &[("artist-ids", joined)]) - .await - { - let arr = res.as_array().or_else(|| res["artists"].as_array()); - if let Some(items) = arr { - for item in items { - if let Some(art) = parse_artist(item) { - if seen.insert(art.id.clone()) { - out.push(art); - } - } - } - } - } - } - Ok(out) - } - pub async fn fetch_liked_albums(&self, uid: u64) -> Result> { - let mut out: Vec = Vec::new(); - let mut seen_ids: HashSet = HashSet::new(); - let mut bare_ids: Vec = Vec::new(); - let mut seen_bare: HashSet = HashSet::new(); - - for page in 0..5u32 { - let path = format!( - "/users/{}/likes/albums/page?rich=true&metaType=music&page={}&pageSize=100", - uid, page - ); - let Ok(res) = self.get_json(&path).await else { - break; - }; - let (raw_count, page_albs, page_bare) = parse_liked_albums_entries(&res); - for alb in page_albs { - if seen_ids.insert(alb.id.clone()) { + let res = match self + .get_json(&format!( + "/users/{}/likes/albums/page?rich=true&page=0&pageSize=100", + uid + )) + .await + { + Ok(v) => v, + Err(_) => { + self.get_json(&format!("/users/{}/likes/albums?rich=true", uid)) + .await? + } + }; + let arr = res["albums"] + .as_array() + .or_else(|| res["items"].as_array()) + .or_else(|| res.as_array()); + let mut out = Vec::new(); + if let Some(items) = arr { + for item in items { + let node = if item.get("album").is_some() { + &item["album"] + } else { + item + }; + if let Some(alb) = parse_album(node) { out.push(alb); } } - for bid in page_bare { - if !seen_ids.contains(&bid) && seen_bare.insert(bid.clone()) { - bare_ids.push(bid); - } - } - if raw_count < 100 { - break; - } } - - // Fallback if `/likes/albums/page` failed or returned nothing - if out.is_empty() && bare_ids.is_empty() { - if let Ok(res) = self - .get_json(&format!("/users/{}/likes/albums?rich=true", uid)) - .await - { - let (_, page_albs, page_bare) = parse_liked_albums_entries(&res); - for alb in page_albs { - if seen_ids.insert(alb.id.clone()) { - out.push(alb); - } - } - for bid in page_bare { - if !seen_ids.contains(&bid) && seen_bare.insert(bid.clone()) { - bare_ids.push(bid); - } - } - } - } - - if !bare_ids.is_empty() { - if let Ok(hydrated) = self.fetch_albums_by_ids(&bare_ids).await { - for alb in hydrated { - if seen_ids.insert(alb.id.clone()) { - out.push(alb); - } - } - } - } - Ok(out) } pub async fn fetch_liked_artists(&self, uid: u64) -> Result> { - let mut out: Vec = Vec::new(); - let mut seen_ids: HashSet = HashSet::new(); - let mut bare_ids: Vec = Vec::new(); - let mut seen_bare: HashSet = HashSet::new(); - - for page in 0..5u32 { - let path = format!( - "/users/{}/likes/artists/page?page={}&pageSize=100", - uid, page - ); - let Ok(res) = self.get_json(&path).await else { - break; - }; - let (raw_count, page_arts, page_bare) = parse_liked_artists_entries(&res); - for art in page_arts { - if seen_ids.insert(art.id.clone()) { + let res = match self + .get_json(&format!( + "/users/{}/likes/artists/page?page=0&pageSize=100", + uid + )) + .await + { + Ok(v) => v, + Err(_) => { + self.get_json(&format!("/users/{}/likes/artists", uid)) + .await? + } + }; + let arr = res["artists"] + .as_array() + .or_else(|| res["items"].as_array()) + .or_else(|| res.as_array()); + let mut out = Vec::new(); + if let Some(items) = arr { + for item in items { + let node = if item.get("artist").is_some() { + &item["artist"] + } else { + item + }; + if let Some(art) = parse_artist(node) { out.push(art); } } - for bid in page_bare { - if !seen_ids.contains(&bid) && seen_bare.insert(bid.clone()) { - bare_ids.push(bid); - } - } - if raw_count < 100 { - break; - } } - - // Fallback if `/likes/artists/page` failed or returned empty! - if out.is_empty() && bare_ids.is_empty() { - if let Ok(res) = self - .get_json(&format!("/users/{}/likes/artists", uid)) - .await - { - let (_, page_arts, page_bare) = parse_liked_artists_entries(&res); - for art in page_arts { - if seen_ids.insert(art.id.clone()) { - out.push(art); - } - } - for bid in page_bare { - if !seen_ids.contains(&bid) && seen_bare.insert(bid.clone()) { - bare_ids.push(bid); - } - } - } - } - - if !bare_ids.is_empty() { - if let Ok(hydrated) = self.fetch_artists_by_ids(&bare_ids).await { - for art in hydrated { - if seen_ids.insert(art.id.clone()) { - out.push(art); - } - } - } - } - Ok(out) } pub async fn fetch_bookshelf_liked(&self) -> Result> { - let mut out: Vec = Vec::new(); - let mut seen: HashSet = HashSet::new(); - - // Fetch BOTH recently-played (for "Continue listening") and liked bookshelf items! - for path in [ - "/non-music/bookshelf/recently-played?page=0&pageSize=50", - "/non-music/bookshelf/liked?page=0&pageSize=50", - ] { - if let Ok(res) = self.get_json(path).await { - for alb in extract_non_music_albums(&res) { - if seen.insert(alb.id.clone()) { - out.push(alb); - } + let res = match self + .get_json("/non-music/bookshelf/liked?page=0&pageSize=50") + .await + { + Ok(v) => v, + Err(_) => { + self.get_json("/non-music/bookshelf/recently-played?page=0&pageSize=50") + .await? + } + }; + let arr = res["items"] + .as_array() + .or_else(|| res["albums"].as_array()) + .or_else(|| res["podcasts"].as_array()) + .or_else(|| res.as_array()); + let mut out = Vec::new(); + if let Some(items) = arr { + for item in items { + let node = if item.get("album").is_some() { + &item["album"] + } else if item.get("data").is_some() { + &item["data"] + } else { + item + }; + if let Some(alb) = parse_album(node) { + out.push(alb); } } } @@ -2086,7 +1794,10 @@ impl YandexApiClient { .as_array() .map(|a| a.iter().filter_map(parse_track).collect()) .unwrap_or_default(); - let albums = parse_artist_detail_albums(&res); + let albums = res["albums"] + .as_array() + .map(|a| a.iter().filter_map(parse_album).collect()) + .unwrap_or_default(); let similar_artists = res["similarArtists"] .as_array() .map(|a| a.iter().filter_map(parse_artist).collect()) @@ -2515,62 +2226,15 @@ impl YandexApiClient { quality: AudioQuality, cache_dir: &Path, ) -> Result { - let never_cancel = std::sync::atomic::AtomicBool::new(false); - self.download_track_to_cache_with_progress(track, quality, cache_dir, &never_cancel, |_| {}) - .await - } - - /// Streaming variant of `download_track_to_cache` reporting throttled `0.0..=1.0` progress - /// and aborting immediately if `cancel` is signaled. - pub async fn download_track_to_cache_with_progress( - &self, - track: &Track, - quality: AudioQuality, - cache_dir: &Path, - cancel: &std::sync::atomic::AtomicBool, - mut on_progress: F, - ) -> Result { - use std::sync::atomic::Ordering; - - if cancel.load(Ordering::Relaxed) { - return Err(anyhow!("Download cancelled")); - } let stream = self.resolve_track_stream(&track.id, quality).await?; - if cancel.load(Ordering::Relaxed) { - return Err(anyhow!("Download cancelled")); - } - on_progress(0.06); - - let mut resp = self.http.get(&stream.url).send().await?; + let resp = self.http.get(&stream.url).send().await?; if !resp.status().is_success() { return Err(anyhow!( "Offline download HTTP {}", resp.status().as_u16() )); } - - let total_len = resp.content_length().unwrap_or(0); - let mut bytes = Vec::with_capacity((total_len as usize).min(64 * 1024 * 1024)); - let mut last_reported = 0.06f32; - while let Some(chunk) = resp.chunk().await? { - if cancel.load(Ordering::Relaxed) { - return Err(anyhow!("Download cancelled")); - } - bytes.extend_from_slice(&chunk); - let frac = if total_len > 0 { - 0.08 + 0.87 * (bytes.len() as f32 / total_len as f32).min(1.0) - } else { - (last_reported + 0.08).min(0.90) - }; - if frac - last_reported >= 0.05 { - last_reported = frac; - on_progress(frac); - } - } - if cancel.load(Ordering::Relaxed) { - return Err(anyhow!("Download cancelled")); - } - + let mut bytes = resp.bytes().await?.to_vec(); if let Some(ref key_hex) = stream.decrypt_key_hex { if !signing::decrypt_encraw_in_place(&mut bytes, key_hex) { return Err(anyhow!("Failed to decrypt encraw offline stream")); @@ -2584,13 +2248,12 @@ impl YandexApiClient { } else { "mp3" }; - tokio::fs::create_dir_all(cache_dir).await?; + std::fs::create_dir_all(cache_dir)?; let safe_id = sanitize_track_filename(&track.id); let final_path = cache_dir.join(format!("{}.{}", safe_id, ext)); let part_path = cache_dir.join(format!("{}.{}.part", safe_id, ext)); - tokio::fs::write(&part_path, &bytes).await?; - tokio::fs::rename(&part_path, &final_path).await?; - on_progress(1.0); + std::fs::write(&part_path, &bytes)?; + std::fs::rename(&part_path, &final_path)?; Ok(final_path) } @@ -2642,7 +2305,6 @@ impl YandexApiClient { is_synced: false, lines, writers, - major: None, }); } } @@ -2680,11 +2342,6 @@ impl YandexApiClient { .filter(|u| !u.is_empty()) .ok_or_else(|| anyhow!("No lyrics downloadUrl ({})", format))?; let writers = parse_writers_field(&res["writers"]); - let major = res["major"]["prettyName"] - .as_str() - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(String::from); let resp = self.http.get(download_url).send().await?; if !resp.status().is_success() { return Err(anyhow!( @@ -2703,728 +2360,8 @@ impl YandexApiClient { is_synced: parsed_synced && format == "LRC", lines, writers, - major, }) } - - // ========================================================================= - // 10. OFFICIAL 5.129.0 AI WORDS CARDS (`POST /words/cards`, `/words/big-cards`, `PUT /words/cards/feedback`) - // ========================================================================= - - pub async fn fetch_words_cards( - &self, - track_ids: &[String], - wave_seeds: Option<&[String]>, - ) -> Result)>> { - if !self.has_token() || track_ids.is_empty() { - return Ok(Vec::new()); - } - let mut body = json!({ - "trackIds": track_ids, - "viewedCards": [], - "viewedBigCards": [], - "actionProvider": "alice", - }); - if let Some(seeds) = wave_seeds { - if !seeds.is_empty() { - body["waveContext"] = json!({ "seeds": seeds }); - } - } - let res = self.post_json("/words/cards", &body, false).await?; - Ok(parse_words_cards_response(&res, track_ids)) - } - - pub async fn fetch_words_big_card( - &self, - big_card_id: &str, - track_id: &str, - card_id: &str, - ) -> Result> { - if !self.has_token() || big_card_id.is_empty() { - return Ok(None); - } - let clean_track_id = track_id.split(':').next().unwrap_or(track_id); - let body = json!({ - "bigCardIds": [big_card_id], - "bigCardContexts": [{ - "bigCardId": big_card_id, - "trackId": clean_track_id, - "cardId": card_id, - }], - "actionProvider": "alice", - }); - let res = self.post_json("/words/big-cards", &body, false).await?; - Ok(parse_words_big_card_response(&res)) - } - - pub async fn send_words_feedback(&self, card_id: &str, feedback_state: &str) -> Result<()> { - if !self.has_token() || card_id.is_empty() { - return Ok(()); - } - let body = json!({ - "feedback": [{ - "id": card_id, - "feedbackState": feedback_state, - }], - }); - let _ = self.put_json("/words/cards/feedback", &body).await?; - Ok(()) - } -} - -fn parse_words_card_source(v: &Value) -> Option { - let title = v["title"].as_str().map(str::trim).filter(|s| !s.is_empty())?.to_string(); - let url = v["url"] - .as_str() - .or_else(|| v["weblink"].as_str()) - .or_else(|| v["link"].as_str()) - .map(str::trim) - .filter(|s| !s.is_empty())? - .to_string(); - let favicon_url = v["faviconUrl"] - .as_str() - .or_else(|| v["favicon_url"].as_str()) - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(String::from); - Some(WordsCardSource { - title, - url, - favicon_url, - }) -} - -fn parse_words_card_entry(item: &Value, clean_track_id: &str) -> Option { - let card_obj = if item.get("card").map_or(false, Value::is_object) { - &item["card"] - } else { - item - }; - let id = value_id(&card_obj["id"]).or_else(|| value_id(&item["id"]))?; - let text = card_obj["text"] - .as_str() - .map(str::trim) - .filter(|s| !s.is_empty())? - .to_string(); - let tags = card_obj["tags"] - .as_array() - .map(|arr| { - arr.iter() - .filter_map(|t| t.as_str().map(String::from)) - .collect() - }) - .unwrap_or_default(); - let action = card_obj.get("action").and_then(|a| { - let title = a["title"].as_str().map(str::trim).filter(|s| !s.is_empty())?; - let url = a["weblink"] - .as_str() - .or_else(|| a["link"].as_str()) - .or_else(|| a["url"].as_str()) - .map(str::trim) - .filter(|s| !s.is_empty())?; - Some(WordsCardAction { - title: title.to_string(), - url: url.to_string(), - }) - }); - let actions = card_obj["actions"] - .as_array() - .map(|arr| arr.iter().filter_map(parse_words_card_source).collect()) - .unwrap_or_default(); - let big_card_ids = card_obj["bigCardIds"] - .as_array() - .map(|arr| arr.iter().filter_map(value_id).collect()) - .unwrap_or_default(); - let feedback_state = item["feedbackState"] - .as_str() - .or_else(|| card_obj["feedbackState"].as_str()) - .map(str::trim) - .filter(|s| !s.is_empty() && !s.eq_ignore_ascii_case("neutral")) - .map(String::from); - - Some(WordsCard { - id, - track_id: clean_track_id.to_string(), - text, - tags, - action, - actions, - big_card_ids, - feedback_state, - }) -} - -fn parse_words_cards_response( - val: &Value, - requested_ids: &[String], -) -> Vec<(String, Option)> { - let mut parsed_map: std::collections::HashMap> = - std::collections::HashMap::new(); - let entries = val - .as_array() - .or_else(|| val["result"].as_array()) - .or_else(|| val["tracks"].as_array()); - if let Some(arr) = entries { - for entry in arr { - let Some(raw_id) = value_id(&entry["id"]).or_else(|| value_id(&entry["trackId"])) - else { - continue; - }; - let clean_id = raw_id.split(':').next().unwrap_or(&raw_id).to_string(); - let mut chosen: Option = None; - if let Some(cards) = entry["cards"].as_array() { - let mut fallback_first: Option = None; - for c in cards { - if let Some(wc) = parse_words_card_entry(c, &clean_id) { - if !wc.is_disliked() { - chosen = Some(wc); - break; - } - if fallback_first.is_none() { - fallback_first = Some(wc); - } - } - } - if chosen.is_none() { - chosen = fallback_first; - } - } - parsed_map.insert(clean_id, chosen); - } - } - - let mut out = Vec::new(); - let mut seen = HashSet::new(); - for req in requested_ids { - let clean = req.split(':').next().unwrap_or(req).to_string(); - if seen.insert(clean.clone()) { - let card = parsed_map.remove(&clean).flatten(); - out.push((clean, card)); - } - } - for (id, card) in parsed_map { - if seen.insert(id.clone()) { - out.push((id, card)); - } - } - out -} - -fn parse_words_big_card_response(val: &Value) -> Option { - let first = val - .as_array() - .and_then(|arr| arr.first()) - .or_else(|| val["result"].as_array().and_then(|arr| arr.first())) - .unwrap_or(val); - let obj = if first.get("bigCard").map_or(false, Value::is_object) { - &first["bigCard"] - } else if first.get("card").map_or(false, Value::is_object) { - &first["card"] - } else { - first - }; - let id = value_id(&obj["id"]).or_else(|| value_id(&first["id"]))?; - let text = obj["text"] - .as_str() - .map(str::trim) - .filter(|s| !s.is_empty())? - .to_string(); - let actions = obj["actions"] - .as_array() - .map(|arr| arr.iter().filter_map(parse_words_card_source).collect()) - .unwrap_or_default(); - Some(WordsBigCard { id, text, actions }) -} - -// ============================================================================= -// Skeleton, Concerts, Non-Music, NewReleases & Waves Pure Parsers -// ============================================================================= - -fn collect_skeleton_blocks<'a>(skeleton: &'a Value) -> Vec<&'a Value> { - let mut blocks: Vec<&'a Value> = Vec::new(); - let root = skeleton.get("result").unwrap_or(skeleton); - if let Some(arr) = root["blocks"].as_array() { - for b in arr { - blocks.push(b); - if let Some(nested) = b["blocks"].as_array() { - blocks.extend(nested.iter()); - } - } - } - if let Some(tabs) = root["tabs"].as_array() { - for tab in tabs { - if let Some(arr) = tab["blocks"].as_array() { - blocks.extend(arr.iter()); - } - if let Some(arr) = tab["tab"]["blocks"].as_array() { - blocks.extend(arr.iter()); - } - } - } - blocks -} - -fn build_skeleton_block_path(block: &Value) -> Option { - let source = block - .get("source") - .filter(|v| v.is_object()) - .or_else(|| block["data"].get("source").filter(|v| v.is_object()))?; - let raw_uri = source["uri"].as_str().map(str::trim).filter(|s| !s.is_empty())?; - let mut path = if let Some(stripped) = raw_uri.strip_prefix("https://api.music.yandex.net") { - stripped.to_string() - } else if raw_uri.starts_with('/') { - raw_uri.to_string() - } else { - format!("/{}", raw_uri) - }; - let count_web = source["countWeb"] - .as_u64() - .or_else(|| source["count"].as_u64()) - .or_else(|| block["data"]["countWeb"].as_u64()); - if let Some(n) = count_web { - if n > 0 && !path.contains("count=") && !path.contains("limit=") { - let sep = if path.contains('?') { '&' } else { '?' }; - path.push_str(&format!("{}count={}", sep, n)); - } - } - Some(path) -} - -fn parse_album_with_fallback_artists( - album_node: &Value, - artists_fallback: Option<&Value>, -) -> Option { - let mut alb = parse_album(album_node)?; - if alb.artists.is_empty() { - if let Some(arr) = artists_fallback.and_then(Value::as_array) { - alb.artists = arr.iter().filter_map(parse_artist).collect(); - } - } - Some(alb) -} - -fn extract_non_music_albums(res: &Value) -> Vec { - let mut out: Vec = Vec::new(); - let mut seen: HashSet = HashSet::new(); - let candidates = [ - res["items"].as_array(), - res["data"]["items"].as_array(), - res["chart"]["albums"].as_array(), - res["albums"].as_array(), - res["podcasts"].as_array(), - res["entities"].as_array(), - res.as_array(), - ]; - for arr in candidates.into_iter().flatten() { - for item in arr { - let item_type = item["type"].as_str().unwrap_or(""); - if item_type.eq_ignore_ascii_case("PLAYLIST_ITEM") { - continue; - } - let parsed = if item["data"]["album"].is_object() { - parse_album_with_fallback_artists( - &item["data"]["album"], - item["data"].get("artists"), - ) - } else if item["album"].is_object() { - parse_album_with_fallback_artists(&item["album"], item.get("artists")) - } else if item["data"].is_object() { - parse_album_with_fallback_artists(&item["data"], item["data"].get("artists")) - } else { - parse_album(item) - }; - if let Some(alb) = parsed { - if seen.insert(alb.id.clone()) { - out.push(alb); - } - } - } - } - out -} - -fn parse_non_music_block( - id: &str, - header_title: &str, - block_type: &str, - res: &Value, -) -> Option { - let title = if !header_title.trim().is_empty() { - header_title.trim().to_string() - } else { - res["title"] - .as_str() - .or_else(|| res["data"]["title"].as_str()) - .or_else(|| res["chart"]["title"].as_str()) - .unwrap_or("") - .trim() - .to_string() - }; - - let mut albums: Vec = Vec::new(); - let mut playlists: Vec = Vec::new(); - let mut seen_albums: HashSet = HashSet::new(); - let mut seen_playlists: HashSet = HashSet::new(); - - let lists = [ - res["items"].as_array(), - res["data"]["items"].as_array(), - res["chart"]["albums"].as_array(), - res["albums"].as_array(), - res["podcasts"].as_array(), - res["playlists"].as_array(), - res["entities"].as_array(), - res.as_array(), - ]; - for arr in lists.into_iter().flatten() { - for item in arr { - let item_type = item["type"].as_str().unwrap_or(""); - let is_playlist_item = item_type.eq_ignore_ascii_case("PLAYLIST_ITEM") - || item["data"]["playlist"].is_object() - || item["playlist"].is_object() - || (item.get("kind").is_some() && item.get("owner").is_some()); - - if is_playlist_item { - let pl_node = if item["data"]["playlist"].is_object() { - &item["data"]["playlist"] - } else if item["playlist"].is_object() { - &item["playlist"] - } else if item["data"].is_object() && item["data"].get("kind").is_some() { - &item["data"] - } else { - item - }; - if let Some(pl) = parse_playlist(pl_node) { - let key = format!("{}:{}", pl.owner_uid, pl.kind); - if seen_playlists.insert(key) { - playlists.push(pl); - } - } - continue; - } - - let alb = if item["data"]["album"].is_object() { - parse_album_with_fallback_artists( - &item["data"]["album"], - item["data"].get("artists"), - ) - } else if item["album"].is_object() { - parse_album_with_fallback_artists(&item["album"], item.get("artists")) - } else if item["data"].is_object() { - parse_album_with_fallback_artists(&item["data"], item["data"].get("artists")) - } else { - parse_album(item) - }; - if let Some(a) = alb { - if seen_albums.insert(a.id.clone()) { - albums.push(a); - } - } - } - } - - if albums.is_empty() && playlists.is_empty() { - return None; - } - Some(NonMusicSection { - id: id.to_string(), - title, - block_type: block_type.to_string(), - albums, - playlists, - }) -} - -fn parse_concerts_feed_response(res: &Value) -> Vec { - let mut out = Vec::new(); - let mut seen = HashSet::new(); - let list = res["items"] - .as_array() - .or_else(|| res["concerts"].as_array()) - .or_else(|| res["data"]["items"].as_array()) - .or_else(|| res.as_array()); - let Some(arr) = list else { - return out; - }; - - for item in arr { - let data_node = item - .get("data") - .filter(|v| v.is_object()) - .unwrap_or(item); - let c = data_node - .get("concert") - .filter(|v| v.is_object()) - .or_else(|| item.get("concert").filter(|v| v.is_object())) - .unwrap_or(data_node); - - let Some(id) = value_id(&c["id"]).or_else(|| value_id(&item["id"])) else { - continue; - }; - if !seen.insert(id.clone()) { - continue; - } - - let title = c["concertTitle"] - .as_str() - .or_else(|| c["title"].as_str()) - .unwrap_or("Concert") - .to_string(); - let artist_name = c["artist"]["name"] - .as_str() - .or_else(|| c["artistName"].as_str()) - .or_else(|| data_node["artist"]["name"].as_str()) - .unwrap_or("") - .to_string(); - let city = c["city"].as_str().unwrap_or("").to_string(); - let place = c["place"].as_str().unwrap_or("").to_string(); - let date = c["datetime"] - .as_str() - .or_else(|| c["date"].as_str()) - .unwrap_or("") - .to_string(); - let cover_uri = c["cover"]["uri"] - .as_str() - .filter(|s| !s.is_empty()) - .or_else(|| { - c["images"].as_array().and_then(|a| { - a.first() - .and_then(|v| v.as_str().or_else(|| v["uri"].as_str())) - }) - }) - .or_else(|| c["artist"]["cover"]["uri"].as_str()) - .or_else(|| data_node["cover"]["uri"].as_str()) - .map(String::from); - let cover_color = c["cover"]["color"] - .as_str() - .or_else(|| data_node["cover"]["color"].as_str()) - .filter(|s| !s.is_empty()) - .map(String::from); - - let price_node = data_node - .get("minPrice") - .or_else(|| c.get("minPrice")) - .or_else(|| item.get("minPrice")); - let min_price = price_node.and_then(|p| { - p["value"] - .as_u64() - .or_else(|| p["value"].as_f64().map(|f| f.round() as u64)) - .or_else(|| p.as_u64()) - }); - let currency = price_node - .and_then(|p| p["currency"].as_str()) - .filter(|s| !s.is_empty()) - .map(String::from); - - let cashback_node = c.get("cashback").or_else(|| data_node.get("cashback")); - let cashback_percent = cashback_node - .and_then(|cb| { - cb["valuePercent"] - .as_u64() - .or_else(|| cb["percent"].as_u64()) - }) - .map(|v| v as u32); - let cashback_title = cashback_node - .and_then(|cb| cb["title"].as_str()) - .filter(|s| !s.is_empty()) - .map(String::from); - - let event_kind = c["eventInfo"]["type"] - .as_str() - .or_else(|| c["eventType"].as_str()) - .filter(|s| !s.is_empty()) - .map(String::from); - - let afisha_url = c["afishaUrl"] - .as_str() - .filter(|s| !s.is_empty()) - .map(String::from) - .or_else(|| { - Some(format!( - "https://afisha.yandex.ru/search?text={}", - urlencoding::encode(&title) - )) - }); - - out.push(ConcertItem { - id, - title, - artist_name, - city, - place, - date, - cover_uri, - afisha_url, - min_price, - currency, - cashback_percent, - cashback_title, - cover_color, - event_kind, - }); - } - out -} - -fn parse_new_releases_block(res: &Value) -> Vec { - let mut out = Vec::new(); - let mut seen = HashSet::new(); - let arr = res["newReleases"] - .as_array() - .or_else(|| res["data"]["newReleases"].as_array()) - .or_else(|| res["items"].as_array()) - .or_else(|| res["data"]["items"].as_array()) - .or_else(|| res["albums"].as_array()) - .or_else(|| res.as_array()); - let Some(items) = arr else { - return out; - }; - - for item in items { - let node = item - .get("data") - .filter(|v| v.is_object()) - .unwrap_or(item); - let album_node = if node["album"].is_object() { - &node["album"] - } else { - node - }; - let Some(album) = parse_album_with_fallback_artists(album_node, node.get("artists")) else { - continue; - }; - if !seen.insert(album.id.clone()) { - continue; - } - let artist_cover_uri = node["artists"] - .as_array() - .and_then(|a| a.first()) - .and_then(|ar| { - ar["cover"]["uri"] - .as_str() - .or_else(|| ar["ogImage"].as_str()) - }) - .filter(|s| !s.is_empty()) - .map(String::from) - .or_else(|| album.artists.first().and_then(|a| a.cover_uri.clone())); - let cover_color = node["cover"]["color"] - .as_str() - .or_else(|| album_node["cover"]["color"].as_str()) - .or_else(|| album_node["derivedColors"]["average"].as_str()) - .or_else(|| node["derivedColors"]["average"].as_str()) - .filter(|s| !s.is_empty()) - .map(String::from); - let release_date = node["releaseDate"] - .as_str() - .or_else(|| album_node["releaseDate"].as_str()) - .filter(|s| !s.is_empty()) - .map(String::from); - - out.push(NewReleaseItem { - album, - artist_cover_uri, - cover_color, - release_date, - }); - } - out -} - -fn parse_vibe_picks_block(res: &Value) -> Vec { - let mut tabs = Vec::new(); - let arr = res["waves"] - .as_array() - .or_else(|| res["data"]["waves"].as_array()) - .or_else(|| res["tabs"].as_array()) - .or_else(|| res["data"]["tabs"].as_array()) - .or_else(|| res.as_array()); - let Some(raw_tabs) = arr else { - return tabs; - }; - - for raw_tab in raw_tabs { - let title = raw_tab["title"] - .as_str() - .or_else(|| raw_tab["name"].as_str()) - .unwrap_or("") - .trim() - .to_string(); - let raw_items = raw_tab["items"] - .as_array() - .or_else(|| raw_tab["waves"].as_array()) - .or_else(|| raw_tab["stations"].as_array()); - let Some(items_arr) = raw_items else { - continue; - }; - - let mut parsed_items = Vec::new(); - for raw_item in items_arr { - let obj = raw_item - .get("data") - .filter(|v| v.is_object()) - .or_else(|| raw_item.get("wave").filter(|v| v.is_object())) - .unwrap_or(raw_item); - let Some(item_title) = obj["title"] - .as_str() - .map(str::trim) - .filter(|s| !s.is_empty()) - else { - continue; - }; - let header = obj["header"] - .as_str() - .or_else(|| obj["subtitle"].as_str()) - .unwrap_or("") - .trim() - .to_string(); - let mut seeds: Vec = obj["seeds"] - .as_array() - .map(|a| { - a.iter() - .filter_map(|s| s.as_str().map(String::from)) - .collect() - }) - .unwrap_or_default(); - if seeds.is_empty() { - if let Some(sid) = obj["stationId"].as_str().filter(|s| !s.is_empty()) { - seeds.push(sid.to_string()); - } - } - let color_hex = obj["colors"]["average"] - .as_str() - .or_else(|| obj["color"].as_str()) - .or_else(|| obj["backgroundColor"].as_str()) - .filter(|s| !s.is_empty()) - .map(String::from); - let background_image_url = obj["backgroundImageUrl"] - .as_str() - .or_else(|| obj["backgroundImageUri"].as_str()) - .filter(|s| !s.is_empty()) - .map(String::from); - let image_url = obj["imageUrl"] - .as_str() - .or_else(|| obj["imageUri"].as_str()) - .filter(|s| !s.is_empty()) - .map(String::from); - - parsed_items.push(VibePickItem { - title: item_title.to_string(), - header, - seeds, - color_hex, - background_image_url, - image_url, - }); - } - - if !parsed_items.is_empty() { - tabs.push(VibePickTab { - title, - items: parsed_items, - }); - } - } - tabs } fn parse_writers_field(v: &Value) -> Option { @@ -3481,103 +2418,9 @@ fn parse_artist(v: &Value) -> Option { }) } -fn parse_liked_albums_entries(res: &Value) -> (usize, Vec, Vec) { - let arr = res["albums"] - .as_array() - .or_else(|| res["items"].as_array()) - .or_else(|| res["library"]["albums"].as_array()) - .or_else(|| res.as_array()); - let Some(items) = arr else { - return (0, Vec::new(), Vec::new()); - }; - let mut albs = Vec::new(); - let mut bare_ids = Vec::new(); - for item in items { - let parsed = if item["data"]["album"].is_object() { - parse_album_with_fallback_artists(&item["data"]["album"], item["data"].get("artists")) - } else if item["album"].is_object() { - parse_album_with_fallback_artists(&item["album"], item.get("artists")) - } else if item["data"].is_object() { - parse_album_with_fallback_artists(&item["data"], item["data"].get("artists")) - } else { - parse_album(item) - }; - if let Some(alb) = parsed { - albs.push(alb); - } else if let Some(bid) = value_id(&item["id"]) - .or_else(|| value_id(&item["album"]["id"])) - .or_else(|| value_id(&item["data"]["id"])) - { - bare_ids.push(bid); - } - } - (items.len(), albs, bare_ids) -} - -fn parse_liked_artists_entries(res: &Value) -> (usize, Vec, Vec) { - let arr = res["artists"] - .as_array() - .or_else(|| res["items"].as_array()) - .or_else(|| res["library"]["artists"].as_array()) - .or_else(|| res.as_array()); - let Some(items) = arr else { - return (0, Vec::new(), Vec::new()); - }; - let mut arts = Vec::new(); - let mut bare_ids = Vec::new(); - for item in items { - let node = if item["data"]["artist"].is_object() { - &item["data"]["artist"] - } else if item["artist"].is_object() { - &item["artist"] - } else if item["data"].is_object() { - &item["data"] - } else { - item - }; - if let Some(art) = parse_artist(node) { - arts.push(art); - } else if let Some(bid) = value_id(&node["id"]).or_else(|| value_id(&item["id"])) { - bare_ids.push(bid); - } - } - (items.len(), arts, bare_ids) -} - -fn parse_artist_detail_albums(res: &Value) -> Vec { - let mut out = Vec::new(); - let mut seen_ids = HashSet::new(); - for key in ["albums", "alsoAlbums", "discography"] { - if let Some(arr) = res[key].as_array() { - for item in arr { - if let Some(alb) = parse_album(item) { - if seen_ids.insert(alb.id.clone()) { - out.push(alb); - } - } - if let Some(dups) = item["duplicates"].as_array() { - for dup in dups { - if let Some(alb) = parse_album(dup) { - if seen_ids.insert(alb.id.clone()) { - out.push(alb); - } - } - } - } - } - } - } - out -} - fn parse_album(v: &Value) -> Option { let title = v["title"].as_str()?.to_string(); let id = value_id(&v["id"])?; - let version = v["version"] - .as_str() - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(String::from); let year = v["year"].as_u64().map(|y| y as u32); let cover_uri = v["coverUri"] .as_str() @@ -3599,7 +2442,6 @@ fn parse_album(v: &Value) -> Option { Some(AlbumSummary { id, title, - version, year, cover_uri, artists, @@ -3669,15 +2511,6 @@ fn parse_track(v: &Value) -> Option { .as_str() .or_else(|| v["derivedColors"]["waveText"].as_str()) .map(String::from); - let fade = v.get("fade").and_then(|f| { - let tf = TrackFade { - in_start: f["inStart"].as_f64()? as f32, - in_stop: f["inStop"].as_f64()? as f32, - out_start: f["outStart"].as_f64()? as f32, - out_stop: f["outStop"].as_f64()? as f32, - }; - tf.is_valid().then_some(tf) - }); Some(Track { id, @@ -3698,7 +2531,6 @@ fn parse_track(v: &Value) -> Option { r128_tp, derived_average_hex, derived_accent_hex, - fade, }) } @@ -3878,362 +2710,4 @@ mod tests { assert_eq!(tr.derived_average_hex.as_deref(), Some("#F56E00")); assert!(tr.has_lyrics); } - - #[test] - fn test_parse_words_cards_and_big_card() { - let payload = json!([ - { - "id": "101:555", - "cards": [ - { - "card": { - "id": "card-1", - "text": "Этот трек записали за одну ночь в студии.", - "tags": ["FACT", "HISTORY"], - "action": { - "title": "Подробнее", - "weblink": "https://music.yandex.ru/album/555" - }, - "actions": [ - { - "title": "Wikipedia", - "url": "https://ru.wikipedia.org/wiki/Test", - "faviconUrl": "https://ru.wikipedia.org/favicon.ico" - } - ], - "bigCardIds": ["big-99"] - }, - "feedbackState": "like" - } - ] - }, - { - "id": "102", - "cards": [] - } - ]); - let requested = vec!["101".to_string(), "102".to_string(), "103".to_string()]; - let parsed = parse_words_cards_response(&payload, &requested); - assert_eq!(parsed.len(), 3); - - assert_eq!(parsed[0].0, "101"); - let card = parsed[0].1.as_ref().expect("track 101 should have card"); - assert_eq!(card.id, "card-1"); - assert_eq!(card.track_id, "101"); - assert!(card.is_fact()); - assert!(card.is_liked()); - assert!(!card.is_disliked()); - assert!(card.has_big_card()); - assert_eq!(card.big_card_ids, vec!["big-99"]); - assert_eq!( - card.action.as_ref().map(|a| (a.title.as_str(), a.url.as_str())), - Some(("Подробнее", "https://music.yandex.ru/album/555")) - ); - assert_eq!(card.actions.len(), 1); - assert_eq!(card.actions[0].title, "Wikipedia"); - - assert_eq!(parsed[1], ("102".to_string(), None)); - assert_eq!(parsed[2], ("103".to_string(), None)); - - let big_payload = json!([ - { - "id": "big-99", - "text": "Полная история создания трека в деталях.", - "actions": [ - { "title": "Genius", "url": "https://genius.com/test" } - ] - } - ]); - let big = parse_words_big_card_response(&big_payload).expect("big card should parse"); - assert_eq!(big.id, "big-99"); - assert_eq!(big.text, "Полная история создания трека в деталях."); - assert_eq!(big.actions.len(), 1); - assert_eq!(big.actions[0].url, "https://genius.com/test"); - } - - #[test] - fn test_parse_concerts_feed_nested_data_shape() { - let payload = json!({ - "items": [ - { - "type": "CONCERT", - "data": { - "concert": { - "id": "conc-42", - "concertTitle": "Баста — Большой концерт", - "city": "Москва", - "place": "ВТБ Арена", - "datetime": "2026-11-28T20:00:00+03:00", - "cover": { - "uri": "avatars.yandex.net/get-afisha/1/poster/%%", - "color": "#2A1F3D" - }, - "afishaUrl": "https://afisha.yandex.ru/moscow/concert/basta", - "cashback": { - "title": "Кешбэк 15%", - "valuePercent": 15 - }, - "eventInfo": { "type": "CONCERT" }, - "artist": { "name": "Баста" } - }, - "minPrice": { - "value": 3500, - "currency": "RUB" - } - } - }, - { - "data": { - "concert": { - "id": "conc-99", - "concertTitle": "Indie Night", - "city": "Казань", - "place": "Werk", - "datetime": "2026-12-05T19:00:00+03:00" - } - } - } - ] - }); - - let parsed = parse_concerts_feed_response(&payload); - assert_eq!(parsed.len(), 2); - let first = &parsed[0]; - assert_eq!(first.id, "conc-42"); - assert_eq!(first.title, "Баста — Большой концерт"); - assert_eq!(first.artist_name, "Баста"); - assert_eq!(first.city, "Москва"); - assert_eq!(first.place, "ВТБ Арена"); - assert_eq!(first.min_price, Some(3500)); - assert_eq!(first.currency.as_deref(), Some("RUB")); - assert_eq!(first.cashback_percent, Some(15)); - assert_eq!(first.cashback_title.as_deref(), Some("Кешбэк 15%")); - assert_eq!(first.cover_color.as_deref(), Some("#2A1F3D")); - assert_eq!(first.event_kind.as_deref(), Some("CONCERT")); - assert_eq!( - first.cover_uri.as_deref(), - Some("avatars.yandex.net/get-afisha/1/poster/%%") - ); - - let second = &parsed[1]; - assert_eq!(second.id, "conc-99"); - assert!(second - .afisha_url - .as_deref() - .unwrap_or("") - .starts_with("https://afisha.yandex.ru/search?text=")); - } - - #[test] - fn test_parse_non_music_skeleton_blocks() { - let block_payload = json!({ - "title": "Популярные аудиокниги и подкасты", - "items": [ - { - "type": "NON_MUSIC_ALBUM_ITEM", - "data": { - "album": { - "id": 7001, - "title": "Дюна", - "type": "audiobook", - "trackCount": 24, - "coverUri": "avatars.yandex.net/get-music-content/1/dune/%%" - }, - "artists": [ - { "id": 10, "name": "Фрэнк Герберт" } - ] - } - }, - { - "type": "PLAYLIST_ITEM", - "data": { - "playlist": { - "kind": 1005, - "owner": { "uid": 500, "name": "Редакция" }, - "title": "Лучшие подкасты недели", - "trackCount": 12 - } - } - } - ] - }); - - let sec = parse_non_music_block("nm-1", "", "MIXED_ENTITIES", &block_payload) - .expect("non-music section should parse"); - assert_eq!(sec.title, "Популярные аудиокниги и подкасты"); - assert_eq!(sec.albums.len(), 1); - assert_eq!(sec.albums[0].id, "7001"); - assert_eq!(sec.albums[0].content_type.as_deref(), Some("audiobook")); - assert_eq!(sec.albums[0].artists.len(), 1); - assert_eq!(sec.albums[0].artists[0].name, "Фрэнк Герберт"); - assert_eq!(sec.playlists.len(), 1); - assert_eq!(sec.playlists[0].title, "Лучшие подкасты недели"); - } - - #[test] - fn test_parse_new_releases_and_waves_blocks() { - let nr_payload = json!({ - "newReleases": [ - { - "album": { - "id": 8888, - "title": "Midnight Pulse", - "type": "single", - "coverUri": "avatars.yandex.net/get-music-content/2/mp/%%" - }, - "artists": [ - { - "id": 301, - "name": "Aether", - "cover": { "uri": "avatars.yandex.net/get-music-content/2/aether/%%" } - } - ], - "releaseDate": "2026-11-27", - "cover": { "uri": "avatars.yandex.net/get-music-content/2/mp/%%", "color": "#1E3A8A" } - } - ] - }); - let rich = parse_new_releases_block(&nr_payload); - assert_eq!(rich.len(), 1); - assert_eq!(rich[0].album.id, "8888"); - assert_eq!(rich[0].album.artists[0].name, "Aether"); - assert_eq!( - rich[0].artist_cover_uri.as_deref(), - Some("avatars.yandex.net/get-music-content/2/aether/%%") - ); - assert_eq!(rich[0].cover_color.as_deref(), Some("#1E3A8A")); - assert_eq!(rich[0].release_date.as_deref(), Some("2026-11-27")); - - let waves_payload = json!({ - "waves": [ - { - "title": "по языку", - "items": [ - { - "title": "Английский", - "header": "Моя волна по языку", - "seeds": ["language:english"], - "colors": { "average": "#3B82F6" }, - "backgroundImageUrl": "https://avatars.yandex.net/bg.png", - "imageUrl": "https://avatars.yandex.net/img.png" - } - ] - } - ] - }); - let tabs = parse_vibe_picks_block(&waves_payload); - assert_eq!(tabs.len(), 1); - assert_eq!(tabs[0].title, "по языку"); - assert_eq!(tabs[0].items.len(), 1); - assert_eq!(tabs[0].items[0].title, "Английский"); - assert_eq!(tabs[0].items[0].header, "Моя волна по языку"); - assert_eq!(tabs[0].items[0].seeds, vec!["language:english"]); - assert_eq!(tabs[0].items[0].color_hex.as_deref(), Some("#3B82F6")); - } - - #[test] - fn test_duplicate_title_albums_and_liked_library_parsers() { - let artist_res = json!({ - "albums": [ - { - "id": 1001, - "title": "After Hours", - "year": 2020, - "duplicates": [ - { - "id": 1002, - "title": "After Hours", - "version": "Deluxe", - "year": 2020 - } - ] - } - ], - "alsoAlbums": [ - { - "id": 1003, - "title": "After Hours (Deluxe)", - "version": "Deluxe", - "year": 2020 - }, - { - "id": 1001, - "title": "After Hours", - "year": 2020 - } - ] - }); - - let albs = parse_artist_detail_albums(&artist_res); - // Strictly deduped by ID (1001, 1002, 1003), NEVER by title! - assert_eq!(albs.len(), 3); - assert_eq!(albs[0].id, "1001"); - assert_eq!(albs[0].full_title(), "After Hours"); - assert_eq!(albs[1].id, "1002"); - assert_eq!(albs[1].full_title(), "After Hours (Deluxe)"); - // Version already in title -> no double "(Deluxe) (Deluxe)" - assert_eq!(albs[2].id, "1003"); - assert_eq!(albs[2].full_title(), "After Hours (Deluxe)"); - - // Liked albums mixed shapes + bare ID record - let liked_albs_res = json!({ - "albums": [ - { "album": { "id": 10, "title": "Same Title" } }, - { "data": { "id": 11, "title": "Same Title", "version": "Slowed" } }, - { "id": 12 } - ] - }); - let (cnt, parsed_albs, bare_alb_ids) = parse_liked_albums_entries(&liked_albs_res); - assert_eq!(cnt, 3); - assert_eq!(parsed_albs.len(), 2); - assert_eq!(parsed_albs[0].full_title(), "Same Title"); - assert_eq!(parsed_albs[1].full_title(), "Same Title (Slowed)"); - assert_eq!(bare_alb_ids, vec!["12"]); - - // Liked artists mixed shapes + bare ID record - let liked_arts_res = json!({ - "artists": [ - { "artist": { "id": 20, "name": "Artist One" } }, - { "data": { "artist": { "id": 21, "name": "Artist Two" } } }, - { "id": 22 } - ] - }); - let (acnt, parsed_arts, bare_art_ids) = parse_liked_artists_entries(&liked_arts_res); - assert_eq!(acnt, 3); - assert_eq!(parsed_arts.len(), 2); - assert_eq!(parsed_arts[0].name, "Artist One"); - assert_eq!(parsed_arts[1].name, "Artist Two"); - assert_eq!(bare_art_ids, vec!["22"]); - } - - #[test] - fn test_parse_track_fade_metadata() { - let valid = json!({ - "id": 12345, - "title": "Crossfade Track", - "durationMs": 210000, - "artists": [{ "id": 1, "name": "Artist" }], - "fade": { - "inStart": 0.25, - "inStop": 4.5, - "outStart": 203.0, - "outStop": 208.5 - } - }); - let tr = parse_track(&valid).expect("valid track"); - let f = tr.fade.expect("valid fade parsed"); - assert!((f.in_start - 0.25).abs() < 1e-4); - assert!((f.in_stop - 4.5).abs() < 1e-4); - assert!((f.out_start - 203.0).abs() < 1e-4); - assert!((f.out_stop - 208.5).abs() < 1e-4); - - let invalid = json!({ - "id": 12346, - "title": "Bad Fade", - "durationMs": 180000, - "fade": { "inStart": 10.0, "inStop": 5.0, "outStart": 4.0, "outStop": 3.0 } - }); - let tr_bad = parse_track(&invalid).expect("track parses"); - assert!(tr_bad.fade.is_none()); - } } diff --git a/src/api/models.rs b/src/api/models.rs index a3aa702..df79252 100644 --- a/src/api/models.rs +++ b/src/api/models.rs @@ -8,8 +8,6 @@ pub struct UserAccount { pub display_name: String, pub has_plus: bool, pub avatar_uri: Option, - #[serde(default)] - pub default_email: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -24,8 +22,6 @@ pub struct ArtistSummary { pub struct AlbumSummary { pub id: String, pub title: String, - #[serde(default)] - pub version: Option, pub year: Option, pub cover_uri: Option, pub artists: Vec, @@ -37,25 +33,7 @@ pub struct AlbumSummary { pub content_type: Option, } -impl AlbumSummary { - /// Display title including edition/version (e.g. `"Album (Deluxe)"`) when `version` is non-empty - /// and not already present in `title`, so duplicate-title editions stay clearly distinguishable. - pub fn full_title(&self) -> String { - match self - .version - .as_deref() - .map(str::trim) - .filter(|v| !v.is_empty()) - { - Some(ver) if !self.title.to_lowercase().contains(&ver.to_lowercase()) => { - format!("{} ({})", self.title, ver) - } - _ => self.title.clone(), - } - } -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct Track { pub id: String, pub title: String, @@ -82,27 +60,6 @@ pub struct Track { pub derived_average_hex: Option, #[serde(default)] pub derived_accent_hex: Option, - /// Official Yandex Music track transition points in seconds (`track.fade`) - #[serde(default)] - pub fade: Option, -} - -/// Official Yandex Music track transition points in seconds (`track.fade`). -#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] -pub struct TrackFade { - pub in_start: f32, - pub in_stop: f32, - pub out_start: f32, - pub out_stop: f32, -} - -impl TrackFade { - pub fn is_valid(&self) -> bool { - self.in_start >= 0.0 - && self.in_stop >= self.in_start - && self.out_start > self.in_stop - && self.out_stop > self.out_start - } } impl Track { @@ -199,8 +156,6 @@ pub struct TrackLyrics { pub is_synced: bool, pub lines: Vec, pub writers: Option, - #[serde(default)] - pub major: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -227,53 +182,6 @@ pub struct LandingData { pub vibe_tracks: Vec, pub podcasts: Vec, pub kids_playlists: Vec, - #[serde(default)] - pub rich_new_releases: Vec, - #[serde(default)] - pub vibe_pick_tabs: Vec, -} - -/// Rich editorial new release item from `GET /landing/skeleton/web_main` (`NEW_RELEASES`). -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct NewReleaseItem { - pub album: AlbumSummary, - #[serde(default)] - pub artist_cover_uri: Option, - #[serde(default)] - pub cover_color: Option, - #[serde(default)] - pub release_date: Option, -} - -/// Single My Vibe wave pick item from `WAVES` / `SETS_BY_WAVES` skeleton block. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct VibePickItem { - pub title: String, - pub header: String, - pub seeds: Vec, - #[serde(default)] - pub color_hex: Option, - #[serde(default)] - pub background_image_url: Option, - #[serde(default)] - pub image_url: Option, -} - -/// Category tab inside `More Picks` (`Ещё подборки`) from `WAVES` / `SETS_BY_WAVES`. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct VibePickTab { - pub title: String, - pub items: Vec, -} - -/// Section block on the Books & Podcasts (`non_music`) landing page. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct NonMusicSection { - pub id: String, - pub title: String, - pub block_type: String, - pub albums: Vec, - pub playlists: Vec, } #[derive(Debug, Clone)] @@ -354,7 +262,7 @@ pub struct PlayTelemetryEvent { pub batch_id: Option, } -/// Concert item returned by `GET /concerts/feed` or `GET /landing/skeleton/concerts` +/// Concert item returned by `GET /concerts/feed` #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ConcertItem { pub id: String, @@ -365,18 +273,6 @@ pub struct ConcertItem { pub date: String, pub cover_uri: Option, pub afisha_url: Option, - #[serde(default)] - pub min_price: Option, - #[serde(default)] - pub currency: Option, - #[serde(default)] - pub cashback_percent: Option, - #[serde(default)] - pub cashback_title: Option, - #[serde(default)] - pub cover_color: Option, - #[serde(default)] - pub event_kind: Option, } fn default_wheel_item_type() -> String { @@ -497,81 +393,3 @@ pub struct MetatagDetail { pub artists: Vec, pub playlists: Vec, } - -/// Optional clickable action link attached to an AI WordsCard (`card.action`). -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct WordsCardAction { - pub title: String, - pub url: String, -} - -/// External source citation attached to an AI WordsCard / WordsBigCard (`actions[]`). -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct WordsCardSource { - pub title: String, - pub url: String, - pub favicon_url: Option, -} - -/// Official 5.129.0 AI Track Fact / Reply card returned by `POST /words/cards`. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct WordsCard { - pub id: String, - pub track_id: String, - pub text: String, - pub tags: Vec, - pub action: Option, - pub actions: Vec, - pub big_card_ids: Vec, - pub feedback_state: Option, -} - -impl WordsCard { - pub fn is_fact(&self) -> bool { - self.tags.iter().any(|t| t == "FACT") - } - - pub fn is_liked(&self) -> bool { - self.feedback_state - .as_deref() - .map_or(false, |s| s.eq_ignore_ascii_case("like")) - } - - pub fn is_disliked(&self) -> bool { - self.feedback_state - .as_deref() - .map_or(false, |s| s.eq_ignore_ascii_case("dislike")) - } - - pub fn has_big_card(&self) -> bool { - !self.big_card_ids.is_empty() - } -} - -/// Expanded full-screen AI fact/story card returned by `POST /words/big-cards`. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct WordsBigCard { - pub id: String, - pub text: String, - pub actions: Vec, -} - -/// Release changelog entry fetched from Forgejo releases API (or built-in fallback). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ReleaseNoteEntry { - pub tag: String, - pub version: String, - pub name: String, - pub date: String, - pub body: String, - pub html_url: String, -} - -/// Available application update metadata for `NotificationUpdate` & Settings card. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct UpdateInfo { - pub version: String, - pub html_url: String, - pub date: String, - pub body: String, -} diff --git a/src/app/i18n.rs b/src/app/i18n.rs index 49a9a00..3a9330b 100644 --- a/src/app/i18n.rs +++ b/src/app/i18n.rs @@ -4,7 +4,7 @@ use crate::config::{Language, ThemeMode}; -pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION"); +pub const APP_VERSION: &str = "5.129.0"; /// Lightweight zero-allocation localization helper bound to a `Language`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -589,36 +589,6 @@ impl I18n { self.pick("Неизвестный исполнитель", "Unknown artist") } - // ------------------------------------------------------------------------- - // Official 5.129.0 AI WordsCard Strings - // ------------------------------------------------------------------------- - - pub const fn words_feedback_like(self) -> &'static str { - self.pick("Спасибо за оценку", "Thank you for your rating!") - } - - pub const fn words_feedback_dislike(self) -> &'static str { - self.pick( - "Спасибо, что помогаете мне стать лучше", - "Thank you for making me become better!", - ) - } - - pub const fn words_more_similar(self) -> &'static str { - self.pick("Больше такого", "More similar replies") - } - - pub const fn words_not_cool(self) -> &'static str { - self.pick("Мимо", "Not cool") - } - - pub const fn words_ai_disclaimer(self) -> &'static str { - self.pick( - "AI может ошибаться, проверяйте важное", - "AI may make mistakes, be sure to double-check important information", - ) - } - // ------------------------------------------------------------------------- // Formatted Labels & Official Toasts (§2.7) // ------------------------------------------------------------------------- @@ -804,46 +774,6 @@ impl I18n { self.pick("Загрузка остановлена", "Download stopped") } - pub fn toast_download_failed_count(self, failed: usize) -> String { - if self.is_ru() { - format!("Не удалось скачать треков: {}", failed) - } else { - format!("Failed to download {} track(s)", failed) - } - } - - pub const fn whats_new(self) -> &'static str { - self.pick("Что нового?", "What's new?") - } - - pub fn update_available_banner(self, ver: &str) -> String { - if self.is_ru() { - format!("Доступна версия v{}", ver) - } else { - format!("Version v{} available", ver) - } - } - - pub const fn update_btn(self) -> &'static str { - self.pick("Обновить", "Update") - } - - pub const fn download_update(self) -> &'static str { - self.pick("Скачать обновление", "Download update") - } - - pub const fn up_to_date_badge(self) -> &'static str { - self.pick("Актуальная версия", "Up to date") - } - - pub const fn current_version_badge(self) -> &'static str { - self.pick("Текущая", "Current") - } - - pub const fn new_version_badge(self) -> &'static str { - self.pick("Новая", "New") - } - pub fn toast_deleted_from_device(self, title: &str) -> String { if self.is_ru() { format!("Удалено с устройства: {}", title) @@ -908,21 +838,11 @@ impl I18n { } } - pub fn toast_latest_version(self) -> String { - self.toast_up_to_date() - } - pub fn toast_update_available(self, newer: &str) -> String { if self.is_ru() { - format!( - "Доступно обновление: {} (текущая {}) — нажмите снова, чтобы открыть", - newer, APP_VERSION - ) + format!("Доступно обновление: {} (текущая {})", newer, APP_VERSION) } else { - format!( - "Update available: {} (current {}) — click again to open", - newer, APP_VERSION - ) + format!("Update available: {} (current {})", newer, APP_VERSION) } } diff --git a/src/app/playback.rs b/src/app/playback.rs index 08469a8..76353e7 100644 --- a/src/app/playback.rs +++ b/src/app/playback.rs @@ -21,7 +21,6 @@ impl AppState { if idx >= self.queue.len() { return; } - self.invalidate_preload(); self.queue_index = idx; let track = self.queue[idx].clone(); @@ -75,17 +74,14 @@ impl AppState { track.duration_ms, track.r128_i, track.r128_tp, - track.fade, ); self.fetch_lyrics_async(&track); - self.ensure_words_for_current_track(); return; } // Report track start to `POST /plays` self.send_play_telemetry("start"); self.fetch_lyrics_async(&track); - self.ensure_words_for_current_track(); if self.api.has_token() { let api = self.api.clone(); @@ -94,7 +90,6 @@ impl AppState { let dur = track.duration_ms; let r128_i = track.r128_i; let r128_tp = track.r128_tp; - let fade = track.fade; let quality = self.config.audio_quality; self.audio.state.is_buffering.store(true, Ordering::SeqCst); self.runtime.spawn(async move { @@ -107,7 +102,6 @@ impl AppState { duration_ms: dur, r128_i, r128_tp, - fade, result, }); }); @@ -118,150 +112,6 @@ impl AppState { } } - pub(crate) fn peek_next_queue_index(&self) -> Option { - if self.queue.is_empty() || self.repeat == RepeatMode::One { - return None; - } - if self.queue_index + 1 < self.queue.len() { - Some(self.queue_index + 1) - } else if self.repeat == RepeatMode::All || self.is_vibe_active { - Some(0) - } else { - None - } - } - - pub fn invalidate_preload(&mut self) { - self.preloaded_next_track_id = None; - self.audio.clear_preload(); - } - - pub(crate) fn maybe_preload_next_track(&mut self) { - if !self.is_audio_playing() || self.is_buffering() || self.preloaded_next_track_id.is_some() { - return; - } - let dur_ms = self.duration_ms(); - if dur_ms < 8_000 { - return; - } - let pos_ms = self.position_ms(); - let curr_fade = self.current_track().and_then(|tr| tr.fade); - let transition_ms = if self.config.crossfade_enabled { - if self.config.crossfade_secs > 0.1 { - dur_ms.saturating_sub((self.config.crossfade_secs * 1000.0) as u64) - } else if let Some(f) = curr_fade { - ((f.out_start * 1000.0) as u64).min(dur_ms) - } else { - dur_ms.saturating_sub(3_500) - } - } else { - dur_ms - }; - if pos_ms + 15_000 < transition_ms { - return; - } - let Some(next_idx) = self.peek_next_queue_index() else { - return; - }; - let next_track = self.queue[next_idx].clone(); - self.preloaded_next_track_id = Some(next_track.id.clone()); - - let cache_dir = AppConfig::offline_cache_dir(); - if let Some(local_path) = find_offline_track_file(&next_track.id, &cache_dir) { - let ext = local_path - .extension() - .and_then(|e| e.to_str()) - .unwrap_or("mp3") - .to_lowercase(); - let (codec_label, bitrate_kbps) = match ext.as_str() { - "flac" => ("FLAC (Offline)".to_string(), 1000), - "m4a" => ("AAC (Offline)".to_string(), 320), - _ => ("MP3 (Offline)".to_string(), 320), - }; - let stream = ResolvedStream { - url: format!("file://{}", local_path.display()), - codec_label, - bitrate_kbps, - decrypt_key_hex: None, - gain_applied: false, - }; - self.audio.preload_next( - next_track.id, - stream, - next_track.duration_ms, - next_track.r128_i, - next_track.r128_tp, - next_track.fade, - ); - return; - } - - if self.api.has_token() { - let api = self.api.clone(); - let tx = self.tx_api.clone(); - let tid = next_track.id.clone(); - let dur = next_track.duration_ms; - let r128_i = next_track.r128_i; - let r128_tp = next_track.r128_tp; - let fade = next_track.fade; - let quality = self.config.audio_quality; - self.runtime.spawn(async move { - let result = api - .resolve_track_stream(&tid, quality) - .await - .map_err(|e| e.to_string()); - let _ = tx.send(ApiEvent::NextStreamPreloaded { - track_id: tid, - duration_ms: dur, - r128_i, - r128_tp, - fade, - result, - }); - }); - } - } - - pub(crate) fn on_seamless_transition_to(&mut self, next_track_id: &str) { - self.preloaded_next_track_id = None; - let pos_sec = self.duration_ms() as f64 / 1000.0; - let outgoing = self.current_track().cloned(); - self.send_play_telemetry("finish"); - if self.is_vibe_active { - self.send_rotor_feedback(RotorFeedbackKind::TrackFinished, outgoing.as_ref(), Some(pos_sec)); - } - - if let Some(next_idx) = self - .peek_next_queue_index() - .filter(|&i| self.queue.get(i).map_or(false, |tr| tr.id == next_track_id)) - .or_else(|| self.queue.iter().position(|tr| tr.id == next_track_id)) - { - self.queue_index = next_idx; - } - - let Some(track) = self.current_track().cloned() else { - return; - }; - self.current_play_id = generate_request_id(); - self.play_start_iso = iso8601_now(); - self.play_seeked = false; - self.play_paused = false; - self.play_from_cache = find_offline_track_file(&track.id, &AppConfig::offline_cache_dir()).is_some(); - self.last_play_heartbeat = Instant::now(); - - if self.is_vibe_active { - self.send_rotor_feedback(RotorFeedbackKind::TrackStarted, Some(&track), None); - self.maybe_prefetch_rotor_batch(); - } - self.play_history.retain(|t| t.id != track.id); - self.play_history.insert(0, track.clone()); - self.play_history.truncate(50); - - self.send_play_telemetry("start"); - self.fetch_lyrics_async(&track); - self.ensure_words_for_current_track(); - } - fn fetch_lyrics_async(&mut self, track: &Track) { self.current_lyrics = None; self.fetch_lyrics_for_track(track); @@ -486,7 +336,6 @@ impl AppState { if idx >= self.queue.len() { return; } - self.invalidate_preload(); let was_playing = self.is_audio_playing(); let old_len = self.queue.len(); let removed = self.queue.remove(idx); @@ -527,7 +376,6 @@ impl AppState { if from >= self.queue.len() || to >= self.queue.len() || from == to { return; } - self.invalidate_preload(); let item = self.queue.remove(from); self.queue.insert(to, item); @@ -541,7 +389,6 @@ impl AppState { } pub fn clear_queue(&mut self) { - self.invalidate_preload(); self.queue.clear(); self.unshuffled_queue.clear(); self.queue_index = 0; @@ -550,13 +397,11 @@ impl AppState { } pub fn add_to_queue(&mut self, track: Track) { - self.invalidate_preload(); self.show_toast(self.i18n().toast_play_last(&track.title)); self.queue.push(track); } pub fn play_next_track(&mut self, track: Track) { - self.invalidate_preload(); self.show_toast(self.i18n().toast_play_next(&track.title)); let pos = if self.queue.is_empty() { 0 @@ -609,7 +454,6 @@ impl AppState { self.show_toast(t.toast_shuffle_vibe_managed()); return; } - self.invalidate_preload(); self.shuffle = !self.shuffle; if self.queue.len() > 1 { if self.shuffle { @@ -638,7 +482,6 @@ impl AppState { /// Exact 5.129.0 Repeat Cycle (`Off -> All -> One -> Off`; in VibeContext toggles `Off <-> One` ONLY!) pub fn cycle_repeat(&mut self) { - self.invalidate_preload(); self.repeat = if self.is_vibe_active { match self.repeat { RepeatMode::Off => RepeatMode::One, @@ -775,189 +618,6 @@ impl AppState { self.start_vibe_by_seeds(default_vibe, vec!["user:onyourwave".to_string()]); } - // ========================================================================= - // 1b. OFFICIAL 5.129.0 AI WORDS CARDS (Facts, Replies, BigCard & Feedback) - // ========================================================================= - - pub fn current_words_card(&self) -> Option<&WordsCard> { - let tr = self.current_track()?; - let clean_id = tr.id.split(':').next().unwrap_or(&tr.id); - self.words_cards - .get(&tr.id) - .or_else(|| self.words_cards.get(clean_id)) - } - - pub fn current_words_feedback_message(&self) -> Option<&str> { - let (ref msg, at) = self.words_feedback_message.as_ref()?; - if at.elapsed() < Duration::from_secs(3) { - Some(msg.as_str()) - } else { - None - } - } - - pub fn clear_words_cache(&mut self) { - self.words_cards.clear(); - self.words_loading_tracks.clear(); - self.words_empty_tracks.clear(); - self.words_big_card = None; - self.words_big_card_loading = false; - self.words_big_card_open = false; - self.words_feedback_message = None; - } - - pub fn ensure_words_for_current_track(&mut self) { - if !self.api.has_token() { - return; - } - let Some(curr) = self.current_track() else { - return; - }; - let curr_clean = curr.id.split(':').next().unwrap_or(&curr.id).to_string(); - if self.words_cards.contains_key(&curr_clean) - || self.words_loading_tracks.contains(&curr_clean) - || self.words_empty_tracks.contains(&curr_clean) - { - return; - } - - // Batch current track + up to 2 upcoming tracks so skipping on My Vibe feels instant! - let mut req_ids: Vec = Vec::new(); - for offset in 0..3 { - if let Some(tr) = self.queue.get(self.queue_index + offset) { - let clean = tr.id.split(':').next().unwrap_or(&tr.id).to_string(); - if !clean.is_empty() - && !self.words_cards.contains_key(&clean) - && !self.words_loading_tracks.contains(&clean) - && !self.words_empty_tracks.contains(&clean) - && !req_ids.contains(&clean) - { - self.words_loading_tracks.insert(clean.clone()); - req_ids.push(clean); - } - } - } - if req_ids.is_empty() { - return; - } - - let wave_seeds: Option> = if self.is_vibe_active { - let parsed: Vec = self - .context_key - .strip_prefix("vibe:") - .map(|s| { - s.split(',') - .map(str::trim) - .filter(|p| !p.is_empty()) - .map(String::from) - .collect() - }) - .unwrap_or_default(); - if parsed.is_empty() { - Some(vec!["user:onyourwave".to_string()]) - } else { - Some(parsed) - } - } else { - None - }; - - let api = self.api.clone(); - let tx = self.tx_api.clone(); - self.runtime.spawn(async move { - match api - .fetch_words_cards(&req_ids, wave_seeds.as_deref()) - .await - { - Ok(entries) => { - let _ = tx.send(ApiEvent::WordsCardsLoaded(entries)); - } - Err(e) => { - log::debug!("[words] /words/cards failed: {}", e); - let empty = req_ids.into_iter().map(|id| (id, None)).collect(); - let _ = tx.send(ApiEvent::WordsCardsLoaded(empty)); - } - } - }); - } - - pub fn open_words_big_card(&mut self, track_id: String) { - let clean_id = track_id.split(':').next().unwrap_or(&track_id).to_string(); - self.words_big_card_open = true; - let maybe_req = self - .words_cards - .get(&track_id) - .or_else(|| self.words_cards.get(&clean_id)) - .and_then(|c| c.big_card_ids.first().map(|bid| (bid.clone(), c.id.clone()))); - - let Some((big_card_id, card_id)) = maybe_req else { - self.words_big_card_loading = false; - return; - }; - - if self - .words_big_card - .as_ref() - .map_or(false, |bc| bc.id == big_card_id) - { - self.words_big_card_loading = false; - return; - } - - self.words_big_card = None; - if !self.api.has_token() { - self.words_big_card_loading = false; - return; - } - - self.words_big_card_loading = true; - let api = self.api.clone(); - let tx = self.tx_api.clone(); - self.runtime.spawn(async move { - let res = api - .fetch_words_big_card(&big_card_id, &clean_id, &card_id) - .await - .ok() - .flatten(); - let _ = tx.send(ApiEvent::WordsBigCardLoaded(res)); - }); - } - - pub fn send_words_feedback(&mut self, track_id: String, card_id: String, state: String) { - let clean_id = track_id.split(':').next().unwrap_or(&track_id).to_string(); - let norm_state = if state.eq_ignore_ascii_case("neutral") { - None - } else { - Some(state.clone()) - }; - let lookup_key = if self.words_cards.contains_key(&track_id) { - &track_id - } else { - &clean_id - }; - if let Some(card) = self.words_cards.get_mut(lookup_key) { - card.feedback_state = norm_state; - } - - let t = self.i18n(); - if state.eq_ignore_ascii_case("dislike") { - self.words_big_card_open = false; - self.words_big_card_loading = false; - self.words_feedback_message = - Some((t.words_feedback_dislike().to_string(), Instant::now())); - } else if state.eq_ignore_ascii_case("like") { - self.words_feedback_message = - Some((t.words_feedback_like().to_string(), Instant::now())); - } - - if self.api.has_token() && !card_id.is_empty() { - let api = self.api.clone(); - self.runtime.spawn(async move { - let _ = api.send_words_feedback(&card_id, &state).await; - }); - } - } - // ========================================================================= // 2. LIKES, DISLIKES & PINS (Playlist, Album, Artist, Liked, Wave) // ========================================================================= @@ -1767,58 +1427,21 @@ impl AppState { !tracks.is_empty() && tracks.iter().all(|t| self.downloaded_track_ids.contains(&t.id)) } - pub fn track_download_progress(&self, track_id: &str) -> f32 { - self.downloading_track_progress - .get(track_id) - .copied() - .unwrap_or(0.0) - } - pub fn download_progress_pct(&self) -> Option { if self.downloading_track_ids.is_empty() || self.download_batch_total == 0 { return None; } - let in_flight: f32 = self.downloading_track_progress.values().sum(); - let total = self.download_batch_total.max(1) as f32; - let frac = ((self.download_batch_done as f32 + in_flight) / total).clamp(0.0, 0.99); - Some((frac * 100.0).round().clamp(0.0, 99.0) as u8) - } - - pub fn tracks_download_progress_pct(&self, tracks: &[Track]) -> Option { - if tracks.is_empty() || self.downloading_track_ids.is_empty() { - return None; - } - let mut active_count = 0usize; - let mut completed_count = 0usize; - let mut in_flight = 0.0f32; - for tr in tracks { - if self.downloaded_track_ids.contains(&tr.id) { - completed_count += 1; - } else if self.downloading_track_ids.contains(&tr.id) { - active_count += 1; - in_flight += self.track_download_progress(&tr.id); - } - } - if active_count == 0 { - return None; - } - let denom = (completed_count + active_count).max(1) as f32; - let frac = ((completed_count as f32 + in_flight) / denom).clamp(0.0, 0.99); - Some((frac * 100.0).round().clamp(0.0, 99.0) as u8) + let pct = ((self.download_batch_done as f32 / self.download_batch_total as f32) * 100.0) + .round() + .clamp(0.0, 99.0) as u8; + Some(pct) } pub fn cancel_downloads(&mut self) { self.download_cancel.store(true, Ordering::SeqCst); self.downloading_track_ids.clear(); - self.downloading_track_progress.clear(); self.download_batch_total = 0; self.download_batch_done = 0; - self.download_batch_succeeded = 0; - self.download_batch_failed = 0; - if self.download_config_dirty_count > 0 { - self.save_config(); - self.download_config_dirty_count = 0; - } self.show_toast(self.i18n().toast_download_stopped()); } @@ -1833,11 +1456,8 @@ impl AppState { } if self.downloading_track_ids.is_empty() { self.download_cancel.store(false, Ordering::SeqCst); - self.download_batch_succeeded = 0; - self.download_batch_failed = 0; } self.downloading_track_ids.insert(track.id.clone()); - self.downloading_track_progress.insert(track.id.clone(), 0.02); self.download_batch_total += 1; let api = self.api.clone(); @@ -1849,15 +1469,8 @@ impl AppState { if cancel.load(Ordering::Relaxed) { return; } - let tid = track.id.clone(); - let tx_prog = tx.clone(); let res = api - .download_track_to_cache_with_progress(&track, quality, &cache_dir, &cancel, |p| { - let _ = tx_prog.send(ApiEvent::TrackDownloadProgress { - track_id: tid.clone(), - progress: p, - }); - }) + .download_track_to_cache(&track, quality, &cache_dir) .await .map_err(|e| e.to_string()); if cancel.load(Ordering::Relaxed) { @@ -1874,11 +1487,7 @@ impl AppState { self.show_toast(self.i18n().toast_sign_in_required()); return; } - if self.downloading_track_ids.is_empty() { - self.download_cancel.store(false, Ordering::SeqCst); - self.download_batch_succeeded = 0; - self.download_batch_failed = 0; - } + self.download_cancel.store(false, Ordering::SeqCst); let to_download: Vec = tracks .into_iter() .filter(|tr| !self.is_track_downloaded(&tr.id) && !self.is_track_downloading(&tr.id)) @@ -1888,7 +1497,6 @@ impl AppState { } for tr in &to_download { self.downloading_track_ids.insert(tr.id.clone()); - self.downloading_track_progress.insert(tr.id.clone(), 0.01); self.download_batch_total += 1; } @@ -1897,52 +1505,20 @@ impl AppState { let quality = self.config.audio_quality; let cache_dir = AppConfig::offline_cache_dir(); let cancel = std::sync::Arc::clone(&self.download_cancel); - let rt = self.runtime.clone(); self.runtime.spawn(async move { - let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(6)); for track in to_download { if cancel.load(Ordering::Relaxed) { break; } - let Ok(permit) = sem.clone().acquire_owned().await else { - break; - }; + let res = api + .download_track_to_cache(&track, quality, &cache_dir) + .await + .map_err(|e| e.to_string()); if cancel.load(Ordering::Relaxed) { - drop(permit); + let _ = remove_offline_track_file(&track.id, &cache_dir); break; } - let api_w = api.clone(); - let tx_w = tx.clone(); - let cache_w = cache_dir.clone(); - let cancel_w = std::sync::Arc::clone(&cancel); - rt.spawn(async move { - let _permit = permit; - if cancel_w.load(Ordering::Relaxed) { - return; - } - let tid = track.id.clone(); - let tx_prog = tx_w.clone(); - let res = api_w - .download_track_to_cache_with_progress( - &track, - quality, - &cache_w, - &cancel_w, - |p| { - let _ = tx_prog.send(ApiEvent::TrackDownloadProgress { - track_id: tid.clone(), - progress: p, - }); - }, - ) - .await - .map_err(|e| e.to_string()); - if cancel_w.load(Ordering::Relaxed) { - let _ = remove_offline_track_file(&track.id, &cache_w); - return; - } - let _ = tx_w.send(ApiEvent::TrackDownloaded { track, result: res }); - }); + let _ = tx.send(ApiEvent::TrackDownloaded { track, result: res }); } }); } @@ -2195,7 +1771,6 @@ mod tests { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, } } @@ -2697,92 +2272,4 @@ mod tests { assert!(!app.shuffle); assert_eq!(app.repeat, RepeatMode::Off); } - - #[test] - fn test_words_card_state_feedback_and_big_card() { - let tracks = vec![make_track("w1", "Track One"), make_track("w2", "Track Two")]; - let (_rt, mut app) = make_test_state(tracks); - - // Simulate WordsCardsLoaded delivering a FACT card for w1 and empty for w2 - app.words_loading_tracks.insert("w1".into()); - app.words_loading_tracks.insert("w2".into()); - let card = WordsCard { - id: "c_1".into(), - track_id: "w1".into(), - text: "Факт о треке".into(), - tags: vec!["FACT".into()], - action: None, - actions: vec![WordsCardSource { - title: "Wiki".into(), - url: "https://wikipedia.org".into(), - favicon_url: None, - }], - big_card_ids: vec!["big_1".into()], - feedback_state: None, - }; - let _ = app.tx_api.send(ApiEvent::WordsCardsLoaded(vec![ - ("w1".into(), Some(card)), - ("w2".into(), None), - ])); - assert!(app.poll_async_events()); - assert!(app.words_loading_tracks.is_empty()); - assert!(app.words_empty_tracks.contains("w2")); - - let cur = app.current_words_card().expect("w1 card should be active"); - assert!(cur.is_fact()); - assert!(cur.has_big_card()); - assert!(!cur.is_liked()); - assert!(!cur.is_disliked()); - - // Open big card & load content - app.dispatch(AppAction::OpenWordsBigCard { - track_id: "w1".into(), - }); - assert!(app.words_big_card_open); - let _ = app.tx_api.send(ApiEvent::WordsBigCardLoaded(Some(WordsBigCard { - id: "big_1".into(), - text: "Полный рассказ о треке".into(), - actions: vec![], - }))); - assert!(app.poll_async_events()); - assert!(!app.words_big_card_loading); - assert_eq!( - app.words_big_card.as_ref().map(|b| b.id.as_str()), - Some("big_1") - ); - - // Like feedback sets localized toast message - app.dispatch(AppAction::SendWordsFeedback { - track_id: "w1".into(), - card_id: "c_1".into(), - state: "like".into(), - }); - assert!(app.current_words_card().unwrap().is_liked()); - assert_eq!( - app.current_words_feedback_message(), - Some("Спасибо за оценку") - ); - - // Dislike feedback closes big card modal and sets EN message after SetLanguage(En) - app.config.language = crate::config::Language::En; - app.dispatch(AppAction::SendWordsFeedback { - track_id: "w1".into(), - card_id: "c_1".into(), - state: "dislike".into(), - }); - assert!(app.current_words_card().unwrap().is_disliked()); - assert!(!app.words_big_card_open); - assert_eq!( - app.current_words_feedback_message(), - Some("Thank you for making me become better!") - ); - - // CloseWordsBigCard & DismissOverlays clear open state - app.words_big_card_open = true; - app.dispatch(AppAction::CloseWordsBigCard); - assert!(!app.words_big_card_open); - app.words_big_card_open = true; - app.dispatch(AppAction::DismissOverlays); - assert!(!app.words_big_card_open); - } } diff --git a/src/app/state.rs b/src/app/state.rs index cb1c51b..5bd9caf 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -1,5 +1,5 @@ use crossbeam_channel::{unbounded, Receiver, Sender}; -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; @@ -9,7 +9,7 @@ use crate::api::models::*; use crate::api::signing::{extract_oauth_token, generate_request_id, iso8601_now}; use crate::api::{open_url_in_browser, YandexApiClient, YANDEX_OAUTH_URL}; use crate::audio::AudioEngine; -use crate::config::{AppConfig, AudioQuality, Language, PinnedItem, PlayerThumbStyle, ThemeMode}; +use crate::config::{AppConfig, AudioQuality, Language, PinnedItem, ThemeMode}; use crate::telemetry::PerfTelemetry; use crate::vulkan::vibe_renderer::VibePushConstants; @@ -248,12 +248,6 @@ pub enum AppAction { title: String, seeds: Vec, }, - StartVibeStation { - title: String, - seeds: Vec, - }, - RefreshConcerts, - RefreshNonMusic, ApplyVibeSettings { mood: Option, activity: Option, @@ -348,24 +342,9 @@ pub enum AppAction { SetVibeModalOpen(bool), SetLoginModalOpen(bool), SetEqPopoverOpen(bool), - SetEqualizerModalOpen(bool), - SetShortcutsModalOpen(bool), OpenTrackDetailModal(Track), CloseTrackDetailModal, - OpenWordsBigCard { - track_id: String, - }, - CloseWordsBigCard, - SendWordsFeedback { - track_id: String, - card_id: String, - state: String, - }, DismissOverlays, - OpenReleaseNotesModal, - CloseReleaseNotesModal, - DismissUpdateNotification, - InstallUpdate, // Account, Settings & Lifecycle SetTheme(ThemeMode), @@ -373,15 +352,12 @@ pub enum AppAction { ToggleLanguage, SetAudioQuality(AudioQuality), SetNormalizeLoudness(bool), - SetCrossfadeEnabled(bool), SetCrossfadeSecs(f32), SetAiContentReduction(bool), SetChildMode(bool), SetCloseToTray(bool), - SetPlayerThumb(PlayerThumbStyle), UpdateEq { enabled: bool, - preamp: f32, bands: [f32; 10], }, SetMaxCoverCache(usize), @@ -402,7 +378,6 @@ pub(crate) enum ApiEvent { AccountLoaded(Result), LandingLoaded(LandingData), ConcertsLoaded(Vec), - NonMusicLoaded(Vec, Vec), SearchHistoryLoaded(Vec), LikedTracksLoaded(Vec), FavoriteFiltersLoaded(Vec), @@ -431,20 +406,9 @@ pub(crate) enum ApiEvent { duration_ms: u64, r128_i: Option, r128_tp: Option, - fade: Option, - result: Result, - }, - NextStreamPreloaded { - track_id: String, - duration_ms: u64, - r128_i: Option, - r128_tp: Option, - fade: Option, result: Result, }, LyricsLoaded(TrackLyrics), - WordsCardsLoaded(Vec<(String, Option)>), - WordsBigCardLoaded(Option), QueueTracksHydrated(Vec), OAuthTokenReceived(Result), PlaylistCreated { @@ -467,18 +431,11 @@ pub(crate) enum ApiEvent { revision: Result, toast_msg: String, }, - TrackDownloadProgress { - track_id: String, - progress: f32, - }, TrackDownloaded { track: Track, result: Result, }, - ReleasesLoaded { - result: Result, String>, - user_initiated: bool, - }, + UpdateCheckFinished(Result, String>), } // ============================================================================= @@ -506,9 +463,6 @@ pub struct AppState { pub account: Option, pub landing: LandingData, pub concerts: Vec, - pub concerts_loading: bool, - pub non_music_sections: Vec, - pub non_music_loading: bool, pub liked_tracks: Vec, pub liked_ids: HashSet, pub disliked_ids: HashSet, @@ -528,12 +482,8 @@ pub struct AppState { // Offline cache & download tracking pub downloaded_track_ids: HashSet, pub downloading_track_ids: HashSet, - pub downloading_track_progress: HashMap, pub download_batch_total: usize, pub download_batch_done: usize, - pub download_batch_succeeded: usize, - pub download_batch_failed: usize, - pub download_config_dirty_count: usize, pub download_cancel: Arc, // Page-specific states @@ -563,18 +513,8 @@ pub struct AppState { pub vibe_prefetching: bool, pub shuffle: bool, pub repeat: RepeatMode, - pub preloaded_next_track_id: Option, pub current_lyrics: Option, pub modal_lyrics: Option, - - // Official 5.129.0 AI WordsCard state (`POST /words/cards`, `/words/big-cards`, `PUT /words/cards/feedback`) - pub words_cards: HashMap, - pub words_loading_tracks: HashSet, - pub words_empty_tracks: HashSet, - pub words_big_card: Option, - pub words_big_card_loading: bool, - pub words_big_card_open: bool, - pub words_feedback_message: Option<(String, Instant)>, pub current_hue: f32, pub target_hue: f32, pub smooth_sat: f32, @@ -602,8 +542,6 @@ pub struct AppState { pub vibe_modal_open: bool, pub login_modal_open: bool, pub eq_popover_open: bool, - pub equalizer_modal_open: bool, - pub shortcuts_modal_open: bool, pub playlist_modal: PlaylistModalState, pub track_detail_modal: Option, pub token_input: String, @@ -616,11 +554,6 @@ pub struct AppState { pub clear_cover_cache_requested: bool, pub cover_cache_capacity_dirty: bool, pub pending_clipboard_text: Option, - pub available_update: Option, - pub releases: Vec, - pub releases_loading: bool, - pub release_notes_modal_open: bool, - pub update_notification_dismissed: bool, pub persist_enabled: bool, } @@ -631,10 +564,8 @@ impl AppState { config.volume, config.muted, config.eq_enabled, - config.eq_preamp, config.eq_bands_db, config.normalize_loudness, - config.crossfade_enabled, config.crossfade_secs, ); let mut api = YandexApiClient::new(config.oauth_token.clone()); @@ -675,9 +606,6 @@ impl AppState { account: None, landing: LandingData::default(), concerts: Vec::new(), - concerts_loading: false, - non_music_sections: Vec::new(), - non_music_loading: false, liked_tracks: Vec::new(), liked_ids: HashSet::new(), disliked_ids: HashSet::new(), @@ -693,12 +621,8 @@ impl AppState { selected_favorite_filter_id: None, downloaded_track_ids: HashSet::new(), downloading_track_ids: HashSet::new(), - downloading_track_progress: HashMap::new(), download_batch_total: 0, download_batch_done: 0, - download_batch_succeeded: 0, - download_batch_failed: 0, - download_config_dirty_count: 0, download_cancel: Arc::new(AtomicBool::new(false)), search_query: String::new(), search_debounce_deadline: None, @@ -724,16 +648,8 @@ impl AppState { vibe_prefetching: false, shuffle: false, repeat: RepeatMode::Off, - preloaded_next_track_id: None, current_lyrics: None, modal_lyrics: None, - words_cards: HashMap::new(), - words_loading_tracks: HashSet::new(), - words_empty_tracks: HashSet::new(), - words_big_card: None, - words_big_card_loading: false, - words_big_card_open: false, - words_feedback_message: None, current_hue: 0.12, target_hue: 0.12, smooth_sat: 1.0, @@ -757,8 +673,6 @@ impl AppState { vibe_modal_open: false, login_modal_open: false, eq_popover_open: false, - equalizer_modal_open: false, - shortcuts_modal_open: false, playlist_modal: PlaylistModalState::None, track_detail_modal: None, token_input: String::new(), @@ -769,11 +683,6 @@ impl AppState { clear_cover_cache_requested: false, cover_cache_capacity_dirty: false, pending_clipboard_text: None, - available_update: None, - releases: Self::builtin_fallback_releases(), - releases_loading: false, - release_notes_modal_open: false, - update_notification_dismissed: false, persist_enabled: true, }; @@ -806,7 +715,6 @@ impl AppState { config.volume, config.muted, config.eq_enabled, - config.eq_preamp, config.eq_bands_db, ); audio.state.position_ms.store(position_ms, Ordering::SeqCst); @@ -837,9 +745,6 @@ impl AppState { account, landing, concerts: Vec::new(), - concerts_loading: false, - non_music_sections: Vec::new(), - non_music_loading: false, liked_tracks, liked_ids, disliked_ids: HashSet::new(), @@ -855,12 +760,8 @@ impl AppState { selected_favorite_filter_id: None, downloaded_track_ids: downloaded_ids, downloading_track_ids: HashSet::new(), - downloading_track_progress: HashMap::new(), download_batch_total: 0, download_batch_done: 0, - download_batch_succeeded: 0, - download_batch_failed: 0, - download_config_dirty_count: 0, download_cancel: Arc::new(AtomicBool::new(false)), search_query: String::new(), search_debounce_deadline: None, @@ -886,16 +787,8 @@ impl AppState { vibe_prefetching: false, shuffle: false, repeat: RepeatMode::Off, - preloaded_next_track_id: None, current_lyrics: None, modal_lyrics: None, - words_cards: HashMap::new(), - words_loading_tracks: HashSet::new(), - words_empty_tracks: HashSet::new(), - words_big_card: None, - words_big_card_loading: false, - words_big_card_open: false, - words_feedback_message: None, current_hue: 0.12, target_hue: 0.12, smooth_sat: 1.0, @@ -919,8 +812,6 @@ impl AppState { vibe_modal_open: false, login_modal_open: false, eq_popover_open: false, - equalizer_modal_open: false, - shortcuts_modal_open: false, playlist_modal: PlaylistModalState::None, track_detail_modal: None, token_input: String::new(), @@ -931,11 +822,6 @@ impl AppState { clear_cover_cache_requested: false, cover_cache_capacity_dirty: false, pending_clipboard_text: None, - available_update: None, - releases: Self::builtin_fallback_releases(), - releases_loading: false, - release_notes_modal_open: false, - update_notification_dismissed: false, persist_enabled: false, } } @@ -1089,13 +975,6 @@ impl AppState { } if playing { - // Animated player bar companion (Duck/Car/Claudik/Antigravity/Ferris/Nyan): smooth 30 FPS when focused! - if window_focused - && self.config.player_thumb != PlayerThumbStyle::Standard - && !self.fullscreen_open - { - return Some(Duration::from_millis(33)); - } // Static pages (Favorites, ForYou, Search, Collection, Fullscreen, Detail): // Progress bar moves ~1px every 150-250ms; no reason to spin GPU at 60 FPS! let lyrics_visible = (self.fullscreen_open && self.fullscreen_lyrics_open) @@ -1306,141 +1185,50 @@ impl AppState { }) } - /// Built-in offline fallback release notes so `ReleaseNotesModal` is always populated immediately. - pub fn builtin_fallback_releases() -> Vec { - vec![ - ReleaseNoteEntry { - tag: format!("v{}", APP_VERSION), - version: APP_VERSION.to_string(), - name: format!("v{}", APP_VERSION), - date: "2026-11-27".to_string(), - body: "## Что нового\n- Плавные переходы между страницами, шторкой очереди, полноэкранным плеером и модалками\n- Быстрое параллельное скачивание треков с круговым индикатором прогресса без спама уведомлениями\n- Встроенный список изменений («Что нового?») и уведомление о доступном обновлении как в оригинале".to_string(), - html_url: "https://git.tatar/marwy/yandex-music-rs/releases/latest".to_string(), - }, - ReleaseNoteEntry { - tag: "v0.1.5".to_string(), - version: "0.1.5".to_string(), - name: "v0.1.5".to_string(), - date: "2026-11-27".to_string(), - body: "- Нативный системный трей Linux (StatusNotifierItem через `ksni` без GTK/libappindicator)\n- Кнопка сворачивания левой панели 1-в-1 как в Яндекс Музыке 5.129.0\n- Оптимизации памяти без потери производительности GPU-рендера".to_string(), - html_url: "https://git.tatar/marwy/yandex-music-rs/releases/tag/v0.1.5".to_string(), - }, - ReleaseNoteEntry { - tag: "v0.1.4".to_string(), - version: "0.1.4".to_string(), - name: "v0.1.4".to_string(), - date: "2026-11-27".to_string(), - body: "- Полноэкранный плеер 1-в-1 и синхронизированный текст песен (SyncLyrics)\n- Отображение плейлистов «Мне нравится» друзей с сердечками на обложках\n- Корректное кадрирование обложек `object-fit: cover` и изолированный скролл каруселей".to_string(), - html_url: "https://git.tatar/marwy/yandex-music-rs/releases/tag/v0.1.4".to_string(), - }, - ] - } - - /// Fetch release changelog + check for newer versions from Forgejo releases API. - pub fn fetch_releases_and_updates(&mut self, user_initiated: bool) { - if self.releases_loading && !user_initiated { - return; - } - self.releases_loading = true; + /// Shows real version status toast (5.129.0) & checks update endpoint asynchronously. + pub fn check_for_updates(&mut self) { + self.show_toast(self.i18n().toast_checking_updates()); let tx = self.tx_api.clone(); self.runtime.spawn(async move { - const RELEASES_API: &str = - "https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases?limit=15"; - const RELEASES_WEB: &str = - "https://git.tatar/marwy/yandex-music-rs/releases"; - let client = reqwest::Client::builder() .timeout(Duration::from_secs(6)) - .user_agent(format!("yandex-music-rs/{}", APP_VERSION)) + .user_agent(format!("YandexMusicDesktopAppWindows/{}", APP_VERSION)) .build(); let res = match client { - Ok(http) => match http.get(RELEASES_API).send().await { - Ok(resp) if resp.status().is_success() => { - match resp.json::>().await { - Ok(arr) => { - let mut entries = Vec::new(); - for val in arr { - if val["draft"].as_bool().unwrap_or(false) { - continue; - } - let tag = val["tag_name"] - .as_str() - .map(str::trim) - .unwrap_or("") - .to_string(); - let version = tag.trim_start_matches(['v', 'V']).to_string(); - if version.is_empty() { - continue; - } - let name = val["name"] - .as_str() - .map(str::trim) - .filter(|s| !s.is_empty()) - .unwrap_or(&tag) - .to_string(); - let raw_date = val["published_at"] - .as_str() - .or_else(|| val["created_at"].as_str()) - .unwrap_or(""); - let date = raw_date - .split('T') - .next() - .unwrap_or("") - .trim() - .to_string(); - let body = val["body"] - .as_str() - .unwrap_or("") - .trim() - .to_string(); - let html_url = val["html_url"] - .as_str() - .map(str::trim) - .filter(|s| !s.is_empty()) - .unwrap_or(RELEASES_WEB) - .to_string(); - entries.push(ReleaseNoteEntry { - tag, - version, - name, - date, - body, - html_url, - }); + Ok(http) => { + match http + .get("https://music-desktop-application.s3.yandex.net/stable/latest.yml") + .send() + .await + { + Ok(resp) if resp.status().is_success() => { + let body = resp.text().await.unwrap_or_default(); + let remote_ver = body.lines().find_map(|l| { + l.trim() + .strip_prefix("version:") + .map(|v| v.trim().trim_matches('"').to_string()) + }); + if let Some(ref v) = remote_ver { + if v != APP_VERSION && !v.is_empty() { + Ok(Some(v.clone())) + } else { + Ok(None) } - Ok(entries) + } else { + Ok(None) } - Err(e) => Err(e.to_string()), } + Ok(resp) => Err(format!("HTTP {}", resp.status().as_u16())), + Err(e) => Err(e.to_string()), } - Ok(resp) if resp.status().as_u16() == 404 => Ok(Vec::new()), - Ok(resp) => Err(format!("HTTP {}", resp.status().as_u16())), - Err(e) => Err(e.to_string()), - }, + } Err(e) => Err(e.to_string()), }; - let _ = tx.send(ApiEvent::ReleasesLoaded { - result: res, - user_initiated, - }); + let _ = tx.send(ApiEvent::UpdateCheckFinished(res)); }); } - /// Shows version status toast & checks `git.tatar/marwy/yandex-music-rs` releases asynchronously. - /// If an update was already detected, clicking opens its release page immediately. - pub fn check_for_updates(&mut self) { - if let Some(ref upd) = self.available_update { - open_url_in_browser(&upd.html_url); - return; - } - self.show_toast(self.i18n().toast_checking_updates()); - self.fetch_releases_and_updates(true); - } - - pub fn bootstrap_api(&mut self) { - if self.persist_enabled { - self.fetch_releases_and_updates(false); - } + pub fn bootstrap_api(&self) { // 1. Landing data + Concerts + Metatags { let api = self.api.clone(); @@ -1455,16 +1243,9 @@ impl AppState { let api = self.api.clone(); let tx = self.tx_api.clone(); self.runtime.spawn(async move { - let concerts = api.fetch_concerts_feed().await.unwrap_or_default(); - let _ = tx.send(ApiEvent::ConcertsLoaded(concerts)); - }); - } - { - let api = self.api.clone(); - let tx = self.tx_api.clone(); - self.runtime.spawn(async move { - let (sections, albums) = api.fetch_non_music_landing().await.unwrap_or_default(); - let _ = tx.send(ApiEvent::NonMusicLoaded(sections, albums)); + if let Ok(concerts) = api.fetch_concerts_feed().await { + let _ = tx.send(ApiEvent::ConcertsLoaded(concerts)); + } }); } { @@ -1611,24 +1392,8 @@ impl AppState { let api_c = api.clone(); let tx_c = tx.clone(); rt.spawn(async move { - let mut merged = Vec::new(); - let mut seen = HashSet::new(); if let Ok(pls) = api_c.fetch_user_playlists(uid).await { - for pl in pls { - if seen.insert((pl.owner_uid.clone(), pl.kind.clone())) { - merged.push(pl); - } - } - } - if let Ok(liked_pls) = api_c.fetch_liked_playlists(uid).await { - for pl in liked_pls { - if seen.insert((pl.owner_uid.clone(), pl.kind.clone())) { - merged.push(pl); - } - } - } - if !merged.is_empty() { - let _ = tx_c.send(ApiEvent::UserPlaylistsLoaded(merged)); + let _ = tx_c.send(ApiEvent::UserPlaylistsLoaded(pls)); } }); } @@ -1826,53 +1591,12 @@ impl AppState { } }); } - Route::Concerts => { - self.detail_loading = false; - if self.concerts.is_empty() && !self.concerts_loading { - self.refresh_concerts(); - } - } - Route::Podcasts => { - self.detail_loading = false; - if self.non_music_sections.is_empty() && !self.non_music_loading { - self.refresh_non_music(); - } - } _ => { self.detail_loading = false; } } } - pub fn refresh_concerts(&mut self) { - self.concerts_loading = true; - let api = self.api.clone(); - let tx = self.tx_api.clone(); - self.runtime.spawn(async move { - let concerts = api.fetch_concerts_feed().await.unwrap_or_default(); - let _ = tx.send(ApiEvent::ConcertsLoaded(concerts)); - }); - } - - pub fn refresh_non_music(&mut self) { - self.non_music_loading = true; - let api = self.api.clone(); - let tx = self.tx_api.clone(); - self.runtime.spawn(async move { - let (sections, albums) = api.fetch_non_music_landing().await.unwrap_or_default(); - let _ = tx.send(ApiEvent::NonMusicLoaded(sections, albums)); - }); - if self.api.has_token() { - let api = self.api.clone(); - let tx = self.tx_api.clone(); - self.runtime.spawn(async move { - if let Ok(shelf) = api.fetch_bookshelf_liked().await { - let _ = tx.send(ApiEvent::BookshelfLoaded(shelf)); - } - }); - } - } - pub fn launch_oauth_login(&mut self) { self.show_toast(self.i18n().toast_opening_oauth()); let tx = self.tx_api.clone(); @@ -1903,15 +1627,10 @@ impl AppState { /// Returns `true` if any visible application state changed (requiring a UI redraw). pub fn poll_async_events(&mut self) -> bool { let mut changed = false; - if let Some(next_tid) = self.audio.take_crossfaded_track_id() { - self.on_seamless_transition_to(&next_tid); - changed = true; - } if self.audio.take_track_finished() { self.advance_track(true, false); changed = true; } - self.maybe_preload_next_track(); // Debounced 500ms live search trigger if let Some(deadline) = self.search_debounce_deadline { @@ -1950,17 +1669,7 @@ impl AppState { match ev { ApiEvent::AccountLoaded(Ok(acc)) => { self.show_toast(t.toast_welcome(&acc.display_name)); - let uid = acc.uid; self.account = Some(acc); - normalize_pins(&mut self.config.pinned_items, Some(uid), t.is_ru()); - self.save_config(); - self.ensure_words_for_current_track(); - if self.concerts.is_empty() && !self.concerts_loading { - self.refresh_concerts(); - } - if self.non_music_sections.is_empty() && !self.non_music_loading { - self.refresh_non_music(); - } } ApiEvent::AccountLoaded(Err(e)) => { self.show_toast(if t.is_ru() { @@ -1970,19 +1679,7 @@ impl AppState { }); } ApiEvent::ConcertsLoaded(concerts) => { - self.concerts_loading = false; - if !concerts.is_empty() || self.concerts.is_empty() { - self.concerts = concerts; - } - } - ApiEvent::NonMusicLoaded(sections, albums) => { - self.non_music_loading = false; - if !sections.is_empty() { - self.non_music_sections = sections; - } - if !albums.is_empty() { - self.landing.podcasts = albums; - } + self.concerts = concerts; } ApiEvent::SearchHistoryLoaded(hist) => { self.config.search_history = hist; @@ -2033,10 +1730,6 @@ impl AppState { self.queue_index = 0; } } - let mut data = data; - if data.podcasts.is_empty() && !self.landing.podcasts.is_empty() { - data.podcasts = self.landing.podcasts.clone(); - } self.landing = data; } ApiEvent::LikedTracksLoaded(tracks) => { @@ -2075,8 +1768,20 @@ impl AppState { self.bookshelf_items = items; } ApiEvent::PinsLoaded(mut pins) => { - let my_uid = self.account.as_ref().map(|a| a.uid); - normalize_pins(&mut pins, my_uid, t.is_ru()); + let mut seen_likes = false; + pins.retain(|p| { + let is_likes = p.kind == "likes" + || p.id == "likes" + || p.title == "Мне нравится" + || p.title == "My Favorites"; + if is_likes { + if seen_likes { + return false; + } + seen_likes = true; + } + true + }); self.config.pinned_items = pins; self.save_config(); } @@ -2168,14 +1873,13 @@ impl AppState { duration_ms, r128_i, r128_tp, - fade, result, } => { if self.current_track().map(|tr| tr.id.as_str()) == Some(track_id.as_str()) { match result { Ok(stream) => { self.audio - .load_stream(track_id, stream, duration_ms, r128_i, r128_tp, fade); + .load_stream(track_id, stream, duration_ms, r128_i, r128_tp); } Err(e) => { log::warn!("Stream resolve failed: {}", e); @@ -2190,37 +1894,6 @@ impl AppState { } } } - ApiEvent::NextStreamPreloaded { - track_id, - duration_ms, - r128_i, - r128_tp, - fade, - result, - } => { - let matches_next = self - .peek_next_queue_index() - .and_then(|i| self.queue.get(i)) - .map_or(false, |tr| tr.id == track_id); - if matches_next { - match result { - Ok(stream) => { - self.audio.preload_next( - track_id, - stream, - duration_ms, - r128_i, - r128_tp, - fade, - ); - } - Err(e) => { - log::debug!("Next-track preload failed for {}: {}", track_id, e); - self.preloaded_next_track_id = None; - } - } - } - } ApiEvent::LyricsLoaded(lyr) => { let has_lines = !lyr.lines.is_empty(); if self.current_track().map(|tr| tr.id.as_str()) == Some(lyr.track_id.as_str()) { @@ -2245,23 +1918,6 @@ impl AppState { } } } - ApiEvent::WordsCardsLoaded(entries) => { - for (track_id, maybe_card) in entries { - self.words_loading_tracks.remove(&track_id); - if let Some(card) = maybe_card { - self.words_empty_tracks.remove(&track_id); - self.words_cards.insert(track_id, card); - } else { - self.words_empty_tracks.insert(track_id); - } - } - } - ApiEvent::WordsBigCardLoaded(big) => { - self.words_big_card_loading = false; - if let Some(bc) = big { - self.words_big_card = Some(bc); - } - } ApiEvent::QueueTracksHydrated(hydrated) => { let mut updated_any = false; for fresh in &hydrated { @@ -2309,7 +1965,6 @@ impl AppState { if updated_any { self.save_playback_state(); } - self.ensure_words_for_current_track(); } ApiEvent::OAuthTokenReceived(res) => match res { Ok(tok) => { @@ -2431,24 +2086,17 @@ impl AppState { self.show_toast(t.toast_action_error()); } }, - ApiEvent::TrackDownloadProgress { track_id, progress } => { - if self.downloading_track_ids.contains(&track_id) { - self.downloading_track_progress - .insert(track_id, progress.clamp(0.0, 1.0)); - } - } ApiEvent::TrackDownloaded { track, result } => { - let was_active = self.downloading_track_ids.remove(&track.id); - self.downloading_track_progress.remove(&track.id); - if was_active && self.download_batch_total > 0 { + self.downloading_track_ids.remove(&track.id); + if self.download_batch_total > 0 { self.download_batch_done = (self.download_batch_done + 1).min(self.download_batch_total); + if self.downloading_track_ids.is_empty() { + self.download_batch_total = 0; + self.download_batch_done = 0; + } } if self.download_cancel.load(Ordering::Relaxed) { - if self.download_config_dirty_count > 0 { - self.save_config(); - self.download_config_dirty_count = 0; - } return; } match result { @@ -2461,74 +2109,24 @@ impl AppState { .any(|tr| tr.id == track.id) { self.config.downloaded_tracks.insert(0, track.clone()); - self.download_config_dirty_count += 1; - if self.download_config_dirty_count >= 10 { - self.save_config(); - self.download_config_dirty_count = 0; - } + self.save_config(); } - self.download_batch_succeeded += 1; + self.show_toast(t.toast_track_downloaded(&track.title)); } Err(e) => { log::warn!("Offline download failed for {}: {}", track.id, e); - self.download_batch_failed += 1; - } - } - if self.downloading_track_ids.is_empty() { - if self.download_config_dirty_count > 0 { - self.save_config(); - self.download_config_dirty_count = 0; - } - if self.download_batch_failed > 0 { - self.show_toast(t.toast_download_failed_count(self.download_batch_failed)); - } - self.download_batch_total = 0; - self.download_batch_done = 0; - self.download_batch_succeeded = 0; - self.download_batch_failed = 0; - } - } - ApiEvent::ReleasesLoaded { - result, - user_initiated, - } => { - self.releases_loading = false; - match result { - Ok(list) => { - if !list.is_empty() { - self.releases = list; - } - let newer = self - .releases - .first() - .filter(|r| is_newer_version(&r.version, APP_VERSION)) - .cloned(); - if let Some(latest) = newer { - self.available_update = Some(UpdateInfo { - version: latest.version.clone(), - html_url: latest.html_url, - date: latest.date, - body: latest.body, - }); - if user_initiated { - self.update_notification_dismissed = false; - self.show_toast(t.toast_update_available(&latest.version)); - } - } else { - self.available_update = None; - if user_initiated { - self.show_toast(t.toast_latest_version()); - } - } - } - Err(e) => { - log::warn!("Release check failed: {}", e); - if user_initiated { - self.show_toast(t.toast_update_check_failed()); - } + self.show_toast(t.toast_download_error()); } } } + ApiEvent::UpdateCheckFinished(res) => match res { + Ok(Some(newer)) => self.show_toast(t.toast_update_available(&newer)), + Ok(None) => self.show_toast(t.toast_up_to_date()), + Err(e) => { + log::warn!("Update check failed: {}", e); + self.show_toast(t.toast_update_check_failed()); + } + }, } } @@ -2750,12 +2348,7 @@ impl AppState { } AppAction::ActivateWheelItem(item) => self.activate_wheel_item(item), AppAction::ReshuffleWheel => self.reshuffle_wheel(), - AppAction::StartVibeBySeeds { title, seeds } - | AppAction::StartVibeStation { title, seeds } => { - self.start_vibe_by_seeds(title, seeds); - } - AppAction::RefreshConcerts => self.refresh_concerts(), - AppAction::RefreshNonMusic => self.refresh_non_music(), + AppAction::StartVibeBySeeds { title, seeds } => self.start_vibe_by_seeds(title, seeds), AppAction::ApplyVibeSettings { mood, activity, @@ -2989,12 +2582,6 @@ impl AppState { AppAction::SetEqPopoverOpen(open) => { self.eq_popover_open = open; } - AppAction::SetEqualizerModalOpen(open) => { - self.equalizer_modal_open = open; - } - AppAction::SetShortcutsModalOpen(open) => { - self.shortcuts_modal_open = open; - } AppAction::OpenTrackDetailModal(tr) => { let tid = tr.id.clone(); let cached_from_current = self @@ -3017,20 +2604,6 @@ impl AppState { AppAction::CloseTrackDetailModal => { self.track_detail_modal = None; } - AppAction::OpenWordsBigCard { track_id } => { - self.open_words_big_card(track_id); - } - AppAction::CloseWordsBigCard => { - self.words_big_card_open = false; - self.words_big_card_loading = false; - } - AppAction::SendWordsFeedback { - track_id, - card_id, - state, - } => { - self.send_words_feedback(track_id, card_id, state); - } AppAction::DismissOverlays => { self.fullscreen_open = false; self.fullscreen_lyrics_open = false; @@ -3038,31 +2611,8 @@ impl AppState { self.vibe_modal_open = false; self.login_modal_open = false; self.eq_popover_open = false; - self.equalizer_modal_open = false; - self.shortcuts_modal_open = false; self.playlist_modal = PlaylistModalState::None; self.track_detail_modal = None; - self.words_big_card_open = false; - self.words_big_card_loading = false; - self.release_notes_modal_open = false; - } - AppAction::OpenReleaseNotesModal => { - self.release_notes_modal_open = true; - if self.releases.len() <= 3 && !self.releases_loading && self.persist_enabled { - self.fetch_releases_and_updates(false); - } - } - AppAction::CloseReleaseNotesModal => { - self.release_notes_modal_open = false; - } - AppAction::DismissUpdateNotification => { - self.update_notification_dismissed = true; - } - AppAction::InstallUpdate => { - if let Some(ref upd) = self.available_update { - open_url_in_browser(&upd.html_url); - } - self.update_notification_dismissed = true; } // Account, Settings & Lifecycle @@ -3075,9 +2625,7 @@ impl AppState { self.config.language = lang; self.save_config(); self.api.set_language(lang.api_code()); - self.clear_words_cache(); self.bootstrap_api(); - self.ensure_words_for_current_track(); } AppAction::ToggleLanguage => { let next = if self.config.language.is_ru() { @@ -3088,9 +2636,7 @@ impl AppState { self.config.language = next; self.save_config(); self.api.set_language(next.api_code()); - self.clear_words_cache(); self.bootstrap_api(); - self.ensure_words_for_current_track(); } AppAction::SetAudioQuality(q) => { self.config.audio_quality = q; @@ -3103,11 +2649,6 @@ impl AppState { self.audio.set_normalize_loudness(v); self.save_config(); } - AppAction::SetCrossfadeEnabled(v) => { - self.config.crossfade_enabled = v; - self.audio.set_crossfade_enabled(v); - self.save_config(); - } AppAction::SetCrossfadeSecs(secs) => { self.config.crossfade_secs = secs.clamp(0.0, 12.0); self.audio.set_crossfade_secs(self.config.crossfade_secs); @@ -3138,20 +2679,10 @@ impl AppState { self.config.close_to_tray = v; self.save_config(); } - AppAction::SetPlayerThumb(style) => { - self.config.player_thumb = style; - self.save_config(); - } - AppAction::UpdateEq { - enabled, - preamp, - bands, - } => { - let preamp = preamp.clamp(0.5, 1.5); + AppAction::UpdateEq { enabled, bands } => { self.config.eq_enabled = enabled; - self.config.eq_preamp = preamp; self.config.eq_bands_db = bands; - self.audio.set_eq(enabled, preamp, bands); + self.audio.set_eq(enabled, bands); self.save_config(); } AppAction::SetMaxCoverCache(cap) => { @@ -3175,7 +2706,6 @@ impl AppState { self.save_config(); self.api.set_token(None); self.account = None; - self.clear_words_cache(); self.show_toast(t.toast_signed_out()); } AppAction::CheckForUpdates => self.check_for_updates(), @@ -3298,149 +2828,3 @@ pub fn vibe_bucket_primary_rgb(raw_rgb: Option<[u8; 3]>) -> [u8; 3] { [0xF5, 0x00, 0x2E] // carmine (340..360 or 0..2) } } - -fn parse_semver_tuple(raw: &str) -> Option<(u32, u32, u32)> { - let trimmed = raw.trim().trim_start_matches(['v', 'V']); - let core = trimmed.split(['-', '+']).next()?.trim(); - if core.is_empty() { - return None; - } - let mut parts = core.split('.'); - let major = parts.next()?.parse::().ok()?; - let minor = match parts.next() { - Some(s) => s.parse::().ok()?, - None => 0, - }; - let patch = match parts.next() { - Some(s) => s.parse::().ok()?, - None => 0, - }; - Some((major, minor, patch)) -} - -/// Returns `true` iff `remote` is strictly newer than `current` by `(major, minor, patch)` semver comparison. -pub fn is_newer_version(remote: &str, current: &str) -> bool { - match (parse_semver_tuple(remote), parse_semver_tuple(current)) { - (Some(r), Some(c)) => r > c, - _ => false, - } -} - -/// Normalize pinned items so only the signed-in user's own `kind == "3"` (`{my_uid}:3`) -/// collapses into system `kind: "likes", id: "likes"`, while friends' `"Мне нравится"` playlists -/// (`{friend_uid}:3`) are ALWAYS preserved as distinct `"playlist"` pins! -fn normalize_pins(pins: &mut Vec, my_uid: Option, ru: bool) { - if let Some(uid) = my_uid { - let my_likes_id = format!("{}:3", uid); - let likes_title = if ru { "Мне нравится" } else { "My Favorites" }; - for p in pins.iter_mut() { - if p.kind == "playlist" && p.id == my_likes_id { - p.id = "likes".into(); - p.kind = "likes".into(); - p.cover_uri = None; - p.title = likes_title.into(); - } - } - } - let mut seen: HashSet<(String, String)> = HashSet::new(); - pins.retain(|p| seen.insert((p.kind.clone(), p.id.clone()))); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_is_newer_version_semver() { - assert_eq!(APP_VERSION, env!("CARGO_PKG_VERSION")); - assert!(!is_newer_version("v0.1.0", "0.1.0")); - assert!(!is_newer_version("0.1.0", "0.1.0")); - assert!(is_newer_version("v0.1.1", "0.1.0")); - assert!(is_newer_version("v0.2.0", "0.1.0")); - assert!(is_newer_version("v1.0.0", "0.9.9")); - assert!(!is_newer_version("v0.0.9", "0.1.0")); - assert!(!is_newer_version("", "0.1.0")); - } - - #[test] - fn test_normalize_pins_keeps_friends_favorites_playlist() { - let mut pins = vec![ - PinnedItem { - id: "likes".into(), - kind: "likes".into(), - title: "Мне нравится".into(), - subtitle: "Плейлист".into(), - cover_uri: None, - owner_uid: Some("1001".into()), - }, - PinnedItem { - id: "1001:3".into(), - kind: "playlist".into(), - title: "Мне нравится".into(), - subtitle: "Плейлист".into(), - cover_uri: None, - owner_uid: Some("1001".into()), - }, - PinnedItem { - id: "2002:3".into(), - kind: "playlist".into(), - title: "Мне нравится".into(), - subtitle: "Плейлист".into(), - cover_uri: None, - owner_uid: Some("2002".into()), - }, - ]; - normalize_pins(&mut pins, Some(1001), true); - assert_eq!(pins.len(), 2, "Own likes + friend's kind=3 likes must BOTH remain"); - assert_eq!(pins[0].kind, "likes"); - assert_eq!(pins[0].id, "likes"); - assert_eq!(pins[1].kind, "playlist"); - assert_eq!(pins[1].id, "2002:3"); - assert_eq!(pins[1].owner_uid.as_deref(), Some("2002")); - } - - #[test] - fn test_download_batch_no_per_track_toast_spam() { - let rt = tokio::runtime::Runtime::new().unwrap(); - let mut app = AppState::new_visual_test( - rt.handle().clone(), - "test-gpu".into(), - Route::LikedTracks, - AppConfig::default(), - LandingData::default(), - None, - Vec::new(), - Vec::new(), - 0, - 0, - 0.0, - ); - - for i in 1..=3 { - let tid = format!("dl_t{}", i); - app.downloading_track_ids.insert(tid.clone()); - app.downloading_track_progress.insert(tid.clone(), 0.5); - app.download_batch_total += 1; - } - for i in 1..=3 { - let tid = format!("dl_t{}", i); - let tr = Track { - id: tid.clone(), - title: format!("Track {}", i), - ..Default::default() - }; - let _ = app.tx_api.send(ApiEvent::TrackDownloaded { - track: tr, - result: Ok(PathBuf::from(format!("/tmp/{}.mp3", tid))), - }); - } - assert!(app.poll_async_events()); - assert!( - app.toast.is_none(), - "Successful track downloads must NOT spam per-track toasts" - ); - assert_eq!(app.downloaded_track_ids.len(), 3); - assert!(app.downloading_track_ids.is_empty()); - assert_eq!(app.download_batch_total, 0); - } -} diff --git a/src/audio/dsp.rs b/src/audio/dsp.rs index 66d8a34..a4ff06a 100644 --- a/src/audio/dsp.rs +++ b/src/audio/dsp.rs @@ -1,140 +1,28 @@ use std::f32::consts::PI; pub const EQ_FREQS: [f32; 10] = [ - 60.0, 170.0, 310.0, 600.0, 1000.0, 3000.0, 6000.0, 12000.0, 14000.0, 16000.0, + 32.0, 64.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0, ]; pub const EQ_LABELS: [&str; 10] = [ - "60", "170", "310", "600", "1k", "3k", "6k", "12k", "14k", "16k", + "32", "64", "125", "250", "500", "1k", "2k", "4k", "8k", "16k", ]; pub struct EqPreset { - pub name_ru: &'static str, - pub name_en: &'static str, + pub name: &'static str, pub gains: [f32; 10], } -impl EqPreset { - pub const fn name(&self, ru: bool) -> &'static str { - if ru { - self.name_ru - } else { - self.name_en - } - } -} - -/// All 18 official Yandex Music Desktop 5.129.0 Equalizer Presets (`layout.js:11387-11783`). pub const EQ_PRESETS: &[EqPreset] = &[ - EqPreset { - name_ru: "По умолчанию", - name_en: "Default", - gains: [0.0; 10], - }, - EqPreset { - name_ru: "Классическая музыка", - name_en: "Classical Music", - gains: [-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -3.5, -3.5, -3.5, -4.5], - }, - EqPreset { - name_ru: "Клубная музыка", - name_en: "Club music", - gains: [-0.5, -0.5, 4.0, 2.5, 2.5, 2.5, 1.5, -0.5, -0.5, -0.5], - }, - EqPreset { - name_ru: "Танцевальная музыка", - name_en: "Dance music", - gains: [4.5, 3.5, 1.0, -0.5, -0.5, -2.5, -3.5, -3.5, -0.5, -0.5], - }, - EqPreset { - name_ru: "Усиление НЧ", - name_en: "Enhanced bass", - gains: [4.0, 4.5, 4.5, 2.5, 0.5, -2.0, -4.0, -5.0, -5.5, -5.5], - }, - EqPreset { - name_ru: "Усиление НЧ и ВЧ", - name_en: "Enhanced bass and treble", - gains: [3.5, 2.5, -0.5, -3.5, -2.0, 0.5, 4.0, 5.5, 6.0, 6.0], - }, - EqPreset { - name_ru: "Усиление ВЧ", - name_en: "Enhanced treble", - gains: [-4.5, -4.5, -4.5, -2.0, 1.0, 5.5, 8.0, 8.0, 8.0, 8.0], - }, - EqPreset { - name_ru: "Колонки ноутбука", - name_en: "Laptop speakers", - gains: [2.0, 5.5, 2.5, -1.5, -1.0, 0.5, 2.0, 4.5, 6.0, 7.0], - }, - EqPreset { - name_ru: "Большой зал", - name_en: "Large Hall", - gains: [5.0, 5.0, 2.5, 2.5, -0.5, -2.0, -2.0, -2.0, -0.5, -0.5], - }, - EqPreset { - name_ru: "Концерт", - name_en: "Live", - gains: [-2.0, -0.5, 2.0, 2.5, 2.5, 2.5, 2.0, 1.0, 1.0, 1.0], - }, - EqPreset { - name_ru: "Вечеринка", - name_en: "Partying", - gains: [3.5, 3.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 3.5, 3.5], - }, - EqPreset { - name_ru: "Поп", - name_en: "Pop", - gains: [-0.5, 2.0, 3.5, 4.0, 2.5, -0.5, -1.0, -1.0, -0.5, -0.5], - }, - EqPreset { - name_ru: "Регги", - name_en: "Reggae", - gains: [-0.5, -0.5, -0.5, -2.5, -0.5, 3.0, 3.0, -0.5, -0.5, -0.5], - }, - EqPreset { - name_ru: "Рок", - name_en: "Rock", - gains: [4.0, 2.0, -2.5, -4.0, -1.5, 2.0, 4.0, 5.5, 5.5, 5.5], - }, - EqPreset { - name_ru: "Ска", - name_en: "Ska", - gains: [-1.0, -2.0, -2.0, -0.5, 2.0, 2.5, 4.0, 4.5, 5.5, 4.5], - }, - EqPreset { - name_ru: "Мягкое звучание", - name_en: "Soft", - gains: [2.0, 0.5, -0.5, -1.0, -0.5, 2.0, 4.0, 4.5, 5.5, 6.0], - }, - EqPreset { - name_ru: "Софт-рок", - name_en: "Soft rock", - gains: [2.0, 2.0, 1.0, -0.5, -2.0, -2.5, -1.5, -0.5, 1.0, 4.0], - }, - EqPreset { - name_ru: "Техно", - name_en: "Techno", - gains: [4.0, 2.5, -0.5, -2.5, -2.0, -0.5, 4.0, 4.5, 4.5, 4.0], - }, + EqPreset { name: "Плоский", gains: [0.0; 10] }, + EqPreset { name: "Бас+", gains: [6.0, 5.5, 4.0, 2.0, 0.0, 0.0, 0.5, 1.0, 1.5, 1.5] }, + EqPreset { name: "Поп", gains: [-1.0, 1.5, 3.5, 4.0, 2.0, -0.5, -1.0, 1.0, 2.5, 3.0] }, + EqPreset { name: "Рок", gains: [4.5, 3.0, 1.5, -1.0, -1.5, 1.0, 3.5, 4.5, 5.0, 4.0] }, + EqPreset { name: "Электроника", gains: [5.0, 4.0, 1.5, -1.5, -1.0, 1.5, 3.0, 4.0, 4.5, 5.0] }, + EqPreset { name: "Вокал", gains: [-2.0, -1.5, 0.0, 2.5, 4.5, 4.5, 3.0, 1.0, -0.5, -1.0] }, + EqPreset { name: "Джаз", gains: [3.0, 2.0, 1.0, 2.0, -1.0, -1.0, 0.0, 1.5, 2.5, 3.0] }, ]; -pub fn active_eq_preset_name(bands: &[f32; 10], ru: bool) -> &'static str { - for preset in EQ_PRESETS { - if bands - .iter() - .zip(preset.gains.iter()) - .all(|(a, b)| (a - b).abs() < 0.15) - { - return preset.name(ru); - } - } - if ru { - "Своя настройка" - } else { - "Custom settings" - } -} - #[derive(Clone, Copy)] struct Biquad { b0: f32, @@ -163,17 +51,13 @@ impl Biquad { } } - fn set_identity(&mut self) { - self.b0 = 1.0; - self.b1 = 0.0; - self.b2 = 0.0; - self.a1 = 0.0; - self.a2 = 0.0; - } - fn set_peaking(&mut self, sample_rate: f32, freq: f32, q: f32, gain_db: f32) { if gain_db.abs() < 0.05 || freq >= sample_rate * 0.48 { - self.set_identity(); + self.b0 = 1.0; + self.b1 = 0.0; + self.b2 = 0.0; + self.a1 = 0.0; + self.a2 = 0.0; return; } let a = 10.0f32.powf(gain_db / 40.0); @@ -195,58 +79,6 @@ impl Biquad { self.a2 = a2 / a0; } - fn set_lowshelf(&mut self, sample_rate: f32, freq: f32, gain_db: f32) { - if gain_db.abs() < 0.05 || freq >= sample_rate * 0.48 { - self.set_identity(); - return; - } - let a = 10.0f32.powf(gain_db / 40.0); - let w0 = 2.0 * PI * freq / sample_rate; - let cos_w0 = w0.cos(); - let sin_w0 = w0.sin(); - let alpha = sin_w0 / 2.0 * ((a + 1.0 / a) * (1.0 / 0.707 - 1.0) + 2.0).max(0.1).sqrt(); - let two_sqrt_a_alpha = 2.0 * a.sqrt() * alpha; - - let b0 = a * ((a + 1.0) - (a - 1.0) * cos_w0 + two_sqrt_a_alpha); - let b1 = 2.0 * a * ((a - 1.0) - (a + 1.0) * cos_w0); - let b2 = a * ((a + 1.0) - (a - 1.0) * cos_w0 - two_sqrt_a_alpha); - let a0 = (a + 1.0) + (a - 1.0) * cos_w0 + two_sqrt_a_alpha; - let a1 = -2.0 * ((a - 1.0) + (a + 1.0) * cos_w0); - let a2 = (a + 1.0) + (a - 1.0) * cos_w0 - two_sqrt_a_alpha; - - self.b0 = b0 / a0; - self.b1 = b1 / a0; - self.b2 = b2 / a0; - self.a1 = a1 / a0; - self.a2 = a2 / a0; - } - - fn set_highshelf(&mut self, sample_rate: f32, freq: f32, gain_db: f32) { - if gain_db.abs() < 0.05 || freq >= sample_rate * 0.48 { - self.set_identity(); - return; - } - let a = 10.0f32.powf(gain_db / 40.0); - let w0 = 2.0 * PI * freq / sample_rate; - let cos_w0 = w0.cos(); - let sin_w0 = w0.sin(); - let alpha = sin_w0 / 2.0 * ((a + 1.0 / a) * (1.0 / 0.707 - 1.0) + 2.0).max(0.1).sqrt(); - let two_sqrt_a_alpha = 2.0 * a.sqrt() * alpha; - - let b0 = a * ((a + 1.0) + (a - 1.0) * cos_w0 + two_sqrt_a_alpha); - let b1 = -2.0 * a * ((a - 1.0) + (a + 1.0) * cos_w0); - let b2 = a * ((a + 1.0) + (a - 1.0) * cos_w0 - two_sqrt_a_alpha); - let a0 = (a + 1.0) - (a - 1.0) * cos_w0 + two_sqrt_a_alpha; - let a1 = 2.0 * ((a - 1.0) - (a + 1.0) * cos_w0); - let a2 = (a + 1.0) - (a - 1.0) * cos_w0 - two_sqrt_a_alpha; - - self.b0 = b0 / a0; - self.b1 = b1 / a0; - self.b2 = b2 / a0; - self.a1 = a1 / a0; - self.a2 = a2 / a0; - } - #[inline(always)] fn process_stereo(&mut self, l: f32, r: f32) -> (f32, f32) { let out_l = self.b0 * l + self.z1_l; @@ -264,7 +96,6 @@ impl Biquad { pub struct Equalizer10Band { bands: [Biquad; 10], enabled: bool, - preamp: f32, sample_rate: f32, gains_db: [f32; 10], } @@ -274,25 +105,17 @@ impl Equalizer10Band { Self { bands: [Biquad::identity(); 10], enabled: false, - preamp: 1.0, sample_rate, gains_db: [0.0; 10], } } - pub fn update(&mut self, enabled: bool, preamp: f32, gains_db: [f32; 10]) { + pub fn update(&mut self, enabled: bool, gains_db: [f32; 10]) { self.enabled = enabled; - self.preamp = preamp.clamp(0.5, 1.5); if self.gains_db != gains_db { self.gains_db = gains_db; for i in 0..10 { - if i == 0 { - self.bands[i].set_lowshelf(self.sample_rate, EQ_FREQS[i], gains_db[i]); - } else if i == 9 { - self.bands[i].set_highshelf(self.sample_rate, EQ_FREQS[i], gains_db[i]); - } else { - self.bands[i].set_peaking(self.sample_rate, EQ_FREQS[i], 1.0, gains_db[i]); - } + self.bands[i].set_peaking(self.sample_rate, EQ_FREQS[i], 1.41, gains_db[i]); } } } @@ -302,8 +125,6 @@ impl Equalizer10Band { if !self.enabled { return (l, r); } - l *= self.preamp; - r *= self.preamp; for band in &mut self.bands { (l, r) = band.process_stereo(l, r); } @@ -357,31 +178,3 @@ impl AudioEnergyAnalyzer { (self.bass_smooth * 5.2).clamp(0.0, 1.0) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_official_18_eq_presets_and_biquad_stability() { - assert_eq!(EQ_PRESETS.len(), 18); - assert_eq!(EQ_FREQS[0], 60.0); - assert_eq!(EQ_FREQS[9], 16000.0); - assert_eq!(active_eq_preset_name(&EQ_PRESETS[0].gains, true), "По умолчанию"); - assert_eq!(active_eq_preset_name(&EQ_PRESETS[13].gains, false), "Rock"); - assert_eq!(active_eq_preset_name(&[1.2; 10], true), "Своя настройка"); - assert_eq!(active_eq_preset_name(&[1.2; 10], false), "Custom settings"); - - let mut eq = Equalizer10Band::new(48_000.0); - eq.update(true, 1.25, EQ_PRESETS[5].gains); - for i in 0..1024 { - let s = (i as f32 * 0.1).sin() * 0.5; - let (l, r) = eq.process(s, -s); - assert!(l.is_finite() && r.is_finite()); - } - let mut eq_pre = Equalizer10Band::new(48_000.0); - eq_pre.update(true, 0.5, [0.0; 10]); - let (pl, pr) = eq_pre.process(0.4, -0.4); - assert!((pl - 0.2).abs() < 1e-4 && (pr + 0.2).abs() < 1e-4); - } -} diff --git a/src/audio/mod.rs b/src/audio/mod.rs index bf28cdd..e5cc967 100644 --- a/src/audio/mod.rs +++ b/src/audio/mod.rs @@ -16,7 +16,7 @@ use symphonia::core::meta::MetadataOptions; use symphonia::core::probe::Hint; use symphonia::core::units::Time; -use crate::api::models::{ResolvedStream, TrackFade}; +use crate::api::models::ResolvedStream; use crate::api::signing::decrypt_encraw_at_offset; use dsp::{AudioEnergyAnalyzer, Equalizer10Band}; @@ -31,21 +31,8 @@ pub enum AudioCommand { duration_ms: u64, r128_i: Option, r128_tp: Option, - fade: Option, seek_seq: u64, }, - PreloadNext { - track_id: String, - stream: ResolvedStream, - duration_ms: u64, - r128_i: Option, - r128_tp: Option, - fade: Option, - preload_gen: u64, - }, - ClearPreload { - preload_gen: u64, - }, Play, Pause, Stop { @@ -66,17 +53,14 @@ pub struct SharedAudioState { pub muted: AtomicBool, pub normalize_loudness: AtomicBool, pub track_gain_bits: AtomicU32, - pub crossfade_enabled: AtomicBool, pub crossfade_secs_bits: AtomicU32, pub energy_bits: AtomicU32, pub bass_bits: AtomicU32, pub eq_enabled: AtomicBool, - pub eq_preamp_bits: AtomicU32, pub eq_bands: Mutex<[f32; 10]>, pub active_codec: Mutex, pub output_device_name: Mutex, pub last_error: Mutex>, - pub crossfaded_track_id: Mutex>, } impl SharedAudioState { @@ -84,10 +68,8 @@ impl SharedAudioState { volume: f32, muted: bool, eq_enabled: bool, - eq_preamp: f32, eq_bands: [f32; 10], normalize_loudness: bool, - crossfade_enabled: bool, crossfade_secs: f32, ) -> Self { Self { @@ -102,17 +84,14 @@ impl SharedAudioState { muted: AtomicBool::new(muted), normalize_loudness: AtomicBool::new(normalize_loudness), track_gain_bits: AtomicU32::new(1.0f32.to_bits()), - crossfade_enabled: AtomicBool::new(crossfade_enabled), crossfade_secs_bits: AtomicU32::new(crossfade_secs.clamp(0.0, 12.0).to_bits()), energy_bits: AtomicU32::new(0.0f32.to_bits()), bass_bits: AtomicU32::new(0.0f32.to_bits()), eq_enabled: AtomicBool::new(eq_enabled), - eq_preamp_bits: AtomicU32::new(eq_preamp.clamp(0.5, 1.5).to_bits()), eq_bands: Mutex::new(eq_bands), active_codec: Mutex::new("FLAC / WASAPI".into()), output_device_name: Mutex::new("Системное устройство (WASAPI)".into()), last_error: Mutex::new(None), - crossfaded_track_id: Mutex::new(None), } } @@ -165,7 +144,6 @@ pub fn compute_r128_gain( pub struct AudioEngine { tx_cmd: Sender, pub state: Arc, - preload_gen: AtomicU64, } impl AudioEngine { @@ -173,20 +151,16 @@ impl AudioEngine { volume: f32, muted: bool, eq_enabled: bool, - eq_preamp: f32, eq_bands: [f32; 10], normalize_loudness: bool, - crossfade_enabled: bool, crossfade_secs: f32, ) -> Self { let state = Arc::new(SharedAudioState::new( volume, muted, eq_enabled, - eq_preamp, eq_bands, normalize_loudness, - crossfade_enabled, crossfade_secs, )); let (tx_cmd, rx_cmd) = unbounded(); @@ -197,30 +171,16 @@ impl AudioEngine { .spawn(move || run_audio_worker(rx_cmd, state_bg)) .expect("Failed to spawn audio thread"); - Self { - tx_cmd, - state, - preload_gen: AtomicU64::new(0), - } + Self { tx_cmd, state } } /// Silent, thread-free audio engine for deterministic headless visual tests. - pub fn new_headless( - volume: f32, - muted: bool, - eq_enabled: bool, - eq_preamp: f32, - eq_bands: [f32; 10], - ) -> Self { + pub fn new_headless(volume: f32, muted: bool, eq_enabled: bool, eq_bands: [f32; 10]) -> Self { let state = Arc::new(SharedAudioState::new( - volume, muted, eq_enabled, eq_preamp, eq_bands, true, false, 0.0, + volume, muted, eq_enabled, eq_bands, true, 0.0, )); let (tx_cmd, _rx_cmd) = unbounded(); - Self { - tx_cmd, - state, - preload_gen: AtomicU64::new(0), - } + Self { tx_cmd, state } } pub fn load_stream( @@ -230,10 +190,7 @@ impl AudioEngine { duration_ms: u64, r128_i: Option, r128_tp: Option, - fade: Option, ) { - self.preload_gen.fetch_add(1, Ordering::SeqCst); - *self.state.crossfaded_track_id.lock() = None; let seek_seq = { let _guard = self.state.position_lock.lock(); let seq = self.state.seek_seq.fetch_add(1, Ordering::SeqCst) + 1; @@ -261,39 +218,10 @@ impl AudioEngine { duration_ms, r128_i, r128_tp, - fade, seek_seq, }); } - pub fn preload_next( - &self, - track_id: String, - stream: ResolvedStream, - duration_ms: u64, - r128_i: Option, - r128_tp: Option, - fade: Option, - ) { - let gen = self.preload_gen.fetch_add(1, Ordering::SeqCst) + 1; - let _ = self.tx_cmd.send(AudioCommand::PreloadNext { - track_id, - stream, - duration_ms, - r128_i, - r128_tp, - fade, - preload_gen: gen, - }); - } - - pub fn clear_preload(&self) { - let gen = self.preload_gen.fetch_add(1, Ordering::SeqCst) + 1; - let _ = self - .tx_cmd - .send(AudioCommand::ClearPreload { preload_gen: gen }); - } - pub fn play(&self) { self.state.is_playing.store(true, Ordering::SeqCst); let _ = self.tx_cmd.send(AudioCommand::Play); @@ -315,8 +243,6 @@ impl AudioEngine { } pub fn stop(&self) { - self.preload_gen.fetch_add(1, Ordering::SeqCst); - *self.state.crossfaded_track_id.lock() = None; let seek_seq = { let _guard = self.state.position_lock.lock(); let seq = self.state.seek_seq.fetch_add(1, Ordering::SeqCst) + 1; @@ -359,31 +285,20 @@ impl AudioEngine { } } - pub fn set_crossfade_enabled(&self, enabled: bool) { - self.state.crossfade_enabled.store(enabled, Ordering::Relaxed); - } - pub fn set_crossfade_secs(&self, secs: f32) { self.state .crossfade_secs_bits .store(secs.clamp(0.0, 12.0).to_bits(), Ordering::Relaxed); } - pub fn set_eq(&self, enabled: bool, preamp: f32, bands: [f32; 10]) { + pub fn set_eq(&self, enabled: bool, bands: [f32; 10]) { self.state.eq_enabled.store(enabled, Ordering::Relaxed); - self.state - .eq_preamp_bits - .store(preamp.clamp(0.5, 1.5).to_bits(), Ordering::Relaxed); *self.state.eq_bands.lock() = bands; } pub fn take_track_finished(&self) -> bool { self.state.track_finished.swap(false, Ordering::SeqCst) } - - pub fn take_crossfaded_track_id(&self) -> Option { - self.state.crossfaded_track_id.lock().take() - } } // ============================================================================= @@ -522,20 +437,6 @@ struct ActiveStreamDecoder { min_report_frames: u64, total_frames: u64, eof: bool, - meta_track_id: String, - duration_ms: u64, - codec_label: String, - r128_i: Option, - r128_tp: Option, - gain_applied: bool, - fade: Option, - fade_in_window: Option<(u64, u64)>, -} - -struct OutgoingCrossfade { - dec: ActiveStreamDecoder, - start_frame: u64, - stop_frame: u64, } impl ActiveStreamDecoder { @@ -833,115 +734,9 @@ fn open_streaming_decoder( min_report_frames: 0, total_frames, eof: false, - meta_track_id: String::new(), - duration_ms: fallback_duration_ms, - codec_label: format!("{} {} kbps", stream.codec_label, stream.bitrate_kbps), - r128_i: None, - r128_tp: None, - gain_applied: stream.gain_applied, - fade: None, - fade_in_window: None, }) } -#[inline] -fn deck_gain(dec: &ActiveStreamDecoder, normalize: bool) -> f32 { - compute_r128_gain(normalize, dec.gain_applied, dec.r128_i, dec.r128_tp) -} - -#[inline] -fn fade_out_gain(t: f32) -> f32 { - (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).cos() -} - -#[inline] -fn fade_in_gain(t: f32) -> f32 { - (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin() -} - -pub(crate) fn compute_crossfade_out_window( - fade: Option, - total_frames: u64, - device_rate: u32, - crossfade_enabled: bool, - crossfade_secs: f32, -) -> Option<(u64, u64)> { - let rate = device_rate.max(1) as u64; - if !crossfade_enabled || total_frames < rate * 4 { - return None; - } - if crossfade_secs > 0.1 { - let cf = ((crossfade_secs.clamp(0.5, 12.0) * rate as f32) as u64).min(total_frames / 3); - return Some((total_frames.saturating_sub(cf), total_frames)); - } - if let Some(f) = fade.filter(|f| f.is_valid()) { - let min_start = total_frames / 2; - let out_start = ((f.out_start * rate as f32) as u64).clamp(min_start, total_frames); - let mut out_stop = ((f.out_stop * rate as f32) as u64).clamp(out_start, total_frames); - let min_dur = rate / 2; - let max_dur = rate * 12; - if out_stop.saturating_sub(out_start) < min_dur { - out_stop = (out_start + min_dur).min(total_frames); - } - if out_stop.saturating_sub(out_start) > max_dur { - out_stop = (out_start + max_dur).min(total_frames); - } - if out_stop > out_start + 100 { - return Some((out_start, out_stop)); - } - } - let cf = ((3.5 * rate as f32) as u64).min(total_frames / 3); - Some((total_frames.saturating_sub(cf), total_frames)) -} - -pub(crate) fn compute_crossfade_in_window( - fade: Option, - total_frames: u64, - device_rate: u32, - crossfade_enabled: bool, - crossfade_secs: f32, -) -> Option<(u64, u64)> { - let rate = device_rate.max(1) as u64; - if !crossfade_enabled || total_frames < rate * 4 { - return None; - } - if crossfade_secs > 0.1 { - let cf = ((crossfade_secs.clamp(0.5, 12.0) * rate as f32) as u64).min(total_frames / 3); - return Some((0, cf)); - } - if let Some(f) = fade.filter(|f| f.is_valid()) { - let in_start = ((f.in_start * rate as f32) as u64).min(total_frames / 3); - let mut in_stop = ((f.in_stop * rate as f32) as u64).clamp(in_start, total_frames / 2); - let min_dur = rate / 2; - let max_dur = rate * 12; - if in_stop.saturating_sub(in_start) < min_dur { - in_stop = (in_start + rate * 3).min(total_frames / 2); - } - if in_stop.saturating_sub(in_start) > max_dur { - in_stop = (in_start + max_dur).min(total_frames / 2); - } - if in_stop > in_start + 100 { - return Some((in_start, in_stop)); - } - } - let cf = ((3.5 * rate as f32) as u64).min(total_frames / 3); - Some((0, cf)) -} - -fn next_stereo_frame(dec: &mut ActiveStreamDecoder) -> Option<(f32, f32)> { - if dec.pending_idx + 1 >= dec.pending.len() && !dec.decode_next_packet() { - return None; - } - if dec.pending_idx + 1 >= dec.pending.len() { - return None; - } - let l = dec.pending[dec.pending_idx]; - let r = dec.pending[dec.pending_idx + 1]; - dec.pending_idx += 2; - dec.played_frames += 1; - Some((l, r)) -} - /// Atomically publish decoder playback position ONLY if no newer `seek_ms` / `load_stream` / `stop` /// has occurred since `applied_seek_seq`. Prevents stale decoder frames from teleporting the seek bar /// back to the pre-seek position! @@ -1036,13 +831,12 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc 0.0 } }; - let gain = vol; + let track_gain = state_cb.track_gain(); + let gain = vol * track_gain; let eq_on = state_cb.eq_enabled.load(Ordering::Relaxed); - let preamp = f32::from_bits(state_cb.eq_preamp_bits.load(Ordering::Relaxed)) - .clamp(0.5, 1.5); if let Some(bands) = state_cb.eq_bands.try_lock() { - eq.update(eq_on, preamp, *bands); + eq.update(eq_on, *bands); } if !playing { @@ -1104,25 +898,10 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc .ok(); let mut active: Option = None; - let mut outgoing: Option = None; - let mut preloaded: Option = None; - let mut latest_preload_gen: u64 = 0; - let (tx_preloaded, rx_preloaded) = - crossbeam_channel::unbounded::<(u64, ActiveStreamDecoder)>(); let mut applied_seek_seq: u64 = 0; let mut flush_wait_iters: u8 = 0; loop { - while let Ok((gen, dec)) = rx_preloaded.try_recv() { - if gen == latest_preload_gen { - if let Some(old) = preloaded.replace(dec) { - old.abort(); - } - } else { - dec.abort(); - } - } - let mut raw_cmds = Vec::new(); while let Ok(cmd) = rx_cmd.try_recv() { raw_cmds.push(cmd); @@ -1132,24 +911,15 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc for cmd in non_seeks { match cmd { AudioCommand::LoadStream { - track_id, stream, duration_ms, r128_i, r128_tp, - fade, .. } => { if let Some(old) = active.take() { old.abort(); } - if let Some(old_out) = outgoing.take() { - old_out.dec.abort(); - } - if let Some(old_pre) = preloaded.take() { - old_pre.abort(); - } - latest_preload_gen = latest_preload_gen.wrapping_add(1); flush_rb.store(true, Ordering::Release); flush_wait_iters = 0; state.is_buffering.store(true, Ordering::SeqCst); @@ -1165,18 +935,13 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc if let Some(ref rt) = rt { match open_streaming_decoder(rt.handle(), &stream, device_rate, duration_ms) { - Ok(mut dec) => { + Ok(dec) => { if dec.total_frames > device_rate as u64 { let ms = (dec.total_frames * 1000) / device_rate as u64; state.duration_ms.store(ms, Ordering::SeqCst); } else { state.duration_ms.store(duration_ms, Ordering::SeqCst); } - dec.meta_track_id = track_id; - dec.duration_ms = duration_ms; - dec.r128_i = r128_i; - dec.r128_tp = r128_tp; - dec.fade = fade; active = Some(dec); state.is_playing.store(true, Ordering::SeqCst); } @@ -1190,42 +955,6 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc } state.is_buffering.store(false, Ordering::SeqCst); } - AudioCommand::PreloadNext { - track_id, - stream, - duration_ms, - r128_i, - r128_tp, - fade, - preload_gen, - } => { - latest_preload_gen = preload_gen; - if let Some(old_pre) = preloaded.take() { - old_pre.abort(); - } - if let Some(ref rt) = rt { - let handle = rt.handle().clone(); - let tx_p = tx_preloaded.clone(); - rt.spawn_blocking(move || { - if let Ok(mut dec) = - open_streaming_decoder(&handle, &stream, device_rate, duration_ms) - { - dec.meta_track_id = track_id; - dec.duration_ms = duration_ms; - dec.r128_i = r128_i; - dec.r128_tp = r128_tp; - dec.fade = fade; - let _ = tx_p.send((preload_gen, dec)); - } - }); - } - } - AudioCommand::ClearPreload { preload_gen } => { - latest_preload_gen = preload_gen; - if let Some(old_pre) = preloaded.take() { - old_pre.abort(); - } - } AudioCommand::Play => { state.is_playing.store(true, Ordering::SeqCst); } @@ -1237,13 +966,6 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc if let Some(old) = active.take() { old.abort(); } - if let Some(old_out) = outgoing.take() { - old_out.dec.abort(); - } - if let Some(old_pre) = preloaded.take() { - old_pre.abort(); - } - latest_preload_gen = latest_preload_gen.wrapping_add(1); flush_rb.store(true, Ordering::Release); flush_wait_iters = 0; } @@ -1254,11 +976,7 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc if let Some((ms, seq)) = pending_seek { flush_rb.store(true, Ordering::Release); flush_wait_iters = 0; - if let Some(old_out) = outgoing.take() { - old_out.dec.abort(); - } if let Some(ref mut dec) = active { - dec.fade_in_window = None; if dec.seek_ms(ms) { dec.played_frames = (ms * device_rate as u64) / 1000; dec.min_report_frames = dec.played_frames; @@ -1285,150 +1003,38 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc } let mut pushed_any = false; - let cf_enabled = state.crossfade_enabled.load(Ordering::Relaxed); - let cf_secs = state.crossfade_secs(); - let normalize = state.normalize_loudness.load(Ordering::Relaxed); - - if active.is_some() { + if let Some(ref mut dec) = active { + let cf_frames = (state.crossfade_secs() * device_rate as f32) as u64; while prod.vacant_len() >= 2048 { + // Bail immediately if a newer seek/load/stop arrived so we don't decode stale audio. if applied_seek_seq != state.seek_seq.load(Ordering::Acquire) { break; } - - // Trigger overlapping crossfade if preloaded next deck is ready and we reached out_start - let should_crossfade = { - let dec = active.as_ref().unwrap(); - preloaded.is_some() - && outgoing.is_none() - && compute_crossfade_out_window( - dec.fade, - dec.total_frames, - device_rate, - cf_enabled, - cf_secs, - ) - .map_or(false, |(out_start, _)| dec.played_frames >= out_start) - }; - - if should_crossfade { - let old_dec = active.take().unwrap(); - let (out_start, out_stop) = compute_crossfade_out_window( - old_dec.fade, - old_dec.total_frames, - device_rate, - cf_enabled, - cf_secs, - ) - .unwrap_or((old_dec.played_frames, old_dec.total_frames)); - - let mut next_dec = preloaded.take().unwrap(); - if let Some((in_start, in_stop)) = compute_crossfade_in_window( - next_dec.fade, - next_dec.total_frames, - device_rate, - cf_enabled, - cf_secs, - ) { - if in_start > device_rate as u64 / 20 { - let seek_ms = (in_start * 1000) / device_rate as u64; - if next_dec.seek_ms(seek_ms) { - next_dec.played_frames = in_start; - next_dec.min_report_frames = in_start; - } - } - next_dec.fade_in_window = Some((in_start, in_stop)); - } - - let new_tid = next_dec.meta_track_id.clone(); - let new_dur = if next_dec.total_frames > device_rate as u64 { - (next_dec.total_frames * 1000) / device_rate as u64 - } else { - next_dec.duration_ms - }; - state.duration_ms.store(new_dur, Ordering::SeqCst); - *state.active_codec.lock() = next_dec.codec_label.clone(); - let new_pos_ms = (next_dec.played_frames * 1000) / device_rate as u64; - publish_decoder_position_ms(&state, applied_seek_seq, new_pos_ms); - *state.crossfaded_track_id.lock() = Some(new_tid); - - outgoing = Some(OutgoingCrossfade { - dec: old_dec, - start_frame: out_start, - stop_frame: out_stop.max(out_start + 1), - }); - active = Some(next_dec); - } - - // Decode up to 1024 stereo frames from active + optional outgoing crossfade deck - let mut frames_mixed = 0usize; - while frames_mixed < 1024 { - let dec = active.as_mut().unwrap(); - let Some((al, ar)) = next_stereo_frame(dec) else { - break; - }; - let mut in_gain = deck_gain(dec, normalize); - if let Some((in_start, in_stop)) = dec.fade_in_window { - let span = in_stop.saturating_sub(in_start).max(1) as f32; - let prog = (dec.played_frames.saturating_sub(in_start) as f32) / span; - in_gain *= fade_in_gain(prog); - if dec.played_frames >= in_stop { - dec.fade_in_window = None; - } - } - - let mut mix_l = al * in_gain; - let mut mix_r = ar * in_gain; - - if let Some(ref mut out) = outgoing { - if let Some((ol, or)) = next_stereo_frame(&mut out.dec) { - let span = out.stop_frame.saturating_sub(out.start_frame).max(1) as f32; - let prog = (out.dec.played_frames.saturating_sub(out.start_frame) as f32) - / span; - let og = deck_gain(&out.dec, normalize) * fade_out_gain(prog); - mix_l = (mix_l + ol * og).clamp(-1.0, 1.0); - mix_r = (mix_r + or * og).clamp(-1.0, 1.0); - if out.dec.played_frames >= out.stop_frame { - if let Some(done) = outgoing.take() { - done.dec.abort(); - } - } - } else if let Some(done) = outgoing.take() { - done.dec.abort(); - } - } - - let _ = prod.try_push(mix_l); - let _ = prod.try_push(mix_r); - frames_mixed += 1; - } - - if frames_mixed == 0 { - // Gapless handoff if active reached EOF and next track is preloaded! - let dec_eof = active.as_ref().map_or(false, |d| d.eof && d.pending_idx >= d.pending.len()); - if dec_eof { - if let Some(mut next_dec) = preloaded.take() { - if let Some(old_done) = active.take() { - old_done.abort(); - } - let new_tid = next_dec.meta_track_id.clone(); - let new_dur = if next_dec.total_frames > device_rate as u64 { - (next_dec.total_frames * 1000) / device_rate as u64 - } else { - next_dec.duration_ms - }; - next_dec.fade_in_window = None; - state.duration_ms.store(new_dur, Ordering::SeqCst); - *state.active_codec.lock() = next_dec.codec_label.clone(); - publish_decoder_position_ms(&state, applied_seek_seq, 0); - *state.crossfaded_track_id.lock() = Some(new_tid); - active = Some(next_dec); - continue; - } - } + if dec.pending_idx >= dec.pending.len() && !dec.decode_next_packet() { break; } - - let dec = active.as_ref().unwrap(); + let avail = (dec.pending.len() - dec.pending_idx).min(2048) & !1; + if avail == 0 { + break; + } + for pair in dec.pending[dec.pending_idx..dec.pending_idx + avail].chunks_exact(2) { + // Smooth crossfade envelope (fade-in at start, fade-out near end when enabled) + let mut env = 1.0_f32; + if cf_frames > 0 { + if dec.played_frames < cf_frames { + env = (dec.played_frames as f32 / cf_frames as f32).clamp(0.0, 1.0); + } else if dec.total_frames > cf_frames + && dec.played_frames + cf_frames > dec.total_frames + { + let rem = dec.total_frames.saturating_sub(dec.played_frames); + env = (rem as f32 / cf_frames as f32).clamp(0.0, 1.0); + } + } + let _ = prod.try_push(pair[0] * env); + let _ = prod.try_push(pair[1] * env); + dec.played_frames += 1; + } + dec.pending_idx += avail; let buffered_frames = if _cpal_stream.is_some() { (prod.occupied_len() / 2) as u64 } else { @@ -1443,29 +1049,24 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc pushed_any = true; } + // Keep audible playback position smoothly updating while CPAL drains the ring buffer. if !pushed_any && _cpal_stream.is_some() && !flush_rb.load(Ordering::Acquire) { - if let Some(ref dec) = active { - let buffered_frames = (prod.occupied_len() / 2) as u64; - let audible_frames = dec - .played_frames - .saturating_sub(buffered_frames) - .max(dec.min_report_frames); - let pos_ms = (audible_frames * 1000) / device_rate as u64; - publish_decoder_position_ms(&state, applied_seek_seq, pos_ms); - } + let buffered_frames = (prod.occupied_len() / 2) as u64; + let audible_frames = dec + .played_frames + .saturating_sub(buffered_frames) + .max(dec.min_report_frames); + let pos_ms = (audible_frames * 1000) / device_rate as u64; + publish_decoder_position_ms(&state, applied_seek_seq, pos_ms); } - if active.as_ref().map_or(false, |dec| { - dec.eof - && dec.pending_idx >= dec.pending.len() - && applied_seek_seq == state.seek_seq.load(Ordering::Acquire) - }) { + if dec.eof + && dec.pending_idx >= dec.pending.len() + && applied_seek_seq == state.seek_seq.load(Ordering::Acquire) + { state.is_playing.store(false, Ordering::SeqCst); state.track_finished.store(true, Ordering::SeqCst); active = None; - if let Some(old_out) = outgoing.take() { - old_out.dec.abort(); - } } } @@ -1481,7 +1082,7 @@ mod tests { #[test] fn seek_seq_prevents_stale_decoder_position_overwrite() { - let engine = AudioEngine::new_headless(0.8, false, false, 1.0, [0.0; 10]); + let engine = AudioEngine::new_headless(0.8, false, false, [0.0; 10]); // Initial playback at seq 0 publishes normally. assert!(publish_decoder_position_ms(&engine.state, 0, 30_000)); @@ -1540,7 +1141,7 @@ mod tests { #[test] fn stop_bumps_seek_seq_preventing_old_decoder_overwrite() { - let engine = AudioEngine::new_headless(0.8, false, false, 1.0, [0.0; 10]); + let engine = AudioEngine::new_headless(0.8, false, false, [0.0; 10]); assert!(publish_decoder_position_ms(&engine.state, 0, 45_000)); engine.stop(); assert_eq!(engine.state.position_ms.load(Ordering::Acquire), 0); @@ -1548,36 +1149,4 @@ mod tests { assert!(!publish_decoder_position_ms(&engine.state, 0, 45_200)); assert_eq!(engine.state.position_ms.load(Ordering::Acquire), 0); } - - #[test] - fn test_crossfade_windows_and_equal_power_curves() { - let rate = 48_000u32; - let total = 200 * rate as u64; - let smart = TrackFade { - in_start: 0.5, - in_stop: 4.5, - out_start: 194.0, - out_stop: 199.0, - }; - assert_eq!( - compute_crossfade_out_window(Some(smart), total, rate, false, 0.0), - None - ); - let out_auto = compute_crossfade_out_window(Some(smart), total, rate, true, 0.0).unwrap(); - assert_eq!(out_auto, (194 * rate as u64, 199 * rate as u64)); - let in_auto = compute_crossfade_in_window(Some(smart), total, rate, true, 0.0).unwrap(); - assert_eq!(in_auto, (rate as u64 / 2, (4.5 * rate as f32) as u64)); - - // Fallback when track has no `fade` metadata - let out_fb = compute_crossfade_out_window(None, total, rate, true, 0.0).unwrap(); - assert_eq!(out_fb.1 - out_fb.0, (3.5 * rate as f32) as u64); - - // Manual duration override - let out_man = compute_crossfade_out_window(Some(smart), total, rate, true, 6.0).unwrap(); - assert_eq!(out_man.1 - out_man.0, 6 * rate as u64); - - // Equal-power crossfade preserves constant power at midpoint (0.5^2 + 0.5^2 -> 1.0) - let p_mid = fade_out_gain(0.5).powi(2) + fade_in_gain(0.5).powi(2); - assert!((p_mid - 1.0).abs() < 1e-5); - } } diff --git a/src/bin/yandex_music_auth.rs b/src/bin/yandex_music_auth.rs deleted file mode 100644 index 142d8cd..0000000 --- a/src/bin/yandex_music_auth.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - yandex_music_rs::native::run_auth_webview_subprocess(); -} diff --git a/src/config.rs b/src/config.rs index c3c293a..45cae2b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -10,48 +10,6 @@ pub enum ThemeMode { Light, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] -pub enum PlayerThumbStyle { - #[default] - Standard, - Duck, - Car, - Claudik, - Antigravity, - Ferris, - Nyan, -} - -impl PlayerThumbStyle { - pub const ALL: &'static [Self] = &[ - Self::Standard, - Self::Duck, - Self::Car, - Self::Claudik, - Self::Antigravity, - Self::Ferris, - Self::Nyan, - ]; - - pub const fn label(self, ru: bool) -> &'static str { - match (self, ru) { - (Self::Standard, true) => "Стандартный", - (Self::Standard, false) => "Default", - (Self::Duck, true) => "Уточка", - (Self::Duck, false) => "Duck", - (Self::Car, true) => "Машинка", - (Self::Car, false) => "Car", - (Self::Claudik, true) => "Клодик", - (Self::Claudik, false) => "Claudik", - (Self::Antigravity, _) => "Antigravity", - (Self::Ferris, true) => "Феррис", - (Self::Ferris, false) => "Ferris", - (Self::Nyan, true) => "Нян-кот", - (Self::Nyan, false) => "Nyan Cat", - } - } -} - impl ThemeMode { /// Resolve `ThemeMode::System` to concrete dark/light boolean via Windows Registry `AppsUseLightTheme` /// (exact match to Chromium's `prefers-color-scheme: light` in Electron 5.129.0). @@ -194,12 +152,8 @@ pub struct AppConfig { pub muted: bool, pub sidebar_collapsed: bool, pub eq_enabled: bool, - #[serde(default = "default_eq_preamp")] - pub eq_preamp: f32, - pub eq_bands_db: [f32; 10], // 60, 170, 310, 600, 1k, 3k, 6k, 12k, 14k, 16k Hz + pub eq_bands_db: [f32; 10], // 32, 64, 125, 250, 500, 1k, 2k, 4k, 8k, 16k Hz pub normalize_loudness: bool, - #[serde(default = "default_true")] - pub crossfade_enabled: bool, pub crossfade_secs: f32, #[serde(default)] pub ai_content_reduction: bool, @@ -207,8 +161,6 @@ pub struct AppConfig { pub child_mode: bool, #[serde(default = "default_true")] pub close_to_tray: bool, - #[serde(default)] - pub player_thumb: PlayerThumbStyle, pub max_cover_cache: usize, pub show_perf_hud: bool, pub search_history: Vec, @@ -241,10 +193,6 @@ fn default_true() -> bool { true } -fn default_eq_preamp() -> f32 { - 1.0 -} - impl Default for AppConfig { fn default() -> Self { Self { @@ -256,15 +204,12 @@ impl Default for AppConfig { muted: false, sidebar_collapsed: false, eq_enabled: false, - eq_preamp: 1.0, eq_bands_db: [0.0; 10], normalize_loudness: true, - crossfade_enabled: true, crossfade_secs: 0.0, ai_content_reduction: false, child_mode: false, close_to_tray: true, - player_thumb: PlayerThumbStyle::Standard, max_cover_cache: 256, show_perf_hud: false, search_history: Vec::new(), diff --git a/src/covers.rs b/src/covers.rs index d69996b..4407d93 100644 --- a/src/covers.rs +++ b/src/covers.rs @@ -7,24 +7,15 @@ use std::sync::Arc; use crate::engine::textures::TextureRegistry; use crate::engine::types::{Color, TextureId}; -/// Hard minimum LRU cover cache capacity. -/// Leaner on Linux integrated-GPU (UMA) builds where GL textures live directly in system RAM! -#[cfg(all(target_os = "linux", not(test)))] -pub const MIN_COVER_CACHE_CAPACITY: usize = 64; -#[cfg(not(all(target_os = "linux", not(test))))] +/// Hard minimum LRU cover cache capacity so even dense pages (Artist/Collection + sidebar + player) +/// can never thrash or flicker visible avatars/covers. pub const MIN_COVER_CACHE_CAPACITY: usize = 128; - -#[cfg(all(target_os = "linux", not(test)))] -const MAX_AUTO_GROW_CAPACITY: usize = 128; -#[cfg(not(all(target_os = "linux", not(test))))] const MAX_AUTO_GROW_CAPACITY: usize = 1024; pub struct CoverEntry { pub texture_id: TextureId, pub dominant_color: Color, pub hue: f32, - pub width: u32, - pub height: u32, pub last_used_frame: u64, } @@ -157,8 +148,6 @@ impl CoverCache { texture_id: tex_id, dominant_color: dom, hue, - width: width as u32, - height: height as u32, last_used_frame: frame_id, }, ); @@ -186,8 +175,6 @@ impl CoverCache { texture_id: tex_id, dominant_color: dom, hue, - width: width as u32, - height: height as u32, last_used_frame: frame_id, }, ); @@ -221,8 +208,6 @@ impl CoverCache { texture_id: tex_id, dominant_color: done.dominant_color, hue: done.hue, - width: done.width, - height: done.height, last_used_frame: frame_id, }, ); @@ -261,17 +246,6 @@ impl CoverCache { /// Reuses an already-cached higher-resolution entry (`200x200` / `400x400`) when available /// because our Vulkan SDF renderer samples full hardware mipmap chains cleanly at any size! pub fn get_or_fetch(&mut self, uri: &str, size_px: u32) -> Option<(TextureId, Color, f32)> { - self.get_or_fetch_with_size(uri, size_px) - .map(|(tex, dom, hue, _, _)| (tex, dom, hue)) - } - - /// Returns `(TextureId, dominant_color, hue, width, height)` if loaded, or triggers background fetch. - /// Exposes decoded pixel dimensions so `draw_cover_art` can apply exact `object-fit: cover` UV cropping. - pub fn get_or_fetch_with_size( - &mut self, - uri: &str, - size_px: u32, - ) -> Option<(TextureId, Color, f32, u32, u32)> { if uri.is_empty() { return None; } @@ -279,13 +253,7 @@ impl CoverCache { let url = Self::format_url(uri, size_px); if let Some(entry) = self.cache.get_mut(&url) { entry.last_used_frame = frame_id; - return Some(( - entry.texture_id, - entry.dominant_color, - entry.hue, - entry.width, - entry.height, - )); + return Some((entry.texture_id, entry.dominant_color, entry.hue)); } // Cross-resolution mipmap reuse: if a higher-resolution variant is already cached, @@ -304,13 +272,7 @@ impl CoverCache { } if let Some(entry) = self.cache.get_mut(&hi_url) { entry.last_used_frame = frame_id; - return Some(( - entry.texture_id, - entry.dominant_color, - entry.hue, - entry.width, - entry.height, - )); + return Some((entry.texture_id, entry.dominant_color, entry.hue)); } if self.in_flight.contains(&hi_url) { return None; @@ -373,9 +335,7 @@ fn decode_and_analyze(bytes: &[u8], target_px: u32) -> Option<(u32, u32, Vec let (ow, oh) = (dyn_img.width(), dyn_img.height()); let max_dim = target_px.max(128); if ow > max_dim || oh > max_dim { - // Preserve original aspect ratio so non-square concert posters / banners never stretch; - // `draw_cover_art` applies CSS `object-fit: cover` UV cropping using `(width, height)`. - dyn_img = dyn_img.resize(max_dim, max_dim, image::imageops::FilterType::Lanczos3); + dyn_img = dyn_img.resize_exact(max_dim, max_dim, image::imageops::FilterType::Lanczos3); } let rgba = dyn_img.to_rgba8(); let (w, h) = rgba.dimensions(); diff --git a/src/engine/input.rs b/src/engine/input.rs index ffa0819..659dac3 100644 --- a/src/engine/input.rs +++ b/src/engine/input.rs @@ -277,7 +277,7 @@ impl InputState { self.pointer_pos = Some(next); if self.left_down { if let Some(origin) = self.drag_origin { - if origin.distance(next) >= 5.0 { + if origin.distance(next) >= 3.0 { self.is_dragging = true; } } @@ -407,7 +407,7 @@ impl InputState { let prev_time = self.time; self.time = time; self.dt = if prev_time > 0.0 && time > prev_time { - ((time - prev_time) as f32).clamp(0.001, 0.033) + ((time - prev_time) as f32).clamp(0.001, 0.1) } else { 1.0 / 60.0 }; @@ -554,36 +554,6 @@ impl InputState { } } - /// Consume the current pointer press (`active_id = None`, `left_pressed = false`, - /// `right_pressed = false`) so releasing over an underlying widget cannot trigger a click/drag. - pub fn consume_pointer_press(&mut self) { - self.active_id = None; - self.left_pressed = false; - self.right_pressed = false; - } - - /// Like `clicked_outside`, but also consumes the dismissing press (`active_id = None`, - /// `left_pressed = false`, `right_pressed = false`) so releasing over an underlying - /// toggle trigger button (e.g. PlayerBar EQ button) can NEVER re-open the overlay. - pub fn consume_clicked_outside(&mut self, rect: Rect) -> bool { - if self.clicked_outside(rect) { - self.consume_pointer_press(); - true - } else { - false - } - } - - /// Multi-rect variant of `consume_clicked_outside`. - pub fn consume_clicked_outside_any(&mut self, rects: &[Rect]) -> bool { - if self.clicked_outside_any(rects) { - self.consume_pointer_press(); - true - } else { - false - } - } - pub fn key_pressed(&self, key: Key) -> bool { self.key_events.iter().any(|e| e.key == key) } @@ -724,47 +694,3 @@ impl Animator { self.values.clear(); } } - -#[cfg(test)] -mod tests { - use super::*; - use winit::dpi::PhysicalPosition; - - #[test] - fn test_consume_clicked_outside_prevents_trigger_reopen_on_release() { - let mut input = InputState::new(); - let screen = Vec2::new(1280.0, 800.0); - let trigger_id = WidgetId::new("pb_r_eq"); - let trigger_r = Rect::from_xywh(1000.0, 740.0, 36.0, 36.0); - let pop_r = Rect::from_xywh(800.0, 400.0, 430.0, 300.0); - - // Frame 1: Mouse down on the underlying trigger button while popover is open. - input.begin_frame(screen, 1.0, 1.0); - input.handle_winit_event(&WindowEvent::CursorMoved { - device_id: unsafe { std::mem::zeroed() }, - position: PhysicalPosition::new(1018.0, 758.0), - }); - input.handle_winit_event(&WindowEvent::MouseInput { - device_id: unsafe { std::mem::zeroed() }, - state: ElementState::Pressed, - button: MouseButton::Left, - }); - - let press_resp = input.interact(trigger_id, ZLayer::Base, trigger_r, None); - assert!(!press_resp.clicked); - assert!(input.consume_clicked_outside(pop_r)); - assert!(input.active_id.is_none()); - input.end_frame(); - - // Frame 2: Mouse up over the same trigger button — MUST NOT fire clicked! - input.begin_frame(screen, 1.0, 1.05); - input.handle_winit_event(&WindowEvent::MouseInput { - device_id: unsafe { std::mem::zeroed() }, - state: ElementState::Released, - button: MouseButton::Left, - }); - let rel_resp = input.interact(trigger_id, ZLayer::Base, trigger_r, None); - assert!(!rel_resp.clicked); - input.end_frame(); - } -} diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 56dacf3..7dea5c8 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -117,8 +117,7 @@ impl UiContext { if let Some((anchor, label)) = self.pending_tooltip.take() { let prev = self.set_layer(ZLayer::Titlebar); let pad_x = 10.0; - let text_style = TextStyle::medium(12.0, pal.text_primary); - let text_sz = self.measure_text(&label, text_style, None); + let text_sz = self.measure_text(&label, TextStyle::medium(12.0, Color::WHITE), None); let tip_w = text_sz.x + pad_x * 2.0; let tip_h = 26.0; let screen = self.input.screen_size; @@ -133,16 +132,15 @@ impl UiContext { tx = tx.round(); ty = ty.round(); let tip_r = Rect::from_xywh(tx, ty, tip_w, tip_h); - let tip_bg = if pal.is_dark { - Color::rgb(0x26, 0x26, 0x26) - } else { - Color::WHITE - }; self.dl() - .push_shadow(tip_r, 8.0, 10.0, 0.0, Vec2::new(0.0, 2.0), pal.shadow_menu); - self.dl() - .push_rect_bordered(tip_r, 8.0, tip_bg, 1.0, pal.border_control); - self.draw_text_ellipsis(&label, text_style, tip_r, TextAlign::Center); + .push_shadow(tip_r, 8.0, 10.0, 0.0, Vec2::new(0.0, 2.0), css_rgba(0, 0, 0, 110)); + self.dl().push_rect(tip_r, 8.0, pal.bg_tooltip); + self.draw_text_ellipsis( + &label, + TextStyle::medium(12.0, Color::WHITE), + tip_r, + TextAlign::Center, + ); self.set_layer(prev); } @@ -154,9 +152,7 @@ impl UiContext { let texture_uploads = self.textures.drain_uploads(); let immediate_repaint = self.repaint_requested || self.animator.needs_repaint() || !texture_uploads.is_empty(); - let repaint_after = if self.repaint_requested || !texture_uploads.is_empty() { - Some(std::time::Duration::from_millis(1)) - } else if self.animator.needs_repaint() { + let repaint_after = if immediate_repaint { Some(std::time::Duration::from_millis(16)) } else { self.repaint_after @@ -370,28 +366,6 @@ impl UiContext { .draw_text_wrapped(dl, &mut self.textures, text, style, rect, max_lines, align) } - /// Draw wrapped multi-line text vertically centered inside `rect` and uniformly scaled - /// around `rect.center()` by `scale` (CSS `transform: scale(...)` without wrap-jump). - pub fn draw_text_wrapped_scaled( - &mut self, - text: &str, - style: TextStyle, - rect: Rect, - scale: f32, - align: TextAlign, - ) -> Vec2 { - let dl = &mut self.layers[self.current_layer.index()]; - self.text.draw_text_wrapped_scaled( - dl, - &mut self.textures, - text, - style, - rect, - scale, - align, - ) - } - pub fn draw_rich_text( &mut self, spans: &[RichSpan<'_>], diff --git a/src/engine/scroll.rs b/src/engine/scroll.rs index c8f5c22..9755e10 100644 --- a/src/engine/scroll.rs +++ b/src/engine/scroll.rs @@ -135,7 +135,7 @@ impl ScrollState { if horizontal { let dx = if input.wheel_delta.x.abs() > 0.01 { -input.wheel_delta.x - } else if input.modifiers.shift { + } else if !vertical || input.modifiers.shift { -input.wheel_delta.y } else { 0.0 diff --git a/src/engine/text.rs b/src/engine/text.rs index 1507d18..fe6ff44 100644 --- a/src/engine/text.rs +++ b/src/engine/text.rs @@ -13,7 +13,7 @@ use crate::engine::types::{ Color, DisplayList, Pos2, Rect, Vec2, GLYPH_ATLAS_TEXTURE_ID, }; -const ATLAS_SIZE: u32 = 1024; +const ATLAS_SIZE: u32 = 2048; /// The 4 official Yandex Music 5.129.0 font roles loaded from `assets/fonts/`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -332,25 +332,8 @@ impl TextEngine { db.set_sans_serif_family(&ys_text_family); - // On Linux, avoid indexing all 400+ system fonts (saves 20-40 MB RSS from Noto CJK/Emoji); - // load only 1-2 lean symbol/fallback faces alongside our 4 embedded official Yandex fonts. - #[cfg(target_os = "linux")] - { - for path in [ - "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", - "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", - "/usr/share/fonts/truetype/noto/NotoSansSymbols2-Regular.ttf", - ] { - if std::path::Path::new(path).is_file() { - let _ = db.load_font_file(path); - } - } - } - #[cfg(not(target_os = "linux"))] - { - // Load system fallback fonts for rare symbols / emoji / CJK - db.load_system_fonts(); - } + // Load system fallback fonts for rare symbols / emoji / CJK + db.load_system_fonts(); let font_system = FontSystem::new_with_locale_and_db("ru-RU".to_string(), db); @@ -469,68 +452,6 @@ impl TextEngine { size } - /// Draw wrapped multi-line text vertically centered inside `rect` and uniformly scaled - /// around `rect.center()` by `scale` (1-to-1 CSS `transform: scale(...)` with zero wrap-jump - /// or fractional-size glyph atlas churn). - #[allow(clippy::too_many_arguments)] - pub fn draw_text_wrapped_scaled( - &mut self, - dl: &mut DisplayList, - textures: &mut TextureRegistry, - text: &str, - style: TextStyle, - rect: Rect, - scale: f32, - align: TextAlign, - ) -> Vec2 { - if text.is_empty() || style.color.a == 0 || rect.w <= 1.0 || scale <= 0.001 { - return Vec2::ZERO; - } - let (key, size) = self.get_or_shape(text, style, Some(rect.w), None, false, align); - let origin = Pos2::new(rect.x, rect.center_y() - size.y * 0.5); - if (scale - 1.0).abs() < 0.0005 { - self.emit_cached_buffer(dl, textures, key, origin, style.color, None); - return size; - } - let Some((buffer, _)) = self.shape_cache.get(&key) else { - return size; - }; - - let dpi = self.scale_factor; - let inv_dpi = 1.0 / dpi; - let origin_px = (origin.x * dpi).round(); - let center = rect.center(); - - let mut glyphs_to_draw = Vec::with_capacity(64); - for run in buffer.layout_runs() { - let baseline_py = ((origin.y + run.line_y) * dpi).floor(); - for glyph in run.glyphs.iter() { - let phys = glyph.physical((0.0, 0.0), dpi); - glyphs_to_draw.push((phys, baseline_py)); - } - } - for (phys, baseline_py) in glyphs_to_draw { - if let Some(entry) = self.atlas.get_or_insert( - phys.cache_key, - &mut self.font_system, - &mut self.swash_cache, - textures, - ) { - let gx = (origin_px + (phys.x + entry.left) as f32) * inv_dpi; - let gy = (baseline_py + (phys.y - entry.top) as f32) * inv_dpi; - let gw = entry.width as f32 * inv_dpi; - let gh = entry.height as f32 * inv_dpi; - - let sx = center.x + (gx - center.x) * scale; - let sy = center.y + (gy - center.y) * scale; - let sw = gw * scale; - let sh = gh * scale; - dl.push_glyph(Rect::from_xywh(sx, sy, sw, sh), entry.uv, style.color); - } - } - size - } - /// Draw multi-span rich text (e.g. clickable `SeparatedArtists` or `Title + Version`) inside `rect`. /// Returns screen-space bounding `Rect`s for every span whose `metadata != 0` so callers can /// perform exact per-span hover & click hit-testing! diff --git a/src/engine/widgets.rs b/src/engine/widgets.rs index 646aeff..b440305 100644 --- a/src/engine/widgets.rs +++ b/src/engine/widgets.rs @@ -374,32 +374,7 @@ pub fn draw_plus_badge( (resp, rect) } -/// Compute exact CSS `object-fit: cover` UV sub-rect so images never stretch when -/// `(tex_w / tex_h)` differs from `dst.w / dst.h`. -/// Uses `focal_y` (e.g. `0.35`) when cropping vertically so portrait faces/heads stay framed, -/// and `0.5` when cropping horizontally. -#[inline] -pub fn cover_fit_uv(tex_w: u32, tex_h: u32, dst: Rect, focal_y: f32) -> Rect { - if tex_w == 0 || tex_h == 0 || dst.w <= 0.0 || dst.h <= 0.0 { - return Rect::UNIT_UV; - } - let tex_ar = tex_w as f32 / tex_h as f32; - let dst_ar = dst.w / dst.h; - if (tex_ar - dst_ar).abs() < 0.015 { - return Rect::UNIT_UV; - } - if tex_ar > dst_ar { - let uw = (dst_ar / tex_ar).clamp(0.01, 1.0); - let u = (1.0 - uw) * 0.5; - Rect::from_xywh(u, 0.0, uw, 1.0) - } else { - let vh = (tex_ar / dst_ar).clamp(0.01, 1.0); - let v = (1.0 - vh) * focal_y.clamp(0.0, 1.0); - Rect::from_xywh(0.0, v, 1.0, vh) - } -} - -/// Draw cover artwork with SDF rounded-rect / circular clip and CSS `object-fit: cover` UV crop: +/// Draw cover artwork with SDF rounded-rect / circular clip: /// - When `special_likes == true`: exact crimson vignette `#8D0F10 -> #59090A` + centered official `heart.png` /// with SDF rounded-rect clip (ZERO `+9.5%` y-shift bug!). If a real CDN cover URI is loaded, uses it. /// - Otherwise: renders real fetched cover texture with SDF rounded/circle clip, or theme-aware neutral placeholder. @@ -424,10 +399,9 @@ pub fn draw_cover_art( if special_likes { // Prefer real CDN cover if provided & already loaded if let Some(u) = uri { - let px = rect.width().max(rect.height()).ceil() as u32; - if let Some((tex_id, dom, hue, tw, th)) = covers.get_or_fetch_with_size(u, px) { - let uv = cover_fit_uv(tw, th, rect, 0.35); - ctx.dl().push_image_uv(rect, tex_id, uv, cr, Color::WHITE); + let px = rect.width().ceil() as u32; + if let Some((tex_id, dom, hue)) = covers.get_or_fetch(u, px) { + ctx.dl().push_image(rect, tex_id, cr, Color::WHITE); return (dom, hue); } } @@ -454,10 +428,9 @@ pub fn draw_cover_art( } if let Some(u) = uri { - let px = rect.width().max(rect.height()).ceil() as u32; - if let Some((tex_id, dom, hue, tw, th)) = covers.get_or_fetch_with_size(u, px) { - let uv = cover_fit_uv(tw, th, rect, 0.35); - ctx.dl().push_image_uv(rect, tex_id, uv, cr, Color::WHITE); + let px = rect.width().ceil() as u32; + if let Some((tex_id, dom, hue)) = covers.get_or_fetch(u, px) { + ctx.dl().push_image(rect, tex_id, cr, Color::WHITE); return (dom, hue); } } @@ -512,8 +485,6 @@ pub struct TrackRowOptions { pub is_liked: bool, pub is_disliked: bool, pub is_downloaded: bool, - pub is_downloading: bool, - pub download_progress: f32, pub menu_open: bool, } @@ -528,8 +499,6 @@ impl Default for TrackRowOptions { is_liked: false, is_disliked: false, is_downloaded: false, - is_downloading: false, - download_progress: 0.0, menu_open: false, } } @@ -698,13 +667,8 @@ pub fn track_row( pal.text_secondary }; - // Title + optional version + explicit badge + downloaded/downloading badge - let badge_w = if track.is_explicit { 22.0 } else { 0.0 } - + if opts.is_downloaded || opts.is_downloading { - 20.0 - } else { - 0.0 - }; + // Title + optional version + explicit badge + downloaded badge + let badge_w = if track.is_explicit { 22.0 } else { 0.0 } + if opts.is_downloaded { 20.0 } else { 0.0 }; let title_rect = Rect::from_xywh(x, rect.top() + 9.5, (title_col_w - badge_w).max(40.0), 20.0); let version_text = track .version @@ -738,17 +702,7 @@ pub fn track_row( ); badge_x += 22.0; } - if opts.is_downloading { - draw_downloading_progress( - ctx, - pal, - Pos2::new(badge_x + 8.0, title_rect.center_y()), - 16.0, - opts.download_progress, - false, - false, - ); - } else if opts.is_downloaded { + if opts.is_downloaded { ctx.draw_icon( Icon::Downloaded, Rect::from_center_size(Pos2::new(badge_x + 8.0, title_rect.center_y()), Vec2::splat(16.0)), @@ -1147,9 +1101,8 @@ pub fn stacked_mix_card( let card_r = Rect::from_xywh(plate_x, plate_y + 8.0, plate_w, plate_w); let mut drew_tex = false; if let Some(u) = cover_uri { - if let Some((tex_id, _, _, tw, th)) = covers.get_or_fetch_with_size(u, 200) { - let uv = cover_fit_uv(tw, th, card_r, 0.35); - ctx.dl().push_image_uv(card_r, tex_id, uv, 6.0, Color::WHITE); + if let Some((tex_id, _, _)) = covers.get_or_fetch(u, 200) { + ctx.dl().push_image(card_r, tex_id, 6.0, Color::WHITE); drew_tex = true; } } @@ -1228,9 +1181,8 @@ pub fn artist_promo_card( // 1. Full-bleed artist photo (or theme-aware gradient placeholder) let mut has_photo = false; if let Some(u) = artist_photo_uri { - if let Some((tex_id, _, _, tw, th)) = covers.get_or_fetch_with_size(u, 400) { - let uv = cover_fit_uv(tw, th, img_r, 0.35); - ctx.dl().push_image_uv(img_r, tex_id, uv, 8.0, Color::WHITE); + if let Some((tex_id, _, _)) = covers.get_or_fetch(u, 400) { + ctx.dl().push_image(img_r, tex_id, 8.0, Color::WHITE); has_photo = true; } } @@ -1818,76 +1770,3 @@ pub fn draw_playing_eq_bars( ctx.request_repaint_after(std::time::Duration::from_millis(40)); } } - -/// Smooth circular progress ring matching official Yandex Music 5.129.0 `CircleProgress` (`68254`). -pub fn draw_circular_progress_ring( - ctx: &mut UiContext, - center: Pos2, - radius: f32, - stroke_w: f32, - progress: f32, - track_color: Color, - progress_color: Color, -) { - use std::f32::consts::{FRAC_PI_2, TAU}; - - ctx.dl() - .push_circle_stroke(center, radius, stroke_w, track_color); - - let frac = progress.clamp(0.0, 1.0); - let (start_angle, sweep) = if frac < 0.03 { - if ctx.input.time > 0.001 { - ctx.request_repaint_after(std::time::Duration::from_millis(24)); - } - ((ctx.input.time as f32 * 3.2) - FRAC_PI_2, 0.24 * TAU) - } else { - (-FRAC_PI_2, frac * TAU) - }; - - let segments = ((sweep / TAU) * 32.0).ceil().max(4.0) as usize; - let step = sweep / segments as f32; - for i in 0..segments { - let a0 = start_angle + i as f32 * step; - let a1 = start_angle + (i + 1) as f32 * step; - let p0 = Pos2::new(center.x + radius * a0.cos(), center.y + radius * a0.sin()); - let p1 = Pos2::new(center.x + radius * a1.cos(), center.y + radius * a1.sin()); - ctx.dl().push_line(p0, p1, stroke_w, progress_color); - } -} - -/// Official Yandex Music 5.129.0 `DownloadingProgress` (`79262` / `63298c27abf81dc6.css:210-218`): -/// yellow circular progress ring with optional centered `close` (`×`) cancel icon. -pub fn draw_downloading_progress( - ctx: &mut UiContext, - pal: &YmPalette, - center: Pos2, - size: f32, - progress: f32, - with_cancel_icon: bool, - hovered: bool, -) { - let stroke_w = if size >= 22.0 { 2.2 } else { 1.8 }; - let radius = ((size - stroke_w) * 0.5).max(3.0); - draw_circular_progress_ring( - ctx, - center, - radius, - stroke_w, - progress, - pal.border_control, - pal.yellow, - ); - if with_cancel_icon { - let icon_sz = (size * 0.42).clamp(8.0, 12.0); - let tint = if hovered { - pal.text_bright - } else { - pal.text_primary - }; - ctx.draw_icon( - Icon::Close, - Rect::from_center_size(center, Vec2::splat(icon_sz)), - tint, - ); - } -} diff --git a/src/icons.rs b/src/icons.rs index 1a49a0c..7798f39 100644 --- a/src/icons.rs +++ b/src/icons.rs @@ -113,26 +113,15 @@ pub enum Icon { PauseFilledXs, LinkXxs, YandexPlusEn, - // Dedicated Yandex ID Profile & Appearance icons (v2.79.0) + WordsCard thumbs + // Dedicated Yandex ID Profile & Appearance icons ProfileAccountXxs, - ProfileSettingsXxs, ProfileSupportXxs, ProfileGlobeXxs, ProfileAppearanceXxs, - ProfileAddAccountXxs, ProfileLogoutXxs, - ProfilePlusXxs, ThemeSystemXxs, ThemeDarkXxs, ThemeLightXxs, - ThumbUpXxs, - ThumbDownXxs, - YandexIdLogoRuDark, - YandexIdLogoRuLight, - YandexIdLogoEnDark, - YandexIdLogoEnLight, - ThumbDuck, - ThumbCar, } impl Icon { @@ -245,24 +234,13 @@ impl Icon { Icon::LinkXxs => include_bytes!("../assets/icons/link_xxs.svg"), Icon::YandexPlusEn => include_bytes!("../assets/icons/yandexPlusEn.svg"), Icon::ProfileAccountXxs => include_bytes!("../assets/icons/profile_account_xxs.svg"), - Icon::ProfileSettingsXxs => include_bytes!("../assets/icons/profile_settings_xxs.svg"), Icon::ProfileSupportXxs => include_bytes!("../assets/icons/profile_support_xxs.svg"), Icon::ProfileGlobeXxs => include_bytes!("../assets/icons/profile_globe_xxs.svg"), Icon::ProfileAppearanceXxs => include_bytes!("../assets/icons/profile_appearance_xxs.svg"), - Icon::ProfileAddAccountXxs => include_bytes!("../assets/icons/profile_add_account_xxs.svg"), Icon::ProfileLogoutXxs => include_bytes!("../assets/icons/profile_logout_xxs.svg"), - Icon::ProfilePlusXxs => include_bytes!("../assets/icons/profile_plus_xxs.svg"), Icon::ThemeSystemXxs => include_bytes!("../assets/icons/theme_system_xxs.svg"), Icon::ThemeDarkXxs => include_bytes!("../assets/icons/theme_dark_xxs.svg"), Icon::ThemeLightXxs => include_bytes!("../assets/icons/theme_light_xxs.svg"), - Icon::ThumbUpXxs => include_bytes!("../assets/icons/thumb_up_xxs.svg"), - Icon::ThumbDownXxs => include_bytes!("../assets/icons/thumb_down_xxs.svg"), - Icon::YandexIdLogoRuDark => include_bytes!("../assets/icons/yandex_id_logo_ru_dark.svg"), - Icon::YandexIdLogoRuLight => include_bytes!("../assets/icons/yandex_id_logo_ru_light.svg"), - Icon::YandexIdLogoEnDark => include_bytes!("../assets/icons/yandex_id_logo_en_dark.svg"), - Icon::YandexIdLogoEnLight => include_bytes!("../assets/icons/yandex_id_logo_en_light.svg"), - Icon::ThumbDuck => include_bytes!("../assets/icons/thumb_duck.svg"), - Icon::ThumbCar => include_bytes!("../assets/icons/thumb_car.svg"), } } @@ -271,12 +249,6 @@ impl Icon { Icon::MusicLogoLeftEn => (276, 96), Icon::MusicLogoLeftRu => (256, 72), Icon::YandexPlusRu | Icon::YandexPlusEn => (160, 44), - Icon::YandexIdLogoRuDark - | Icon::YandexIdLogoRuLight - | Icon::YandexIdLogoEnDark - | Icon::YandexIdLogoEnLight => (124, 60), - Icon::ThumbDuck => (96, 96), - Icon::ThumbCar => (220, 68), Icon::MusicLogo | Icon::PlayFilled | Icon::PauseFilled | Icon::PlayLarge | Icon::PauseLarge => (72, 72), _ => (48, 48), } @@ -396,24 +368,13 @@ impl Icon { Icon::LinkXxs, Icon::YandexPlusEn, Icon::ProfileAccountXxs, - Icon::ProfileSettingsXxs, Icon::ProfileSupportXxs, Icon::ProfileGlobeXxs, Icon::ProfileAppearanceXxs, - Icon::ProfileAddAccountXxs, Icon::ProfileLogoutXxs, - Icon::ProfilePlusXxs, Icon::ThemeSystemXxs, Icon::ThemeDarkXxs, Icon::ThemeLightXxs, - Icon::ThumbUpXxs, - Icon::ThumbDownXxs, - Icon::YandexIdLogoRuDark, - Icon::YandexIdLogoRuLight, - Icon::YandexIdLogoEnDark, - Icon::YandexIdLogoEnLight, - Icon::ThumbDuck, - Icon::ThumbCar, ]; } diff --git a/src/main.rs b/src/main.rs index 7f44916..afd9149 100644 --- a/src/main.rs +++ b/src/main.rs @@ -135,8 +135,7 @@ fn build_window_attrs(init_w: f64, init_h: f64) -> WindowAttributes { .with_inner_size(LogicalSize::new(init_w, init_h)) .with_min_inner_size(LogicalSize::new(768.0, 650.0)) .with_decorations(false) // Custom frameless 32px Yandex TitleBar! - .with_resizable(true) - .with_visible(false); // Stay hidden until DWM + first pure-black/splash frame is presented! + .with_resizable(true); #[cfg(target_os = "linux")] { use winit::platform::wayland::WindowAttributesExtWayland; @@ -169,32 +168,6 @@ fn init_opengl_backend( Ok((window, RenderBackend::OpenGl(gl))) } -/// Probe hardware Vulkan in an isolated short-lived subprocess on Linux so Mesa's software -/// `libvulkan_lvp.so` + `libLLVM.so` (~80–100 MB) are NEVER mapped into the main OpenGL player -/// process on legacy GPUs without hardware Vulkan (e.g. Intel HD Graphics 3000). -fn has_hardware_vulkan_isolated() -> bool { - #[cfg(target_os = "linux")] - { - use std::process::{Command, Stdio}; - if let Ok(exe) = std::env::current_exe() { - if let Ok(status) = Command::new(exe) - .arg("--probe-vulkan") - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status() - { - return status.success(); - } - } - false - } - #[cfg(not(target_os = "linux"))] - { - VulkanContext::has_hardware_vulkan() - } -} - struct AppRunner { runtime: tokio::runtime::Runtime, // Drop GPU backend BEFORE the native winit Window so Vulkan/GL surfaces destroy cleanly! @@ -439,12 +412,7 @@ impl AppRunner { let is_max = window.is_maximized(); let elapsed = shell.elapsed_secs(); - let had_splash = shell.splash.is_some(); let (frame, win_cmd) = shell.render_frame(logical, sf, elapsed, is_max); - if had_splash && shell.splash.is_none() { - telemetry::PerfTelemetry::trim_working_set(); - shell.app.perf.sample_memory(); - } // Sync cursor icon if frame.cursor != self.last_cursor { @@ -592,7 +560,7 @@ impl ApplicationHandler for AppRunner { RendererPreference::Vulkan => init_vulkan_backend(event_loop, init_w, init_h) .expect("Failed to initialize Vulkan renderer (--renderer=vulkan)"), RendererPreference::Auto => { - if has_hardware_vulkan_isolated() { + if VulkanContext::has_hardware_vulkan() { match init_vulkan_backend(event_loop, init_w, init_h) { Ok(pair) => pair, Err(vk_err) => { @@ -660,17 +628,6 @@ impl ApplicationHandler for AppRunner { self.window_focused = true; self.window_occluded = false; self.last_frame_hash = None; - - // Present the first theme-matched + splash frame into the swapchain BEFORE making the - // window visible so there is zero white OS/DWM flash on startup! - // (On Linux/Wayland where an unmapped window may report 0x0, skip pre-render and reveal.) - let init_size = window.inner_size(); - if init_size.width > 0 && init_size.height > 0 { - self.render(event_loop); - self.last_frame_hash = None; - } - window.set_visible(true); - window.focus_window(); window.request_redraw(); } @@ -923,76 +880,6 @@ fn apply_win11_dwm_style(window: &Window, is_dark: bool) { &round as *const _ as *const _, std::mem::size_of::() as u32, ); - // DWMWA_CAPTION_COLOR (35): pure black in dark mode, pure white in light mode - const DWMWA_CAPTION_COLOR: u32 = 35; - let caption_color: u32 = if is_dark { 0x0000_0000 } else { 0x00FF_FFFF }; - DwmSetWindowAttribute( - hwnd, - DWMWA_CAPTION_COLOR, - &caption_color as *const _ as *const _, - std::mem::size_of::() as u32, - ); - - // Replace Win32 class background brush (BLACK_BRUSH=4 / WHITE_BRUSH=0) & prime - // the client backing surface so Win32 never flashes white before or during resize. - #[repr(C)] - struct WinRect { - left: i32, - top: i32, - right: i32, - bottom: i32, - } - #[link(name = "gdi32")] - extern "system" { - fn GetStockObject(i: i32) -> *mut std::ffi::c_void; - } - #[link(name = "user32")] - extern "system" { - #[cfg(target_pointer_width = "64")] - fn SetClassLongPtrW( - hwnd: *mut std::ffi::c_void, - index: i32, - new_long: isize, - ) -> isize; - #[cfg(target_pointer_width = "32")] - fn SetClassLongW( - hwnd: *mut std::ffi::c_void, - index: i32, - new_long: i32, - ) -> i32; - fn GetClientRect(hwnd: *mut std::ffi::c_void, rect: *mut WinRect) -> i32; - fn GetDC(hwnd: *mut std::ffi::c_void) -> *mut std::ffi::c_void; - fn FillRect( - hdc: *mut std::ffi::c_void, - rect: *const WinRect, - hbr: *mut std::ffi::c_void, - ) -> i32; - fn ReleaseDC(hwnd: *mut std::ffi::c_void, hdc: *mut std::ffi::c_void) -> i32; - } - const WHITE_BRUSH: i32 = 0; - const BLACK_BRUSH: i32 = 4; - const GCLP_HBRBACKGROUND: i32 = -10; - let brush = GetStockObject(if is_dark { BLACK_BRUSH } else { WHITE_BRUSH }); - if !brush.is_null() { - #[cfg(target_pointer_width = "64")] - SetClassLongPtrW(hwnd, GCLP_HBRBACKGROUND, brush as isize); - #[cfg(target_pointer_width = "32")] - SetClassLongW(hwnd, GCLP_HBRBACKGROUND, brush as i32); - - let mut rc = WinRect { - left: 0, - top: 0, - right: 0, - bottom: 0, - }; - if GetClientRect(hwnd, &mut rc) != 0 { - let hdc = GetDC(hwnd); - if !hdc.is_null() { - FillRect(hdc, &rc, brush); - ReleaseDC(hwnd, hdc); - } - } - } } } } @@ -1058,30 +945,7 @@ fn acquire_single_instance_lock() -> bool { true } -#[cfg(all(target_os = "linux", target_env = "gnu"))] -fn tune_linux_glibc_allocator() { - extern "C" { - fn mallopt(param: std::ffi::c_int, value: std::ffi::c_int) -> std::ffi::c_int; - } - const M_TRIM_THRESHOLD: std::ffi::c_int = -1; - const M_MMAP_THRESHOLD: std::ffi::c_int = -3; - const M_ARENA_MAX: std::ffi::c_int = -8; - unsafe { - let _ = mallopt(M_ARENA_MAX, 2); - let _ = mallopt(M_TRIM_THRESHOLD, 128 * 1024); - let _ = mallopt(M_MMAP_THRESHOLD, 128 * 1024); - } -} - fn main() { - #[cfg(all(target_os = "linux", target_env = "gnu"))] - tune_linux_glibc_allocator(); - - // Isolated Vulkan HW probe subprocess (keeps libvulkan_lvp / libLLVM out of main Linux RSS) - if std::env::args().any(|a| a == "--probe-vulkan") { - std::process::exit(if VulkanContext::has_hardware_vulkan() { 0 } else { 1 }); - } - // Isolated zero-resident-RAM WebView2 OAuth subprocess (exits immediately after login!) if std::env::args().any(|a| a == "--auth-webview") { run_auth_webview_subprocess(); diff --git a/src/native/mod.rs b/src/native/mod.rs index dadd154..3e97f70 100644 --- a/src/native/mod.rs +++ b/src/native/mod.rs @@ -451,267 +451,26 @@ mod imp { mod imp { use super::NativeEvent; use crate::api::models::Track; - use crossbeam_channel::{unbounded, Receiver, Sender}; - use ksni::blocking::{Handle, TrayMethods}; - use std::io::{BufRead, BufReader}; + use crate::api::signing::extract_oauth_token; + use crate::api::YANDEX_OAUTH_URL; + use gtk::prelude::*; + use std::io::{BufRead, BufReader, Write}; use std::process::{Command, Stdio}; - use std::sync::Arc; use winit::window::Window; + use wry::{WebViewBuilder, WebViewBuilderExtUnix}; const OAUTH_TOKEN_PREFIX: &str = "YM_OAUTH_TOKEN:"; - struct LinuxTray { - tx: Sender, - icons: Arc>, - is_ru: bool, - window_visible: bool, - is_playing: bool, - track_summary: String, - } - - impl ksni::Tray for LinuxTray { - fn id(&self) -> String { - "yandex-music-rs".into() - } - - fn category(&self) -> ksni::Category { - ksni::Category::ApplicationStatus - } - - fn title(&self) -> String { - if self.is_ru { - "Яндекс Музыка".into() - } else { - "Yandex Music".into() - } - } - - fn icon_name(&self) -> String { - "yandex-music-rs".into() - } - - fn icon_pixmap(&self) -> Vec { - (*self.icons).clone() - } - - fn tool_tip(&self) -> ksni::ToolTip { - ksni::ToolTip { - icon_name: "yandex-music-rs".into(), - icon_pixmap: Vec::new(), - title: self.title(), - description: self.track_summary.clone(), - } - } - - fn activate(&mut self, _x: i32, _y: i32) { - let _ = self.tx.send(NativeEvent::ToggleWindow); - } - - fn menu(&self) -> Vec> { - use ksni::menu::*; - let toggle_label = if self.window_visible { - if self.is_ru { "Скрыть" } else { "Hide" } - } else if self.is_ru { - "Показать" - } else { - "Show" - }; - let play_label = if self.is_playing { - if self.is_ru { "Пауза" } else { "Pause" } - } else if self.is_ru { - "Играть" - } else { - "Play" - }; - let ver_label = if self.is_ru { - format!("Яндекс Музыка {}", env!("CARGO_PKG_VERSION")) - } else { - format!("Yandex Music {}", env!("CARGO_PKG_VERSION")) - }; - - vec![ - StandardItem { - label: toggle_label.into(), - activate: Box::new(|this: &mut Self| { - let _ = this.tx.send(NativeEvent::ToggleWindow); - }), - ..Default::default() - } - .into(), - StandardItem { - label: if self.is_ru { - "Проверить обновления".into() - } else { - "Check updates".into() - }, - activate: Box::new(|this: &mut Self| { - let _ = this.tx.send(NativeEvent::CheckUpdates); - }), - ..Default::default() - } - .into(), - MenuItem::Separator, - StandardItem { - label: play_label.into(), - activate: Box::new(|this: &mut Self| { - let _ = this.tx.send(NativeEvent::TogglePlay); - }), - ..Default::default() - } - .into(), - StandardItem { - label: if self.is_ru { - "Предыдущий трек".into() - } else { - "Previous song".into() - }, - activate: Box::new(|this: &mut Self| { - let _ = this.tx.send(NativeEvent::Prev); - }), - ..Default::default() - } - .into(), - StandardItem { - label: if self.is_ru { - "Следующий трек".into() - } else { - "Next song".into() - }, - activate: Box::new(|this: &mut Self| { - let _ = this.tx.send(NativeEvent::Next); - }), - ..Default::default() - } - .into(), - MenuItem::Separator, - SubMenu { - label: if self.is_ru { - "О приложении".into() - } else { - "About the app".into() - }, - submenu: vec![StandardItem { - label: ver_label, - enabled: false, - ..Default::default() - } - .into()], - ..Default::default() - } - .into(), - MenuItem::Separator, - StandardItem { - label: if self.is_ru { - "Закрыть приложение".into() - } else { - "Close app".into() - }, - activate: Box::new(|this: &mut Self| { - let _ = this.tx.send(NativeEvent::QuitApp); - }), - ..Default::default() - } - .into(), - ] - } - } - - fn decode_ksni_icon(png_bytes: &[u8]) -> Option { - let img = image::load_from_memory(png_bytes).ok()?.to_rgba8(); - let (w, h) = img.dimensions(); - let mut data = img.into_raw(); - for px in data.chunks_exact_mut(4) { - px.rotate_right(1); // RGBA -> ARGB32 network byte order (SNI spec) - } - Some(ksni::Icon { - width: w as i32, - height: h as i32, - data, - }) - } - - pub struct NativeDesktop { - handle: Option>, - rx: Receiver, - last_playing: Option, - last_track_id: Option, - } - - impl Drop for NativeDesktop { - fn drop(&mut self) { - if let Some(ref handle) = self.handle { - handle.shutdown(); - } - } - } - + pub struct NativeDesktop; impl NativeDesktop { - pub fn new(_window: &Window, is_ru: bool) -> Self { - let (tx, rx) = unbounded(); - let mut pixmaps = Vec::with_capacity(2); - if let Some(ic32) = decode_ksni_icon(include_bytes!("../../assets/icons/tray_32.png")) { - pixmaps.push(ic32); - } - if let Some(ic48) = decode_ksni_icon(include_bytes!("../../assets/icons/app_48.png")) { - pixmaps.push(ic48); - } - let tray = LinuxTray { - tx, - icons: Arc::new(pixmaps), - is_ru, - window_visible: true, - is_playing: false, - track_summary: String::new(), - }; - let handle = tray.assume_sni_available(true).spawn().ok(); - Self { - handle, - rx, - last_playing: None, - last_track_id: None, - } + pub fn new(_window: &Window, _is_ru: bool) -> Self { + Self } - - pub fn set_window_visible_label(&self, visible: bool) { - if let Some(ref handle) = self.handle { - handle.update(move |t| { - t.window_visible = visible; - }); - } - } - + pub fn set_window_visible_label(&self, _visible: bool) {} pub fn poll_events(&self) -> Vec { - let mut out = Vec::new(); - while let Ok(ev) = self.rx.try_recv() { - out.push(ev); - } - out - } - - pub fn sync_playback(&mut self, track: Option<&Track>, is_playing: bool, _pos_ms: u64) { - let track_id = track.map(|t| t.id.as_str()); - if self.last_playing == Some(is_playing) && self.last_track_id.as_deref() == track_id { - return; - } - self.last_playing = Some(is_playing); - self.last_track_id = track_id.map(String::from); - let summary = track - .map(|tr| { - let artists = tr.artists_string(); - if artists.is_empty() { - tr.title.clone() - } else { - format!("{} — {}", artists, tr.title) - } - }) - .unwrap_or_default(); - if let Some(ref handle) = self.handle { - handle.update(move |t| { - t.is_playing = is_playing; - t.track_summary = summary; - }); - } + Vec::new() } + pub fn sync_playback(&mut self, _track: Option<&Track>, _is_playing: bool, _pos_ms: u64) {} } pub fn load_window_icon() -> Option { @@ -721,17 +480,8 @@ mod imp { winit::window::Icon::from_rgba(img.into_raw(), w, h).ok() } - /// Entry point for the short-lived `yandex-music-auth` subprocess on Linux (GTK3 + WebKitGTK). - /// Compiled ONLY when `--features linux-webview` is enabled so the main player binary has - /// zero `libwebkit2gtk` / `libjavascriptcoregtk` / `libgtk-3` DT_NEEDED dependencies! - #[cfg(feature = "linux-webview")] + /// Entry point for the short-lived `--auth-webview` subprocess on Linux (GTK3 + WebKitGTK). pub fn run_auth_webview_subprocess() { - use crate::api::signing::extract_oauth_token; - use crate::api::YANDEX_OAUTH_URL; - use gtk::prelude::*; - use std::io::Write; - use wry::{WebViewBuilder, WebViewBuilderExtUnix}; - // Avoid blank WebKitGTK window on NVIDIA/Wayland/VM drivers during OAuth login. if std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_none() { std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1"); @@ -804,38 +554,14 @@ mod imp { gtk::main(); } - #[cfg(not(feature = "linux-webview"))] - pub fn run_auth_webview_subprocess() { - eprintln!("yandex-music-auth helper required"); - std::process::exit(2); - } - - /// Spawn the isolated `yandex-music-auth` helper binary (or `--auth-webview` if built with - /// `linux-webview`) and return the captured OAuth token. + /// Spawn the isolated `--auth-webview` subprocess and return the captured OAuth token. pub fn spawn_auth_webview_subprocess() -> anyhow::Result { let exe = std::env::current_exe()?; - let sibling_helper = exe.with_file_name("yandex-music-auth"); - - let mut child = if sibling_helper.is_file() { - Command::new(&sibling_helper) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn()? - } else if let Ok(c) = Command::new("yandex-music-auth") + let mut child = Command::new(exe) + .arg("--auth-webview") .stdout(Stdio::piped()) .stderr(Stdio::null()) - .spawn() - { - c - } else if cfg!(feature = "linux-webview") { - Command::new(&exe) - .arg("--auth-webview") - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn()? - } else { - anyhow::bail!("WebKitGTK auth helper (yandex-music-auth) unavailable"); - }; + .spawn()?; let stdout = child .stdout diff --git a/src/telemetry.rs b/src/telemetry.rs index 1f5995f..2df9633 100644 --- a/src/telemetry.rs +++ b/src/telemetry.rs @@ -61,17 +61,7 @@ impl PerfTelemetry { } } - #[cfg(all(target_os = "linux", target_env = "gnu"))] - pub fn trim_working_set() { - extern "C" { - fn malloc_trim(pad: usize) -> i32; - } - unsafe { - let _ = malloc_trim(0); - } - } - - #[cfg(not(any(windows, all(target_os = "linux", target_env = "gnu"))))] + #[cfg(not(windows))] pub fn trim_working_set() {} #[cfg(windows)] @@ -96,62 +86,7 @@ impl PerfTelemetry { } } - #[cfg(target_os = "linux")] - pub fn sample_memory(&mut self) { - fn parse_kb_line(line: &str, prefix: &str) -> Option { - let rest = line.strip_prefix(prefix)?; - rest.split_whitespace().next()?.parse::().ok() - } - - if let Ok(rollup) = std::fs::read_to_string("/proc/self/smaps_rollup") { - let mut rss_kb: Option = None; - let mut pss_kb: Option = None; - let mut priv_clean_kb: u64 = 0; - let mut priv_dirty_kb: u64 = 0; - let mut has_priv = false; - for line in rollup.lines() { - if let Some(v) = parse_kb_line(line, "Rss:") { - rss_kb = Some(v); - } else if let Some(v) = parse_kb_line(line, "Pss:") { - pss_kb = Some(v); - } else if let Some(v) = parse_kb_line(line, "Private_Clean:") { - priv_clean_kb = v; - has_priv = true; - } else if let Some(v) = parse_kb_line(line, "Private_Dirty:") { - priv_dirty_kb = v; - has_priv = true; - } - } - if let Some(rss) = rss_kb { - self.working_set_mb = rss as f32 / 1024.0; - let priv_kb = if has_priv { - priv_clean_kb.saturating_add(priv_dirty_kb) - } else { - pss_kb.unwrap_or(rss) - }; - self.private_mb = priv_kb as f32 / 1024.0; - return; - } - } - - if let Ok(status) = std::fs::read_to_string("/proc/self/status") { - let mut rss_kb: Option = None; - let mut anon_kb: Option = None; - for line in status.lines() { - if let Some(v) = parse_kb_line(line, "VmRSS:") { - rss_kb = Some(v); - } else if let Some(v) = parse_kb_line(line, "RssAnon:") { - anon_kb = Some(v); - } - } - if let Some(rss) = rss_kb { - self.working_set_mb = rss as f32 / 1024.0; - self.private_mb = anon_kb.unwrap_or(rss) as f32 / 1024.0; - } - } - } - - #[cfg(not(any(windows, target_os = "linux")))] + #[cfg(not(windows))] pub fn sample_memory(&mut self) { self.working_set_mb = 28.0; self.private_mb = 22.0; diff --git a/src/views/collection.rs b/src/views/collection.rs index 2016195..e4ba9bd 100644 --- a/src/views/collection.rs +++ b/src/views/collection.rs @@ -3,7 +3,7 @@ use crate::app::state::{AppAction, AppState, CollectionTab, Route}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; use crate::engine::scroll::visible_row_range; -use crate::engine::text::{RichSpan, TextAlign, TextStyle}; +use crate::engine::text::{TextAlign, TextStyle}; use crate::engine::theme::{YmPalette, TRACK_ROW_HEIGHT}; use crate::engine::types::{Color, CursorKind, Pos2, Rect, Vec2}; use crate::engine::widgets::{ @@ -14,18 +14,15 @@ use crate::engine::UiContext; use crate::icons::Icon; use crate::views::overlays::{EntityContextMenuState, ShellUiState}; -/// 1-to-1 Official Yandex Music Desktop 5.129.0 `My Collection` (`web_collection`): -/// - Default view (`CollectionTab::Tracks`): clean vertical feed: -/// - Header (`Коллекция` / `My Collection`) + colored subtitle (`У вашей музыки есть цвет`) -/// - Section 1: `❤️ Мне нравится >` transparent header + 2-column × 4-row compact track grid -/// - Section 2: `Любимые исполнители >` horizontal circular artist carousel -/// - Section 3: `Плейлисты >` horizontal carousel starting with `+ Создать плейлист` -/// - Section 4: `Альбомы >` horizontal carousel -/// - Section 5: `Подкасты и книги >` horizontal carousel (when non-empty) -/// - Section 6: `История >` 2-column × 4-row compact track grid (when non-empty) -/// - Section 7: `Скачанное >` 2-column × 4-row compact track grid (when non-empty) -/// - Sub-views (`Artists`, `Playlists`, `Albums`, `PodcastsAndBooks`, `History`, `Downloaded`): -/// clean `← Коллекция` back button + full interactive grid/list with full CRUD & menus. +/// Exact Yandex Music Desktop 5.129.0 Collection Page (`pages_api_spec.md` §5): +/// All 7 original tabs: +/// 1. Любимые треки (My Favorites) +/// 2. Плейлисты (with "+ Создать плейлист" card/button + Rename & Delete controls!) +/// 3. Альбомы (Liked albums grid) +/// 4. Исполнители (Liked artists circular grid) +/// 5. Подкасты и книги (Bookshelf / Podcasts grid) +/// 6. Скачанное (Offline downloaded tracks with play & delete from device) +/// 7. История (Listening history) pub fn render_collection( ctx: &mut UiContext, pal: &YmPalette, @@ -43,695 +40,168 @@ pub fn render_collection( let scroll_id = WidgetId::new("collection_scroll"); let scroll_y = ctx.begin_scroll_v(scroll_id, rect, 0.0); + // `views/mod.rs` already insets `inner_r` by (25, 13, 25, 0) let x = rect.left(); let avail_w = (rect.width() - 6.0).max(320.0); let mut y = rect.top() + 8.0 - scroll_y; - // ------------------------------------------------------------------------- - // DEFAULT VERTICAL OVERVIEW (`CollectionTab::Tracks`) - // ------------------------------------------------------------------------- - if app.collection_tab == CollectionTab::Tracks { - // Header: Bold 34px Headline + official colored subtitle - ctx.draw_text_ellipsis( - t.collection(), - TextStyle::headline(34.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 42.0), - TextAlign::Left, - ); - y += 44.0; - - let pink_accent = Color::rgb(0xE8, 0x3E, 0x8C); - let spans = if ru { - [ - RichSpan::new( - "У вашей музыки есть ", - TextStyle::medium(14.0, pal.text_secondary), - ), - RichSpan::new("цвет", TextStyle::medium(14.0, pink_accent)), - ] - } else { - [ - RichSpan::new( - "Your music has a ", - TextStyle::medium(14.0, pal.text_secondary), - ), - RichSpan::new("color", TextStyle::medium(14.0, pink_accent)), - ] - }; - ctx.draw_rich_text( - &spans, - Rect::from_xywh(x, y, avail_w, 24.0), - Some(1), - TextAlign::Left, - ); - y += 38.0; - - // --------------------------------------------------------------------- - // SECTION 1: ❤️ My Favorites > (transparent header + 2×4 compact grid) - // --------------------------------------------------------------------- - let fav_title = t.liked_playlist(); - { - let hdr_r = Rect::from_xywh(x, y, avail_w.min(460.0), 58.0); - let hdr_resp = ctx.interact(WidgetId::new("col_fav_header"), hdr_r); - - let cov_r = Rect::from_xywh(x, y + 1.0, 56.0, 56.0); - draw_cover_art(ctx, pal, covers, cov_r, None, "likes", 10.0, false, true); - - let tx = cov_r.right() + 14.0; - let title_style = TextStyle::headline( - 22.0, - if hdr_resp.hovered { - pal.text_bright - } else { - pal.text_primary - }, - ); - let title_w = ctx.measure_text(fav_title, title_style, None).x; - ctx.draw_text_ellipsis( - fav_title, - title_style, - Rect::from_xywh(tx, y + 4.0, (avail_w - 110.0).max(120.0), 28.0), - TextAlign::Left, - ); - ctx.draw_icon( - Icon::ArrowRight, - Rect::from_center_size( - Pos2::new( - (tx + title_w + 14.0).min(x + avail_w - 14.0), - y + 18.0, - ), - Vec2::splat(20.0), - ), - if hdr_resp.hovered { - pal.text_bright - } else { - pal.text_secondary - }, - ); - ctx.draw_text_ellipsis( - &t.count_tracks(app.liked_tracks.len()), - TextStyle::regular(13.5, pal.text_secondary), - Rect::from_xywh(tx, y + 34.0, (avail_w - 90.0).max(120.0), 20.0), - TextAlign::Left, - ); - - if hdr_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if hdr_resp.clicked { - actions.push(AppAction::Navigate(Route::LikedTracks)); - } - } - y += 58.0 + 16.0; - - if app.liked_tracks.is_empty() { - ctx.draw_text_wrapped( - if ru { - "Ставьте лайки трекам или войдите в аккаунт Яндекс Музыки — они появятся здесь." - } else { - "Like tracks or sign in to Yandex Music — they will appear here." - }, - TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 40.0), - Some(2), - TextAlign::Left, - ); - y += 48.0; - } else { - let liked_tracks = app.liked_tracks.clone(); - y = render_compact_two_col_track_grid( - ctx, - pal, - covers, - app, - shell, - rect, - x, - y, - avail_w, - &liked_tracks, - "col_ov_fav", - fav_title, - "likes", - current_track_id.as_deref(), - is_playing, - actions, - ); - y += 28.0; - } - - // --------------------------------------------------------------------- - // SECTION 2: Favorite Artists > (horizontal circular carousel) - // --------------------------------------------------------------------- - { - let art_title = if ru { - "Любимые исполнители" - } else { - "Favorite Artists" - }; - let h_id = WidgetId::new("col_ov_artists_h"); - if draw_section_heading( - ctx, - pal, - WidgetId::new("col_sec_artists"), - art_title, - x, - y, - avail_w, - Some(h_id), - !app.liked_artists.is_empty(), - ) { - app.collection_tab = CollectionTab::Artists; - } - y += 38.0; - - if app.liked_artists.is_empty() { - ctx.draw_text_ellipsis( - if ru { - "Здесь появятся ваши любимые исполнители." - } else { - "Your favorite artists will appear here." - }, - TextStyle::regular(13.5, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 22.0), - TextAlign::Left, - ); - y += 34.0; - } else { - let artists = app.liked_artists.clone(); - let card_w = 168.0; - let card_h = card_w + 52.0; - let gap = 16.0; - let row_vp = Rect::from_xywh(x, y, avail_w, card_h); - let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); - let mut cx = x - sx; - - for art in artists.iter().take(24) { - let cr = Rect::from_xywh(cx, y, card_w, card_h); - if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { - let m = media_card( - ctx, - pal, - covers, - WidgetId::from_pair("col_ov_art", &art.id), - cr, - &art.name, - t.artist(), - art.cover_uri.as_deref(), - &format!("art_{}", art.id), - true, - false, - ); - if let Some(pos) = m.right_clicked_pos { - shell.open_entity_menu(EntityContextMenuState { - kind: "artist".into(), - id: art.id.clone(), - title: art.name.clone(), - subtitle: t.artist().into(), - cover_uri: art.cover_uri.clone(), - owner_uid: None, - is_own_playlist: false, - tracks: Vec::new(), - anchor: pos, - share_url: format!("https://music.yandex.ru/artist/{}", art.id), - }); - } else if m.play_clicked { - actions.push(AppAction::PlayArtist { - id: art.id.clone(), - name: art.name.clone(), - }); - } else if m.clicked { - actions.push(AppAction::Navigate(Route::Artist { - id: art.id.clone(), - name: art.name.clone(), - })); - } - } - cx += card_w + gap; - } - ctx.end_scroll_h( - h_id, - pal, - artists.len().min(24) as f32 * (card_w + gap), - false, - ); - y += card_h + 26.0; - } - } - - // --------------------------------------------------------------------- - // SECTION 3: Playlists > (horizontal carousel starting with `+ Create`) - // --------------------------------------------------------------------- - { - let h_id = WidgetId::new("col_ov_playlists_h"); - if draw_section_heading( - ctx, - pal, - WidgetId::new("col_sec_playlists"), - t.playlists(), - x, - y, - avail_w, - Some(h_id), - true, - ) { - app.collection_tab = CollectionTab::Playlists; - } - y += 38.0; - - let playlists = app.user_playlists.clone(); - let my_uid = app.account.as_ref().map(|a| a.uid.to_string()); - let card_w = 168.0; - let card_h = card_w + 54.0; - let gap = 16.0; - let row_vp = Rect::from_xywh(x, y, avail_w, card_h); - let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); - let mut cx = x - sx; - - // Slot 0: compact `+ Создать плейлист` card - { - let cr = Rect::from_xywh(cx, y, card_w, card_h); - if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { - let cov_r = Rect::from_xywh(cr.left(), cr.top(), card_w, card_w); - let resp = ctx.interact(WidgetId::new("col_ov_create_pl"), cr); - ctx.dl().push_rect_bordered( - cov_r, - 10.0, - if resp.hovered { - pal.surface_hover - } else { - pal.surface_secondary - }, - 1.0, - pal.border_control, - ); - ctx.draw_icon( - Icon::AddXxs, - Rect::from_center_size(cov_r.center(), Vec2::splat(34.0)), - if resp.hovered { - pal.text_bright - } else { - pal.text_secondary - }, - ); - ctx.draw_text_ellipsis( - t.create_playlist(), - TextStyle::medium(13.5, pal.text_primary), - Rect::from_xywh(cr.left(), cov_r.bottom() + 8.0, card_w, 20.0), - TextAlign::Left, - ); - if resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if resp.clicked { - actions.push(AppAction::OpenCreatePlaylistModal { - initial_track: None, - }); - } - } - cx += card_w + gap; - } - - for (idx, pl) in playlists.iter().take(60).enumerate() { - let cr = Rect::from_xywh(cx, y, card_w, card_h); - if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { - let sub = t.count_tracks(pl.track_count as usize); - let is_own = pl.kind != "3" - && (pl.owner_uid == "local" - || my_uid.as_deref() == Some(pl.owner_uid.as_str())); - let m = media_card( - ctx, - pal, - covers, - WidgetId::from_pair( - "col_ov_pl", - (idx, format!("{}_{}", pl.owner_uid, pl.kind)), - ), - cr, - &pl.title, - &sub, - pl.cover_uri.as_deref(), - &format!("upl_{}_{}", pl.owner_uid, pl.kind), - false, - pl.kind == "3" && pl.cover_uri.is_none(), - ); - if let Some(pos) = m.right_clicked_pos { - shell.open_entity_menu(EntityContextMenuState { - kind: "playlist".into(), - id: format!("{}:{}", pl.owner_uid, pl.kind), - title: pl.title.clone(), - subtitle: t.playlist().into(), - cover_uri: pl.cover_uri.clone(), - owner_uid: Some(pl.owner_uid.clone()), - is_own_playlist: is_own, - tracks: Vec::new(), - anchor: pos, - share_url: format!( - "https://music.yandex.ru/users/{}/playlists/{}", - pl.owner_uid, pl.kind - ), - }); - } else if m.play_clicked { - actions.push(AppAction::PlayPlaylist { - owner_uid: pl.owner_uid.clone(), - kind: pl.kind.clone(), - title: pl.title.clone(), - }); - } else if m.clicked { - actions.push(AppAction::Navigate(Route::Playlist { - owner_uid: pl.owner_uid.clone(), - kind: pl.kind.clone(), - title: pl.title.clone(), - })); - } - } - cx += card_w + gap; - } - ctx.end_scroll_h( - h_id, - pal, - (playlists.len().min(60) + 1) as f32 * (card_w + gap), - false, - ); - y += card_h + 26.0; - } - - // --------------------------------------------------------------------- - // SECTION 4: Albums > (horizontal carousel) - // --------------------------------------------------------------------- - { - let h_id = WidgetId::new("col_ov_albums_h"); - if draw_section_heading( - ctx, - pal, - WidgetId::new("col_sec_albums"), - t.albums(), - x, - y, - avail_w, - Some(h_id), - !app.liked_albums.is_empty(), - ) { - app.collection_tab = CollectionTab::Albums; - } - y += 38.0; - - if app.liked_albums.is_empty() { - ctx.draw_text_ellipsis( - if ru { - "Здесь появятся ваши любимые альбомы." - } else { - "Your favorite albums will appear here." - }, - TextStyle::regular(13.5, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 22.0), - TextAlign::Left, - ); - y += 34.0; - } else { - let albums = app.liked_albums.clone(); - let card_w = 168.0; - let card_h = card_w + 54.0; - let gap = 16.0; - let row_vp = Rect::from_xywh(x, y, avail_w, card_h); - let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); - let mut cx = x - sx; - - for (idx, alb) in albums.iter().take(60).enumerate() { - let cr = Rect::from_xywh(cx, y, card_w, card_h); - if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { - let alb_title = alb.full_title(); - let sub = alb - .artists - .first() - .map(|a| a.name.as_str()) - .unwrap_or(t.album()); - let m = media_card( - ctx, - pal, - covers, - WidgetId::from_pair("col_ov_alb", (idx, &alb.id)), - cr, - &alb_title, - sub, - alb.cover_uri.as_deref(), - &format!("alb_{}", alb.id), - false, - false, - ); - if let Some(pos) = m.right_clicked_pos { - shell.open_entity_menu(EntityContextMenuState { - kind: "album".into(), - id: alb.id.clone(), - title: alb_title.clone(), - subtitle: t.album().into(), - cover_uri: alb.cover_uri.clone(), - owner_uid: None, - is_own_playlist: false, - tracks: Vec::new(), - anchor: pos, - share_url: format!("https://music.yandex.ru/album/{}", alb.id), - }); - } else if m.play_clicked { - actions.push(AppAction::PlayAlbum { - id: alb.id.clone(), - title: alb_title, - }); - } else if m.clicked { - actions.push(AppAction::Navigate(Route::Album { - id: alb.id.clone(), - title: alb_title, - })); - } - } - cx += card_w + gap; - } - ctx.end_scroll_h( - h_id, - pal, - albums.len().min(60) as f32 * (card_w + gap), - false, - ); - y += card_h + 26.0; - } - } - - // --------------------------------------------------------------------- - // SECTION 5: Podcasts & Audiobooks > (when non-empty) - // --------------------------------------------------------------------- - if !app.bookshelf_items.is_empty() { - let h_id = WidgetId::new("col_ov_books_h"); - if draw_section_heading( - ctx, - pal, - WidgetId::new("col_sec_books"), - t.podcasts_and_books(), - x, - y, - avail_w, - Some(h_id), - true, - ) { - app.collection_tab = CollectionTab::PodcastsAndBooks; - } - y += 38.0; - - let items = app.bookshelf_items.clone(); - let card_w = 168.0; - let card_h = card_w + 54.0; - let gap = 16.0; - let row_vp = Rect::from_xywh(x, y, avail_w, card_h); - let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); - let mut cx = x - sx; - - for pod in items.iter().take(24) { - let cr = Rect::from_xywh(cx, y, card_w, card_h); - if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { - let sub = pod - .artists - .first() - .map(|a| a.name.as_str()) - .unwrap_or(if ru { "Подкаст" } else { "Podcast" }); - let m = media_card( - ctx, - pal, - covers, - WidgetId::from_pair("col_ov_pod", &pod.id), - cr, - &pod.title, - sub, - pod.cover_uri.as_deref(), - &format!("pod_{}", pod.id), - false, - false, - ); - if let Some(pos) = m.right_clicked_pos { - shell.open_entity_menu(EntityContextMenuState { - kind: "album".into(), - id: pod.id.clone(), - title: pod.title.clone(), - subtitle: sub.to_string(), - cover_uri: pod.cover_uri.clone(), - owner_uid: None, - is_own_playlist: false, - tracks: Vec::new(), - anchor: pos, - share_url: format!("https://music.yandex.ru/album/{}", pod.id), - }); - } else if m.play_clicked { - actions.push(AppAction::PlayAlbum { - id: pod.id.clone(), - title: pod.title.clone(), - }); - } else if m.clicked { - actions.push(AppAction::Navigate(Route::Album { - id: pod.id.clone(), - title: pod.title.clone(), - })); - } - } - cx += card_w + gap; - } - ctx.end_scroll_h( - h_id, - pal, - items.len().min(24) as f32 * (card_w + gap), - false, - ); - y += card_h + 26.0; - } - - // --------------------------------------------------------------------- - // SECTION 6: History > (2-col × 4-row compact track grid when non-empty) - // --------------------------------------------------------------------- - if !app.play_history.is_empty() { - if draw_section_heading( - ctx, - pal, - WidgetId::new("col_sec_history"), - t.history(), - x, - y, - avail_w, - None, - false, - ) { - app.collection_tab = CollectionTab::History; - } - y += 38.0; - - let hist = app.play_history.clone(); - y = render_compact_two_col_track_grid( - ctx, - pal, - covers, - app, - shell, - rect, - x, - y, - avail_w, - &hist, - "col_ov_hist", - t.history(), - "history", - current_track_id.as_deref(), - is_playing, - actions, - ); - y += 28.0; - } - - // --------------------------------------------------------------------- - // SECTION 7: Downloaded > (compact preview list when non-empty) - // --------------------------------------------------------------------- - if !app.config.downloaded_tracks.is_empty() { - if draw_section_heading( - ctx, - pal, - WidgetId::new("col_sec_downloaded"), - t.downloaded(), - x, - y, - avail_w, - None, - false, - ) { - app.collection_tab = CollectionTab::Downloaded; - } - y += 38.0; - - let dl = app.config.downloaded_tracks.clone(); - y = render_compact_two_col_track_grid( - ctx, - pal, - covers, - app, - shell, - rect, - x, - y, - avail_w, - &dl, - "col_ov_dl", - t.downloaded_tracks(), - "downloads", - current_track_id.as_deref(), - is_playing, - actions, - ); - y += 16.0; - } - - y += 20.0; - let total_h = y - (rect.top() - scroll_y); - ctx.end_scroll_v(scroll_id, pal, total_h, true); - return; - } - - // ------------------------------------------------------------------------- - // SUB-VIEWS (Back button `← Коллекция` + full grid/list) - // ------------------------------------------------------------------------- - let (back_resp, _) = secondary_pill_button( - ctx, - pal, - WidgetId::new("col_sub_back"), - Pos2::new(x, y), - Some(Icon::ArrowLeft), - t.collection(), - 34.0, - false, - ); - if back_resp.clicked { - app.collection_tab = CollectionTab::Tracks; - } - y += 48.0; - - let sub_title = match app.collection_tab { - CollectionTab::Tracks => t.collection(), - CollectionTab::Playlists => t.playlists(), - CollectionTab::Albums => t.albums(), - CollectionTab::Artists => { - if ru { - "Любимые исполнители" - } else { - "Favorite Artists" - } - } - CollectionTab::PodcastsAndBooks => t.podcasts_and_books(), - CollectionTab::Downloaded => t.downloaded(), - CollectionTab::History => t.history(), - }; + // Page Heading ctx.draw_text_ellipsis( - sub_title, - TextStyle::headline(32.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 40.0), + t.collection(), + TextStyle::headline(34.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 42.0), TextAlign::Left, ); - y += 52.0; + y += 58.0; + // Signature "Мне нравится" / "My Favorites" Hero Banner Card (theme-aware!) + let hero_r = Rect::from_xywh(x, y, avail_w, 120.0); + let hero_resp = ctx.interact(WidgetId::new("col_fav_hero"), hero_r); + let hero_bg = if pal.is_dark { + if hero_resp.hovered { + Color::rgb(0x2A, 0x24, 0x17) + } else { + Color::rgb(0x22, 0x1D, 0x12) + } + } else if hero_resp.hovered { + Color::rgb(0xFF, 0xF2, 0xBC) + } else { + Color::rgb(0xFF, 0xF8, 0xD6) + }; + ctx.dl() + .push_rect_bordered(hero_r, 16.0, hero_bg, 1.0, pal.border_subtle); + + let cov_r = Rect::from_xywh(hero_r.left() + 18.0, hero_r.center_y() - 42.0, 84.0, 84.0); + draw_cover_art(ctx, pal, covers, cov_r, None, "likes", 12.0, false, true); + + let fav_title = t.liked_playlist(); + ctx.draw_text_ellipsis( + fav_title, + TextStyle::headline(26.0, pal.text_bright), + Rect::from_xywh(cov_r.right() + 20.0, hero_r.top() + 28.0, avail_w - 280.0, 32.0), + TextAlign::Left, + ); + ctx.draw_text_ellipsis( + &t.count_tracks(app.liked_tracks.len()), + TextStyle::regular(14.0, pal.text_secondary), + Rect::from_xywh(cov_r.right() + 20.0, hero_r.top() + 66.0, avail_w - 280.0, 22.0), + TextAlign::Left, + ); + + let likes_playing = app.is_context_playing("likes"); + let play_btn_label = if likes_playing { t.pause() } else { t.listen() }; + let play_text_w = ctx + .measure_text(play_btn_label, TextStyle::medium(14.0, pal.on_yellow), None) + .x; + let play_btn_w = (play_text_w + 28.0 + 36.0).max(100.0).ceil(); + let play_btn_r = Rect::from_xywh( + hero_r.right() - play_btn_w - 24.0, + hero_r.center_y() - 21.0, + play_btn_w, + 42.0, + ); + let play_resp = crate::engine::widgets::yellow_pill_button_in( + ctx, + pal, + WidgetId::new("col_fav_play"), + play_btn_r, + Some(if likes_playing { + Icon::PauseXxs + } else { + Icon::PlayXxs + }), + play_btn_label, + app.liked_tracks.is_empty(), + ); + if play_resp.clicked && !app.liked_tracks.is_empty() { + actions.push(AppAction::ToggleContextPlay { + tracks: app.liked_tracks.clone(), + context_name: fav_title.into(), + context_key: "likes".into(), + is_vibe: false, + }); + } else if hero_resp.clicked { + actions.push(AppAction::Navigate(Route::LikedTracks)); + } + if hero_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + y += 120.0 + 20.0; + + // All 7 Original Collection Tabs (horizontal scrollable pill bar!) + let tabs_vp = Rect::from_xywh(x, y, avail_w, 42.0); + let tabs_h_id = WidgetId::new("col_tabs_hscroll"); + let tabs_sx = ctx.begin_scroll_h(tabs_h_id, tabs_vp, 0.0); + let mut tx = x - tabs_sx; + let all_tabs = [ + (CollectionTab::Tracks, t.liked_tracks_tab()), + (CollectionTab::Playlists, t.playlists()), + (CollectionTab::Albums, t.albums()), + (CollectionTab::Artists, t.artists()), + (CollectionTab::PodcastsAndBooks, t.podcasts_and_books()), + (CollectionTab::Downloaded, t.downloaded()), + (CollectionTab::History, t.history()), + ]; + for (tab_kind, label) in all_tabs { + let (resp, r) = secondary_pill_button( + ctx, + pal, + WidgetId::from_pair("col_tab", tab_kind as u8), + Pos2::new(tx, y), + None, + label, + 38.0, + app.collection_tab == tab_kind, + ); + if resp.clicked { + app.collection_tab = tab_kind; + } + tx = r.right() + 8.0; + } + let tabs_total_w = (tx + tabs_sx) - x; + ctx.end_scroll_h(tabs_h_id, pal, tabs_total_w, false); + y += 56.0; + + // ------------------------------------------------------------------------- + // TAB BODY + // ------------------------------------------------------------------------- match app.collection_tab { - CollectionTab::Tracks => {} + CollectionTab::Tracks => { + if app.liked_tracks.is_empty() { + ctx.draw_text_wrapped( + if ru { + "Ставьте лайки трекам или войдите в аккаунт Яндекс Музыки — они появятся здесь." + } else { + "Like tracks or sign in to Yandex Music — they will appear here." + }, + TextStyle::regular(14.0, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 44.0), + Some(2), + TextAlign::Left, + ); + y += 48.0; + } else { + let tracks = app.liked_tracks.clone(); + y = render_virtual_track_list( + ctx, + pal, + covers, + app, + shell, + rect, + x, + y, + avail_w, + &tracks, + "col_liked", + fav_title, + "likes", + current_track_id.as_deref(), + is_playing, + actions, + ); + } + } CollectionTab::Playlists => { let gap = 16.0; @@ -739,6 +209,7 @@ pub fn render_collection( let card_w = ((avail_w - gap * (cols as f32 - 1.0)) / cols as f32).max(132.0); let card_h = card_w + 62.0; + // Total slots = 1 ("+ Create playlist" card) + user_playlists.len() let playlists = app.user_playlists.clone(); let my_uid = app.account.as_ref().map(|a| a.uid.to_string()); @@ -797,7 +268,7 @@ pub fn render_collection( continue; } let sub = t.count_tracks(pl.track_count as usize); - let wid = WidgetId::from_pair("col_pl", (i, format!("{}_{}", pl.owner_uid, pl.kind))); + let wid = WidgetId::from_pair("col_pl", format!("{}_{}", pl.owner_uid, pl.kind)); let m = media_card( ctx, pal, @@ -809,7 +280,7 @@ pub fn render_collection( pl.cover_uri.as_deref(), &format!("upl_{}_{}", pl.owner_uid, pl.kind), false, - pl.kind == "3" && pl.cover_uri.is_none(), + false, ); // Own playlists (not Liked kind=3) get quick Rename & Delete action icons on hover! @@ -904,7 +375,11 @@ pub fn render_collection( } CollectionTab::Albums => { - let albums = app.liked_albums.clone(); + let albums = if !app.liked_albums.is_empty() { + app.liked_albums.clone() + } else { + Vec::new() + }; if albums.is_empty() { ctx.draw_text_ellipsis( if ru { @@ -932,7 +407,6 @@ pub fn render_collection( card_h, ); if cr.bottom() >= rect.top() - 40.0 && cr.top() <= rect.bottom() + 40.0 { - let alb_title = alb.full_title(); let sub = alb .artists .first() @@ -942,9 +416,9 @@ pub fn render_collection( ctx, pal, covers, - WidgetId::from_pair("col_alb", (idx, &alb.id)), + WidgetId::from_pair("col_alb", &alb.id), cr, - &alb_title, + &alb.title, sub, alb.cover_uri.as_deref(), &format!("alb_{}", alb.id), @@ -955,7 +429,7 @@ pub fn render_collection( shell.open_entity_menu(EntityContextMenuState { kind: "album".into(), id: alb.id.clone(), - title: alb_title.clone(), + title: alb.title.clone(), subtitle: t.album().into(), cover_uri: alb.cover_uri.clone(), owner_uid: None, @@ -967,12 +441,12 @@ pub fn render_collection( } else if m.play_clicked { actions.push(AppAction::PlayAlbum { id: alb.id.clone(), - title: alb_title, + title: alb.title.clone(), }); } else if m.clicked { actions.push(AppAction::Navigate(Route::Album { id: alb.id.clone(), - title: alb_title, + title: alb.title.clone(), })); } } @@ -1153,6 +627,7 @@ pub fn render_collection( ); y += 48.0; } else { + // Header bar with Play Offline + Clear all downloaded let dl_playing = app.is_context_playing("downloads"); let (play_r, pr) = yellow_pill_button( ctx, @@ -1255,233 +730,6 @@ pub fn render_collection( ctx.end_scroll_v(scroll_id, pal, total_h, true); } -/// Clickable `Section Title >` heading with optional `<` `>` carousel scroll arrows on the right. -#[allow(clippy::too_many_arguments)] -fn draw_section_heading( - ctx: &mut UiContext, - pal: &YmPalette, - id: WidgetId, - title: &str, - x: f32, - y: f32, - avail_w: f32, - h_scroll_id: Option, - show_arrows: bool, -) -> bool { - let style_idle = TextStyle::headline(22.0, pal.text_primary); - let tw = ctx.measure_text(title, style_idle, None).x; - let head_w = (tw + 30.0).min((avail_w - 84.0).max(140.0)); - let head_r = Rect::from_xywh(x, y, head_w, 28.0); - let resp = ctx.interact(id, head_r); - - ctx.draw_text_ellipsis( - title, - TextStyle::headline( - 22.0, - if resp.hovered { - pal.text_bright - } else { - pal.text_primary - }, - ), - Rect::from_xywh(x, y, (head_w - 24.0).max(60.0), 28.0), - TextAlign::Left, - ); - ctx.draw_icon( - Icon::ArrowRight, - Rect::from_center_size( - Pos2::new(head_r.right() - 10.0, head_r.center_y()), - Vec2::splat(20.0), - ), - if resp.hovered { - pal.text_bright - } else { - pal.text_secondary - }, - ); - if resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - - if let (Some(h_id), true) = (h_scroll_id, show_arrows) { - let right_x = x + avail_w; - let cy = y + 14.0; - let next_r = Rect::from_center_size(Pos2::new(right_x - 15.0, cy), Vec2::splat(30.0)); - let prev_r = Rect::from_center_size(Pos2::new(right_x - 51.0, cy), Vec2::splat(30.0)); - - let (off_x, max_x) = { - let st = ctx.scrolls.get_or_create(h_id); - (st.offset.x, st.max_offset().x) - }; - let can_prev = off_x > 2.0; - let can_next = max_x > 2.0 && off_x < max_x - 2.0; - - let prev_resp = ctx.interact(h_id.with("prev"), prev_r); - let next_resp = ctx.interact(h_id.with("next"), next_r); - - ctx.dl().push_rect_bordered( - prev_r, - 15.0, - if prev_resp.hovered && can_prev { - pal.surface_hover - } else { - pal.surface_secondary - }, - 1.0, - pal.border_subtle, - ); - ctx.draw_icon( - Icon::ArrowLeft, - Rect::from_center_size(prev_r.center(), Vec2::splat(16.0)), - if can_prev { - pal.text_bright - } else { - pal.text_secondary.scale_alpha(0.35) - }, - ); - ctx.dl().push_rect_bordered( - next_r, - 15.0, - if next_resp.hovered && can_next { - pal.surface_hover - } else { - pal.surface_secondary - }, - 1.0, - pal.border_subtle, - ); - ctx.draw_icon( - Icon::ArrowRight, - Rect::from_center_size(next_r.center(), Vec2::splat(16.0)), - if can_next { - pal.text_bright - } else { - pal.text_secondary.scale_alpha(0.35) - }, - ); - if (prev_resp.hovered && can_prev) || (next_resp.hovered && can_next) { - ctx.set_cursor(CursorKind::Pointer); - } - if prev_resp.clicked && can_prev { - ctx.scrolls.get_or_create(h_id).scroll_by_x(-552.0); - ctx.request_repaint(); - } - if next_resp.clicked && can_next { - ctx.scrolls.get_or_create(h_id).scroll_by_x(552.0); - ctx.request_repaint(); - } - } - - resp.clicked -} - -/// Official 5.129.0 2-column × 4-row compact track grid (tracks 0..4 left, 4..8 right, 24px gap, 56px row height). -/// Gracefully collapses to 1 column of up to 6 tracks when `avail_w < 660.0`. -#[allow(clippy::too_many_arguments)] -fn render_compact_two_col_track_grid( - ctx: &mut UiContext, - pal: &YmPalette, - covers: &mut CoverCache, - app: &AppState, - shell: &mut ShellUiState, - viewport: Rect, - x: f32, - top_y: f32, - avail_w: f32, - tracks: &[Track], - salt: &str, - context_name: &str, - context_key: &str, - current_track_id: Option<&str>, - is_playing: bool, - actions: &mut Vec, -) -> f32 { - let t = app.i18n(); - let row_h = 56.0; - let two_cols = avail_w >= 660.0; - let col_gap = 24.0; - let max_items = if two_cols { 8 } else { 6 }; - let count = tracks.len().min(max_items); - let rows_per_col = if two_cols { 4 } else { count }; - let col_w = if two_cols { - (avail_w - col_gap) * 0.5 - } else { - avail_w - }; - - for idx in 0..count { - let col = if two_cols { idx / 4 } else { 0 }; - let row = if two_cols { idx % 4 } else { idx }; - let row_r = Rect::from_xywh( - x + col as f32 * (col_w + col_gap), - top_y + row as f32 * row_h, - col_w, - row_h, - ); - if row_r.bottom() < viewport.top() - 40.0 || row_r.top() > viewport.bottom() + 40.0 { - continue; - } - let tr = &tracks[idx]; - let is_curr = current_track_id == Some(tr.id.as_str()); - match track_row( - ctx, - pal, - covers, - WidgetId::from_pair(salt, idx), - row_r, - tr, - TrackRowOptions { - index: None, - show_chart_rank: false, - show_cover: true, - is_current: is_curr, - is_playing: is_curr && is_playing, - is_liked: app.liked_ids.contains(&tr.id), - is_disliked: app.disliked_ids.contains(&tr.id), - is_downloaded: app.is_track_downloaded(&tr.id), - is_downloading: app.is_track_downloading(&tr.id), - download_progress: app.track_download_progress(&tr.id), - menu_open: shell.is_track_menu_open(&tr.id), - }, - ) { - TrackRowAction::Play => { - actions.push(AppAction::PlayTracks { - tracks: tracks.to_vec(), - start_index: idx, - context_name: context_name.to_string(), - context_key: context_key.to_string(), - is_vibe: false, - }); - } - TrackRowAction::ToggleLike => actions.push(AppAction::ToggleLike(tr.clone())), - TrackRowAction::ToggleDislike => actions.push(AppAction::ToggleDislike(tr.clone())), - TrackRowAction::OpenArtist(id, name) => { - actions.push(AppAction::Navigate(Route::Artist { id, name })); - } - TrackRowAction::OpenAlbum(id) => { - actions.push(AppAction::Navigate(Route::Album { - id, - title: tr - .album_title - .clone() - .unwrap_or_else(|| t.album().into()), - })); - } - TrackRowAction::OpenContextMenu(pos) => { - shell.open_track_menu(tr.clone(), pos); - } - TrackRowAction::None => {} - } - } - - let used_rows = if two_cols { - count.min(rows_per_col) - } else { - count - }; - top_y + used_rows as f32 * row_h -} - #[allow(clippy::too_many_arguments)] fn render_virtual_track_list( ctx: &mut UiContext, @@ -1524,8 +772,6 @@ fn render_virtual_track_list( is_liked: app.liked_ids.contains(&tr.id), is_disliked: app.disliked_ids.contains(&tr.id), is_downloaded: app.is_track_downloaded(&tr.id), - is_downloading: app.is_track_downloading(&tr.id), - download_progress: app.track_download_progress(&tr.id), menu_open: shell.is_track_menu_open(&tr.id), }, ) { diff --git a/src/views/detail.rs b/src/views/detail.rs index 0fc8742..6deb089 100644 --- a/src/views/detail.rs +++ b/src/views/detail.rs @@ -5,9 +5,9 @@ use crate::engine::input::WidgetId; use crate::engine::scroll::visible_row_range; use crate::engine::text::{TextAlign, TextStyle}; use crate::engine::theme::{YmPalette, TRACK_ROW_HEIGHT}; -use crate::engine::types::{Color, CornerRadii, CursorKind, Pos2, Rect, Vec2}; +use crate::engine::types::{CornerRadii, CursorKind, Pos2, Rect, Vec2}; use crate::engine::widgets::{ - draw_cover_art, media_card, separated_artists, text_input_widget, + draw_cover_art, media_card, secondary_pill_button, separated_artists, text_input_widget, track_row, yellow_pill_button, TextInputOptions, TrackRowAction, TrackRowOptions, }; use crate::engine::UiContext; @@ -144,7 +144,6 @@ pub fn render_detail( }; let p_id = format!("{}:{}", owner_uid, kind); let p_seed = format!("pl_{}_{}", owner_uid, kind); - let is_likes_art = kind == "3" && pl_cov.is_none(); ( EntityKind::Playlist { owner_uid: owner_uid.clone(), @@ -157,7 +156,7 @@ pub fn render_detail( pl_cov, p_seed, false, - is_likes_art, + false, "playlist", p_id, Some(owner_uid), @@ -632,18 +631,12 @@ pub fn render_detail( .any(|tr| app.is_track_downloading(&tr.id)); if any_downloading { - let pct = app - .tracks_download_progress_pct(&raw_tracks) - .or_else(|| app.download_progress_pct()) - .unwrap_or(0); + let pct = app.download_progress_pct().unwrap_or(0); let label = format!("{}%", pct); - let pct_w = ctx - .measure_text(&label, TextStyle::medium(13.5, pal.text_primary), None) - .x; - let btn_w = (pct_w + 48.0).max(80.0).ceil(); + let btn_w = 78.0; let dl_r = Rect::from_xywh(bx, btn_y, btn_w, 40.0); let resp = ctx.interact(WidgetId::new("det_dl_btn"), dl_r); - ctx.dl().push_rect( + ctx.dl().push_rect_bordered( dl_r, 20.0, if resp.hovered { @@ -651,20 +644,18 @@ pub fn render_detail( } else { pal.surface_secondary }, + 1.5, + pal.yellow, ); - crate::engine::widgets::draw_downloading_progress( - ctx, - pal, - Pos2::new(dl_r.left() + 20.0, dl_r.center_y()), - 24.0, - pct as f32 / 100.0, - true, - resp.hovered, + ctx.draw_icon( + Icon::Download, + Rect::from_center_size(Pos2::new(dl_r.left() + 20.0, dl_r.center_y()), Vec2::splat(18.0)), + pal.yellow, ); ctx.draw_text_ellipsis( &label, - TextStyle::medium(13.5, pal.text_primary), - Rect::from_xywh(dl_r.left() + 38.0, dl_r.top(), (btn_w - 44.0).max(24.0), dl_r.height()), + TextStyle::bold(13.0, pal.text_primary), + Rect::from_xywh(dl_r.left() + 34.0, dl_r.top(), 40.0, dl_r.height()), TextAlign::Left, ); if resp.hovered { @@ -769,29 +760,16 @@ pub fn render_detail( None => chip.id == "all", Some(sel) => sel == &chip.id, }; - let chip_id = WidgetId::from_pair("fav_chip", &chip.id); - let text_sz = ctx.measure_text(&chip.name, TextStyle::bold(14.0, pal.text_primary), None); - let w = (text_sz.x + 36.0).clamp(48.0, 200.0); - let r = Rect::from_xywh(cx, y, w, 40.0); - let resp = ctx.interact(chip_id, r); - // Official `PlaylistFilter_root`: idle `#333` dark / `#E6E6E6` light; on hover slightly darkens (`#282828` / `#D6D6D6`)! - let hover_bg = if pal.is_dark { - Color::rgb(0x28, 0x28, 0x28) - } else { - Color::rgb(0xD6, 0xD6, 0xD6) - }; - let bg = if resp.hovered { hover_bg } else { pal.chip_bg }; - let border_col = if is_selected { pal.outline_selected } else { bg }; - ctx.dl().push_rect_bordered(r, 20.0, bg, 2.0, border_col); - ctx.draw_text_ellipsis( + let (resp, r) = secondary_pill_button( + ctx, + pal, + WidgetId::from_pair("fav_chip", &chip.id), + Pos2::new(cx, y), + None, &chip.name, - TextStyle::bold(14.0, pal.text_primary), - Rect::from_xywh(r.left() + 16.0, r.top(), (r.width() - 32.0).max(12.0), r.height()), - TextAlign::Center, + 40.0, + is_selected, ); - if resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } if resp.clicked { let next_id = if chip.id == "all" { None @@ -845,8 +823,6 @@ pub fn render_detail( is_liked: app.liked_ids.contains(&tr.id), is_disliked: app.disliked_ids.contains(&tr.id), is_downloaded: app.is_track_downloaded(&tr.id), - is_downloading: app.is_track_downloading(&tr.id), - download_progress: app.track_download_progress(&tr.id), menu_open: shell.is_track_menu_open(&tr.id), }, ) { @@ -926,10 +902,9 @@ pub fn render_detail( let h_id = WidgetId::new("artist_albums_hscroll"); let sx = ctx.begin_scroll_h(h_id, vp, 0.0); let mut cx = x - sx; - for (idx, alb) in art_detail.albums.iter().take(48).enumerate() { + for alb in art_detail.albums.iter().take(16) { let cr = Rect::from_xywh(cx, y, card_w, card_h); if cr.right() >= vp.left() - 80.0 && cr.left() <= vp.right() + 80.0 { - let alb_title = alb.full_title(); let yr = alb .year .map(|yr| yr.to_string()) @@ -938,9 +913,9 @@ pub fn render_detail( ctx, pal, covers, - WidgetId::from_pair("art_alb", (idx, &alb.id)), + WidgetId::from_pair("art_alb", &alb.id), cr, - &alb_title, + &alb.title, &yr, alb.cover_uri.as_deref(), &format!("artalb_{}", alb.id), @@ -950,12 +925,12 @@ pub fn render_detail( if m.play_clicked { actions.push(AppAction::PlayAlbum { id: alb.id.clone(), - title: alb_title, + title: alb.title.clone(), }); } else if m.clicked { actions.push(AppAction::Navigate(Route::Album { id: alb.id.clone(), - title: alb_title, + title: alb.title.clone(), })); } } @@ -964,7 +939,7 @@ pub fn render_detail( ctx.end_scroll_h( h_id, pal, - art_detail.albums.len().min(48) as f32 * (card_w + 16.0), + art_detail.albums.len().min(16) as f32 * (card_w + 16.0), false, ); } diff --git a/src/views/for_you.rs b/src/views/for_you.rs index 68b21be..3e12343 100644 --- a/src/views/for_you.rs +++ b/src/views/for_you.rs @@ -1,6 +1,3 @@ -use std::cell::Cell; - -use crate::api::models::{NewReleaseItem, VibePickItem, VibePickTab}; use crate::app::state::{AppAction, AppState, CollectionTab, ForYouTab, Route}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; @@ -12,11 +9,7 @@ use crate::engine::widgets::{ }; use crate::engine::UiContext; use crate::icons::Icon; -use crate::views::overlays::{EntityContextMenuState, ShellUiState}; - -thread_local! { - static FOR_YOU_PICKS_TAB: Cell = const { Cell::new(0) }; -} +use crate::views::overlays::ShellUiState; /// Exact Yandex Music Desktop 5.129.0 "For you and Trends" page (`vibe_wheel_foryou_spec.md` §4): /// - Persistent heading ("Для вас и Тренды" / "For you and Trends") + IN-PLACE switcher tabs ("Для вас" / "Тренды") @@ -465,7 +458,7 @@ pub fn render_for_you( let playlists = app.landing.personal_playlists.clone(); let mut cx = x - scroll_x; - for (idx, pl) in playlists.iter().enumerate() { + for pl in &playlists { let cr = Rect::from_xywh(cx, y, card_w, card_h); if cr.right() >= row_vp.left() - 20.0 && cr.left() <= row_vp.right() + 20.0 { let sub = pl.description.as_deref().unwrap_or(t.playlist()); @@ -473,10 +466,7 @@ pub fn render_for_you( ctx, pal, covers, - WidgetId::from_pair( - "fy_pl", - (idx, format!("{}_{}", pl.owner_uid, pl.kind)), - ), + WidgetId::from_pair("fy_pl", format!("{}_{}", pl.owner_uid, pl.kind)), cr, &pl.title, sub, @@ -506,15 +496,10 @@ pub fn render_for_you( y += card_h + 26.0; } - // 5. "New Releases >" (1-to-1 official `NewRelease` + `NewReleaseCard` circular portrait + colored release card!) - if !app.landing.rich_new_releases.is_empty() || !app.landing.new_releases.is_empty() { - y = render_new_releases_carousel( - ctx, pal, covers, app, shell, rect, x, y, avail_w, "fy_rel", actions, - ); + // 5. "New Releases" + if !app.landing.new_releases.is_empty() { + y = render_new_releases_carousel(ctx, pal, covers, app, x, y, avail_w, "fy_rel", actions); } - - // 6. Official "More Picks" / "Ещё подборки" (`Waves` / `SETS_BY_WAVES`) - y = render_more_picks_section(ctx, pal, app, rect, x, y, avail_w, actions); } ForYouTab::Trends => { @@ -579,8 +564,6 @@ pub fn render_for_you( is_liked: app.liked_ids.contains(&tr.id), is_disliked: app.disliked_ids.contains(&tr.id), is_downloaded: app.is_track_downloaded(&tr.id), - is_downloading: app.is_track_downloading(&tr.id), - download_progress: app.track_download_progress(&tr.id), menu_open: shell.is_track_menu_open(&tr.id), }, ) { @@ -623,14 +606,12 @@ pub fn render_for_you( } // 2. New Releases Carousel - if !app.landing.rich_new_releases.is_empty() || !app.landing.new_releases.is_empty() { + if !app.landing.new_releases.is_empty() { y = render_new_releases_carousel( ctx, pal, covers, app, - shell, - rect, x, y, avail_w, @@ -657,17 +638,14 @@ pub fn render_for_you( let playlists = app.landing.popular_playlists.clone(); let mut cx = x - scroll_x; - for (idx, pl) in playlists.iter().enumerate() { + for pl in &playlists { let cr = Rect::from_xywh(cx, y, card_w, card_h); if cr.right() >= row_vp.left() - 20.0 && cr.left() <= row_vp.right() + 20.0 { let m = media_card( ctx, pal, covers, - WidgetId::from_pair( - "tr_pl", - (idx, format!("{}_{}", pl.owner_uid, pl.kind)), - ), + WidgetId::from_pair("tr_pl", format!("{}_{}", pl.owner_uid, pl.kind)), cr, &pl.title, &pl.owner_name, @@ -700,162 +678,9 @@ pub fn render_for_you( } y += 20.0; + let _ = CornerRadii::ZERO; let total_h = y - (rect.top() - scroll_y); ctx.end_scroll_v(scroll_id, pal, total_h, true); - - // Sticky Frosted Top Switcher Bar when scrolled (`scroll_y > 72.0` -> zero impact on `scroll_y == 0` parity!) - if scroll_y > 72.0 { - let fade_in = ((scroll_y - 72.0) / 36.0).clamp(0.0, 1.0); - let bar_r = Rect::from_xywh( - rect.left() - 25.0, - rect.top() - 12.0, - rect.width() + 50.0, - 66.0, - ); - // Subtle atmospheric gradient glow behind the frosted sticky bar - let glow_c = if pal.is_dark { - Color::rgb(0x4E, 0x35, 0x62) - } else { - Color::rgb(0xD8, 0xD2, 0xE8) - }; - ctx.dl().push_gradient_rect( - bar_r, - CornerRadii::top(12.0), - glow_c.with_alpha((54.0 * fade_in).round() as u8), - glow_c.with_alpha(0), - Vec2::new(0.0, 1.0), - ); - let glass_tint = if pal.is_dark { - css_rgba(18, 18, 18, (186.0 * fade_in).round() as u8) - } else { - css_rgba(255, 255, 255, (206.0 * fade_in).round() as u8) - }; - ctx.dl().push_backdrop_blur( - bar_r, - CornerRadii::top(12.0), - 2.0, - glass_tint, - 0.0, - Color::TRANSPARENT, - ); - ctx.dl().push_rect( - Rect::from_xywh(bar_r.left(), bar_r.bottom() - 1.0, bar_r.width(), 1.0), - 0.0, - pal.border_subtle.scale_alpha(fade_in), - ); - - let mut sx = x; - let sy = bar_r.center_y() - 19.0; - for (tab_kind, label) in [ - (ForYouTab::ForYou, t.for_you()), - (ForYouTab::Trends, t.trends()), - ] { - let active = app.for_you_tab == tab_kind; - let tw = ctx - .measure_text(label, TextStyle::bold(14.5, pal.text_primary), None) - .x - + 32.0; - let pr = Rect::from_xywh(sx, sy, tw.max(88.0), 38.0); - let resp = ctx.interact(WidgetId::from_pair("fy_sticky_tab", tab_kind as u8), pr); - if active || resp.hovered { - ctx.dl().push_rect( - pr, - 19.0, - if active { - pal.surface_hover - } else { - pal.surface_secondary - }, - ); - } - ctx.draw_text_ellipsis( - label, - TextStyle::bold( - 14.5, - if active || resp.hovered { - pal.text_bright - } else { - pal.text_secondary - }, - ), - pr, - TextAlign::Center, - ); - if resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if resp.clicked && !active { - actions.push(AppAction::SetForYouTab(tab_kind)); - } - sx = pr.right() + 8.0; - } - } -} - -fn rich_dark_tint(raw: Color) -> Color { - // Rich dark-saturated card tint (~24% lightness) keeping high contrast for white album text - let r = (raw.r as f32 / 255.0).clamp(0.0, 1.0); - let g = (raw.g as f32 / 255.0).clamp(0.0, 1.0); - let b = (raw.b as f32 / 255.0).clamp(0.0, 1.0); - let max_c = r.max(g).max(b); - let min_c = r.min(g).min(b); - let avg = (max_c + min_c) * 0.5; - // Slightly boost chroma then scale luminance into ~0.22..0.28 range - let sat_r = (avg + (r - avg) * 1.25).clamp(0.0, 1.0); - let sat_g = (avg + (g - avg) * 1.25).clamp(0.0, 1.0); - let sat_b = (avg + (b - avg) * 1.25).clamp(0.0, 1.0); - let luma = (0.299 * sat_r + 0.587 * sat_g + 0.114 * sat_b).max(0.01); - let scale = (0.24 / luma).clamp(0.28, 0.95); - Color::rgb( - ((sat_r * scale).clamp(0.08, 0.48) * 255.0).round() as u8, - ((sat_g * scale).clamp(0.08, 0.48) * 255.0).round() as u8, - ((sat_b * scale).clamp(0.08, 0.48) * 255.0).round() as u8, - ) -} - -fn format_release_subtitle(item: &NewReleaseItem, ru: bool) -> String { - let is_single = item - .album - .content_type - .as_deref() - .map_or(false, |ct| ct.eq_ignore_ascii_case("single")) - || (item.album.track_count > 0 && item.album.track_count <= 3); - let kind = if is_single { - if ru { "сингл" } else { "single" } - } else if ru { - "альбом" - } else { - "album" - }; - - if let Some(ref rd) = item.release_date { - let date_part = rd.split('T').next().unwrap_or(rd); - let parts: Vec<&str> = date_part.split('-').collect(); - if parts.len() >= 3 { - if let (Ok(m), Ok(d)) = (parts[1].parse::(), parts[2].parse::()) { - if (1..=12).contains(&m) && d > 0 { - const MONTHS_RU: [&str; 12] = [ - "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", - "сентября", "октября", "ноября", "декабря", - ]; - const MONTHS_EN: [&str; 12] = [ - "January", "February", "March", "April", "May", "June", "July", "August", - "September", "October", "November", "December", - ]; - return if ru { - format!("{} · {} {}", kind, d, MONTHS_RU[m - 1]) - } else { - format!("{} · {} {}", kind, MONTHS_EN[m - 1], d) - }; - } - } - } - } - if let Some(yr) = item.album.year { - format!("{} · {}", kind, yr) - } else { - kind.to_string() - } } #[allow(clippy::too_many_arguments)] @@ -864,8 +689,6 @@ fn render_new_releases_carousel( pal: &YmPalette, covers: &mut CoverCache, app: &AppState, - shell: &mut ShellUiState, - viewport: Rect, x: f32, mut y: f32, avail_w: f32, @@ -873,590 +696,58 @@ fn render_new_releases_carousel( actions: &mut Vec, ) -> f32 { let t = app.i18n(); - let ru = t.is_ru(); - let items: Vec = if !app.landing.rich_new_releases.is_empty() { - app.landing.rich_new_releases.clone() - } else { - app.landing - .new_releases - .iter() - .cloned() - .map(|album| NewReleaseItem { - artist_cover_uri: album.artists.first().and_then(|a| a.cover_uri.clone()), - cover_color: None, - release_date: None, - album, - }) - .collect() - }; - if items.is_empty() { - return y; - } - - let h_id = WidgetId::new(salt); - let card_w = 286.0_f32; - let gap = 18.0_f32; - let portrait_d = 236.0_f32; - let overlap = 56.0_f32; - let bottom_h = 80.0_f32; - let card_h = portrait_d - overlap + bottom_h; // 260.0 - let total_w = items.len() as f32 * (card_w + gap); - - // Header row: "New Releases >" + circular `<` `>` carousel arrows on right - let head_txt = t.new_releases(); - let head_tw = ctx - .measure_text(head_txt, TextStyle::headline(24.0, pal.text_primary), None) - .x; ctx.draw_text_ellipsis( - head_txt, - TextStyle::headline(24.0, pal.text_primary), - Rect::from_xywh(x, y, head_tw + 4.0, 30.0), - TextAlign::Left, - ); - ctx.draw_icon( - Icon::ArrowRight, - Rect::from_center_size(Pos2::new(x + head_tw + 16.0, y + 15.0), Vec2::splat(22.0)), - pal.text_secondary, - ); - - let (can_left, can_right) = ctx - .scrolls - .get(h_id) - .map(|s| (s.can_scroll_left(), s.can_scroll_right())) - .unwrap_or((false, total_w > avail_w + 10.0)); - let l_btn_c = Pos2::new(x + avail_w - 54.0, y + 15.0); - let r_btn_c = Pos2::new(x + avail_w - 16.0, y + 15.0); - for (c, ic, enabled, is_right) in [ - (l_btn_c, Icon::ArrowLeftXxs, can_left, false), - (r_btn_c, Icon::ArrowRightXxs, can_right, true), - ] { - let br = Rect::from_center_size(c, Vec2::splat(32.0)); - let resp = ctx.interact(WidgetId::from_pair(salt, if is_right { "next" } else { "prev" }), br); - let bg = if enabled && resp.hovered { - pal.surface_hover - } else { - pal.surface_secondary - }; - ctx.dl().push_circle(c, 16.0, bg); - ctx.draw_icon( - ic, - Rect::from_center_size(c, Vec2::splat(18.0)), - if enabled { - if resp.hovered { pal.text_bright } else { pal.text_primary } - } else { - pal.text_disabled - }, - ); - if enabled && resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if enabled && resp.clicked { - let delta = if is_right { (card_w + gap) * 2.0 } else { -(card_w + gap) * 2.0 }; - ctx.scrolls.scroll_by_x(h_id, delta); - ctx.request_repaint(); - } - } - y += 42.0; - - let row_vp = Rect::from_xywh(x, y, avail_w, card_h); - if row_vp.bottom() >= viewport.top() - 120.0 && row_vp.top() <= viewport.bottom() + 120.0 { - let scroll_x = ctx.begin_scroll_h(h_id, row_vp, 0.0); - let mut cx = x - scroll_x; - for (idx, item) in items.iter().enumerate() { - let alb = &item.album; - let alb_title = alb.full_title(); - let outer_r = Rect::from_xywh(cx, y, card_w, card_h); - if outer_r.right() >= row_vp.left() - 80.0 && outer_r.left() <= row_vp.right() + 80.0 { - // 1. Huge 236x236 circular artist portrait overlapping the bottom card by 56px - let circle_r = Rect::from_xywh( - cx + (card_w - portrait_d) * 0.5, - y, - portrait_d, - portrait_d, - ); - let portrait_uri = item - .artist_cover_uri - .as_deref() - .or(alb.cover_uri.as_deref()); - let (portrait_dom, _) = draw_cover_art( - ctx, - pal, - covers, - circle_r, - portrait_uri, - &format!("nr_art_{}", alb.id), - portrait_d * 0.5, - true, - false, - ); - - // Resolve rich dark-saturated tint from `cover_color` or cover dominant color - let raw_tint = item - .cover_color - .as_deref() - .and_then(Color::from_hex_str) - .or_else(|| { - alb.cover_uri - .as_deref() - .and_then(|u| covers.get_or_fetch(u, 200)) - .map(|(_, dom, _)| dom) - }) - .unwrap_or(portrait_dom); - let card_tint = rich_dark_tint(raw_tint); - - // Smooth lower gradient fade over lower 42% of circular portrait - ctx.push_clip(circle_r, portrait_d * 0.5); - let scrim_h = portrait_d * 0.46; - ctx.dl().push_gradient_rect( - Rect::from_xywh(circle_r.left(), circle_r.bottom() - scrim_h, portrait_d, scrim_h), - 0.0, - card_tint.with_alpha(0), - card_tint.with_alpha(232), - Vec2::new(0.0, 1.0), - ); - ctx.pop_clip(); - - // Bold white centered Artist Name above the card overlap - let artist_name = alb - .artists - .first() - .map(|a| a.name.as_str()) - .unwrap_or(alb_title.as_str()); - let art_lbl_r = Rect::from_xywh( - circle_r.left() + 18.0, - y + portrait_d - overlap - 54.0, - portrait_d - 36.0, - 50.0, - ); - ctx.draw_text_wrapped( - artist_name, - TextStyle::headline(21.0, Color::WHITE).with_line_height(24.0), - art_lbl_r, - Some(2), - TextAlign::Center, - ); - - let port_click_r = Rect::from_xywh(circle_r.left(), circle_r.top(), portrait_d, portrait_d - overlap); - let port_resp = ctx.interact(WidgetId::from_pair(salt, (idx, format!("port_{}", alb.id))), port_click_r); - if port_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - - // 2. Bottom 80px colored rounded release card (`radius: 14px`) - let card_r = Rect::from_xywh(cx, y + portrait_d - overlap, card_w, bottom_h); - let card_resp = ctx.interact(WidgetId::from_pair(salt, (idx, format!("card_{}", alb.id))), card_r); - let card_bg = if card_resp.hovered { - card_tint.lerp(Color::WHITE, 0.08) - } else { - card_tint - }; - ctx.dl().push_shadow( - card_r, - 14.0, - 12.0, - 0.0, - Vec2::new(0.0, 4.0), - css_rgba(0, 0, 0, 72), - ); - ctx.dl().push_rect_bordered( - card_r, - 14.0, - card_bg, - 1.0, - css_rgba(255, 255, 255, 26), - ); - - // Left 62x62 rounded (8px) album cover - let cov_r = Rect::from_xywh(card_r.left() + 9.0, card_r.top() + 9.0, 62.0, 62.0); - draw_cover_art( - ctx, - pal, - covers, - cov_r, - alb.cover_uri.as_deref(), - &format!("nr_alb_{}", alb.id), - 8.0, - false, - false, - ); - - // Right 38x38 crisp white circular Play/Pause button - let play_c = Pos2::new(card_r.right() - 28.0, card_r.center_y()); - let play_r = Rect::from_center_size(play_c, Vec2::splat(38.0)); - let play_resp = ctx.interact(WidgetId::from_pair(salt, (idx, format!("play_{}", alb.id))), play_r); - let play_rad = if play_resp.hovered { 20.0 } else { 19.0 }; - ctx.dl().push_circle(play_c, play_rad, Color::WHITE); - let alb_playing = app.is_context_playing(&format!("album:{}", alb.id)); - ctx.draw_icon( - if alb_playing { - Icon::PauseFilledXs - } else { - Icon::PlayFilledXs - }, - Rect::from_center_size(play_c, Vec2::splat(18.0)), - Color::rgb(0x14, 0x14, 0x14), - ); - - // Middle bold white title + muted release subtitle - let tx_l = cov_r.right() + 12.0; - let tx_w = (play_r.left() - tx_l - 8.0).max(40.0); - ctx.draw_text_ellipsis( - &alb_title, - TextStyle::bold(14.5, Color::WHITE), - Rect::from_xywh(tx_l, card_r.top() + 18.0, tx_w, 20.0), - TextAlign::Left, - ); - let sub = format_release_subtitle(item, ru); - ctx.draw_text_ellipsis( - &sub, - TextStyle::medium(12.5, css_rgba(255, 255, 255, 172)), - Rect::from_xywh(tx_l, card_r.top() + 42.0, tx_w, 18.0), - TextAlign::Left, - ); - - if play_resp.hovered || card_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if card_resp.right_clicked { - let pos = ctx - .input - .pointer_pos - .unwrap_or(Pos2::new(card_r.center_x(), card_r.bottom())); - shell.open_entity_menu(EntityContextMenuState { - kind: "album".into(), - id: alb.id.clone(), - title: alb.title.clone(), - subtitle: sub, - cover_uri: alb.cover_uri.clone(), - owner_uid: None, - is_own_playlist: false, - tracks: Vec::new(), - anchor: pos, - share_url: format!("https://music.yandex.ru/album/{}", alb.id), - }); - } else if play_resp.clicked { - actions.push(AppAction::PlayAlbum { - id: alb.id.clone(), - title: alb.title.clone(), - }); - } else if card_resp.clicked { - actions.push(AppAction::Navigate(Route::Album { - id: alb.id.clone(), - title: alb.title.clone(), - })); - } else if port_resp.clicked { - if let Some(first) = alb.artists.first() { - actions.push(AppAction::Navigate(Route::Artist { - id: first.id.clone(), - name: first.name.clone(), - })); - } else { - actions.push(AppAction::Navigate(Route::Album { - id: alb.id.clone(), - title: alb.title.clone(), - })); - } - } - } - cx += card_w + gap; - } - ctx.end_scroll_h(h_id, pal, total_w, false); - } - - y + card_h + 34.0 -} - -fn fallback_vibe_pick_tabs(ru: bool) -> Vec { - let mk = |title: &str, header: &str, seed: &str, hex: &str| VibePickItem { - title: title.into(), - header: header.into(), - seeds: vec![seed.into()], - color_hex: Some(hex.into()), - background_image_url: None, - image_url: None, - }; - if ru { - vec![ - VibePickTab { - title: "топ".into(), - items: vec![ - mk("Английский", "Моя волна по языку", "language:english", "#3F68F9"), - mk("Электроника", "Моя волна по жанру", "genre:electronics", "#8341EF"), - mk("Бодрое", "Моя волна по настроению", "mood:energetic", "#FF5C4D"), - mk("Для работы", "Моя волна по занятию", "activity:work", "#0D9488"), - mk("Незнакомое", "Моя волна по характеру", "diversity:discover", "#D97706"), - ], - }, - VibePickTab { - title: "по языку".into(), - items: vec![ - mk("Английский", "Моя волна по языку", "language:english", "#3F68F9"), - mk("Русский", "Моя волна по языку", "language:russian", "#E11D48"), - mk("Без слов", "Моя волна по языку", "language:without-words", "#0F766E"), - ], - }, - VibePickTab { - title: "по жанру".into(), - items: vec![ - mk("Электроника", "Моя волна по жанру", "genre:electronics", "#7C3AED"), - mk("Хип-хоп", "Моя волна по жанру", "genre:hiphop", "#EA580C"), - mk("Рок", "Моя волна по жанру", "genre:rock", "#DC2626"), - mk("Поп", "Моя волна по жанру", "genre:pop", "#DB2777"), - ], - }, - VibePickTab { - title: "по настроению".into(), - items: vec![ - mk("Бодрое", "Моя волна по настроению", "mood:energetic", "#F97316"), - mk("Спокойное", "Моя волна по настроению", "mood:calm", "#2563EB"), - mk("Весёлое", "Моя волна по настроению", "mood:fun", "#EAB308"), - ], - }, - VibePickTab { - title: "по занятию".into(), - items: vec![ - mk("Для работы", "Моя волна по занятию", "activity:work", "#0D9488"), - mk("Тренировка", "Моя волна по занятию", "activity:workout", "#E11D48"), - mk("В дорогу", "Моя волна по занятию", "activity:road-trip", "#4F46E5"), - ], - }, - VibePickTab { - title: "по характеру".into(), - items: vec![ - mk("Незнакомое", "Моя волна по характеру", "diversity:discover", "#8B5CF6"), - mk("Любимое", "Моя волна по характеру", "diversity:favorite", "#EC4899"), - mk("Популярное", "Моя волна по характеру", "diversity:popular", "#059669"), - ], - }, - ] - } else { - vec![ - VibePickTab { - title: "top".into(), - items: vec![ - mk("English", "My Vibe by language", "language:english", "#3F68F9"), - mk("Electronic", "My Vibe by genre", "genre:electronics", "#8341EF"), - mk("Energetic", "My Vibe by mood", "mood:energetic", "#FF5C4D"), - mk("Focus & Work", "My Vibe by activity", "activity:work", "#0D9488"), - mk("Discover", "My Vibe by character", "diversity:discover", "#D97706"), - ], - }, - VibePickTab { - title: "by language".into(), - items: vec![ - mk("English", "My Vibe by language", "language:english", "#3F68F9"), - mk("Russian", "My Vibe by language", "language:russian", "#E11D48"), - mk("Instrumental", "My Vibe by language", "language:without-words", "#0F766E"), - ], - }, - VibePickTab { - title: "by genre".into(), - items: vec![ - mk("Electronic", "My Vibe by genre", "genre:electronics", "#7C3AED"), - mk("Hip-Hop", "My Vibe by genre", "genre:hiphop", "#EA580C"), - mk("Rock", "My Vibe by genre", "genre:rock", "#DC2626"), - mk("Pop", "My Vibe by genre", "genre:pop", "#DB2777"), - ], - }, - VibePickTab { - title: "by mood".into(), - items: vec![ - mk("Energetic", "My Vibe by mood", "mood:energetic", "#F97316"), - mk("Calm", "My Vibe by mood", "mood:calm", "#2563EB"), - mk("Upbeat", "My Vibe by mood", "mood:fun", "#EAB308"), - ], - }, - VibePickTab { - title: "by activity".into(), - items: vec![ - mk("Work", "My Vibe by activity", "activity:work", "#0D9488"), - mk("Workout", "My Vibe by activity", "activity:workout", "#E11D48"), - mk("Road trip", "My Vibe by activity", "activity:road-trip", "#4F46E5"), - ], - }, - VibePickTab { - title: "by character".into(), - items: vec![ - mk("Discover", "My Vibe by character", "diversity:discover", "#8B5CF6"), - mk("Favorites", "My Vibe by character", "diversity:favorite", "#EC4899"), - mk("Popular", "My Vibe by character", "diversity:popular", "#059669"), - ], - }, - ] - } -} - -#[allow(clippy::too_many_arguments)] -fn render_more_picks_section( - ctx: &mut UiContext, - pal: &YmPalette, - app: &AppState, - viewport: Rect, - x: f32, - mut y: f32, - avail_w: f32, - actions: &mut Vec, -) -> f32 { - let ru = app.i18n().is_ru(); - let tabs: Vec = if !app.landing.vibe_pick_tabs.is_empty() { - app.landing.vibe_pick_tabs.clone() - } else { - fallback_vibe_pick_tabs(ru) - }; - if tabs.is_empty() { - return y; - } - - ctx.draw_text_ellipsis( - if ru { "Ещё подборки" } else { "More Picks" }, + t.new_releases(), TextStyle::headline(24.0, pal.text_primary), Rect::from_xywh(x, y, avail_w, 30.0), TextAlign::Left, ); y += 40.0; - let active_idx = FOR_YOU_PICKS_TAB.with(|c| c.get()).min(tabs.len() - 1); - - // Horizontal category filter tabs (`32px` active pill, clean secondary text inactive) - let tabs_vp = Rect::from_xywh(x, y, avail_w, 34.0); - let tabs_h_id = WidgetId::new("fy_picks_tabs_hscroll"); - let tabs_sx = ctx.begin_scroll_h(tabs_h_id, tabs_vp, 0.0); - let mut tx = x - tabs_sx; - for (idx, tab) in tabs.iter().enumerate() { - let is_act = idx == active_idx; - let style = TextStyle::medium( - 14.0, - if is_act { pal.text_bright } else { pal.text_secondary }, - ); - let tw = ctx.measure_text(&tab.title, style, None).x + 24.0; - let tr = Rect::from_xywh(tx, y, tw.max(52.0), 32.0); - let resp = ctx.interact(WidgetId::from_pair("fy_pick_tab", idx), tr); - if is_act { - ctx.dl().push_rect(tr, 16.0, pal.surface_hover); - } else if resp.hovered { - ctx.dl().push_rect(tr, 16.0, pal.surface_secondary); - } - ctx.draw_text_ellipsis( - &tab.title, - TextStyle::medium( - 14.0, - if is_act || resp.hovered { - pal.text_bright - } else { - pal.text_secondary - }, - ), - tr, - TextAlign::Center, - ); - if resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if resp.clicked { - FOR_YOU_PICKS_TAB.with(|c| c.set(idx)); - } - tx = tr.right() + 8.0; - } - ctx.end_scroll_h(tabs_h_id, pal, (tx + tabs_sx) - x, false); - y += 46.0; - - // Vibrant gradient-tinted glossy Vibe-Station cards (`260x70`, `radius: 16px`) - const CURATED_PALETTE: &[Color] = &[ - Color::rgb(0x3F, 0x68, 0xF9), - Color::rgb(0x83, 0x41, 0xEF), - Color::rgb(0xE1, 0x3A, 0x52), - Color::rgb(0x0D, 0x94, 0x88), - Color::rgb(0xD9, 0x77, 0x06), - Color::rgb(0xDB, 0x27, 0x77), - ]; - - let card_w = 260.0_f32; - let card_h = 70.0_f32; - let gap = 14.0_f32; + let card_w = 164.0; + let card_h = card_w + 54.0; let row_vp = Rect::from_xywh(x, y, avail_w, card_h); - let items = &tabs[active_idx].items; - if row_vp.bottom() >= viewport.top() - 120.0 && row_vp.top() <= viewport.bottom() + 120.0 { - let h_id = WidgetId::from_pair("fy_picks_cards", active_idx); - let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); - let mut cx = x - sx; - for (idx, item) in items.iter().enumerate() { - let cr = Rect::from_xywh(cx, y, card_w, card_h); - if cr.right() >= row_vp.left() - 60.0 && cr.left() <= row_vp.right() + 60.0 { - let resp = ctx.interact(WidgetId::from_pair("fy_pick_card", (active_idx, idx)), cr); - let base_c = item - .color_hex - .as_deref() - .and_then(Color::from_hex_str) - .unwrap_or(CURATED_PALETTE[idx % CURATED_PALETTE.len()]); - let c_left = base_c.lerp(Color::BLACK, if resp.hovered { 0.14 } else { 0.24 }); - let c_right = base_c.lerp(Color::BLACK, if resp.hovered { 0.36 } else { 0.48 }); - ctx.dl() - .push_gradient_rect(cr, 16.0, c_left, c_right, Vec2::new(1.0, 0.4)); - // Subtle glossy top sheen - ctx.dl().push_gradient_rect( - Rect::from_xywh(cr.left(), cr.top(), cr.width(), cr.height() * 0.48), - CornerRadii::top(16.0), - css_rgba(255, 255, 255, if resp.hovered { 42 } else { 28 }), - css_rgba(255, 255, 255, 0), - Vec2::new(0.0, 1.0), - ); - ctx.dl().push_rect_bordered( - cr, - 16.0, - Color::TRANSPARENT, - 1.0, - css_rgba(255, 255, 255, 28), - ); + let h_id = WidgetId::new(salt); + let scroll_x = ctx.begin_scroll_h(h_id, row_vp, 0.0); - // Eyebrow ("Моя волна по языку" / "My Vibe by language") - if !item.header.is_empty() { - ctx.draw_text_ellipsis( - &item.header, - TextStyle::medium(12.0, css_rgba(255, 255, 255, 196)), - Rect::from_xywh(cr.left() + 14.0, cr.top() + 13.0, cr.width() - 28.0, 16.0), - TextAlign::Center, - ); - } - - // Centered bold white `▶` + station title (`17px` Headline) - let title_style = TextStyle::headline(17.0, Color::WHITE); - let tw = ctx - .measure_text(&item.title, title_style, None) - .x - .min(cr.width() - 52.0); - let inner_w = 16.0 + 6.0 + tw; - let tx_start = cr.center_x() - inner_w * 0.5; - let row_y = if item.header.is_empty() { - cr.center_y() - } else { - cr.top() + 45.0 - }; - ctx.draw_icon( - Icon::PlayFilledXs, - Rect::from_center_size(Pos2::new(tx_start + 8.0, row_y), Vec2::splat(14.0)), - Color::WHITE, - ); - ctx.draw_text_ellipsis( - &item.title, - title_style, - Rect::from_xywh(tx_start + 22.0, row_y - 11.0, tw + 4.0, 22.0), - TextAlign::Left, - ); - - if resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if resp.clicked && !item.seeds.is_empty() { - actions.push(AppAction::StartVibeBySeeds { - title: item.title.clone(), - seeds: item.seeds.clone(), - }); - } + let releases = app.landing.new_releases.clone(); + let mut cx = x - scroll_x; + for alb in &releases { + let cr = Rect::from_xywh(cx, y, card_w, card_h); + if cr.right() >= row_vp.left() - 20.0 && cr.left() <= row_vp.right() + 20.0 { + let art = alb + .artists + .first() + .map(|a| a.name.as_str()) + .unwrap_or(t.album()); + let m = media_card( + ctx, + pal, + covers, + WidgetId::from_pair(salt, &alb.id), + cr, + &alb.title, + art, + alb.cover_uri.as_deref(), + &format!("alb_{}", alb.id), + false, + false, + ); + if m.play_clicked { + actions.push(AppAction::PlayAlbum { + id: alb.id.clone(), + title: alb.title.clone(), + }); + } else if m.clicked { + actions.push(AppAction::Navigate(Route::Album { + id: alb.id.clone(), + title: alb.title.clone(), + })); } - cx += card_w + gap; } - ctx.end_scroll_h(h_id, pal, items.len() as f32 * (card_w + gap), false); + cx += card_w + 16.0; } - + let total_w = (releases.len() as f32) * (card_w + 16.0); + ctx.end_scroll_h(h_id, pal, total_w, false); y + card_h + 26.0 } diff --git a/src/views/mod.rs b/src/views/mod.rs index ddd5a66..d356813 100644 --- a/src/views/mod.rs +++ b/src/views/mod.rs @@ -4,7 +4,6 @@ pub mod for_you; pub mod my_vibe; pub mod overlays; pub mod player_bar; -pub mod player_thumbs; pub mod podcasts_kids; pub mod search; pub mod settings; @@ -24,10 +23,9 @@ use crate::vulkan::vibe_renderer::VibePushConstants; use overlays::{ render_delete_playlist_confirm_modal, render_entity_context_menu, render_eq_popover, - render_equalizer_modal, render_fullscreen_player, render_login_modal, render_playlist_modal, - render_release_notes_modal, render_right_drawer, render_shortcuts_modal, - render_toast_with_offset, render_track_context_menu, render_track_detail_modal, - render_update_notification, render_vibe_settings_modal, ShellUiState, SplashPlayer, + render_fullscreen_player, render_login_modal, render_playlist_modal, render_right_drawer, + render_toast, render_track_context_menu, render_track_detail_modal, render_vibe_settings_modal, + ShellUiState, SplashPlayer, }; use player_bar::render_player_bar; use sidebar::render_sidebar; @@ -248,46 +246,9 @@ impl YandexMusicShell { ); } - // Route transition (0.20s ease-out upward glide + dissolve; 0 overhead when steady or deterministic test!) - if self.app.fixed_vibe_time.is_none() - && self.shell.last_route.as_ref() != Some(&self.app.route) - { - if self.shell.last_route.is_some() { - self.shell.route_transition_start = time; - } - self.shell.last_route = Some(self.app.route.clone()); - } - let route_t = if self.app.fixed_vibe_time.is_some() || self.shell.route_transition_start <= 0.0 - { - 1.0f32 - } else { - ((time - self.shell.route_transition_start) as f32 / 0.20).clamp(0.0, 1.0) - }; - if route_t < 1.0 { - self.ui.request_repaint(); - } - let route_ease = { - let u = 1.0 - route_t; - 1.0 - u * u * u - }; - let page_dy = if route_t < 1.0 { - ((1.0 - route_ease) * 14.0).round() - } else { - 0.0 - }; - - // 3. Optional Right Slide-Over Drawer (smooth 0.22s slide-in/out; instant in deterministic test!) + // 3. Optional Right Slide-Over Drawer (Queue / Sync Lyrics; hidden when Fullscreen is open) let show_side_drawer = self.app.right_drawer != RightDrawerTab::None && !self.app.fullscreen_open; - let drawer_t = if self.app.fixed_vibe_time.is_some() { - if show_side_drawer { 1.0 } else { 0.0 } - } else { - self.ui.animate_bool(WidgetId::new("ym_right_drawer_anim"), show_side_drawer, 0.22) - }; - let drawer_ease = { - let u = 1.0 - drawer_t.clamp(0.0, 1.0); - 1.0 - u * u * u - }; let content_bottom = if is_my_vibe_page { screen.bottom() } else { @@ -295,14 +256,13 @@ impl YandexMusicShell { }; let drawer_w = 332.0; let content_top = screen.top() + TITLEBAR_HEIGHT + 1.0; - let drawer_shift = drawer_ease * (drawer_w + LAYOUT_GAP); let drawer_rect = Rect::from_xywh( - screen.right() - drawer_shift, + screen.right() - drawer_w - LAYOUT_GAP, content_top, drawer_w, (content_bottom - content_top).max(40.0), ); - if drawer_ease > 0.01 { + if show_side_drawer { render_right_drawer( &mut self.ui, &pal, @@ -319,7 +279,7 @@ impl YandexMusicShell { let vibe_rect = Rect::from_xywh( nav_w, screen.top(), - (screen.width() - nav_w - if drawer_ease > 0.01 { drawer_shift + LAYOUT_GAP } else { 0.0 }) + (screen.width() - nav_w - if show_side_drawer { drawer_w + LAYOUT_GAP * 2.0 } else { 0.0 }) .max(100.0), screen.height(), ); @@ -332,15 +292,8 @@ impl YandexMusicShell { vibe_rect, &mut actions, ); - if route_t < 1.0 { - self.ui.dl().push_rect( - vibe_rect, - 0.0, - pal.bg_basic.with_alpha_f32((1.0 - route_ease) * 0.55), - ); - } } else { - let content_right = if drawer_ease > 0.01 { + let content_right = if show_side_drawer { drawer_rect.left() - LAYOUT_GAP } else { screen.right() - LAYOUT_GAP @@ -390,13 +343,7 @@ impl YandexMusicShell { ); // Exact inner content rect (+25px horizontal, +12px top so inner y stays 45.0 with +1px card_top) - let base_inner_r = outer_r.inset(25.0, 12.0, 25.0, 0.0); - let inner_r = Rect::from_xywh( - base_inner_r.left(), - base_inner_r.top() + page_dy, - base_inner_r.width(), - base_inner_r.height(), - ); + let inner_r = outer_r.inset(25.0, 12.0, 25.0, 0.0); self.ui.push_clip(outer_r, CONTENT_RADIUS); match self.app.route.clone() { Route::MyVibe => {} @@ -503,32 +450,11 @@ impl YandexMusicShell { &mut actions, ), } - if route_t < 1.0 { - self.ui.dl().push_rect( - outer_r, - CONTENT_RADIUS, - pal.bg_content.with_alpha_f32((1.0 - route_ease) * 0.65), - ); - } self.ui.pop_clip(); } - // 5. FullscreenPlayerDesktop (ZLayer::Drawer — smooth 0.24s glide-up/down!) - let fs_t = if self.app.fixed_vibe_time.is_some() { - if self.app.fullscreen_open { 1.0 } else { 0.0 } - } else { - self.ui.animate_bool(WidgetId::new("ym_fullscreen_anim"), self.app.fullscreen_open, 0.24) - }; - let fs_ease = { - let u = 1.0 - fs_t.clamp(0.0, 1.0); - 1.0 - u * u * u - }; - self.shell.fs_slide_dy = if fs_ease < 0.999 { - ((1.0 - fs_ease) * 48.0).round() - } else { - 0.0 - }; - if fs_ease > 0.01 { + // 5. FullscreenPlayerDesktop (ZLayer::Drawer — sits below Popovers/Modals/Titlebar!) + if self.app.fullscreen_open { render_fullscreen_player( &mut self.ui, &pal, @@ -540,38 +466,8 @@ impl YandexMusicShell { } // 6. Floating Popovers & Context Menus (ZLayer::Popover) - let ease_out = |t: f32| -> f32 { - let u = 1.0 - t.clamp(0.0, 1.0); - 1.0 - u * u * u - }; - let eq_pop_t = if self.app.fixed_vibe_time.is_some() { - if self.app.eq_popover_open { 1.0 } else { 0.0 } - } else { - ease_out(self.ui.animate_bool( - WidgetId::new("ym_quality_popover_anim"), - self.app.eq_popover_open, - 0.22, - )) - }; - let eq_expand_t = if self.app.fixed_vibe_time.is_some() { - if self.app.config.eq_enabled { 1.0 } else { 0.0 } - } else { - self.ui.animate_bool( - WidgetId::new("ym_quality_eq_expand"), - self.app.config.eq_enabled, - 0.20, - ) - }; - if eq_pop_t > 0.01 { - render_eq_popover( - &mut self.ui, - &pal, - &self.app, - &mut self.shell, - eq_pop_t, - eq_expand_t, - &mut actions, - ); + if self.app.eq_popover_open { + render_eq_popover(&mut self.ui, &pal, &self.app, &mut actions); } render_track_context_menu(&mut self.ui, &pal, &self.app, &mut self.shell, &mut actions); render_entity_context_menu(&mut self.ui, &pal, &self.app, &mut self.shell, &mut actions); @@ -594,49 +490,6 @@ impl YandexMusicShell { if self.app.track_detail_modal.is_some() { render_track_detail_modal(&mut self.ui, &pal, &mut self.covers, &self.app, &mut actions); } - let rn_mod_t = if self.app.fixed_vibe_time.is_some() { - if self.app.release_notes_modal_open { 1.0 } else { 0.0 } - } else { - ease_out(self.ui.animate_bool( - WidgetId::new("ym_release_notes_modal_anim"), - self.app.release_notes_modal_open, - 0.18, - )) - }; - if rn_mod_t > 0.01 { - render_release_notes_modal(&mut self.ui, &pal, &self.app, rn_mod_t, &mut actions); - } - let eq_mod_t = if self.app.fixed_vibe_time.is_some() { - if self.app.equalizer_modal_open { 1.0 } else { 0.0 } - } else { - ease_out(self.ui.animate_bool( - WidgetId::new("ym_eq_modal_anim"), - self.app.equalizer_modal_open, - 0.18, - )) - }; - if eq_mod_t > 0.01 { - render_equalizer_modal( - &mut self.ui, - &pal, - &self.app, - &mut self.shell, - eq_mod_t, - &mut actions, - ); - } - let sc_mod_t = if self.app.fixed_vibe_time.is_some() { - if self.app.shortcuts_modal_open { 1.0 } else { 0.0 } - } else { - ease_out(self.ui.animate_bool( - WidgetId::new("ym_shortcuts_modal_anim"), - self.app.shortcuts_modal_open, - 0.18, - )) - }; - if sc_mod_t > 0.01 { - render_shortcuts_modal(&mut self.ui, &pal, &self.app, sc_mod_t, &mut actions); - } // 8. Transparent 32px Floating TitleBar (ZLayer::Titlebar) let win_cmd = render_titlebar( @@ -647,20 +500,10 @@ impl YandexMusicShell { self.app.fullscreen_open, ); - // 9. Official `NotificationUpdate` + Floating Toast (when splash is done) - let show_upd_notif = self.splash.is_none() - && !self.app.fullscreen_open - && !self.app.update_notification_dismissed - && self.app.available_update.is_some(); - if show_upd_notif { - if let Some(ref upd) = self.app.available_update { - render_update_notification(&mut self.ui, &pal, &self.app, upd, &mut actions); - } - } + // 9. Floating Toast (when splash is done) if self.splash.is_none() { if let Some(msg) = self.app.current_toast().map(String::from) { - let extra_offset = if show_upd_notif { 64.0 } else { 0.0 }; - render_toast_with_offset(&mut self.ui, &pal, &msg, extra_offset); + render_toast(&mut self.ui, &pal, &msg); } } @@ -672,16 +515,9 @@ impl YandexMusicShell { } // Dispatch all actions emitted during this frame - let had_actions = !actions.is_empty(); for act in actions { self.app.dispatch(act); } - // Any dispatched UI action may open/close a popover, modal, or start an animation - // that wasn't evaluated yet this frame — schedule an immediate follow-up frame so - // 0 FPS idle mode never stalls opening a menu until the next mouse move. - if had_actions { - self.ui.request_repaint(); - } // Flush any clipboard write requested by Share > Copy link / HTML code if let Some(clip_text) = self.app.take_pending_clipboard_text() { diff --git a/src/views/my_vibe.rs b/src/views/my_vibe.rs index a9dc301..27c158f 100644 --- a/src/views/my_vibe.rs +++ b/src/views/my_vibe.rs @@ -1,6 +1,6 @@ use std::cell::RefCell; -use crate::api::models::{format_ms, Track, VibeStationSummary, WordsCard}; +use crate::api::models::{format_ms, Track, VibeStationSummary}; use crate::api::YandexApiClient; use crate::app::i18n::APP_VERSION; use crate::app::state::{ @@ -35,8 +35,6 @@ struct VibePageLocalState { wheel_scroll_target: Option, submenu: VibeSubmenu, submenu_anchor_y: f32, - words_popover_open: bool, - words_popover_track_id: String, } impl Default for VibePageLocalState { @@ -47,28 +45,10 @@ impl Default for VibePageLocalState { wheel_scroll_target: None, submenu: VibeSubmenu::None, submenu_anchor_y: 0.0, - words_popover_open: false, - words_popover_track_id: String::new(), } } } -const WORDS_LOADING_PHRASES_RU: &[&str] = &[ - "Собираю интересное силой ИИ", - "Настраиваюсь", - "Ловлю ритм", - "Читаю про артиста", - "Изучаю звучание", -]; - -const WORDS_LOADING_PHRASES_EN: &[&str] = &[ - "Using the AI power to collect interesting stuff", - "Getting ready", - "Getting in the rhythm", - "Reading about the artist", - "Analyzing the sound", -]; - thread_local! { static VIBE_LOCAL: RefCell = RefCell::new(VibePageLocalState::default()); } @@ -254,74 +234,111 @@ pub fn render_my_vibe( "Reset to My Vibe" }; - if is_non_vibe_context || is_custom_vibe_station { - // Exact official 5.129.0 `.VibeResetButton_button__i8Cvy` + `.VibeResetButton_context__hsTlv`: - // ONE unified dark translucent 44px pill (radius 22px) with electric yellow 19px Headline text - // and a filled 22px yellow circle (`×` dark `#141414` inside) on the right of the SAME pill! - let pill_label = if is_non_vibe_context { - app.context_name.as_str() - } else { - vibe_label - }; - let yellow = if pal.is_dark { - Color::rgb(0xFF, 0xFF, 0x00) - } else { - Color::rgb(0xFF, 0xEE, 0x00) - }; - let lbl_style = TextStyle::headline(19.0, yellow); - let max_pill_w = (hero_rect.width() - 80.0).clamp(160.0, 440.0); - let max_text_w = (max_pill_w - 64.0).max(40.0); - let text_w = ctx.measure_text(pill_label, lbl_style, None).x.min(max_text_w); - let pill_w = (20.0 + text_w + 10.0 + 22.0 + 12.0).clamp(96.0, max_pill_w); - let pill_r = Rect::from_center_size(Pos2::new(cx, top_y), Vec2::new(pill_w, 44.0)); + if is_non_vibe_context { + let ctx_style = TextStyle::bold(16.0, pal.text_bright); + let max_pill_w = (hero_rect.width() - 120.0).clamp(140.0, 420.0); + let text_w = ctx + .measure_text(&app.context_name, ctx_style, None) + .x + .min(max_pill_w - 28.0); + let pill_w = (text_w + 28.0).clamp(72.0, max_pill_w); + let total_w = pill_w + 8.0 + 28.0; + let start_x = cx - total_w * 0.5; - let close_center = Pos2::new(pill_r.right() - 12.0 - 11.0, pill_r.center_y()); - let reset_r = Rect::from_center_size(close_center, Vec2::splat(32.0)); - let reset_resp = ctx.interact(WidgetId::new("vb_ctx_reset_btn"), reset_r); + let pill_r = Rect::from_xywh(start_x, top_y - 16.0, pill_w, 32.0); let pill_resp = ctx.interact(WidgetId::new("vb_ctx_source_pill"), pill_r); - - let pill_bg = if pill_resp.pressed || reset_resp.pressed { - css_rgba(0, 0, 0, 153) // rgba(0,0,0,0.60) - } else if pill_resp.hovered || reset_resp.hovered { - css_rgba(0, 0, 0, 102) // rgba(0,0,0,0.40) + let pill_bg = if pill_resp.hovered { + pal.surface_hover } else { - css_rgba(0, 0, 0, 77) // rgba(0,0,0,0.30) + pal.surface_secondary }; - ctx.dl().push_rect(pill_r, 22.0, pill_bg); + ctx.dl().push_rect(pill_r, 16.0, pill_bg); ctx.draw_text_ellipsis( - pill_label, - lbl_style, + &app.context_name, + ctx_style, Rect::from_xywh( - pill_r.left() + 20.0, + pill_r.left() + 14.0, pill_r.top(), - (text_w + 4.0).min(pill_r.width() - 56.0).max(20.0), + (pill_r.width() - 28.0).max(20.0), pill_r.height(), ), - TextAlign::Left, + TextAlign::Center, ); + if pill_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if pill_resp.clicked { + actions.push(AppAction::NavigateToCurrentContext); + } - let close_rad = if reset_resp.hovered { 11.5 } else { 11.0 }; - ctx.dl().push_circle(close_center, close_rad, yellow); + let reset_r = Rect::from_xywh(pill_r.right() + 8.0, top_y - 14.0, 28.0, 28.0); + let reset_resp = ctx.interact(WidgetId::new("vb_ctx_reset_btn"), reset_r); + ctx.dl().push_circle( + reset_r.center(), + 14.0, + if reset_resp.hovered { + pal.surface_hover + } else { + pal.surface_secondary + }, + ); ctx.draw_icon( Icon::Close, - Rect::from_center_size(close_center, Vec2::splat(12.0)), - Color::rgb(0x14, 0x14, 0x14), + Rect::from_center_size(reset_r.center(), Vec2::splat(14.0)), + if reset_resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, ); - if reset_resp.hovered { ctx.set_cursor(CursorKind::Pointer); ctx.show_tooltip(reset_r, reset_tooltip); - } else if pill_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); } if reset_resp.clicked { actions.push(AppAction::ResetContextToMyVibe); - } else if pill_resp.clicked { - if is_non_vibe_context { - actions.push(AppAction::NavigateToCurrentContext); + } + } else if is_custom_vibe_station { + let lbl_col = if has_active_track { + pal.logo_text + } else { + pal.text_primary + }; + let lbl_style = TextStyle::headline(18.0, lbl_col); + let max_lbl_w = (hero_rect.width() - 120.0).clamp(140.0, 420.0); + let text_w = ctx.measure_text(vibe_label, lbl_style, None).x.min(max_lbl_w); + let total_w = text_w + 10.0 + 28.0; + let start_x = cx - total_w * 0.5; + + let lbl_r = Rect::from_xywh(start_x, top_y - 14.0, text_w + 4.0, 28.0); + ctx.draw_text_ellipsis(vibe_label, lbl_style, lbl_r, TextAlign::Center); + + let reset_r = Rect::from_xywh(lbl_r.right() + 8.0, top_y - 14.0, 28.0, 28.0); + let reset_resp = ctx.interact(WidgetId::new("vb_ctx_reset_btn"), reset_r); + ctx.dl().push_circle( + reset_r.center(), + 14.0, + if reset_resp.hovered { + pal.surface_hover } else { - actions.push(AppAction::ResetContextToMyVibe); - } + pal.surface_secondary + }, + ); + ctx.draw_icon( + Icon::Close, + Rect::from_center_size(reset_r.center(), Vec2::splat(14.0)), + if reset_resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ); + if reset_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + ctx.show_tooltip(reset_r, reset_tooltip); + } + if reset_resp.clicked { + actions.push(AppAction::ResetContextToMyVibe); } } else if playing_alpha > 0.005 && current_track.is_some() { // Default My Vibe playing: top Vibe label (`pal.logo_text`: #FFFF00 dark / #000000 light) @@ -764,14 +781,29 @@ pub fn render_my_vibe( } } - // 6c. Like Button (official 5.129.0 renders a clean white filled heart when liked!) + // 6c. Like Button (darker contrast backing when liked over bright playing orange/red gradient!) let like_center = Pos2::new(capsule_r.right() + 28.0, btn_y); + if is_liked && play_fade_t > 0.1 { + ctx.dl().push_circle( + like_center, + 24.0, + css_rgba(0, 0, 0, (56.0 * play_fade_t).round() as u8), + ); + } if draw_vibe_circle_btn( ctx, like_center, "vb_like", if is_liked { Icon::Liked } else { Icon::Like }, - if is_liked { col_side_hi } else { col_side_lo }, + if is_liked { + if play_fade_t > 0.1 { + Color::rgb(0xFF, 0x3B, 0x30) + } else { + pal.accent_coral + } + } else { + col_side_lo + }, ) { if let Some(ref tr) = current_track { actions.push(AppAction::ToggleLike(tr.clone())); @@ -865,252 +897,84 @@ pub fn render_my_vibe( actions.push(AppAction::Next); } - // 8. OFFICIAL 5.129.0 `WordsCard` (AI Track Facts / Replies — `4874` mod `78572`, `5b3a6ee99e2bd1b8.css`) + // 8. AI METEOR GLOW SETTINGS BUTTON + // Verified verbatim from `5b3a6ee99e2bd1b8.css`: // `.AiBadge_root__EfKG1 { width: 48px; height: 48px; }` // `.AiBadge_glow__R6cQa { opacity: 0.65; transform: translate3d(-25%, -43%, 0); }` + // `.WordsCard_root__6r3u2`: 14px medium, subtle 1.02 hover scale let ai_y = (tr_y + 100.0).min(rect.bottom() - 68.0); + let ai_rect = Rect::from_center_size(Pos2::new(cx, ai_y), Vec2::new(380.0, 48.0)); + let ai_resp = ctx.interact(WidgetId::new("vb_ai_settings"), ai_rect); + let ai_hov = ctx.animate_bool(WidgetId::new("vb_ai_hov"), ai_resp.hovered, 0.18); + let ai_scale = 1.0 + 0.02 * ai_hov; + let sp_c = Pos2::new(ai_rect.left() + 29.0, ai_y); let meteor_tex = ctx.icons.get_official_meteor_glow(&mut ctx.textures); - // Exact 180px base size at t=0 (matches lossless CDP reference) with gentle 1.25s alternate breathing - let pulse_t = 0.5 - 0.5 * ((ctx.input.time as f32) * (std::f32::consts::TAU / 2.5)).cos(); + // Exact 180px base size at t=0 (matches lossless CDP reference) with subtle 1.0..1.04 breathing + let pulse_t = 0.5 - 0.5 * ((ctx.input.time as f32) * 1.6).cos(); let glow_sz = 180.0_f32 * (1.0 + 0.04 * pulse_t); - - let active_words_card: Option = app.current_words_card().cloned(); - let feedback_msg: Option = app.current_words_feedback_message().map(str::to_string); - let current_tid = current_track.as_ref().map(|tr| tr.id.as_str()).unwrap_or(""); - let words_is_empty = !current_tid.is_empty() && app.words_empty_tracks.contains(current_tid); - - // Auto-close WordsCard popover whenever the active track changes or feedback toast activates - VIBE_LOCAL.with(|s| { - let mut st = s.borrow_mut(); - if st.words_popover_open && (st.words_popover_track_id != current_tid || feedback_msg.is_some()) { - st.words_popover_open = false; - } - }); - - let mut words_popover_anchor: Option<(Rect, WordsCard)> = None; - - if let Some(ref msg) = feedback_msg { - // State A — Feedback toast active (< 3s): sparkle + centered feedback message (non-clickable) - let msg_style = TextStyle::medium(14.0, pal.text_primary); - let msg_w = ctx - .measure_text(msg, msg_style, None) - .x - .min((hero_rect.width() - 120.0).max(160.0)); - let block_w = 44.0 + msg_w; - let block_l = cx - block_w * 0.5; - let sp_c = Pos2::new(block_l + 18.0, ai_y); - let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0); - let meteor_r = Rect::from_xywh( - badge_tl.x - glow_sz * 0.25, - badge_tl.y - glow_sz * 0.43, - glow_sz, - glow_sz, - ); - ctx.dl() - .push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(166)); - ctx.draw_icon( - Icon::AiSparkles, - Rect::from_center_size(sp_c, Vec2::splat(24.0)), - pal.text_bright, - ); - ctx.draw_text_ellipsis( - msg, - msg_style, - Rect::from_xywh(block_l + 40.0, ai_y - 16.0, msg_w + 8.0, 32.0), - TextAlign::Left, - ); - ctx.request_repaint_after(std::time::Duration::from_millis(250)); - } else if let Some(ref card) = active_words_card.as_ref().filter(|c| !c.is_disliked()) { - // State B — Real `WordsCard` loaded for current track & not disliked! - let max_card_w = (hero_rect.width() - 64.0).clamp(320.0, 480.0); - let text_max_w = (max_card_w - 60.0).max(200.0); - let text_style_base = TextStyle::medium(14.0, pal.text_primary).with_line_height(19.0); - let measured_text = ctx.measure_text(&card.text, text_style_base, Some(text_max_w)); - let text_h = measured_text.y.clamp(20.0, 58.0); - let has_action = card.action.is_some(); - let action_h = if has_action { 22.0 } else { 0.0 }; - let card_h = (text_h + action_h + 10.0).clamp(48.0, 92.0); - let card_w = (measured_text.x + 64.0).clamp(240.0, max_card_w); - let card_cy = ai_y.min(rect.bottom() - card_h * 0.5 - 12.0); - let card_r = Rect::from_center_size(Pos2::new(cx, card_cy), Vec2::new(card_w, card_h)); - - let card_resp = ctx.interact(WidgetId::new("vb_words_card"), card_r); - let ai_hov = ctx.animate_bool(WidgetId::new("vb_words_hov"), card_resp.hovered, 0.18); - let ai_scale = 1.0 + 0.02 * ai_hov; - - let sp_c = Pos2::new(card_r.left() + 24.0, card_r.center_y()); - let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0); - let meteor_r = Rect::from_xywh( - badge_tl.x - glow_sz * 0.25, - badge_tl.y - glow_sz * 0.43, - glow_sz, - glow_sz, - ); - ctx.dl() - .push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(166)); - ctx.draw_icon( - Icon::AiSparkles, - Rect::from_center_size(sp_c, Vec2::splat(24.0 * ai_scale)), - pal.text_bright, - ); - - let text_x = card_r.left() + 50.0; - let text_w = (card_r.right() - text_x - 8.0).max(120.0); - let text_top = card_r.center_y() - (text_h + action_h) * 0.5; - let card_text_col = if card_resp.hovered { - pal.text_bright - } else { - pal.text_primary - }; - let card_text_style = TextStyle::medium(14.0 * ai_scale, card_text_col) - .with_line_height(19.0 * ai_scale); - ctx.draw_text_wrapped( - &card.text, - card_text_style, - Rect::from_xywh(text_x, text_top, text_w, text_h + 4.0), - Some(3), - TextAlign::Left, - ); - - let mut action_clicked = false; - if let Some(ref act) = card.action { - let act_r = Rect::from_xywh(text_x, text_top + text_h + 2.0, text_w, 20.0); - let act_resp = ctx.interact(WidgetId::new("vb_words_action"), act_r); - ctx.draw_text_ellipsis( - &act.title, - TextStyle::medium( - 13.0, - if act_resp.hovered { - pal.text_bright - } else { - pal.logo_text - }, - ), - act_r, - TextAlign::Left, - ); - if act_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if act_resp.clicked && !act.url.is_empty() { - actions.push(AppAction::OpenUrl(act.url.clone())); - action_clicked = true; - } - } - - if card_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if card_resp.clicked && !action_clicked { - if card.has_big_card() { - VIBE_LOCAL.with(|s| s.borrow_mut().words_popover_open = false); - actions.push(AppAction::OpenWordsBigCard { - track_id: card.track_id.clone(), - }); - } else { - shell.close_all_menus(); - VIBE_LOCAL.with(|s| { - let mut st = s.borrow_mut(); - st.words_popover_open = !st.words_popover_open; - st.words_popover_track_id = card.track_id.clone(); - }); - } - } - - words_popover_anchor = Some((card_r, (*card).clone())); - } else if words_is_empty || active_words_card.as_ref().map_or(false, |c| c.is_disliked()) { - // State C — Resolved empty OR card disliked: centered dimmed sparkle badge (opacity 0.50, non-clickable) - let sp_c = Pos2::new(cx, ai_y); - let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0); - let meteor_r = Rect::from_xywh( - badge_tl.x - glow_sz * 0.25, - badge_tl.y - glow_sz * 0.43, - glow_sz, - glow_sz, - ); - ctx.dl() - .push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(72)); - ctx.draw_icon( - Icon::AiSparkles, - Rect::from_center_size(sp_c, Vec2::splat(24.0)), - pal.text_bright.scale_alpha(0.50), - ); + let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0); + let meteor_r = Rect::from_xywh( + badge_tl.x - glow_sz * 0.25, + badge_tl.y - glow_sz * 0.43, + glow_sz, + glow_sz, + ); + ctx.dl() + .push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(166)); + ctx.draw_icon( + Icon::AiSparkles, + Rect::from_center_size(sp_c, Vec2::splat(24.0 * ai_scale)), + pal.text_bright, + ); + let ai_lead = if ru { "Настроить " } else { "Using the " }; + let ai_rest = if ru { + "Мою волну по настроению и характеру" } else { - // State D — Loading OR offline visual fixture: official rotating 5.129.0 `words.loading-phrase-*` - // (Index 0 at `t == 0.0` matches `my_vibe.jpg` & lossless CDP `test_ext_02` pixel-for-pixel; - // clicking while loading does NOTHING — zero fake Vibe-settings modal!) - let ai_rect = Rect::from_center_size(Pos2::new(cx, ai_y), Vec2::new(380.0, 48.0)); - let sp_c = Pos2::new(ai_rect.left() + 29.0, ai_y); - let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0); - let meteor_r = Rect::from_xywh( - badge_tl.x - glow_sz * 0.25, - badge_tl.y - glow_sz * 0.43, - glow_sz, - glow_sz, - ); - ctx.dl() - .push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(166)); - ctx.draw_icon( - Icon::AiSparkles, - Rect::from_center_size(sp_c, Vec2::splat(24.0)), - pal.text_bright, - ); - let phrases = if ru { - WORDS_LOADING_PHRASES_RU - } else { - WORDS_LOADING_PHRASES_EN - }; - let phrase_idx = if ctx.input.time <= 0.001 { - 0 - } else { - ((ctx.input.time / 2.5).floor() as usize) % phrases.len() - }; - let ai_text_r = Rect::from_xywh( - ai_rect.left() + 56.0, - ai_rect.top(), - ai_rect.width() - 60.0, - ai_rect.height(), - ); - if phrase_idx == 0 { - let (lead, rest) = if ru { - ("Собираю ", "интересное силой ИИ") - } else { - ("Using the ", "AI power to collect interesting stuff") - }; - let ai_spans = [ - RichSpan::new(lead, TextStyle::medium(14.0, pal.text_secondary)), - RichSpan::new(rest, TextStyle::medium(14.0, pal.text_primary)), - ]; - ctx.draw_rich_text(&ai_spans, ai_text_r, Some(1), TextAlign::Left); - } else { - ctx.draw_text_ellipsis( - phrases[phrase_idx], - TextStyle::medium(14.0, pal.text_primary), - ai_text_r, - TextAlign::Left, - ); - } - if ctx.input.time > 0.001 && !current_tid.is_empty() && app.words_loading_tracks.contains(current_tid) { - ctx.request_repaint_after(std::time::Duration::from_millis(80)); - } + "AI power to collect interesting stuff" + }; + let ai_fs = 14.0 * ai_scale; + let ai_spans = [ + RichSpan::new( + ai_lead, + TextStyle::medium( + ai_fs, + if ai_resp.hovered { + pal.text_primary + } else { + pal.text_secondary + }, + ), + ), + RichSpan::new( + ai_rest, + TextStyle::medium( + ai_fs, + if ai_resp.hovered { + pal.text_bright + } else { + pal.text_primary + }, + ), + ), + ]; + let ai_text_r = Rect::from_xywh( + ai_rect.left() + 56.0, + ai_rect.top(), + ai_rect.width() - 60.0, + ai_rect.height(), + ); + ctx.draw_rich_text(&ai_spans, ai_text_r, Some(1), TextAlign::Left); + if ai_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if ai_resp.clicked { + actions.push(AppAction::SetVibeModalOpen(true)); } - // 9. BOTTOM-RIGHT VERSION BADGE (`APP_VERSION` = `0.1.5`, or `0.1.5 → {ver}` when update available!) - let (ver_label, ver_col) = if let Some(ref upd) = app.available_update { - ( - format!("{} → {}", APP_VERSION, upd.version), - if pal.is_dark { - pal.yellow - } else { - pal.outline_selected - }, - ) - } else { - (APP_VERSION.to_string(), pal.text_secondary) - }; - let ver_style = TextStyle::bold(13.5, ver_col); - let ver_w = (ctx.measure_text(&ver_label, ver_style, None).x + 16.0) - .max(46.0) + // 9. BOTTOM-RIGHT VERSION BADGE (`5.129.0`, theme-aware `pal.surface_secondary` + `pal.text_secondary`) + let ver_style = TextStyle::medium(13.0, pal.text_secondary); + let ver_w = (ctx.measure_text(APP_VERSION, ver_style, None).x + 22.0) + .max(68.0) .ceil(); let ver_r = Rect::from_xywh( (rect.right() - ver_w - 16.0).floor(), @@ -1128,12 +992,12 @@ pub fn render_my_vibe( pal.surface_secondary }, ); - ctx.draw_text_ellipsis(&ver_label, ver_style, ver_r, TextAlign::Center); + ctx.draw_text_ellipsis(APP_VERSION, ver_style, ver_r, TextAlign::Center); if ver_resp.hovered { ctx.set_cursor(CursorKind::Pointer); } if ver_resp.clicked { - actions.push(AppAction::OpenReleaseNotesModal); + actions.push(AppAction::CheckForUpdates); } // 10. LEFT CURVED-ARC WHEEL CAROUSEL (`WheelDesktop` exact math from `vibe_wheel_foryou_spec.md` §2.1) @@ -1476,526 +1340,6 @@ pub fn render_my_vibe( actions, ); } - - // 12. OFFICIAL 5.129.0 `WordsCardPopoverDesktop` (floating 12px above `WordsCard`, `ZLayer::Popover`) - let words_pop_open = VIBE_LOCAL.with(|s| s.borrow().words_popover_open); - if words_pop_open { - if let Some((anchor_r, ref card)) = words_popover_anchor { - render_words_card_popover(ctx, pal, ru, anchor_r, card, actions); - } else { - VIBE_LOCAL.with(|s| s.borrow_mut().words_popover_open = false); - } - } - - // 13. OFFICIAL 5.129.0 `WordsCardFullscreen` (`ZLayer::Modal` when `app.words_big_card_open`) - if app.words_big_card_open { - render_words_card_fullscreen(ctx, pal, covers, app, ru, active_words_card.as_ref(), actions); - } -} - -fn render_words_card_popover( - ctx: &mut UiContext, - pal: &YmPalette, - ru: bool, - anchor_rect: Rect, - card: &WordsCard, - actions: &mut Vec, -) { - let pop_w = 260.0_f32; - let item_h = 36.0_f32; - let div_h = 13.0_f32; - let src_count = card.actions.len().min(5); - let mut pop_h = 16.0 + 2.0 * item_h; - if src_count > 0 { - pop_h += src_count as f32 * item_h + div_h; - } - let disclaimer_text = if ru { - "AI может ошибаться, проверяйте важное" - } else { - "AI may make mistakes, be sure to double-check important information" - }; - let disclaimer_h = if card.is_fact() { - let mh = ctx - .measure_text( - disclaimer_text, - TextStyle::regular(12.0, pal.text_secondary).with_line_height(16.0), - Some(pop_w - 32.0), - ) - .y - .clamp(18.0, 40.0); - pop_h += div_h + mh + 8.0; - mh - } else { - 0.0 - }; - - let screen = ctx.screen_rect(); - let pop_x = (anchor_rect.center_x() - pop_w * 0.5) - .clamp(screen.left() + 12.0, (screen.right() - pop_w - 12.0).max(screen.left() + 12.0)); - let pop_y = (anchor_rect.top() - pop_h - 12.0).clamp(40.0, (screen.bottom() - pop_h - 12.0).max(40.0)); - let pop_rect = Rect::from_xywh(pop_x, pop_y, pop_w, pop_h); - - let mut close_pop = false; - ctx.with_layer(ZLayer::Popover, |ctx| { - let inner = ym_menu_frame(ctx, pal, pop_rect); - let mut y = inner.top(); - let w = inner.width(); - - if src_count > 0 { - for (idx, src) in card.actions.iter().take(src_count).enumerate() { - let r = Rect::from_xywh(inner.left(), y, w, item_h); - y += item_h; - if ym_menu_item( - ctx, - pal, - WidgetId::from_pair("wcp_src", idx), - r, - Icon::LinkXxs, - &src.title, - false, - false, - ) - .clicked - { - if !src.url.is_empty() { - actions.push(AppAction::OpenUrl(src.url.clone())); - } - close_pop = true; - } - } - ym_menu_divider(ctx, pal, Rect::from_xywh(inner.left(), y, w, div_h)); - y += div_h; - } - - let like_lbl = if ru { - "Больше такого" - } else { - "More similar replies" - }; - let dislike_lbl = if ru { "Мимо" } else { "Not cool" }; - - let r_like = Rect::from_xywh(inner.left(), y, w, item_h); - y += item_h; - if ym_menu_item( - ctx, - pal, - WidgetId::new("wcp_like"), - r_like, - Icon::ThumbUpXxs, - like_lbl, - card.is_liked(), - false, - ) - .clicked - { - actions.push(AppAction::SendWordsFeedback { - track_id: card.track_id.clone(), - card_id: card.id.clone(), - state: if card.is_liked() { - "neutral".into() - } else { - "like".into() - }, - }); - close_pop = true; - } - - let r_dislike = Rect::from_xywh(inner.left(), y, w, item_h); - y += item_h; - if ym_menu_item( - ctx, - pal, - WidgetId::new("wcp_dislike"), - r_dislike, - Icon::ThumbDownXxs, - dislike_lbl, - card.is_disliked(), - false, - ) - .clicked - { - actions.push(AppAction::SendWordsFeedback { - track_id: card.track_id.clone(), - card_id: card.id.clone(), - state: "dislike".into(), - }); - close_pop = true; - } - - if card.is_fact() { - ym_menu_divider(ctx, pal, Rect::from_xywh(inner.left(), y, w, div_h)); - y += div_h + 2.0; - ctx.draw_text_wrapped( - disclaimer_text, - TextStyle::regular(12.0, pal.text_secondary).with_line_height(16.0), - Rect::from_xywh(inner.left() + 8.0, y, w - 16.0, disclaimer_h + 4.0), - Some(3), - TextAlign::Center, - ); - } - - if ctx.input.clicked_outside_any(&[pop_rect, anchor_rect]) - || ctx.input.key_pressed(Key::Escape) - { - close_pop = true; - } - }); - - if close_pop { - VIBE_LOCAL.with(|s| s.borrow_mut().words_popover_open = false); - } -} - -fn render_words_card_fullscreen( - ctx: &mut UiContext, - pal: &YmPalette, - covers: &mut CoverCache, - app: &AppState, - ru: bool, - fallback_card: Option<&WordsCard>, - actions: &mut Vec, -) { - let screen = ctx.screen_rect(); - let mut should_close = false; - - ctx.with_layer(ZLayer::Modal, |ctx| { - ctx.register_blocker(screen); - ctx.dl().push_backdrop_blur( - screen, - 0.0, - 4.0, - pal.bg_overlay, - 0.0, - Color::TRANSPARENT, - ); - - // Top-right circular Close `×` button - let close_r = Rect::from_center_size( - Pos2::new(screen.right() - 40.0, screen.top() + 56.0), - Vec2::splat(40.0), - ); - let close_resp = ctx.interact(WidgetId::new("wcf_close"), close_r); - ctx.dl().push_circle( - close_r.center(), - 20.0, - if close_resp.hovered { - pal.surface_hover - } else { - pal.surface_secondary - }, - ); - ctx.draw_icon( - Icon::Close, - Rect::from_center_size(close_r.center(), Vec2::splat(18.0)), - if close_resp.hovered { - pal.text_bright - } else { - pal.text_primary - }, - ); - if close_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if close_resp.clicked { - should_close = true; - } - - let col_w = (screen.width() - 96.0).clamp(300.0, 560.0); - let col_x = screen.center_x() - col_w * 0.5; - let disclaimer = if ru { - "AI может ошибаться, проверяйте важное" - } else { - "AI may make mistakes, be sure to double-check important information" - }; - let disclaimer_y = screen.bottom() - 38.0; - let content_rect = Rect::from_min_max( - Pos2::new(col_x - 24.0, screen.top() + 92.0), - Pos2::new(col_x + col_w + 24.0, disclaimer_y - 12.0), - ); - - if app.words_big_card_loading { - // 3 subtle animated shimmer bars centered vertically while `POST /words/big-cards` loads - let shimmer = 0.5 + 0.5 * ((ctx.input.time as f32) * 3.2).sin(); - let a = (28.0 + 36.0 * shimmer).round() as u8; - let bar_col = if pal.is_dark { - css_rgba(255, 255, 255, a) - } else { - css_rgba(0, 0, 0, a) - }; - let sy = content_rect.center_y() - 40.0; - for (i, frac) in [0.88_f32, 1.0_f32, 0.64_f32].iter().enumerate() { - let bw = col_w * frac; - let br = Rect::from_xywh( - screen.center_x() - bw * 0.5, - sy + i as f32 * 30.0, - bw, - 18.0, - ); - ctx.dl().push_rect(br, 9.0, bar_col); - } - ctx.request_repaint(); - } else { - let full_text = app - .words_big_card - .as_ref() - .map(|b| b.text.as_str()) - .filter(|s| !s.is_empty()) - .or_else(|| fallback_card.map(|c| c.text.as_str())) - .unwrap_or(""); - let sources = app - .words_big_card - .as_ref() - .filter(|b| !b.actions.is_empty()) - .map(|b| b.actions.as_slice()) - .or_else(|| fallback_card.map(|c| c.actions.as_slice())) - .unwrap_or(&[]); - - let text_style = TextStyle::bold(20.0, pal.text_bright).with_line_height(28.0); - let measured = ctx.measure_text(full_text, text_style, Some(col_w)); - let src_count = sources.len().min(2); - let src_block_h = if src_count > 0 { - 28.0 + src_count as f32 * 46.0 - 8.0 - } else { - 0.0 - }; - let fb_block_h = if fallback_card.is_some() { 22.0 + 32.0 } else { 0.0 }; - let max_text_h = (content_rect.height() - src_block_h - fb_block_h - 16.0).max(110.0); - let used_text_h = measured.y.min(max_text_h); - let total_stack_h = used_text_h + src_block_h + fb_block_h; - let mut y = (content_rect.center_y() - total_stack_h * 0.5).max(content_rect.top()); - - // 1. Centered 20px bold story text (scrollable if longer than viewport, ZERO floating sparkle!) - let text_vp = Rect::from_xywh(col_x, y, col_w, used_text_h + 6.0); - if measured.y > max_text_h { - let scroll_id = WidgetId::new("wcf_text_scroll"); - let scroll_y = ctx.begin_scroll_v(scroll_id, text_vp, 0.0); - ctx.draw_text_wrapped( - full_text, - text_style, - Rect::from_xywh(col_x, text_vp.top() - scroll_y, col_w, measured.y + 12.0), - None, - TextAlign::Center, - ); - ctx.end_scroll_v(scroll_id, pal, measured.y + 16.0, false); - } else { - ctx.draw_text_wrapped( - full_text, - text_style, - Rect::from_xywh(col_x, y, col_w, measured.y + 12.0), - None, - TextAlign::Center, - ); - } - y += used_text_h; - - // 2. Centered full-width-fitted source/Alice glass pill(s) (28px below text, NEVER truncates!) - if src_count > 0 { - y += 28.0; - let max_pill_w = (screen.width() - 64.0).min(520.0); - for (idx, src) in sources.iter().take(src_count).enumerate() { - let lbl_style = TextStyle::medium(14.0, pal.text_bright); - let tw = ctx.measure_text(&src.title, lbl_style, None).x; - let pill_w = (tw + 54.0).clamp(160.0, max_pill_w); - let pill_r = Rect::from_xywh( - screen.center_x() - pill_w * 0.5, - y, - pill_w, - 38.0, - ); - let resp = ctx.interact(WidgetId::from_pair("wcf_src_pill", idx), pill_r); - let bg = if pal.is_dark { - css_rgba(255, 255, 255, if resp.hovered { 32 } else { 18 }) - } else if resp.hovered { - pal.surface_hover - } else { - pal.surface_secondary - }; - let border = if pal.is_dark { - css_rgba(255, 255, 255, 28) - } else { - pal.border_subtle - }; - ctx.dl().push_rect_bordered(pill_r, 19.0, bg, 1.0, border); - - // Left 18x18 icon: favicon_url -> Alice purple ring -> LinkRounded - let ic_center = Pos2::new(pill_r.left() + 22.0, pill_r.center_y()); - let ic_rect = Rect::from_center_size(ic_center, Vec2::splat(18.0)); - let mut drew_fav = false; - if let Some(ref fav) = src.favicon_url { - if let Some((tex_id, _, _)) = covers.get_or_fetch(fav, 64) { - ctx.dl().push_image(ic_rect, tex_id, 9.0, Color::WHITE); - drew_fav = true; - } - } - if !drew_fav { - let tl = src.title.to_lowercase(); - if tl.contains("алис") || tl.contains("alice") { - ctx.dl() - .push_circle(ic_center, 9.0, Color::rgb(0x18, 0x13, 0x26)); - ctx.dl().push_circle_stroke( - ic_center, - 8.0, - 2.2, - Color::rgb(0x8B, 0x5C, 0xF6), - ); - ctx.dl() - .push_circle(ic_center, 2.6, Color::rgb(0xC4, 0xB5, 0xFD)); - } else { - ctx.draw_icon( - Icon::LinkRounded, - Rect::from_center_size(ic_center, Vec2::splat(16.0)), - pal.text_bright, - ); - } - } - - ctx.draw_text_ellipsis( - &src.title, - lbl_style, - Rect::from_xywh( - pill_r.left() + 38.0, - pill_r.top(), - (pill_r.width() - 52.0).max(40.0), - pill_r.height(), - ), - TextAlign::Left, - ); - if resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if resp.clicked && !src.url.is_empty() { - actions.push(AppAction::OpenUrl(src.url.clone())); - } - y += 46.0; - } - y -= 8.0; - } - - // 3. BORDERLESS TEXT-ONLY feedback buttons (22px below source pill, 28px gap, ZERO boxes!) - if let Some(card) = fallback_card { - y += 22.0; - let like_lbl = if ru { - "Больше такого" - } else { - "More similar replies" - }; - let dislike_lbl = if ru { "Мимо" } else { "Not cool" }; - let muted = if pal.is_dark { - css_rgba(255, 255, 255, 148) - } else { - pal.text_secondary - }; - let lbl_style = TextStyle::medium(14.0, muted); - let like_tw = ctx.measure_text(like_lbl, lbl_style, None).x; - let dislike_tw = ctx.measure_text(dislike_lbl, lbl_style, None).x; - let like_w = 16.0 + 7.0 + like_tw + 8.0; - let dislike_w = 16.0 + 7.0 + dislike_tw + 8.0; - let gap = 28.0_f32; - let total_w = like_w + gap + dislike_w; - let start_x = screen.center_x() - total_w * 0.5; - let btn_h = 32.0; - - let like_r = Rect::from_xywh(start_x, y, like_w, btn_h); - let like_resp = ctx.interact(WidgetId::new("wcf_like"), like_r); - let like_fg = if card.is_liked() || like_resp.hovered { - pal.text_bright - } else { - muted - }; - ctx.draw_icon( - Icon::ThumbUpXxs, - Rect::from_center_size( - Pos2::new(like_r.left() + 10.0, like_r.center_y()), - Vec2::splat(16.0), - ), - like_fg, - ); - ctx.draw_text_ellipsis( - like_lbl, - TextStyle::medium(14.0, like_fg), - Rect::from_xywh(like_r.left() + 24.0, like_r.top(), like_tw + 8.0, btn_h), - TextAlign::Left, - ); - if like_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if like_resp.clicked { - actions.push(AppAction::SendWordsFeedback { - track_id: card.track_id.clone(), - card_id: card.id.clone(), - state: if card.is_liked() { - "neutral".into() - } else { - "like".into() - }, - }); - } - - let dislike_r = Rect::from_xywh(like_r.right() + gap, y, dislike_w, btn_h); - let dislike_resp = ctx.interact(WidgetId::new("wcf_dislike"), dislike_r); - let dislike_fg = if card.is_disliked() || dislike_resp.hovered { - pal.text_bright - } else { - muted - }; - ctx.draw_icon( - Icon::ThumbDownXxs, - Rect::from_center_size( - Pos2::new(dislike_r.left() + 10.0, dislike_r.center_y()), - Vec2::splat(16.0), - ), - dislike_fg, - ); - ctx.draw_text_ellipsis( - dislike_lbl, - TextStyle::medium(14.0, dislike_fg), - Rect::from_xywh( - dislike_r.left() + 24.0, - dislike_r.top(), - dislike_tw + 8.0, - btn_h, - ), - TextAlign::Left, - ); - if dislike_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if dislike_resp.clicked { - actions.push(AppAction::SendWordsFeedback { - track_id: card.track_id.clone(), - card_id: card.id.clone(), - state: "dislike".into(), - }); - } - } - } - - // 4. Disclaimer pinned cleanly near the bottom (`screen.bottom() - 32.0`) - let disc_col = if pal.is_dark { - css_rgba(255, 255, 255, 96) - } else { - pal.text_secondary - }; - ctx.draw_text_ellipsis( - disclaimer, - TextStyle::regular(12.0, disc_col), - Rect::from_center_size( - Pos2::new(screen.center_x(), screen.bottom() - 32.0), - Vec2::new((screen.width() - 64.0).max(200.0), 22.0), - ), - TextAlign::Center, - ); - - if ctx.input.key_pressed(Key::Escape) - || ctx.input.clicked_outside_any(&[content_rect, close_r]) - { - should_close = true; - } - }); - - if should_close { - actions.push(AppAction::CloseWordsBigCard); - } } #[allow(clippy::too_many_arguments)] diff --git a/src/views/overlays.rs b/src/views/overlays.rs index ec841f7..71ce6b1 100644 --- a/src/views/overlays.rs +++ b/src/views/overlays.rs @@ -2,19 +2,15 @@ use std::time::Instant; use crossbeam_channel::Receiver; -use crate::api::models::{format_ms, Track, TrackLyrics, UpdateInfo}; -use crate::app::i18n::APP_VERSION; -use crate::app::state::is_newer_version; +use crate::api::models::{format_ms, Track, TrackLyrics}; use crate::app::{AppAction, AppState, PlaylistModalState, RepeatMode, RightDrawerTab, Route}; -use crate::audio::dsp::{active_eq_preset_name, EQ_LABELS, EQ_PRESETS}; -use crate::config::AudioQuality; +use crate::audio::dsp::{EQ_LABELS, EQ_PRESETS}; use crate::covers::CoverCache; -use crate::engine::text::RichSpan; use crate::engine::textures::{premultiply_rgba_srgb, TextureRegistry}; use crate::engine::widgets::{ - draw_cover_art, draw_downloading_progress, icon_button, secondary_pill_button, - separated_artists, text_input_widget, yellow_pill_button, ym_menu_frame, ym_menu_item, - ym_menu_item_ex, ym_volume_capsule, SliderResponse, TextInputOptions, + draw_cover_art, icon_button, secondary_pill_button, separated_artists, text_input_widget, + yellow_pill_button, ym_menu_frame, ym_menu_item, ym_menu_item_ex, ym_vertical_slider, + ym_volume_capsule, TextInputOptions, }; use crate::engine::{ css_rgba, Color, CornerRadii, CursorKind, Pos2, Rect, TextAlign, TextStyle, TextureId, @@ -71,7 +67,6 @@ pub struct ShellUiState { pub entity_share_submenu_open: bool, pub sidebar_profile_open: bool, pub sidebar_appearance_open: bool, - pub sidebar_lang_open: bool, pub sidebar_pin_menu: Option<(usize, Pos2)>, pub vibe_menu_open: bool, pub vibe_vol_open: bool, @@ -84,14 +79,7 @@ pub struct ShellUiState { pub queue_drag: Option, pub fs_lyrics_scroll_y: f32, pub fs_lyrics_manual_until: f64, - pub fs_lyrics_upper_until: f64, - pub fs_lyrics_last_mouse: Option, pub fs_lyrics_track_id: String, - pub last_route: Option, - pub route_transition_start: f64, - pub last_drawer_tab: Option, - pub fs_slide_dy: f32, - pub eq_presets_dropdown_open: bool, } impl ShellUiState { @@ -184,7 +172,6 @@ impl ShellUiState { self.entity_share_submenu_open = false; self.sidebar_profile_open = false; self.sidebar_appearance_open = false; - self.sidebar_lang_open = false; self.sidebar_pin_menu = None; self.vibe_menu_open = false; self.vibe_vol_open = false; @@ -206,12 +193,7 @@ pub fn render_right_drawer( ) { let i18n = app.i18n(); let ru = i18n.is_ru(); - let tab = if app.right_drawer != RightDrawerTab::None { - shell.last_drawer_tab = Some(app.right_drawer); - app.right_drawer - } else { - shell.last_drawer_tab.unwrap_or(RightDrawerTab::Queue) - }; + let tab = app.right_drawer; ctx.with_layer(ZLayer::Drawer, |ctx| { ctx.register_blocker(rect); @@ -620,15 +602,7 @@ pub fn render_fullscreen_player( shell: &mut ShellUiState, actions: &mut Vec, ) { - let mut screen = ctx.screen_rect(); - if shell.fs_slide_dy.abs() > 0.5 { - screen = Rect::from_xywh( - screen.left(), - screen.top() + shell.fs_slide_dy, - screen.width(), - screen.height(), - ); - } + let screen = ctx.screen_rect(); let i18n = app.i18n(); let ru = i18n.is_ru(); let track = app.current_track(); @@ -664,9 +638,37 @@ pub fn render_fullscreen_player( ctx.register_blocker(screen); ctx.dl().push_rect(screen, 0.0, bg_color); - // Render track player + 50/50 split BEFORE top-right `v` collapse button so - // SyncLyrics top gradient fade mask never slices over `FullscreenPlayerDesktop_closeButton`! - if let Some(tr) = track { + // Top-right circular `v` collapse button (`FullscreenPlayerDesktop_closeButton`) + let close_r = Rect::from_center_size( + Pos2::new(screen.right() - 44.0, screen.top() + 56.0), + Vec2::splat(40.0), + ); + let close_resp = ctx.interact(WidgetId::new("fs_close"), close_r); + ctx.dl().push_circle( + close_r.center(), + if close_resp.hovered { 21.0 } else { 20.0 }, + if close_resp.hovered { + css_rgba(255, 255, 255, 36) + } else { + css_rgba(255, 255, 255, 22) + }, + ); + ctx.draw_icon( + Icon::ArrowDown, + Rect::from_center_size(close_r.center(), Vec2::splat(24.0)), + Color::WHITE, + ); + if close_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + ctx.show_tooltip(close_r, i18n.close()); + } + if close_resp.clicked { + actions.push(AppAction::SetFullscreen(false)); + } + + let Some(tr) = track else { + return; + }; // Mutually exclusive right split modes (SyncLyrics OR PlayQueue) WITHOUT closing fullscreen! let is_split = app.fullscreen_lyrics_open || app.fullscreen_queue_open; @@ -688,8 +690,7 @@ pub fn render_fullscreen_player( let cx_center = screen.center_x(); let cx_left = screen.left() + screen.width() * 0.25; let cx = cx_center + (cx_left - cx_center) * split_t; - // Center the entire (poster + 110px info) block symmetrically around `screen.center_y()` - let cov_cy = screen.center_y() - 55.0; + let cov_cy = screen.center_y() - 36.0; let cov_r = Rect::from_center_size(Pos2::new(cx, cov_cy), Vec2::splat(cov_sz)); // Soft cover elevation shadow @@ -849,7 +850,11 @@ pub fn render_fullscreen_player( "fs_ov_like", if is_liked { Icon::Liked } else { Icon::Like }, 30.0, - Color::WHITE, + if is_liked { + pal.accent_coral + } else { + Color::WHITE + }, i18n.like(), ) { actions.push(AppAction::ToggleLike(tr.clone())); @@ -949,7 +954,7 @@ pub fn render_fullscreen_player( } // Below Cover: Clickable Track Title + Explicit + Individually Clickable Artists - let title_y = cov_r.bottom() + 24.0; + let title_y = cov_r.bottom() + 20.0; let meta_w = cov_sz.max(320.0); let full_title = tr.full_title(); let measured_tw = ctx @@ -996,7 +1001,7 @@ pub fn render_fullscreen_player( } // Individually clickable artists below title (`SeparatedArtists`)! - let art_r = Rect::from_xywh(cx - meta_w * 0.5, title_y + 26.0, meta_w, 22.0); + let art_r = Rect::from_center_size(Pos2::new(cx, title_y + 34.0), Vec2::new(meta_w, 22.0)); if let Some((aid, aname)) = separated_artists( ctx, pal, @@ -1013,7 +1018,7 @@ pub fn render_fullscreen_player( } // Progress bar (`ChangeTimecode`: 4px `#E6E6E6` fill/thumb + hover timecodes + smooth drag seek) - let bar_y = cov_r.bottom() + 86.0; + let bar_y = title_y + 64.0; let bar_hit = Rect::from_center_size(Pos2::new(cx, bar_y), Vec2::new(cov_sz, 22.0)); let bar_resp = ctx.interact(WidgetId::new("fs_progress"), bar_hit); let bar_r = Rect::from_center_size(Pos2::new(cx, bar_y), Vec2::new(cov_sz, 4.0)); @@ -1083,24 +1088,13 @@ pub fn render_fullscreen_player( ctx.dl().push_circle(Pos2::new(fill_x, bar_y), 6.0, fill_col); } - // Right-Half 50/50 Animated Pane (`FullscreenPlayerDesktopContent_additionalContent`): SyncLyrics OR PlayQueue! + // Right-Half 50/50 Animated Pane: SyncLyrics OR PlayQueue! if split_t > 0.02 { - let indent = if screen.width() > 1060.0 { - 44.0 - } else if screen.width() > 960.0 { - 20.0 - } else { - 10.0 - }; - let right_left = screen.left() + screen.width() * 0.50 - indent; - let right_right = (right_left + screen.width() * 0.50).min(screen.right()); - let right_bottom = screen.bottom() - (screen.height() * 0.09).max(56.0); - + let right_rect = Rect::from_min_max( + Pos2::new(screen.left() + screen.width() * 0.48, screen.top() + 56.0), + Pos2::new(screen.right() - 48.0, screen.bottom() - 40.0), + ); if app.fullscreen_queue_open { - let right_rect = Rect::from_min_max( - Pos2::new(right_left, screen.top() + 56.0), - Pos2::new((right_right - 48.0).max(right_left + 120.0), right_bottom), - ); ctx.draw_text_ellipsis( i18n.queue(), TextStyle::headline(22.0, Color::WHITE.with_alpha_f32(split_t)), @@ -1123,17 +1117,12 @@ pub fn render_fullscreen_player( actions, ); } else { - let lyr_rect = Rect::from_min_max( - Pos2::new(right_left, screen.top() + 32.0), - Pos2::new(right_right, right_bottom), - ); render_fullscreen_sync_lyrics( ctx, app.current_lyrics.as_ref(), tr, position_ms, - is_playing, - lyr_rect, + right_rect, bg_color, split_t, ru, @@ -1142,41 +1131,13 @@ pub fn render_fullscreen_player( ); } } - } // end `if let Some(tr) = track` - - // Top-right circular `v` collapse button (`FullscreenPlayerDesktop_closeButton`, z-index: header) - let close_r = Rect::from_center_size( - Pos2::new(screen.right() - 44.0, screen.top() + 56.0), - Vec2::splat(40.0), - ); - let close_resp = ctx.interact(WidgetId::new("fs_close"), close_r); - ctx.dl().push_circle( - close_r.center(), - if close_resp.hovered { 21.0 } else { 20.0 }, - if close_resp.hovered { - css_rgba(255, 255, 255, 36) - } else { - css_rgba(255, 255, 255, 22) - }, - ); - ctx.draw_icon( - Icon::ArrowDown, - Rect::from_center_size(close_r.center(), Vec2::splat(24.0)), - Color::WHITE, - ); - if close_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - ctx.show_tooltip(close_r, i18n.close()); - } - if close_resp.clicked { - actions.push(AppAction::SetFullscreen(false)); - } - - if track.is_none() { - return; - } - // Bottom-right Volume / Mute button anchored cleanly at bottom-right aligned with top-right `v`! - let vol_center = Pos2::new(screen.right() - 44.0, screen.bottom() - 40.0); + // Bottom-right Volume / Mute button with upward 44×216 `ym_volume_capsule` hover popover! + // Smoothly shifts into the left player column when `split_t > 0` so neither the button nor + // its upward popover ever collides with `right_rect` (SyncLyrics / Queue split pane). + let vol_x_centered = screen.right() - 44.0; + let vol_x_split = (screen.left() + screen.width() * 0.48 - 34.0).max(screen.left() + 44.0); + let vol_x = vol_x_centered + (vol_x_split - vol_x_centered) * split_t; + let vol_center = Pos2::new(vol_x, screen.bottom() - 44.0); let vol_btn_r = Rect::from_center_size(vol_center, Vec2::splat(40.0)); let vol_resp = ctx.interact(WidgetId::new("fs_vol_btn"), vol_btn_r); let vol_val = app.config.volume; @@ -1244,19 +1205,12 @@ pub fn render_fullscreen_player( }); } -/// 1-to-1 Official `SyncLyrics` (`83ceed5f9f3f6e01.css` + `9631.422e0bf38581fe75.js`): -/// - `40vh` active anchor, `32px` Swiper spacing, `base_sz` `(2.5vw clamped 32..48px)`, `scale(1.2)` active line -/// - `INTRO` 4 staggered pulsing dots + `PREPARE` `3/2/1` countdown slot above line 0 -/// - `withVisibleUpperLyrics` (3s on mouse move) & `withVisibleScrolledLyrics` (3s on wheel scroll) -/// - Exact opacity ladder (`1.0` active, `0.30` next, `0.10` upcoming / upper-visible, `0.0` hidden past) -/// - Official `SyncLyricsFooter` (`Авторы:` / `Writers:` + `Источник:` / `Source:`) + `80px` top/bottom fades #[allow(clippy::too_many_arguments)] fn render_fullscreen_sync_lyrics( ctx: &mut UiContext, lyrics: Option<&TrackLyrics>, track: &Track, position_ms: u64, - is_playing: bool, lyr_rect: Rect, bg_color: Color, split_t: f32, @@ -1268,8 +1222,6 @@ fn render_fullscreen_sync_lyrics( shell.fs_lyrics_track_id = track.id.clone(); shell.fs_lyrics_scroll_y = 0.0; shell.fs_lyrics_manual_until = 0.0; - shell.fs_lyrics_upper_until = 0.0; - shell.fs_lyrics_last_mouse = None; } let Some(lyr) = lyrics.filter(|l| !l.lines.is_empty()) else { @@ -1287,85 +1239,52 @@ fn render_fullscreen_sync_lyrics( return; }; - let screen = ctx.screen_rect(); - let screen_w = screen.width(); - let base_sz = (screen_w * 0.025).clamp(32.0, 48.0).round(); - let active_sz = (base_sz * 1.2).round(); - let base_lh = (base_sz * 1.25).round(); - let active_lh = (active_sz * 1.25).round(); - let max_line_w = (lyr_rect.width() * 0.80).max(200.0); - let line_gap = 32.0f32; // exact Swiper `spaceBetween: 32` - - // Exact `--sync-lyrics-scroller-inset-top-vh: 40vh` anchor - let anchor_y = (screen.top() + screen.height() * 0.40) - .clamp(lyr_rect.top() + 48.0, lyr_rect.bottom() - 80.0); - - // Exact state machine: INTRO / PREPARE / PLAYING - let start_ms = lyr.lines.first().map_or(0, |l| l.time_ms); - let is_prepare = lyr.is_synced - && start_ms >= 3000 - && position_ms < start_ms - && (start_ms - position_ms) <= 3000; - let is_intro = lyr.is_synced && start_ms > 0 && position_ms < start_ms && !is_prepare; - let active_idx: Option = if lyr.is_synced && !is_intro && !is_prepare { - lyr.lines.iter().rposition(|l| l.time_ms <= position_ms) + let active_idx = if lyr.is_synced { + lyr.lines + .iter() + .rposition(|l| l.time_ms <= position_ms) + .unwrap_or(0) } else { - None + usize::MAX }; - // Pre-measure every line at fixed `base_sz` / `base_lh` (zero wrap-jumping during `scale(1.2)`) - let measure_style = TextStyle::headline(base_sz, Color::WHITE).with_line_height(base_lh); + let screen_w = ctx.screen_rect().width(); + let base_sz = (screen_w * 0.022).clamp(24.0, 32.0); + let active_sz = base_sz * 1.15; + let max_line_w = (lyr_rect.width() - 48.0).max(200.0); + + // Pre-measure lines let mut line_heights = Vec::with_capacity(lyr.lines.len()); let mut line_y = Vec::with_capacity(lyr.lines.len()); let mut cur_y = 0.0f32; - for line in &lyr.lines { + for (i, line) in lyr.lines.iter().enumerate() { + let is_active = i == active_idx; + let sz = if is_active { active_sz } else { base_sz }; let txt = if line.text.trim().is_empty() { "• • •" } else { line.text.as_str() }; - let measured = ctx.measure_text(txt, measure_style, Some(max_line_w)); - let h = measured.y.max(base_lh); + let measured = ctx.measure_text(txt, TextStyle::headline(sz, Color::WHITE), Some(max_line_w)); + let h = measured.y.max(sz * 1.25); line_y.push(cur_y + h * 0.5); line_heights.push(h); - cur_y += h + line_gap; + cur_y += h + 22.0; } let total_h = cur_y; - let counter_y = -(line_gap + 22.0); - let min_scroll = if is_intro || is_prepare { counter_y } else { 0.0 }; let now_t = ctx.input.time; let dt = ctx.input.dt; - - // Mouse movement (`> 2px`) reveals past upper lines for 3s (`withVisibleUpperLyrics`) - if let Some(pos) = ctx.input.pointer_pos { - if let Some(prev) = shell.fs_lyrics_last_mouse { - if pos.distance(prev) > 2.0 { - shell.fs_lyrics_upper_until = now_t + 3.0; - shell.fs_lyrics_last_mouse = Some(pos); - } - } else { - shell.fs_lyrics_last_mouse = Some(pos); - } - } - - // Wheel scroll enters manual browse mode for 3s (`withVisibleScrolledLyrics`) let wheel_dy = if ctx.is_hovered(lyr_rect) { ctx.input.wheel_delta.y } else { 0.0 }; if wheel_dy.abs() > 0.25 { - shell.fs_lyrics_scroll_y = (shell.fs_lyrics_scroll_y - wheel_dy).clamp(min_scroll, total_h.max(0.0)); + shell.fs_lyrics_scroll_y = (shell.fs_lyrics_scroll_y - wheel_dy).clamp(0.0, total_h.max(0.0)); shell.fs_lyrics_manual_until = now_t + 3.0; - } else if lyr.is_synced && now_t >= shell.fs_lyrics_manual_until { - let target_y = if is_intro || is_prepare { - counter_y - } else if let Some(act) = active_idx { - line_y[act] - } else { - 0.0 - }; + } else if lyr.is_synced && active_idx < line_y.len() && now_t >= shell.fs_lyrics_manual_until { + let target_y = line_y[active_idx]; let alpha = 1.0 - (-dt * 7.5).exp(); shell.fs_lyrics_scroll_y += (target_y - shell.fs_lyrics_scroll_y) * alpha; if (target_y - shell.fs_lyrics_scroll_y).abs() > 0.4 { @@ -1374,190 +1293,82 @@ fn render_fullscreen_sync_lyrics( } let manual_scrolled = now_t < shell.fs_lyrics_manual_until; - let upper_visible = now_t < shell.fs_lyrics_upper_until; + let center_y = lyr_rect.center_y(); let lyr_cx = lyr_rect.center_x(); ctx.push_clip(lyr_rect, 0.0); - - // Counter / Loader slot above line 0 (`INTRO`: 4 staggered pulsing dots; `PREPARE`: "3"/"2"/"1") - if is_intro || is_prepare { - let cy_screen = anchor_y + (counter_y - shell.fs_lyrics_scroll_y); - if cy_screen >= lyr_rect.top() - 40.0 && cy_screen <= lyr_rect.bottom() + 40.0 { - if is_prepare { - let rem_ms = start_ms.saturating_sub(position_ms); - let digit = ((rem_ms.saturating_sub(1)) / 1000 + 1).clamp(1, 3); - ctx.draw_text_ellipsis( - &digit.to_string(), - TextStyle::headline(base_sz, Color::WHITE.with_alpha_f32(0.50 * split_t)), - Rect::from_center_size(Pos2::new(lyr_cx, cy_screen), Vec2::new(80.0, base_lh)), - TextAlign::Center, - ); - } else { - let spacing = 20.0f32; - let start_x = lyr_cx - spacing * 1.5; - for k in 0..4 { - let (dy, dot_a) = if is_playing { - let phase = (now_t as f32 * 4.2 - k as f32 * 0.55).sin(); - (-phase.max(0.0) * 6.0, (0.30 + 0.55 * (phase * 0.5 + 0.5)) * split_t) - } else { - (0.0, 0.35 * split_t) - }; - ctx.dl().push_circle( - Pos2::new(start_x + k as f32 * spacing, cy_screen + dy), - 5.5, - Color::WHITE.with_alpha_f32(dot_a), - ); - } - if is_playing { - ctx.request_repaint(); - } - } - } - } - for (i, line) in lyr.lines.iter().enumerate() { - let y_screen = anchor_y + (line_y[i] - shell.fs_lyrics_scroll_y); + let y_screen = center_y + (line_y[i] - shell.fs_lyrics_scroll_y); let h = line_heights[i]; - let is_active = !manual_scrolled && active_idx == Some(i); - - let target_op: f32 = if !lyr.is_synced || manual_scrolled { - 1.0 - } else if is_intro || is_prepare { - if i == 0 { 0.30 } else { 0.10 } - } else if let Some(act) = active_idx { - if i == act { - 1.0 - } else if i == act + 1 { - 0.30 - } else if i > act + 1 { - 0.10 - } else if upper_visible { - 0.10 - } else { - 0.0 - } - } else { - 0.10 - }; - - let op_t = ctx.animate_f32(WidgetId::from_pair("fs_lyr_op", i), target_op, 0.45); - let act_t = ctx.animate_bool(WidgetId::from_pair("fs_lyr_act", i), is_active, 0.45); - - if y_screen + h * 0.65 < lyr_rect.top() - 48.0 - || y_screen - h * 0.65 > lyr_rect.bottom() + 48.0 - { + if y_screen + h * 0.5 < lyr_rect.top() - 40.0 || y_screen - h * 0.5 > lyr_rect.bottom() + 40.0 { continue; } - let line_visible = op_t > 0.02 || manual_scrolled || upper_visible || !lyr.is_synced; - let hit_r = Rect::from_center_size(Pos2::new(lyr_cx, y_screen), Vec2::new(max_line_w, h + 14.0)); + let is_active = i == active_idx; + let is_next = active_idx != usize::MAX && i == active_idx + 1; + let hit_r = Rect::from_center_size(Pos2::new(lyr_cx, y_screen), Vec2::new(max_line_w, h + 12.0)); let resp = ctx.interact(WidgetId::from_pair("fs_lyr_ln", i), hit_r); + let act_t = ctx.animate_bool(WidgetId::from_pair("fs_lyr_act", i), is_active, 0.35); let hov_t = ctx.animate_bool( WidgetId::from_pair("fs_lyr_hov", i), - resp.hovered && lyr.is_synced && line_visible, + resp.hovered && lyr.is_synced, 0.18, ); - let alpha = op_t.max(0.85 * hov_t) * split_t; - if alpha > 0.005 { - let col = Color::WHITE.with_alpha_f32(alpha); - let txt = if line.text.trim().is_empty() { - "• • •" - } else { - line.text.as_str() - }; + let base_alpha = if !lyr.is_synced || manual_scrolled { + 0.90f32 + } else if is_next { + 0.34 + } else { + 0.16 + }; + let alpha = (base_alpha + (1.0 - base_alpha) * act_t) + .max(0.90 * hov_t) + * split_t; + let sz = base_sz + (active_sz - base_sz) * act_t; + let col = Color::WHITE.with_alpha_f32(alpha); + let txt = if line.text.trim().is_empty() { + "• • •" + } else { + line.text.as_str() + }; - if act_t < 0.01 { - ctx.draw_text_wrapped_scaled( - txt, - TextStyle::headline(base_sz, col).with_line_height(base_lh), - Rect::from_center_size(Pos2::new(lyr_cx, y_screen), Vec2::new(max_line_w, h)), - 1.0, - TextAlign::Center, - ); - } else { - let sc = (1.0 + 0.2 * act_t) / 1.2; - ctx.draw_text_wrapped_scaled( - txt, - TextStyle::headline(active_sz, col).with_line_height(active_lh), - Rect::from_center_size( - Pos2::new(lyr_cx, y_screen), - Vec2::new(max_line_w * 1.2, h * 1.2), - ), - sc, - TextAlign::Center, - ); - } - } + let draw_r = Rect::from_center_size(Pos2::new(lyr_cx, y_screen), Vec2::new(max_line_w, h + 6.0)); + ctx.draw_text_wrapped(txt, TextStyle::headline(sz, col), draw_r, None, TextAlign::Center); - if lyr.is_synced && line_visible { + if lyr.is_synced { if resp.hovered { ctx.set_cursor(CursorKind::Pointer); } if resp.clicked { - actions.push(AppAction::SeekMs(line.time_ms.saturating_add(10))); + actions.push(AppAction::SeekMs(line.time_ms)); shell.fs_lyrics_manual_until = 0.0; } } } - // Official `SyncLyricsFooter`: Writers + Source (`major`) attribution at `0.50` alpha - let has_writers = lyr.writers.as_deref().map_or(false, |s| !s.trim().is_empty()); - let has_major = lyr.major.as_deref().map_or(false, |s| !s.trim().is_empty()); - if has_writers || has_major { - let footer_pad_top = (screen_w * 0.0625).clamp(48.0, 96.0); - let footer_sz = (screen_w * 0.0125).clamp(15.0, 20.0); - let footer_col = Color::WHITE.with_alpha_f32(0.50 * split_t); - let footer_style = TextStyle::medium(footer_sz, footer_col); - let mut fy = anchor_y + (total_h + footer_pad_top - shell.fs_lyrics_scroll_y); - - if let Some(ref writers) = lyr.writers.as_deref().filter(|s| !s.trim().is_empty()) { + // Writers footer + if let Some(ref writers) = lyr.writers { + let fy = center_y + (total_h + 24.0 - shell.fs_lyrics_scroll_y); + if fy >= lyr_rect.top() - 40.0 && fy <= lyr_rect.bottom() + 40.0 { let txt = if ru { format!("Авторы: {}", writers) } else { format!("Writers: {}", writers) }; - let mh = ctx - .measure_text(&txt, footer_style, Some(max_line_w)) - .y - .max(footer_sz * 1.35); - if fy + mh >= lyr_rect.top() - 40.0 && fy <= lyr_rect.bottom() + 40.0 { - ctx.draw_text_wrapped( - &txt, - footer_style, - Rect::from_xywh(lyr_cx - max_line_w * 0.5, fy, max_line_w, mh + 4.0), - Some(3), - TextAlign::Center, - ); - } - fy += mh + 8.0; - } - - if let Some(ref major) = lyr.major.as_deref().filter(|s| !s.trim().is_empty()) { - let txt = if ru { - format!("Источник: {}", major) - } else { - format!("Source: {}", major) - }; - let mh = ctx - .measure_text(&txt, footer_style, Some(max_line_w)) - .y - .max(footer_sz * 1.35); - if fy + mh >= lyr_rect.top() - 40.0 && fy <= lyr_rect.bottom() + 40.0 { - ctx.draw_text_wrapped( - &txt, - footer_style, - Rect::from_xywh(lyr_cx - max_line_w * 0.5, fy, max_line_w, mh + 4.0), - Some(2), - TextAlign::Center, - ); - } + ctx.draw_text_wrapped( + &txt, + TextStyle::regular(14.0, Color::WHITE.with_alpha_f32(0.5 * split_t)), + Rect::from_center_size(Pos2::new(lyr_cx, fy), Vec2::new(max_line_w, 40.0)), + Some(2), + TextAlign::Center, + ); } } - // Official `80px` (`5rem`) top & bottom gradient fade masks into `bg_color` - let fade_h = 80.0f32.min(lyr_rect.height() * 0.25); + // Smooth top & bottom gradient fade masks into `bg_color` + let fade_h = 84.0f32.min(lyr_rect.height() * 0.22); let bg_clear = bg_color.with_alpha(0); ctx.dl().push_gradient_rect( Rect::from_xywh(lyr_rect.left(), lyr_rect.top(), lyr_rect.width(), fade_h), @@ -1690,35 +1501,9 @@ pub fn render_track_context_menu( } y += row_h; - // 3. Download / Downloading / Delete from device (`TrackContextMenuDownloadItem`) - let is_downloading = app.is_track_downloading(&tr.id); + // 3. Download / Delete from device let r = Rect::from_xywh(inner.x, y, inner.w, row_h); - if is_downloading { - let dl_resp = ctx.interact(WidgetId::new("tcm_dl"), r); - if dl_resp.hovered { - ctx.dl().push_rect(r, 8.0, pal.surface_hover); - ctx.set_cursor(CursorKind::Pointer); - } - draw_downloading_progress( - ctx, - pal, - Pos2::new(r.left() + 18.0, r.center_y()), - 20.0, - app.track_download_progress(&tr.id), - true, - dl_resp.hovered, - ); - ctx.draw_text_ellipsis( - i18n.stop_download(), - TextStyle::medium(13.5, pal.text_primary), - Rect::from_xywh(r.left() + 38.0, r.top(), (r.width() - 46.0).max(40.0), r.height()), - TextAlign::Left, - ); - if dl_resp.clicked { - actions.push(AppAction::CancelDownload); - close_menu = true; - } - } else if ym_menu_item( + if ym_menu_item( ctx, pal, WidgetId::new("tcm_dl"), @@ -2151,7 +1936,7 @@ pub fn render_track_context_menu( if !sub_rect.is_empty() { keep.push(sub_rect); } - if ctx.input.consume_clicked_outside_any(&keep) { + if ctx.input.clicked_outside_any(&keep) { close_menu = true; } }); @@ -2481,7 +2266,7 @@ pub fn render_entity_context_menu( if !sub_rect.is_empty() { keep.push(sub_rect); } - if ctx.input.consume_clicked_outside_any(&keep) { + if ctx.input.clicked_outside_any(&keep) { close_menu = true; } }); @@ -2687,7 +2472,7 @@ pub fn render_vibe_settings_modal( 36.0, false, ); - if done_resp.clicked || ctx.input.consume_clicked_outside(modal_r) { + if done_resp.clicked || ctx.input.clicked_outside(modal_r) { actions.push(AppAction::SetVibeModalOpen(false)); } }); @@ -2913,7 +2698,7 @@ pub fn render_playlist_modal( submit = true; } - if ctx.input.consume_clicked_outside(modal_r) { + if ctx.input.clicked_outside(modal_r) { close_modal = true; } }); @@ -3066,7 +2851,7 @@ pub fn render_delete_playlist_confirm_modal( confirm = true; } - if ctx.input.consume_clicked_outside(modal_r) { + if ctx.input.clicked_outside(modal_r) { close_modal = true; } }); @@ -3210,7 +2995,7 @@ pub fn render_login_modal( actions.push(AppAction::SubmitOAuthToken(app.token_input.clone())); } - if ctx.input.consume_clicked_outside(modal_r) { + if ctx.input.clicked_outside(modal_r) { actions.push(AppAction::SetLoginModalOpen(false)); } }); @@ -3409,8 +3194,8 @@ pub fn render_track_detail_modal( like_r, if is_liked { Icon::Liked } else { Icon::Like }, 22.0, - if is_liked { pal.text_bright } else { pal.text_primary }, - pal.text_bright, + if is_liked { pal.accent_coral } else { pal.text_primary }, + if is_liked { pal.accent_coral_hover } else { pal.text_bright }, pal.surface_hover, false, i18n.like(), @@ -3636,7 +3421,7 @@ pub fn render_track_detail_modal( let total_h = (y - (body_viewport.top() - scroll_y)).max(0.0); ctx.end_scroll_v(scroll_id, pal, total_h, true); - if ctx.input.consume_clicked_outside(panel_r) { + if ctx.input.clicked_outside(panel_r) { actions.push(AppAction::CloseTrackDetailModal); } }); @@ -3650,931 +3435,158 @@ pub fn render_eq_popover( ctx: &mut UiContext, pal: &YmPalette, app: &AppState, - shell: &mut ShellUiState, - anim_t: f32, - eq_expand_t: f32, actions: &mut Vec, ) { - let i18n = app.i18n(); - let ru = i18n.is_ru(); + let ru = app.i18n().is_ru(); let screen = ctx.screen_rect(); - let open = app.eq_popover_open; - let alpha = anim_t.clamp(0.0, 1.0); - let expand_t = eq_expand_t.clamp(0.0, 1.0); - - let pop_w = (screen.width() - 32.0).clamp(320.0, 430.0); - let qualities = [ - ( - AudioQuality::Lossless, - if ru { "Превосходное" } else { "Superb" }, - if ru { - "Музыка в lossless и других высококачественных форматах для быстрого интернета и хорошей акустики" - } else { - "Music in lossless and other high-quality formats for fast internet connections and superior acoustic systems" - }, - ), - ( - AudioQuality::High, - if ru { "Оптимальное" } else { "Balanced" }, - if ru { - "Сбалансированный звук для большинства устройств" - } else { - "Balanced sound for most devices" - }, - ), - ( - AudioQuality::Standard, - if ru { "Экономичное" } else { "Efficient" }, - if ru { - "Стабильное звучание при медленном интернете" - } else { - "Stable sound with a slow internet connection" - }, - ), - ]; - - let txt_w = (pop_w - 72.0).max(120.0); - let mut row_heights = [0.0f32; 3]; - let mut total_rows_h = 0.0f32; - for (idx, (_, _, sub)) in qualities.iter().enumerate() { - let sub_h = ctx - .measure_text(sub, TextStyle::regular(12.0, pal.text_secondary), Some(txt_w)) - .y - .max(16.0); - let rh = 10.0 + 19.0 + 3.0 + sub_h + 10.0; - row_heights[idx] = rh; - total_rows_h += rh + 4.0; - } - - // Header (20+32+18) + Quality rows + Gap (20) + EQ header (28) + Bottom pad (22) - let base_h = 70.0 + total_rows_h + 20.0 + 28.0 + 22.0; - let eq_extra_h = 246.0 * expand_t; - let pop_h = (base_h + eq_extra_h).min((screen.height() - PLAYER_BAR_HEIGHT - 56.0).max(280.0)); - // Official `Modal` (`placement="right"`, `1372-8bc732062b5d53ca.js`): glides smoothly in from right edge! - let slide_dx = (1.0 - alpha) * 32.0; + let pop_w = 436.0; + let pop_h = 248.0; let pop_r = Rect::from_xywh( - (screen.right() - pop_w - 16.0).max(16.0) + slide_dx, - (screen.bottom() - PLAYER_BAR_HEIGHT - pop_h - 18.0).max(40.0), + (screen.right() - pop_w - 20.0).max(8.0), + (screen.bottom() - PLAYER_BAR_HEIGHT - pop_h - 26.0).max(36.0), pop_w, pop_h, ); let mut enabled = app.config.eq_enabled; - let mut preamp = app.config.eq_preamp; let mut bands = app.config.eq_bands_db; let mut changed = false; ctx.with_layer(ZLayer::Popover, |ctx| { - if open { - ctx.register_blocker(pop_r); - } - ctx.dl().push_shadow( - pop_r, - 16.0, - 24.0, - 0.0, - Vec2::new(0.0, 6.0), - pal.shadow_menu.scale_alpha(alpha), - ); - ctx.dl().push_rect_bordered( - pop_r, - 16.0, - pal.bg_popover.scale_alpha(alpha), - 1.0, - pal.border_subtle.scale_alpha(alpha), - ); - - ctx.push_clip(pop_r, 16.0); - - // Header: `"Настройки звука"` + filled circular Close `×` (`radius="round" color="secondary"`) - let hdr_r = Rect::from_xywh(pop_r.left() + 24.0, pop_r.top() + 20.0, pop_w - 48.0, 32.0); - ctx.draw_text_ellipsis( - i18n.sound_settings(), - TextStyle::headline(20.0, pal.text_bright.scale_alpha(alpha)), - Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 40.0, hdr_r.height()), - TextAlign::Left, - ); - let close_r = Rect::from_xywh(hdr_r.right() - 32.0, hdr_r.top(), 32.0, 32.0); + ctx.register_blocker(pop_r); ctx.dl() - .push_circle(close_r.center(), 16.0, pal.surface_hover.scale_alpha(alpha)); - if open - && icon_button( - ctx, - WidgetId::new("qs_close_btn"), - close_r, - Icon::Close, - 14.0, - pal.text_bright.scale_alpha(alpha), - pal.text_bright.scale_alpha(alpha), - pal.surface_hover.scale_alpha(alpha), - false, - i18n.close(), - ) - .clicked - { - shell.eq_presets_dropdown_open = false; - actions.push(AppAction::SetEqPopoverOpen(false)); - } + .push_shadow(pop_r, 16.0, 22.0, 0.0, Vec2::new(0.0, 6.0), pal.shadow_menu); + ctx.dl() + .push_backdrop_blur(pop_r, 16.0, 2.0, pal.bg_menu, 1.0, pal.border_control); - // 3 Official Quality Options (`QualitySettings_item`) - let mut y = hdr_r.bottom() + 18.0; - for (idx, (q, title, sub)) in qualities.iter().enumerate() { - let rh = row_heights[idx]; - let row_r = Rect::from_xywh(pop_r.left() + 10.0, y, pop_w - 20.0, rh); - let resp = if open { - ctx.interact(WidgetId::from_pair("qs_qual", *q as u8), row_r) - } else { - Default::default() - }; - let active = app.config.audio_quality == *q; - if resp.hovered { - ctx.dl() - .push_rect(row_r, 10.0, pal.surface_hover.scale_alpha(alpha)); - ctx.set_cursor(CursorKind::Pointer); - } - let row_txt_x = row_r.left() + 14.0; - let row_txt_w = (row_r.width() - 48.0).max(80.0); - ctx.draw_text_ellipsis( - title, - TextStyle::bold(14.5, pal.text_bright.scale_alpha(alpha)), - Rect::from_xywh(row_txt_x, row_r.top() + 9.0, row_txt_w, 19.0), - TextAlign::Left, - ); - ctx.draw_text_wrapped( - sub, - TextStyle::regular(12.0, pal.text_secondary.scale_alpha(alpha)), - Rect::from_xywh(row_txt_x, row_r.top() + 31.0, row_txt_w, rh - 36.0), - None, - TextAlign::Left, - ); - if active { - ctx.draw_icon( - Icon::CheckXxs, - Rect::from_center_size( - Pos2::new(row_r.right() - 18.0, row_r.center_y()), - Vec2::splat(16.0), - ), - pal.text_bright.scale_alpha(alpha), - ); - } - if resp.clicked && !active { - actions.push(AppAction::SetAudioQuality(*q)); - } - y += rh + 4.0; - } + let inner = pop_r.shrink(14.0); - // Clean official vertical spacing before Equalizer section (no extra divider line) - y += 20.0; - - // Inline Official Equalizer (`Equalizer_header` + animated expandable Preamp + 10 bands + Presets) - let eq_area = Rect::from_min_max( - Pos2::new(pop_r.left() + 24.0, y), - Pos2::new(pop_r.right() - 24.0, pop_r.bottom() - 20.0), - ); - let dd_anchor = render_equalizer_body( - ctx, - pal, - eq_area, - if ru { "Эквалайзер" } else { "Equalizer" }, - ru, - &mut enabled, - &mut preamp, - &mut bands, - &mut changed, - &mut shell.eq_presets_dropdown_open, - alpha, - expand_t, - false, - open, - "qs_eq", - ); - - ctx.pop_clip(); - - // Render floating presets dropdown OUTSIDE popover clip so `placement: "top"` is never cut off! - let mut dd_rect: Option = None; - if open && shell.eq_presets_dropdown_open { - if let Some((sel_r, sel_clicked)) = dd_anchor { - dd_rect = render_eq_presets_dropdown( - ctx, - pal, - sel_r, - pop_r, - ru, - &mut enabled, - &mut preamp, - &mut bands, - &mut changed, - &mut shell.eq_presets_dropdown_open, - sel_clicked, - "qs_eq", - ); - } - } - - if open { - let mut keep = vec![pop_r]; - if let Some(dr) = dd_rect { - keep.push(dr); - } - if ctx.input.consume_clicked_outside_any(&keep) { - shell.eq_presets_dropdown_open = false; - actions.push(AppAction::SetEqPopoverOpen(false)); - } - } - }); - - if changed { - actions.push(AppAction::UpdateEq { - enabled, - preamp, - bands, - }); - } -} - -/// 1-to-1 Official `EqualizerModal` (`Equalizer_modal__yW0lz`, `430px` centered modal). -pub fn render_equalizer_modal( - ctx: &mut UiContext, - pal: &YmPalette, - app: &AppState, - shell: &mut ShellUiState, - anim_t: f32, - actions: &mut Vec, -) { - let i18n = app.i18n(); - let ru = i18n.is_ru(); - let open = app.equalizer_modal_open; - let alpha = anim_t.clamp(0.0, 1.0); - let screen = ctx.screen_rect(); - let modal_w = (screen.width() - 48.0).clamp(320.0, 430.0); - let modal_h = 370.0; - let modal_r = Rect::from_center_size( - Pos2::new(screen.center_x(), screen.center_y()), - Vec2::new(modal_w, modal_h), - ); - - let mut enabled = app.config.eq_enabled; - let mut preamp = app.config.eq_preamp; - let mut bands = app.config.eq_bands_db; - let mut changed = false; - - ctx.with_layer(ZLayer::Modal, |ctx| { - if open { - ctx.register_blocker(screen); - } - ctx.dl().push_rect( - screen, - 0.0, - Color::rgba(0, 0, 0, (150.0 * alpha).round() as u8), - ); - ctx.dl().push_shadow( - modal_r, - 16.0, - 32.0, - 0.0, - Vec2::new(0.0, 8.0), - pal.shadow_modal.scale_alpha(alpha), - ); - ctx.dl().push_rect_bordered( - modal_r, - 16.0, - pal.bg_popover.scale_alpha(alpha), - 1.0, - pal.border_subtle.scale_alpha(alpha), - ); - - let hdr_r = Rect::from_xywh(modal_r.left() + 24.0, modal_r.top() + 20.0, modal_w - 48.0, 32.0); + // Header: Title + Enabled toggle + Close `×` ctx.draw_text_ellipsis( if ru { "Эквалайзер" } else { "Equalizer" }, - TextStyle::headline(20.0, pal.text_bright.scale_alpha(alpha)), - Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 40.0, hdr_r.height()), + TextStyle::bold(15.0, pal.text_bright), + Rect::from_xywh(inner.x, inner.y, 120.0, 24.0), TextAlign::Left, ); - let eq_close_r = Rect::from_xywh(hdr_r.right() - 32.0, hdr_r.top(), 32.0, 32.0); - ctx.dl() - .push_circle(eq_close_r.center(), 16.0, pal.surface_hover.scale_alpha(alpha)); - if open - && icon_button( - ctx, - WidgetId::new("eq_modal_close"), - eq_close_r, - Icon::Close, - 14.0, - pal.text_bright.scale_alpha(alpha), - pal.text_bright.scale_alpha(alpha), - pal.surface_hover.scale_alpha(alpha), - false, - i18n.close(), - ) - .clicked - { - shell.eq_presets_dropdown_open = false; - actions.push(AppAction::SetEqualizerModalOpen(false)); - } - let eq_area = Rect::from_min_max( - Pos2::new(modal_r.left() + 20.0, hdr_r.bottom() + 24.0), - Pos2::new(modal_r.right() - 20.0, modal_r.bottom() - 20.0), + let tog_r = Rect::from_xywh(inner.x + 126.0, inner.y, 110.0, 24.0); + let tog_resp = ctx.interact(WidgetId::new("eq_enable_tog"), tog_r); + let box_r = Rect::from_xywh(tog_r.x, tog_r.center_y() - 8.0, 16.0, 16.0); + ctx.dl().push_rect_bordered( + box_r, + 4.0, + if enabled { pal.yellow } else { Color::TRANSPARENT }, + 1.5, + if enabled { pal.yellow } else { pal.input_border }, ); - let is_disabled = !enabled; - let dd_anchor = render_equalizer_body( - ctx, - pal, - eq_area, - if ru { "Включить" } else { "Turn on" }, - ru, - &mut enabled, - &mut preamp, - &mut bands, - &mut changed, - &mut shell.eq_presets_dropdown_open, - alpha, - 1.0, - is_disabled, - open, - "em_eq", - ); - - let mut dd_rect: Option = None; - if open && shell.eq_presets_dropdown_open { - if let Some((sel_r, sel_clicked)) = dd_anchor { - dd_rect = render_eq_presets_dropdown( - ctx, - pal, - sel_r, - modal_r, - ru, - &mut enabled, - &mut preamp, - &mut bands, - &mut changed, - &mut shell.eq_presets_dropdown_open, - sel_clicked, - "em_eq", - ); - } - } - - if open { - let mut keep = vec![modal_r]; - if let Some(dr) = dd_rect { - keep.push(dr); - } - if ctx.input.consume_clicked_outside_any(&keep) { - shell.eq_presets_dropdown_open = false; - actions.push(AppAction::SetEqualizerModalOpen(false)); - } - } - }); - - if changed { - actions.push(AppAction::UpdateEq { - enabled, - preamp, - bands, - }); - } -} - -/// Official `EqualizerSlider` (`8711fa44496b8e09.css:340-416` + `.d6VuG0HnwpGO47uPjPeb` + `.P8_ABi1YnAOS8p8EY87f`): -/// - Thin `1px` (`0.0625rem`) muted vertical track (NO yellow fill from bottom) -/// - Centered `8×1px` `0 dB` serif tick -/// - Always-visible `13px` (`0.8125rem`) hollow dark-filled circular thumb with `1.5px` yellow border (`border_control` when disabled) -fn eq_vertical_slider( - ctx: &mut UiContext, - pal: &YmPalette, - id: WidgetId, - rect: Rect, - norm_val: f32, - disabled: bool, - interactive: bool, - alpha: f32, -) -> SliderResponse { - let resp = if !disabled && interactive { - ctx.interact(id, rect) - } else { - Default::default() - }; - let active = !disabled && (resp.hovered || resp.pressed || resp.dragged); - let cx = rect.center_x(); - let top = rect.top() + 7.0; - let bot = rect.bottom() - 7.0; - let track_h = (bot - top).max(20.0); - - // Thin 1.5px muted vertical track (`trackSize_xxs`) - let track_col = pal.border_control.scale_alpha(alpha); - ctx.dl() - .push_rect(Rect::from_xywh(cx - 0.75, top, 1.5, track_h), 0.75, track_col); - - // Centered 8×1px horizontal serif tick at midpoint (`EqualizerSlider_serif`) - ctx.dl().push_rect( - Rect::from_xywh((cx - 4.0).round(), (top + track_h * 0.5).round(), 8.0, 1.0), - 0.0, - track_col, - ); - - // Official circular thumb (`14px` diameter, medium-gray interior + crisp `1.5px` yellow ring) - let frac = norm_val.clamp(0.0, 1.0); - let thumb_y = bot - frac * track_h; - let thumb_r = if active { 7.5 } else { 7.0 }; - let thumb_fill = if pal.is_dark { - Color::rgb(0x42, 0x42, 0x42) - } else { - Color::rgb(0xE0, 0xE0, 0xE0) - } - .scale_alpha(alpha); - let border_col = if disabled { - pal.border_control.scale_alpha(alpha) - } else { - pal.yellow.scale_alpha(alpha) - }; - ctx.dl().push_rect_bordered( - Rect::from_center_size(Pos2::new(cx, thumb_y), Vec2::splat(thumb_r * 2.0)), - thumb_r, - thumb_fill, - 1.5, - border_col, - ); - - if active { - ctx.set_cursor(CursorKind::Pointer); - } - - let mut new_val = None; - if !disabled && interactive && (resp.pressed || resp.dragged || resp.clicked) { - if let Some(p) = ctx.input.pointer_pos { - new_val = Some((1.0 - (p.y - top) / track_h).clamp(0.0, 1.0)); - } - } - - SliderResponse { - value: new_val, - hovered: resp.hovered, - dragging: resp.pressed || resp.dragged, - } -} - -/// Shared official Yandex Music 5.129.0 Equalizer UI (module `31051`, `8711fa44496b8e09.css:136-422`): -/// Header + Toggle -> Expandable (Preamp + `12dB/0dB/-12dB` labels + 10 frequency bands) -> Full-width Pill Preset Selector. -#[allow(clippy::too_many_arguments)] -fn render_equalizer_body( - ctx: &mut UiContext, - pal: &YmPalette, - area: Rect, - toggle_title: &str, - ru: bool, - enabled: &mut bool, - preamp: &mut f32, - bands: &mut [f32; 10], - changed: &mut bool, - dropdown_open: &mut bool, - anim_alpha: f32, - expand_t: f32, - is_disabled: bool, - interactive: bool, - salt: &str, -) -> Option<(Rect, bool)> { - // 1. Header row: Title + official Toggle (`32×20px`, `16px` knob, `rqUESGQ8jp3tbDawOzuG`) - let hdr_r = Rect::from_xywh(area.left(), area.top(), area.width(), 24.0); - ctx.draw_text_ellipsis( - toggle_title, - TextStyle::medium(16.0, pal.text_bright.scale_alpha(anim_alpha)), - Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 44.0, hdr_r.height()), - TextAlign::Left, - ); - let sw_w = 32.0; - let sw_h = 20.0; - let sw_r = Rect::from_xywh(hdr_r.right() - sw_w, hdr_r.center_y() - sw_h * 0.5, sw_w, sw_h); - let sw_id = WidgetId::new(salt).with("toggle"); - let sw_resp = if interactive { - ctx.interact(sw_id, sw_r) - } else { - Default::default() - }; - let tog_t = ctx.animate_bool(sw_id.with("anim"), *enabled, 0.16); - let track_col = pal.surface_hover.lerp(pal.yellow, tog_t).scale_alpha(anim_alpha); - ctx.dl().push_rect(sw_r, sw_h * 0.5, track_col); - let knob_x = sw_r.left() + 10.0 + tog_t * 12.0; - let knob_col = if tog_t > 0.5 { - pal.on_yellow - } else if sw_resp.hovered { - pal.text_bright - } else { - pal.text_secondary - }; - ctx.dl() - .push_circle(Pos2::new(knob_x, sw_r.center_y()), 8.0, knob_col.scale_alpha(anim_alpha)); - if sw_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if sw_resp.clicked { - *enabled = !*enabled; - *changed = true; - if !*enabled { - *dropdown_open = false; - } - } - - if expand_t <= 0.01 { - return None; - } - - let content_alpha = (anim_alpha * expand_t).clamp(0.0, 1.0); - let clip_h = (246.0 * expand_t).max(0.0); - ctx.push_clip( - Rect::from_xywh(area.left() - 4.0, hdr_r.bottom(), area.width() + 8.0, clip_h), - 0.0, - ); - - let y = hdr_r.bottom() + 16.0; - let sliders_h = 144.0; // `9rem` - let lbl_col = if is_disabled { - pal.text_disabled - } else { - pal.text_secondary - } - .scale_alpha(content_alpha); - - // 2. Left Preamp column (`Equalizer_preamp`) + amp labels (`12dB / 0dB / -12dB`) - let preamp_w = 42.0; - let preamp_r = Rect::from_xywh(area.left(), y, preamp_w, sliders_h); - let preamp_norm = ((*preamp - 0.5) / 1.0).clamp(0.0, 1.0); - let presp = eq_vertical_slider( - ctx, - pal, - WidgetId::new(salt).with("preamp"), - preamp_r, - preamp_norm, - is_disabled, - interactive && expand_t > 0.85, - content_alpha, - ); - if presp.hovered || presp.dragging { - ctx.show_tooltip(preamp_r, format!("{:.2}×", *preamp)); - } - if let Some(v) = presp.value { - let next = ((0.5 + v * 1.0) * 20.0).round() / 20.0; - let clamped = next.clamp(0.5, 1.5); - if (clamped - *preamp).abs() >= 0.025 { - *preamp = clamped; - *changed = true; - } - } - ctx.draw_text_ellipsis( - if ru { "уровень" } else { "level" }, - TextStyle::regular(11.5, lbl_col), - Rect::from_xywh(area.left() - 4.0, y + sliders_h + 8.0, preamp_w + 8.0, 16.0), - TextAlign::Center, - ); - - let scale_x = area.left() + preamp_w + 2.0; - let scale_w = 34.0; - ctx.draw_text_ellipsis( - "12dB", - TextStyle::regular(11.0, lbl_col), - Rect::from_xywh(scale_x, y, scale_w, 16.0), - TextAlign::Left, - ); - ctx.draw_text_ellipsis( - "0dB", - TextStyle::regular(11.0, lbl_col), - Rect::from_xywh(scale_x, y + sliders_h * 0.5 - 8.0, scale_w, 16.0), - TextAlign::Left, - ); - ctx.draw_text_ellipsis( - "-12dB", - TextStyle::regular(11.0, lbl_col), - Rect::from_xywh(scale_x, y + sliders_h - 16.0, scale_w, 16.0), - TextAlign::Left, - ); - - // 3. 10 Frequency Sliders (`60`..`16k`) - let grid_x = scale_x + scale_w + 4.0; - let grid_w = (area.right() - grid_x).max(160.0); - let col_w = grid_w / 10.0; - for i in 0..10 { - let bx = grid_x + i as f32 * col_w; - let sr = Rect::from_xywh(bx + 1.0, y, (col_w - 2.0).max(18.0), sliders_h); - let norm = ((bands[i] + 12.0) / 24.0).clamp(0.0, 1.0); - let sresp = eq_vertical_slider( - ctx, - pal, - WidgetId::new(salt).with("band").with(i), - sr, - norm, - is_disabled, - interactive && expand_t > 0.85, - content_alpha, - ); - if sresp.hovered || sresp.dragging { - ctx.show_tooltip(sr, format!("{:+.1} dB", bands[i])); - } - if let Some(v) = sresp.value { - let db = ((v * 24.0 - 12.0) * 2.0).round() * 0.5; - let clamped = db.clamp(-12.0, 12.0); - if (clamped - bands[i]).abs() >= 0.25 { - bands[i] = clamped; - *changed = true; - } - } - ctx.draw_text_ellipsis( - EQ_LABELS[i], - TextStyle::regular(11.5, lbl_col), - Rect::from_xywh(bx, y + sliders_h + 8.0, col_w, 16.0), - TextAlign::Center, - ); - } - - // 4. Full-width Outlined Pill Preset Selector BELOW sliders (`EqualizerPresets_button`, `radius = h/2`) - let sel_y = y + sliders_h + 8.0 + 16.0 + 18.0; - let sel_h = 44.0; - let sel_r = Rect::from_xywh(area.left(), sel_y, area.width(), sel_h); - let sel_resp = if !is_disabled && interactive && expand_t > 0.85 { - ctx.interact(WidgetId::new(salt).with("preset_sel"), sel_r) - } else { - Default::default() - }; - let sel_bg = if sel_resp.hovered { - pal.surface_hover.scale_alpha(content_alpha) - } else { - Color::TRANSPARENT - }; - let sel_border = if is_disabled { - pal.border_subtle.scale_alpha(content_alpha) - } else { - pal.border_control.scale_alpha(content_alpha) - }; - ctx.dl() - .push_rect_bordered(sel_r, sel_h * 0.5, sel_bg, 1.0, sel_border); - let preset_lbl = active_eq_preset_name(bands, ru); - let label_col = if is_disabled { - pal.text_disabled - } else { - pal.text_bright - } - .scale_alpha(content_alpha); - ctx.draw_text_ellipsis( - preset_lbl, - TextStyle::bold(13.5, label_col), - Rect::from_xywh(sel_r.left() + 18.0, sel_r.top(), sel_r.width() - 46.0, sel_r.height()), - TextAlign::Left, - ); - ctx.draw_icon( - Icon::ArrowDown, - Rect::from_center_size(Pos2::new(sel_r.right() - 20.0, sel_r.center_y()), Vec2::splat(16.0)), - if is_disabled { - pal.text_disabled - } else { - pal.text_bright - } - .scale_alpha(content_alpha), - ); - if sel_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if sel_resp.clicked { - *dropdown_open = !*dropdown_open; - } - - ctx.pop_clip(); - - if *dropdown_open { - Some((sel_r, sel_resp.clicked)) - } else { - None - } -} - -/// Floating upward Equalizer Presets dropdown (`EqualizerPresets_container`, `placement: "top"`). -#[allow(clippy::too_many_arguments)] -fn render_eq_presets_dropdown( - ctx: &mut UiContext, - pal: &YmPalette, - sel_r: Rect, - parent_r: Rect, - ru: bool, - enabled: &mut bool, - preamp: &mut f32, - bands: &mut [f32; 10], - changed: &mut bool, - dropdown_open: &mut bool, - sel_clicked: bool, - salt: &str, -) -> Option { - let screen = ctx.screen_rect(); - let max_above = (sel_r.top() - screen.top() - 24.0).max(140.0); - let dd_h = 260.0f32.min(max_above); - let dd_r = Rect::from_xywh(sel_r.left(), (sel_r.top() - dd_h - 6.0).max(screen.top() + 12.0), sel_r.width(), dd_h); - ctx.register_blocker(dd_r); - ctx.dl() - .push_shadow(dd_r, 14.0, 20.0, 0.0, Vec2::new(0.0, 6.0), pal.shadow_menu); - ctx.dl() - .push_rect_bordered(dd_r, 14.0, pal.bg_popover, 1.0, pal.border_control); - - let dd_scroll_id = WidgetId::new(salt).with("dd_scroll"); - let dd_inner = dd_r.shrink2(Vec2::new(6.0, 6.0)); - let scroll_y = ctx.begin_scroll_v(dd_scroll_id, dd_inner, 0.0); - let mut dy = dd_inner.top() - scroll_y; - let row_h = 36.0; - let cur_name = active_eq_preset_name(bands, ru); - - for (pi, preset) in EQ_PRESETS.iter().enumerate() { - let pname = preset.name(ru); - let rr = Rect::from_xywh(dd_inner.left(), dy, dd_inner.width() - 8.0, row_h); - let rresp = ctx.interact(WidgetId::new(salt).with("dd_item").with(pi), rr); - let is_cur = pname == cur_name; - if rresp.hovered { - ctx.dl().push_rect(rr, 8.0, pal.surface_hover); - ctx.set_cursor(CursorKind::Pointer); - } - ctx.draw_text_ellipsis( - pname, - TextStyle::medium(13.5, if is_cur { pal.text_bright } else { pal.text_primary }), - Rect::from_xywh(rr.left() + 12.0, rr.top(), rr.width() - 36.0, rr.height()), - TextAlign::Left, - ); - if is_cur { + if enabled { ctx.draw_icon( Icon::CheckXxs, - Rect::from_center_size(Pos2::new(rr.right() - 14.0, rr.center_y()), Vec2::splat(15.0)), - pal.yellow, + Rect::from_center_size(box_r.center(), Vec2::splat(13.0)), + pal.on_yellow, ); } - if rresp.clicked { - *bands = preset.gains; - if pi == 0 { - *preamp = 1.0; - } - *enabled = true; - *changed = true; - *dropdown_open = false; - } - dy += row_h; - } - let total_dd_h = dy - (dd_inner.top() - scroll_y); - ctx.end_scroll_v(dd_scroll_id, pal, total_dd_h, true); - - if ctx.input.clicked_outside(dd_r) && !sel_clicked { - *dropdown_open = false; - if ctx.input.pointer_pos.map_or(false, |p| parent_r.contains(p)) { - ctx.input.consume_pointer_press(); - } - } - Some(dd_r) -} - -/// 1-to-1 Official `ShortcutsModal` (`29c95960ed6ac633.css:137-238`, `settings/page.js:1076-1175`). -pub fn render_shortcuts_modal( - ctx: &mut UiContext, - pal: &YmPalette, - app: &AppState, - anim_t: f32, - actions: &mut Vec, -) { - let i18n = app.i18n(); - let ru = i18n.is_ru(); - let open = app.shortcuts_modal_open; - let alpha = anim_t.clamp(0.0, 1.0); - let screen = ctx.screen_rect(); - let modal_w = (screen.width() - 48.0).clamp(320.0, 430.0); - let modal_h = (screen.height() - 84.0).clamp(320.0, 560.0); - let slide_dy = (1.0 - alpha) * 14.0; - let modal_r = Rect::from_center_size( - Pos2::new(screen.center_x(), screen.center_y() + slide_dy), - Vec2::new(modal_w, modal_h), - ); - - ctx.with_layer(ZLayer::Modal, |ctx| { - if open { - ctx.register_blocker(screen); - } - ctx.dl().push_rect( - screen, - 0.0, - Color::rgba(0, 0, 0, (150.0 * alpha).round() as u8), - ); - ctx.dl().push_shadow( - modal_r, - 16.0, - 32.0, - 0.0, - Vec2::new(0.0, 8.0), - pal.shadow_modal.scale_alpha(alpha), - ); - ctx.dl().push_rect_bordered( - modal_r, - 16.0, - pal.bg_popover.scale_alpha(alpha), - 1.0, - pal.border_subtle.scale_alpha(alpha), - ); - - let hdr_r = Rect::from_xywh(modal_r.left() + 20.0, modal_r.top() + 18.0, modal_w - 40.0, 32.0); ctx.draw_text_ellipsis( - if ru { "Горячие клавиши" } else { "Hot keys" }, - TextStyle::headline(20.0, pal.text_bright.scale_alpha(alpha)), - Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), + if ru { "Включён" } else { "Enabled" }, + TextStyle::medium(12.5, pal.text_primary), + Rect::from_xywh(box_r.right() + 6.0, tog_r.y, 84.0, 24.0), TextAlign::Left, ); + if tog_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if tog_resp.clicked { + enabled = !enabled; + changed = true; + } + if icon_button( ctx, - WidgetId::new("sc_modal_close"), - Rect::from_xywh(hdr_r.right() - 30.0, hdr_r.top() + 1.0, 30.0, 30.0), + WidgetId::new("eq_close_btn"), + Rect::from_xywh(inner.right() - 24.0, inner.y, 24.0, 24.0), Icon::Close, - 15.0, + 12.0, pal.text_secondary, pal.text_bright, pal.surface_hover, false, - i18n.close(), + app.i18n().close(), ) .clicked { - actions.push(AppAction::SetShortcutsModalOpen(false)); + actions.push(AppAction::SetEqPopoverOpen(false)); } - let shortcuts: &[(&str, &str, &[&str])] = &[ - ("Пауза / Воспроизведение", "Play / Pause", &["K"]), - ("Включить или выключить звук", "Mute / Unmute", &["M"]), - ("Прибавить громкость", "Increase volume", &["↑"]), - ("Уменьшить громкость", "Decrease volume", &["↓"]), - ("Нравится", "Like", &["F"]), - ("Не нравится", "Dislike", &["D"]), - ("Следующий трек", "Next track", &["N"]), - ("Предыдущий трек", "Previous track", &["P"]), - ("Перемотка вперёд", "Seek forward", &["→", "L"]), - ("Перемотка назад", "Seek backward", &["←", "J"]), - ("Повтор трека или очереди", "Repeat", &["R"]), - ("Перемешать", "Shuffle", &["S"]), - ("Полноэкранный плеер", "Fullscreen player", &["W"]), - ("Закрыть", "Close", &["Esc"]), - ]; - - let scroll_r = Rect::from_min_max( - Pos2::new(modal_r.left() + 20.0, hdr_r.bottom() + 18.0), - Pos2::new(modal_r.right() - 16.0, modal_r.bottom() - 20.0), - ); - let scroll_id = WidgetId::new("shortcuts_modal_scroll"); - let scroll_y = ctx.begin_scroll_v(scroll_id, scroll_r, 0.0); - let mut y = scroll_r.top() - scroll_y; - let or_word = if ru { "или" } else { "or" }; - let or_w = ctx - .measure_text(or_word, TextStyle::regular(12.5, pal.text_secondary), None) - .x - + 12.0; - - for (label_ru, label_en, keys) in shortcuts { - let row_h = 34.0; - let mut right_x = scroll_r.right() - 6.0; - for (ki, key) in keys.iter().rev().enumerate() { - let kw = (ctx - .measure_text(key, TextStyle::medium(12.5, pal.text_bright), None) - .x - + 16.0) - .max(32.0); - let kr = Rect::from_xywh(right_x - kw, y + 4.0, kw, 26.0); - ctx.dl().push_rect_bordered( - kr, - 6.0, - pal.surface_hover, - 1.0, - pal.border_control, - ); - ctx.draw_text_ellipsis( - key, - TextStyle::medium(12.5, pal.text_bright), - kr, - TextAlign::Center, - ); - right_x = kr.left() - 6.0; - if ki + 1 < keys.len() { - let or_r = Rect::from_xywh(right_x - or_w, y, or_w, row_h); - ctx.draw_text_ellipsis( - or_word, - TextStyle::regular(12.5, pal.text_secondary), - or_r, - TextAlign::Center, - ); - right_x = or_r.left() - 6.0; - } - } - let text_w = (right_x - scroll_r.left() - 10.0).max(100.0); - ctx.draw_text_ellipsis( - if ru { label_ru } else { label_en }, - TextStyle::regular(14.0, pal.text_bright), - Rect::from_xywh(scroll_r.left(), y, text_w, row_h), - TextAlign::Left, + // Preset chips row + let mut px = inner.x; + let py = inner.y + 32.0; + for (pi, preset) in EQ_PRESETS.iter().take(5).enumerate() { + let lbl_w = ctx + .measure_text(preset.name, TextStyle::medium(11.5, pal.text_primary), None) + .x + + 16.0; + let pr = Rect::from_xywh(px, py, lbl_w, 24.0); + let presp = ctx.interact(WidgetId::from_pair("eq_preset", pi), pr); + ctx.dl().push_rect( + pr, + 12.0, + if presp.hovered { pal.chip_hover } else { pal.chip_bg }, ); - y += row_h + 4.0; + ctx.draw_text_ellipsis( + preset.name, + TextStyle::medium(11.5, pal.text_primary), + pr, + TextAlign::Center, + ); + if presp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if presp.clicked { + enabled = true; + bands = preset.gains; + changed = true; + } + px += lbl_w + 6.0; } - let total_h = y - (scroll_r.top() - scroll_y); - ctx.end_scroll_v(scroll_id, pal, total_h, true); - if open && ctx.input.consume_clicked_outside(modal_r) { - actions.push(AppAction::SetShortcutsModalOpen(false)); + // 10 vertical band sliders + let band_top = py + 34.0; + let band_h = (inner.bottom() - band_top - 22.0).max(80.0); + let col_w = inner.w / 10.0; + for i in 0..10 { + let bx = inner.x + i as f32 * col_w; + let sr = Rect::from_xywh(bx + 4.0, band_top, col_w - 8.0, band_h); + let norm = ((bands[i] + 12.0) / 24.0).clamp(0.0, 1.0); + let sresp = ym_vertical_slider( + ctx, + pal, + WidgetId::from_pair("eq_band", i), + sr, + norm, + false, + if enabled { pal.yellow } else { pal.text_primary }, + ); + if let Some(v) = sresp.value { + bands[i] = (v * 24.0 - 12.0).clamp(-12.0, 12.0); + enabled = true; + changed = true; + } + ctx.draw_text_ellipsis( + EQ_LABELS[i], + TextStyle::bold(10.0, pal.text_secondary), + Rect::from_xywh(bx, band_top + band_h + 4.0, col_w, 16.0), + TextAlign::Center, + ); + } + + if ctx.input.clicked_outside(pop_r) { + actions.push(AppAction::SetEqPopoverOpen(false)); } }); + + if changed { + actions.push(AppAction::UpdateEq { enabled, bands }); + } } // ============================================================================= @@ -4582,20 +3594,13 @@ pub fn render_shortcuts_modal( // ============================================================================= pub fn render_toast(ctx: &mut UiContext, pal: &YmPalette, msg: &str) { - render_toast_with_offset(ctx, pal, msg, 0.0); -} - -pub fn render_toast_with_offset(ctx: &mut UiContext, pal: &YmPalette, msg: &str, extra_bottom_offset: f32) { let screen = ctx.screen_rect(); let max_w = (screen.width() - 64.0).min(520.0); let text_sz = ctx.measure_text(msg, TextStyle::medium(13.5, pal.text_bright), Some(max_w - 32.0)); let w = (text_sz.x + 36.0).clamp(160.0, max_w); let h = (text_sz.y + 20.0).max(40.0); let rect = Rect::from_center_size( - Pos2::new( - screen.center_x(), - screen.bottom() - PLAYER_BAR_HEIGHT - 44.0 - extra_bottom_offset, - ), + Pos2::new(screen.center_x(), screen.bottom() - PLAYER_BAR_HEIGHT - 44.0), Vec2::new(w, h), ); @@ -4613,508 +3618,6 @@ pub fn render_toast_with_offset(ctx: &mut UiContext, pal: &YmPalette, msg: &str, }); } -/// 1-to-1 Official `NotificationUpdate` (`28bcd8bd8493d95a.css:1-15` + `5eace9426adf24a8.css:12-23`): -/// Frosted floating bottom bar with available version text, `"Что нового?"` button, -/// yellow `"Обновить"` CTA button (`min-width: 112px`), and dismiss `×`. -pub fn render_update_notification( - ctx: &mut UiContext, - pal: &YmPalette, - app: &AppState, - upd: &UpdateInfo, - actions: &mut Vec, -) { - let i18n = app.i18n(); - let anim_t = if app.fixed_vibe_time.is_some() { - 1.0 - } else { - let raw = ctx.animate_bool(WidgetId::new("ym_update_notif_anim"), true, 0.24); - let u = 1.0 - raw; - 1.0 - u * u * u - }; - let screen = ctx.screen_rect(); - let bottom_margin = if matches!(app.route, Route::MyVibe) { - 26.0 - } else { - PLAYER_BAR_HEIGHT + 22.0 - }; - let bar_w = (screen.width() - 64.0).clamp(430.0, 560.0); - let bar_h = 54.0; - let slide_dy = (1.0 - anim_t) * 26.0; - let rect = Rect::from_xywh( - (screen.center_x() - bar_w * 0.5).round(), - (screen.bottom() - bottom_margin - bar_h + slide_dy).round(), - bar_w, - bar_h, - ); - - ctx.with_layer(ZLayer::Titlebar, |ctx| { - ctx.register_blocker(rect); - ctx.dl() - .push_shadow(rect, 16.0, 22.0, 0.0, Vec2::new(0.0, 4.0), pal.shadow_menu); - ctx.dl().push_backdrop_blur( - rect, - 16.0, - 2.5, - pal.bg_popover.with_alpha(235), - 1.0, - pal.border_control, - ); - - // Left: Yellow status dot + `"Доступна версия vX.Y.Z"` - let dot_pos = Pos2::new(rect.left() + 20.0, rect.center_y()); - ctx.dl().push_circle(dot_pos, 4.0, pal.yellow); - - let close_sz = 28.0; - let close_r = Rect::from_xywh( - rect.right() - close_sz - 10.0, - rect.center_y() - close_sz * 0.5, - close_sz, - close_sz, - ); - let upd_lbl = i18n.update_btn(); - let on_yellow = Color::rgb(0x19, 0x19, 0x19); - let upd_txt_w = ctx - .measure_text(upd_lbl, TextStyle::bold(13.5, on_yellow), None) - .x; - let upd_w = (upd_txt_w + 32.0).max(114.0).ceil(); - let upd_r = Rect::from_xywh( - close_r.left() - upd_w - 8.0, - rect.center_y() - 18.0, - upd_w, - 36.0, - ); - let wn_lbl = i18n.whats_new(); - let wn_txt_w = ctx - .measure_text(wn_lbl, TextStyle::medium(12.5, pal.text_primary), None) - .x; - let wn_w = (wn_txt_w + 22.0).max(88.0).ceil(); - let wn_r = Rect::from_xywh( - upd_r.left() - wn_w - 8.0, - rect.center_y() - 16.0, - wn_w, - 32.0, - ); - - let text_x = rect.left() + 34.0; - let text_w = (wn_r.left() - text_x - 10.0).max(80.0); - let msg = i18n.update_available_banner(&upd.version); - ctx.draw_text_ellipsis( - &msg, - TextStyle::medium(14.0, pal.text_bright), - Rect::from_xywh(text_x, rect.top(), text_w, rect.height()), - TextAlign::Left, - ); - - // Secondary "Что нового?" pill - let wn_resp = ctx.interact(WidgetId::new("upd_notif_changelog"), wn_r); - if wn_resp.hovered { - ctx.dl().push_rect(wn_r, 16.0, pal.surface_hover); - ctx.set_cursor(CursorKind::Pointer); - } else { - ctx.dl().push_rect(wn_r, 16.0, pal.surface_secondary); - } - ctx.draw_text_ellipsis( - wn_lbl, - TextStyle::medium(12.5, pal.text_primary), - wn_r, - TextAlign::Center, - ); - if wn_resp.clicked { - actions.push(AppAction::OpenReleaseNotesModal); - } - - // Primary yellow "Обновить" button (`min-width: 7.875rem`) - let upd_resp = ctx.interact(WidgetId::new("upd_notif_install"), upd_r); - ctx.dl().push_rect( - upd_r, - 18.0, - if upd_resp.hovered { - pal.yellow_hover - } else { - pal.yellow - }, - ); - ctx.draw_text_ellipsis( - upd_lbl, - TextStyle::bold(13.5, on_yellow), - upd_r, - TextAlign::Center, - ); - if upd_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if upd_resp.clicked { - actions.push(AppAction::InstallUpdate); - } - - // Dismiss × button - if icon_button( - ctx, - WidgetId::new("upd_notif_close"), - close_r, - Icon::Close, - 14.0, - pal.text_secondary, - pal.text_bright, - pal.surface_hover, - false, - "", - ) - .clicked - { - actions.push(AppAction::DismissUpdateNotification); - } - }); -} - -/// 1-to-1 Official `ReleaseNotesModal` (`28bcd8bd8493d95a.css:16-100`, `7956-fd3a458349d8bd97.js:490-525`). -pub fn render_release_notes_modal( - ctx: &mut UiContext, - pal: &YmPalette, - app: &AppState, - anim_t: f32, - actions: &mut Vec, -) { - let i18n = app.i18n(); - let ru = i18n.is_ru(); - let open = app.release_notes_modal_open; - let alpha = anim_t.clamp(0.0, 1.0); - let screen = ctx.screen_rect(); - let modal_w = (screen.width() - 48.0).clamp(320.0, 460.0); - let modal_h = (screen.height() - 84.0).clamp(320.0, 500.0); - let slide_dy = (1.0 - alpha) * 14.0; - let modal_r = Rect::from_center_size( - Pos2::new(screen.center_x(), screen.center_y() + slide_dy), - Vec2::new(modal_w, modal_h), - ); - - ctx.with_layer(ZLayer::Modal, |ctx| { - if open { - ctx.register_blocker(screen); - } - ctx.dl().push_rect( - screen, - 0.0, - Color::rgba(0, 0, 0, (150.0 * alpha).round() as u8), - ); - ctx.dl().push_shadow( - modal_r, - 16.0, - 32.0, - 0.0, - Vec2::new(0.0, 8.0), - pal.shadow_modal.scale_alpha(alpha), - ); - ctx.dl().push_rect_bordered( - modal_r, - 16.0, - pal.bg_popover.scale_alpha(alpha), - 1.0, - pal.border_subtle.scale_alpha(alpha), - ); - - // Header (`padding: 16px`, title + circular close ×) - let hdr_r = Rect::from_xywh(modal_r.left() + 20.0, modal_r.top() + 14.0, modal_w - 40.0, 34.0); - ctx.draw_text_ellipsis( - i18n.whats_new(), - TextStyle::headline(20.0, pal.text_bright.scale_alpha(alpha)), - Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), - TextAlign::Left, - ); - let close_r = Rect::from_xywh(hdr_r.right() - 32.0, hdr_r.top() + 1.0, 32.0, 32.0); - if open - && icon_button( - ctx, - WidgetId::new("rn_modal_close"), - close_r, - Icon::Close, - 16.0, - pal.text_secondary, - pal.text_bright, - pal.surface_hover, - false, - "", - ) - .clicked - { - actions.push(AppAction::CloseReleaseNotesModal); - } - - let mut content_top = hdr_r.bottom() + 10.0; - - // Optional update banner inside modal if newer version is available - if let Some(ref upd) = app.available_update { - let banner_r = Rect::from_xywh(modal_r.left() + 20.0, content_top, modal_w - 40.0, 48.0); - ctx.dl().push_rect_bordered( - banner_r, - 12.0, - pal.surface_secondary, - 1.0, - pal.yellow.with_alpha(120), - ); - let on_yellow = Color::rgb(0x19, 0x19, 0x19); - let btn_lbl = i18n.update_btn(); - let btn_w = (ctx - .measure_text(btn_lbl, TextStyle::bold(13.0, on_yellow), None) - .x - + 24.0) - .max(94.0) - .ceil(); - let btn_r = Rect::from_xywh( - banner_r.right() - btn_w - 8.0, - banner_r.center_y() - 16.0, - btn_w, - 32.0, - ); - let upd_resp = ctx.interact(WidgetId::new("rn_modal_upd_btn"), btn_r); - ctx.dl().push_rect( - btn_r, - 16.0, - if upd_resp.hovered { - pal.yellow_hover - } else { - pal.yellow - }, - ); - ctx.draw_text_ellipsis( - btn_lbl, - TextStyle::bold(13.0, on_yellow), - btn_r, - TextAlign::Center, - ); - if upd_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if upd_resp.clicked { - actions.push(AppAction::InstallUpdate); - } - ctx.draw_text_ellipsis( - &i18n.update_available_banner(&upd.version), - TextStyle::bold(13.5, pal.text_bright), - Rect::from_xywh( - banner_r.left() + 14.0, - banner_r.top(), - (btn_r.left() - banner_r.left() - 22.0).max(60.0), - banner_r.height(), - ), - TextAlign::Left, - ); - content_top = banner_r.bottom() + 12.0; - } - - // Scrollable list of release notes - let scroll_r = Rect::from_min_max( - Pos2::new(modal_r.left() + 20.0, content_top), - Pos2::new(modal_r.right() - 12.0, modal_r.bottom() - 16.0), - ); - let scroll_id = WidgetId::new("release_notes_scroll"); - let scroll_y = ctx.begin_scroll_v(scroll_id, scroll_r, 0.0); - let body_w = (scroll_r.width() - 16.0).max(160.0); - let mut y = scroll_r.top() - scroll_y; - - if app.releases.is_empty() { - let empty_msg = if ru { - "Список изменений пуст" - } else { - "No release notes available" - }; - ctx.draw_text_ellipsis( - empty_msg, - TextStyle::regular(13.5, pal.text_secondary), - Rect::from_xywh(scroll_r.left(), y + 12.0, body_w, 22.0), - TextAlign::Left, - ); - y += 40.0; - } else { - for (idx, entry) in app.releases.iter().enumerate() { - // Version heading + badge + date - let ver_text = if entry.name.is_empty() { - format!("v{}", entry.version) - } else { - entry.name.clone() - }; - let ver_style = TextStyle::bold(15.5, pal.text_bright); - let ver_w = ctx.measure_text(&ver_text, ver_style, None).x.min(body_w * 0.65); - ctx.draw_text_ellipsis( - &ver_text, - ver_style, - Rect::from_xywh(scroll_r.left(), y, ver_w + 4.0, 22.0), - TextAlign::Left, - ); - - let is_current = entry.version == APP_VERSION; - let is_newer = is_newer_version(&entry.version, APP_VERSION); - if is_current || is_newer { - let badge_txt = if is_newer { - i18n.new_version_badge() - } else { - i18n.current_version_badge() - }; - let badge_col = if is_newer { Color::rgb(0x19, 0x19, 0x19) } else { pal.text_primary }; - let badge_bg = if is_newer { pal.yellow } else { pal.surface_secondary }; - let bw = ctx - .measure_text(badge_txt, TextStyle::bold(11.0, badge_col), None) - .x - + 14.0; - let br = Rect::from_xywh(scroll_r.left() + ver_w + 10.0, y + 2.0, bw, 18.0); - ctx.dl().push_rect(br, 9.0, badge_bg); - ctx.draw_text_ellipsis( - badge_txt, - TextStyle::bold(11.0, badge_col), - br, - TextAlign::Center, - ); - } - - if !entry.date.is_empty() { - ctx.draw_text_ellipsis( - &entry.date, - TextStyle::regular(12.5, pal.text_secondary), - Rect::from_xywh(scroll_r.left(), y + 1.0, body_w, 20.0), - TextAlign::Right, - ); - } - y += 28.0; - - // Markdown release notes lines - for raw_line in entry.body.lines() { - let line = raw_line.trim(); - if line.is_empty() || line == "---" || line == "***" { - continue; - } - if let Some(heading) = line - .strip_prefix("### ") - .or_else(|| line.strip_prefix("## ")) - .or_else(|| line.strip_prefix("# ")) - { - let clean = heading.trim(); - let h_style = TextStyle::bold(13.5, pal.text_bright); - let sz = ctx.measure_text(clean, h_style, Some(body_w)); - let lh = (sz.y + 4.0).max(20.0); - ctx.draw_text_wrapped( - clean, - h_style, - Rect::from_xywh(scroll_r.left(), y, body_w, lh), - None, - TextAlign::Left, - ); - y += lh + 4.0; - } else if let Some(bullet) = line - .strip_prefix("- ") - .or_else(|| line.strip_prefix("* ")) - { - let item_x = scroll_r.left() + 14.0; - let item_w = (body_w - 14.0).max(100.0); - ctx.dl().push_circle(Pos2::new(scroll_r.left() + 5.0, y + 9.0), 2.0, pal.text_secondary); - let spans = parse_release_note_spans(bullet.trim(), pal); - let plain: String = spans.iter().map(|s| s.text).collect(); - let sz = ctx.measure_text( - &plain, - TextStyle::regular(13.5, pal.text_primary), - Some(item_w), - ); - let lh = (sz.y + 4.0).max(20.0); - ctx.draw_rich_text( - &spans, - Rect::from_xywh(item_x, y, item_w, lh), - None, - TextAlign::Left, - ); - y += lh + 4.0; - } else { - let spans = parse_release_note_spans(line, pal); - let plain: String = spans.iter().map(|s| s.text).collect(); - let sz = ctx.measure_text( - &plain, - TextStyle::regular(13.5, pal.text_primary), - Some(body_w), - ); - let lh = (sz.y + 4.0).max(20.0); - ctx.draw_rich_text( - &spans, - Rect::from_xywh(scroll_r.left(), y, body_w, lh), - None, - TextAlign::Left, - ); - y += lh + 4.0; - } - } - - if idx + 1 < app.releases.len() { - y += 8.0; - ctx.dl().push_rect( - Rect::from_xywh(scroll_r.left(), y, body_w, 1.0), - 0.0, - pal.border_subtle, - ); - y += 14.0; - } else { - y += 8.0; - } - } - } - - let total_h = y - (scroll_r.top() - scroll_y); - ctx.end_scroll_v(scroll_id, pal, total_h, true); - - if open && ctx.input.consume_clicked_outside(modal_r) { - actions.push(AppAction::CloseReleaseNotesModal); - } - }); -} - -fn parse_release_note_spans<'a>(line: &'a str, pal: &YmPalette) -> Vec> { - let mut spans = Vec::new(); - let mut rest = line; - let code_col = if pal.is_dark { pal.yellow } else { pal.outline_selected }; - while !rest.is_empty() { - let next_bold = rest.find("**"); - let next_code = rest.find('`'); - let next = match (next_bold, next_code) { - (Some(b), Some(c)) => Some((b <= c, b.min(c))), - (Some(b), None) => Some((true, b)), - (None, Some(c)) => Some((false, c)), - (None, None) => None, - }; - match next { - None => { - spans.push(RichSpan::new(rest, TextStyle::regular(13.5, pal.text_primary))); - break; - } - Some((is_bold, idx)) => { - if idx > 0 { - spans.push(RichSpan::new( - &rest[..idx], - TextStyle::regular(13.5, pal.text_primary), - )); - } - let delim = if is_bold { "**" } else { "`" }; - let after = &rest[idx + delim.len()..]; - if let Some(end) = after.find(delim) { - let inner = &after[..end]; - let style = if is_bold { - TextStyle::bold(13.5, pal.text_bright) - } else { - TextStyle::medium(13.0, code_col) - }; - spans.push(RichSpan::new(inner, style)); - rest = &after[end + delim.len()..]; - } else { - spans.push(RichSpan::new( - &rest[idx..], - TextStyle::regular(13.5, pal.text_primary), - )); - break; - } - } - } - } - if spans.is_empty() { - spans.push(RichSpan::new(line, TextStyle::regular(13.5, pal.text_primary))); - } - spans -} - // ============================================================================= // 8. Theme-Aware Streaming Animated Splash Screen (`splash_dark.webp` / `splash_light.webp`) // ============================================================================= @@ -5138,7 +3641,7 @@ impl SplashPlayer { /// Spawns a bounded 4-frame background WebP decoder selecting `splash_dark.webp` on `#000` /// or `splash_light.webp` on `#FFF` to match official Yandex Music 5.129.0 SplashScreen 1-to-1! pub fn spawn(is_dark: bool) -> Self { - let (tx, rx) = crossbeam_channel::bounded::(1); + let (tx, rx) = crossbeam_channel::bounded::(4); std::thread::Builder::new() .name("ym-splash-decode".into()) .spawn(move || { diff --git a/src/views/player_bar.rs b/src/views/player_bar.rs index 33f4a10..33f65ed 100644 --- a/src/views/player_bar.rs +++ b/src/views/player_bar.rs @@ -1,6 +1,5 @@ use crate::api::models::format_ms; use crate::app::{AppAction, AppState, RepeatMode, Route}; -use crate::config::PlayerThumbStyle; use crate::covers::CoverCache; use crate::engine::widgets::{draw_cover_art, separated_artists, ym_volume_capsule}; use crate::engine::{ @@ -9,7 +8,6 @@ use crate::engine::{ }; use crate::icons::Icon; use crate::views::overlays::ShellUiState; -use crate::views::player_thumbs::render_player_bar_companion; /// Exact Yandex Music Desktop 5.129.0 Bottom PlayerBar (`PlayerBarDesktopWithBackgroundProgressBar`): /// - Exact 80px height, `hsl(h, s%, 20%)` track-derived bg (or `pal.bg_player`) in BOTH themes @@ -88,13 +86,11 @@ pub fn render_player_bar( ctx.dl().push_rect(rect, 12.0, base_bg); - // 2. Top-edge progress bar (Standard hover yellow bar OR live animated Duck/Car/Claudik/Antigravity/Ferris/Nyan companion!) - let thumb_style = app.config.player_thumb; - let is_custom_thumb = thumb_style != PlayerThumbStyle::Standard; - let bar_hover_zone = rect.expand2(Vec2::new(0.0, if is_custom_thumb { 20.0 } else { 6.0 })); + // 2. Top-edge 4px yellow progress bar + 12px thumb + hover timecode pills + let bar_hover_zone = rect.expand2(Vec2::new(0.0, 6.0)); let bar_hovered = ctx.is_hovered(bar_hover_zone); let scrub_zone = Rect::from_min_max( - Pos2::new(rect.left() + 8.0, rect.top() - if is_custom_thumb { 22.0 } else { 6.0 }), + Pos2::new(rect.left() + 8.0, rect.top() - 6.0), Pos2::new(rect.right() - 8.0, rect.top() + 12.0), ); let scrub_resp = ctx.interact(WidgetId::new("pb_top_scrub"), scrub_zone); @@ -140,85 +136,65 @@ pub fn render_player_bar( scrub_resp.hovered || scrub_resp.pressed || scrub_resp.dragged || shell.pb_scrub_frac.is_some(); let hover_t = ctx.animate_bool(WidgetId::new("pb_scrub_hover_anim"), bar_hovered || scrub_active, 0.15); - // Never draw PlayerBar's `ZLayer::Popover` progress bar/companion on top of FullscreenPlayer (`ZLayer::Drawer`)! - if !app.fullscreen_open && (is_custom_thumb || hover_t > 0.01) { + if hover_t > 0.01 { let display_frac = display_progress; ctx.with_layer(ZLayer::Popover, |ctx| { let bar_y = rect.top() + 2.0; - if is_custom_thumb { - let anim_time = app.fixed_vibe_time.unwrap_or(ctx.input.time as f32); - render_player_bar_companion( - ctx, - pal, - thumb_style, - scrub_zone.left(), - scrub_zone.right(), - bar_y, - display_frac, - is_playing, - anim_time, - ); - } else { - let bar_r = Rect::from_min_max( - Pos2::new(scrub_zone.left(), bar_y - 2.0), - Pos2::new(scrub_zone.right(), bar_y + 2.0), - ); - ctx.dl() - .push_rect(bar_r, 2.0, css_rgba(255, 255, 255, (38.0 * hover_t).round() as u8)); + let bar_r = Rect::from_min_max( + Pos2::new(scrub_zone.left(), bar_y - 2.0), + Pos2::new(scrub_zone.right(), bar_y + 2.0), + ); + ctx.dl() + .push_rect(bar_r, 2.0, css_rgba(255, 255, 255, (38.0 * hover_t).round() as u8)); - let fill_x = scrub_zone.left() + scrub_zone.width() * display_frac; - let fill_r = Rect::from_min_max(bar_r.min(), Pos2::new(fill_x, bar_r.bottom())); - let yellow_a = pal.yellow.with_alpha_f32(hover_t); - ctx.dl().push_rect(fill_r, 2.0, yellow_a); + let fill_x = scrub_zone.left() + scrub_zone.width() * display_frac; + let fill_r = Rect::from_min_max(bar_r.min(), Pos2::new(fill_x, bar_r.bottom())); + let yellow_a = pal.yellow.with_alpha_f32(hover_t); + ctx.dl().push_rect(fill_r, 2.0, yellow_a); - // Exact 12px circular yellow thumb (`radius = 6px`) - ctx.dl() - .push_circle(Pos2::new(fill_x, bar_y), 6.0 * hover_t, yellow_a); - } + // Exact 12px circular yellow thumb (`radius = 6px`) + ctx.dl() + .push_circle(Pos2::new(fill_x, bar_y), 6.0 * hover_t, yellow_a); - if hover_t > 0.01 { - // Left & right timecode pills (lifted cleanly above custom companions) - let cur_ms = (display_frac * duration_ms as f32) as u64; - let tc_bg = css_rgba(20, 20, 20, (215.0 * hover_t).round() as u8); - let tc_fg = Color::rgb(0xE6, 0xE6, 0xE6).with_alpha_f32(hover_t); - let tc_y = rect.top() - if is_custom_thumb { 36.0 } else { 24.0 }; + // Left & right timecode pills + let cur_ms = (display_frac * duration_ms as f32) as u64; + let tc_bg = css_rgba(20, 20, 20, (215.0 * hover_t).round() as u8); + let tc_fg = Color::rgb(0xE6, 0xE6, 0xE6).with_alpha_f32(hover_t); - let left_tc_r = Rect::from_xywh(rect.left() + 8.0, tc_y, 44.0, 18.0); - ctx.dl().push_rect(left_tc_r, 9.0, tc_bg); - ctx.draw_text_ellipsis( - &format_ms(cur_ms), - TextStyle::medium(11.0, tc_fg), - left_tc_r, - TextAlign::Center, - ); + let left_tc_r = Rect::from_xywh(rect.left() + 8.0, rect.top() - 24.0, 44.0, 18.0); + ctx.dl().push_rect(left_tc_r, 9.0, tc_bg); + ctx.draw_text_ellipsis( + &format_ms(cur_ms), + TextStyle::medium(11.0, tc_fg), + left_tc_r, + TextAlign::Center, + ); - let right_tc_r = Rect::from_xywh(rect.right() - 52.0, tc_y, 44.0, 18.0); - ctx.dl().push_rect(right_tc_r, 9.0, tc_bg); - ctx.draw_text_ellipsis( - &format_ms(duration_ms), - TextStyle::medium(11.0, tc_fg), - right_tc_r, - TextAlign::Center, - ); + let right_tc_r = Rect::from_xywh(rect.right() - 52.0, rect.top() - 24.0, 44.0, 18.0); + ctx.dl().push_rect(right_tc_r, 9.0, tc_bg); + ctx.draw_text_ellipsis( + &format_ms(duration_ms), + TextStyle::medium(11.0, tc_fg), + right_tc_r, + TextAlign::Center, + ); - // Hover seek cursor timecode tooltip - if scrub_active { - ctx.set_cursor(CursorKind::Pointer); - if let Some(pos) = ctx.input.pointer_pos { - let frac = ((pos.x - scrub_zone.left()) / scrub_zone.width().max(1.0)).clamp(0.0, 1.0); - let hover_ms = (frac * duration_ms as f32) as u64; - let tip_x = pos.x.clamp(rect.left() + 78.0, (rect.right() - 78.0).max(rect.left() + 78.0)); - let tip_y = rect.top() - if is_custom_thumb { 32.0 } else { 18.0 }; - let tip_r = Rect::from_center_size(Pos2::new(tip_x, tip_y), Vec2::new(50.0, 22.0)); - ctx.dl().push_rect(tip_r, 11.0, css_rgba(20, 20, 20, 230)); - ctx.draw_text_ellipsis( - &format_ms(hover_ms), - TextStyle::medium(12.0, Color::WHITE), - tip_r, - TextAlign::Center, - ); - } + // Hover seek cursor timecode tooltip + if scrub_active { + ctx.set_cursor(CursorKind::Pointer); + if let Some(pos) = ctx.input.pointer_pos { + let frac = ((pos.x - scrub_zone.left()) / scrub_zone.width().max(1.0)).clamp(0.0, 1.0); + let hover_ms = (frac * duration_ms as f32) as u64; + let tip_x = pos.x.clamp(rect.left() + 78.0, (rect.right() - 78.0).max(rect.left() + 78.0)); + let tip_r = Rect::from_center_size(Pos2::new(tip_x, rect.top() - 18.0), Vec2::new(50.0, 22.0)); + ctx.dl().push_rect(tip_r, 11.0, css_rgba(20, 20, 20, 230)); + ctx.draw_text_ellipsis( + &format_ms(hover_ms), + TextStyle::medium(12.0, Color::WHITE), + tip_r, + TextAlign::Center, + ); } } }); @@ -525,7 +501,9 @@ pub fn render_player_bar( ctx.draw_icon( if is_liked { Icon::Liked } else { Icon::Like }, Rect::from_center_size(like_r.center(), Vec2::splat(24.0)), - if is_liked || like_resp.hovered { + if is_liked { + pal.accent_coral + } else if like_resp.hovered { fg_bright } else { fg_muted diff --git a/src/views/player_thumbs.rs b/src/views/player_thumbs.rs deleted file mode 100644 index ac8aa37..0000000 --- a/src/views/player_thumbs.rs +++ /dev/null @@ -1,385 +0,0 @@ -use crate::config::PlayerThumbStyle; -use crate::engine::theme::YmPalette; -use crate::engine::types::{Color, Pos2, Rect, Vec2}; -use crate::engine::{css_rgba, UiContext}; -use crate::icons::Icon; - -/// Draws the progress trail + live animated companion on the top edge of `PlayerBar`. -/// Called only when `style != PlayerThumbStyle::Standard`. -#[allow(clippy::too_many_arguments)] -pub fn render_player_bar_companion( - ctx: &mut UiContext, - pal: &YmPalette, - style: PlayerThumbStyle, - bar_left: f32, - bar_right: f32, - bar_y: f32, - progress: f32, - playing: bool, - time: f32, -) { - let frac = progress.clamp(0.0, 1.0); - let track_w = (bar_right - bar_left).max(1.0); - let fill_x = bar_left + track_w * frac; - let anim_t = if playing { time } else { 0.0 }; - - // Subtle base track along top edge - let track_r = Rect::from_xywh(bar_left, bar_y - 1.5, track_w, 3.0); - ctx.dl().push_rect(track_r, 1.5, css_rgba(255, 255, 255, 34)); - - // Themed progress trail behind the companion - let fill_w = (fill_x - bar_left).max(0.0); - if fill_w > 1.0 { - match style { - PlayerThumbStyle::Standard => {} - PlayerThumbStyle::Duck => { - ctx.dl() - .push_rect(Rect::from_xywh(bar_left, bar_y - 1.5, fill_w, 3.0), 1.5, pal.yellow); - } - PlayerThumbStyle::Car => { - ctx.dl().push_rect( - Rect::from_xywh(bar_left, bar_y - 1.5, fill_w, 3.0), - 1.5, - Color::rgb(0xE8, 0x22, 0x38), - ); - // Tiny drifting exhaust puffs while driving - if playing && fill_w > 48.0 { - for k in 0..3 { - let phase = ((anim_t * 2.4 + k as f32 * 0.33) % 1.0).clamp(0.0, 1.0); - let px = fill_x - 30.0 - phase * 24.0; - let py = bar_y - 5.0 - phase * 6.0; - let a = ((1.0 - phase) * 90.0).round() as u8; - if px > bar_left { - ctx.dl() - .push_circle(Pos2::new(px, py), 2.0 + phase * 2.5, css_rgba(220, 224, 232, a)); - } - } - } - } - PlayerThumbStyle::Claudik => { - ctx.dl().push_rect( - Rect::from_xywh(bar_left, bar_y - 1.5, fill_w, 3.0), - 1.5, - Color::rgb(0xD9, 0x77, 0x57), - ); - } - PlayerThumbStyle::Antigravity => { - ctx.dl().push_gradient_rect( - Rect::from_xywh(bar_left, bar_y - 1.5, fill_w, 3.0), - 1.5, - Color::rgb(0x9B, 0x84, 0xEC), - Color::rgb(0x52, 0xB6, 0xFF), - Vec2::new(1.0, 0.0), - ); - // Twinkling cosmic star dust trailing behind Antigravity - let count = ((fill_w / 22.0) as usize).min(6); - for k in 0..count { - let phase = ((anim_t * 1.6 + k as f32 * 0.27) % 1.0).clamp(0.0, 1.0); - let sx = fill_x - 16.0 - k as f32 * 18.0 - phase * 10.0; - let sy = bar_y - 6.0 - ((k as f32 * 1.9 + anim_t * 3.0).sin() * 4.5).abs(); - let twinkle = 0.35 + 0.65 * ((anim_t * 5.0 + k as f32 * 1.7).sin() * 0.5 + 0.5); - if sx > bar_left + 4.0 { - let col = if k % 2 == 0 { - Color::rgb(0x9B, 0x84, 0xEC).scale_alpha(twinkle * 0.85) - } else { - Color::rgb(0x6C, 0xD4, 0xFF).scale_alpha(twinkle * 0.85) - }; - ctx.dl().push_rect(Rect::from_xywh(sx.round(), sy.round(), 2.0, 2.0), 0.0, col); - } - } - } - PlayerThumbStyle::Ferris => { - ctx.dl().push_rect( - Rect::from_xywh(bar_left, bar_y - 1.5, fill_w, 3.0), - 1.5, - Color::rgb(0xF7, 0x4C, 0x00), - ); - } - PlayerThumbStyle::Nyan => { - // Classic 6-stripe waving pixel rainbow trail! - let stripes = [ - Color::rgb(0xFF, 0x26, 0x26), - Color::rgb(0xFF, 0x99, 0x00), - Color::rgb(0xFF, 0xEE, 0x00), - Color::rgb(0x33, 0xDD, 0x33), - Color::rgb(0x1E, 0x9E, 0xFF), - Color::rgb(0x7A, 0x44, 0xFF), - ]; - let seg_w = 10.0f32; - let max_trail = (fill_w - 6.0).max(0.0); - let num_segs = (max_trail / seg_w).ceil() as usize; - let wave_step = (anim_t * 8.0).floor() as i32; - for s in 0..num_segs { - let sx = bar_left + s as f32 * seg_w; - let sw = (fill_x - 6.0 - sx).min(seg_w); - if sw <= 0.5 { - break; - } - let dy = if ((s as i32 + wave_step) & 1) == 0 { -1.0 } else { 1.0 }; - for (ci, &col) in stripes.iter().enumerate() { - let sy = bar_y - 11.0 + ci as f32 * 2.0 + dy; - ctx.dl() - .push_rect(Rect::from_xywh(sx, sy, sw + 0.5, 2.0), 0.0, col); - } - } - } - } - } - - // Draw the companion anchored cleanly at `(fill_x, bar_y)` - match style { - PlayerThumbStyle::Standard => {} - PlayerThumbStyle::Duck => { - let bob = if playing { (anim_t * 9.0).sin().abs() * -2.0 } else { 0.0 }; - let sz = 32.0; - let r = Rect::from_xywh(fill_x - sz * 0.5, bar_y - sz + 3.0 + bob, sz, sz); - ctx.draw_icon(Icon::ThumbDuck, r, Color::WHITE); - } - PlayerThumbStyle::Car => { - let vib = if playing { (anim_t * 28.0).sin() * 0.6 } else { 0.0 }; - let w = 68.0; - let h = 21.0; - let r = Rect::from_xywh(fill_x - w * 0.52, bar_y - h + 2.0 + vib, w, h); - // Warm headlight beam ahead of the car when playing - if playing && r.right() < bar_right { - let beam_w = (bar_right - r.right()).min(26.0); - ctx.dl().push_gradient_rect( - Rect::from_xywh(r.right() - 2.0, bar_y - 10.0 + vib, beam_w, 8.0), - 2.0, - css_rgba(255, 240, 160, 95), - css_rgba(255, 240, 160, 0), - Vec2::new(1.0, 0.0), - ); - } - ctx.draw_icon(Icon::ThumbCar, r, Color::WHITE); - } - PlayerThumbStyle::Claudik => { - let step = if playing { ((anim_t * 7.0).floor() as u32) & 1 } else { 0 }; - let bob = if playing && step == 1 { -1.5 } else { 0.0 }; - draw_claudik_sprite(ctx, Pos2::new(fill_x, bar_y + bob), 2.5, step == 1); - } - PlayerThumbStyle::Antigravity => { - let hover = if playing { (anim_t * 4.5).sin() * 2.2 - 3.5 } else { -2.5 }; - draw_antigravity_sprite(ctx, Pos2::new(fill_x, bar_y + hover), 2.5, anim_t, true); - } - PlayerThumbStyle::Ferris => { - let step = if playing { ((anim_t * 8.0).floor() as u32) & 1 } else { 0 }; - let bob = if playing && step == 1 { -1.0 } else { 0.0 }; - draw_ferris_sprite(ctx, Pos2::new(fill_x, bar_y + bob), 2.2, step == 1); - } - PlayerThumbStyle::Nyan => { - let step = if playing { ((anim_t * 9.0).floor() as u32) & 1 } else { 0 }; - let bob = if playing && step == 1 { -1.5 } else { 0.0 }; - draw_nyan_sprite(ctx, Pos2::new(fill_x, bar_y + bob), 2.0, step == 1); - } - } -} - -/// Draws the centered preview inside Settings -> «Вид плеера» card (`preview_r`). -pub fn render_thumb_preview( - ctx: &mut UiContext, - pal: &YmPalette, - style: PlayerThumbStyle, - preview_r: Rect, - time: f32, -) { - let cx = preview_r.center_x(); - let cy = preview_r.center_y(); - match style { - PlayerThumbStyle::Standard => { - let bar_w = 60.0; - ctx.dl().push_rect( - Rect::from_center_size(Pos2::new(cx, cy), Vec2::new(bar_w, 5.0)), - 2.5, - pal.border_control, - ); - ctx.dl().push_rect( - Rect::from_xywh(cx - bar_w * 0.5, cy - 2.5, bar_w * 0.52, 5.0), - 2.5, - pal.yellow, - ); - ctx.dl().push_circle(Pos2::new(cx, cy), 10.0, pal.yellow); - } - PlayerThumbStyle::Duck => { - ctx.draw_icon( - Icon::ThumbDuck, - Rect::from_center_size(Pos2::new(cx, cy + 2.0), Vec2::splat(48.0)), - Color::WHITE, - ); - } - PlayerThumbStyle::Car => { - ctx.draw_icon( - Icon::ThumbCar, - Rect::from_center_size(Pos2::new(cx, cy + 4.0), Vec2::new(82.0, 26.0)), - Color::WHITE, - ); - } - PlayerThumbStyle::Claudik => { - draw_claudik_sprite(ctx, Pos2::new(cx, cy + 16.0), 3.6, false); - } - PlayerThumbStyle::Antigravity => { - draw_antigravity_sprite(ctx, Pos2::new(cx - 2.0, cy + 16.0), 3.5, time, true); - } - PlayerThumbStyle::Ferris => { - draw_ferris_sprite(ctx, Pos2::new(cx, cy + 15.0), 3.2, false); - } - PlayerThumbStyle::Nyan => { - // Mini rainbow preview behind Nyan Cat - let stripes = [ - Color::rgb(0xFF, 0x26, 0x26), - Color::rgb(0xFF, 0x99, 0x00), - Color::rgb(0xFF, 0xEE, 0x00), - Color::rgb(0x33, 0xDD, 0x33), - Color::rgb(0x1E, 0x9E, 0xFF), - Color::rgb(0x7A, 0x44, 0xFF), - ]; - for (ci, &col) in stripes.iter().enumerate() { - ctx.dl().push_rect( - Rect::from_xywh(cx - 40.0, cy - 8.0 + ci as f32 * 2.5, 24.0, 2.5), - 0.0, - col, - ); - } - draw_nyan_sprite(ctx, Pos2::new(cx + 8.0, cy + 12.0), 2.7, false); - } - } -} - -/// Crisp pixel helper anchored at bottom-center `origin`, unit size `p` logical px. -#[inline] -fn px_rect(ctx: &mut UiContext, origin: Pos2, p: f32, gx: f32, gy: f32, gw: f32, gh: f32, col: Color) { - ctx.dl().push_rect( - Rect::from_xywh( - (origin.x + gx * p).round(), - (origin.y - gy * p).round(), - (gw * p).round().max(1.0), - (gh * p).round().max(1.0), - ), - 0.0, - col, - ); -} - -/// Pixel-art Claudik (Claude Code terracotta buddy `#D97757`, matching user's reference!). -fn draw_claudik_sprite(ctx: &mut UiContext, origin: Pos2, p: f32, alt_step: bool) { - let body = Color::rgb(0xD9, 0x77, 0x57); - let eye = Color::rgb(0x1B, 0x1D, 0x24); - // Main blocky head/body (10×6 pixels) - px_rect(ctx, origin, p, -5.0, 8.0, 10.0, 6.0, body); - // Little side pixel arms - let arm_y = if alt_step { 4.5 } else { 4.0 }; - px_rect(ctx, origin, p, -6.5, arm_y, 1.5, 1.5, body); - px_rect(ctx, origin, p, 5.0, arm_y, 1.5, 1.5, body); - // Vertical dark eyes - px_rect(ctx, origin, p, -3.0, 6.5, 1.0, 2.0, eye); - px_rect(ctx, origin, p, 2.0, 6.5, 1.0, 2.0, eye); - // 4 cute little legs with walk alternation - let (l1, l2) = if alt_step { (1.4, 2.0) } else { (2.0, 1.4) }; - px_rect(ctx, origin, p, -4.0, 2.0, 1.0, l1, body); - px_rect(ctx, origin, p, -2.0, 2.0, 1.0, l2, body); - px_rect(ctx, origin, p, 1.0, 2.0, 1.0, l1, body); - px_rect(ctx, origin, p, 3.0, 2.0, 1.0, l2, body); -} - -/// Pixel-art Antigravity cosmic violet cat-bot (`#9B84EC`) + tiny succulent pot & floating aura! -fn draw_antigravity_sprite(ctx: &mut UiContext, origin: Pos2, p: f32, time: f32, with_plant: bool) { - let body = Color::rgb(0x9B, 0x84, 0xEC); - let hi = Color::rgb(0xC2, 0xB3, 0xFF); - let eye = Color::rgb(0x17, 0x18, 0x22); - // Soft cyan-violet anti-gravity glow underneath - let pulse = 0.55 + 0.35 * (time * 4.5).sin(); - ctx.dl().push_rect( - Rect::from_xywh((origin.x - 4.0 * p).round(), (origin.y + 0.5 * p).round(), (8.0 * p).round(), (1.0 * p).round().max(2.0)), - 2.0, - Color::rgb(0x52, 0xB6, 0xFF).scale_alpha(pulse * 0.65), - ); - // Pointed cat ears - px_rect(ctx, origin, p, -5.0, 9.5, 1.5, 2.0, body); - px_rect(ctx, origin, p, -3.5, 8.5, 1.0, 1.0, body); - px_rect(ctx, origin, p, 3.5, 9.5, 1.5, 2.0, body); - px_rect(ctx, origin, p, 2.5, 8.5, 1.0, 1.0, body); - // Main body - px_rect(ctx, origin, p, -5.0, 7.5, 10.0, 5.5, body); - // Subtle top sheen - px_rect(ctx, origin, p, -2.5, 7.5, 5.0, 0.8, hi); - // Dark pixel eyes with tiny sparkle - px_rect(ctx, origin, p, -3.0, 6.0, 1.2, 2.0, eye); - px_rect(ctx, origin, p, 1.8, 6.0, 1.2, 2.0, eye); - // 4 floating legs - px_rect(ctx, origin, p, -4.0, 2.0, 1.0, 1.8, body); - px_rect(ctx, origin, p, -2.0, 2.0, 1.0, 1.8, body); - px_rect(ctx, origin, p, 1.0, 2.0, 1.0, 1.8, body); - px_rect(ctx, origin, p, 3.0, 2.0, 1.0, 1.8, body); - // Cute tiny potted cactus/succulent friend on the right (matching Screenshot 3!) - if with_plant { - px_rect(ctx, origin, p, 5.2, 1.8, 3.2, 1.2, Color::rgb(0x8D, 0x55, 0x2B)); - px_rect(ctx, origin, p, 5.7, 0.8, 2.2, 0.8, Color::rgb(0x6E, 0x40, 0x1E)); - px_rect(ctx, origin, p, 6.2, 4.4, 1.2, 2.6, Color::rgb(0x6D, 0xE8, 0x7A)); - px_rect(ctx, origin, p, 7.6, 3.2, 0.9, 1.4, Color::rgb(0x52, 0xC9, 0x60)); - } -} - -/// Pixel-art Ferris the Rust Crab (`#F74C00`) scuttling along the progress bar! -fn draw_ferris_sprite(ctx: &mut UiContext, origin: Pos2, p: f32, alt_step: bool) { - let shell = Color::rgb(0xF7, 0x4C, 0x00); - let dark = Color::rgb(0xC2, 0x35, 0x00); - let white = Color::WHITE; - let pupil = Color::rgb(0x16, 0x16, 0x1A); - // Raised crab claws - let claw_dy = if alt_step { 0.7 } else { 0.0 }; - px_rect(ctx, origin, p, -7.2, 7.5 + claw_dy, 2.2, 2.4, shell); - px_rect(ctx, origin, p, 5.0, 7.5 + claw_dy, 2.2, 2.4, shell); - px_rect(ctx, origin, p, -6.5, 5.2, 1.8, 1.4, dark); - px_rect(ctx, origin, p, 4.7, 5.2, 1.8, 1.4, dark); - // Spiky rounded crab carapace - px_rect(ctx, origin, p, -5.0, 7.2, 10.0, 5.0, shell); - px_rect(ctx, origin, p, -3.5, 8.2, 7.0, 1.2, shell); - // Googly eyes - px_rect(ctx, origin, p, -3.0, 6.0, 2.0, 2.0, white); - px_rect(ctx, origin, p, 1.0, 6.0, 2.0, 2.0, white); - px_rect(ctx, origin, p, -2.0, 5.5, 1.0, 1.2, pupil); - px_rect(ctx, origin, p, 2.0, 5.5, 1.0, 1.2, pupil); - // Cute smile - px_rect(ctx, origin, p, -1.0, 3.4, 2.0, 0.8, dark); - // Scuttling legs - let off = if alt_step { 0.5 } else { 0.0 }; - px_rect(ctx, origin, p, -4.5 + off, 2.2, 1.2, 2.0, dark); - px_rect(ctx, origin, p, -2.0 - off, 2.2, 1.2, 2.0, dark); - px_rect(ctx, origin, p, 0.8 + off, 2.2, 1.2, 2.0, dark); - px_rect(ctx, origin, p, 3.3 - off, 2.2, 1.2, 2.0, dark); -} - -/// Pixel-art Nyan Cat zooming along the rainbow progress bar! -fn draw_nyan_sprite(ctx: &mut UiContext, origin: Pos2, p: f32, alt_step: bool) { - let crust = Color::rgb(0xF6, 0xCC, 0x8F); - let icing = Color::rgb(0xFF, 0x99, 0xD6); - let sprinkle = Color::rgb(0xFF, 0x33, 0x88); - let cat = Color::rgb(0x9A, 0x9E, 0xA8); - let dark = Color::rgb(0x1C, 0x1E, 0x24); - let blush = Color::rgb(0xFF, 0x85, 0xA1); - // Tail wagging on left - let ty = if alt_step { 6.2 } else { 4.8 }; - px_rect(ctx, origin, p, -8.0, ty, 2.5, 1.4, cat); - // Pop-tart body - px_rect(ctx, origin, p, -5.8, 8.6, 8.8, 6.8, crust); - px_rect(ctx, origin, p, -4.8, 7.6, 6.8, 4.8, icing); - // Sprinkles - px_rect(ctx, origin, p, -3.8, 6.6, 1.0, 1.0, sprinkle); - px_rect(ctx, origin, p, -1.5, 5.4, 1.0, 1.0, sprinkle); - px_rect(ctx, origin, p, 0.2, 6.8, 1.0, 1.0, sprinkle); - // Cat head on right - px_rect(ctx, origin, p, 1.2, 7.8, 5.4, 4.8, cat); - px_rect(ctx, origin, p, 1.5, 9.2, 1.5, 1.5, cat); - px_rect(ctx, origin, p, 4.8, 9.2, 1.5, 1.5, cat); - // Eyes & blush - px_rect(ctx, origin, p, 2.4, 6.4, 1.0, 1.2, dark); - px_rect(ctx, origin, p, 4.8, 6.4, 1.0, 1.2, dark); - px_rect(ctx, origin, p, 1.8, 5.0, 1.0, 0.9, blush); - px_rect(ctx, origin, p, 5.4, 5.0, 1.0, 0.9, blush); - // Tiny running paws - let paw_dx = if alt_step { 0.8 } else { 0.0 }; - px_rect(ctx, origin, p, -4.8 + paw_dx, 2.0, 1.5, 1.8, cat); - px_rect(ctx, origin, p, -1.8 + paw_dx, 2.0, 1.5, 1.8, cat); - px_rect(ctx, origin, p, 1.6 + paw_dx, 2.0, 1.5, 1.8, cat); - px_rect(ctx, origin, p, 4.0 + paw_dx, 2.0, 1.5, 1.8, cat); -} diff --git a/src/views/podcasts_kids.rs b/src/views/podcasts_kids.rs index ef8bfee..b349079 100644 --- a/src/views/podcasts_kids.rs +++ b/src/views/podcasts_kids.rs @@ -1,6 +1,4 @@ -use std::cell::RefCell; - -use crate::api::models::{AlbumSummary, ConcertItem, PlaylistSummary}; +use crate::api::models::AlbumSummary; use crate::app::state::{AppAction, AppState, Route}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; @@ -16,10 +14,6 @@ use crate::engine::UiContext; use crate::icons::Icon; use crate::views::overlays::{EntityContextMenuState, ShellUiState}; -thread_local! { - static CONCERT_CITY_FILTER: RefCell> = const { RefCell::new(None) }; -} - fn is_audiobook_item(item: &AlbumSummary) -> bool { item.content_type .as_deref() @@ -29,277 +23,10 @@ fn is_audiobook_item(item: &AlbumSummary) -> bool { }) } -fn is_audiobook_section(id: &str, block_type: &str, title: &str) -> bool { - let low_id = id.to_lowercase(); - let low_bt = block_type.to_lowercase(); - let low_ti = title.to_lowercase(); - low_id.contains("book") - || low_bt.contains("book") - || low_ti.contains("книг") - || low_ti.contains("book") - || low_ti.contains("роман") - || low_ti.contains("фантаст") -} - -fn draw_carousel_arrows( - ctx: &mut UiContext, - pal: &YmPalette, - h_id: WidgetId, - right_x: f32, - center_y: f32, - step: f32, -) { - let next_r = Rect::from_center_size(Pos2::new(right_x - 16.0, center_y), Vec2::splat(30.0)); - let prev_r = Rect::from_center_size(Pos2::new(right_x - 52.0, center_y), Vec2::splat(30.0)); - - let (off_x, max_x) = { - let st = ctx.scrolls.get_or_create(h_id); - (st.offset.x, st.max_offset().x) - }; - let can_prev = off_x > 2.0; - let can_next = max_x > 2.0 && off_x < max_x - 2.0; - - let prev_resp = ctx.interact(h_id.with("prev"), prev_r); - let next_resp = ctx.interact(h_id.with("next"), next_r); - - let prev_bg = if prev_resp.hovered && can_prev { - pal.surface_hover - } else { - pal.surface_secondary - }; - let next_bg = if next_resp.hovered && can_next { - pal.surface_hover - } else { - pal.surface_secondary - }; - - ctx.dl() - .push_rect_bordered(prev_r, 15.0, prev_bg, 1.0, pal.border_subtle); - ctx.draw_icon( - Icon::ArrowLeft, - Rect::from_center_size(prev_r.center(), Vec2::splat(16.0)), - if can_prev { - pal.text_bright - } else { - pal.text_secondary.scale_alpha(0.35) - }, - ); - - ctx.dl() - .push_rect_bordered(next_r, 15.0, next_bg, 1.0, pal.border_subtle); - ctx.draw_icon( - Icon::ArrowRight, - Rect::from_center_size(next_r.center(), Vec2::splat(16.0)), - if can_next { - pal.text_bright - } else { - pal.text_secondary.scale_alpha(0.35) - }, - ); - - if (prev_resp.hovered && can_prev) || (next_resp.hovered && can_next) { - ctx.set_cursor(CursorKind::Pointer); - } - if prev_resp.clicked && can_prev { - ctx.scrolls.get_or_create(h_id).scroll_by_x(-step); - ctx.request_repaint(); - } - if next_resp.clicked && can_next { - ctx.scrolls.get_or_create(h_id).scroll_by_x(step); - ctx.request_repaint(); - } -} - -fn shimmer_color(pal: &YmPalette, phase: f32) -> Color { - let pulse = 0.5 + 0.5 * phase.sin(); - let base = pal.surface_secondary; - let hi = pal.surface_hover; - let lerp = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * pulse).round() as u8; - Color::from_rgba( - lerp(base.r, hi.r), - lerp(base.g, hi.g), - lerp(base.b, hi.b), - 255, - ) -} - -fn format_price_spaced(price: u64) -> String { - let s = price.to_string(); - let mut out = String::with_capacity(s.len() + s.len() / 3); - for (i, ch) in s.chars().rev().enumerate() { - if i > 0 && i % 3 == 0 { - out.push(' '); - } - out.push(ch); - } - out.chars().rev().collect() -} - -fn currency_symbol(cur: Option<&str>) -> &'static str { - match cur.map(|s| s.to_ascii_uppercase()).as_deref() { - Some("USD") => "$", - Some("EUR") => "€", - Some("KZT") => "₸", - Some("BYN") => "Br", - Some("UZS") => "сум", - _ => "₽", - } -} - -fn format_ticket_label(c: &ConcertItem, ru: bool) -> String { - if let Some(price) = c.min_price.filter(|&p| p > 0) { - let sym = currency_symbol(c.currency.as_deref()); - let formatted = format_price_spaced(price); - if ru { - format!("от {} {}", formatted, sym) - } else { - format!("from {} {}", formatted, sym) - } - } else if ru { - "Билеты".into() - } else { - "Tickets".into() - } -} - -fn format_cashback_label(c: &ConcertItem, ru: bool) -> Option { - if let Some(ref title) = c.cashback_title { - if !title.trim().is_empty() { - return Some(title.trim().to_string()); - } - } - c.cashback_percent.filter(|&p| p > 0).map(|pct| { - if ru { - format!("Кешбэк {}%", pct) - } else { - format!("{}% Cashback", pct) - } - }) -} - -fn month_short(month: u32, ru: bool) -> &'static str { - if ru { - match month { - 1 => "ЯНВ", - 2 => "ФЕВ", - 3 => "МАР", - 4 => "АПР", - 5 => "МАЯ", - 6 => "ИЮН", - 7 => "ИЮЛ", - 8 => "АВГ", - 9 => "СЕН", - 10 => "ОКТ", - 11 => "НОЯ", - 12 => "ДЕК", - _ => "LIVE", - } - } else { - match month { - 1 => "JAN", - 2 => "FEB", - 3 => "MAR", - 4 => "APR", - 5 => "MAY", - 6 => "JUN", - 7 => "JUL", - 8 => "AUG", - 9 => "SEP", - 10 => "OCT", - 11 => "NOV", - 12 => "DEC", - _ => "LIVE", - } - } -} - -fn parse_concert_date_parts(raw: &str, ru: bool) -> (String, String, Option) { - let trimmed = raw.trim(); - // ISO-8601 e.g. "2026-05-15T19:00:00+03:00" or "2026-05-15" - if trimmed.len() >= 10 - && trimmed.as_bytes()[4] == b'-' - && trimmed.as_bytes()[7] == b'-' - { - if let (Ok(m), Ok(d)) = (trimmed[5..7].parse::(), trimmed[8..10].parse::()) { - let time = if trimmed.len() >= 16 - && (trimmed.as_bytes()[10] == b'T' || trimmed.as_bytes()[10] == b' ') - { - let hhmm = &trimmed[11..16]; - if hhmm != "00:00" { - Some(hhmm.to_string()) - } else { - None - } - } else { - None - }; - return (d.to_string(), month_short(m, ru).to_string(), time); - } - } - // DD.MM.YYYY - let dot_parts: Vec<&str> = trimmed.split(['.', ' ', ',']).filter(|s| !s.is_empty()).collect(); - if dot_parts.len() >= 2 { - if let (Ok(d), Ok(m)) = (dot_parts[0].parse::(), dot_parts[1].parse::()) { - if (1..=31).contains(&d) && (1..=12).contains(&m) { - let time = dot_parts - .iter() - .find(|p| p.contains(':') && p.len() >= 4) - .map(|s| s.chars().take(5).collect()); - return (d.to_string(), month_short(m, ru).to_string(), time); - } - } - } - // Human readable e.g. "15 мая, 19:00" or "15 May 20:00" - let tokens: Vec<&str> = trimmed - .split(|c: char| c.is_whitespace() || c == ',') - .filter(|s| !s.is_empty()) - .collect(); - if tokens.len() >= 2 && tokens[0].chars().all(|c| c.is_ascii_digit()) { - let day = tokens[0].to_string(); - let mon: String = tokens[1].chars().take(3).collect::().to_uppercase(); - let time = tokens - .iter() - .skip(2) - .find(|p| p.contains(':')) - .map(|s| s.chars().take(5).collect()); - return (day, mon, time); - } - let fallback = trimmed.chars().take(6).collect::(); - if fallback.is_empty() { - ("•".into(), "LIVE".into(), None) - } else { - (fallback, if ru { "АФИША" } else { "SHOW" }.into(), None) - } -} - -fn draw_cashback_pill(ctx: &mut UiContext, pos_right_or_left: Pos2, align_right: bool, label: &str) -> Rect { - let style = TextStyle::bold(11.5, Color::WHITE); - let tw = ctx.measure_text(label, style, None).x; - let w = (tw + 18.0).ceil(); - let h = 22.0; - let x = if align_right { - pos_right_or_left.x - w - } else { - pos_right_or_left.x - }; - let pill = Rect::from_xywh(x, pos_right_or_left.y, w, h); - ctx.dl().push_gradient_rect( - pill, - 11.0, - Color::rgb(0xFF, 0x3B, 0x7F), - Color::rgb(0x7B, 0x42, 0xFF), - Vec2::new(1.0, 0.0), - ); - ctx.draw_text_ellipsis(label, style, pill, TextAlign::Center); - pill -} - -/// 1-to-1 Official Books & Podcasts (`non_music`) landing page (100% theme-aware & RU/EN localized): -/// - Category filter tabs (`Все` / `Подкасты` / `Аудиокниги` / `Моя полка`) -/// - Animated loading shimmer + Refresh action when empty -/// - "Продолжить слушать" horizontal shelf -/// - Every official skeleton section from `app.non_music_sections` with `<` `>` carousel arrows -/// - Filtered Podcasts, Audiobooks & My Shelf grids with right-click context menus +/// Books & Podcasts landing page (100% theme-aware & RU/EN localized): +/// - Category filter tabs (`Все` / `Подкасты` / `Аудиокниги`) +/// - "Продолжить слушать" / "Continue listening" horizontal shelf +/// - Podcasts & Audiobooks grids with right-click context menus pub fn render_podcasts( ctx: &mut UiContext, pal: &YmPalette, @@ -318,34 +45,13 @@ pub fn render_podcasts( let avail_w = (rect.width() - 6.0).max(320.0); let mut y = rect.top() + 8.0 - scroll_y; - // Header + Refresh pill - let title_w = (avail_w - 132.0).max(180.0); ctx.draw_text_ellipsis( t.books_and_podcasts(), TextStyle::headline(34.0, pal.text_bright), - Rect::from_xywh(x, y, title_w, 42.0), + Rect::from_xywh(x, y, avail_w, 42.0), TextAlign::Left, ); - let refresh_label = if ru { "Обновить" } else { "Refresh" }; - let refresh_tw = ctx - .measure_text(refresh_label, TextStyle::medium(13.5, pal.text_primary), None) - .x; - let refresh_w = (refresh_tw + 28.0).ceil(); - let (ref_resp, _) = secondary_pill_button( - ctx, - pal, - WidgetId::new("pod_refresh_top"), - Pos2::new(x + avail_w - refresh_w, y + 4.0), - None, - refresh_label, - 34.0, - false, - ); - if ref_resp.clicked { - actions.push(AppAction::RefreshNonMusic); - } y += 46.0; - ctx.draw_text_ellipsis( if ru { "Шоу, интервью, аудиокниги и новые выпуски каждый день" @@ -358,17 +64,13 @@ pub fn render_podcasts( ); y += 32.0; - // Category filter tabs (All / Podcasts / Audiobooks / My shelf) + // Category filter tabs (All / Podcasts / Audiobooks) let active_tab = shell.podcast_filter_tab; - let tabs_vp = Rect::from_xywh(x, y, avail_w, 40.0); - let tabs_h_id = WidgetId::new("pod_tabs_hscroll"); - let tabs_sx = ctx.begin_scroll_h(tabs_h_id, tabs_vp, 0.0); - let mut tx = x - tabs_sx; + let mut tx = x; for (idx, label) in [ (0u8, t.search_all()), (1u8, if ru { "Подкасты" } else { "Podcasts" }), (2u8, t.audiobooks()), - (3u8, if ru { "Моя полка" } else { "My shelf" }), ] { let (resp, r) = secondary_pill_button( ctx, @@ -385,139 +87,67 @@ pub fn render_podcasts( } tx = r.right() + 8.0; } - ctx.end_scroll_h(tabs_h_id, pal, (tx + tabs_sx) - x, false); - y += 54.0; + y += 52.0; - // Collect deduplicated catalog from bookshelf + landing.podcasts + non_music_sections + // Merge bookshelf_items + landing.podcasts cleanly let mut all_items: Vec = Vec::new(); - let mut audiobook_ids: std::collections::HashSet = std::collections::HashSet::new(); for item in app.bookshelf_items.iter().chain(app.landing.podcasts.iter()) { - if is_audiobook_item(item) { - audiobook_ids.insert(item.id.clone()); - } if !all_items.iter().any(|existing| existing.id == item.id) { all_items.push(item.clone()); } } - for sec in &app.non_music_sections { - let sec_is_book = is_audiobook_section(&sec.id, &sec.block_type, &sec.title); - for alb in &sec.albums { - if sec_is_book || is_audiobook_item(alb) { - audiobook_ids.insert(alb.id.clone()); - } - if !all_items.iter().any(|existing| existing.id == alb.id) { - all_items.push(alb.clone()); - } - } - } - let has_any_content = !all_items.is_empty() - || app - .non_music_sections - .iter() - .any(|s| !s.albums.is_empty() || !s.playlists.is_empty()); - - if !has_any_content && app.non_music_loading { - ctx.request_repaint(); - let t_sec = app.start_time.elapsed().as_secs_f32() * 3.0; - let card_w = 168.0; - let card_h = card_w + 54.0; - for row_idx in 0..2 { - let head_col = shimmer_color(pal, t_sec + row_idx as f32 * 0.7); - ctx.dl() - .push_rect(Rect::from_xywh(x, y, 210.0, 22.0), 6.0, head_col); - y += 34.0; - let count = ((avail_w + 16.0) / (card_w + 16.0)).floor().clamp(2.0, 6.0) as usize; - for i in 0..count { - let cx = x + i as f32 * (card_w + 16.0); - let col = shimmer_color(pal, t_sec + i as f32 * 0.45 + row_idx as f32 * 0.8); - ctx.dl() - .push_rect(Rect::from_xywh(cx, y, card_w, card_w), 12.0, col); - ctx.dl().push_rect( - Rect::from_xywh(cx, y + card_w + 10.0, card_w * 0.78, 14.0), - 5.0, - col, - ); - ctx.dl().push_rect( - Rect::from_xywh(cx, y + card_w + 30.0, card_w * 0.52, 12.0), - 5.0, - col, - ); - } - y += card_h + 26.0; - } - } else if !has_any_content { - ctx.draw_text_wrapped( + if all_items.is_empty() { + ctx.draw_text_ellipsis( if ru { - "Подкасты и аудиокниги пока не загрузились. Нажмите «Обновить», чтобы повторить запрос." + "Загрузка подкастов и книг…" } else { - "Podcasts and audiobooks haven't loaded yet. Click Refresh to try again." + "Loading podcasts & audiobooks…" }, TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 44.0), - Some(2), + Rect::from_xywh(x, y, avail_w, 24.0), TextAlign::Left, ); - y += 52.0; - let (btn, _) = yellow_pill_button( - ctx, - pal, - WidgetId::new("pod_empty_refresh"), - Pos2::new(x, y), - None, - refresh_label, - 38.0, - false, - ); - if btn.clicked { - actions.push(AppAction::RefreshNonMusic); - } - y += 56.0; + y += 32.0; } else { - // Helper to draw a horizontal shelf of albums + playlists with `<` `>` carousel arrows - let draw_shelf = |ctx: &mut UiContext, - covers: &mut CoverCache, - shell: &mut ShellUiState, - actions: &mut Vec, - title: &str, - salt: &str, - albums: &[AlbumSummary], - playlists: &[PlaylistSummary], - start_y: f32| - -> f32 { - let total_cards = albums.len() + playlists.len(); - if total_cards == 0 { - return start_y; + // 1. "Continue listening" horizontal shelf (bookshelf + recently played podcasts/books) + let mut continue_items: Vec = Vec::new(); + for tr in &app.play_history { + if let Some(ref aid) = tr.album_id { + if let Some(found) = all_items.iter().find(|it| &it.id == aid) { + if !continue_items.iter().any(|c| c.id == found.id) { + continue_items.push(found.clone()); + } + } } - let card_w = 168.0; - let card_h = card_w + 54.0; - let gap = 16.0; - let h_id = WidgetId::from_pair("pod_shelf_h", salt); + } + for item in &app.bookshelf_items { + if !continue_items.iter().any(|c| c.id == item.id) { + continue_items.push(item.clone()); + } + } + if continue_items.is_empty() { + continue_items = all_items.iter().take(4).cloned().collect(); + } - let mut cur_y = start_y; + if active_tab == 0 && !continue_items.is_empty() { ctx.draw_text_ellipsis( - title, + t.continue_listening(), TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, cur_y, (avail_w - 80.0).max(160.0), 28.0), + Rect::from_xywh(x, y, avail_w, 28.0), TextAlign::Left, ); - draw_carousel_arrows( - ctx, - pal, - h_id, - x + avail_w, - cur_y + 14.0, - (card_w + gap) * 3.0, - ); - cur_y += 38.0; + y += 38.0; - let row_vp = Rect::from_xywh(x, cur_y, avail_w, card_h); + let card_w = 164.0; + let card_h = card_w + 54.0; + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + let h_id = WidgetId::new("pod_continue_hscroll"); let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); let mut cx = x - sx; - - for item in albums { - let cr = Rect::from_xywh(cx, cur_y, card_w, card_h); - if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { + for item in continue_items.iter().take(12) { + let cr = Rect::from_xywh(cx, y, card_w, card_h); + if cr.right() >= row_vp.left() - 20.0 && cr.left() <= row_vp.right() + 20.0 { let sub = item .artists .first() @@ -533,12 +163,12 @@ pub fn render_podcasts( ctx, pal, covers, - WidgetId::from_pair(salt, format!("a_{}", item.id)), + WidgetId::from_pair("pod_cont", &item.id), cr, &item.title, sub, item.cover_uri.as_deref(), - &format!("{}_{}", salt, item.id), + &format!("podc_{}", item.id), false, false, ); @@ -567,62 +197,30 @@ pub fn render_podcasts( })); } } - cx += card_w + gap; + cx += card_w + 16.0; } + ctx.end_scroll_h( + h_id, + pal, + continue_items.len().min(12) as f32 * (card_w + 16.0), + false, + ); + y += card_h + 28.0; + } - for pl in playlists { - let cr = Rect::from_xywh(cx, cur_y, card_w, card_h); - if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { - let sub = pl.description.as_deref().unwrap_or(t.playlist()); - let m = media_card( - ctx, - pal, - covers, - WidgetId::from_pair(salt, format!("p_{}_{}", pl.owner_uid, pl.kind)), - cr, - &pl.title, - sub, - pl.cover_uri.as_deref(), - &format!("{}_pl_{}_{}", salt, pl.owner_uid, pl.kind), - false, - false, - ); - if let Some(pos) = m.right_clicked_pos { - shell.open_entity_menu(EntityContextMenuState { - kind: "playlist".into(), - id: format!("{}:{}", pl.owner_uid, pl.kind), - title: pl.title.clone(), - subtitle: sub.to_string(), - cover_uri: pl.cover_uri.clone(), - owner_uid: Some(pl.owner_uid.clone()), - is_own_playlist: false, - tracks: Vec::new(), - anchor: pos, - share_url: format!( - "https://music.yandex.ru/users/{}/playlists/{}", - pl.owner_uid, pl.kind - ), - }); - } else if m.play_clicked { - actions.push(AppAction::PlayPlaylist { - owner_uid: pl.owner_uid.clone(), - kind: pl.kind.clone(), - title: pl.title.clone(), - }); - } else if m.clicked { - actions.push(AppAction::Navigate(Route::Playlist { - owner_uid: pl.owner_uid.clone(), - kind: pl.kind.clone(), - title: pl.title.clone(), - })); - } - } - cx += card_w + gap; + let mut podcasts_only: Vec = Vec::new(); + let mut audiobooks_only: Vec = Vec::new(); + for item in &all_items { + if is_audiobook_item(item) { + audiobooks_only.push(item.clone()); + } else { + podcasts_only.push(item.clone()); } - - ctx.end_scroll_h(h_id, pal, total_cards as f32 * (card_w + gap), false); - cur_y + card_h + 28.0 - }; + } + // If API metadata did not tag audiobooks separately, surface bookshelf items in Audiobooks too + if audiobooks_only.is_empty() && !app.bookshelf_items.is_empty() { + audiobooks_only = app.bookshelf_items.clone(); + } // Helper closure to render a podcast/audiobook grid with right-click context menu let draw_grid = |ctx: &mut UiContext, @@ -635,7 +233,7 @@ pub fn render_podcasts( start_y: f32| -> f32 { let gap = 16.0; - let cols = ((avail_w + gap) / 192.0).floor().clamp(2.0, 6.0) as usize; + let cols = ((avail_w + gap) / 196.0).floor().clamp(2.0, 6.0) as usize; let card_w = ((avail_w - gap * (cols as f32 - 1.0)) / cols as f32).max(140.0); let card_h = card_w + 54.0; for (idx, pod) in items.iter().enumerate() { @@ -706,224 +304,59 @@ pub fn render_podcasts( start_y + rows as f32 * (card_h + 18.0) + 20.0 }; - let mut podcasts_only: Vec = Vec::new(); - let mut audiobooks_only: Vec = Vec::new(); - for item in &all_items { - if audiobook_ids.contains(&item.id) || is_audiobook_item(item) { - audiobooks_only.push(item.clone()); - } else { - podcasts_only.push(item.clone()); - } - } - if audiobooks_only.is_empty() && !app.bookshelf_items.is_empty() { - audiobooks_only = app.bookshelf_items.clone(); + // 2. Podcasts Section + if (active_tab == 0 || active_tab == 1) && !podcasts_only.is_empty() { + ctx.draw_text_ellipsis( + if ru { "Подкасты" } else { "Podcasts" }, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, + ); + y += 38.0; + y = draw_grid( + ctx, + covers, + shell, + actions, + &podcasts_only, + "pod_card", + if ru { "Подкаст" } else { "Podcast" }, + y, + ); } - match active_tab { - 0 => { - // 1. "Continue listening" horizontal shelf - let mut continue_items: Vec = Vec::new(); - for tr in &app.play_history { - if let Some(ref aid) = tr.album_id { - if let Some(found) = all_items.iter().find(|it| &it.id == aid) { - if !continue_items.iter().any(|c| c.id == found.id) { - continue_items.push(found.clone()); - } - } - } - } - for item in &app.bookshelf_items { - if !continue_items.iter().any(|c| c.id == item.id) { - continue_items.push(item.clone()); - } - } - if continue_items.is_empty() { - continue_items = all_items.iter().take(6).cloned().collect(); - } - if !continue_items.is_empty() { - let empty_pl: [PlaylistSummary; 0] = []; - let slice_len = continue_items.len().min(12); - y = draw_shelf( - ctx, - covers, - shell, - actions, - t.continue_listening(), - "pod_continue", - &continue_items[..slice_len], - &empty_pl, - y, - ); - } - - // 2. Render EVERY official skeleton section from `app.non_music_sections` - let sections = app.non_music_sections.clone(); - let mut rendered_sections = 0usize; - for (sidx, sec) in sections.iter().enumerate() { - if sec.albums.is_empty() && sec.playlists.is_empty() { - continue; - } - let sec_title = if sec.title.trim().is_empty() { - if ru { "Подборка" } else { "Selection" } + // 3. Audiobooks Section + if active_tab == 0 || active_tab == 2 { + ctx.draw_text_ellipsis( + t.audiobooks(), + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, + ); + y += 38.0; + if audiobooks_only.is_empty() { + ctx.draw_text_ellipsis( + if ru { + "Добавляйте аудиокниги на книжную полку — они появятся здесь." } else { - sec.title.as_str() - }; - let salt = format!("nm_sec_{}_{}", sidx, sec.id); - y = draw_shelf( - ctx, - covers, - shell, - actions, - sec_title, - &salt, - &sec.albums, - &sec.playlists, - y, - ); - rendered_sections += 1; - } - - // Fallback grids if skeleton sections weren't returned yet - if rendered_sections == 0 { - if !podcasts_only.is_empty() { - ctx.draw_text_ellipsis( - if ru { "Подкасты" } else { "Podcasts" }, - TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), - TextAlign::Left, - ); - y += 38.0; - y = draw_grid( - ctx, - covers, - shell, - actions, - &podcasts_only, - "pod_card", - if ru { "Подкаст" } else { "Podcast" }, - y, - ); - } - if !audiobooks_only.is_empty() { - ctx.draw_text_ellipsis( - t.audiobooks(), - TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), - TextAlign::Left, - ); - y += 38.0; - y = draw_grid( - ctx, - covers, - shell, - actions, - &audiobooks_only, - "book_card", - t.audiobooks(), - y, - ); - } - } - } - 1 => { - ctx.draw_text_ellipsis( - if ru { "Подкасты" } else { "Podcasts" }, - TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), + "Save audiobooks to your bookshelf and they will appear here." + }, + TextStyle::regular(14.0, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 24.0), TextAlign::Left, ); - y += 38.0; - if podcasts_only.is_empty() { - ctx.draw_text_ellipsis( - if ru { - "Подкасты не найдены." - } else { - "No podcasts found." - }, - TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 24.0), - TextAlign::Left, - ); - y += 32.0; - } else { - y = draw_grid( - ctx, - covers, - shell, - actions, - &podcasts_only, - "pod_tab_card", - if ru { "Подкаст" } else { "Podcast" }, - y, - ); - } - } - 2 => { - ctx.draw_text_ellipsis( + y += 32.0; + } else { + y = draw_grid( + ctx, + covers, + shell, + actions, + &audiobooks_only, + "book_card", t.audiobooks(), - TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), - TextAlign::Left, + y, ); - y += 38.0; - if audiobooks_only.is_empty() { - ctx.draw_text_ellipsis( - if ru { - "Добавляйте аудиокниги на книжную полку — они появятся здесь." - } else { - "Save audiobooks to your bookshelf and they will appear here." - }, - TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 24.0), - TextAlign::Left, - ); - y += 32.0; - } else { - y = draw_grid( - ctx, - covers, - shell, - actions, - &audiobooks_only, - "book_tab_card", - t.audiobooks(), - y, - ); - } - } - _ => { - ctx.draw_text_ellipsis( - if ru { "Моя полка" } else { "My shelf" }, - TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), - TextAlign::Left, - ); - y += 38.0; - let shelf_items = app.bookshelf_items.clone(); - if shelf_items.is_empty() { - ctx.draw_text_ellipsis( - if ru { - "Сохраняйте любимые подкасты и аудиокниги — они появятся на вашей полке." - } else { - "Save podcasts and audiobooks to see them on your shelf." - }, - TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 24.0), - TextAlign::Left, - ); - y += 32.0; - } else { - y = draw_grid( - ctx, - covers, - shell, - actions, - &shelf_items, - "shelf_card", - t.audiobooks(), - y, - ); - } } } } @@ -1055,11 +488,7 @@ pub fn render_kids( ctx.end_scroll_v(scroll_id, pal, total_h, true); } -/// 1-to-1 Official Concerts Page (`ConcertsPage` + `ConcertCard_root__fcR9B`): -/// - City filter pills ("Все города" + unique cities) -/// - Animated shimmer while loading + Refresh action when empty -/// - Top Featured Concerts 3-card poster grid with frosted date badge + Plus cashback pill + price CTA -/// - Upcoming Concerts Feed with 68x74 date block, 60x60 cover, metadata + cashback pill, and price/tickets CTA +/// Real Concerts Feed powered by `GET /concerts/feed`. pub fn render_concerts( ctx: &mut UiContext, pal: &YmPalette, @@ -1078,34 +507,13 @@ pub fn render_concerts( let avail_w = (rect.width() - 6.0).max(320.0); let mut y = rect.top() + 8.0 - scroll_y; - // Header + Refresh button - let refresh_label = if ru { "Обновить" } else { "Refresh" }; - let refresh_tw = ctx - .measure_text(refresh_label, TextStyle::medium(13.5, pal.text_primary), None) - .x; - let refresh_w = (refresh_tw + 28.0).ceil(); - ctx.draw_text_ellipsis( t.concerts(), TextStyle::headline(34.0, pal.text_bright), - Rect::from_xywh(x, y, (avail_w - refresh_w - 16.0).max(160.0), 42.0), + Rect::from_xywh(x, y, avail_w, 42.0), TextAlign::Left, ); - let (ref_resp, _) = secondary_pill_button( - ctx, - pal, - WidgetId::new("concerts_refresh_top"), - Pos2::new(x + avail_w - refresh_w, y + 4.0), - None, - refresh_label, - 34.0, - false, - ); - if ref_resp.clicked { - actions.push(AppAction::RefreshConcerts); - } y += 46.0; - ctx.draw_text_ellipsis( if ru { "Афиша ближайших выступлений любимых исполнителей" @@ -1116,129 +524,19 @@ pub fn render_concerts( Rect::from_xywh(x, y, avail_w, 22.0), TextAlign::Left, ); - y += 32.0; + y += 38.0; - let concerts = app.concerts.clone(); - - // Collect unique cities for filter pills - let mut cities: Vec = Vec::new(); - for c in &concerts { - let city = c.city.trim(); - if !city.is_empty() && !cities.iter().any(|existing| existing == city) { - cities.push(city.to_string()); - } - } - - let mut selected_city = CONCERT_CITY_FILTER.with(|cell| cell.borrow().clone()); - if let Some(ref sc) = selected_city { - if !cities.iter().any(|c| c == sc) { - selected_city = None; - CONCERT_CITY_FILTER.with(|cell| *cell.borrow_mut() = None); - } - } - - if !cities.is_empty() { - let pills_vp = Rect::from_xywh(x, y, avail_w, 40.0); - let pills_h_id = WidgetId::new("concerts_city_pills"); - let sx = ctx.begin_scroll_h(pills_h_id, pills_vp, 0.0); - let mut px = x - sx; - - let all_label = if ru { "Все города" } else { "All cities" }; - let (all_resp, all_r) = secondary_pill_button( - ctx, - pal, - WidgetId::new("concerts_city_all"), - Pos2::new(px, y), - None, - all_label, - 34.0, - selected_city.is_none(), - ); - if all_resp.clicked { - selected_city = None; - CONCERT_CITY_FILTER.with(|cell| *cell.borrow_mut() = None); - } - px = all_r.right() + 8.0; - - for (ci, city) in cities.iter().enumerate() { - let is_active = selected_city.as_deref() == Some(city.as_str()); - let (c_resp, c_r) = secondary_pill_button( - ctx, - pal, - WidgetId::from_pair("concerts_city", ci), - Pos2::new(px, y), - None, - city, - 34.0, - is_active, - ); - if c_resp.clicked { - selected_city = Some(city.clone()); - CONCERT_CITY_FILTER.with(|cell| *cell.borrow_mut() = Some(city.clone())); - } - px = c_r.right() + 8.0; - } - ctx.end_scroll_h(pills_h_id, pal, (px + sx) - x, false); - y += 50.0; - } - - let filtered: Vec<&ConcertItem> = concerts - .iter() - .filter(|c| match selected_city.as_deref() { - Some(city) => c.city.trim() == city, - None => true, - }) - .collect(); - - if concerts.is_empty() && app.concerts_loading { - ctx.request_repaint(); - let t_sec = app.start_time.elapsed().as_secs_f32() * 3.0; - - // 3 featured shimmer poster cards (matching official 0.963 TopConcertsCarousel aspect ratio) - let gap = 16.0; - let f_cols = if avail_w >= 860.0 { - 3usize - } else if avail_w >= 560.0 { - 2 - } else { - 1 - }; - let f_w = ((avail_w - gap * (f_cols as f32 - 1.0)) / f_cols as f32).clamp(240.0, 440.0); - let f_h = (f_w / 0.963).clamp(240.0, 320.0); - for i in 0..f_cols { - let col = shimmer_color(pal, t_sec + i as f32 * 0.55); - ctx.dl().push_rect( - Rect::from_xywh(x + i as f32 * (f_w + gap), y, f_w, f_h), - 16.0, - col, - ); - } - y += f_h + 26.0; - - // 4 shimmer feed rows - for i in 0..4 { - let col = shimmer_color(pal, t_sec + 1.2 + i as f32 * 0.45); - ctx.dl() - .push_rect(Rect::from_xywh(x, y, avail_w, 92.0), 14.0, col); - y += 104.0; - } - } else if filtered.is_empty() { + if app.concerts.is_empty() { let msg = if app.account.is_none() { if ru { "Войдите в аккаунт Яндекс ID, чтобы видеть персональную афишу концертов." } else { "Sign in with Yandex ID to see personalized upcoming concerts." } - } else if selected_city.is_some() { - if ru { - "В выбранном городе ближайших концертов не найдено." - } else { - "No upcoming concerts found in the selected city." - } } else if ru { - "Ближайшие концерты не найдены. Попробуйте обновить афишу." + "Ближайшие концерты не найдены или ещё загружаются." } else { - "No upcoming concerts found. Try refreshing the feed." + "No upcoming concerts found or still loading." }; ctx.draw_text_wrapped( msg, @@ -1247,193 +545,13 @@ pub fn render_concerts( Some(2), TextAlign::Left, ); - y += 50.0; - let (btn, _) = yellow_pill_button( - ctx, - pal, - WidgetId::new("concerts_empty_refresh"), - Pos2::new(x, y), - None, - refresh_label, - 38.0, - false, - ); - if btn.clicked { - actions.push(AppAction::RefreshConcerts); - } - y += 54.0; + y += 48.0; } else { - // --------------------------------------------------------------------- - // 1. TOP FEATURED CONCERTS GRID (first up to 3 concerts) - // --------------------------------------------------------------------- - let featured_count = filtered.len().min(3); - let gap = 16.0; - let f_cols = if avail_w >= 860.0 { - featured_count.min(3) - } else if avail_w >= 560.0 { - featured_count.min(2) - } else { - 1 - } - .max(1); - let f_w = ((avail_w - gap * (f_cols as f32 - 1.0)) / f_cols as f32).clamp(240.0, 440.0); - let f_h = (f_w / 0.963).clamp(240.0, 320.0); - - ctx.draw_text_ellipsis( - if ru { "Рекомендуем" } else { "Featured" }, - TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), - TextAlign::Left, - ); - y += 38.0; - - for (i, c) in filtered.iter().take(featured_count).enumerate() { - let col = i % f_cols; - let row = i / f_cols; - let cr = Rect::from_xywh( - x + col as f32 * (f_w + gap), - y + row as f32 * (f_h + gap), - f_w, - f_h, - ); + let concerts = app.concerts.clone(); + for (idx, c) in concerts.iter().enumerate() { + let cr = Rect::from_xywh(x, y, avail_w, 94.0); if cr.bottom() >= rect.top() - 40.0 && cr.top() <= rect.bottom() + 40.0 { - let resp = ctx.interact(WidgetId::from_pair("concert_feat", i), cr); - - // Full-bleed cover poster - draw_cover_art( - ctx, - pal, - covers, - cr, - c.cover_uri.as_deref(), - &c.id, - 16.0, - false, - false, - ); - - // Rich dark bottom gradient scrim for legible white text on any artwork - ctx.dl().push_gradient_rect( - cr, - 16.0, - Color::from_rgba(12, 12, 16, if resp.hovered { 32 } else { 52 }), - Color::from_rgba(10, 10, 14, 232), - Vec2::new(0.0, 1.0), - ); - ctx.dl().push_rect_bordered( - cr, - 16.0, - Color::TRANSPARENT, - 1.0, - Color::from_rgba(255, 255, 255, if resp.hovered { 48 } else { 24 }), - ); - - // Top-left frosted date pill - let (day_s, mon_s, time_opt) = parse_concert_date_parts(&c.date, ru); - let date_chip = format!("{} {}", day_s, mon_s); - let date_style = TextStyle::bold(12.0, Color::WHITE); - let dtw = ctx.measure_text(&date_chip, date_style, None).x; - let date_r = Rect::from_xywh(cr.left() + 14.0, cr.top() + 14.0, (dtw + 20.0).ceil(), 26.0); - ctx.dl().push_rect_bordered( - date_r, - 13.0, - Color::from_rgba(14, 14, 18, 188), - 1.0, - Color::from_rgba(255, 255, 255, 36), - ); - ctx.draw_text_ellipsis(&date_chip, date_style, date_r, TextAlign::Center); - - // Top-right Plus cashback pill - if let Some(cb) = format_cashback_label(c, ru) { - draw_cashback_pill(ctx, Pos2::new(cr.right() - 14.0, cr.top() + 16.0), true, &cb); - } - - // Bottom-right price/tickets yellow CTA - let ticket_label = format_ticket_label(c, ru); - let btn_style = TextStyle::bold(12.5, pal.on_yellow); - let btn_w = (ctx.measure_text(&ticket_label, btn_style, None).x + 24.0) - .clamp(88.0, 144.0) - .ceil(); - let btn_r = Rect::from_xywh( - cr.right() - btn_w - 14.0, - cr.bottom() - 48.0, - btn_w, - 34.0, - ); - ctx.dl().push_rect(btn_r, 17.0, pal.yellow); - ctx.draw_text_ellipsis(&ticket_label, btn_style, btn_r, TextAlign::Center); - - // Bottom-left title + venue - let heading = if c.artist_name.is_empty() { - c.title.clone() - } else if c.title.is_empty() || c.title == c.artist_name { - c.artist_name.clone() - } else { - format!("{} · {}", c.artist_name, c.title) - }; - let info_w = (btn_r.left() - cr.left() - 24.0).max(90.0); - ctx.draw_text_ellipsis( - &heading, - TextStyle::bold(17.0, Color::WHITE), - Rect::from_xywh(cr.left() + 14.0, cr.bottom() - 56.0, info_w, 24.0), - TextAlign::Left, - ); - let mut meta_parts: Vec<&str> = Vec::new(); - if !c.city.is_empty() { - meta_parts.push(c.city.as_str()); - } - if !c.place.is_empty() { - meta_parts.push(c.place.as_str()); - } - let time_str = time_opt.as_deref().unwrap_or(""); - if !time_str.is_empty() { - meta_parts.push(time_str); - } - ctx.draw_text_ellipsis( - &meta_parts.join(" · "), - TextStyle::regular(12.5, Color::from_rgba(255, 255, 255, 210)), - Rect::from_xywh(cr.left() + 14.0, cr.bottom() - 31.0, info_w, 18.0), - TextAlign::Left, - ); - - if resp.hovered && c.afisha_url.is_some() { - ctx.set_cursor(CursorKind::Pointer); - } - if resp.clicked { - if let Some(ref url) = c.afisha_url { - actions.push(AppAction::OpenUrl(url.clone())); - } - } - } - } - let f_rows = featured_count.div_ceil(f_cols); - y += f_rows as f32 * (f_h + gap) + 18.0; - - // --------------------------------------------------------------------- - // 2. UPCOMING CONCERTS FEED (`ConcertCard_root__fcR9B`) - // --------------------------------------------------------------------- - let feed_items = if filtered.len() > 3 { - &filtered[3..] - } else { - &filtered[..] - }; - - ctx.draw_text_ellipsis( - if ru { - "Ближайшие концерты" - } else { - "Upcoming concerts" - }, - TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), - TextAlign::Left, - ); - y += 38.0; - - for (idx, c) in feed_items.iter().enumerate() { - let cr = Rect::from_xywh(x, y, avail_w, 96.0); - if cr.bottom() >= rect.top() - 40.0 && cr.top() <= rect.bottom() + 40.0 { - let resp = ctx.interact(WidgetId::from_pair("concert_feed_row", idx), cr); + let resp = ctx.interact(WidgetId::from_pair("concert_card", idx), cr); ctx.dl().push_rect_bordered( cr, 14.0, @@ -1445,32 +563,7 @@ pub fn render_concerts( 1.0, pal.border_subtle, ); - - // Left 68x74 rounded Date Block (big bold day + short uppercase month) - let (day_s, mon_s, time_opt) = parse_concert_date_parts(&c.date, ru); - let date_r = Rect::from_xywh(cr.left() + 12.0, cr.center_y() - 37.0, 68.0, 74.0); - ctx.dl().push_rect_bordered( - date_r, - 11.0, - pal.bg_content, - 1.0, - pal.border_subtle, - ); - ctx.draw_text_ellipsis( - &day_s, - TextStyle::headline(24.0, pal.text_bright), - Rect::from_xywh(date_r.left() + 4.0, date_r.top() + 12.0, date_r.w - 8.0, 30.0), - TextAlign::Center, - ); - ctx.draw_text_ellipsis( - &mon_s, - TextStyle::bold(11.5, pal.text_secondary), - Rect::from_xywh(date_r.left() + 4.0, date_r.top() + 44.0, date_r.w - 8.0, 18.0), - TextAlign::Center, - ); - - // 60x60 thumbnail - let cov_r = Rect::from_xywh(date_r.right() + 14.0, cr.center_y() - 30.0, 60.0, 60.0); + let cov_r = Rect::from_xywh(cr.left() + 14.0, cr.top() + 14.0, 66.0, 66.0); draw_cover_art( ctx, pal, @@ -1483,40 +576,6 @@ pub fn render_concerts( false, ); - // Right CTA button (128x38) - let ticket_label = format_ticket_label(c, ru); - let btn_w = 128.0; - let btn_r = Rect::from_xywh( - cr.right() - btn_w - 16.0, - cr.center_y() - 19.0, - btn_w, - 38.0, - ); - if c.afisha_url.is_some() { - ctx.dl().push_rect(btn_r, 19.0, pal.yellow); - ctx.draw_text_ellipsis( - &ticket_label, - TextStyle::bold(13.0, pal.on_yellow), - btn_r, - TextAlign::Center, - ); - } else { - ctx.dl().push_rect_bordered( - btn_r, - 19.0, - pal.surface_hover, - 1.0, - pal.border_subtle, - ); - ctx.draw_text_ellipsis( - &ticket_label, - TextStyle::medium(13.0, pal.text_secondary), - btn_r, - TextAlign::Center, - ); - } - - // Middle info column: title + city/place/time + Plus cashback pill let heading = if c.artist_name.is_empty() { c.title.clone() } else if c.title.is_empty() || c.title == c.artist_name { @@ -1525,42 +584,37 @@ pub fn render_concerts( format!("{} · {}", c.artist_name, c.title) }; let text_x = cov_r.right() + 16.0; - let text_w = (btn_r.left() - text_x - 14.0).max(100.0); - let cashback = format_cashback_label(c, ru); - - let title_y = if cashback.is_some() { - cr.top() + 13.0 - } else { - cr.top() + 21.0 - }; + let text_w = (cr.right() - text_x - 136.0).max(100.0); ctx.draw_text_ellipsis( &heading, TextStyle::bold(16.0, pal.text_bright), - Rect::from_xywh(text_x, title_y, text_w, 24.0), + Rect::from_xywh(text_x, cr.top() + 20.0, text_w, 24.0), TextAlign::Left, ); - - let mut meta: Vec<&str> = Vec::new(); - if !c.city.is_empty() { - meta.push(c.city.as_str()); - } - if !c.place.is_empty() { - meta.push(c.place.as_str()); - } - if let Some(ref tm) = time_opt { - meta.push(tm.as_str()); - } + let meta: Vec<&str> = [c.date.as_str(), c.city.as_str(), c.place.as_str()] + .into_iter() + .filter(|s| !s.is_empty()) + .collect(); ctx.draw_text_ellipsis( &meta.join(" · "), TextStyle::regular(13.5, pal.text_secondary), - Rect::from_xywh(text_x, title_y + 26.0, text_w, 20.0), + Rect::from_xywh(text_x, cr.top() + 50.0, text_w, 20.0), TextAlign::Left, ); - if let Some(cb) = cashback { - draw_cashback_pill(ctx, Pos2::new(text_x, title_y + 49.0), false, &cb); + if c.afisha_url.is_some() { + let btn_r = Rect::from_center_size( + Pos2::new(cr.right() - 68.0, cr.center_y()), + Vec2::new(108.0, 34.0), + ); + ctx.dl().push_rect(btn_r, 17.0, pal.yellow); + ctx.draw_text_ellipsis( + if ru { "Билеты" } else { "Tickets" }, + TextStyle::bold(13.0, pal.on_yellow), + btn_r, + TextAlign::Center, + ); } - if resp.hovered && c.afisha_url.is_some() { ctx.set_cursor(CursorKind::Pointer); } @@ -1570,7 +624,7 @@ pub fn render_concerts( } } } - y += 106.0; + y += 104.0; } } @@ -1676,8 +730,6 @@ pub fn render_chart( is_liked: app.liked_ids.contains(&tr.id), is_disliked: app.disliked_ids.contains(&tr.id), is_downloaded: app.is_track_downloaded(&tr.id), - is_downloading: app.is_track_downloading(&tr.id), - download_progress: app.track_download_progress(&tr.id), menu_open: shell.is_track_menu_open(&tr.id), }, ) { @@ -2013,8 +1065,6 @@ pub fn render_metatag_detail( is_liked: app.liked_ids.contains(&tr.id), is_disliked: app.disliked_ids.contains(&tr.id), is_downloaded: app.is_track_downloaded(&tr.id), - is_downloading: app.is_track_downloading(&tr.id), - download_progress: app.track_download_progress(&tr.id), menu_open: shell.is_track_menu_open(&tr.id), }, ) { diff --git a/src/views/search.rs b/src/views/search.rs index 81ac659..77e10ce 100644 --- a/src/views/search.rs +++ b/src/views/search.rs @@ -339,9 +339,8 @@ pub fn render_search( false, false, ); - let balb_title = balb.full_title(); ctx.draw_text_ellipsis( - &balb_title, + &balb.title, TextStyle::bold(16.5, pal.text_bright), Rect::from_xywh(text_x, card_r.top() + 22.0, text_w, 24.0), TextAlign::Left, @@ -572,8 +571,6 @@ pub fn render_search( is_liked: app.liked_ids.contains(&tr.id), is_disliked: app.disliked_ids.contains(&tr.id), is_downloaded: app.is_track_downloaded(&tr.id), - is_downloading: app.is_track_downloading(&tr.id), - download_progress: app.track_download_progress(&tr.id), menu_open: shell.is_track_menu_open(&tr.id), }, ) { @@ -729,9 +726,8 @@ pub fn render_search( let h_id = WidgetId::new("search_albums_hscroll"); let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); let mut cx = x - sx; - for (idx, alb) in res.albums.iter().take(12).enumerate() { + for alb in res.albums.iter().take(12) { let cr = Rect::from_xywh(cx, y, card_w, card_h); - let alb_title = alb.full_title(); let sub = alb .artists .first() @@ -741,9 +737,9 @@ pub fn render_search( ctx, pal, covers, - WidgetId::from_pair("s_alb", (idx, &alb.id)), + WidgetId::from_pair("s_alb", &alb.id), cr, - &alb_title, + &alb.title, sub, alb.cover_uri.as_deref(), &format!("alb_{}", alb.id), @@ -753,12 +749,12 @@ pub fn render_search( if m.play_clicked { actions.push(AppAction::PlayAlbum { id: alb.id.clone(), - title: alb_title, + title: alb.title.clone(), }); } else if m.clicked { actions.push(AppAction::Navigate(Route::Album { id: alb.id.clone(), - title: alb_title, + title: alb.title.clone(), })); } cx += card_w + 16.0; @@ -780,7 +776,6 @@ pub fn render_search( card_h, ); if cr.bottom() >= body_vp.top() - 40.0 && cr.top() <= body_vp.bottom() + 40.0 { - let alb_title = alb.full_title(); let sub = alb .artists .first() @@ -790,9 +785,9 @@ pub fn render_search( ctx, pal, covers, - WidgetId::from_pair("s_alb_grid", (idx, &alb.id)), + WidgetId::from_pair("s_alb_grid", &alb.id), cr, - &alb_title, + &alb.title, sub, alb.cover_uri.as_deref(), &format!("alb_{}", alb.id), @@ -802,12 +797,12 @@ pub fn render_search( if m.play_clicked { actions.push(AppAction::PlayAlbum { id: alb.id.clone(), - title: alb_title, + title: alb.title.clone(), }); } else if m.clicked { actions.push(AppAction::Navigate(Route::Album { id: alb.id.clone(), - title: alb_title, + title: alb.title.clone(), })); } } @@ -836,16 +831,13 @@ pub fn render_search( let h_id = WidgetId::new("search_playlists_hscroll"); let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); let mut cx = x - sx; - for (idx, pl) in res.playlists.iter().take(12).enumerate() { + for pl in res.playlists.iter().take(12) { let cr = Rect::from_xywh(cx, y, card_w, card_h); let m = media_card( ctx, pal, covers, - WidgetId::from_pair( - "s_pl", - (idx, format!("{}_{}", pl.owner_uid, pl.kind)), - ), + WidgetId::from_pair("s_pl", format!("{}_{}", pl.owner_uid, pl.kind)), cr, &pl.title, &pl.owner_name, @@ -897,7 +889,7 @@ pub fn render_search( covers, WidgetId::from_pair( "s_pl_grid", - (idx, format!("{}_{}", pl.owner_uid, pl.kind)), + format!("{}_{}", pl.owner_uid, pl.kind), ), cr, &pl.title, diff --git a/src/views/settings.rs b/src/views/settings.rs index 27851ed..aa2aa7b 100644 --- a/src/views/settings.rs +++ b/src/views/settings.rs @@ -1,23 +1,29 @@ use crate::app::i18n::APP_VERSION; use crate::app::state::{AppAction, AppState}; -use crate::config::{AudioQuality, Language, PlayerThumbStyle, ThemeMode}; +use crate::audio::dsp::{EQ_LABELS, EQ_PRESETS}; +use crate::config::{AudioQuality, Language, ThemeMode}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; use crate::engine::text::{TextAlign, TextStyle}; use crate::engine::theme::YmPalette; -use crate::engine::types::{Color, CursorKind, Pos2, Rect, Vec2}; +use crate::engine::types::{CursorKind, Pos2, Rect}; use crate::engine::widgets::{ - draw_cover_art, draw_plus_avatar_ring, secondary_pill_button, secondary_pill_button_in, - text_input_widget, yellow_pill_button, ym_slider, TextInputOptions, + secondary_pill_button, text_input_widget, yellow_pill_button, ym_slider, ym_vertical_slider, + TextInputOptions, }; use crate::engine::UiContext; use crate::icons::Icon; use crate::views::overlays::ShellUiState; -use crate::views::player_thumbs::render_thumb_preview; -/// 1-to-1 Official Yandex Music Desktop 5.129.0 `SettingsPage` (`Settings_root__FVVrn`, `379bcce309ec9c74.css`): -/// Clean borderless list of `SettingsListButtonItem` (title + description + `arrowRight` chevron) -/// and `SettingsListToggleItem` (title + description + right pill toggle), `max-width: 520px`. +/// Authentic Yandex Music Desktop 5.129.0 Settings Page: +/// - Account (Yandex ID / OAuth) +/// - Appearance & Language (3-way System / Dark / Light theme selector + RU/EN + Close to tray) +/// - Sound (Audio quality, Loudness normalization, Crossfade) +/// - 10-band Equalizer (Enable, Presets, 10 vertical band sliders) +/// - Recommendations & Content (Less AI, Show Kids section) +/// - Keyboard shortcuts +/// - About 5.129.0 (Update check & Clear cover cache) +/// 100% `YmPalette` theme-aware & 100% localized RU/EN! pub fn render_settings( ctx: &mut UiContext, pal: &YmPalette, @@ -32,71 +38,68 @@ pub fn render_settings( let scroll_id = WidgetId::new("settings_scroll"); let scroll_y = ctx.begin_scroll_v(scroll_id, rect, 0.0); - // `views/mod.rs` already insets `inner_r` by (25, 12, 25, 0) - let x = rect.left(); - let col_w = (rect.width() - 12.0).clamp(320.0, 482.0); + // `views/mod.rs` already insets `inner_r` by (25, 13, 25, 0) + let content_x = rect.left(); + let content_w = (rect.width() - 8.0).clamp(320.0, 960.0); let mut y = rect.top() + 8.0 - scroll_y; // Page Heading ctx.draw_text_ellipsis( t.settings(), - TextStyle::headline(32.0, pal.text_bright), - Rect::from_xywh(x, y, col_w, 40.0), + TextStyle::headline(34.0, pal.text_bright), + Rect::from_xywh(content_x, y, content_w, 42.0), TextAlign::Left, ); - y += 56.0; + y += 58.0; // ------------------------------------------------------------------------- - // 1. Account (Compact Yandex ID strip — clean borderless row + hairline) + // 1. Account (Yandex ID) // ------------------------------------------------------------------------- + let acc_h = if app.account.is_some() { 112.0 } else { 196.0 }; + let acc_inner = draw_settings_card( + ctx, + pal, + Rect::from_xywh(content_x, y, content_w, acc_h), + if ru { + "Аккаунт Яндекс ID" + } else { + "Yandex ID Account" + }, + ); if let Some(ref acc) = app.account { - let av_sz = 44.0; - let av_r = Rect::from_xywh(x, y + 2.0, av_sz, av_sz); - if acc.has_plus { - draw_plus_avatar_ring(ctx, av_r.center(), av_sz * 0.5 + 2.5, 2.0); - } - draw_cover_art( - ctx, - pal, - covers, - av_r, - acc.avatar_uri.as_deref(), - "set_avatar", - av_sz * 0.5, - true, - false, - ); let sign_out_lbl = t.sign_out(); let measured_w = ctx - .measure_text(sign_out_lbl, TextStyle::bold(13.5, pal.text_primary), None) + .measure_text(sign_out_lbl, TextStyle::bold(14.0, pal.text_primary), None) .x; - let btn_w = (measured_w + 46.0).max(102.0).ceil(); - let txt_x = av_r.right() + 14.0; - let txt_w = (col_w - (av_sz + 14.0) - btn_w - 12.0).max(100.0); - + let btn_w = (measured_w + 54.0).max(112.0).ceil(); + let text_w = (acc_inner.width() - btn_w - 16.0).max(120.0); + let row_y = acc_inner.top(); ctx.draw_text_ellipsis( &acc.display_name, TextStyle::bold(16.0, pal.text_bright), - Rect::from_xywh(txt_x, y + 3.0, txt_w, 22.0), + Rect::from_xywh(acc_inner.left(), row_y, text_w, 22.0), TextAlign::Left, ); let plan = if acc.has_plus { - if ru { "Яндекс Плюс" } else { "Yandex Plus" } + if ru { + "Яндекс Плюс активен" + } else { + "Yandex Plus active" + } } else if ru { "Базовый тариф" } else { "Free plan" }; - let meta = format!("@{} · {}", acc.login, plan); + let meta = format!("@{} · UID {} · {}", acc.login, acc.uid, plan); ctx.draw_text_ellipsis( &meta, TextStyle::regular(13.0, pal.text_secondary), - Rect::from_xywh(txt_x, y + 26.0, txt_w, 18.0), + Rect::from_xywh(acc_inner.left(), row_y + 24.0, text_w, 20.0), TextAlign::Left, ); - - let logout_r = Rect::from_xywh(x + col_w - btn_w, y + 6.0, btn_w, 36.0); - let resp = secondary_pill_button_in( + let logout_r = Rect::from_xywh(acc_inner.right() - btn_w, row_y + 4.0, btn_w, 38.0); + let resp = crate::engine::widgets::secondary_pill_button_in( ctx, pal, WidgetId::new("set_logout"), @@ -108,13 +111,26 @@ pub fn render_settings( if resp.clicked { actions.push(AppAction::Logout); } - y += 62.0; } else { + let mut cy = acc_inner.top(); + ctx.draw_text_wrapped( + if ru { + "Войдите через Яндекс ID, чтобы слушать свою коллекцию, «Мою волну» и Lossless FLAC." + } else { + "Sign in with Yandex ID to access your collection, My Vibe, and Lossless FLAC." + }, + TextStyle::regular(13.5, pal.text_secondary), + Rect::from_xywh(acc_inner.left(), cy, acc_inner.width(), 36.0), + Some(2), + TextAlign::Left, + ); + cy += 36.0; + let (oauth_resp, _) = yellow_pill_button( ctx, pal, WidgetId::new("set_oauth_btn"), - Pos2::new(x, y), + Pos2::new(acc_inner.left(), cy), Some(Icon::Plus), if ru { "Войти через Яндекс ID" @@ -127,10 +143,10 @@ pub fn render_settings( if oauth_resp.clicked { actions.push(AppAction::OpenOAuthBrowser); } - y += 48.0; + cy += 50.0; - let input_w = (col_w - 118.0).clamp(180.0, 400.0); - let input_r = Rect::from_xywh(x, y, input_w, 36.0); + let input_w = (acc_inner.width() - 130.0).clamp(180.0, 420.0); + let input_r = Rect::from_xywh(acc_inner.left(), cy, input_w, 38.0); let mut token_copy = app.token_input.clone(); let ti = text_input_widget( ctx, @@ -140,15 +156,15 @@ pub fn render_settings( &mut token_copy, TextInputOptions { placeholder: if ru { - "OAuth-токен (y0_...) или URL" + "Вставьте OAuth-токен (y0_...) или URL" } else { - "OAuth token (y0_...) or redirect URL" + "Paste OAuth token (y0_...) or redirect URL" }, leading_icon: None, show_clear_button: true, hide_placeholder_when_unfocused: false, transparent_bg: false, - font_size: 13.0, + font_size: 13.5, pill: true, }, ); @@ -159,180 +175,213 @@ pub fn render_settings( ctx, pal, WidgetId::new("set_token_submit"), - Pos2::new(input_r.right() + 10.0, y), + Pos2::new(input_r.right() + 10.0, cy), Some(Icon::CheckXxs), t.log_in(), - 36.0, + 38.0, !token_copy.trim().is_empty(), ); if (sub_resp.clicked || ti.submitted) && !token_copy.trim().is_empty() { actions.push(AppAction::SubmitOAuthToken(token_copy)); } - y += 50.0; } - - ctx.dl() - .push_rect(Rect::from_xywh(x, y, col_w, 1.0), 0.0, pal.border_subtle); - y += 18.0; + y += acc_h + 14.0; // ------------------------------------------------------------------------- - // 2. Official «Вид плеера» (`branded-player.player-type`) + Fun Companions + // 2. Appearance & Language (3-way System / Dark / Light + RU/EN + Tray) // ------------------------------------------------------------------------- - ctx.draw_text_ellipsis( - if ru { "Вид плеера" } else { "Player view" }, - TextStyle::bold(18.0, pal.text_bright), - Rect::from_xywh(x, y, col_w, 24.0), - TextAlign::Left, - ); - y += 34.0; - - let gap = 12.0; - let cols = 4usize; - let card_sz = ((col_w - gap * (cols as f32 - 1.0)) / cols as f32).floor().clamp(88.0, 114.0); - let anim_time = ctx.input.time as f32; - for (idx, &style) in PlayerThumbStyle::ALL.iter().enumerate() { - let col = idx % cols; - let row = idx / cols; - let cx = x + col as f32 * (card_sz + gap); - let cy = y + row as f32 * (card_sz + gap); - let card_r = Rect::from_xywh(cx, cy, card_sz, card_sz); - let resp = ctx.interact(WidgetId::from_pair("set_thumb_card", idx), card_r); - let selected = app.config.player_thumb == style; - let bg = if resp.hovered { - pal.surface_hover - } else { - pal.surface_secondary - }; - if selected { - ctx.dl().push_rect_bordered(card_r, 16.0, bg, 1.5, pal.yellow); - } else { - ctx.dl().push_rect(card_r, 16.0, bg); - } - let preview_r = Rect::from_xywh(card_r.left() + 8.0, card_r.top() + 10.0, card_sz - 16.0, card_sz - 38.0); - render_thumb_preview(ctx, pal, style, preview_r, anim_time); - ctx.draw_text_ellipsis( - style.label(ru), - TextStyle::medium(12.5, if selected { pal.text_bright } else { pal.text_secondary }), - Rect::from_xywh(card_r.left() + 6.0, card_r.bottom() - 26.0, card_sz - 12.0, 18.0), - TextAlign::Center, - ); - if resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if resp.clicked && !selected { - actions.push(AppAction::SetPlayerThumb(style)); - } - } - let thumb_rows = (PlayerThumbStyle::ALL.len() + cols - 1) / cols; - y += thumb_rows as f32 * (card_sz + gap) + 18.0; - - // ------------------------------------------------------------------------- - // 3. Official Settings List (`Settings_root`, 32px vertical spacing) - // ------------------------------------------------------------------------- - - // 2a. Clear memory (`offline.clear-memory`) - if settings_button_item( + let app_h = 204.0; + let app_inner = draw_settings_card( ctx, pal, - WidgetId::new("set_clear_cache"), - x, - &mut y, - col_w, - if ru { "Очистить память" } else { "Clear cache" }, - Some(if ru { - "Удалим только скачанное и кэш. Это не повлияет на ваши рекомендации и лайки" - } else { - "We'll only delete downloaded content and cache. This won't affect your recommendations or likes" - }), - None, - ) { - actions.push(AppAction::ClearCoverCache); - } - - // 2b. Equalizer (`EqualizerModal` trigger — clean row, no status subtitle) - if settings_button_item( - ctx, - pal, - WidgetId::new("set_eq_btn"), - x, - &mut y, - col_w, - if ru { "Эквалайзер" } else { "Equalizer" }, - None, - None, - ) { - actions.push(AppAction::SetEqualizerModalOpen(true)); - } - - // 2c. Sound settings (`QualitySettingsModal` trigger) - let qual_sub = match app.config.audio_quality { - AudioQuality::Lossless => { - if ru { "Превосходное" } else { "Superb" } - } - AudioQuality::High => { - if ru { "Оптимальное" } else { "Balanced" } - } - AudioQuality::Standard => { - if ru { "Экономичное" } else { "Efficient" } - } - }; - if settings_button_item( - ctx, - pal, - WidgetId::new("set_quality_btn"), - x, - &mut y, - col_w, - t.sound_settings(), - Some(qual_sub), - None, - ) { - actions.push(AppAction::SetEqPopoverOpen(true)); - } - - // 2d. Crossfade between tracks (toggle + optional duration override) - let cf_sub = if app.config.crossfade_enabled { - if app.config.crossfade_secs < 0.1 { - if ru { - Some("Авто (умные точки Яндекс Музыки)".to_string()) - } else { - Some("Auto (Yandex Music smart fade)".to_string()) - } - } else if ru { - Some(format!("Длительность: {:.0} с", app.config.crossfade_secs)) - } else { - Some(format!("Duration: {:.0} s", app.config.crossfade_secs)) - } - } else { - None - }; - if let Some(next) = settings_toggle_item( - ctx, - pal, - WidgetId::new("set_crossfade_toggle"), - x, - &mut y, - col_w, + Rect::from_xywh(content_x, y, content_w, app_h), if ru { - "Плавные переходы между треками" + "Оформление и интерфейс" } else { - "Crossfade between tracks" + "Appearance & Language" }, - cf_sub.as_deref(), - app.config.crossfade_enabled, - ) { - actions.push(AppAction::SetCrossfadeEnabled(next)); + ); + { + let mut cy = app_inner.top(); + ctx.draw_text_ellipsis( + t.appearance(), + TextStyle::medium(13.0, pal.text_secondary), + Rect::from_xywh(app_inner.left(), cy, app_inner.width(), 18.0), + TextAlign::Left, + ); + cy += 24.0; + + let mut tx = app_inner.left(); + for (mode, icon, label) in [ + (ThemeMode::System, Icon::ThemeSystemXxs, t.theme_system()), + (ThemeMode::Dark, Icon::ThemeDarkXxs, t.theme_dark()), + (ThemeMode::Light, Icon::ThemeLightXxs, t.theme_light()), + ] { + let (resp, r) = secondary_pill_button( + ctx, + pal, + WidgetId::from_pair("set_theme", mode as u8), + Pos2::new(tx, cy), + Some(icon), + label, + 38.0, + app.config.theme == mode, + ); + if resp.clicked { + actions.push(AppAction::SetTheme(mode)); + } + tx = r.right() + 10.0; + } + cy += 50.0; + + // Language selector + let mut lx = app_inner.left(); + for (lang, label) in [(Language::Ru, "Русский"), (Language::En, "English")] { + let (resp, r) = secondary_pill_button( + ctx, + pal, + WidgetId::from_pair("set_lang", lang as u8), + Pos2::new(lx, cy), + Some(Icon::ProfileGlobeXxs), + label, + 36.0, + app.config.language == lang, + ); + if resp.clicked { + actions.push(AppAction::SetLanguage(lang)); + } + lx = r.right() + 10.0; + } + cy += 48.0; + + // Close to tray toggle + if let Some(next) = settings_toggle_row( + ctx, + pal, + WidgetId::new("set_close_to_tray"), + Rect::from_xywh(app_inner.left(), cy, app_inner.width(), 32.0), + if ru { + "Сворачивать в системный трей при закрытии окна" + } else { + "Minimize to system tray on close" + }, + app.config.close_to_tray, + ) { + actions.push(AppAction::SetCloseToTray(next)); + } } - if app.config.crossfade_enabled { - y -= 10.0; - let sl_label = if app.config.crossfade_secs < 0.1 { - if ru { "Авто" } else { "Auto" }.to_string() - } else if ru { - format!("{:.0} с", app.config.crossfade_secs) + y += app_h + 14.0; + + // ------------------------------------------------------------------------- + // 3. Sound (Audio quality, Loudness normalization, Crossfade) + // ------------------------------------------------------------------------- + let sound_inner_w = (content_w - 36.0).max(100.0); + let mut q_rows = 1usize; + let mut sim_qx = 0.0_f32; + for q in [ + AudioQuality::Lossless, + AudioQuality::High, + AudioQuality::Standard, + ] { + let lbl = q.label_for(app.config.language); + let btn_w = (ctx + .measure_text(lbl, TextStyle::bold(14.0, pal.text_primary), None) + .x + + 36.0) + .min(260.0); + if sim_qx + btn_w > sound_inner_w && sim_qx > 0.0 { + q_rows += 1; + sim_qx = 0.0; + } + sim_qx += btn_w + 8.0; + } + let sound_h = 196.0 + (q_rows.saturating_sub(1) as f32) * 44.0; + let sound_inner = draw_settings_card( + ctx, + pal, + Rect::from_xywh(content_x, y, content_w, sound_h), + if ru { "Звук" } else { "Sound" }, + ); + { + let mut cy = sound_inner.top(); + ctx.draw_text_ellipsis( + if ru { + "Качество звука" + } else { + "Audio quality" + }, + TextStyle::medium(13.0, pal.text_secondary), + Rect::from_xywh(sound_inner.left(), cy, sound_inner.width(), 18.0), + TextAlign::Left, + ); + cy += 24.0; + + let mut qx = sound_inner.left(); + for q in [ + AudioQuality::Lossless, + AudioQuality::High, + AudioQuality::Standard, + ] { + let lbl = q.label_for(app.config.language); + let measured = ctx + .measure_text(lbl, TextStyle::bold(14.0, pal.text_primary), None) + .x + + 36.0; + let btn_w = measured.min(260.0); + if qx + btn_w > sound_inner.right() && qx > sound_inner.left() { + qx = sound_inner.left(); + cy += 44.0; + } + let r = Rect::from_xywh(qx, cy, btn_w, 38.0); + let resp = crate::engine::widgets::secondary_pill_button_in( + ctx, + pal, + WidgetId::from_pair("set_quality", q as u8), + r, + None, + lbl, + app.config.audio_quality == q, + ); + if resp.clicked { + actions.push(AppAction::SetAudioQuality(q)); + } + qx = r.right() + 8.0; + } + cy += 50.0; + + if let Some(next) = settings_toggle_row( + ctx, + pal, + WidgetId::new("set_loudness"), + Rect::from_xywh(sound_inner.left(), cy, sound_inner.width(), 32.0), + if ru { + "Выравнивание громкости (EBU R128)" + } else { + "Loudness normalization (EBU R128)" + }, + app.config.normalize_loudness, + ) { + actions.push(AppAction::SetNormalizeLoudness(next)); + } + cy += 40.0; + + let cf_label = if ru { + format!("Плавные переходы между треками: {:.0} с", app.config.crossfade_secs) } else { - format!("{:.0} s", app.config.crossfade_secs) + format!("Crossfade between tracks: {:.0} s", app.config.crossfade_secs) }; - let slider_r = Rect::from_xywh(x, y, (col_w - 64.0).max(160.0), 22.0); + ctx.draw_text_ellipsis( + &cf_label, + TextStyle::regular(14.0, pal.text_primary), + Rect::from_xywh(sound_inner.left(), cy, 310.0, 26.0), + TextAlign::Left, + ); + let slider_r = Rect::from_xywh( + sound_inner.left() + 320.0, + cy, + (sound_inner.width() - 330.0).clamp(120.0, 280.0), + 26.0, + ); let sr = ym_slider( ctx, pal, @@ -343,453 +392,375 @@ pub fn render_settings( true, true, ); - ctx.draw_text_ellipsis( - &sl_label, - TextStyle::medium(12.5, pal.text_secondary), - Rect::from_xywh(slider_r.right() + 10.0, y, 54.0, 22.0), - TextAlign::Right, - ); if let Some(v) = sr.value { let secs = (v * 12.0).round(); if (secs - app.config.crossfade_secs).abs() >= 0.5 { actions.push(AppAction::SetCrossfadeSecs(secs)); } } - y += 40.0; } + y += sound_h + 14.0; - // 2d. Loudness normalization (EBU R128) - if let Some(next) = settings_toggle_item( - ctx, - pal, - WidgetId::new("set_loudness"), - x, - &mut y, - col_w, - if ru { - "Выравнивание громкости" - } else { - "Loudness normalization" - }, - Some(if ru { - "Автоматически выравнивать громкость треков (EBU R128)" - } else { - "Automatically normalize track volume (EBU R128)" - }), - app.config.normalize_loudness, - ) { - actions.push(AppAction::SetNormalizeLoudness(next)); - } - - // 2e. Less AI - if let Some(next) = settings_toggle_item( - ctx, - pal, - WidgetId::new("set_ai_red"), - x, - &mut y, - col_w, - if ru { "Меньше ИИ" } else { "Less AI" }, - Some(if ru { - "В рекомендациях будет реже встречаться музыка, созданная с помощью ИИ" - } else { - "AI-generated music will appear less frequently in recommendations" - }), - app.config.ai_content_reduction, - ) { - actions.push(AppAction::SetAiContentReduction(next)); - } - - // 2f. Kids section toggle - if let Some(next) = settings_toggle_item( - ctx, - pal, - WidgetId::new("set_child_mode"), - x, - &mut y, - col_w, - if ru { - "Показывать раздел «Детям»" - } else { - "Show «For Kids» section" - }, - None, - app.config.child_mode, - ) { - actions.push(AppAction::SetChildMode(next)); - } - - // 2g. Minimize to tray - if let Some(next) = settings_toggle_item( - ctx, - pal, - WidgetId::new("set_close_to_tray"), - x, - &mut y, - col_w, - if ru { - "Сворачивать в трей при закрытии" - } else { - "Minimize to system tray on close" - }, - None, - app.config.close_to_tray, - ) { - actions.push(AppAction::SetCloseToTray(next)); - } - - // 2i. Keyboard shortcuts (`ShortcutsModal` trigger) - if settings_button_item( - ctx, - pal, - WidgetId::new("set_shortcuts_btn"), - x, - &mut y, - col_w, - if ru { "Горячие клавиши" } else { "Hot keys" }, - None, - None, - ) { - actions.push(AppAction::SetShortcutsModalOpen(true)); - } - - // 2j. About (`ReleaseNotesModal` trigger) - let about_sub = if let Some(ref upd) = app.available_update { - format!("v{} · {}", APP_VERSION, t.update_available_banner(&upd.version)) - } else { - format!("v{}", APP_VERSION) - }; - let about_badge_col = if app.available_update.is_some() { - Some(pal.yellow) - } else { - None - }; - if settings_button_item( - ctx, - pal, - WidgetId::new("set_about_btn"), - x, - &mut y, - col_w, - if ru { "О приложении" } else { "About the app" }, - Some(&about_sub), - about_badge_col, - ) { - actions.push(AppAction::OpenReleaseNotesModal); - } - - // 2j. Appearance & Language (compact official pill selectors) - ctx.draw_text_ellipsis( - t.appearance(), - TextStyle::bold(16.0, pal.text_bright), - Rect::from_xywh(x, y, col_w, 22.0), - TextAlign::Left, - ); - y += 30.0; - let mut tx = x; - for (mode, icon, label) in [ - (ThemeMode::System, Icon::ThemeSystemXxs, t.theme_system()), - (ThemeMode::Dark, Icon::ThemeDarkXxs, t.theme_dark()), - (ThemeMode::Light, Icon::ThemeLightXxs, t.theme_light()), - ] { - let (resp, r) = secondary_pill_button( - ctx, - pal, - WidgetId::from_pair("set_theme", mode as u8), - Pos2::new(tx, y), - Some(icon), - label, - 34.0, - app.config.theme == mode, - ); - if resp.clicked { - actions.push(AppAction::SetTheme(mode)); + // ------------------------------------------------------------------------- + // 4. 10-Band Equalizer (dynamic height so wrapped EQ presets never clip or break) + // ------------------------------------------------------------------------- + let eq_inner_w = (content_w - 36.0).max(100.0); + let mut eq_preset_rows = 1usize; + let mut sim_px = 0.0_f32; + for preset in EQ_PRESETS.iter() { + let pw = (ctx + .measure_text(preset.name, TextStyle::bold(14.0, pal.text_primary), None) + .x + + 32.0) + .max(54.0); + if sim_px + pw > eq_inner_w && sim_px > 0.0 { + eq_preset_rows += 1; + sim_px = 0.0; } - tx = r.right() + 8.0; + sim_px += pw + 6.0; } - y += 46.0; - - ctx.draw_text_ellipsis( - if ru { "Язык" } else { "Language" }, - TextStyle::bold(16.0, pal.text_bright), - Rect::from_xywh(x, y, col_w, 22.0), - TextAlign::Left, + let eq_h = 266.0 + (eq_preset_rows.saturating_sub(1) as f32) * 38.0; + let eq_inner = draw_settings_card( + ctx, + pal, + Rect::from_xywh(content_x, y, content_w, eq_h), + if ru { "Эквалайзер" } else { "Equalizer" }, ); - y += 30.0; - let mut lx = x; - for (lang, label) in [(Language::Ru, "Русский"), (Language::En, "English")] { - let (resp, r) = secondary_pill_button( + { + let mut enabled = app.config.eq_enabled; + let mut bands = app.config.eq_bands_db; + let mut changed = false; + let mut cy = eq_inner.top(); + + if let Some(next) = settings_toggle_row( ctx, pal, - WidgetId::from_pair("set_lang", lang as u8), - Pos2::new(lx, y), - Some(Icon::ProfileGlobeXxs), - label, - 34.0, - app.config.language == lang, - ); - if resp.clicked { - actions.push(AppAction::SetLanguage(lang)); + WidgetId::new("set_eq_enable"), + Rect::from_xywh(eq_inner.left(), cy, eq_inner.width(), 30.0), + if ru { + "Включить 10-полосный эквалайзер" + } else { + "Enable 10-band equalizer" + }, + enabled, + ) { + enabled = next; + changed = true; + } + cy += 38.0; + + // Presets rows (wrap cleanly across multiple lines — NO truncation!) + let mut px = eq_inner.left(); + for (idx, preset) in EQ_PRESETS.iter().enumerate() { + let pw = (ctx + .measure_text(preset.name, TextStyle::bold(14.0, pal.text_primary), None) + .x + + 32.0) + .max(54.0); + if px + pw > eq_inner.right() && px > eq_inner.left() { + px = eq_inner.left(); + cy += 38.0; + } + let is_match = enabled + && bands + .iter() + .zip(preset.gains.iter()) + .all(|(a, b)| (a - b).abs() < 0.2); + let r = Rect::from_xywh(px, cy, pw, 30.0); + let resp = crate::engine::widgets::secondary_pill_button_in( + ctx, + pal, + WidgetId::from_pair("set_eq_preset", idx), + r, + None, + preset.name, + is_match, + ); + if resp.clicked { + enabled = true; + bands = preset.gains; + changed = true; + } + px = r.right() + 6.0; + } + cy += 42.0; + + // 10 vertical band sliders + let col_w = (eq_inner.width() / 10.0).min(64.0); + for i in 0..10 { + let bx = eq_inner.left() + i as f32 * col_w; + ctx.draw_text_ellipsis( + &format!("{:+.0}", bands[i]), + TextStyle::regular(11.5, pal.text_secondary), + Rect::from_xywh(bx, cy, col_w, 16.0), + TextAlign::Center, + ); + let sl_r = Rect::from_xywh(bx + col_w * 0.5 - 14.0, cy + 20.0, 28.0, 96.0); + let norm = ((bands[i] + 12.0) / 24.0).clamp(0.0, 1.0); + let sr = ym_vertical_slider( + ctx, + pal, + WidgetId::from_pair("set_eq_band", i), + sl_r, + norm, + false, + if enabled { pal.yellow } else { pal.text_primary }, + ); + if let Some(v) = sr.value { + let db = ((v * 24.0) - 12.0).round().clamp(-12.0, 12.0); + if (db - bands[i]).abs() >= 0.5 { + bands[i] = db; + enabled = true; + changed = true; + } + } + ctx.draw_text_ellipsis( + EQ_LABELS[i], + TextStyle::bold(11.5, pal.text_primary), + Rect::from_xywh(bx, cy + 120.0, col_w, 16.0), + TextAlign::Center, + ); + } + + if changed { + actions.push(AppAction::UpdateEq { enabled, bands }); } - lx = r.right() + 8.0; } - y += 52.0; + y += eq_h + 14.0; - ctx.dl() - .push_rect(Rect::from_xywh(x, y, col_w, 1.0), 0.0, pal.border_subtle); - y += 18.0; - - ctx.dl() - .push_rect(Rect::from_xywh(x, y, col_w, 1.0), 0.0, pal.border_subtle); - y += 18.0; - - if let Some(ref upd) = app.available_update { - let banner_r = Rect::from_xywh(x, y - 6.0, col_w, 54.0); - ctx.dl().push_rect_bordered( - banner_r, - 12.0, - pal.surface_secondary, - 1.0, - pal.yellow.with_alpha(120), - ); - let (dl_resp, dl_r) = yellow_pill_button( + // ------------------------------------------------------------------------- + // 5. Recommendations & Content (Less AI, Kids toggle) + // ------------------------------------------------------------------------- + let rec_h = 132.0; + let rec_inner = draw_settings_card( + ctx, + pal, + Rect::from_xywh(content_x, y, content_w, rec_h), + if ru { + "Рекомендации и разделы" + } else { + "Recommendations & Content" + }, + ); + { + let mut cy = rec_inner.top(); + if let Some(next) = settings_toggle_row( ctx, pal, - WidgetId::new("set_install_update"), - Pos2::new(banner_r.right() - 184.0, banner_r.center_y() - 17.0), + WidgetId::new("set_ai_red"), + Rect::from_xywh(rec_inner.left(), cy, rec_inner.width(), 32.0), + if ru { + "Меньше ИИ — реже показывать музыку, созданную с помощью ИИ" + } else { + "Less AI — reduce AI-generated music in recommendations" + }, + app.config.ai_content_reduction, + ) { + actions.push(AppAction::SetAiContentReduction(next)); + } + cy += 40.0; + if let Some(next) = settings_toggle_row( + ctx, + pal, + WidgetId::new("set_child_mode"), + Rect::from_xywh(rec_inner.left(), cy, rec_inner.width(), 32.0), + if ru { + "Показывать раздел «Детям»" + } else { + "Show «For Kids» section" + }, + app.config.child_mode, + ) { + actions.push(AppAction::SetChildMode(next)); + } + } + y += rec_h + 14.0; + + // ------------------------------------------------------------------------- + // 6. Keyboard Shortcuts + // ------------------------------------------------------------------------- + let shortcuts: &[(&str, &str, &str)] = &[ + ("Space / K", "Пауза / Воспроизведение", "Play / Pause"), + ("N / P", "Следующий / Предыдущий трек", "Next / Previous track"), + ("← / → (J / L)", "Перемотка ±2 сек", "Seek ±2 sec"), + ("↑ / ↓", "Громкость ±5%", "Volume ±5%"), + ("M", "Выключить / включить звук", "Mute / Unmute"), + ("F / D", "Нравится / Не нравится", "Like / Dislike"), + ("R / S", "Повтор / Перемешать", "Repeat / Shuffle"), + ("W", "Полноэкранный плеер", "Fullscreen player"), + ("Ctrl + F / Ctrl + L", "Поиск / Текст песни", "Search / Lyrics"), + ]; + let sc_h = 62.0 + shortcuts.len() as f32 * 26.0; + let sc_inner = draw_settings_card( + ctx, + pal, + Rect::from_xywh(content_x, y, content_w, sc_h), + if ru { + "Горячие клавиши" + } else { + "Keyboard shortcuts" + }, + ); + { + let mut cy = sc_inner.top(); + for (keys, desc_ru, desc_en) in shortcuts { + ctx.draw_text_ellipsis( + keys, + TextStyle::bold(13.0, pal.text_bright), + Rect::from_xywh(sc_inner.left(), cy, 175.0, 22.0), + TextAlign::Left, + ); + ctx.draw_text_ellipsis( + if ru { *desc_ru } else { *desc_en }, + TextStyle::regular(13.0, pal.text_secondary), + Rect::from_xywh(sc_inner.left() + 185.0, cy, sc_inner.width() - 185.0, 22.0), + TextAlign::Left, + ); + cy += 26.0; + } + } + y += sc_h + 14.0; + + // ------------------------------------------------------------------------- + // 7. About 5.129.0 & Cache + // ------------------------------------------------------------------------- + let about_h = 148.0; + let about_inner = draw_settings_card( + ctx, + pal, + Rect::from_xywh(content_x, y, content_w, about_h), + if ru { "О приложении" } else { "About" }, + ); + { + let mut cy = about_inner.top(); + let ver_str = if ru { + format!("Яндекс Музыка · Версия {}", APP_VERSION) + } else { + format!("Yandex Music · Version {}", APP_VERSION) + }; + ctx.draw_text_ellipsis( + &ver_str, + TextStyle::medium(14.0, pal.text_primary), + Rect::from_xywh(about_inner.left(), cy, about_inner.width(), 22.0), + TextAlign::Left, + ); + cy += 24.0; + let cache_str = if ru { + format!("© Яндекс · Кэш обложек: {} шт.", covers.len()) + } else { + format!("© Yandex · Cover cache: {} items", covers.len()) + }; + ctx.draw_text_ellipsis( + &cache_str, + TextStyle::regular(12.5, pal.text_secondary), + Rect::from_xywh(about_inner.left(), cy, about_inner.width(), 20.0), + TextAlign::Left, + ); + cy += 28.0; + + let (upd_resp, upd_r) = secondary_pill_button( + ctx, + pal, + WidgetId::new("set_check_updates"), + Pos2::new(about_inner.left(), cy), None, - t.download_update(), - 34.0, + if ru { + "Проверить обновления" + } else { + "Check for updates" + }, + 36.0, false, ); - let _ = dl_r; - if dl_resp.clicked { - actions.push(AppAction::InstallUpdate); + if upd_resp.clicked { + actions.push(AppAction::CheckForUpdates); } - let title_line = t.update_available_banner(&upd.version); - let sub_line = if upd.date.is_empty() { - t.whats_new().to_string() - } else { - upd.date.clone() - }; - let txt_w = (banner_r.width() - 208.0).max(100.0); - ctx.draw_text_ellipsis( - &title_line, - TextStyle::bold(13.5, pal.text_bright), - Rect::from_xywh(banner_r.left() + 14.0, banner_r.top() + 9.0, txt_w, 18.0), - TextAlign::Left, - ); - ctx.draw_text_ellipsis( - &sub_line, - TextStyle::regular(12.0, pal.text_secondary), - Rect::from_xywh(banner_r.left() + 14.0, banner_r.top() + 28.0, txt_w, 16.0), - TextAlign::Left, - ); - y += 62.0; - } - - // Footer action pills: Check updates + What's new + Repo link - let (chk_resp, chk_r) = secondary_pill_button( - ctx, - pal, - WidgetId::new("set_check_updates"), - Pos2::new(x, y), - None, - if ru { - "Проверить обновления" - } else { - "Check for updates" - }, - 34.0, - false, - ); - if chk_resp.clicked { - actions.push(AppAction::CheckForUpdates); - } - let (wn_resp, _) = secondary_pill_button( - ctx, - pal, - WidgetId::new("set_whats_new"), - Pos2::new(chk_r.right() + 10.0, y), - None, - t.whats_new(), - 34.0, - false, - ); - if wn_resp.clicked { - actions.push(AppAction::OpenReleaseNotesModal); - } - y += 44.0; - - let repo_label = "git.tatar/marwy/yandex-music-rs"; - let repo_w = ctx - .measure_text(repo_label, TextStyle::medium(12.5, pal.text_secondary), None) - .x - + 8.0; - let repo_r = Rect::from_xywh(x, y, repo_w.min(col_w), 20.0); - let repo_resp = ctx.interact(WidgetId::new("set_repo_link"), repo_r); - ctx.draw_text_ellipsis( - repo_label, - TextStyle::medium( - 12.5, - if repo_resp.hovered { - pal.text_bright + let (clr_resp, _) = secondary_pill_button( + ctx, + pal, + WidgetId::new("set_clear_cache"), + Pos2::new(upd_r.right() + 10.0, cy), + None, + if ru { + "Очистить кэш обложек" } else { - pal.text_secondary + "Clear cover cache" }, - ), - repo_r, - TextAlign::Left, - ); - if repo_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); + 36.0, + false, + ); + if clr_resp.clicked { + actions.push(AppAction::ClearCoverCache); + } } - if repo_resp.clicked { - actions.push(AppAction::OpenUrl( - "https://git.tatar/marwy/yandex-music-rs".into(), - )); - } - y += 38.0; + y += about_h + 28.0; let total_content_h = y - (rect.top() - scroll_y); ctx.end_scroll_v(scroll_id, pal, total_content_h, true); } -/// Official `SettingsListButtonItem` (`29c95960ed6ac633.css:74-119`): -/// Borderless row with NO hover background fill — 16px title, optional wrapped 14px description, -/// and right-aligned `arrowRight` chevron that glides +6px right on hover. -#[allow(clippy::too_many_arguments)] -fn settings_button_item( - ctx: &mut UiContext, - pal: &YmPalette, - id: WidgetId, - x: f32, - y: &mut f32, - w: f32, - title: &str, - description: Option<&str>, - dot_color: Option, -) -> bool { - let text_w = (w - 36.0).max(100.0); - let desc_h = description.map_or(0.0, |d| { - ctx.measure_text(d, TextStyle::regular(14.0, pal.text_secondary), Some(text_w)) - .y - .max(18.0) - + 4.0 - }); - let row_h = (22.0 + desc_h).max(26.0); - let hit_r = Rect::from_xywh(x, *y - 2.0, w, row_h + 4.0); - let resp = ctx.interact(id, hit_r); - let hover_t = ctx.animate_bool(id.with("hov"), resp.hovered, 0.16); - - if resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - +/// Renders a theme-aware settings section card and returns its inner body `Rect` below the heading. +fn draw_settings_card(ctx: &mut UiContext, pal: &YmPalette, rect: Rect, heading: &str) -> Rect { + ctx.dl() + .push_rect_bordered(rect, 14.0, pal.surface_secondary, 1.0, pal.border_subtle); + let inner_x = rect.left() + 18.0; + let inner_w = (rect.width() - 36.0).max(100.0); ctx.draw_text_ellipsis( - title, - TextStyle::medium(16.0, pal.text_bright), - Rect::from_xywh(x, *y, text_w, 22.0), + heading, + TextStyle::bold(16.0, pal.text_bright), + Rect::from_xywh(inner_x, rect.top() + 16.0, inner_w, 22.0), TextAlign::Left, ); - if let Some(desc) = description { - ctx.draw_text_wrapped( - desc, - TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, *y + 24.0, text_w, desc_h), - None, - TextAlign::Left, - ); - } - - if let Some(dc) = dot_color { - ctx.dl() - .push_circle(Pos2::new(x + w - 34.0, *y + 11.0), 4.0, dc); - } - - let chev_x = x + w - 12.0 + hover_t * 6.0; - ctx.draw_icon( - Icon::MenuArrowXxs, - Rect::from_center_size(Pos2::new(chev_x, *y + 11.0), Vec2::splat(16.0)), - if resp.hovered { - pal.text_bright - } else { - pal.text_secondary - }, - ); - - *y += row_h + 28.0; - resp.clicked + Rect::from_xywh( + inner_x, + rect.top() + 46.0, + inner_w, + (rect.height() - 62.0).max(0.0), + ) } -/// Official `SettingsListToggleItem` (`29c95960ed6ac633.css:120-136`): -/// Borderless row with 16px title, optional wrapped 14px description, and right-aligned pill toggle. -#[allow(clippy::too_many_arguments)] -fn settings_toggle_item( +/// Interactive pill toggle switch row (100% theme-aware). Returns `Some(new_val)` when toggled. +fn settings_toggle_row( ctx: &mut UiContext, pal: &YmPalette, id: WidgetId, - x: f32, - y: &mut f32, - w: f32, - title: &str, - description: Option<&str>, + rect: Rect, + label: &str, checked: bool, ) -> Option { - let text_w = (w - 60.0).max(100.0); - let desc_h = description.map_or(0.0, |d| { - ctx.measure_text(d, TextStyle::regular(14.0, pal.text_secondary), Some(text_w)) - .y - .max(18.0) - + 4.0 - }); - let row_h = (22.0 + desc_h).max(26.0); - let hit_r = Rect::from_xywh(x, *y - 2.0, w, row_h + 4.0); - let resp = ctx.interact(id, hit_r); - let anim = ctx.animate_bool(id.with("tog"), checked, 0.16); + let resp = ctx.interact(id, rect); + let anim = ctx.animate_bool(id.with("tog"), checked, 0.18); ctx.draw_text_ellipsis( - title, - TextStyle::medium(16.0, pal.text_bright), - Rect::from_xywh(x, *y, text_w, 22.0), + label, + TextStyle::regular(14.0, pal.text_primary), + Rect::from_xywh(rect.left(), rect.top(), (rect.width() - 56.0).max(40.0), rect.height()), TextAlign::Left, ); - if let Some(desc) = description { - ctx.draw_text_wrapped( - desc, - TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, *y + 24.0, text_w, desc_h), - None, - TextAlign::Left, - ); - } - let sw_w = 32.0; - let sw_h = 20.0; + let sw_w = 42.0; + let sw_h = 24.0; let sw_r = Rect::from_xywh( - x + w - sw_w, - *y + (row_h - sw_h) * 0.5, + rect.right() - sw_w, + rect.center_y() - sw_h * 0.5, sw_w, sw_h, ); - let track_col = pal.surface_hover.lerp(pal.yellow, anim); + let track_col = pal.border_control.lerp(pal.yellow, anim); ctx.dl().push_rect(sw_r, sw_h * 0.5, track_col); - let knob_x = sw_r.left() + 10.0 + anim * 12.0; + let knob_x = sw_r.left() + 12.0 + anim * (sw_w - 24.0); let knob_col = if anim > 0.5 { pal.on_yellow - } else if resp.hovered { - pal.text_bright } else { - pal.text_secondary + pal.text_bright }; ctx.dl() - .push_circle(Pos2::new(knob_x, sw_r.center_y()), 8.0, knob_col); + .push_circle(Pos2::new(knob_x, sw_r.center_y()), 8.5, knob_col); if resp.hovered { ctx.set_cursor(CursorKind::Pointer); } - *y += row_h + 28.0; if resp.clicked { Some(!checked) } else { diff --git a/src/views/sidebar.rs b/src/views/sidebar.rs index b8f38d9..8159571 100644 --- a/src/views/sidebar.rs +++ b/src/views/sidebar.rs @@ -1,8 +1,9 @@ use crate::app::{AppAction, AppState, Route}; -use crate::config::{Language, PinnedItem, ThemeMode}; +use crate::config::{PinnedItem, ThemeMode}; use crate::covers::CoverCache; use crate::engine::widgets::{ draw_cover_art, draw_plus_avatar_ring, draw_plus_badge, ym_menu_frame, ym_menu_item, + ym_menu_item_ex, }; use crate::engine::{ css_rgba, Color, CursorKind, Pos2, Rect, TextAlign, TextStyle, UiContext, Vec2, WidgetId, @@ -80,58 +81,42 @@ pub fn render_sidebar( } } - // Exact 5.129.0 `.NavbarDesktop_collapseButton__XQh9d` (`f43a2cc01fed8ead.css:157-198`): - // - 16×28px pill (`width: 1rem`, `border-radius: 6px`), `margin-inline-end: -8px` overhanging - // right onto the sidebar/content seam on `ZLayer::Drawer` (`z-index: header`) so the content - // card never clips its right half! - // - Smooth 0.20s opacity fade on sidebar OR button hover; 16×16 `xxs` chevron inside; - // tooltip ("Развернуть"/"Expand") shown ONLY when collapsed (`enabled: s`). - let col_btn_rect = Rect::from_center_size( - Pos2::new(sidebar_rect.right(), sidebar_rect.top() + 20.0), - Vec2::new(16.0, 28.0), - ); - let show_col_target = - !app.fullscreen_open && (ctx.is_hovered(sidebar_rect) || ctx.is_hovered(col_btn_rect)); - let col_vis = ctx.animate_bool(WidgetId::new("sb_col_vis"), show_col_target, 0.20); - if col_vis > 0.01 { - ctx.with_layer(ZLayer::Drawer, |ctx| { - let col_resp = ctx.interact(WidgetId::new("sb_collapse"), col_btn_rect); - let bg_col = if col_resp.hovered { + // Collapse button on hover (`.NavbarDesktop_collapseButton`: 16×28px pill, 6px radius) + let sidebar_hovered = ctx.is_hovered(sidebar_rect); + if sidebar_hovered { + let col_btn_rect = Rect::from_center_size( + Pos2::new(sidebar_rect.right() - 8.0, sidebar_rect.top() + 22.0), + Vec2::new(16.0, 28.0), + ); + let col_resp = ctx.interact(WidgetId::new("sb_collapse"), col_btn_rect); + ctx.dl().push_rect( + col_btn_rect, + 6.0, + if col_resp.hovered { pal.surface_hover } else { pal.surface_secondary - } - .scale_alpha(col_vis); - let icon_col = if col_resp.hovered { + }, + ); + ctx.draw_icon( + if collapsed { + Icon::ArrowRightXxs + } else { + Icon::ArrowLeftXxs + }, + Rect::from_center_size(col_btn_rect.center(), Vec2::splat(20.0)), + if col_resp.hovered { pal.text_primary } else { - Color::rgb(0x80, 0x80, 0x80) - } - .scale_alpha(col_vis); - - ctx.dl().push_rect(col_btn_rect, 6.0, bg_col); - ctx.draw_icon( - if collapsed { - Icon::ArrowRightXxs - } else { - Icon::ArrowLeftXxs - }, - Rect::from_center_size(col_btn_rect.center(), Vec2::splat(16.0)), - icon_col, - ); - if col_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - if collapsed { - ctx.show_tooltip( - col_btn_rect, - if ru { "Развернуть" } else { "Expand" }, - ); - } - } - if col_resp.clicked { - actions.push(AppAction::ToggleSidebarCollapse); - } - }); + pal.text_secondary + }, + ); + if col_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if col_resp.clicked { + actions.push(AppAction::ToggleSidebarCollapse); + } } // 2. Navigation Items (exact 5.129.0 order + optional Kids section) @@ -303,8 +288,6 @@ pub fn render_sidebar( }; let cover_rect = Rect::from_center_size(cover_center, Vec2::splat(40.0)); let is_circle = pin.kind == "artist" || is_wave; - let is_likes_art = pin.kind == "likes" - || (pin.kind == "playlist" && pin.id.ends_with(":3") && pin.cover_uri.is_none()); draw_cover_art( ctx, pal, @@ -314,7 +297,7 @@ pub fn render_sidebar( &pin.id, 4.0, is_circle, - is_likes_art, + pin.kind == "likes", ); // Hover Play/Pause overlay on ALL pinned items (playlists, albums, favorites, artists & waves!) @@ -381,7 +364,7 @@ pub fn render_sidebar( if show_labels { let text_x = item_r.left() + 54.0; let show_more = resp.hovered || menu_open_for_this; - let right_reserve = if show_more { 38.0 } else { 10.0 }; + let right_reserve = if show_more { 30.0 } else { 8.0 }; let max_tw = (item_r.right() - text_x - right_reserve).max(40.0); let title_col = if is_active { @@ -402,16 +385,16 @@ pub fn render_sidebar( TextAlign::Left, ); - // `•••` menu button on hover or when menu open (12px breathing room from right edge!) + // `•••` menu button on hover or when menu open (available on ALL pinned items, including Liked!) let more_r = Rect::from_center_size( - Pos2::new(item_r.right() - 20.0, item_r.center_y()), - Vec2::splat(26.0), + Pos2::new(item_r.right() - 14.0, item_r.center_y()), + Vec2::splat(24.0), ); let more_resp = ctx.interact(WidgetId::from_pair("sb_pin_more", pi), more_r); if show_more || more_resp.hovered { ctx.draw_icon( Icon::MoreXxs, - Rect::from_center_size(more_r.center(), Vec2::splat(18.0)), + Rect::from_center_size(more_r.center(), Vec2::splat(20.0)), if more_resp.hovered || menu_open_for_this { pal.text_primary } else { @@ -606,17 +589,7 @@ pub fn render_sidebar( } if shell.sidebar_profile_open { - render_profile_card_popup( - ctx, - pal, - covers, - app, - shell, - sidebar_rect, - footer_rect, - profile_hit, - actions, - ); + render_profile_card_popup(ctx, pal, app, shell, sidebar_rect, footer_rect, profile_hit, actions); } } @@ -643,14 +616,11 @@ fn is_pin_active_route(pin: &PinnedItem, app: &AppState) -> bool { } } -/// 1-to-1 Official Yandex ID `/music` Account Popup (v2.79.0) — Dark & Light themes, -/// exact surface/text/hover tokens, centered 56px Plus-ring avatar, dynamic Appearance icon, -/// Language popover (`ru`/`en`), and 3-way Appearance popover (`Всегда светлый` / `Всегда тёмный` / `Как в системе`). +/// 100% Theme-aware Yandex ID Profile Card Popup + 3-way Appearance Submenu (`Как в системе` / `Тёмная` / `Светлая`) #[allow(clippy::too_many_arguments)] fn render_profile_card_popup( ctx: &mut UiContext, pal: &YmPalette, - covers: &mut CoverCache, app: &AppState, shell: &mut ShellUiState, sidebar_rect: Rect, @@ -660,233 +630,118 @@ fn render_profile_card_popup( ) { let i18n = app.i18n(); let ru = i18n.is_ru(); - let is_dark = pal.is_dark; let has_plus = app.account.as_ref().map_or(false, |a| a.has_plus); let logged_in = app.account.is_some(); - // Exact Yandex ID v2.79.0 Surface & Color Tokens (`307ea1c94a69877eefe9.css`) - let card_bg = if is_dark { - Color::rgb(0x1F, 0x1F, 0x24) - } else { - Color::WHITE - }; - let card_border = if is_dark { - Color::rgb(0x33, 0x33, 0x33) - } else { - Color::rgb(0xE6, 0xE6, 0xE6) - }; - let popover_bg = if is_dark { - Color::rgb(0x2D, 0x2D, 0x34) - } else { - Color::WHITE - }; - let popover_border = if is_dark { - css_rgba(250, 250, 255, 26) - } else { - Color::rgb(0xE6, 0xE6, 0xE6) - }; - let id_text_primary = if is_dark { - Color::rgb(0xFA, 0xFA, 0xFF) - } else { - Color::rgb(0x26, 0x26, 0x33) - }; - let id_text_secondary = if is_dark { - css_rgba(240, 240, 255, 118) - } else { - Color::rgb(0x85, 0x88, 0x9E) - }; - let id_row_hover = if is_dark { - css_rgba(250, 250, 255, 20) - } else { - css_rgba(180, 184, 204, 36) - }; - let id_separator = if is_dark { - css_rgba(250, 250, 255, 22) - } else { - css_rgba(38, 38, 51, 22) - }; - let card_w = 320.0; - let header_h = if logged_in { 144.0 } else { 198.0 }; - let group1_h = 54.0 + if logged_in { 44.0 * 5.0 } else { 44.0 * 3.0 }; - let sep_h = 13.0; // 6px top + 1px line + 6px bottom - let group2_h = 44.0; - let group3_h = if logged_in { sep_h + 44.0 * 2.0 } else { 0.0 }; - let card_h = header_h + group1_h + sep_h + group2_h + group3_h + 10.0; + let header_h = if logged_in { 88.0 } else { 154.0 }; + let rows_h = 50.0 // Plus row with subtitle + + 40.0 * 4.0 // Account, Settings, Support, Language + + 13.0 // divider + + 40.0 // Appearance + + if logged_in { 40.0 } else { 0.0 }; // Sign out + let card_h = 20.0 + header_h + rows_h + 20.0; let screen = ctx.screen_rect(); let card_x = (sidebar_rect.left() + 20.0).min((screen.right() - card_w - 12.0).max(8.0)); - let card_y = - (footer_rect.top() - card_h - 10.0).clamp(40.0, (screen.bottom() - card_h - 12.0).max(40.0)); + let card_y = (footer_rect.top() - card_h - 10.0).clamp(40.0, (screen.bottom() - card_h - 12.0).max(40.0)); let card_rect = Rect::from_xywh(card_x, card_y, card_w, card_h); let mut close_popup = false; - let mut lang_row_rect = Rect::ZERO; let mut appearance_row_rect = Rect::ZERO; ctx.with_layer(ZLayer::Popover, |ctx| { ctx.register_blocker(card_rect); - // Card container: exact `24px` radius, `card_bg`, `1px` `card_border`, elevation shadow + // Card container: exact `pal.profile_bg` (`#121212` dark / `#FFFFFF` light) + `pal.border_control`! ctx.dl() - .push_shadow(card_rect, 24.0, 28.0, 0.0, Vec2::new(0.0, 8.0), pal.shadow_modal); + .push_shadow(card_rect, 24.0, 24.0, 0.0, Vec2::new(0.0, 6.0), pal.shadow_modal); ctx.dl() - .push_rect_bordered(card_rect, 24.0, card_bg, 1.0, card_border); + .push_rect_bordered(card_rect, 24.0, pal.profile_bg, 1.0, pal.border_control); - // 1. Top Overlay Bar (`_overlap_1v1kx_1`): 41×20 Yandex ID vector logo + 32×32 circular Close `×` - let logo_r = Rect::from_xywh(card_rect.left() + 16.0, card_rect.top() + 16.0, 41.0, 20.0); - let logo_icon = match (ru, is_dark) { - (true, true) => Icon::YandexIdLogoRuDark, - (true, false) => Icon::YandexIdLogoRuLight, - (false, true) => Icon::YandexIdLogoEnDark, - (false, false) => Icon::YandexIdLogoEnLight, - }; - let logo_resp = ctx.interact(WidgetId::new("prof_yid_logo"), logo_r); - ctx.draw_icon(logo_icon, logo_r, Color::WHITE); - if logo_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if logo_resp.clicked { - actions.push(AppAction::OpenUrl("https://id.yandex.ru".into())); - close_popup = true; - } + let inner = card_rect.shrink(20.0); + let mut y = inner.top(); - let close_r = Rect::from_xywh(card_rect.right() - 44.0, card_rect.top() + 10.0, 32.0, 32.0); + // Top row: Yandex ID badge + Close `×` + let badge_cy = y + 11.0; + ctx.dl() + .push_circle(Pos2::new(inner.left() + 11.0, badge_cy), 10.0, Color::rgb(0xFC, 0x3F, 0x1D)); + ctx.draw_text_ellipsis( + if ru { "Я" } else { "Y" }, + TextStyle::bold(12.0, Color::WHITE), + Rect::from_center_size(Pos2::new(inner.left() + 11.0, badge_cy), Vec2::splat(20.0)), + TextAlign::Center, + ); + let id_pill = Rect::from_xywh(inner.left() + 24.0, y + 1.0, 24.0, 20.0); + ctx.dl().push_rect(id_pill, 6.0, pal.text_bright); + ctx.draw_text_ellipsis( + "ID", + TextStyle::bold(11.0, pal.profile_bg), + id_pill, + TextAlign::Center, + ); + + let close_r = Rect::from_xywh(inner.right() - 26.0, y - 2.0, 26.0, 26.0); let close_resp = ctx.interact(WidgetId::new("prof_card_close"), close_r); if close_resp.hovered { - ctx.dl().push_circle(close_r.center(), 16.0, id_row_hover); + ctx.dl().push_circle(close_r.center(), 13.0, pal.surface_hover); ctx.set_cursor(CursorKind::Pointer); } ctx.draw_icon( Icon::Close, - Rect::from_center_size(close_r.center(), Vec2::splat(18.0)), - if close_resp.hovered { - id_text_primary - } else { - id_text_secondary - }, + Rect::from_center_size(close_r.center(), Vec2::splat(16.0)), + pal.text_primary, ); if close_resp.clicked { close_popup = true; } - // 2. Header: Logged In (`cv`) vs Logged Out (`Av`) - let mut y = card_rect.top() + header_h; - if let Some(ref acc) = app.account { - let avatar_center = Pos2::new(card_rect.center_x(), card_rect.top() + 20.0 + 28.0); - if acc.has_plus { - draw_plus_avatar_ring(ctx, avatar_center, 31.0, 2.0); - ctx.dl().push_circle(avatar_center, 29.0, card_bg); - } - let av_rect = Rect::from_center_size(avatar_center, Vec2::splat(56.0)); - if acc.avatar_uri.is_some() { - draw_cover_art( - ctx, - pal, - covers, - av_rect, - acc.avatar_uri.as_deref(), - "profile_popup_avatar", - 28.0, - true, - false, - ); - } else { - ctx.dl().push_circle( - avatar_center, - 28.0, - if is_dark { - Color::rgb(0x32, 0x32, 0x3B) - } else { - Color::rgb(0xEB, 0xEC, 0xF2) - }, - ); - let initial = acc - .display_name - .chars() - .next() - .or_else(|| acc.login.chars().next()) - .unwrap_or(if ru { 'Я' } else { 'Y' }) - .to_uppercase() - .to_string(); - ctx.draw_text_ellipsis( - &initial, - TextStyle::bold(22.0, id_text_primary), - av_rect, - TextAlign::Center, - ); - } + y += 32.0; - let name_y = card_rect.top() + 20.0 + 56.0 + 10.0; + // Account info OR Guest login prompt + if let Some(ref acc) = app.account { ctx.draw_text_ellipsis( &acc.display_name, - TextStyle::bold(16.0, id_text_primary), - Rect::from_center_size(Pos2::new(card_rect.center_x(), name_y + 11.0), Vec2::new(260.0, 22.0)), - TextAlign::Center, - ); - - let sub_y = name_y + 22.0 + 2.0; - let contact_str = acc - .default_email - .as_deref() - .filter(|s| !s.is_empty()) - .unwrap_or(&acc.login); - ctx.draw_text_ellipsis( - contact_str, - TextStyle::regular(13.0, id_text_secondary), - Rect::from_center_size(Pos2::new(card_rect.center_x(), sub_y + 9.0), Vec2::new(260.0, 18.0)), - TextAlign::Center, - ); - } else { - let hx = card_rect.left() + 16.0; - let hw = card_w - 32.0; - let mut hy = card_rect.top() + 52.0; - - let title = if ru { "Войдите в аккаунт" } else { "Log in" }; - ctx.draw_text_ellipsis( - title, - TextStyle::bold(20.0, id_text_primary), - Rect::from_xywh(hx, hy, hw, 28.0), + TextStyle::bold(20.0, pal.text_bright), + Rect::from_xywh(inner.left(), y, inner.width(), 26.0), TextAlign::Left, ); - hy += 34.0; - - let subtitle = if ru { - "Чтобы сохранить свои закладки, пароли и карты" - } else { - "To save your bookmarks, passwords, and cards" - }; + y += 26.0; + ctx.draw_text_ellipsis( + &format!("@{}", acc.login), + TextStyle::regular(13.0, pal.text_secondary), + Rect::from_xywh(inner.left(), y, inner.width(), 18.0), + TextAlign::Left, + ); + y += 30.0; + } else { + ctx.draw_text_ellipsis( + i18n.log_in(), + TextStyle::bold(22.0, pal.text_bright), + Rect::from_xywh(inner.left(), y, inner.width(), 28.0), + TextAlign::Left, + ); + y += 30.0; ctx.draw_text_wrapped( - subtitle, - TextStyle::regular(13.0, id_text_secondary), - Rect::from_xywh(hx, hy, hw, 36.0), + i18n.login_subtitle(), + TextStyle::regular(13.0, pal.text_secondary), + Rect::from_xywh(inner.left(), y, inner.width(), 34.0), Some(2), TextAlign::Left, ); - hy += 52.0; + y += 40.0; - let btn_r = Rect::from_xywh(hx, hy, hw, 44.0); + let btn_r = Rect::from_xywh(inner.left(), y, inner.width(), 42.0); let btn_resp = ctx.interact(WidgetId::new("prof_login_btn"), btn_r); - let btn_bg = if is_dark { - if btn_resp.hovered { - Color::rgb(0xE8, 0xE8, 0xF2) - } else { - Color::rgb(0xFA, 0xFA, 0xFF) - } - } else if btn_resp.hovered { - Color::rgb(0x3B, 0x3B, 0x47) + let btn_bg = if btn_resp.hovered { + pal.text_primary } else { - Color::rgb(0x29, 0x29, 0x33) + pal.text_bright }; - let btn_fg = if is_dark { - Color::rgb(0x1F, 0x1F, 0x24) - } else { - Color::WHITE - }; - ctx.dl().push_rect(btn_r, 12.0, btn_bg); + ctx.dl().push_rect(btn_r, 14.0, btn_bg); ctx.draw_text_ellipsis( - if ru { "Войти" } else { "Log in" }, - TextStyle::bold(15.0, btn_fg), + i18n.log_in(), + TextStyle::bold(15.0, pal.profile_bg), btn_r, TextAlign::Center, ); @@ -897,506 +752,242 @@ fn render_profile_card_popup( actions.push(AppAction::SetLoginModalOpen(true)); close_popup = true; } + y += 52.0; } - // Helper for exact Yandex ID v2.79.0 menu rows (`padding: 0 8px`, `radius: 12px`, `24px` icon @ `+12px`, text @ `+48px`) - let row_x = card_rect.left() + 8.0; - let row_w = card_w - 16.0; - let draw_id_row = |ctx: &mut UiContext, - id: &str, - y_pos: f32, - row_h: f32, - ic: Icon, - ic_tint: Color, - title: &str, - subtitle: Option<&str>, - has_chevron: bool, - active: bool, - right_plus_badge: Option<&str>| + // Helper for 100% theme-aware Yandex ID card rows + let draw_profile_row = |ctx: &mut UiContext, + id: &str, + y_pos: f32, + ic: Icon, + title: &str, + subtitle: Option<&str>, + has_chevron: bool, + active: bool| -> (bool, bool, Rect) { - let r = Rect::from_xywh(row_x, y_pos, row_w, row_h); + let h = if subtitle.is_some() { 50.0 } else { 40.0 }; + let r = Rect::from_xywh(inner.left(), y_pos, inner.width(), h); let resp = ctx.interact(WidgetId::new(id), r); if resp.hovered || active { - ctx.dl().push_rect(r, 12.0, id_row_hover); + ctx.dl().push_rect(r, 12.0, pal.surface_hover); } if resp.hovered { ctx.set_cursor(CursorKind::Pointer); } ctx.draw_icon( ic, - Rect::from_center_size(Pos2::new(r.left() + 24.0, r.center_y()), Vec2::splat(24.0)), - ic_tint, + Rect::from_center_size(Pos2::new(r.left() + 18.0, r.center_y()), Vec2::splat(20.0)), + pal.text_primary, ); - let tx = r.left() + 48.0; - let right_reserve = if right_plus_badge.is_some() { - 68.0 - } else if has_chevron { - 32.0 - } else { - 12.0 - }; - let tw = (r.right() - tx - right_reserve).max(40.0); + let tx = r.left() + 42.0; + let tw = (r.right() - tx - if has_chevron { 28.0 } else { 8.0 }).max(40.0); if let Some(sub) = subtitle { ctx.draw_text_ellipsis( title, - TextStyle::medium(14.5, id_text_primary), - Rect::from_xywh(tx, r.top() + 8.0, tw, 20.0), + TextStyle::medium(14.0, pal.text_primary), + Rect::from_xywh(tx, r.top() + 6.0, tw, 19.0), TextAlign::Left, ); ctx.draw_text_ellipsis( sub, - TextStyle::regular(12.5, id_text_secondary), - Rect::from_xywh(tx, r.top() + 29.0, tw, 17.0), + TextStyle::regular(12.0, pal.text_secondary), + Rect::from_xywh(tx, r.top() + 26.0, tw, 17.0), TextAlign::Left, ); } else { ctx.draw_text_ellipsis( title, - TextStyle::medium(14.5, id_text_primary), + TextStyle::medium(14.0, pal.text_primary), Rect::from_xywh(tx, r.top(), tw, r.height()), TextAlign::Left, ); } - if let Some(badge_txt) = right_plus_badge { - let bw = (ctx.measure_text(badge_txt, TextStyle::bold(11.5, Color::WHITE), None).x - + 18.0) - .max(46.0); - let br = Rect::from_xywh(r.right() - bw - 10.0, r.center_y() - 10.0, bw, 20.0); - ctx.dl().push_plus_gradient_rect(br, 10.0, 1.0); - ctx.draw_text_ellipsis( - badge_txt, - TextStyle::bold(11.5, Color::WHITE), - br, - TextAlign::Center, - ); - } else if has_chevron { + if has_chevron { ctx.draw_icon( Icon::MenuArrowXxs, - Rect::from_center_size(Pos2::new(r.right() - 16.0, r.center_y()), Vec2::splat(20.0)), - id_text_secondary, + Rect::from_center_size(Pos2::new(r.right() - 14.0, r.center_y()), Vec2::splat(20.0)), + pal.text_secondary, ); } (resp.clicked, resp.hovered, r) }; - let draw_separator = |ctx: &mut UiContext, y_pos: f32| { - ctx.dl().push_rect( - Rect::from_xywh(card_rect.left() + 16.0, y_pos + 6.0, card_w - 32.0, 1.0), - 0.0, - id_separator, - ); - }; - - // 3. Menu Group 1 (`r.Menu`) - // Row 1 — Plus (`54px`) - let (plus_title, plus_sub, plus_pill) = if has_plus { - ( - if ru { "Плюс" } else { "Plus" }, - if ru { - "Подписка активна" - } else { - "Subscription is active" - }, - Some(if ru { "Плюс" } else { "Plus" }), - ) + // Row 1: Yandex Plus + let plus_title = if has_plus { + if ru { "Яндекс Плюс" } else { "Yandex Plus" } + } else if ru { + "Подключить Яндекс Плюс" } else { - ( - if ru { - "Подключить Плюс" - } else { - "Connect Yandex Plus" - }, - if ru { - "Все развлечения и выгода в одной подписке" - } else { - "All the fun and benefits in one subscription" - }, - None, - ) + "Connect Yandex Plus" }; - let (c, h, _) = draw_id_row( - ctx, - "prof_plus", - y, - 54.0, - Icon::ProfilePlusXxs, - Color::WHITE, // multi-stop gradient SVG - plus_title, - Some(plus_sub), - false, - false, - plus_pill, - ); - if h { - shell.sidebar_lang_open = false; - shell.sidebar_appearance_open = false; - } - if c { + let plus_sub = if ru { + "Все преимущества в одной подписке" + } else { + "All the fun and benefits in one subscription" + }; + if draw_profile_row(ctx, "prof_plus", y, Icon::Plus, plus_title, Some(plus_sub), false, false).0 { actions.push(AppAction::OpenUrl("https://plus.yandex.ru".into())); close_popup = true; } - y += 54.0; + y += 50.0; - // Row 2 — Account management (logged in) - if logged_in { - let (c, h, _) = draw_id_row( - ctx, - "prof_account", - y, - 44.0, - Icon::ProfileAccountXxs, - id_text_primary, - if ru { - "Управление аккаунтом" - } else { - "Account management" - }, - None, - false, - false, - None, - ); - if h { - shell.sidebar_lang_open = false; - shell.sidebar_appearance_open = false; - } - if c { - actions.push(AppAction::OpenUrl("https://id.yandex.ru".into())); - close_popup = true; - } - y += 44.0; - - // Row 3 — Settings (logged in) - let (c, h, _) = draw_id_row( - ctx, - "prof_settings", - y, - 44.0, - Icon::ProfileSettingsXxs, - id_text_primary, - if ru { "Настройки" } else { "Settings" }, - None, - false, - false, - None, - ); - if h { - shell.sidebar_lang_open = false; - shell.sidebar_appearance_open = false; - } - if c { - actions.push(AppAction::Navigate(Route::Settings)); - close_popup = true; - } - y += 44.0; + // Row 2: Account management (dedicated `ProfileAccountXxs`) + if draw_profile_row( + ctx, + "prof_account", + y, + Icon::ProfileAccountXxs, + i18n.account_management(), + None, + false, + false, + ) + .0 + { + actions.push(AppAction::OpenUrl("https://id.yandex.ru".into())); + close_popup = true; } + y += 40.0; - // Row 4 — Support chat (paper-plane) - let (c, h, _) = draw_id_row( + // Row 3: Settings (`SettingsXxs`) + if draw_profile_row( + ctx, + "prof_settings", + y, + Icon::SettingsXxs, + i18n.settings(), + None, + false, + false, + ) + .0 + { + actions.push(AppAction::Navigate(Route::Settings)); + close_popup = true; + } + y += 40.0; + + // Row 4: Support chat (`ProfileSupportXxs`) + if draw_profile_row( ctx, "prof_support", y, - 44.0, Icon::ProfileSupportXxs, - id_text_primary, - if ru { - "Чат с поддержкой" - } else { - "Chat with support" - }, + i18n.support_chat(), None, false, false, - None, - ); - if h { - shell.sidebar_lang_open = false; - shell.sidebar_appearance_open = false; - } - if c { - actions.push(AppAction::OpenUrl( - "https://yandex.ru/support/plus/help/ru/?utm_source=music".into(), - )); + ) + .0 + { + actions.push(AppAction::OpenUrl("https://yandex.ru/support/music/".into())); close_popup = true; } - y += 44.0; + y += 40.0; - // Row 4b — What's new (ReleaseNotesModal) - let (c, h, wn_r) = draw_id_row( - ctx, - "prof_whats_new", - y, - 44.0, - Icon::AiSparkles, - id_text_primary, - i18n.whats_new(), - None, - false, - false, - None, - ); - if app.available_update.is_some() { - ctx.dl() - .push_circle(Pos2::new(wn_r.right() - 18.0, wn_r.center_y()), 4.0, pal.yellow); - } - if h { - shell.sidebar_lang_open = false; - shell.sidebar_appearance_open = false; - } - if c { - actions.push(AppAction::OpenReleaseNotesModal); - close_popup = true; - } - y += 44.0; - - // Row 5 — Language (opens Yandex ID Language Popover!) - let (lang_clicked, lang_hovered, lang_r) = draw_id_row( + // Row 5: Language (`ProfileGlobeXxs`) + if draw_profile_row( ctx, "prof_lang", y, - 44.0, Icon::ProfileGlobeXxs, - id_text_primary, - if ru { "Русский" } else { "English" }, + i18n.language_name(), None, - true, - shell.sidebar_lang_open, - None, - ); - lang_row_rect = lang_r; - if lang_clicked { - shell.sidebar_lang_open = !shell.sidebar_lang_open; - if shell.sidebar_lang_open { - shell.sidebar_appearance_open = false; - } - } else if lang_hovered { - shell.sidebar_lang_open = true; - shell.sidebar_appearance_open = false; + false, + false, + ) + .0 + { + actions.push(AppAction::ToggleLanguage); + close_popup = true; } - y += 44.0; + y += 40.0; - // 4. Hairline Separator 1 - draw_separator(ctx, y); - y += sep_h; + // Divider + ctx.dl() + .push_rect(Rect::from_xywh(inner.left(), y + 6.0, inner.width(), 1.0), 0.0, pal.border_control); + y += 13.0; - // 5. Menu Group 2 (`r.Submenu`) — Appearance (dynamic icon matching current theme!) - let theme_row_icon = match app.config.theme { - ThemeMode::Light => Icon::ThemeLightXxs, - ThemeMode::Dark => Icon::ThemeDarkXxs, - ThemeMode::System => Icon::ThemeSystemXxs, - }; - let (app_clicked, app_hovered, app_r) = draw_id_row( + // Row 6: Appearance (`ProfileAppearanceXxs`) -> opens 3-way Appearance submenu! + let (app_clicked, app_hovered, app_rect) = draw_profile_row( ctx, "prof_appearance", y, - 44.0, - theme_row_icon, - id_text_primary, - if ru { "Внешний вид" } else { "Appearance" }, + Icon::ProfileAppearanceXxs, + i18n.appearance(), None, true, shell.sidebar_appearance_open, - None, ); - appearance_row_rect = app_r; + appearance_row_rect = app_rect; if app_clicked { shell.sidebar_appearance_open = !shell.sidebar_appearance_open; - if shell.sidebar_appearance_open { - shell.sidebar_lang_open = false; - } } else if app_hovered { shell.sidebar_appearance_open = true; - shell.sidebar_lang_open = false; } - y += 44.0; + y += 40.0; - // 6. Hairline Separator 2 + Account Actions (when logged in) - if logged_in { - draw_separator(ctx, y); - y += sep_h; - - // Row 7 — Add account - let (c, h, _) = draw_id_row( - ctx, - "prof_add_account", - y, - 44.0, - Icon::ProfileAddAccountXxs, - id_text_primary, - if ru { - "Добавить аккаунт" - } else { - "Add account" - }, - None, - false, - false, - None, - ); - if h { - shell.sidebar_lang_open = false; - shell.sidebar_appearance_open = false; - } - if c { - actions.push(AppAction::SetLoginModalOpen(true)); - close_popup = true; - } - y += 44.0; - - // Row 8 — Sign out - let (c, h, _) = draw_id_row( + // Row 7: Sign out (`ProfileLogoutXxs`) when logged in + if logged_in + && draw_profile_row( ctx, "prof_logout", y, - 44.0, Icon::ProfileLogoutXxs, - id_text_primary, - if ru { "Выйти" } else { "Sign out" }, + i18n.sign_out(), None, false, false, - None, - ); - if h { - shell.sidebar_lang_open = false; - shell.sidebar_appearance_open = false; - } - if c { - actions.push(AppAction::Logout); - close_popup = true; - } + ) + .0 + { + actions.push(AppAction::Logout); + close_popup = true; } - // 7A. Yandex ID Language Popover (`210px`, `radius: 16px`, `40px` items: `ru Русский` / `en English`) - let mut lang_sub_rect = Rect::ZERO; - if shell.sidebar_lang_open { - let sub_w = 210.0; - let sub_h = 40.0 * 2.0 + 16.0; - let sub_x = (card_rect.right() + 8.0).min((screen.right() - sub_w - 8.0).max(8.0)); - let sub_y = (lang_row_rect.top() - 8.0) - .clamp(40.0, (screen.bottom() - sub_h - 12.0).max(40.0)); - lang_sub_rect = Rect::from_xywh(sub_x, sub_y, sub_w, sub_h); - ctx.register_blocker(lang_sub_rect); - ctx.dl() - .push_shadow(lang_sub_rect, 16.0, 24.0, 0.0, Vec2::new(0.0, 6.0), pal.shadow_modal); - ctx.dl() - .push_rect_bordered(lang_sub_rect, 16.0, popover_bg, 1.0, popover_border); - - let sub_inner = lang_sub_rect.shrink(8.0); - let lang_opts = [ - (Language::Ru, "ru", "Русский", "lang_opt_ru"), - (Language::En, "en", "English", "lang_opt_en"), - ]; - for (idx, (lang, code, lbl, wid)) in lang_opts.into_iter().enumerate() { - let is_cur = app.config.language == lang; - let ir = Rect::from_xywh(sub_inner.x, sub_inner.y + idx as f32 * 40.0, sub_inner.w, 40.0); - let r = ctx.interact(WidgetId::new(wid), ir); - if r.hovered { - ctx.dl().push_rect(ir, 12.0, id_row_hover); - ctx.set_cursor(CursorKind::Pointer); - } - ctx.draw_text_ellipsis( - code, - TextStyle::bold(13.0, id_text_secondary), - Rect::from_xywh(ir.left() + 12.0, ir.top(), 24.0, ir.height()), - TextAlign::Left, - ); - ctx.draw_text_ellipsis( - lbl, - TextStyle::medium(14.0, id_text_primary), - Rect::from_xywh(ir.left() + 42.0, ir.top(), (ir.width() - 72.0).max(40.0), ir.height()), - TextAlign::Left, - ); - if is_cur { - ctx.draw_icon( - Icon::CheckXxs, - Rect::from_center_size(Pos2::new(ir.right() - 16.0, ir.center_y()), Vec2::splat(20.0)), - id_text_primary, - ); - } - if r.clicked { - actions.push(AppAction::SetLanguage(lang)); - shell.sidebar_lang_open = false; - } - } - } - - // 7B. Yandex ID Appearance Popover (`224px`, `radius: 16px`, `40px` items in exact official order!) - let mut app_sub_rect = Rect::ZERO; + // Appearance Submenu (`Как в системе` / `Тёмная` / `Светлая` + active `CheckXxs`!) + let mut submenu_rect = Rect::ZERO; if shell.sidebar_appearance_open { - let sub_w = 224.0; - let sub_h = 40.0 * 3.0 + 16.0; + let sub_w = 220.0; + let sub_h = 36.0 * 3.0 + 16.0; let sub_x = (card_rect.right() + 8.0).min((screen.right() - sub_w - 8.0).max(8.0)); let sub_y = (appearance_row_rect.top() - 8.0) .clamp(40.0, (screen.bottom() - sub_h - 12.0).max(40.0)); - app_sub_rect = Rect::from_xywh(sub_x, sub_y, sub_w, sub_h); - ctx.register_blocker(app_sub_rect); - ctx.dl() - .push_shadow(app_sub_rect, 16.0, 24.0, 0.0, Vec2::new(0.0, 6.0), pal.shadow_modal); - ctx.dl() - .push_rect_bordered(app_sub_rect, 16.0, popover_bg, 1.0, popover_border); + submenu_rect = Rect::from_xywh(sub_x, sub_y, sub_w, sub_h); - let sub_inner = app_sub_rect.shrink(8.0); + let sub_inner = ym_menu_frame(ctx, pal, submenu_rect); let theme_opts = [ - ( - ThemeMode::Light, - Icon::ThemeLightXxs, - if ru { "Всегда светлый" } else { "Always light" }, - "theme_opt_light", - ), - ( - ThemeMode::Dark, - Icon::ThemeDarkXxs, - if ru { "Всегда тёмный" } else { "Always dark" }, - "theme_opt_dark", - ), - ( - ThemeMode::System, - Icon::ThemeSystemXxs, - if ru { "Как в системе" } else { "System settings" }, - "theme_opt_sys", - ), + (ThemeMode::System, Icon::ThemeSystemXxs, i18n.theme_system(), "theme_opt_sys"), + (ThemeMode::Dark, Icon::ThemeDarkXxs, i18n.theme_dark(), "theme_opt_dark"), + (ThemeMode::Light, Icon::ThemeLightXxs, i18n.theme_light(), "theme_opt_light"), ]; for (idx, (mode, ic, lbl, wid)) in theme_opts.into_iter().enumerate() { let is_cur = app.config.theme == mode; - let ir = Rect::from_xywh(sub_inner.x, sub_inner.y + idx as f32 * 40.0, sub_inner.w, 40.0); - let r = ctx.interact(WidgetId::new(wid), ir); - if r.hovered { - ctx.dl().push_rect(ir, 12.0, id_row_hover); - ctx.set_cursor(CursorKind::Pointer); - } - ctx.draw_icon( + let ir = Rect::from_xywh(sub_inner.x, sub_inner.y + idx as f32 * 36.0, sub_inner.w, 36.0); + if ym_menu_item_ex( + ctx, + pal, + WidgetId::new(wid), + ir, ic, - Rect::from_center_size(Pos2::new(ir.left() + 20.0, ir.center_y()), Vec2::splat(20.0)), - id_text_primary, - ); - ctx.draw_text_ellipsis( lbl, - TextStyle::medium(14.0, id_text_primary), - Rect::from_xywh(ir.left() + 42.0, ir.top(), (ir.width() - 72.0).max(40.0), ir.height()), - TextAlign::Left, - ); - if is_cur { - ctx.draw_icon( - Icon::CheckXxs, - Rect::from_center_size(Pos2::new(ir.right() - 16.0, ir.center_y()), Vec2::splat(20.0)), - id_text_primary, - ); - } - if r.clicked { + is_cur, + is_cur, + false, + false, + ) + .clicked + { actions.push(AppAction::SetTheme(mode)); shell.sidebar_appearance_open = false; } } } - // Click outside profile card + open sub-popover + profile trigger button closes everything cleanly + // Click outside profile card + submenu + profile trigger button closes popup let mut keep_rects = vec![card_rect, profile_hit]; - if !lang_sub_rect.is_empty() { - keep_rects.push(lang_sub_rect); - } - if !app_sub_rect.is_empty() { - keep_rects.push(app_sub_rect); + if !submenu_rect.is_empty() { + keep_rects.push(submenu_rect); } if ctx.input.clicked_outside_any(&keep_rects) { close_popup = true; @@ -1406,6 +997,5 @@ fn render_profile_card_popup( if close_popup { shell.sidebar_profile_open = false; shell.sidebar_appearance_open = false; - shell.sidebar_lang_open = false; } } diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 37d343b..2d002bd 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -211,7 +211,6 @@ fn make_track( r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, } } @@ -399,7 +398,6 @@ fn build_reference_matched_shell( uid: 42, login: "marwy".into(), display_name: "Marwy".into(), - default_email: None, has_plus: true, avatar_uri: Some("test.local/avatar_marwy/%%".into()), }); diff --git a/tests/parity_extended.rs b/tests/parity_extended.rs index b8ae92f..4a464fa 100644 --- a/tests/parity_extended.rs +++ b/tests/parity_extended.rs @@ -105,7 +105,6 @@ fn make_base_shell( uid: 1, login: "Marwy".into(), display_name: "Marwy".into(), - default_email: Some("marwy@yandex.ru".into()), has_plus: true, avatar_uri: None, }); @@ -133,7 +132,6 @@ fn make_base_shell( r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, }; let track2 = Track { id: "t_2".into(), @@ -159,7 +157,6 @@ fn make_base_shell( r128_tp: None, derived_average_hex: None, derived_accent_hex: None, - fade: None, }; let landing = demo_data::demo_landing(); let app = AppState::new_visual_test( @@ -1676,932 +1673,3 @@ fn test_ext_15_opengl33_strict_shaders_and_renderer_backend() { ); } } - -#[test] -fn test_ext_16_yandex_id_popup_and_words_card_visual_parity() { - use yandex_music_rs::api::models::{WordsCard, WordsCardSource}; - use yandex_music_rs::engine::types::Pos2; - - let rt = tokio::runtime::Runtime::new().unwrap(); - let mut vk = HeadlessVulkanRenderer::new(NATIVE_W, NATIVE_H).expect("Vulkan init failed"); - let out_dir = output_dir(); - let _ = std::fs::create_dir_all(&out_dir); - - // 1. Dark Theme Yandex ID v2.79.0 Account Popup + Appearance Popover (`dark_profile_popup.png`) - { - let mut shell = make_base_shell( - rt.handle().clone(), - vk.gpu_name.clone(), - Route::LikedTracks, - ThemeMode::Dark, - Language::Ru, - 0.0, - ); - shell.shell.sidebar_profile_open = true; - shell.shell.sidebar_appearance_open = true; - let mut img = render_single_frame(&mut vk, &mut shell, 0.0); - for f in 1..3 { - img = render_single_frame(&mut vk, &mut shell, f as f64 * 0.016); - } - let _ = img.save(out_dir.join("dark_profile_popup.png")); - - // Verify `#1F1F24` dark Yandex ID card surface inside x=32..320, y=240..660 - let mut card_bg_px = 0usize; - let mut bright_text_px = 0usize; - for y in 240..660 { - for x in 32..320 { - let [r, g, b] = img.get_pixel(x, y).0; - if (r as i32 - 0x1F).abs() <= 6 - && (g as i32 - 0x1F).abs() <= 6 - && (b as i32 - 0x24).abs() <= 6 - { - card_bg_px += 1; - } else if r >= 220 && g >= 220 && b >= 225 { - bright_text_px += 1; - } - } - } - assert!( - card_bg_px > 40_000, - "[dark_profile_popup] Expected Yandex ID #1F1F24 dark surface (got {} px)", - card_bg_px - ); - assert!( - bright_text_px > 1_200, - "[dark_profile_popup] Expected high-contrast #FAFAFF text/icons (got {} px)", - bright_text_px - ); - - // Verify Appearance submenu popover rendered to the right of the card (x=345..555) - let mut sub_bg_px = 0usize; - for y in 420..660 { - for x in 348..555 { - let [r, g, b] = img.get_pixel(x, y).0; - if (r as i32 - 0x2D).abs() <= 8 - && (g as i32 - 0x2D).abs() <= 8 - && (b as i32 - 0x34).abs() <= 8 - { - sub_bg_px += 1; - } - } - } - assert!( - sub_bg_px > 10_000, - "[dark_profile_popup] Expected Yandex ID #2D2D34 Appearance popover (got {} px)", - sub_bg_px - ); - } - - // 2. My Vibe official 5.129.0 `WordsCard` + `WordsCardPopoverDesktop` (`my_vibe_words_popover.png`) - { - // Static guard: fake AI Vibe-settings string MUST be completely gone from `src/views/my_vibe.rs` - let mv_src = std::fs::read_to_string( - Path::new(env!("CARGO_MANIFEST_DIR")).join("src/views/my_vibe.rs"), - ) - .expect("read src/views/my_vibe.rs"); - assert!( - !mv_src.contains("Мою волну по настроению и характеру"), - "Fake AI Vibe-settings phrase must be removed from WordsCard in src/views/my_vibe.rs!" - ); - - let mut shell = make_base_shell( - rt.handle().clone(), - vk.gpu_name.clone(), - Route::MyVibe, - ThemeMode::Dark, - Language::Ru, - 108.0, - ); - shell.app.words_cards.insert( - "t_1".into(), - WordsCard { - id: "wc_test_1".into(), - track_id: "t_1".into(), - text: "Трек вдохновлён бразильским фонком и энергичными рейвами 2000-х".into(), - tags: vec!["FACT".into()], - action: None, - actions: vec![WordsCardSource { - title: "Подробнее об артисте".into(), - url: "https://music.yandex.ru".into(), - favicon_url: None, - }], - big_card_ids: Vec::new(), - feedback_state: None, - }, - ); - - // Warm up WordsCard layout (renders State B around cx~943, ai_y~732) - let before = render_single_frame(&mut vk, &mut shell, 0.0); - let click_pos = Pos2::new(943.0, 732.0); - // Simulate genuine left-click press + release on WordsCard to toggle WordsCardPopoverDesktop - shell.ui.input.pointer_pos = Some(click_pos); - shell.ui.input.left_down = true; - shell.ui.input.left_pressed = true; - let _ = render_single_frame(&mut vk, &mut shell, 0.016); - shell.ui.input.left_down = false; - shell.ui.input.left_released = true; - let _ = render_single_frame(&mut vk, &mut shell, 0.032); - let after = render_single_frame(&mut vk, &mut shell, 0.048); - - let _ = after.save(out_dir.join("my_vibe_words_popover.png")); - - // Verify WordsCardPopoverDesktop actually appeared above WordsCard (y=500..700, x=810..1075) - let popover_delta = region_mean_abs_diff(&before, &after, 810, 500, 1075, 700); - assert!( - popover_delta > 4.0, - "[my_vibe_words_popover] Clicking WordsCard did not open WordsCardPopoverDesktop (delta={:.2} RGB)", - popover_delta - ); - assert!( - !shell.app.vibe_modal_open, - "[my_vibe_words_popover] Clicking WordsCard MUST NOT open fake Vibe settings modal!" - ); - } - - // 3. Official 1-to-1 `VibeResetButton` unified pill + `0.1.0` version badge (`my_vibe_context_pill.png`) - { - use yandex_music_rs::app::APP_VERSION; - assert_eq!( - APP_VERSION, - env!("CARGO_PKG_VERSION"), - "APP_VERSION must match Cargo.toml" - ); - - let mut shell = make_base_shell( - rt.handle().clone(), - vk.gpu_name.clone(), - Route::MyVibe, - ThemeMode::Dark, - Language::En, - 12.0, - ); - if let Some(tr) = shell.app.queue.get_mut(0) { - tr.derived_average_hex = Some("#F56E00".into()); - } - shell.app.is_vibe_active = false; - shell.app.context_name = "My Favorites".into(); - shell.app.context_key = "likes".into(); - shell.app.set_vibe_playback_for_test(true, 0.45, 0.35); - - let mut img = render_single_frame(&mut vk, &mut shell, 0.0); - for f in 1..4 { - img = render_single_frame(&mut vk, &mut shell, f as f64 * 0.2); - } - let _ = img.save(out_dir.join("my_vibe_context_pill.png")); - - // Verify bright electric yellow pixels (#FFFF00) inside top-center VibeResetButton pill (y=32..80, x=830..1060) - let mut pill_yellow_px = 0usize; - for y in 32..80 { - for x in 830..1060 { - if is_yandex_yellow(img.get_pixel(x, y).0) { - pill_yellow_px += 1; - } - } - } - assert!( - pill_yellow_px >= 400, - "[my_vibe_context_pill] Expected electric yellow text + filled yellow close circle inside unified VibeResetButton pill, found {} yellow px", - pill_yellow_px - ); - } -} - -#[test] -fn test_ext_17_for_you_collection_concerts_words_fullscreen() { - use yandex_music_rs::api::models::{ - AlbumSummary, ConcertItem, NewReleaseItem, VibePickItem, VibePickTab, WordsBigCard, - WordsCard, WordsCardSource, - }; - use yandex_music_rs::engine::WidgetId; - - let rt = tokio::runtime::Runtime::new().unwrap(); - let mut vk = HeadlessVulkanRenderer::new(NATIVE_W, NATIVE_H).expect("Vulkan init failed"); - let out_dir = output_dir(); - let _ = std::fs::create_dir_all(&out_dir); - - // 1. Official `For You` scrolled down: sticky frosted header + circular NewReleases + More Picks (`for_you_new_releases_picks.png`) - { - let mut shell = make_base_shell( - rt.handle().clone(), - vk.gpu_name.clone(), - Route::ForYou, - ThemeMode::Dark, - Language::En, - 0.0, - ); - let mk_album = |id: &str, title: &str, artist: &str| AlbumSummary { - id: id.into(), - title: title.into(), - version: None, - year: Some(2026), - cover_uri: None, - artists: vec![ArtistSummary { - id: format!("art_{id}"), - name: artist.into(), - cover_uri: None, - genres: vec![], - }], - track_count: 12, - genre: Some("electronic".into()), - is_explicit: false, - content_type: Some("album".into()), - }; - shell.app.landing.rich_new_releases = vec![ - NewReleaseItem { - album: mk_album("nr1", "Neon Horizon", "SALUKI"), - artist_cover_uri: None, - cover_color: Some("#3B4CA8".into()), - release_date: Some("2026-11-20".into()), - }, - NewReleaseItem { - album: mk_album("nr2", "Velvet Pulse", "Mirele"), - artist_cover_uri: None, - cover_color: Some("#7B2D5F".into()), - release_date: Some("2026-11-18".into()), - }, - NewReleaseItem { - album: mk_album("nr3", "Night Drive", "SLAVA MARLOW"), - artist_cover_uri: None, - cover_color: Some("#1E6B52".into()), - release_date: Some("2026-11-15".into()), - }, - NewReleaseItem { - album: mk_album("nr4", "Solar Flare", "OG BLESS"), - artist_cover_uri: None, - cover_color: Some("#8F4A1E".into()), - release_date: Some("2026-11-12".into()), - }, - ]; - shell.app.landing.vibe_pick_tabs = vec![ - VibePickTab { - title: "Mood".into(), - items: vec![ - VibePickItem { - title: "Energetic".into(), - header: "Vibe".into(), - seeds: vec!["mood:energetic".into()], - color_hex: Some("#D94E2A".into()), - background_image_url: None, - image_url: None, - }, - VibePickItem { - title: "Night Focus".into(), - header: "Vibe".into(), - seeds: vec!["mood:calm".into()], - color_hex: Some("#2F55A4".into()), - background_image_url: None, - image_url: None, - }, - VibePickItem { - title: "Dreamy Synth".into(), - header: "Vibe".into(), - seeds: vec!["genre:electronic".into()], - color_hex: Some("#7C3AED".into()), - background_image_url: None, - image_url: None, - }, - ], - }, - VibePickTab { - title: "Activity".into(), - items: vec![VibePickItem { - title: "Workout".into(), - header: "Vibe".into(), - seeds: vec!["activity:workout".into()], - color_hex: Some("#0F766E".into()), - background_image_url: None, - image_url: None, - }], - }, - VibePickTab { - title: "Genres".into(), - items: vec![], - }, - ]; - - // Warm up layout so scroll content height is computed, then scroll to show New Releases + More Picks + sticky switcher - let _ = render_single_frame(&mut vk, &mut shell, 0.0); - let _ = render_single_frame(&mut vk, &mut shell, 0.016); - shell - .ui - .scrolls - .jump_to_y(WidgetId::new("foryou_page_scroll"), 860.0); - let _ = render_single_frame(&mut vk, &mut shell, 0.032); - let img = render_single_frame(&mut vk, &mut shell, 0.048); - let _ = img.save(out_dir.join("for_you_new_releases_picks.png")); - - // Verify colored NewRelease cards / More Picks cards rendered non-flat rich pixels in content card - let mut colored_px = 0usize; - for y in 110..680 { - for x in 250..1240 { - let [r, g, b] = img.get_pixel(x, y).0; - let max_c = r.max(g).max(b); - let min_c = r.min(g).min(b); - if max_c.saturating_sub(min_c) >= 24 { - colored_px += 1; - } - } - } - assert!( - colored_px > 5_000, - "[for_you_new_releases_picks] Expected colored New Releases / More Picks cards, found only {} chromatic px", - colored_px - ); - } - - // 2. Official `My Collection` vertical feed (`my_collection_official.png`) - { - let mut shell = make_base_shell( - rt.handle().clone(), - vk.gpu_name.clone(), - Route::Collection, - ThemeMode::Dark, - Language::En, - 0.0, - ); - let extra_tracks = [ - ("c_1", "MONTAGEM TENTA", "KYOR", 141_000), - ("c_2", "Midnight Sun", "SuperSolar", 184_000), - ("c_3", "BANG A RANG", "GSTRNM", 100_000), - ("c_4", "BOSS BITCH TEKK", "wharoxmane", 107_000), - ("c_5", "Neon Rain", "Mirele", 192_000), - ("c_6", "Skyline Pulse", "SALUKI", 168_000), - ("c_7", "Electric Horizon", "SLAVA MARLOW", 155_000), - ("c_8", "Deep Focus", "OG BLESS", 210_000), - ]; - shell.app.liked_tracks = extra_tracks - .iter() - .map(|(id, title, art, dur)| Track { - id: (*id).into(), - title: (*title).into(), - version: None, - artists: vec![ArtistSummary { - id: format!("ca_{id}"), - name: (*art).into(), - cover_uri: None, - genres: vec![], - }], - album_id: Some(format!("calb_{id}")), - album_title: Some((*title).into()), - duration_ms: *dur, - cover_uri: None, - is_explicit: false, - has_lossless: true, - has_lyrics: true, - chart_position: None, - chart_progress: None, - preview_url: None, - r128_i: None, - r128_tp: None, - derived_average_hex: None, - derived_accent_hex: None, - fade: None, - }) - .collect(); - shell.app.liked_artists = ["SALUKI", "Mirele", "KYOR", "SuperSolar", "GSTRNM", "OG BLESS"] - .iter() - .enumerate() - .map(|(i, name)| ArtistSummary { - id: format!("la_{i}"), - name: (*name).into(), - cover_uri: None, - genres: vec![], - }) - .collect(); - - let _ = render_single_frame(&mut vk, &mut shell, 0.0); - let _ = render_single_frame(&mut vk, &mut shell, 0.016); - let img = render_single_frame(&mut vk, &mut shell, 0.032); - let _ = img.save(out_dir.join("my_collection_official.png")); - - // Verify pink-magenta colored "color" word in subtitle + crimson 3D heart icon present, - // and ZERO old yellow-bordered My Favorites hero card! - let mut pink_subtitle_px = 0usize; - for y in 75..125 { - for x in 250..520 { - let [r, g, b] = img.get_pixel(x, y).0; - if r > 170 && b > 100 && (r as u16) > (g as u16) + 50 { - pink_subtitle_px += 1; - } - } - } - assert!( - pink_subtitle_px >= 15, - "[my_collection_official] Expected magenta-colored subtitle word 'color', found {} px", - pink_subtitle_px - ); - } - - // 3. Official `ConcertsPage` (`concerts_official.png`) - { - let mut shell = make_base_shell( - rt.handle().clone(), - vk.gpu_name.clone(), - Route::Concerts, - ThemeMode::Dark, - Language::Ru, - 0.0, - ); - shell.app.concerts = vec![ - ConcertItem { - id: "con_1".into(), - title: "SALUKI — Большой сольный концерт".into(), - artist_name: "SALUKI".into(), - city: "Москва".into(), - place: "VK Stadium".into(), - date: "14 дек, 20:00".into(), - cover_uri: None, - afisha_url: Some("https://afisha.yandex.ru".into()), - min_price: Some(2500), - currency: Some("RUB".into()), - cashback_percent: Some(15), - cashback_title: Some("Кешбэк 15%".into()), - cover_color: Some("#4C2A85".into()), - event_kind: Some("concert".into()), - }, - ConcertItem { - id: "con_2".into(), - title: "Mirele — Акустический вечер".into(), - artist_name: "Mirele".into(), - city: "Санкт-Петербург".into(), - place: "A2 Green Concert".into(), - date: "21 дек, 19:30".into(), - cover_uri: None, - afisha_url: Some("https://afisha.yandex.ru".into()), - min_price: Some(1900), - currency: Some("RUB".into()), - cashback_percent: Some(10), - cashback_title: None, - cover_color: Some("#1D5B79".into()), - event_kind: Some("concert".into()), - }, - ConcertItem { - id: "con_3".into(), - title: "SLAVA MARLOW — Live Tour".into(), - artist_name: "SLAVA MARLOW".into(), - city: "Казань".into(), - place: "Korston Club Hotel".into(), - date: "28 дек, 20:00".into(), - cover_uri: None, - afisha_url: Some("https://afisha.yandex.ru".into()), - min_price: Some(2200), - currency: Some("RUB".into()), - cashback_percent: Some(20), - cashback_title: None, - cover_color: Some("#8C2F39".into()), - event_kind: Some("concert".into()), - }, - ConcertItem { - id: "con_4".into(), - title: "Электрофорез — Зимний сет".into(), - artist_name: "Электрофорез".into(), - city: "Москва".into(), - place: "Урбан".into(), - date: "5 янв, 20:00".into(), - cover_uri: None, - afisha_url: Some("https://afisha.yandex.ru".into()), - min_price: Some(1700), - currency: Some("RUB".into()), - cashback_percent: Some(10), - cashback_title: None, - cover_color: Some("#2D4F1E".into()), - event_kind: Some("concert".into()), - }, - ]; - - let _ = render_single_frame(&mut vk, &mut shell, 0.0); - let _ = render_single_frame(&mut vk, &mut shell, 0.016); - let img = render_single_frame(&mut vk, &mut shell, 0.032); - let _ = img.save(out_dir.join("concerts_official.png")); - - // Verify Top 3 poster cards (aspect 0.963, h~320px) + cashback pills + yellow price CTAs rendered cleanly - let mut poster_chromatic_px = 0usize; - for y in 160..540 { - for x in 250..1240 { - let [r, g, b] = img.get_pixel(x, y).0; - if r.max(g).max(b).saturating_sub(r.min(g).min(b)) >= 20 { - poster_chromatic_px += 1; - } - } - } - assert!( - poster_chromatic_px > 10_000, - "[concerts_official] Expected Top 3 concert poster cards + cashback pills, found {} chromatic px", - poster_chromatic_px - ); - } - - // 4. Official `WordsCardFullscreen` (`words_fullscreen_official.png`) - { - let mut shell = make_base_shell( - rt.handle().clone(), - vk.gpu_name.clone(), - Route::MyVibe, - ThemeMode::Dark, - Language::Ru, - 108.0, - ); - shell.app.words_cards.insert( - "t_1".into(), - WordsCard { - id: "wc_fs_1".into(), - track_id: "t_1".into(), - text: "MONTAGEM TENTA сочетает бразильский фонк и жёсткие хардстайл-кики.".into(), - tags: vec!["FACT".into()], - action: None, - actions: vec![], - big_card_ids: vec!["bc_1".into()], - feedback_state: None, - }, - ); - shell.app.words_big_card_open = true; - shell.app.words_big_card_loading = false; - shell.app.words_big_card = Some(WordsBigCard { - id: "bc_1".into(), - text: "MONTAGEM TENTA (Hardstyle) — взрывной кроссовер бразильского фонка и европейского хардстайла с плотным саб-басом и стремительным ритмом.".into(), - actions: vec![WordsCardSource { - title: "Обсудить с Алисой AI".into(), - url: "https://alice.yandex.ru".into(), - favicon_url: None, - }], - }); - - let _ = render_single_frame(&mut vk, &mut shell, 0.0); - let _ = render_single_frame(&mut vk, &mut shell, 0.016); - let img = render_single_frame(&mut vk, &mut shell, 0.032); - let _ = img.save(out_dir.join("words_fullscreen_official.png")); - - // Verify purple Alice ring (#8B5CF6) rendered inside the centered source pill - let mut alice_purple_px = 0usize; - for y in 360..600 { - for x in 560..960 { - let [r, g, b] = img.get_pixel(x, y).0; - if b > 160 && r > 90 && (b as u16) > (g as u16) + 50 { - alice_purple_px += 1; - } - } - } - assert!( - alice_purple_px >= 15, - "[words_fullscreen_official] Expected purple Alice AI icon inside source pill, found {} px", - alice_purple_px - ); - } -} - -#[test] -fn test_ext_18_qa_sync_lyrics_scroll_concerts_duplicate_albums() { - use std::sync::atomic::Ordering; - use yandex_music_rs::api::models::{AlbumSummary, LyricLine, TrackLyrics}; - use yandex_music_rs::app::CollectionTab; - use yandex_music_rs::engine::input::{InputState, ZLayer}; - use yandex_music_rs::engine::scroll::ScrollState; - use yandex_music_rs::engine::types::{Pos2, Rect}; - use yandex_music_rs::engine::widgets::cover_fit_uv; - - let rt = tokio::runtime::Runtime::new().unwrap(); - let mut vk = HeadlessVulkanRenderer::new(NATIVE_W, NATIVE_H).expect("Vulkan init failed"); - let out_dir = output_dir(); - let _ = std::fs::create_dir_all(&out_dir); - - // 1. 1-to-1 Official FullscreenPlayerDesktop 50/50 SyncLyrics (`fullscreen_sync_lyrics_official.png`) - { - let mut shell = make_base_shell( - rt.handle().clone(), - vk.gpu_name.clone(), - Route::LikedTracks, - ThemeMode::Dark, - Language::Ru, - 0.0, - ); - if let Some(tr) = shell.app.queue.get_mut(0) { - tr.derived_average_hex = Some("#1A2238".into()); - } - shell.app.current_lyrics = Some(TrackLyrics { - track_id: "t_1".into(), - is_synced: true, - lines: vec![ - LyricLine { time_ms: 4_000, text: "Первая строчка уходит вверх".into() }, - LyricLine { time_ms: 10_000, text: "Вторая строчка уже прозвучала".into() }, - LyricLine { time_ms: 16_000, text: "Третья строчка перед текущей".into() }, - LyricLine { time_ms: 21_000, text: "Активная яркая строка прямо по центру".into() }, - LyricLine { time_ms: 28_000, text: "Следующая строчка ждёт своей очереди".into() }, - LyricLine { time_ms: 35_000, text: "Пятая строчка чуть дальше вниз".into() }, - LyricLine { time_ms: 42_000, text: "Шестая строчка в приглушённом цвете".into() }, - LyricLine { time_ms: 49_000, text: "Финальная строчка композиции".into() }, - ], - writers: Some("Test Writer".into()), - major: Some("Genius".into()), - }); - shell.app.fullscreen_open = true; - shell.app.fullscreen_lyrics_open = true; - shell.app.audio.state.position_ms.store(22_000, Ordering::SeqCst); - shell.app.audio.state.is_playing.store(true, Ordering::SeqCst); - shell.shell.fs_lyrics_upper_until = 0.0; - shell.shell.fs_lyrics_manual_until = 0.0; - - // Settle 0.45s split + opacity animations cleanly with mouse idle - let mut img = render_single_frame(&mut vk, &mut shell, 0.0); - for f in 1..25 { - img = render_single_frame(&mut vk, &mut shell, f as f64 * 0.05); - } - let _ = img.save(out_dir.join("fullscreen_sync_lyrics_official.png")); - - // Verify bright white active line near 40vh (y=250..410, x=600..1220) - let mut active_bright_px = 0usize; - for y in 250..410 { - for x in 600..1220 { - let [r, g, b] = img.get_pixel(x, y).0; - if r >= 200 && g >= 200 && b >= 200 { - active_bright_px += 1; - } - } - } - assert!( - active_bright_px >= 600, - "[fullscreen_sync_lyrics] Expected bright white active line near 40vh, found {} px", - active_bright_px - ); - - // Verify past lines above active (y=60..210, x=640..1180) are hidden (0 bright white px) when mouse is idle - let mut past_bright_px = 0usize; - for y in 60..210 { - for x in 640..1180 { - let [r, g, b] = img.get_pixel(x, y).0; - if r >= 170 && g >= 170 && b >= 170 { - past_bright_px += 1; - } - } - } - assert_eq!( - past_bright_px, 0, - "[fullscreen_sync_lyrics] Past upper lines must be hidden (opacity 0.0) when mouse is idle, found {} bright px", - past_bright_px - ); - - // Verify Volume button is anchored in the bottom-right corner (center ~(1236, 760)), NOT bottom-center - let mut vol_corner_bright_px = 0usize; - for y in 740..780 { - for x in 1216..1256 { - let [r, g, b] = img.get_pixel(x, y).0; - if r >= 160 && g >= 160 && b >= 160 { - vol_corner_bright_px += 1; - } - } - } - assert!( - vol_corner_bright_px >= 25, - "[fullscreen_sync_lyrics] Expected Volume icon anchored in bottom-right corner (1236,760), found {} bright px", - vol_corner_bright_px - ); - } - - // 2. Horizontal Scroll Isolation: plain vertical wheel MUST NOT scroll horizontal-only carousels! - { - let vp = Rect::from_xywh(0.0, 0.0, 600.0, 200.0); - let mut st = ScrollState::new(); - st.content_size = Vec2::new(2000.0, 200.0); - - let mut inp = InputState::new(); - inp.pointer_pos = Some(Pos2::new(200.0, 100.0)); - inp.wheel_delta = Vec2::new(0.0, -120.0); - st.update(&inp, ZLayer::Base, vp, false, true); - assert!( - st.target.x.abs() < 0.001, - "Horizontal-only ScrollState must ignore plain vertical wheel_delta.y, got target.x={}", - st.target.x - ); - - // Shift + vertical wheel scrolls horizontally - inp.modifiers.shift = true; - st.update(&inp, ZLayer::Base, vp, false, true); - assert!( - st.target.x > 50.0, - "Shift + wheel_delta.y must scroll horizontally, got target.x={}", - st.target.x - ); - - // Trackpad horizontal wheel_delta.x scrolls horizontally without Shift - st.reset(); - inp.modifiers.shift = false; - inp.wheel_delta = Vec2::new(-120.0, 0.0); - st.update(&inp, ZLayer::Base, vp, false, true); - assert!( - st.target.x > 50.0, - "Horizontal wheel_delta.x must scroll horizontally, got target.x={}", - st.target.x - ); - } - - // 3. `object-fit: cover` (`cover_fit_uv`) preserves aspect ratio with zero stretching - { - let uv_wide = cover_fit_uv(400, 400, Rect::from_xywh(0.0, 0.0, 300.0, 150.0), 0.35); - assert!( - (uv_wide.w - 1.0).abs() < 1e-4 && (uv_wide.h - 0.5).abs() < 1e-4, - "400x400 in 300x150 expected uv (w=1.0, h=0.5), got {:?}", - uv_wide - ); - let uv_portrait = cover_fit_uv(200, 400, Rect::from_xywh(0.0, 0.0, 200.0, 200.0), 0.35); - assert!( - (uv_portrait.w - 1.0).abs() < 1e-4 && (uv_portrait.h - 0.5).abs() < 1e-4, - "200x400 in 200x200 expected uv (w=1.0, h=0.5), got {:?}", - uv_portrait - ); - } - - // 4. Concerts Active Icon (`Icon::ConcertsSelected`) rasterizes with symmetric filled ticket silhouette - { - let opt = resvg::usvg::Options::default(); - let tree = resvg::usvg::Tree::from_data(Icon::ConcertsSelected.raw_svg(), &opt) - .expect("ConcertsSelected SVG parse failed"); - let sz = 48u32; - let mut pixmap = resvg::tiny_skia::Pixmap::new(sz, sz).unwrap(); - let sx = sz as f32 / tree.size().width(); - let sy = sz as f32 / tree.size().height(); - resvg::render( - &tree, - resvg::tiny_skia::Transform::from_scale(sx, sy), - &mut pixmap.as_mut(), - ); - let data = pixmap.data(); - let mut left_cov = 0u64; - let mut right_cov = 0u64; - for y in 0..sz { - for x in 0..sz { - let a = data[((y * sz + x) * 4 + 3) as usize] as u64; - if x < sz / 2 { - left_cov += a; - } else { - right_cov += a; - } - } - } - let total = left_cov + right_cov; - assert!( - total > 40_000, - "ConcertsSelected SVG coverage too small ({})", - total - ); - let asym = (left_cov as i64 - right_cov as i64).unsigned_abs() as f64 / total as f64; - assert!( - asym < 0.05, - "ConcertsSelected SVG is asymmetric (left={}, right={}, asym={:.3})", - left_cov, - right_cov, - asym - ); - } - - // 5. Duplicate-Title Albums render distinctly in Collection overview + Albums sub-view with zero panics - { - let mk_dup = |id: &str, version: Option<&str>| AlbumSummary { - id: id.into(), - title: "Same Title Album".into(), - version: version.map(String::from), - year: Some(2025), - cover_uri: None, - artists: vec![ArtistSummary { - id: "art_dup".into(), - name: "Test Artist".into(), - cover_uri: None, - genres: vec![], - }], - track_count: 10, - genre: Some("pop".into()), - is_explicit: false, - content_type: Some("album".into()), - }; - let std_alb = mk_dup("alb_std", None); - let dlx_alb = mk_dup("alb_dlx", Some("Deluxe")); - assert_eq!(std_alb.full_title(), "Same Title Album"); - assert_eq!(dlx_alb.full_title(), "Same Title Album (Deluxe)"); - - let mut shell = make_base_shell( - rt.handle().clone(), - vk.gpu_name.clone(), - Route::Collection, - ThemeMode::Dark, - Language::Ru, - 0.0, - ); - shell.app.liked_albums = vec![std_alb, dlx_alb]; - shell.app.collection_tab = CollectionTab::Tracks; - let _ = render_single_frame(&mut vk, &mut shell, 0.0); - let _ = render_single_frame(&mut vk, &mut shell, 0.016); - - shell.app.collection_tab = CollectionTab::Albums; - let _ = render_single_frame(&mut vk, &mut shell, 0.032); - let img_albums = render_single_frame(&mut vk, &mut shell, 0.048); - - // Confirm both album cards rendered distinct non-empty content in the Albums grid (x=250..650, y=130..360) - let mut card1_lit = 0usize; - let mut card2_lit = 0usize; - for y in 130..360 { - for x in 250..430 { - let [r, g, b] = img_albums.get_pixel(x, y).0; - if r > 30 || g > 30 || b > 30 { - card1_lit += 1; - } - } - for x in 450..630 { - let [r, g, b] = img_albums.get_pixel(x, y).0; - if r > 30 || g > 30 || b > 30 { - card2_lit += 1; - } - } - } - assert!( - card1_lit > 2_000 && card2_lit > 2_000, - "Expected both duplicate-title album cards to render distinctly (card1={}, card2={})", - card1_lit, - card2_lit - ); - } -} - -#[test] -fn test_ext_15_release_notes_modal_update_notification_and_download_ring() { - let rt = tokio::runtime::Runtime::new().unwrap(); - let mut vk = HeadlessVulkanRenderer::new(NATIVE_W, NATIVE_H).expect("Vulkan init failed"); - - for theme in [ThemeMode::Dark, ThemeMode::Light] { - let mut shell = make_base_shell( - rt.handle().clone(), - vk.gpu_name.clone(), - Route::LikedTracks, - theme, - Language::Ru, - 0.0, - ); - if let Some(first_id) = shell.app.liked_tracks.first().map(|t| t.id.clone()) { - shell.app.downloading_track_ids.insert(first_id.clone()); - shell.app.downloading_track_progress.insert(first_id, 0.45); - shell.app.download_batch_total = 2; - shell.app.download_batch_done = 0; - } - shell.app.available_update = Some(yandex_music_rs::api::models::UpdateInfo { - version: "9.9.9".into(), - html_url: "https://git.tatar/marwy/yandex-music-rs/releases/tag/v9.9.9".into(), - date: "2026-11-28".into(), - body: "## Новое\n- Тестовое обновление".into(), - }); - shell.app.release_notes_modal_open = true; - - let _ = render_single_frame(&mut vk, &mut shell, 0.0); - let img = render_single_frame(&mut vk, &mut shell, 0.016); - assert!(img.width() == NATIVE_W && img.height() == NATIVE_H); - } -} - -#[test] -fn test_ext_19_official_settings_sound_quality_equalizer_and_shortcuts_modals() { - let rt = tokio::runtime::Runtime::new().unwrap(); - let mut vk = HeadlessVulkanRenderer::new(NATIVE_W, NATIVE_H).expect("Vulkan init failed"); - - for theme in [ThemeMode::Dark, ThemeMode::Light] { - let mut shell = make_base_shell( - rt.handle().clone(), - vk.gpu_name.clone(), - Route::Settings, - theme, - Language::Ru, - 0.0, - ); - shell.app.config.eq_enabled = true; - shell.app.config.eq_preamp = 1.15; - shell.app.eq_popover_open = true; - let _ = render_single_frame(&mut vk, &mut shell, 0.0); - let img_qs = render_single_frame(&mut vk, &mut shell, 0.016); - assert!(img_qs.width() == NATIVE_W && img_qs.height() == NATIVE_H); - - shell.app.config.eq_enabled = false; - shell.app.eq_popover_open = false; - shell.app.equalizer_modal_open = true; - let img_eq = render_single_frame(&mut vk, &mut shell, 0.032); - assert!(img_eq.width() == NATIVE_W && img_eq.height() == NATIVE_H); - - shell.app.equalizer_modal_open = false; - shell.app.shortcuts_modal_open = true; - let img_sc = render_single_frame(&mut vk, &mut shell, 0.048); - assert!(img_sc.width() == NATIVE_W && img_sc.height() == NATIVE_H); - - shell.app.shortcuts_modal_open = false; - for &style in yandex_music_rs::config::PlayerThumbStyle::ALL { - shell.app.config.player_thumb = style; - let img_th = render_single_frame(&mut vk, &mut shell, 0.064); - assert!(img_th.width() == NATIVE_W && img_th.height() == NATIVE_H); - } - - // Regression: Fullscreen player must NOT leak the bottom PlayerBar companion on top of it! - shell.app.config.player_thumb = yandex_music_rs::config::PlayerThumbStyle::Claudik; - shell.app.fullscreen_open = true; - let img_fs_claudik = render_single_frame(&mut vk, &mut shell, 0.080); - shell.app.config.player_thumb = yandex_music_rs::config::PlayerThumbStyle::Standard; - let img_fs_std = render_single_frame(&mut vk, &mut shell, 0.080); - assert_eq!( - img_fs_claudik.as_raw(), - img_fs_std.as_raw(), - "Fullscreen player leaked bottom PlayerBar companion onto ZLayer::Popover!" - ); - } -}