Compare commits

..

No commits in common. "main" and "v0.1.2" have entirely different histories.
main ... v0.1.2

42 changed files with 1359 additions and 6911 deletions

View file

@ -1,36 +1,12 @@
# Инструкция для 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).
В системе (Windows Credential Manager) уже сохранён рабочий токен для `https://git.tatar` (`git:https://git.tatar`).
> **ВАЖНО:**
> 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=<TOKEN>`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)
```
---

334
Cargo.lock generated
View file

@ -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.2"
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",
]

View file

@ -1,22 +1,9 @@
[package]
name = "yandex-music-rs"
version = "0.1.9"
version = "0.1.2"
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"],

View file

@ -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.2-windows-x86_64.exe` и запустите (переносной файл, установка не требуется).
- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.2-1_amd64.deb` и установите:
```bash
sudo apt install ./yandex-music-rs_0.1.9-1_amd64.deb
sudo apt install ./yandex-music-rs_0.1.2-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.2-linux-x86_64.tar.gz` с готовым бинарником.
## Стек и возможности

View file

@ -1,3 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" d="M4.5 2H9A3 3 0 0 0 15 2H19.5A1.5 1.5 0 0 1 21 3.5V20A1.5 1.5 0 0 1 19.5 21.5H15A3 3 0 0 0 9 21.5H4.5A1.5 1.5 0 0 1 3 20V3.5A1.5 1.5 0 0 1 4.5 2ZM6.1 11.75A1.15 1.15 0 1 0 8.4 11.75A1.15 1.15 0 1 0 6.1 11.75ZM10.85 11.75A1.15 1.15 0 1 0 13.15 11.75A1.15 1.15 0 1 0 10.85 11.75ZM15.6 11.75A1.15 1.15 0 1 0 17.9 11.75A1.15 1.15 0 1 0 15.6 11.75Z"/>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#FFFFFF">
<path d="M9.21045 2.5625L9.21338 2.56641C9.21634 2.57313 9.22214 2.58822 9.23193 2.6084C9.25167 2.64901 9.28502 2.71412 9.3335 2.79492C9.4315 2.95824 9.58683 3.17912 9.80713 3.39941C10.2365 3.82878 10.9225 4.26746 11.9995 4.26758C13.0768 4.26758 13.7634 3.82885 14.1929 3.39941C14.413 3.17929 14.5675 2.9582 14.6655 2.79492C14.714 2.71412 14.7483 2.64901 14.7681 2.6084C14.7778 2.58825 14.7837 2.57312 14.7866 2.56641C14.7878 2.56379 14.7896 2.5625 14.7896 2.5625L15.0142 2H21.0698V21.5H15.0142L14.7896 20.9375L14.7866 20.9336C14.7837 20.9269 14.7778 20.9118 14.7681 20.8916C14.7483 20.851 14.714 20.7859 14.6655 20.7051C14.5675 20.5418 14.413 20.3207 14.1929 20.1006C13.7634 19.6711 13.0768 19.2324 11.9995 19.2324C10.9225 19.2325 10.2365 19.6712 9.80713 20.1006C9.58683 20.3209 9.4315 20.5418 9.3335 20.7051C9.28502 20.7859 9.25167 20.851 9.23193 20.8916C9.22214 20.9118 9.21634 20.9269 9.21338 20.9336C9.21215 20.9362 9.21045 20.9375 9.21045 20.9375L8.98584 21.5H2.93018V14.2441H4.74365V19.6865H7.8335C7.99017 19.4377 8.21477 19.1276 8.52393 18.8184C9.22813 18.1142 10.3562 17.4191 11.9995 17.4189C13.6431 17.4189 14.7708 18.1141 15.4751 18.8184C15.7845 19.1277 16.0098 19.4376 16.1665 19.6865H19.2554V11.5234H10.3677C9.02751 11.5234 7.94894 11.5238 7.08936 11.4307C6.21319 11.3357 5.45728 11.1344 4.80029 10.6572C4.41531 10.3775 4.0761 10.0383 3.79639 9.65332C3.31915 8.99631 3.11695 8.24047 3.02197 7.36426C2.92884 6.50469 2.93018 5.42607 2.93018 4.08594V2H8.98584L9.21045 2.5625Z" fill="#FFFFFF" />
</svg>

Before

Width:  |  Height:  |  Size: 492 B

After

Width:  |  Height:  |  Size: 1.5 KiB

Before After
Before After

View file

@ -1,54 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 156 48" width="156" height="48">
<defs>
<linearGradient id="carRed" x1="0" y1="0" x2="0.15" y2="1">
<stop offset="0%" stop-color="#FF2942"/>
<stop offset="48%" stop-color="#D90F26"/>
<stop offset="100%" stop-color="#8C0717"/>
</linearGradient>
<linearGradient id="carHighlight" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#FF7A89" stop-opacity="0.25"/>
<stop offset="45%" stop-color="#FF99A5" stop-opacity="0.85"/>
<stop offset="100%" stop-color="#FF7A89" stop-opacity="0.2"/>
</linearGradient>
<linearGradient id="carGlass" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#4A5568"/>
<stop offset="45%" stop-color="#1A1E26"/>
<stop offset="100%" stop-color="#0D0F14"/>
</linearGradient>
<radialGradient id="rimGrad" cx="50%" cy="50%" r="50%">
<stop offset="0%" stop-color="#F5F7FA"/>
<stop offset="60%" stop-color="#B8C0CC"/>
<stop offset="100%" stop-color="#5C6470"/>
</radialGradient>
</defs>
<!-- Underbody shadow -->
<rect x="12" y="37" width="134" height="4" rx="2" fill="#09090C"/>
<!-- Main supercar silhouette -->
<path d="M8 29.5L10.5 19.5C12.5 16.5 22 14.8 38 14.2L57 8.4C67 5.6 82 5.4 95 7.4L115 15.2C131 16.4 143 19.8 148.5 24.5C150.5 26.2 151.5 29.2 150.5 32.5L146.5 36.2L134 36.8H22L10.5 35.5C8 34.8 7.2 32.2 8 29.5Z" fill="url(#carRed)"/>
<!-- Roof & shoulder highlight -->
<path d="M18 19.8C36 17.5 64 16.8 106 18.2C125 18.8 139 21.4 146 25" stroke="url(#carHighlight)" stroke-width="1.8" fill="none" stroke-linecap="round"/>
<!-- Side cabin glass -->
<path d="M55 15.6L71 9.6C80 8.5 91 8.8 101 11.4L111 16.2L55 16.4Z" fill="url(#carGlass)"/>
<path d="M77 9.4L73 16.2" stroke="#111318" stroke-width="2.2"/>
<!-- Side air intake & door sculpt -->
<path d="M46 24.5L68 21.5L66 30.5L47 30.2Z" fill="#5E0611" opacity="0.82"/>
<path d="M68 23.2L104 23.8L98 28.6L67 28.4Z" fill="#9E0B1D" opacity="0.65"/>
<!-- Tail light -->
<path d="M9.5 20.5L18 20L17 24.2L9 24Z" fill="#FF595E"/>
<!-- Headlight -->
<path d="M134 22.8L147 25.4L144.5 28.4L132 25.6Z" fill="#FFF2A6"/>
<path d="M136 23.6L145 25.6" stroke="#FFFFFF" stroke-width="1.3" stroke-linecap="round"/>
<!-- Wheel arches -->
<circle cx="34" cy="34.5" r="11.2" fill="#121317"/>
<circle cx="122" cy="34.5" r="11.2" fill="#121317"/>
<!-- Rear wheel -->
<circle cx="34" cy="34.5" r="9.6" fill="#23262E"/>
<circle cx="34" cy="34.5" r="6.8" fill="url(#rimGrad)"/>
<circle cx="34" cy="34.5" r="2.2" fill="#2B2F38"/>
<path d="M34 28.2V40.8M27.7 34.5H40.3M29.6 30.1L38.4 38.9M38.4 30.1L29.6 38.9" stroke="#474E5C" stroke-width="1.15"/>
<!-- Front wheel -->
<circle cx="122" cy="34.5" r="9.6" fill="#23262E"/>
<circle cx="122" cy="34.5" r="6.8" fill="url(#rimGrad)"/>
<circle cx="122" cy="34.5" r="2.2" fill="#2B2F38"/>
<path d="M122 28.2V40.8M115.7 34.5H128.3M117.6 30.1L126.4 38.9M126.4 30.1L117.6 38.9" stroke="#474E5C" stroke-width="1.15"/>
</svg>

Before

Width:  |  Height:  |  Size: 3 KiB

View file

@ -1,44 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
<defs>
<linearGradient id="duckBody" x1="0.2" y1="0.1" x2="0.8" y2="0.95">
<stop offset="0%" stop-color="#FFE44D"/>
<stop offset="55%" stop-color="#FFC818"/>
<stop offset="100%" stop-color="#F29F05"/>
</linearGradient>
<linearGradient id="duckWing" x1="0" y1="0" x2="0.6" y2="1">
<stop offset="0%" stop-color="#FFD833"/>
<stop offset="100%" stop-color="#E89304"/>
</linearGradient>
<linearGradient id="duckBeak" x1="0" y1="0" x2="1" y2="0.8">
<stop offset="0%" stop-color="#FF8C24"/>
<stop offset="100%" stop-color="#E65200"/>
</linearGradient>
<linearGradient id="wheelRim" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#E64B17"/>
<stop offset="100%" stop-color="#B0280A"/>
</linearGradient>
</defs>
<!-- Wheels -->
<circle cx="22" cy="54" r="7.5" fill="url(#wheelRim)"/>
<circle cx="22" cy="54" r="4.2" fill="#FF8F26"/>
<circle cx="22" cy="54" r="1.6" fill="#B0280A"/>
<path d="M22 49.8v8.4M17.8 54h8.4" stroke="#C8340E" stroke-width="1.2" stroke-linecap="round"/>
<circle cx="41" cy="54" r="7.5" fill="url(#wheelRim)"/>
<circle cx="41" cy="54" r="4.2" fill="#FF8F26"/>
<circle cx="41" cy="54" r="1.6" fill="#B0280A"/>
<path d="M41 49.8v8.4M36.8 54h8.4" stroke="#C8340E" stroke-width="1.2" stroke-linecap="round"/>
<!-- Beak -->
<path d="M47.5 22.5c5.8 0 11.2 1.8 11.5 4.4.2 2.2-3.4 4.1-9.2 4.3-2.5.1-4.1-.8-4.5-2.6z" fill="url(#duckBeak)"/>
<path d="M49 26.8c3.6.3 6.8-.3 8.8-1.2" stroke="#B83B00" stroke-width="1.1" fill="none" stroke-linecap="round" opacity="0.65"/>
<!-- Body + Head -->
<path d="M12.5 28.5c-2.8-1.4-4.2-3.5-3.2-4.8 1.2-1.4 4.9.2 8.2 3.4 2.4 2.3 5.7 3.1 9.2 2.1 2.2-.6 2.8-2.8 1.5-5.3-1.4-2.7-1.7-5.7-.9-8.8C29 9.5 34.1 6.5 39.8 7c6.4.5 11.3 5.5 11.4 11.8.1 3.7-1.6 7-3.9 9.1-1.3 1.2-1.4 2.4-.2 3.8 2.8 3.2 4.1 7.1 3.5 11.2-.9 6.2-6.1 10.6-13.2 10.9H25.2c-8.2 0-14.6-5.2-15.4-12.6-.5-4.6.6-9.1 2.7-12.7z" fill="url(#duckBody)"/>
<!-- Head highlight -->
<ellipse cx="36.5" cy="12.5" rx="6" ry="3" transform="rotate(-14 36.5 12.5)" fill="#FFF59D" opacity="0.55"/>
<!-- Wing -->
<path d="M19.5 36.2c5.4-2.2 13.5-1.5 16.6 2.7 1.7 2.3.9 5.9-2.4 7.7-4.4 2.4-11.2 1.6-14.7-1.7-2.4-2.3-2.3-7.5.5-8.7z" fill="url(#duckWing)"/>
<path d="M21.5 38.4c4.3-1.2 9.4-.6 12.1 1.6" stroke="#FFF29A" stroke-width="1.4" fill="none" stroke-linecap="round" opacity="0.6"/>
<!-- Eye -->
<circle cx="42.4" cy="18.2" r="3.6" fill="#1A1D24"/>
<circle cx="43.5" cy="16.9" r="1.25" fill="#FFFFFF"/>
<circle cx="41.1" cy="19.5" r="0.55" fill="#FFFFFF" opacity="0.65"/>
</svg>

Before

Width:  |  Height:  |  Size: 2.6 KiB

View file

@ -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

View file

@ -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", "Дж. Р. Р. Толкин")],
@ -366,7 +356,6 @@ pub fn demo_chart_tracks() -> Vec<Track> {
r128_tp: None,
derived_average_hex: None,
derived_accent_hex: None,
fade: None,
},
Track {
id: "demo_2".into(),
@ -387,7 +376,6 @@ pub fn demo_chart_tracks() -> Vec<Track> {
r128_tp: None,
derived_average_hex: None,
derived_accent_hex: None,
fade: None,
},
Track {
id: "demo_3".into(),
@ -408,7 +396,6 @@ pub fn demo_chart_tracks() -> Vec<Track> {
r128_tp: None,
derived_average_hex: None,
derived_accent_hex: None,
fade: None,
},
Track {
id: "demo_4".into(),
@ -429,7 +416,6 @@ pub fn demo_chart_tracks() -> Vec<Track> {
r128_tp: None,
derived_average_hex: None,
derived_accent_hex: None,
fade: None,
},
Track {
id: "demo_5".into(),
@ -450,7 +436,6 @@ pub fn demo_chart_tracks() -> Vec<Track> {
r128_tp: None,
derived_average_hex: None,
derived_accent_hex: None,
fade: None,
},
Track {
id: "demo_6".into(),
@ -471,7 +456,6 @@ pub fn demo_chart_tracks() -> Vec<Track> {
r128_tp: None,
derived_average_hex: None,
derived_accent_hex: None,
fade: None,
},
Track {
id: "demo_7".into(),
@ -492,7 +476,6 @@ pub fn demo_chart_tracks() -> Vec<Track> {
r128_tp: None,
derived_average_hex: None,
derived_accent_hex: None,
fade: None,
},
Track {
id: "demo_8".into(),
@ -513,7 +496,6 @@ pub fn demo_chart_tracks() -> Vec<Track> {
r128_tp: None,
derived_average_hex: None,
derived_accent_hex: None,
fade: None,
},
Track {
id: "demo_9".into(),
@ -534,7 +516,6 @@ pub fn demo_chart_tracks() -> Vec<Track> {
r128_tp: None,
derived_average_hex: None,
derived_accent_hex: None,
fade: None,
},
Track {
id: "demo_10".into(),
@ -555,7 +536,6 @@ pub fn demo_chart_tracks() -> Vec<Track> {
r128_tp: None,
derived_average_hex: None,
derived_accent_hex: None,
fade: None,
},
]
}
@ -577,7 +557,6 @@ pub fn demo_lyrics(track: &Track) -> TrackLyrics {
is_synced: true,
lines,
writers: Some("Яндекс Музыка Rust (Демо-режим)".into()),
major: None,
}
}

View file

@ -670,7 +670,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 +679,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),
});
}
@ -1746,183 +1739,71 @@ impl YandexApiClient {
Ok(out)
}
pub async fn fetch_albums_by_ids(&self, ids: &[String]) -> Result<Vec<AlbumSummary>> {
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<Vec<ArtistSummary>> {
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<Vec<AlbumSummary>> {
let mut out: Vec<AlbumSummary> = Vec::new();
let mut seen_ids: HashSet<String> = HashSet::new();
let mut bare_ids: Vec<String> = Vec::new();
let mut seen_bare: HashSet<String> = 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<Vec<ArtistSummary>> {
let mut out: Vec<ArtistSummary> = Vec::new();
let mut seen_ids: HashSet<String> = HashSet::new();
let mut bare_ids: Vec<String> = Vec::new();
let mut seen_bare: HashSet<String> = 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)
}
@ -2086,7 +1967,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 +2399,15 @@ impl YandexApiClient {
quality: AudioQuality,
cache_dir: &Path,
) -> Result<PathBuf> {
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<F: FnMut(f32)>(
&self,
track: &Track,
quality: AudioQuality,
cache_dir: &Path,
cancel: &std::sync::atomic::AtomicBool,
mut on_progress: F,
) -> Result<PathBuf> {
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 +2421,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 +2478,6 @@ impl YandexApiClient {
is_synced: false,
lines,
writers,
major: None,
});
}
}
@ -2680,11 +2515,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,7 +2533,6 @@ impl YandexApiClient {
is_synced: parsed_synced && format == "LRC",
lines,
writers,
major,
})
}
@ -3481,103 +3310,9 @@ fn parse_artist(v: &Value) -> Option<ArtistSummary> {
})
}
fn parse_liked_albums_entries(res: &Value) -> (usize, Vec<AlbumSummary>, Vec<String>) {
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<ArtistSummary>, Vec<String>) {
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<AlbumSummary> {
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<AlbumSummary> {
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 +3334,6 @@ fn parse_album(v: &Value) -> Option<AlbumSummary> {
Some(AlbumSummary {
id,
title,
version,
year,
cover_uri,
artists,
@ -3669,15 +3403,6 @@ fn parse_track(v: &Value) -> Option<Track> {
.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 +3423,6 @@ fn parse_track(v: &Value) -> Option<Track> {
r128_tp,
derived_average_hex,
derived_accent_hex,
fade,
})
}
@ -4130,110 +3854,4 @@ mod tests {
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());
}
}

View file

@ -24,8 +24,6 @@ pub struct ArtistSummary {
pub struct AlbumSummary {
pub id: String,
pub title: String,
#[serde(default)]
pub version: Option<String>,
pub year: Option<u32>,
pub cover_uri: Option<String>,
pub artists: Vec<ArtistSummary>,
@ -37,25 +35,7 @@ pub struct AlbumSummary {
pub content_type: Option<String>,
}
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 +62,6 @@ pub struct Track {
pub derived_average_hex: Option<String>,
#[serde(default)]
pub derived_accent_hex: Option<String>,
/// Official Yandex Music track transition points in seconds (`track.fade`)
#[serde(default)]
pub fade: Option<TrackFade>,
}
/// 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 +158,6 @@ pub struct TrackLyrics {
pub is_synced: bool,
pub lines: Vec<LyricLine>,
pub writers: Option<String>,
#[serde(default)]
pub major: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@ -555,23 +512,3 @@ pub struct WordsBigCard {
pub text: String,
pub actions: Vec<WordsCardSource>,
}
/// 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,
}

View file

@ -804,46 +804,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)

View file

@ -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,7 +74,6 @@ impl AppState {
track.duration_ms,
track.r128_i,
track.r128_tp,
track.fade,
);
self.fetch_lyrics_async(&track);
self.ensure_words_for_current_track();
@ -94,7 +92,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 +104,6 @@ impl AppState {
duration_ms: dur,
r128_i,
r128_tp,
fade,
result,
});
});
@ -118,150 +114,6 @@ impl AppState {
}
}
pub(crate) fn peek_next_queue_index(&self) -> Option<usize> {
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 +338,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 +378,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 +391,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 +399,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 +456,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 +484,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,
@ -1767,58 +1612,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<u8> {
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<u8> {
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 +1641,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 +1654,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 +1672,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<Track> = tracks
.into_iter()
.filter(|tr| !self.is_track_downloaded(&tr.id) && !self.is_track_downloading(&tr.id))
@ -1888,7 +1682,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 +1690,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 +1956,6 @@ mod tests {
r128_tp: None,
derived_average_hex: None,
derived_accent_hex: None,
fade: None,
}
}

View file

@ -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;
@ -348,8 +348,6 @@ pub enum AppAction {
SetVibeModalOpen(bool),
SetLoginModalOpen(bool),
SetEqPopoverOpen(bool),
SetEqualizerModalOpen(bool),
SetShortcutsModalOpen(bool),
OpenTrackDetailModal(Track),
CloseTrackDetailModal,
OpenWordsBigCard {
@ -362,10 +360,6 @@ pub enum AppAction {
state: String,
},
DismissOverlays,
OpenReleaseNotesModal,
CloseReleaseNotesModal,
DismissUpdateNotification,
InstallUpdate,
// Account, Settings & Lifecycle
SetTheme(ThemeMode),
@ -373,15 +367,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),
@ -431,15 +422,6 @@ pub(crate) enum ApiEvent {
duration_ms: u64,
r128_i: Option<f32>,
r128_tp: Option<f32>,
fade: Option<TrackFade>,
result: Result<ResolvedStream, String>,
},
NextStreamPreloaded {
track_id: String,
duration_ms: u64,
r128_i: Option<f32>,
r128_tp: Option<f32>,
fade: Option<TrackFade>,
result: Result<ResolvedStream, String>,
},
LyricsLoaded(TrackLyrics),
@ -467,18 +449,11 @@ pub(crate) enum ApiEvent {
revision: Result<u32, String>,
toast_msg: String,
},
TrackDownloadProgress {
track_id: String,
progress: f32,
},
TrackDownloaded {
track: Track,
result: Result<PathBuf, String>,
},
ReleasesLoaded {
result: Result<Vec<ReleaseNoteEntry>, String>,
user_initiated: bool,
},
UpdateCheckFinished(Result<Option<(String, String)>, String>),
}
// =============================================================================
@ -528,12 +503,8 @@ pub struct AppState {
// Offline cache & download tracking
pub downloaded_track_ids: HashSet<String>,
pub downloading_track_ids: HashSet<String>,
pub downloading_track_progress: HashMap<String, f32>,
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<AtomicBool>,
// Page-specific states
@ -563,7 +534,6 @@ pub struct AppState {
pub vibe_prefetching: bool,
pub shuffle: bool,
pub repeat: RepeatMode,
pub preloaded_next_track_id: Option<String>,
pub current_lyrics: Option<TrackLyrics>,
pub modal_lyrics: Option<TrackLyrics>,
@ -602,8 +572,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<Track>,
pub token_input: String,
@ -616,11 +584,7 @@ pub struct AppState {
pub clear_cover_cache_requested: bool,
pub cover_cache_capacity_dirty: bool,
pub pending_clipboard_text: Option<String>,
pub available_update: Option<UpdateInfo>,
pub releases: Vec<ReleaseNoteEntry>,
pub releases_loading: bool,
pub release_notes_modal_open: bool,
pub update_notification_dismissed: bool,
pub available_update: Option<(String, String)>,
pub persist_enabled: bool,
}
@ -631,10 +595,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());
@ -693,12 +655,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,7 +682,6 @@ 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(),
@ -757,8 +714,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(),
@ -770,10 +725,6 @@ impl AppState {
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 +757,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);
@ -855,12 +805,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,7 +832,6 @@ 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(),
@ -919,8 +864,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(),
@ -932,10 +875,6 @@ impl AppState {
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 +1028,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 +1238,59 @@ impl AppState {
})
}
/// Built-in offline fallback release notes so `ReleaseNotesModal` is always populated immediately.
pub fn builtin_fallback_releases() -> Vec<ReleaseNoteEntry> {
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;
/// Shows version status toast (`APP_VERSION` = `0.1.0`) & checks `git.tatar/marwy/yandex-music-rs` latest release asynchronously.
/// If an update was already detected, clicking again opens its release page immediately.
pub fn check_for_updates(&mut self) {
if let Some((_, ref url)) = self.available_update {
open_url_in_browser(url);
}
self.releases_loading = true;
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";
const LATEST_RELEASE_API: &str =
"https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases/latest";
const LATEST_RELEASE_WEB: &str =
"https://git.tatar/marwy/yandex-music-rs/releases/latest";
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(6))
.user_agent(format!("yandex-music-rs/{}", APP_VERSION))
.build();
let res = match client {
Ok(http) => match http.get(RELEASES_API).send().await {
Ok(http) => match http.get(LATEST_RELEASE_API).send().await {
Ok(resp) if resp.status().is_success() => {
match resp.json::<Vec<serde_json::Value>>().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,
});
match resp.json::<serde_json::Value>().await {
Ok(val) => {
let tag = val["tag_name"]
.as_str()
.map(|s| s.trim().trim_start_matches(['v', 'V']).to_string())
.unwrap_or_default();
let html_url = val["html_url"]
.as_str()
.map(str::trim)
.filter(|s| !s.is_empty())
.unwrap_or(LATEST_RELEASE_WEB)
.to_string();
if !tag.is_empty() && is_newer_version(&tag, APP_VERSION) {
Ok(Some((tag, html_url)))
} else {
Ok(None)
}
Ok(entries)
}
Err(e) => Err(e.to_string()),
}
}
Ok(resp) if resp.status().as_u16() == 404 => Ok(Vec::new()),
Ok(resp) if resp.status().as_u16() == 404 => Ok(None),
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();
@ -1611,24 +1461,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));
}
});
}
@ -1903,15 +1737,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,10 +1779,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();
@ -2075,8 +1901,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 +2006,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 +2027,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()) {
@ -2431,24 +2237,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 +2260,30 @@ 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, url))) => {
self.available_update = Some((newer.clone(), url));
self.show_toast(t.toast_update_available(&newer));
}
Ok(None) => {
self.available_update = None;
self.show_toast(t.toast_latest_version());
}
Err(e) => {
log::warn!("Update check failed: {}", e);
self.show_toast(t.toast_update_check_failed());
}
},
}
}
@ -2989,12 +2744,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
@ -3038,31 +2787,10 @@ 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
@ -3103,11 +2831,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 +2861,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) => {
@ -3326,26 +3039,6 @@ pub fn is_newer_version(remote: &str, current: &str) -> bool {
}
}
/// 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<PinnedItem>, my_uid: Option<u64>, 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::*;
@ -3361,86 +3054,4 @@ mod tests {
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);
}
}

View file

@ -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);
}
}

View file

@ -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<f32>,
r128_tp: Option<f32>,
fade: Option<TrackFade>,
seek_seq: u64,
},
PreloadNext {
track_id: String,
stream: ResolvedStream,
duration_ms: u64,
r128_i: Option<f32>,
r128_tp: Option<f32>,
fade: Option<TrackFade>,
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<String>,
pub output_device_name: Mutex<String>,
pub last_error: Mutex<Option<String>>,
pub crossfaded_track_id: Mutex<Option<String>>,
}
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<AudioCommand>,
pub state: Arc<SharedAudioState>,
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<f32>,
r128_tp: Option<f32>,
fade: Option<TrackFade>,
) {
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<f32>,
r128_tp: Option<f32>,
fade: Option<TrackFade>,
) {
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<String> {
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<f32>,
r128_tp: Option<f32>,
gain_applied: bool,
fade: Option<TrackFade>,
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<TrackFade>,
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<TrackFade>,
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<AudioCommand>, state: Arc<SharedAudioState>
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<AudioCommand>, state: Arc<SharedAudioState>
.ok();
let mut active: Option<ActiveStreamDecoder> = None;
let mut outgoing: Option<OutgoingCrossfade> = None;
let mut preloaded: Option<ActiveStreamDecoder> = 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<AudioCommand>, state: Arc<SharedAudioState>
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<AudioCommand>, state: Arc<SharedAudioState>
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<AudioCommand>, state: Arc<SharedAudioState>
}
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<AudioCommand>, state: Arc<SharedAudioState>
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<AudioCommand>, state: Arc<SharedAudioState>
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<AudioCommand>, state: Arc<SharedAudioState>
}
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<AudioCommand>, state: Arc<SharedAudioState>
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);
}
}

View file

@ -1,3 +0,0 @@
fn main() {
yandex_music_rs::native::run_auth_webview_subprocess();
}

View file

@ -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<String>,
@ -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(),

View file

@ -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<u8>
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();

View file

@ -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();
}
}

View file

@ -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<'_>],

View file

@ -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

View file

@ -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!

View file

@ -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,
);
}
}

View file

@ -131,8 +131,6 @@ pub enum Icon {
YandexIdLogoRuLight,
YandexIdLogoEnDark,
YandexIdLogoEnLight,
ThumbDuck,
ThumbCar,
}
impl Icon {
@ -261,8 +259,6 @@ impl Icon {
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"),
}
}
@ -275,8 +271,6 @@ impl Icon {
| 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),
}
@ -412,8 +406,6 @@ impl Icon {
Icon::YandexIdLogoRuLight,
Icon::YandexIdLogoEnDark,
Icon::YandexIdLogoEnLight,
Icon::ThumbDuck,
Icon::ThumbCar,
];
}

View file

@ -169,32 +169,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 +413,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 +561,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) => {
@ -1058,30 +1027,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();

View file

@ -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<NativeEvent>,
icons: Arc<Vec<ksni::Icon>>,
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<ksni::Icon> {
(*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<ksni::MenuItem<Self>> {
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<ksni::Icon> {
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<Handle<LinuxTray>>,
rx: Receiver<NativeEvent>,
last_playing: Option<bool>,
last_track_id: Option<String>,
}
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<NativeEvent> {
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<winit::window::Icon> {
@ -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<String> {
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

View file

@ -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<u64> {
let rest = line.strip_prefix(prefix)?;
rest.split_whitespace().next()?.parse::<u64>().ok()
}
if let Ok(rollup) = std::fs::read_to_string("/proc/self/smaps_rollup") {
let mut rss_kb: Option<u64> = None;
let mut pss_kb: Option<u64> = 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<u64> = None;
let mut anon_kb: Option<u64> = 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;

View file

@ -352,7 +352,7 @@ pub fn render_collection(
cx += card_w + gap;
}
for (idx, pl) in playlists.iter().take(60).enumerate() {
for pl in playlists.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 = t.count_tracks(pl.track_count as usize);
@ -363,17 +363,14 @@ pub fn render_collection(
ctx,
pal,
covers,
WidgetId::from_pair(
"col_ov_pl",
(idx, format!("{}_{}", pl.owner_uid, pl.kind)),
),
WidgetId::from_pair("col_ov_pl", 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(),
false,
);
if let Some(pos) = m.right_clicked_pos {
shell.open_entity_menu(EntityContextMenuState {
@ -410,7 +407,7 @@ pub fn render_collection(
ctx.end_scroll_h(
h_id,
pal,
(playlists.len().min(60) + 1) as f32 * (card_w + gap),
(playlists.len().min(24) + 1) as f32 * (card_w + gap),
false,
);
y += card_h + 26.0;
@ -457,10 +454,9 @@ pub fn render_collection(
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() {
for alb in albums.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 alb_title = alb.full_title();
let sub = alb
.artists
.first()
@ -470,9 +466,9 @@ pub fn render_collection(
ctx,
pal,
covers,
WidgetId::from_pair("col_ov_alb", (idx, &alb.id)),
WidgetId::from_pair("col_ov_alb", &alb.id),
cr,
&alb_title,
&alb.title,
sub,
alb.cover_uri.as_deref(),
&format!("alb_{}", alb.id),
@ -483,7 +479,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,
@ -495,12 +491,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(),
}));
}
}
@ -509,7 +505,7 @@ pub fn render_collection(
ctx.end_scroll_h(
h_id,
pal,
albums.len().min(60) as f32 * (card_w + gap),
albums.len().min(24) as f32 * (card_w + gap),
false,
);
y += card_h + 26.0;
@ -797,7 +793,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 +805,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!
@ -932,7 +928,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 +937,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 +950,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 +962,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(),
}));
}
}
@ -1439,8 +1434,6 @@ fn render_compact_two_col_track_grid(
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),
},
) {
@ -1524,8 +1517,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),
},
) {

View file

@ -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,
);
}

View file

@ -465,7 +465,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 +473,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,
@ -579,8 +576,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),
},
) {
@ -657,17 +652,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,
@ -962,9 +954,8 @@ fn render_new_releases_carousel(
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() {
for item in &items {
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
@ -1021,7 +1012,7 @@ fn render_new_releases_carousel(
.artists
.first()
.map(|a| a.name.as_str())
.unwrap_or(alb_title.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,
@ -1037,14 +1028,14 @@ fn render_new_releases_carousel(
);
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);
let port_resp = ctx.interact(WidgetId::from_pair(salt, 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_resp = ctx.interact(WidgetId::from_pair(salt, format!("card_{}", alb.id)), card_r);
let card_bg = if card_resp.hovered {
card_tint.lerp(Color::WHITE, 0.08)
} else {
@ -1083,7 +1074,7 @@ fn render_new_releases_carousel(
// 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_resp = ctx.interact(WidgetId::from_pair(salt, 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));
@ -1101,7 +1092,7 @@ fn render_new_releases_carousel(
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,
&alb.title,
TextStyle::bold(14.5, Color::WHITE),
Rect::from_xywh(tx_l, card_r.top() + 18.0, tx_w, 20.0),
TextAlign::Left,

View file

@ -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() {

View file

@ -764,14 +764,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()));
@ -1095,10 +1110,10 @@ pub fn render_my_vibe(
}
}
// 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 {
// 9. BOTTOM-RIGHT VERSION BADGE (`APP_VERSION` = `0.1.0`, or `0.1.0 → {ver}` when update available!)
let (ver_label, ver_col) = if let Some((ref new_ver, _)) = app.available_update {
(
format!("{} → {}", APP_VERSION, upd.version),
format!("{} → {}", APP_VERSION, new_ver),
if pal.is_dark {
pal.yellow
} else {
@ -1108,9 +1123,9 @@ pub fn render_my_vibe(
} 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)
let ver_style = TextStyle::medium(13.0, ver_col);
let ver_w = (ctx.measure_text(&ver_label, ver_style, None).x + 22.0)
.max(68.0)
.ceil();
let ver_r = Rect::from_xywh(
(rect.right() - ver_w - 16.0).floor(),
@ -1133,7 +1148,7 @@ pub fn render_my_vibe(
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)

File diff suppressed because it is too large Load diff

View file

@ -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

View file

@ -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);
}

View file

@ -1194,7 +1194,7 @@ pub fn render_concerts(
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)
// 3 featured shimmer poster cards
let gap = 16.0;
let f_cols = if avail_w >= 860.0 {
3usize
@ -1203,17 +1203,16 @@ pub fn render_concerts(
} 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);
let f_w = ((avail_w - gap * (f_cols as f32 - 1.0)) / f_cols as f32).max(220.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),
Rect::from_xywh(x + i as f32 * (f_w + gap), y, f_w, 210.0),
16.0,
col,
);
}
y += f_h + 26.0;
y += 236.0;
// 4 shimmer feed rows
for i in 0..4 {
@ -1277,7 +1276,7 @@ pub fn render_concerts(
}
.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);
let f_h = 216.0;
ctx.draw_text_ellipsis(
if ru { "Рекомендуем" } else { "Featured" },
@ -1676,8 +1675,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 +2010,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),
},
) {

View file

@ -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,

File diff suppressed because it is too large Load diff

View file

@ -80,58 +80,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 +287,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 +296,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 +363,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 +384,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 {
@ -708,7 +690,7 @@ fn render_profile_card_popup(
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 group1_h = 54.0 + if logged_in { 44.0 * 4.0 } else { 44.0 * 2.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 };
@ -1121,34 +1103,6 @@ fn render_profile_card_popup(
}
y += 44.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(
ctx,

View file

@ -211,7 +211,6 @@ fn make_track(
r128_tp: None,
derived_average_hex: None,
derived_accent_hex: None,
fade: None,
}
}

View file

@ -133,7 +133,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 +158,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(
@ -1892,7 +1890,6 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
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 {
@ -2055,7 +2052,6 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
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"]
@ -2174,9 +2170,9 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
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
// Verify Top 3 colored poster cards + upcoming feed rendered cleanly
let mut poster_chromatic_px = 0usize;
for y in 160..540 {
for y in 160..420 {
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 {
@ -2248,360 +2244,3 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
);
}
}
#[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!"
);
}
}